import { sameUsageLimitCommandCoverage, withUsageLimitsCommands,} from "@t3tools/shared/usageLimits";import * as Cause from "effect/Cause";import * as Crypto from "effect/Crypto";import * as DateTime from "effect/DateTime";import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Option from "effect/Option";import * as Path from "effect/Path";import * as Queue from "effect/Queue";import * as Ref from "effect/Ref";import * as Schema from "effect/Schema";import * as Stream from "effect/Stream";import { DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL, AuthAccessStreamError, type AuthAccessStreamEvent, type AuthEnvironmentScope, AuthSessionId, ClientConnectionMethod, ClientDeviceType, ClientOs, ClientSurface, ClientWebDeployment, CommandId, type DiscoveredLocalServerList, EventId, type EditorId, type FileManagerRevealKind, type OrchestrationClientOrigin, type OrchestrationCommand, type GitActionProgressEvent, type GitManagerServiceError, OrchestrationDispatchCommandError, type OrchestrationEvent, type OrchestrationShellStreamEvent, type OrchestrationShellStreamItem, OrchestrationGetFullThreadDiffError, OrchestrationGetSnapshotError, OrchestrationSearchThreadsError, OrchestrationGetTurnDiffError, ORCHESTRATION_WS_METHODS, ProjectId, type ProjectEntriesFailure, type ProjectFileFailure, type ProjectFileOperation, ProjectListEntriesError, ProjectReadFileError, ProjectSearchContentsError, ProjectSearchEntriesError, ProjectWriteFileError, ProviderUploadFeedbackError, ProviderSetupError, RelayClientInstallFailedError, type RelayClientInstallProgressEvent, ServerSelfUpdateError, type ServerSelfUpdateProgressEvent, type ServerLifecycleStreamEvent, type FilesystemBrowseFailure, FilesystemBrowseError, AssetWorkspaceContextNotFoundError, AssetWorkspaceContextResolutionError, RpcClientId, EnvironmentAuthorizationError, ThreadId, type TerminalAttachStreamEvent, type TerminalError, type TerminalEvent, type TerminalMetadataStreamEvent, type PullRequestRef, WS_METHODS, WsRpcGroup,} from "@t3tools/contracts";import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";import { HttpRouter, HttpServerRequest, HttpServerRespondable } from "effect/unstable/http";import { RpcSerialization, RpcServer } from "effect/unstable/rpc"; import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";import * as ServerConfig from "./config.ts";import * as EnvironmentTheme from "./environmentTheme.ts";import * as Keybindings from "./keybindings.ts";import * as ExternalLauncher from "./process/externalLauncher.ts";import { projectActivityEvent, projectThreadDetailSnapshot,} from "./orchestration/ActivityPayloadProjection.ts";import { makeThreadLiveEventCoalescer } from "./orchestration/ThreadLiveEventCoalescer.ts";import { makeLiveStreamBudget, type RetainedLiveItem } from "./orchestration/LiveStreamBudget.ts";import { cleanupFailedUploadedAttachments, normalizeDispatchCommand,} from "./orchestration/Normalizer.ts";import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";import { ThreadDeletionReactor } from "./orchestration/Services/ThreadDeletionReactor.ts";import { observeRpcEffect as instrumentRpcEffect, observeRpcStream as instrumentRpcStream, observeRpcStreamEffect as instrumentRpcStreamEffect,} from "./observability/RpcInstrumentation.ts";import * as ProviderRegistry from "./provider/Services/ProviderRegistry.ts";import * as ProviderService from "./provider/Services/ProviderService.ts";import * as ProviderSessionDirectory from "./provider/Services/ProviderSessionDirectory.ts";import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts";import { ProviderAuthService } from "./provider/Services/ProviderAuthService.ts";import { ProviderInstanceRegistry } from "./provider/Services/ProviderInstanceRegistry.ts";import { makeProviderInstallation } from "./provider/providerInstallation.ts";import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";import * as ServerSettings from "./serverSettings.ts";import * as TerminalManager from "./terminal/Manager.ts";import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";import * as DeviceService from "./device/DeviceService.ts";import * as PreviewManager from "./preview/Manager.ts";import { issueAssetUrl } from "./assets/AssetAccess.ts";import { deletePendingAttachment, issueAttachmentUploadUrl } from "./assets/AttachmentUpload.ts";import * as PortScanner from "./preview/PortScanner.ts";import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";import { readWorkflowScript } from "./orchestration/workflowScriptQuery.ts";import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";import * as GitWorkflowService from "./git/GitWorkflowService.ts";import { linkCreatedPullRequest } from "./git/linkCreatedPullRequest.ts";import * as ReviewService from "./review/ReviewService.ts";import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts";import * as AgentSessionScanner from "./project/AgentSessionScanner.ts";import { importRecentAgentThreads } from "./project/AgentSessionImporter.ts";import * as ServerEnvironment from "./environment/ServerEnvironment.ts";import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";import { requiredScopeForRpcMethod } from "./auth/RpcAuthorization.ts";import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";import * as HostResources from "./resourceTelemetry/HostResources.ts";import * as AnalyticsService from "./telemetry/AnalyticsService.ts";import * as UsageLimitSources from "./usage/UsageLimitSources.ts";import * as UsageService from "./usage/UsageService.ts";import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";import * as PullRequestService from "./pullRequest/PullRequestService.ts";import { listLinkedPullRequestThreads } from "./pullRequest/linkedThreads.ts";import { pullRequestSyncKey } from "./pullRequest/pullRequestSyncKey.ts";import * as SqlClient from "effect/unstable/sql/SqlClient";import * as PullRequestSyncReactor from "./orchestration/PullRequestSyncReactor.ts";import * as SourceControlDiscovery from "./sourceControl/SourceControlDiscovery.ts";import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";import * as AzureDevOpsCli from "./sourceControl/AzureDevOpsCli.ts";import * as BitbucketApi from "./sourceControl/BitbucketApi.ts";import * as GitHubCli from "./sourceControl/GitHubCli.ts";import * as GitLabCli from "./sourceControl/GitLabCli.ts";import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";import * as PairingGrantStore from "./auth/PairingGrantStore.ts";import * as SessionStore from "./auth/SessionStore.ts";import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts";import * as RelayClient from "@t3tools/shared/relayClient";const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError); const nowIso = Effect.map(DateTime.now, DateTime.formatIso);const CONFIG_DISCOVERY_TIMEOUT = Duration.seconds(5); const resolveDiscoveryForConfig = <A, E, R>( discovery: Effect.Effect<A, E, R>, onTimeout: () => A,) => discovery.pipe( Effect.timeoutOption(CONFIG_DISCOVERY_TIMEOUT), Effect.map(Option.getOrElse(onTimeout)), ); export const resolveAvailableEditorsForConfig = <A, E, R>( discovery: Effect.Effect<ReadonlyArray<A>, E, R>,) => resolveDiscoveryForConfig(discovery, () => []); export const resolveFileManagerRevealKindForConfig = <E, R>( discovery: Effect.Effect<FileManagerRevealKind | undefined, E, R>,) => resolveDiscoveryForConfig(discovery, () => undefined); function unexpectedCompatibilityError(error: never): never { throw new Error(`Unhandled compatibility error: ${String(error)}`);} /** Preserve the setup runner's broader pre-refactor message normalization. */function legacySetupFailureDescription(cause: unknown): string { if ( typeof cause === "object" && cause !== null && "message" in cause && typeof cause.message === "string" ) { return cause.message; } return String(cause);} function projectEntriesFailureContext(error: WorkspaceEntries.WorkspaceEntriesError): { readonly failure: ProjectEntriesFailure; readonly normalizedCwd?: string; readonly timeout?: string; readonly detail?: string;} { switch (error._tag) { case "WorkspaceRootNotExistsError": return { failure: "workspace_root_not_found", normalizedCwd: error.normalizedWorkspaceRoot, }; case "WorkspaceRootCreateFailedError": return { failure: "workspace_root_create_failed", normalizedCwd: error.normalizedWorkspaceRoot, }; case "WorkspaceRootStatFailedError": return { failure: "workspace_root_stat_failed", normalizedCwd: error.normalizedWorkspaceRoot, detail: error.phase, }; case "WorkspaceRootNotDirectoryError": return { failure: "workspace_root_not_directory", normalizedCwd: error.normalizedWorkspaceRoot, }; case "WorkspaceSearchIndexCreateFailed": return { failure: "search_index_create_failed", normalizedCwd: error.cwd, detail: error.reason, }; case "WorkspaceSearchIndexScanTimedOut": return { failure: "search_index_scan_timed_out", normalizedCwd: error.cwd, timeout: error.timeout, }; case "WorkspaceSearchIndexSearchFailed": return { failure: "search_index_search_failed", normalizedCwd: error.cwd, detail: error.reason, }; default: return unexpectedCompatibilityError(error); }} function filesystemBrowseFailureContext(error: WorkspaceEntries.WorkspaceEntriesBrowseError): { readonly failure: FilesystemBrowseFailure; readonly parentPath?: string; readonly platform?: string;} { switch (error._tag) { case "WorkspaceEntriesWindowsPathUnsupportedError": return { failure: "windows_path_unsupported", platform: error.platform }; case "WorkspaceEntriesCurrentProjectRequiredError": return { failure: "current_project_required" }; case "WorkspaceEntriesReadDirectoryError": return { failure: "read_directory_failed", parentPath: error.parentPath }; default: return unexpectedCompatibilityError(error); }} function projectFileFailureContext( error: | WorkspaceFileSystem.WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError,): { readonly failure: ProjectFileFailure; readonly resolvedPath?: string; readonly resolvedWorkspaceRoot?: string; readonly operation?: ProjectFileOperation; readonly operationPath?: string;} { switch (error._tag) { case "WorkspacePathOutsideRootError": return { failure: "workspace_path_outside_root" }; case "WorkspaceFileSystemOperationError": return { failure: "operation_failed", resolvedPath: error.resolvedPath, operation: error.operation, operationPath: error.operationPath, }; case "WorkspaceFilePathEscapeError": return { failure: "resolved_path_outside_root", resolvedPath: error.resolvedPath, resolvedWorkspaceRoot: error.resolvedWorkspaceRoot, }; case "WorkspacePathNotFileError": return { failure: "path_not_file", resolvedPath: error.resolvedPath }; case "WorkspaceBinaryFileError": return { failure: "binary_file", resolvedPath: error.resolvedPath }; default: return unexpectedCompatibilityError(error); }} function projectSetupScriptCompatibilityDetail( error: ProjectSetupScriptRunner.ProjectSetupScriptRunnerError,): string { switch (error._tag) { case "ProjectSetupScriptOperationError": return legacySetupFailureDescription(error.cause); case "ProjectSetupScriptProjectNotFoundError": return "Project was not found for setup script execution."; default: return unexpectedCompatibilityError(error); }} export function isThreadDetailEvent(event: OrchestrationEvent): event is Extract< OrchestrationEvent, { type: | "thread.message-sent" | "thread.proposed-plan-upserted" | "thread.activity-appended" | "thread.turn-diff-completed" | "thread.reverted" | "thread.session-set"; }> { return ( event.type === "thread.message-sent" || event.type === "thread.proposed-plan-upserted" || event.type === "thread.activity-appended" || event.type === "thread.turn-diff-completed" || event.type === "thread.reverted" || event.type === "thread.session-set" );} const PROVIDER_STATUS_DEBOUNCE_MS = 200; // When a resuming client's cursor is more than this many events behind the// current head, skip the per-event catch-up replay and send a fresh shell// snapshot instead. Replaying each intervening event costs a shell refetch;// past this gap a single O(active-threads) snapshot is cheaper and bounded.// Matches the event store's default page size (DEFAULT_READ_FROM_SEQUENCE_LIMIT).const SHELL_RESUME_MAX_GAP = 1_000; // Thread replay counts only this thread's rows. Busy or pruned unrelated// streams must not force a full thread snapshot.const THREAD_RESUME_MAX_EVENTS = 1_000;// Row count alone does not bound replay memory: a few events with large tool// payloads can decode to gigabytes. Before replaying, sum the serialized// payload bytes of the range in SQL and reset with a snapshot past this budget.const ORCHESTRATION_REPLAY_PAYLOAD_BUDGET_BYTES = 8 * 1024 * 1024; function toAuthAccessStreamEvent( change: PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange, revision: number, currentSessionId: AuthSessionId,): AuthAccessStreamEvent { switch (change.type) { case "pairingLinkUpserted": return { version: 1, revision, type: "pairingLinkUpserted", payload: change.pairingLink, }; case "pairingLinkRemoved": return { version: 1, revision, type: "pairingLinkRemoved", payload: { id: change.id }, }; case "clientUpserted": return { version: 1, revision, type: "clientUpserted", payload: { ...change.clientSession, current: change.clientSession.sessionId === currentSessionId, }, }; case "clientRemoved": return { version: 1, revision, type: "clientRemoved", payload: { sessionId: change.sessionId }, }; }} const isClientSurface = Schema.is(ClientSurface);const isClientConnectionMethod = Schema.is(ClientConnectionMethod);const isClientDeviceType = Schema.is(ClientDeviceType);const isClientOs = Schema.is(ClientOs);const isClientWebDeployment = Schema.is(ClientWebDeployment);const MAX_CLIENT_APP_VERSION_LENGTH = 64;const MAX_CLIENT_BROWSER_LENGTH = 64;const MAX_CLIENT_DEVICE_MODEL_LENGTH = 80; // Optional client identity announced on the /ws upgrade URL next to wsTicket.// Lenient by design: absent or malformed values degrade to {} so a connection// never fails over attribution metadata.function readClientConnectionOrigin( request: HttpServerRequest.HttpServerRequest,): OrchestrationClientOrigin { const url = HttpServerRequest.toURL(request); if (Option.isNone(url)) { return {}; } const surface = url.value.searchParams.get("clientSurface"); const appVersion = url.value.searchParams.get("clientAppVersion")?.trim() ?? ""; return { ...(isClientSurface(surface) ? { surface } : {}), ...(appVersion !== "" && appVersion.length <= MAX_CLIENT_APP_VERSION_LENGTH ? { appVersion } : {}), };} // Client telemetry stays in this socket's RPC layer. It must not become a// server-global "current client" because several client types can connect at once.function readClientAnalyticsProps(request: HttpServerRequest.HttpServerRequest) { const url = HttpServerRequest.toURL(request); if (Option.isNone(url)) { return {}; } const surface = url.value.searchParams.get("clientSurface"); const appVersion = url.value.searchParams.get("clientAppVersion")?.trim() ?? ""; const deviceType = url.value.searchParams.get("clientDeviceType"); const os = url.value.searchParams.get("clientOs"); const webDeployment = url.value.searchParams.get("clientWebDeployment"); const browser = url.value.searchParams.get("clientBrowser")?.trim() ?? ""; const connectionMethod = url.value.searchParams.get("connectionMethod"); const rawOsMajorVersion = url.value.searchParams.get("clientOsMajorVersion") ?? ""; const osMajorVersion = Number(rawOsMajorVersion); const deviceModel = url.value.searchParams.get("clientDeviceModel")?.trim() ?? ""; const isMobile = surface === "mobile"; const hasOsMajorVersion = isMobile && rawOsMajorVersion !== "" && Number.isInteger(osMajorVersion) && osMajorVersion > 0; const hasDeviceModel = isMobile && deviceModel !== "" && deviceModel.length <= MAX_CLIENT_DEVICE_MODEL_LENGTH; return { ...(isClientSurface(surface) ? { surface } : {}), ...(appVersion !== "" && appVersion.length <= MAX_CLIENT_APP_VERSION_LENGTH ? { appVersion, clientAppVersion: appVersion } : {}), ...(isClientOs(os) ? { clientOs: os, ...(isMobile && (os === "iOS" || os === "Android") ? { os } : {}), } : {}), ...(isClientDeviceType(deviceType) ? { clientDeviceType: deviceType } : {}), ...(surface === "web" && isClientWebDeployment(webDeployment) ? { webDeployment } : {}), ...(surface === "web" && browser !== "" && browser.length <= MAX_CLIENT_BROWSER_LENGTH ? { clientBrowser: browser } : {}), ...(hasOsMajorVersion ? { osMajorVersion, clientOsMajorVersion: osMajorVersion } : {}), ...(hasDeviceModel ? { deviceModel, clientDeviceModel: deviceModel } : {}), ...(isClientConnectionMethod(connectionMethod) ? { connectionMethod } : {}), };} const makeWsRpcLayer = ( currentSession: EnvironmentAuth.AuthenticatedSession, clientOrigin: OrchestrationClientOrigin, clientAnalyticsProps: Readonly<Record<string, unknown>>, previewAutomationBroker: PreviewAutomationBroker.PreviewAutomationBroker["Service"],) => WsRpcGroup.toLayer( Effect.gen(function* () { const currentSessionId = currentSession.sessionId; const crypto = yield* Crypto.Crypto; const sql = yield* SqlClient.SqlClient; const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery; /** A reference's host-level link key; the project's own host where the ref names none. */ const resolvePullRequestSyncKey = (reference: PullRequestRef) => reference.host !== undefined && reference.repository.includes("/") ? Effect.succeed(pullRequestSyncKey(reference)) : projectionSnapshotQuery.getProjectShellById(reference.projectId).pipe( Effect.map((project) => pullRequestSyncKey(reference, Option.getOrUndefined(project)?.repositoryIdentity), ), Effect.orElseSucceed(() => null), ); const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService; const threadDeletionReactor = yield* ThreadDeletionReactor; const analytics = yield* AnalyticsService.AnalyticsService;Lines 1–500 of 3132. Load more
import { sameUsageLimitCommandCoverage, withUsageLimitsCommands, } from "@t3tools/shared/usageLimits"; import * as Cause from "effect/Cause"; import * as Crypto from "effect/Crypto"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import { DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL, AuthAccessStreamError, type AuthAccessStreamEvent, type AuthEnvironmentScope, AuthSessionId, ClientConnectionMethod, ClientDeviceType, ClientOs, ClientSurface, ClientWebDeployment, CommandId, type DiscoveredLocalServerList, EventId, type EditorId, type FileManagerRevealKind, type OrchestrationClientOrigin, type OrchestrationCommand, type GitActionProgressEvent, type GitManagerServiceError, OrchestrationDispatchCommandError, type OrchestrationEvent, type OrchestrationShellStreamEvent, type OrchestrationShellStreamItem, OrchestrationGetFullThreadDiffError, OrchestrationGetSnapshotError, OrchestrationSearchThreadsError, OrchestrationGetTurnDiffError, ORCHESTRATION_WS_METHODS, ProjectId, type ProjectEntriesFailure, type ProjectFileFailure, type ProjectFileOperation, ProjectListEntriesError, ProjectReadFileError, ProjectSearchContentsError, ProjectSearchEntriesError, ProjectWriteFileError, ProviderUploadFeedbackError, ProviderSetupError, RelayClientInstallFailedError, type RelayClientInstallProgressEvent, ServerSelfUpdateError, type ServerSelfUpdateProgressEvent, type ServerLifecycleStreamEvent, type FilesystemBrowseFailure, FilesystemBrowseError, AssetWorkspaceContextNotFoundError, AssetWorkspaceContextResolutionError, RpcClientId, EnvironmentAuthorizationError, ThreadId, type TerminalAttachStreamEvent, type TerminalError, type TerminalEvent, type TerminalMetadataStreamEvent, type PullRequestRef, WS_METHODS, WsRpcGroup, } from "@t3tools/contracts"; import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings"; import { HttpRouter, HttpServerRequest, HttpServerRespondable } from "effect/unstable/http"; import { RpcSerialization, RpcServer } from "effect/unstable/rpc"; import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts"; import * as ServerConfig from "./config.ts"; import * as EnvironmentTheme from "./environmentTheme.ts"; import * as Keybindings from "./keybindings.ts"; import * as ExternalLauncher from "./process/externalLauncher.ts"; import { projectActivityEvent, projectThreadDetailSnapshot, } from "./orchestration/ActivityPayloadProjection.ts"; import { makeThreadLiveEventCoalescer } from "./orchestration/ThreadLiveEventCoalescer.ts"; import { makeLiveStreamBudget, type RetainedLiveItem } from "./orchestration/LiveStreamBudget.ts"; import { cleanupFailedUploadedAttachments, normalizeDispatchCommand, } from "./orchestration/Normalizer.ts"; import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts"; import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts"; import { ThreadDeletionReactor } from "./orchestration/Services/ThreadDeletionReactor.ts"; import { observeRpcEffect as instrumentRpcEffect, observeRpcStream as instrumentRpcStream, observeRpcStreamEffect as instrumentRpcStreamEffect, } from "./observability/RpcInstrumentation.ts"; import * as ProviderRegistry from "./provider/Services/ProviderRegistry.ts"; import * as ProviderService from "./provider/Services/ProviderService.ts"; import * as ProviderSessionDirectory from "./provider/Services/ProviderSessionDirectory.ts"; import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts"; import { ProviderAuthService } from "./provider/Services/ProviderAuthService.ts"; import { ProviderInstanceRegistry } from "./provider/Services/ProviderInstanceRegistry.ts"; import { makeProviderInstallation } from "./provider/providerInstallation.ts"; import * as ServerSelfUpdate from "./cloud/selfUpdate.ts"; import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts"; import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts"; import * as ServerSettings from "./serverSettings.ts"; import * as TerminalManager from "./terminal/Manager.ts"; import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts"; import * as DeviceService from "./device/DeviceService.ts"; import * as PreviewManager from "./preview/Manager.ts"; import { issueAssetUrl } from "./assets/AssetAccess.ts"; import { deletePendingAttachment, issueAttachmentUploadUrl } from "./assets/AttachmentUpload.ts"; import * as PortScanner from "./preview/PortScanner.ts"; import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts"; import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts"; import { readWorkflowScript } from "./orchestration/workflowScriptQuery.ts"; import * as WorkspacePaths from "./workspace/WorkspacePaths.ts"; import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts"; import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts"; import * as GitWorkflowService from "./git/GitWorkflowService.ts"; import { linkCreatedPullRequest } from "./git/linkCreatedPullRequest.ts"; import * as ReviewService from "./review/ReviewService.ts"; import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts"; import * as AgentSessionScanner from "./project/AgentSessionScanner.ts"; import { importRecentAgentThreads } from "./project/AgentSessionImporter.ts"; import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts"; import * as BackgroundPolicy from "./background/BackgroundPolicy.ts"; import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; import { requiredScopeForRpcMethod } from "./auth/RpcAuthorization.ts"; import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts"; import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts"; import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts"; import * as HostResources from "./resourceTelemetry/HostResources.ts"; import * as AnalyticsService from "./telemetry/AnalyticsService.ts"; import * as UsageLimitSources from "./usage/UsageLimitSources.ts"; import * as UsageService from "./usage/UsageService.ts"; import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts"; import * as PullRequestService from "./pullRequest/PullRequestService.ts"; import { listLinkedPullRequestThreads } from "./pullRequest/linkedThreads.ts"; import { pullRequestSyncKey } from "./pullRequest/pullRequestSyncKey.ts"; import * as SqlClient from "effect/unstable/sql/SqlClient"; import * as PullRequestSyncReactor from "./orchestration/PullRequestSyncReactor.ts"; import * as SourceControlDiscovery from "./sourceControl/SourceControlDiscovery.ts"; import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts"; import * as AzureDevOpsCli from "./sourceControl/AzureDevOpsCli.ts"; import * as BitbucketApi from "./sourceControl/BitbucketApi.ts"; import * as GitHubCli from "./sourceControl/GitHubCli.ts"; import * as GitLabCli from "./sourceControl/GitLabCli.ts"; import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts"; import * as GitVcsDriver from "./vcs/GitVcsDriver.ts"; import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts"; import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts"; import * as PairingGrantStore from "./auth/PairingGrantStore.ts"; import * as SessionStore from "./auth/SessionStore.ts"; import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts"; import * as RelayClient from "@t3tools/shared/relayClient"; const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError); const nowIso = Effect.map(DateTime.now, DateTime.formatIso); const CONFIG_DISCOVERY_TIMEOUT = Duration.seconds(5); const resolveDiscoveryForConfig = <A, E, R>( discovery: Effect.Effect<A, E, R>, onTimeout: () => A, ) => discovery.pipe( Effect.timeoutOption(CONFIG_DISCOVERY_TIMEOUT), Effect.map(Option.getOrElse(onTimeout)), ); export const resolveAvailableEditorsForConfig = <A, E, R>( discovery: Effect.Effect<ReadonlyArray<A>, E, R>, ) => resolveDiscoveryForConfig(discovery, () => []); export const resolveFileManagerRevealKindForConfig = <E, R>( discovery: Effect.Effect<FileManagerRevealKind | undefined, E, R>, ) => resolveDiscoveryForConfig(discovery, () => undefined); function unexpectedCompatibilityError(error: never): never { throw new Error(`Unhandled compatibility error: ${String(error)}`); } /** Preserve the setup runner's broader pre-refactor message normalization. */ function legacySetupFailureDescription(cause: unknown): string { if ( typeof cause === "object" && cause !== null && "message" in cause && typeof cause.message === "string" ) { return cause.message; } return String(cause); } function projectEntriesFailureContext(error: WorkspaceEntries.WorkspaceEntriesError): { readonly failure: ProjectEntriesFailure; readonly normalizedCwd?: string; readonly timeout?: string; readonly detail?: string; } { switch (error._tag) { case "WorkspaceRootNotExistsError": return { failure: "workspace_root_not_found", normalizedCwd: error.normalizedWorkspaceRoot, }; case "WorkspaceRootCreateFailedError": return { failure: "workspace_root_create_failed", normalizedCwd: error.normalizedWorkspaceRoot, }; case "WorkspaceRootStatFailedError": return { failure: "workspace_root_stat_failed", normalizedCwd: error.normalizedWorkspaceRoot, detail: error.phase, }; case "WorkspaceRootNotDirectoryError": return { failure: "workspace_root_not_directory", normalizedCwd: error.normalizedWorkspaceRoot, }; case "WorkspaceSearchIndexCreateFailed": return { failure: "search_index_create_failed", normalizedCwd: error.cwd, detail: error.reason, }; case "WorkspaceSearchIndexScanTimedOut": return { failure: "search_index_scan_timed_out", normalizedCwd: error.cwd, timeout: error.timeout, }; case "WorkspaceSearchIndexSearchFailed": return { failure: "search_index_search_failed", normalizedCwd: error.cwd, detail: error.reason, }; default: return unexpectedCompatibilityError(error); } } function filesystemBrowseFailureContext(error: WorkspaceEntries.WorkspaceEntriesBrowseError): { readonly failure: FilesystemBrowseFailure; readonly parentPath?: string; readonly platform?: string; } { switch (error._tag) { case "WorkspaceEntriesWindowsPathUnsupportedError": return { failure: "windows_path_unsupported", platform: error.platform }; case "WorkspaceEntriesCurrentProjectRequiredError": return { failure: "current_project_required" }; case "WorkspaceEntriesReadDirectoryError": return { failure: "read_directory_failed", parentPath: error.parentPath }; default: return unexpectedCompatibilityError(error); } } function projectFileFailureContext( error: | WorkspaceFileSystem.WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError, ): { readonly failure: ProjectFileFailure; readonly resolvedPath?: string; readonly resolvedWorkspaceRoot?: string; readonly operation?: ProjectFileOperation; readonly operationPath?: string; } { switch (error._tag) { case "WorkspacePathOutsideRootError": return { failure: "workspace_path_outside_root" }; case "WorkspaceFileSystemOperationError": return { failure: "operation_failed", resolvedPath: error.resolvedPath, operation: error.operation, operationPath: error.operationPath, }; case "WorkspaceFilePathEscapeError": return { failure: "resolved_path_outside_root", resolvedPath: error.resolvedPath, resolvedWorkspaceRoot: error.resolvedWorkspaceRoot, }; case "WorkspacePathNotFileError": return { failure: "path_not_file", resolvedPath: error.resolvedPath }; case "WorkspaceBinaryFileError": return { failure: "binary_file", resolvedPath: error.resolvedPath }; default: return unexpectedCompatibilityError(error); } } function projectSetupScriptCompatibilityDetail( error: ProjectSetupScriptRunner.ProjectSetupScriptRunnerError, ): string { switch (error._tag) { case "ProjectSetupScriptOperationError": return legacySetupFailureDescription(error.cause); case "ProjectSetupScriptProjectNotFoundError": return "Project was not found for setup script execution."; default: return unexpectedCompatibilityError(error); } } export function isThreadDetailEvent(event: OrchestrationEvent): event is Extract< OrchestrationEvent, { type: | "thread.message-sent" | "thread.proposed-plan-upserted" | "thread.activity-appended" | "thread.turn-diff-completed" | "thread.reverted" | "thread.session-set"; } > { return ( event.type === "thread.message-sent" || event.type === "thread.proposed-plan-upserted" || event.type === "thread.activity-appended" || event.type === "thread.turn-diff-completed" || event.type === "thread.reverted" || event.type === "thread.session-set" ); } const PROVIDER_STATUS_DEBOUNCE_MS = 200; // When a resuming client's cursor is more than this many events behind the // current head, skip the per-event catch-up replay and send a fresh shell // snapshot instead. Replaying each intervening event costs a shell refetch; // past this gap a single O(active-threads) snapshot is cheaper and bounded. // Matches the event store's default page size (DEFAULT_READ_FROM_SEQUENCE_LIMIT). const SHELL_RESUME_MAX_GAP = 1_000; // Thread replay counts only this thread's rows. Busy or pruned unrelated // streams must not force a full thread snapshot. const THREAD_RESUME_MAX_EVENTS = 1_000; // Row count alone does not bound replay memory: a few events with large tool // payloads can decode to gigabytes. Before replaying, sum the serialized // payload bytes of the range in SQL and reset with a snapshot past this budget. const ORCHESTRATION_REPLAY_PAYLOAD_BUDGET_BYTES = 8 * 1024 * 1024; function toAuthAccessStreamEvent( change: PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange, revision: number, currentSessionId: AuthSessionId, ): AuthAccessStreamEvent { switch (change.type) { case "pairingLinkUpserted": return { version: 1, revision, type: "pairingLinkUpserted", payload: change.pairingLink, }; case "pairingLinkRemoved": return { version: 1, revision, type: "pairingLinkRemoved", payload: { id: change.id }, }; case "clientUpserted": return { version: 1, revision, type: "clientUpserted", payload: { ...change.clientSession, current: change.clientSession.sessionId === currentSessionId, }, }; case "clientRemoved": return { version: 1, revision, type: "clientRemoved", payload: { sessionId: change.sessionId }, }; } } const isClientSurface = Schema.is(ClientSurface); const isClientConnectionMethod = Schema.is(ClientConnectionMethod); const isClientDeviceType = Schema.is(ClientDeviceType); const isClientOs = Schema.is(ClientOs); const isClientWebDeployment = Schema.is(ClientWebDeployment); const MAX_CLIENT_APP_VERSION_LENGTH = 64; const MAX_CLIENT_BROWSER_LENGTH = 64; const MAX_CLIENT_DEVICE_MODEL_LENGTH = 80; // Optional client identity announced on the /ws upgrade URL next to wsTicket. // Lenient by design: absent or malformed values degrade to {} so a connection // never fails over attribution metadata. function readClientConnectionOrigin( request: HttpServerRequest.HttpServerRequest, ): OrchestrationClientOrigin { const url = HttpServerRequest.toURL(request); if (Option.isNone(url)) { return {}; } const surface = url.value.searchParams.get("clientSurface"); const appVersion = url.value.searchParams.get("clientAppVersion")?.trim() ?? ""; return { ...(isClientSurface(surface) ? { surface } : {}), ...(appVersion !== "" && appVersion.length <= MAX_CLIENT_APP_VERSION_LENGTH ? { appVersion } : {}), }; } // Client telemetry stays in this socket's RPC layer. It must not become a // server-global "current client" because several client types can connect at once. function readClientAnalyticsProps(request: HttpServerRequest.HttpServerRequest) { const url = HttpServerRequest.toURL(request); if (Option.isNone(url)) { return {}; } const surface = url.value.searchParams.get("clientSurface"); const appVersion = url.value.searchParams.get("clientAppVersion")?.trim() ?? ""; const deviceType = url.value.searchParams.get("clientDeviceType"); const os = url.value.searchParams.get("clientOs"); const webDeployment = url.value.searchParams.get("clientWebDeployment"); const browser = url.value.searchParams.get("clientBrowser")?.trim() ?? ""; const connectionMethod = url.value.searchParams.get("connectionMethod"); const rawOsMajorVersion = url.value.searchParams.get("clientOsMajorVersion") ?? ""; const osMajorVersion = Number(rawOsMajorVersion); const deviceModel = url.value.searchParams.get("clientDeviceModel")?.trim() ?? ""; const isMobile = surface === "mobile"; const hasOsMajorVersion = isMobile && rawOsMajorVersion !== "" && Number.isInteger(osMajorVersion) && osMajorVersion > 0; const hasDeviceModel = isMobile && deviceModel !== "" && deviceModel.length <= MAX_CLIENT_DEVICE_MODEL_LENGTH; return { ...(isClientSurface(surface) ? { surface } : {}), ...(appVersion !== "" && appVersion.length <= MAX_CLIENT_APP_VERSION_LENGTH ? { appVersion, clientAppVersion: appVersion } : {}), ...(isClientOs(os) ? { clientOs: os, ...(isMobile && (os === "iOS" || os === "Android") ? { os } : {}), } : {}), ...(isClientDeviceType(deviceType) ? { clientDeviceType: deviceType } : {}), ...(surface === "web" && isClientWebDeployment(webDeployment) ? { webDeployment } : {}), ...(surface === "web" && browser !== "" && browser.length <= MAX_CLIENT_BROWSER_LENGTH ? { clientBrowser: browser } : {}), ...(hasOsMajorVersion ? { osMajorVersion, clientOsMajorVersion: osMajorVersion } : {}), ...(hasDeviceModel ? { deviceModel, clientDeviceModel: deviceModel } : {}), ...(isClientConnectionMethod(connectionMethod) ? { connectionMethod } : {}), }; } const makeWsRpcLayer = ( currentSession: EnvironmentAuth.AuthenticatedSession, clientOrigin: OrchestrationClientOrigin, clientAnalyticsProps: Readonly<Record<string, unknown>>, previewAutomationBroker: PreviewAutomationBroker.PreviewAutomationBroker["Service"], ) => WsRpcGroup.toLayer( Effect.gen(function* () { const currentSessionId = currentSession.sessionId; const crypto = yield* Crypto.Crypto; const sql = yield* SqlClient.SqlClient; const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery; /** A reference's host-level link key; the project's own host where the ref names none. */ const resolvePullRequestSyncKey = (reference: PullRequestRef) => reference.host !== undefined && reference.repository.includes("/") ? Effect.succeed(pullRequestSyncKey(reference)) : projectionSnapshotQuery.getProjectShellById(reference.projectId).pipe( Effect.map((project) => pullRequestSyncKey(reference, Option.getOrUndefined(project)?.repositoryIdentity), ), Effect.orElseSucceed(() => null), ); const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService; const threadDeletionReactor = yield* ThreadDeletionReactor; const analytics = yield* AnalyticsService.AnalyticsService;