The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | import { OrchestrationDispatchCommandError } from "@t3tools/contracts"; |
| 2 | // @effect-diagnostics-next-line nodeBuiltinImport:off -- A synchronous digest inside the pure provider mapping. |
| 3 | import * as NodeCrypto from "node:crypto"; |
| 4 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 5 | import * as Context from "effect/Context"; |
| 6 | import * as NodeHttpServerRequest from "@effect/platform-node/NodeHttpServerRequest"; |
| 7 | import * as SecureRandom from "effect/crypto/SecureRandom"; |
| 8 | import * as Orchestrator from "./orchestration-v2/Orchestrator.ts"; |
| 9 | import * as PeerClientPairing from "./peer/PeerClientPairing.ts"; |
| 10 | import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts"; |
| 11 | import * as PeerLinks from "./peer/PeerLinks.ts"; |
| 12 | import * as PeerThreadRelay from "./peer/PeerThreadRelay.ts"; |
| 13 | |
| 14 | import * as DateTime from "effect/DateTime"; |
| 15 | import * as Duration from "effect/Duration"; |
| 16 | import * as Base64 from "effect/encoding/Base64"; |
| 17 | import * as Effect from "effect/Effect"; |
| 18 | import * as Fiber from "effect/Fiber"; |
| 19 | import * as FileSystem from "effect/FileSystem"; |
| 20 | import * as Layer from "effect/Layer"; |
| 21 | import * as Option from "effect/Option"; |
| 22 | import * as Path from "effect/Path"; |
| 23 | import * as Queue from "effect/Queue"; |
| 24 | import * as Ref from "effect/Ref"; |
| 25 | import * as Schema from "effect/Schema"; |
| 26 | import * as Stream from "effect/Stream"; |
| 27 | import { rpcInitialItems } from "./rpcInitialItems.ts"; |
| 28 | import { subscribeChatGptHandoff } from "./provider/CodexChatGptHandoff.ts"; |
| 29 | import { |
| 30 | AcpRegistryOperationError, |
| 31 | CommandId, |
| 32 | authScopeResponse, |
| 33 | AuthAccessStreamError, |
| 34 | type AuthAccessStreamEvent, |
| 35 | AuthOrchestrationOperateScope, |
| 36 | AuthProvidersManageScope, |
| 37 | type AuthEnvironmentScope, |
| 38 | type ScheduledTaskListResult, |
| 39 | AuthSessionId, |
| 40 | ClientConnectionMethod, |
| 41 | ClientDeviceType, |
| 42 | ClientOs, |
| 43 | ClientSurface, |
| 44 | ClientWebDeployment, |
| 45 | type DiscoveredLocalServerList, |
| 46 | type EditorId, |
| 47 | type FileManagerRevealKind, |
| 48 | type OrchestrationV2Command, |
| 49 | type GitActionProgressEvent, |
| 50 | type GitManagerServiceError, |
| 51 | type MessageId, |
| 52 | type AcpRegistryDeleteSessionInput, |
| 53 | type AcpRegistryDisableProviderInput, |
| 54 | type AcpRegistryListProvidersInput, |
| 55 | type AcpRegistryListSessionsInput, |
| 56 | type AcpRegistrySetProviderInput, |
| 57 | OrchestrationGetFullThreadDiffError, |
| 58 | OrchestrationSearchThreadsError, |
| 59 | OrchestrationV2SearchThreadError, |
| 60 | OrchestrationGetTurnDiffError, |
| 61 | ORCHESTRATION_V2_WS_METHODS, |
| 62 | ORCHESTRATION_PROTOCOL_QUERY_PARAM, |
| 63 | CLIENT_CAPABILITIES_QUERY_PARAM, |
| 64 | SETTINGS_SECRET_REFERENCES_CAPABILITY, |
| 65 | ORCHESTRATION_PROTOCOL_VERSION, |
| 66 | OrchestrationV2DispatchCommandError, |
| 67 | OrchestrationV2GetShellSnapshotError, |
| 68 | OrchestrationV2GetThreadProjectionError, |
| 69 | OrchestrationV2ThreadLaunchError, |
| 70 | type OrchestrationProjectShell, |
| 71 | type OrchestrationV2ShellSnapshot, |
| 72 | type OrchestrationV2ShellStreamItem, |
| 73 | type OrchestrationV2ThreadStreamItem, |
| 74 | type ApplicationStoredEvent, |
| 75 | type ProjectEntriesFailure, |
| 76 | type ProjectFileFailure, |
| 77 | type ProjectFileOperation, |
| 78 | type ProjectMutation, |
| 79 | ProjectListEntriesError, |
| 80 | ProjectReadFileError, |
| 81 | ProjectSearchContentsError, |
| 82 | ProjectSearchEntriesError, |
| 83 | ProjectWriteFileError, |
| 84 | ProjectMutationError, |
| 85 | ProviderUploadFeedbackError, |
| 86 | ProviderSetupError, |
| 87 | RelayClientInstallFailedError, |
| 88 | type RelayClientInstallProgressEvent, |
| 89 | type ServerConfig as ClientServerConfig, |
| 90 | type ServerConfigStreamEvent, |
| 91 | type ServerLifecycleStreamEvent, |
| 92 | type ServerProvider, |
| 93 | serverProviderDeltas, |
| 94 | type FilesystemBrowseFailure, |
| 95 | FilesystemBrowseError, |
| 96 | AssetWorkspaceContextNotFoundError, |
| 97 | AssetWorkspaceContextResolutionError, |
| 98 | SOURCE_CONTROL_MEDIA_ASSET, |
| 99 | ChatAttachmentId, |
| 100 | PersistChatAttachmentsError, |
| 101 | RpcClientId, |
| 102 | EnvironmentAuthorizationError, |
| 103 | ThreadId, |
| 104 | type TerminalMetadataStreamEvent, |
| 105 | type PullRequestRef, |
| 106 | WS_METHODS, |
| 107 | WsRpcGroup, |
| 108 | } from "@t3tools/contracts"; |
| 109 | import { |
| 110 | HttpRouter, |
| 111 | HttpServerRequest, |
| 112 | HttpServerRespondable, |
| 113 | HttpServerResponse, |
| 114 | } from "effect/http"; |
| 115 | import { RpcGroup, RpcSerialization, RpcServer } from "effect/rpc"; |
| 116 | |
| 117 | import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts"; |
| 118 | import * as NativeChildWorkQuery from "./orchestration-v2/NativeChildWorkQuery.ts"; |
| 119 | import * as ServerConfig from "./config.ts"; |
| 120 | import * as EnvironmentTheme from "./environmentTheme.ts"; |
| 121 | import * as Keybindings from "./keybindings.ts"; |
| 122 | import * as ExternalLauncher from "./process/externalLauncher.ts"; |
| 123 | import * as ThreadManagementService from "./orchestration-v2/ThreadManagementService.ts"; |
| 124 | import * as ThreadViewers from "./orchestration-v2/ThreadViewers.ts"; |
| 125 | import * as CommandOutputHub from "./orchestration-v2/CommandOutputHub.ts"; |
| 126 | import * as McpAppRequests from "./mcpApps/McpAppRequests.ts"; |
| 127 | import * as McpSignIn from "./mcpApps/McpSignIn.ts"; |
| 128 | import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts"; |
| 129 | import * as ThreadLaunchService from "./orchestration-v2/ThreadLaunchService.ts"; |
| 130 | import * as ThreadMessageIntake from "./orchestration-v2/ThreadMessageIntake.ts"; |
| 131 | import * as DocumentText from "./provider/DocumentText.ts"; |
| 132 | import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts"; |
| 133 | import * as SecretRequests from "./secrets/SecretRequests.ts"; |
| 134 | import * as GuestShareService from "./guest/GuestShareService.ts"; |
| 135 | import { |
| 136 | bufferShellLiveStream, |
| 137 | coalesceShellApplicationEvents, |
| 138 | composeShellStreamWithEnrichment, |
| 139 | dedupeShellEnrichment, |
| 140 | loadOlderSettledThreadsPage, |
| 141 | loadShellSnapshotParts, |
| 142 | shellStreamItemFromEnrichmentRefresh, |
| 143 | shellStreamItemFromThreadShell, |
| 144 | shellStreamItemsFromInitialSnapshot, |
| 145 | loadSubscriberShellSnapshot, |
| 146 | canResumeShellFrom, |
| 147 | resumeIdentityRoots, |
| 148 | shellStreamItemsFromResumeSnapshot, |
| 149 | shouldPublishShellApplicationEvent, |
| 150 | skipUnchangedThreadShells, |
| 151 | toShellApplicationEvent, |
| 152 | type ShellApplicationEvent, |
| 153 | } from "./orchestration-v2/ShellStream.ts"; |
| 154 | import { ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION } from "./orchestration-v2/ProjectionStore.ts"; |
| 155 | import { |
| 156 | coalesceLiveUpdatedEvents, |
| 157 | coalesceThreadLiveStream, |
| 158 | } from "./orchestration-v2/ThreadLiveEventCoalescer.ts"; |
| 159 | import { |
| 160 | buildBoundedThreadStreamSnapshot, |
| 161 | decideThreadResume, |
| 162 | isThreadReplayRawPayloadSafe, |
| 163 | threadReplayEncodedBytes, |
| 164 | THREAD_RESUME_MAX_REPLAY_EVENTS, |
| 165 | } from "./orchestration-v2/ThreadStream.ts"; |
| 166 | import { |
| 167 | buildBoundedThreadProjection, |
| 168 | THREAD_HISTORY_PAGE_POLICY, |
| 169 | THREAD_HISTORY_SNAPSHOT_ROW_LIMIT, |
| 170 | } from "./orchestration-v2/threadHistoryPaging.ts"; |
| 171 | import { |
| 172 | makeLiveBodyDeduper, |
| 173 | projectDomainEventForWire, |
| 174 | projectThreadProjectionForWire, |
| 175 | threadStreamEventItem, |
| 176 | } from "./orchestration-v2/WireProjection.ts"; |
| 177 | import { dedupeSnapshotBodies } from "@t3tools/shared/orchestrationV2DedupedBodies"; |
| 178 | import * as ProjectStore from "./orchestration-v2/ProjectStore.ts"; |
| 179 | import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts"; |
| 180 | import * as OrchestrationEventStore from "./persistence/OrchestrationEventStore.ts"; |
| 181 | import { userFacingDispatchErrorMessage } from "./orchestration-v2/UserFacingErrors.ts"; |
| 182 | import * as ProviderRegistry from "./provider/ProviderRegistry.ts"; |
| 183 | import * as SecretCheck from "./secrets/SecretCheck.ts"; |
| 184 | import * as AcpRegistrySessions from "./provider/AcpRegistrySessions.ts"; |
| 185 | import * as ProviderInstanceRegistry from "./provider/ProviderInstanceRegistry.ts"; |
| 186 | import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRegistrySupport"; |
| 187 | import * as AcpRegistryRuntimeCoordinator from "@t3tools/provider-acp-registry/server/AcpRegistryRuntimeCoordinator"; |
| 188 | import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts"; |
| 189 | import * as ProviderAuthService from "./provider/ProviderAuthService.ts"; |
| 190 | import * as ProviderInstallation from "./provider/providerInstallation.ts"; |
| 191 | import * as ServerSelfUpdate from "./cloud/selfUpdate.ts"; |
| 192 | import * as NpmRelease from "./cloud/npmRelease.ts"; |
| 193 | import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts"; |
| 194 | import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts"; |
| 195 | import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; |
| 196 | import * as ServerSettings from "./serverSettings.ts"; |
| 197 | import { invalidateSettingsSecrets } from "./sourceControl/sourceControlHostSecrets.ts"; |
| 198 | import * as DatabaseStorage from "./persistence/DatabaseStorage.ts"; |
| 199 | import * as StorageCleanup from "./storageCleanup.ts"; |
| 200 | import * as TerminalManager from "./terminal/Manager.ts"; |
| 201 | import { makePrepareTerminalLaunch } from "./workspace/restoreMissingWorktree.ts"; |
| 202 | import { terminalOutputStream, withOutputWindow } from "./terminal/OutputProtocol.ts"; |
| 203 | import * as ServerBrowser from "./preview/ServerBrowser.ts"; |
| 204 | import * as DeviceService from "./device/DeviceService.ts"; |
| 205 | import { remoteSshDeviceHosts } from "./device/localSshDeviceHost.ts"; |
| 206 | import * as PreviewManager from "./preview/Manager.ts"; |
| 207 | import { issueAssetUrl } from "./assets/AssetAccess.ts"; |
| 208 | import { |
| 209 | attachmentRelativePath, |
| 210 | chatAttachmentStableKey, |
| 211 | createDeterministicAttachmentId, |
| 212 | } from "./attachmentStore.ts"; |
| 213 | import { parseBase64DataUrl } from "./imageMime.ts"; |
| 214 | import { deletePendingAttachment, issueAttachmentUploadUrl } from "./assets/AttachmentUpload.ts"; |
| 215 | import * as PortScanner from "./preview/PortScanner.ts"; |
| 216 | import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts"; |
| 217 | import * as KnownWorkspaces from "./workspace/KnownWorkspaces.ts"; |
| 218 | import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts"; |
| 219 | import { readWorkflowScript } from "./orchestration-v2/workflowScriptQuery.ts"; |
| 220 | import * as WorkspacePaths from "./workspace/WorkspacePaths.ts"; |
| 221 | import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts"; |
| 222 | import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts"; |
| 223 | import * as GitWorkflowService from "./git/GitWorkflowService.ts"; |
| 224 | import { refreshPushedPullRequests } from "./git/refreshPushedPullRequests.ts"; |
| 225 | import { linkCreatedPullRequest } from "./git/linkCreatedPullRequest.ts"; |
| 226 | import * as ReviewService from "./review/ReviewService.ts"; |
| 227 | import * as ProjectEnrichmentService from "./project/ProjectEnrichmentService.ts"; |
| 228 | import * as ProjectService from "./project/ProjectService.ts"; |
| 229 | import { threadWorkspaceRoot } from "./project/threadWorkspaceRoot.ts"; |
| 230 | import * as ManagedProjectFolders from "./project/ManagedProjectFolders.ts"; |
| 231 | import * as ScratchThreadPromotion from "./project/ScratchThreadPromotion.ts"; |
| 232 | import { mutateProjectWithClone } from "./project/ProjectMutation.ts"; |
| 233 | import * as ProjectCloneTracker from "./project/ProjectCloneTracker.ts"; |
| 234 | import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts"; |
| 235 | import * as WorktreeSetupTracker from "./project/WorktreeSetupTracker.ts"; |
| 236 | import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; |
| 237 | import * as DirectEndpoints from "./environment/DirectEndpoints.ts"; |
| 238 | import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts"; |
| 239 | import * as DefectReporter from "./observability/DefectReporter.ts"; |
| 240 | import * as EventLoopMonitor from "./observability/EventLoopMonitor.ts"; |
| 241 | import * as BackgroundPolicy from "./background/BackgroundPolicy.ts"; |
| 242 | import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; |
| 243 | import { requiredScopeForDeviceList, rpcAuthorizationError } from "./auth/RpcAuthorization.ts"; |
| 244 | import * as RpcAuthorization from "./auth/RpcAuthorization.ts"; |
| 245 | import { RpcInstrumentation, rpcInstrumentationLayer } from "./observability/RpcInstrumentation.ts"; |
| 246 | import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts"; |
| 247 | import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts"; |
| 248 | import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts"; |
| 249 | import * as HostResources from "./resourceTelemetry/HostResources.ts"; |
| 250 | import * as AnalyticsService from "./telemetry/AnalyticsService.ts"; |
| 251 | import { commandFeatureUsage, featureUsage } from "./telemetry/FeatureUsage.ts"; |
| 252 | import type { TelemetryOwner } from "./telemetry/Identify.ts"; |
| 253 | import * as UsageService from "./usage/UsageService.ts"; |
| 254 | import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts"; |
| 255 | import * as TriageService from "./triage/TriageService.ts"; |
| 256 | import * as PullRequestService from "./pullRequest/PullRequestService.ts"; |
| 257 | import * as IssueService from "./issue/IssueService.ts"; |
| 258 | import * as ThreadIssueService from "./orchestration-v2/ThreadIssueService.ts"; |
| 259 | import * as IssueTrackerConnections from "./issue/IssueTrackerConnections.ts"; |
| 260 | import * as PullRequestReviewGuideService from "./pullRequest/PullRequestReviewGuideService.ts"; |
| 261 | import { listLinkedPullRequestThreads } from "./pullRequest/linkedThreads.ts"; |
| 262 | import { pullRequestSyncKey } from "./pullRequest/pullRequestSyncKey.ts"; |
| 263 | import * as SqlClient from "effect/sql/SqlClient"; |
| 264 | import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts"; |
| 265 | import * as SourceControlDiscovery from "./sourceControl/SourceControlDiscovery.ts"; |
| 266 | import * as OtlpEndpointCheck from "./observability/OtlpEndpointCheck.ts"; |
| 267 | import * as TextGenerators from "./textGeneration/TextGenerators.ts"; |
| 268 | import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts"; |
| 269 | import * as SourceControlSignIn from "./sourceControl/SourceControlSignIn.ts"; |
| 270 | import * as SourceControlBuiltInDrivers from "./sourceControl/builtInDrivers.ts"; |
| 271 | import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts"; |
| 272 | import * as GitVcsDriver from "./vcs/GitVcsDriver.ts"; |
| 273 | import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts"; |
| 274 | import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts"; |
| 275 | import * as PairingGrantStore from "./auth/PairingGrantStore.ts"; |
| 276 | import * as SessionStore from "./auth/SessionStore.ts"; |
| 277 | import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts"; |
| 278 | import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; |
| 279 | import { isNetworkPath } from "@t3tools/shared/path"; |
| 280 | import * as RelayClient from "@t3tools/shared/relayClient"; |
| 281 | import { |
| 282 | SOCKET_FRAME_PARTS_QUERY_PARAM, |
| 283 | splitLargeSocketFrames, |
| 284 | } from "@t3tools/shared/socketFrameParts"; |
| 285 | import { isTelemetryIdHash } from "@t3tools/shared/telemetryId"; |
| 286 | import { |
| 287 | sameUsageLimitCommandCoverage, |
| 288 | withUsageLimitsCommands, |
| 289 | } from "@t3tools/shared/usageLimits"; |
| 290 | import * as AgentSessionScanner from "./project/AgentSessionScanner.ts"; |
| 291 | import * as AgentSessionImporter from "./project/AgentSessionImporter.ts"; |
| 292 | import * as UsageLimitSources from "./usage/UsageLimitSources.ts"; |
| 293 | import { requestUrl } from "./requestUrl.ts"; |
| 294 | |
| 295 | const CONFIG_DISCOVERY_TIMEOUT = Duration.seconds(5); |
| 296 | const isProviderUploadFeedbackError = Schema.is(ProviderUploadFeedbackError); |
| 297 | |
| 298 | const resolveDiscoveryForConfig = <A, E, R>( |
| 299 | discovery: Effect.Effect<A, E, R>, |
| 300 | onTimeout: () => A, |
| 301 | ) => |
| 302 | discovery.pipe( |
| 303 | Effect.timeoutOption(CONFIG_DISCOVERY_TIMEOUT), |
| 304 | Effect.map(Option.getOrElse(onTimeout)), |
| 305 | ); |
| 306 | |
| 307 | const resolveAvailableEditorsForConfig = <A, E, R>( |
| 308 | discovery: Effect.Effect<ReadonlyArray<A>, E, R>, |
| 309 | ) => resolveDiscoveryForConfig(discovery, () => []); |
| 310 | |
| 311 | const resolveFileManagerRevealKindForConfig = <E, R>( |
| 312 | discovery: Effect.Effect<FileManagerRevealKind | undefined, E, R>, |
| 313 | ) => resolveDiscoveryForConfig(discovery, () => undefined); |
| 314 | |
| 315 | type EditorDiscovery = Pick< |
| 316 | ExternalLauncher.ExternalLauncher["Service"], |
| 317 | "resolveAvailableEditors" | "resolveFileManagerRevealKind" |
| 318 | >; |
| 319 | |
| 320 | const resolveEditorConfig = Effect.fn("ws.resolveEditorConfig")(function* <E, R>( |
| 321 | availableEditors: ReadonlyArray<EditorId>, |
| 322 | revealKind: Effect.Effect<FileManagerRevealKind | undefined, E, R>, |
| 323 | ) { |
| 324 | const fileManagerRevealKind = availableEditors.includes("file-manager") |
| 325 | ? yield* revealKind |
| 326 | : undefined; |
| 327 | return { |
| 328 | availableEditors, |
| 329 | ...(fileManagerRevealKind === undefined |
| 330 | ? {} |
| 331 | : { |
| 332 | shellRevealInFileManager: true, |
| 333 | shellRevealInFileManagerKind: fileManagerRevealKind, |
| 334 | }), |
| 335 | }; |
| 336 | }); |
| 337 | |
| 338 | export const withLateConfigDiscovery = <E, R>( |
| 339 | config: ClientServerConfig, |
| 340 | liveUpdates: Stream.Stream<ServerConfigStreamEvent, E, R>, |
| 341 | launcher: EditorDiscovery, |
| 342 | remoteOpenTargets: RemoteOpenTargets.RemoteOpenTargets["Service"], |
| 343 | directEndpoints: Pick<DirectEndpoints.DirectEndpoints["Service"], "resolve">, |
| 344 | ) => { |
| 345 | const lateEditorConfig = Stream.fromEffect(launcher.resolveAvailableEditors()).pipe( |
| 346 | Stream.filter( |
| 347 | (editors) => |
| 348 | editors.join() !== config.availableEditors.join() || |
| 349 | (editors.includes("file-manager") && config.shellRevealInFileManagerKind === undefined), |
| 350 | ), |
| 351 | // Unbounded, unlike the snapshot: this exists to deliver a probe that |
| 352 | // outlasts the snapshot's timeout. |
| 353 | Stream.mapEffect((editors) => |
| 354 | resolveEditorConfig(editors, launcher.resolveFileManagerRevealKind()), |
| 355 | ), |
| 356 | Stream.filter( |
| 357 | (editorConfig) => |
| 358 | editorConfig.availableEditors.join() !== config.availableEditors.join() || |
| 359 | editorConfig.shellRevealInFileManagerKind !== config.shellRevealInFileManagerKind, |
| 360 | ), |
| 361 | Stream.map((editorConfig) => ({ type: "editorsResolved" as const, editorConfig })), |
| 362 | ); |
| 363 | |
| 364 | const lateRemoteOpenTargets = Stream.fromEffect(remoteOpenTargets.resolveTargets()).pipe( |
| 365 | Stream.filter( |
| 366 | (targets) => JSON.stringify(targets) !== JSON.stringify(config.remoteOpenTargets ?? []), |
| 367 | ), |
| 368 | Stream.map((targets) => ({ type: "remoteOpenTargetsResolved" as const, targets })), |
| 369 | ); |
| 370 | |
| 371 | const lateDirectEndpoints = Stream.fromEffect(directEndpoints.resolve()).pipe( |
| 372 | Stream.catchCause(() => Stream.empty), |
| 373 | Stream.map((endpoints) => ({ type: "directEndpointsResolved" as const, endpoints })), |
| 374 | ); |
| 375 | |
| 376 | return Stream.merge( |
| 377 | liveUpdates, |
| 378 | Stream.merge(lateEditorConfig, Stream.merge(lateRemoteOpenTargets, lateDirectEndpoints)), |
| 379 | ).pipe( |
| 380 | Stream.mapAccum( |
| 381 | (): ClientServerConfig => config, |
| 382 | (current, event): readonly [ClientServerConfig, ReadonlyArray<ServerConfigStreamEvent>] => { |
| 383 | switch (event.type) { |
| 384 | case "editorsResolved": { |
| 385 | const { |
| 386 | availableEditors: _editors, |
| 387 | shellRevealInFileManager: _reveal, |
| 388 | shellRevealInFileManagerKind: _revealKind, |
| 389 | ...rest |
| 390 | } = current; |
| 391 | const next = { ...rest, ...event.editorConfig }; |
| 392 | return [next, [{ version: 1, type: "snapshot", config: next }]]; |
| 393 | } |
| 394 | case "remoteOpenTargetsResolved": { |
| 395 | const next = { ...current, remoteOpenTargets: event.targets }; |
| 396 | return [next, [{ version: 1, type: "snapshot", config: next }]]; |
| 397 | } |
| 398 | case "directEndpointsResolved": { |
| 399 | if (JSON.stringify(current.directEndpoints ?? []) === JSON.stringify(event.endpoints)) { |
| 400 | return [current, []]; |
| 401 | } |
| 402 | const next = { ...current, directEndpoints: event.endpoints }; |
| 403 | return [next, [{ version: 1, type: "snapshot", config: next }]]; |
| 404 | } |
| 405 | case "keybindingsUpdated": |
| 406 | return [{ ...current, ...event.payload }, [event]]; |
| 407 | case "providerStatuses": |
| 408 | return [{ ...current, providers: event.payload.providers }, [event]]; |
| 409 | case "settingsUpdated": |
| 410 | return [{ ...current, settings: event.payload.settings }, [event]]; |
| 411 | // Themes and usage-limit sources survive snapshots because snapshots never include them. |
| 412 | default: |
| 413 | return [current, [event]]; |
| 414 | } |
| 415 | }, |
| 416 | ), |
| 417 | ); |
| 418 | }; |
| 419 | |
| 420 | // Discoveries run side by side so the slowest one, not their sum, bounds the |
| 421 | // server config snapshot. Each degrades on timeout rather than failing it. |
| 422 | export const resolveOpenDiscoveryForConfig = <T, D, E1, R1, E2, R2, E3, R3, E4, R4>(discovery: { |
| 423 | readonly editors: Effect.Effect<ReadonlyArray<EditorId>, E1, R1>; |
| 424 | readonly fileManagerRevealKind: Effect.Effect<FileManagerRevealKind | undefined, E2, R2>; |
| 425 | readonly remoteOpenTargets: Effect.Effect<ReadonlyArray<T>, E3, R3>; |
| 426 | readonly directEndpoints: Effect.Effect<ReadonlyArray<D>, E4, R4>; |
| 427 | }) => |
| 428 | Effect.all( |
| 429 | { |
| 430 | editorConfig: resolveAvailableEditorsForConfig(discovery.editors).pipe( |
| 431 | Effect.flatMap((availableEditors) => |
| 432 | resolveEditorConfig( |
| 433 | availableEditors, |
| 434 | resolveFileManagerRevealKindForConfig(discovery.fileManagerRevealKind), |
| 435 | ), |
| 436 | ), |
| 437 | ), |
| 438 | // Same discovery-with-timeout treatment as editors: a slow probe must |
| 439 | // not stall server.getConfig, so it degrades to an empty list. |
| 440 | remoteOpenTargets: resolveAvailableEditorsForConfig(discovery.remoteOpenTargets), |
| 441 | directEndpoints: resolveAvailableEditorsForConfig(discovery.directEndpoints), |
| 442 | }, |
| 443 | { concurrency: "unbounded" }, |
| 444 | ).pipe(Effect.map(({ editorConfig, ...endpoints }) => ({ ...editorConfig, ...endpoints }))); |
| 445 | // A failed scan leaves no cwd snapshot, so a client without the machine catalog gets it |
| 446 | // as a pending snapshot, which it shows while it retries the scan. |
| 447 | function workspaceSnapshotOrCatalog( |
| 448 | provider: ServerProvider, |
| 449 | cwd: string, |
| 450 | catalogOnDemand: boolean, |
| 451 | ) { |
| 452 | const snapshots = (provider.workspaceSnapshots ?? []).filter((snapshot) => snapshot.cwd === cwd); |
| 453 | if (snapshots.length > 0 || !catalogOnDemand) return snapshots; |
| 454 | return [ |
| 455 | { |
| 456 | cwd, |
| 457 | checkedAt: provider.checkedAt, |
| 458 | slashCommands: provider.slashCommands, |
| 459 | slashCommandsPending: true, |
| 460 | skills: provider.skills, |
| 461 | }, |
| 462 | ]; |
| 463 | } |
| 464 | |
| 465 | // What an on-demand catalog client keeps of the machine catalog: full entries come from the |
| 466 | // cwd snapshot it fetches, and skill names and labels keep skill links working without one. |
| 467 | function machineCatalogNames(provider: Pick<ServerProvider, "slashCommands" | "skills">) { |
| 468 | return { |
| 469 | slashCommands: provider.slashCommands.map(({ name }) => ({ name })), |
| 470 | skills: provider.skills.map(({ description: _d, shortDescription: _s, ...skill }) => skill), |
| 471 | }; |
| 472 | } |
| 473 | |
| 474 | // Stable across restarts, so a client's cached lists stay current until the catalog changes. |
| 475 | // It covers the full entries: a changed description or input hint must reach the client too. |
| 476 | const machineCatalogDigest = (provider: Pick<ServerProvider, "slashCommands" | "skills">) => |
| 477 | NodeCrypto.createHash("sha256") |
| 478 | .update(JSON.stringify([provider.slashCommands, provider.skills])) |
| 479 | .digest("hex") |
| 480 | .slice(0, 16); |
| 481 | |
| 482 | // Names, or the digest that stands for them, still change the config when the machine catalog |
| 483 | // does, so the client refetches its cwd snapshot. |
| 484 | function withoutWorkspaceSnapshots( |
| 485 | providers: ReadonlyArray<ServerProvider>, |
| 486 | catalogsPerCwd: ReadonlySet<string> = new Set(), |
| 487 | catalogDigests = false, |
| 488 | ): ServerProvider[] { |
| 489 | return providers.map(({ workspaceSnapshots: _workspaceSnapshots, ...provider }) => { |
| 490 | if (!catalogsPerCwd.has(provider.instanceId)) return provider; |
| 491 | return catalogDigests |
| 492 | ? { |
| 493 | ...provider, |
| 494 | slashCommands: [], |
| 495 | skills: [], |
| 496 | catalogDigest: machineCatalogDigest(provider), |
| 497 | } |
| 498 | : { ...provider, ...machineCatalogNames(provider) }; |
| 499 | }); |
| 500 | } |
| 501 | |
| 502 | // Deltas are taken from the list this client last received, which a late snapshot replaces. |
| 503 | const withProviderStatusDeltas = (sent: ReadonlyArray<ServerProvider>) => |
| 504 | Stream.mapAccum( |
| 505 | () => sent, |
| 506 | ( |
| 507 | previous, |
| 508 | event: ServerConfigStreamEvent, |
| 509 | ): readonly [ReadonlyArray<ServerProvider>, ReadonlyArray<ServerConfigStreamEvent>] => { |
| 510 | if (event.type === "snapshot") return [event.config.providers, [event]]; |
| 511 | if (event.type !== "providerStatuses") return [previous, [event]]; |
| 512 | const { providers } = event.payload; |
| 513 | return [ |
| 514 | providers, |
| 515 | [ |
| 516 | { |
| 517 | version: 1, |
| 518 | type: "providerStatusDeltas", |
| 519 | payload: { providers: serverProviderDeltas(previous, providers) }, |
| 520 | }, |
| 521 | ], |
| 522 | ]; |
| 523 | }, |
| 524 | ); |
| 525 | |
| 526 | function unexpectedCompatibilityError(error: never): never { |
| 527 | throw new Error(`Unhandled compatibility error: ${String(error)}`); |
| 528 | } |
| 529 | |
| 530 | const persistChatAttachments = Effect.fn("ws.assets.persistChatAttachments")(function* (input: { |
| 531 | readonly threadId: ThreadId; |
| 532 | readonly messageId: MessageId; |
| 533 | readonly attachments: ReadonlyArray<{ |
| 534 | readonly type: "image"; |
| 535 | readonly name: string; |
| 536 | readonly mimeType: string; |
| 537 | readonly sizeBytes: number; |
| 538 | readonly dataUrl: string; |
| 539 | }>; |
| 540 | }) { |
| 541 | const config = yield* ServerConfig.ServerConfig; |
| 542 | const fileSystem = yield* FileSystem.FileSystem; |
| 543 | const path = yield* Path.Path; |
| 544 | return yield* Effect.forEach( |
| 545 | input.attachments.map((attachment, index) => ({ attachment, index })), |
| 546 | Effect.fn("ws.assets.persistChatAttachment")(function* ({ attachment, index }) { |
| 547 | const parsed = parseBase64DataUrl(attachment.dataUrl); |
| 548 | if (parsed === null || parsed.mimeType !== attachment.mimeType.toLowerCase()) { |
| 549 | return yield* new PersistChatAttachmentsError({ |
| 550 | message: `Attachment ${attachment.name} has an invalid image payload.`, |
| 551 | }); |
| 552 | } |
| 553 | const bytes = yield* Effect.fromResult(Base64.decode(parsed.base64)).pipe( |
| 554 | Effect.mapError( |
| 555 | (cause) => |
| 556 | new PersistChatAttachmentsError({ |
| 557 | message: `Attachment ${attachment.name} is not valid base64.`, |
| 558 | cause, |
| 559 | }), |
| 560 | ), |
| 561 | ); |
| 562 | if (bytes.byteLength !== attachment.sizeBytes) { |
| 563 | return yield* new PersistChatAttachmentsError({ |
| 564 | message: `Attachment ${attachment.name} size does not match its payload.`, |
| 565 | }); |
| 566 | } |
| 567 | const rawId = createDeterministicAttachmentId( |
| 568 | input.threadId, |
| 569 | chatAttachmentStableKey(input.messageId, index, bytes), |
| 570 | ); |
| 571 | if (rawId === null) { |
| 572 | return yield* new PersistChatAttachmentsError({ |
| 573 | message: "Could not allocate an attachment identifier.", |
| 574 | }); |
| 575 | } |
| 576 | const persisted = { |
| 577 | type: "image" as const, |
| 578 | id: ChatAttachmentId.make(rawId), |
| 579 | name: attachment.name, |
| 580 | mimeType: attachment.mimeType, |
| 581 | sizeBytes: attachment.sizeBytes, |
| 582 | }; |
| 583 | yield* fileSystem |
| 584 | .writeFile(path.join(config.attachmentsDir, attachmentRelativePath(persisted)!), bytes) |
| 585 | .pipe( |
| 586 | Effect.mapError( |
| 587 | (cause) => |
| 588 | new PersistChatAttachmentsError({ |
| 589 | message: `Could not persist attachment ${attachment.name}.`, |
| 590 | cause, |
| 591 | }), |
| 592 | ), |
| 593 | ); |
| 594 | return persisted; |
| 595 | }), |
| 596 | { concurrency: 2 }, |
| 597 | ); |
| 598 | }); |
| 599 | |
| 600 | function projectEntriesFailureContext(error: WorkspaceEntries.WorkspaceEntriesError): { |
| 601 | readonly failure: ProjectEntriesFailure; |
| 602 | readonly normalizedCwd?: string; |
| 603 | readonly timeout?: string; |
| 604 | readonly detail?: string; |
| 605 | } { |
| 606 | switch (error._tag) { |
| 607 | case "WorkspaceRootNotExistsError": |
| 608 | return { |
| 609 | failure: "workspace_root_not_found", |
| 610 | normalizedCwd: error.normalizedWorkspaceRoot, |
| 611 | }; |
| 612 | case "WorkspaceRootCreateFailedError": |
| 613 | return { |
| 614 | failure: "workspace_root_create_failed", |
| 615 | normalizedCwd: error.normalizedWorkspaceRoot, |
| 616 | }; |
| 617 | case "WorkspaceRootStatFailedError": |
| 618 | return { |
| 619 | failure: "workspace_root_stat_failed", |
| 620 | normalizedCwd: error.normalizedWorkspaceRoot, |
| 621 | detail: error.phase, |
| 622 | }; |
| 623 | case "WorkspaceRootNotDirectoryError": |
| 624 | return { |
| 625 | failure: "workspace_root_not_directory", |
| 626 | normalizedCwd: error.normalizedWorkspaceRoot, |
| 627 | }; |
| 628 | case "WorkspaceEntriesReadDirectoryError": |
| 629 | return { |
| 630 | failure: "directory_list_failed", |
| 631 | ...(error.cwd !== undefined ? { normalizedCwd: error.cwd } : {}), |
| 632 | detail: error.message, |
| 633 | }; |
| 634 | case "WorkspaceSearchIndexCreateFailed": |
| 635 | return { |
| 636 | failure: "search_index_create_failed", |
| 637 | normalizedCwd: error.cwd, |
| 638 | detail: error.reason, |
| 639 | }; |
| 640 | case "WorkspaceSearchIndexScanTimedOut": |
| 641 | return { |
| 642 | failure: "search_index_scan_timed_out", |
| 643 | normalizedCwd: error.cwd, |
| 644 | timeout: error.timeout, |
| 645 | }; |
| 646 | case "WorkspaceSearchIndexSearchFailed": |
| 647 | return { |
| 648 | failure: "search_index_search_failed", |
| 649 | normalizedCwd: error.cwd, |
| 650 | detail: error.reason, |
| 651 | }; |
| 652 | default: |
| 653 | return unexpectedCompatibilityError(error); |
| 654 | } |
| 655 | } |
| 656 | |
| 657 | function filesystemBrowseFailureContext(error: WorkspaceEntries.WorkspaceEntriesBrowseError): { |
| 658 | readonly failure: FilesystemBrowseFailure; |
| 659 | readonly parentPath?: string; |
| 660 | readonly platform?: string; |
| 661 | readonly pathMissing?: boolean; |
| 662 | } { |
| 663 | switch (error._tag) { |
| 664 | case "WorkspaceEntriesWindowsPathUnsupportedError": |
| 665 | return { failure: "windows_path_unsupported", platform: error.platform }; |
| 666 | case "WorkspaceEntriesCurrentProjectRequiredError": |
| 667 | return { failure: "current_project_required" }; |
| 668 | case "WorkspaceEntriesReadDirectoryError": |
| 669 | return { |
| 670 | failure: "read_directory_failed", |
| 671 | parentPath: error.parentPath, |
| 672 | ...(error.pathMissing ? { pathMissing: true } : {}), |
| 673 | }; |
| 674 | default: |
| 675 | return unexpectedCompatibilityError(error); |
| 676 | } |
| 677 | } |
| 678 | |
| 679 | function projectFileFailureContext( |
| 680 | error: |
| 681 | | WorkspaceFileSystem.WorkspaceFileSystemError |
| 682 | | WorkspacePaths.WorkspacePathOutsideRootError |
| 683 | | KnownWorkspaces.UnknownWorkspaceError, |
| 684 | ): { |
| 685 | readonly failure: ProjectFileFailure; |
| 686 | readonly resolvedPath?: string; |
| 687 | readonly resolvedWorkspaceRoot?: string; |
| 688 | readonly operation?: ProjectFileOperation; |
| 689 | readonly operationPath?: string; |
| 690 | } { |
| 691 | switch (error._tag) { |
| 692 | case "WorkspacePathOutsideRootError": |
| 693 | case "UnknownWorkspaceError": |
| 694 | return { failure: "workspace_path_outside_root" }; |
| 695 | case "WorkspaceFileSystemOperationError": |
| 696 | return { |
| 697 | failure: "operation_failed", |
| 698 | resolvedPath: error.resolvedPath, |
| 699 | operation: error.operation, |
| 700 | operationPath: error.operationPath, |
| 701 | }; |
| 702 | case "WorkspaceFilePathEscapeError": |
| 703 | return { |
| 704 | failure: "resolved_path_outside_root", |
| 705 | resolvedPath: error.resolvedPath, |
| 706 | resolvedWorkspaceRoot: error.resolvedWorkspaceRoot, |
| 707 | }; |
| 708 | case "WorkspacePathNotFileError": |
| 709 | return { failure: "path_not_file", resolvedPath: error.resolvedPath }; |
| 710 | case "WorkspaceBinaryFileError": |
| 711 | return { failure: "binary_file", resolvedPath: error.resolvedPath }; |
| 712 | default: |
| 713 | return unexpectedCompatibilityError(error); |
| 714 | } |
| 715 | } |
| 716 | |
| 717 | const PROVIDER_STATUS_DEBOUNCE_MS = 200; |
| 718 | |
| 719 | // Middleware added later wraps middleware added earlier, so instrumentation wraps authorization. |
| 720 | const ServerWsRpcGroup = WsRpcGroup.middleware(RpcInstrumentation); |
| 721 | |
| 722 | // RpcGroup.toLayer derives each handler's requirements by scanning every RPC in |
| 723 | // the group, so its type cost grows with handlers × RPCs. Near 200 methods that |
| 724 | // crosses TypeScript's instantiation limit and the layer's requirements degrade to |
| 725 | // `any`, so the handlers are registered as two disjoint, smaller groups. |
| 726 | type ServerWsRpc = RpcGroup.Rpcs<typeof ServerWsRpcGroup>; |
| 727 | const SPLIT_WS_RPC_PREFIXES = [ |
| 728 | "server", |
| 729 | "pullRequests", |
| 730 | "issues", |
| 731 | "issueTrackers", |
| 732 | "provider", |
| 733 | "orchestration", |
| 734 | ] as const; |
| 735 | type SplitWsRpc = Extract< |
| 736 | ServerWsRpc, |
| 737 | { readonly _tag: `${(typeof SPLIT_WS_RPC_PREFIXES)[number]}.${string}` } |
| 738 | >; |
| 739 | const isSplitWsRpc = (rpc: ServerWsRpc): rpc is SplitWsRpc => |
| 740 | SPLIT_WS_RPC_PREFIXES.some((prefix) => rpc._tag.startsWith(`${prefix}.`)); |
| 741 | const isOtherWsRpc = (rpc: ServerWsRpc): rpc is Exclude<ServerWsRpc, SplitWsRpc> => |
| 742 | !isSplitWsRpc(rpc); |
| 743 | const serverWsRpcs = Array.from(ServerWsRpcGroup.requests.values()); |
| 744 | const SplitWsRpcGroup = RpcGroup.make(...serverWsRpcs.filter(isSplitWsRpc)); |
| 745 | const OtherWsRpcGroup = RpcGroup.make(...serverWsRpcs.filter(isOtherWsRpc)); |
| 746 | function toAuthAccessStreamEvent( |
| 747 | change: Exclude< |
| 748 | PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange, |
| 749 | { readonly type: "connectDevicesChanged" } |
| 750 | >, |
| 751 | revision: number, |
| 752 | currentSessionId: AuthSessionId, |
| 753 | ): AuthAccessStreamEvent { |
| 754 | switch (change.type) { |
| 755 | case "pairingLinkUpserted": |
| 756 | return { |
| 757 | version: 1, |
| 758 | revision, |
| 759 | type: "pairingLinkUpserted", |
| 760 | payload: { ...change.pairingLink, ...authScopeResponse(change.pairingLink.scopes) }, |
| 761 | }; |
| 762 | case "pairingLinkRemoved": |
| 763 | return { |
| 764 | version: 1, |
| 765 | revision, |
| 766 | type: "pairingLinkRemoved", |
| 767 | payload: { id: change.id }, |
| 768 | }; |
| 769 | case "clientUpserted": |
| 770 | return { |
| 771 | version: 1, |
| 772 | revision, |
| 773 | type: "clientUpserted", |
| 774 | payload: { |
| 775 | ...change.clientSession, |
| 776 | ...authScopeResponse(change.clientSession.scopes), |
| 777 | current: change.clientSession.sessionId === currentSessionId, |
| 778 | }, |
| 779 | }; |
| 780 | case "clientRemoved": |
| 781 | return { |
| 782 | version: 1, |
| 783 | revision, |
| 784 | type: "clientRemoved", |
| 785 | payload: { sessionId: change.sessionId }, |
| 786 | }; |
| 787 | } |
| 788 | } |
| 789 | |
| 790 | const isClientSurface = Schema.is(ClientSurface); |
| 791 | const isClientConnectionMethod = Schema.is(ClientConnectionMethod); |
| 792 | const isClientDeviceType = Schema.is(ClientDeviceType); |
| 793 | const isClientOs = Schema.is(ClientOs); |
| 794 | const isClientWebDeployment = Schema.is(ClientWebDeployment); |
| 795 | const MAX_CLIENT_APP_VERSION_LENGTH = 64; |
| 796 | const MAX_CLIENT_BROWSER_LENGTH = 64; |
| 797 | const MAX_CLIENT_DEVICE_MODEL_LENGTH = 80; |
| 798 | |
| 799 | function hasCompatibleOrchestrationProtocol(url: URL): boolean { |
| 800 | return ( |
| 801 | url.searchParams.get(ORCHESTRATION_PROTOCOL_QUERY_PARAM) === |
| 802 | String(ORCHESTRATION_PROTOCOL_VERSION) |
| 803 | ); |
| 804 | } |
| 805 | |
| 806 | function readSettingsClient(url: URL) { |
| 807 | const capabilities = url.searchParams.get(CLIENT_CAPABILITIES_QUERY_PARAM)?.split(",") ?? []; |
| 808 | return { secretReferences: capabilities.includes(SETTINGS_SECRET_REFERENCES_CAPABILITY) }; |
| 809 | } |
| 810 | |
| 811 | function shouldUseBoundedThreadSnapshot(input: { |
| 812 | readonly acceptBoundedSnapshot?: boolean; |
| 813 | readonly acceptDeferredWork?: boolean; |
| 814 | }): boolean { |
| 815 | return input.acceptBoundedSnapshot === true; |
| 816 | } |
| 817 | |
| 818 | // Keep telemetry per socket; several client types can connect simultaneously. |
| 819 | function readClientAnalyticsProps(request: HttpServerRequest.HttpServerRequest) { |
| 820 | const url = requestUrl(request); |
| 821 | if (Option.isNone(url)) { |
| 822 | return {}; |
| 823 | } |
| 824 | |
| 825 | const surface = url.value.searchParams.get("clientSurface"); |
| 826 | const appVersion = url.value.searchParams.get("clientAppVersion")?.trim() ?? ""; |
| 827 | const deviceType = url.value.searchParams.get("clientDeviceType"); |
| 828 | const os = url.value.searchParams.get("clientOs"); |
| 829 | const webDeployment = url.value.searchParams.get("clientWebDeployment"); |
| 830 | const browser = url.value.searchParams.get("clientBrowser")?.trim() ?? ""; |
| 831 | const connectionMethod = url.value.searchParams.get("connectionMethod"); |
| 832 | const rawOsMajorVersion = url.value.searchParams.get("clientOsMajorVersion") ?? ""; |
| 833 | const osMajorVersion = Number(rawOsMajorVersion); |
| 834 | const deviceModel = url.value.searchParams.get("clientDeviceModel")?.trim() ?? ""; |
| 835 | const isMobile = surface === "mobile"; |
| 836 | const hasOsMajorVersion = |
| 837 | isMobile && rawOsMajorVersion !== "" && Number.isInteger(osMajorVersion) && osMajorVersion > 0; |
| 838 | const hasDeviceModel = |
| 839 | isMobile && deviceModel !== "" && deviceModel.length <= MAX_CLIENT_DEVICE_MODEL_LENGTH; |
| 840 | |
| 841 | return { |
| 842 | ...(isClientSurface(surface) ? { surface } : {}), |
| 843 | ...(appVersion !== "" && appVersion.length <= MAX_CLIENT_APP_VERSION_LENGTH |
| 844 | ? { appVersion, clientAppVersion: appVersion } |
| 845 | : {}), |
| 846 | ...(isClientOs(os) |
| 847 | ? { |
| 848 | clientOs: os, |
| 849 | ...(isMobile && (os === "iOS" || os === "Android") ? { os } : {}), |
| 850 | } |
| 851 | : {}), |
| 852 | ...(isClientDeviceType(deviceType) ? { clientDeviceType: deviceType } : {}), |
| 853 | ...(surface === "web" && isClientWebDeployment(webDeployment) ? { webDeployment } : {}), |
| 854 | ...(surface === "web" && browser !== "" && browser.length <= MAX_CLIENT_BROWSER_LENGTH |
| 855 | ? { clientBrowser: browser } |
| 856 | : {}), |
| 857 | ...(hasOsMajorVersion ? { osMajorVersion, clientOsMajorVersion: osMajorVersion } : {}), |
| 858 | ...(hasDeviceModel ? { deviceModel, clientDeviceModel: deviceModel } : {}), |
| 859 | ...(isClientConnectionMethod(connectionMethod) ? { connectionMethod } : {}), |
| 860 | }; |
| 861 | } |
| 862 | |
| 863 | /** |
| 864 | * Owners a connecting client reports: its hashed T3 Connect account and its |
| 865 | * hashed device id. Only hashes are accepted, so a raw id never reaches analytics. |
| 866 | */ |
| 867 | function readClientOwners( |
| 868 | request: HttpServerRequest.HttpServerRequest, |
| 869 | ): ReadonlyArray<TelemetryOwner> { |
| 870 | const url = requestUrl(request); |
| 871 | if (Option.isNone(url)) { |
| 872 | return []; |
| 873 | } |
| 874 | const params = url.value.searchParams; |
| 875 | return ( |
| 876 | [ |
| 877 | ["connect", params.get("clientOwner")], |
| 878 | ["device", params.get("clientDevice")], |
| 879 | ] as const |
| 880 | ).flatMap(([source, ownerId]) => |
| 881 | ownerId !== null && isTelemetryIdHash(ownerId) ? [{ source, ownerId }] : [], |
| 882 | ); |
| 883 | } |
| 884 | |
| 885 | const enrichProjectShells = Effect.fn("ws.orchestrationV2.enrichProjectShells")( |
| 886 | (projects: ReadonlyArray<OrchestrationProjectShell>) => |
| 887 | Effect.flatMap(ProjectEnrichmentService.ProjectEnrichmentService, (projectEnrichment) => |
| 888 | Effect.forEach( |
| 889 | projects, |
| 890 | (project) => |
| 891 | projectEnrichment.getAvailable(project.workspaceRoot).pipe( |
| 892 | Effect.map((enrichment) => ({ |
| 893 | project: { |
| 894 | ...project, |
| 895 | repositoryIdentity: enrichment.repositoryIdentity, |
| 896 | }, |
| 897 | repositoryIdentityResolved: enrichment.repositoryIdentityResolved, |
| 898 | })), |
| 899 | ), |
| 900 | { concurrency: 16 }, |
| 901 | ).pipe( |
| 902 | Effect.map((enriched) => ({ |
| 903 | projects: enriched.map((entry) => entry.project), |
| 904 | resolvedRepositoryIdentityRoots: enriched |
| 905 | .filter((entry) => entry.repositoryIdentityResolved) |
| 906 | .map((entry) => entry.project.workspaceRoot), |
| 907 | })), |
| 908 | ), |
| 909 | ), |
| 910 | ); |
| 911 | |
| 912 | export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subscribeThread")( |
| 913 | function* (input: { |
| 914 | readonly threadId: ThreadId; |
| 915 | readonly afterSequence?: number; |
| 916 | readonly requestCompletionMarker?: boolean; |
| 917 | readonly acceptBoundedSnapshot?: boolean; |
| 918 | readonly acceptDeferredWork?: boolean; |
| 919 | readonly acceptCompactTurnItems?: boolean; |
| 920 | readonly acceptDedupedBodies?: boolean; |
| 921 | readonly acceptCompactIds?: boolean; |
| 922 | }) { |
| 923 | const threadManagement = yield* ThreadManagementService.ThreadManagementService; |
| 924 | const dedupeBodies = input.acceptDedupedBodies === true; |
| 925 | // Replay, snapshot, and live tail share one deduper: it must see every delivered record. |
| 926 | const withLiveDedupe = <E, R>(stream: Stream.Stream<OrchestrationV2ThreadStreamItem, E, R>) => |
| 927 | dedupeBodies ? Stream.suspend(() => Stream.map(stream, makeLiveBodyDeduper())) : stream; |
| 928 | const applicationEvents = yield* OrchestrationEventStore.OrchestrationEventStore; |
| 929 | |
| 930 | yield* Effect.annotateCurrentSpan({ |
| 931 | "orchestration_v2.thread_id": input.threadId, |
| 932 | }); |
| 933 | yield* threadManagement.ensureLegacyTranscript(input.threadId).pipe( |
| 934 | Effect.mapError( |
| 935 | (cause) => |
| 936 | new OrchestrationV2GetThreadProjectionError({ |
| 937 | threadId: input.threadId, |
| 938 | message: `Failed to hydrate migrated thread ${input.threadId}`, |
| 939 | cause, |
| 940 | }), |
| 941 | ), |
| 942 | ); |
| 943 | |
| 944 | const eventStreamFrom = (afterSequence: number) => |
| 945 | threadManagement |
| 946 | .streamStoredEventsFrom({ |
| 947 | threadId: input.threadId, |
| 948 | afterSequence, |
| 949 | }) |
| 950 | .pipe( |
| 951 | Stream.map(threadStreamEventItem), |
| 952 | coalesceThreadLiveStream, |
| 953 | Stream.mapError( |
| 954 | (cause) => |
| 955 | new OrchestrationV2GetThreadProjectionError({ |
| 956 | threadId: input.threadId, |
| 957 | message: `Failed while streaming orchestration V2 thread ${input.threadId}`, |
| 958 | cause, |
| 959 | }), |
| 960 | ), |
| 961 | ); |
| 962 | |
| 963 | const loadReplayThrough = (afterSequence: number, throughSequence: number) => |
| 964 | applicationEvents |
| 965 | .readAgentEvents({ |
| 966 | threadId: input.threadId, |
| 967 | afterSequence, |
| 968 | throughSequence, |
| 969 | limit: THREAD_RESUME_MAX_REPLAY_EVENTS + 1, |
| 970 | // Downgrades can leave unknown rows; skip them and resume live from highWater so later events survive. |
| 971 | skipUnknownEventTypes: true, |
| 972 | }) |
| 973 | .pipe( |
| 974 | Stream.map((stored) => ({ |
| 975 | kind: "event" as const, |
| 976 | sequence: stored.sequence, |
| 977 | event: projectDomainEventForWire(stored.event), |
| 978 | })), |
| 979 | Stream.runCollect, |
| 980 | Effect.map((items) => Array.from(items)), |
| 981 | Effect.mapError( |
| 982 | (cause) => |
| 983 | new OrchestrationV2GetThreadProjectionError({ |
| 984 | threadId: input.threadId, |
| 985 | message: `Failed while replaying orchestration V2 thread ${input.threadId}`, |
| 986 | cause, |
| 987 | }), |
| 988 | ), |
| 989 | ); |
| 990 | |
| 991 | const completionMarker = |
| 992 | input.requestCompletionMarker === true |
| 993 | ? Stream.make({ kind: "synchronized" as const }) |
| 994 | : Stream.empty; |
| 995 | |
| 996 | const snapshotThenLive = Effect.fn("ws.orchestrationV2.threadSnapshotThenLive")(function* () { |
| 997 | const useBoundedSnapshot = shouldUseBoundedThreadSnapshot(input); |
| 998 | const snapshot = yield* ( |
| 999 | useBoundedSnapshot |
| 1000 | ? threadManagement.getThreadSnapshotWindow(input.threadId, { |
| 1001 | rowLimit: THREAD_HISTORY_SNAPSHOT_ROW_LIMIT, |
| 1002 | deferWork: input.acceptDeferredWork === true, |
| 1003 | userTurnLimit: THREAD_HISTORY_PAGE_POLICY.maxUserTurns, |
| 1004 | }) |
| 1005 | : threadManagement.getThreadSnapshot(input.threadId) |
| 1006 | ).pipe( |
| 1007 | Effect.mapError( |
| 1008 | (cause) => |
| 1009 | new OrchestrationV2GetThreadProjectionError({ |
| 1010 | threadId: input.threadId, |
| 1011 | message: `Failed to load orchestration V2 thread ${input.threadId}`, |
| 1012 | cause, |
| 1013 | }), |
| 1014 | ), |
| 1015 | ); |
| 1016 | const { snapshotSequence } = snapshot; |
| 1017 | const snapshotItem = useBoundedSnapshot |
| 1018 | ? buildBoundedThreadStreamSnapshot({ |
| 1019 | ...snapshot, |
| 1020 | compactTurnItems: input.acceptCompactTurnItems === true, |
| 1021 | dedupeBodies, |
| 1022 | compactIds: input.acceptCompactIds === true, |
| 1023 | }) |
| 1024 | : (() => { |
| 1025 | const projection = projectThreadProjectionForWire(snapshot.projection); |
| 1026 | return { |
| 1027 | kind: "snapshot" as const, |
| 1028 | snapshotSequence, |
| 1029 | projection: dedupeBodies ? dedupeSnapshotBodies(projection) : projection, |
| 1030 | }; |
| 1031 | })(); |
| 1032 | return rpcInitialItems([snapshotItem]).pipe( |
| 1033 | Stream.concat(completionMarker), |
| 1034 | Stream.concat(eventStreamFrom(snapshotSequence)), |
| 1035 | withLiveDedupe, |
| 1036 | ); |
| 1037 | }); |
| 1038 | |
| 1039 | // Subscribe before reading persisted events to retain concurrent publishes; clients dedupe overlap by sequence. |
| 1040 | if (input.afterSequence !== undefined) { |
| 1041 | const highWater = yield* applicationEvents.latestAgentSequence(input.threadId).pipe( |
| 1042 | Effect.mapError( |
| 1043 | (cause) => |
| 1044 | new OrchestrationV2GetThreadProjectionError({ |
| 1045 | threadId: input.threadId, |
| 1046 | message: `Failed to prepare orchestration V2 thread ${input.threadId} replay`, |
| 1047 | cause, |
| 1048 | }), |
| 1049 | ), |
| 1050 | ); |
| 1051 | const prunedThrough = yield* applicationEvents.prunedThroughSequence.pipe( |
| 1052 | Effect.mapError( |
| 1053 | (cause) => |
| 1054 | new OrchestrationV2GetThreadProjectionError({ |
| 1055 | threadId: input.threadId, |
| 1056 | message: `Failed to prepare orchestration V2 thread ${input.threadId} replay`, |
| 1057 | cause, |
| 1058 | }), |
| 1059 | ), |
| 1060 | ); |
| 1061 | // An idle thread's cursor sits at its own high-water: nothing was missed, so replay nothing. |
| 1062 | if ( |
| 1063 | input.afterSequence > highWater || |
| 1064 | (input.afterSequence < highWater && input.afterSequence < prunedThrough) |
| 1065 | ) { |
| 1066 | return yield* snapshotThenLive(); |
| 1067 | } |
| 1068 | const stats = yield* applicationEvents |
| 1069 | .getAgentReplayStats({ |
| 1070 | threadId: input.threadId, |
| 1071 | afterSequence: input.afterSequence, |
| 1072 | throughSequence: highWater, |
| 1073 | maxEvents: THREAD_RESUME_MAX_REPLAY_EVENTS, |
| 1074 | }) |
| 1075 | .pipe( |
| 1076 | Effect.mapError( |
| 1077 | (cause) => |
| 1078 | new OrchestrationV2GetThreadProjectionError({ |
| 1079 | threadId: input.threadId, |
| 1080 | message: `Failed to measure orchestration V2 thread ${input.threadId} replay`, |
| 1081 | cause, |
| 1082 | }), |
| 1083 | ), |
| 1084 | ); |
| 1085 | // Bound stored and projected payload bytes separately; neither bounds process memory. |
| 1086 | if ( |
| 1087 | stats.eventCount > THREAD_RESUME_MAX_REPLAY_EVENTS || |
| 1088 | !isThreadReplayRawPayloadSafe(stats.rawPayloadBytes) |
| 1089 | ) { |
| 1090 | return yield* snapshotThenLive(); |
| 1091 | } |
| 1092 | if (stats.hasCreateEvent) { |
| 1093 | const shell = yield* threadManagement.getThreadShell(input.threadId).pipe( |
| 1094 | Effect.mapError( |
| 1095 | (cause) => |
| 1096 | new OrchestrationV2GetThreadProjectionError({ |
| 1097 | threadId: input.threadId, |
| 1098 | message: `Failed to locate recreated orchestration V2 thread ${input.threadId}`, |
| 1099 | cause, |
| 1100 | }), |
| 1101 | ), |
| 1102 | ); |
| 1103 | // Retained creation events may describe deleted threads; replace replay only if a snapshot exists. |
| 1104 | if (shell !== null) return yield* snapshotThenLive(); |
| 1105 | } |
| 1106 | const replayed = yield* loadReplayThrough(input.afterSequence, highWater); |
| 1107 | // Pruning publishes its boundary before deleting, so a pass during the read shows up here. |
| 1108 | if ( |
| 1109 | input.afterSequence < highWater && |
| 1110 | input.afterSequence < |
| 1111 | (yield* applicationEvents.prunedThroughSequence.pipe( |
| 1112 | Effect.mapError( |
| 1113 | (cause) => |
| 1114 | new OrchestrationV2GetThreadProjectionError({ |
| 1115 | threadId: input.threadId, |
| 1116 | message: `Failed to prepare orchestration V2 thread ${input.threadId} replay`, |
| 1117 | cause, |
| 1118 | }), |
| 1119 | ), |
| 1120 | )) |
| 1121 | ) { |
| 1122 | return yield* snapshotThenLive(); |
| 1123 | } |
| 1124 | const replay = coalesceLiveUpdatedEvents(replayed); |
| 1125 | const plan = decideThreadResume({ |
| 1126 | afterSequence: input.afterSequence, |
| 1127 | highWater, |
| 1128 | replayEventCount: replay.length, |
| 1129 | replayEncodedBytes: threadReplayEncodedBytes(replay), |
| 1130 | }); |
| 1131 | if (plan.mode === "snapshot") { |
| 1132 | return yield* snapshotThenLive(); |
| 1133 | } |
| 1134 | return rpcInitialItems(replay).pipe( |
| 1135 | Stream.concat(completionMarker), |
| 1136 | Stream.concat(eventStreamFrom(highWater)), |
| 1137 | withLiveDedupe, |
| 1138 | ); |
| 1139 | } |
| 1140 | |
| 1141 | return yield* snapshotThenLive(); |
| 1142 | }, |
| 1143 | ); |
| 1144 | |
| 1145 | export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subscribeShell")( |
| 1146 | function* (input: { |
| 1147 | readonly afterSequence?: number; |
| 1148 | readonly httpSnapshotFallback?: true; |
| 1149 | readonly knownProjectIdentities?: string; |
| 1150 | readonly requestCompletionMarker?: boolean; |
| 1151 | readonly omitIdleSubagents?: boolean; |
| 1152 | readonly omitOlderSettled?: boolean; |
| 1153 | }) { |
| 1154 | const sql = yield* SqlClient.SqlClient; |
| 1155 | const threadManagement = yield* ThreadManagementService.ThreadManagementService; |
| 1156 | const applicationEvents = yield* OrchestrationEventStore.OrchestrationEventStore; |
| 1157 | const projects = yield* ProjectStore.ProjectStoreV2; |
| 1158 | const projectService = yield* ProjectService.ProjectService; |
| 1159 | const projectEnrichment = yield* ProjectEnrichmentService.ProjectEnrichmentService; |
| 1160 | let subagentThreadIds = new Set<string>(); |
| 1161 | const filterSubagentTranscript = (stored: ApplicationStoredEvent) => |
| 1162 | shouldPublishShellApplicationEvent(stored, subagentThreadIds); |
| 1163 | |
| 1164 | const enrichmentChanges = yield* projectEnrichment.subscribeChanges; |
| 1165 | const loadProjectMetadataSnapshot = Effect.fn("ws.orchestrationV2.loadProjectMetadataSnapshot")( |
| 1166 | function* (snapshotSequence: number) { |
| 1167 | const enriched = yield* enrichProjectShells(yield* projects.listShells()); |
| 1168 | return { |
| 1169 | snapshot: { |
| 1170 | schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION, |
| 1171 | snapshotSequence, |
| 1172 | projects: enriched.projects, |
| 1173 | threads: [], |
| 1174 | archivedThreads: [], |
| 1175 | } as OrchestrationV2ShellSnapshot, |
| 1176 | resolvedRepositoryIdentityRoots: enriched.resolvedRepositoryIdentityRoots, |
| 1177 | }; |
| 1178 | }, |
| 1179 | ); |
| 1180 | const loadSnapshot = Effect.fn("ws.orchestrationV2.loadShellSnapshot")(function* () { |
| 1181 | const forSubscriber = yield* loadSubscriberShellSnapshot({ |
| 1182 | sql, |
| 1183 | listShellIndex: threadManagement.listActiveShellIndex(), |
| 1184 | readThreads: (threadIds) => |
| 1185 | threadManagement.readShellSnapshot({ |
| 1186 | location: "active", |
| 1187 | ...(threadIds === undefined ? {} : { threadIds }), |
| 1188 | }), |
| 1189 | listProjects: projects.listShells(), |
| 1190 | latestSequence: applicationEvents.latestApplicationSequence, |
| 1191 | options: { |
| 1192 | omitIdleSubagents: input.omitIdleSubagents === true, |
| 1193 | omitOlderSettled: input.omitOlderSettled === true, |
| 1194 | }, |
| 1195 | }); |
| 1196 | subagentThreadIds = forSubscriber.subagentThreadIds; |
| 1197 | const enriched = yield* enrichProjectShells(forSubscriber.snapshot.projects); |
| 1198 | return { |
| 1199 | snapshot: { |
| 1200 | ...forSubscriber.snapshot, |
| 1201 | projects: enriched.projects, |
| 1202 | } as OrchestrationV2ShellSnapshot, |
| 1203 | resolvedRepositoryIdentityRoots: enriched.resolvedRepositoryIdentityRoots, |
| 1204 | }; |
| 1205 | }); |
| 1206 | const projectItem = Effect.fn("ws.orchestrationV2.projectShellItem")(function* ( |
| 1207 | stored: Extract<ShellApplicationEvent, { readonly aggregateKind: "project" }>, |
| 1208 | ) { |
| 1209 | if (stored.type === "project.deleted") { |
| 1210 | return { |
| 1211 | kind: "project.removed" as const, |
| 1212 | sequence: stored.sequence, |
| 1213 | projectId: stored.aggregateId, |
| 1214 | }; |
| 1215 | } |
| 1216 | const project = yield* projectService.getShell(stored.aggregateId); |
| 1217 | return Option.match(project, { |
| 1218 | onNone: () => ({ |
| 1219 | kind: "project.removed" as const, |
| 1220 | sequence: stored.sequence, |
| 1221 | projectId: stored.aggregateId, |
| 1222 | }), |
| 1223 | onSome: (value) => ({ |
| 1224 | kind: "project.updated" as const, |
| 1225 | sequence: stored.sequence, |
| 1226 | project: value, |
| 1227 | }), |
| 1228 | }); |
| 1229 | }); |
| 1230 | |
| 1231 | const projectShellItems = Effect.fn("ws.orchestrationV2.projectShellItems")(function* ( |
| 1232 | events: ReadonlyArray<ShellApplicationEvent>, |
| 1233 | ) { |
| 1234 | const coalesced = coalesceShellApplicationEvents(events); |
| 1235 | const threadIds = coalesced.flatMap((stored) => |
| 1236 | "aggregateKind" in stored ? [] : [stored.event.threadId], |
| 1237 | ); |
| 1238 | // A failed batch can't name its thread, so the scalar reads below report which one is bad. |
| 1239 | const batch = |
| 1240 | threadIds.length > 1 |
| 1241 | ? yield* threadManagement |
| 1242 | .getShellSnapshot({ threadIds }) |
| 1243 | .pipe(Effect.orElseSucceed(() => null)) |
| 1244 | : null; |
| 1245 | const batchedShells = |
| 1246 | batch === null |
| 1247 | ? null |
| 1248 | : new Map( |
| 1249 | [...batch.threads, ...batch.archivedThreads].map( |
| 1250 | (shell) => [shell.id, shell] as const, |
| 1251 | ), |
| 1252 | ); |
| 1253 | return yield* Effect.forEach( |
| 1254 | coalesced, |
| 1255 | (stored) => |
| 1256 | Effect.gen(function* () { |
| 1257 | if ("aggregateKind" in stored) { |
| 1258 | return yield* projectItem(stored); |
| 1259 | } |
| 1260 | const threadId = stored.event.threadId; |
| 1261 | const shell = |
| 1262 | batchedShells === null |
| 1263 | ? yield* threadManagement.getThreadShell(threadId) |
| 1264 | : (batchedShells.get(threadId) ?? null); |
| 1265 | return shellStreamItemFromThreadShell({ stored, shell }); |
| 1266 | }), |
| 1267 | { concurrency: 8 }, |
| 1268 | ); |
| 1269 | }); |
| 1270 | |
| 1271 | const toShellStream = <E, R>(stream: Stream.Stream<ShellApplicationEvent, E, R>) => |
| 1272 | stream.pipe( |
| 1273 | Stream.groupedWithin(512, Duration.millis(50)), |
| 1274 | Stream.mapEffect((events) => projectShellItems(Array.from(events))), |
| 1275 | Stream.flatMap(Stream.fromIterable), |
| 1276 | skipUnchangedThreadShells, |
| 1277 | ); |
| 1278 | |
| 1279 | const liveFrom = (afterSequence: number) => |
| 1280 | bufferShellLiveStream( |
| 1281 | toShellStream( |
| 1282 | applicationEvents.streamProjectedApplicationEvents({ |
| 1283 | afterSequence, |
| 1284 | project: toShellApplicationEvent, |
| 1285 | filter: filterSubagentTranscript, |
| 1286 | }), |
| 1287 | ), |
| 1288 | ); |
| 1289 | |
| 1290 | const enrichmentRefreshes = Stream.fromSubscription(enrichmentChanges).pipe( |
| 1291 | Stream.filter((change) => change.repositoryIdentityResolved), |
| 1292 | Stream.groupedWithin(64, Duration.millis(25)), |
| 1293 | Stream.mapEffect((changes) => |
| 1294 | Effect.gen(function* () { |
| 1295 | const identities = new Map( |
| 1296 | Array.from(changes, (change) => [ |
| 1297 | change.workspaceRoot, |
| 1298 | change.enrichment.repositoryIdentity, |
| 1299 | ]), |
| 1300 | ); |
| 1301 | const snapshotSequence = yield* applicationEvents.latestApplicationSequence; |
| 1302 | const changedProjects = (yield* projects.listShells()).flatMap((project) => |
| 1303 | identities.has(project.workspaceRoot) |
| 1304 | ? [{ ...project, repositoryIdentity: identities.get(project.workspaceRoot) ?? null }] |
| 1305 | : [], |
| 1306 | ); |
| 1307 | return shellStreamItemFromEnrichmentRefresh({ |
| 1308 | snapshot: { |
| 1309 | schemaVersion: ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION, |
| 1310 | snapshotSequence, |
| 1311 | projects: changedProjects, |
| 1312 | threads: [], |
| 1313 | archivedThreads: [], |
| 1314 | } as OrchestrationV2ShellSnapshot, |
| 1315 | changes: Array.from(changes), |
| 1316 | }); |
| 1317 | }), |
| 1318 | ), |
| 1319 | ); |
| 1320 | |
| 1321 | // Subscribe before loading for racing enrichments; initial refresh covers pre-subscription completions and cold HTTP snapshots. |
| 1322 | const completionMarker = |
| 1323 | input.requestCompletionMarker === true |
| 1324 | ? Stream.make({ kind: "synchronized" as const }) |
| 1325 | : Stream.empty; |
| 1326 | const initialSnapshotItems = (loaded: { |
| 1327 | readonly snapshot: OrchestrationV2ShellSnapshot; |
| 1328 | readonly resolvedRepositoryIdentityRoots: ReadonlyArray<string>; |
| 1329 | }) => |
| 1330 | rpcInitialItems( |
| 1331 | shellStreamItemsFromInitialSnapshot({ |
| 1332 | snapshot: loaded.snapshot, |
| 1333 | resolvedRepositoryIdentityRoots: loaded.resolvedRepositoryIdentityRoots, |
| 1334 | }), |
| 1335 | ); |
| 1336 | const initialEnrichmentItems = (loaded: { |
| 1337 | readonly snapshot: OrchestrationV2ShellSnapshot; |
| 1338 | readonly resolvedRepositoryIdentityRoots: ReadonlyArray<string>; |
| 1339 | }) => |
| 1340 | rpcInitialItems( |
| 1341 | shellStreamItemsFromResumeSnapshot({ |
| 1342 | snapshot: loaded.snapshot, |
| 1343 | resolvedRepositoryIdentityRoots: loaded.resolvedRepositoryIdentityRoots, |
| 1344 | }), |
| 1345 | ); |
| 1346 | // Drain initial frames before merging enrichment with live events so marked refreshes cannot precede the initial frame. |
| 1347 | const completionThenLive = (afterSequence: number) => |
| 1348 | Stream.concat(completionMarker, liveFrom(afterSequence)); |
| 1349 | |
| 1350 | const stream = yield* Effect.gen(function* () { |
| 1351 | if (input.afterSequence === undefined) { |
| 1352 | const loaded = yield* loadSnapshot(); |
| 1353 | return composeShellStreamWithEnrichment({ |
| 1354 | initial: initialSnapshotItems(loaded), |
| 1355 | tail: completionThenLive(loaded.snapshot.snapshotSequence), |
| 1356 | enrichment: enrichmentRefreshes, |
| 1357 | }); |
| 1358 | } |
| 1359 | |
| 1360 | const snapshotRequired: Stream.Stream<OrchestrationV2ShellStreamItem> = Stream.make({ |
| 1361 | kind: "snapshot-required", |
| 1362 | }); |
| 1363 | const fromSnapshot = |
| 1364 | input.httpSnapshotFallback === true |
| 1365 | ? Effect.succeed(snapshotRequired) |
| 1366 | : Effect.gen(function* () { |
| 1367 | const loaded = yield* loadSnapshot(); |
| 1368 | return composeShellStreamWithEnrichment({ |
| 1369 | initial: initialSnapshotItems(loaded), |
| 1370 | tail: completionThenLive(loaded.snapshot.snapshotSequence), |
| 1371 | enrichment: enrichmentRefreshes, |
| 1372 | }); |
| 1373 | }); |
| 1374 | const highWater = yield* applicationEvents.latestApplicationSequence; |
| 1375 | if (!(yield* canResumeShellFrom(applicationEvents, input.afterSequence, highWater))) { |
| 1376 | return yield* fromSnapshot; |
| 1377 | } |
| 1378 | |
| 1379 | subagentThreadIds = new Set(yield* threadManagement.listActiveSubagentThreadIds()); |
| 1380 | |
| 1381 | const loaded = yield* loadProjectMetadataSnapshot(highWater); |
| 1382 | // Read before replying: the range is budgeted above, and a prune pass during the read |
| 1383 | // publishes its boundary first, so the recheck below catches deleted rows. |
| 1384 | const replayed = yield* applicationEvents |
| 1385 | .readApplicationEvents({ |
| 1386 | afterSequence: input.afterSequence, |
| 1387 | throughSequence: highWater, |
| 1388 | // A row a newer build wrote (e.g. after a downgrade) must not fail |
| 1389 | // every shell resubscribe. The live tail below resumes from |
| 1390 | // highWater, so a dropped row never hides later events. |
| 1391 | skipUnknownEventTypes: true, |
| 1392 | }) |
| 1393 | .pipe(Stream.filter(filterSubagentTranscript), Stream.runCollect); |
| 1394 | if ( |
| 1395 | input.afterSequence < highWater && |
| 1396 | input.afterSequence < (yield* applicationEvents.prunedThroughSequence) |
| 1397 | ) { |
| 1398 | return yield* fromSnapshot; |
| 1399 | } |
| 1400 | const replay = toShellStream(Stream.fromIterable(replayed)); |
| 1401 | return composeShellStreamWithEnrichment({ |
| 1402 | initial: initialEnrichmentItems({ |
| 1403 | snapshot: loaded.snapshot, |
| 1404 | resolvedRepositoryIdentityRoots: resumeIdentityRoots({ |
| 1405 | projects: loaded.snapshot.projects, |
| 1406 | resolvedRepositoryIdentityRoots: loaded.resolvedRepositoryIdentityRoots, |
| 1407 | knownProjectIdentities: input.knownProjectIdentities, |
| 1408 | }), |
| 1409 | }), |
| 1410 | tail: Stream.concat(Stream.concat(replay, completionMarker), liveFrom(highWater)), |
| 1411 | enrichment: enrichmentRefreshes, |
| 1412 | }); |
| 1413 | }).pipe( |
| 1414 | Effect.mapError( |
| 1415 | (cause) => |
| 1416 | new OrchestrationV2GetShellSnapshotError({ |
| 1417 | message: "Failed to prepare the application shell stream", |
| 1418 | cause, |
| 1419 | }), |
| 1420 | ), |
| 1421 | ); |
| 1422 | |
| 1423 | return stream.pipe( |
| 1424 | dedupeShellEnrichment, |
| 1425 | Stream.mapError( |
| 1426 | (cause) => |
| 1427 | new OrchestrationV2GetShellSnapshotError({ |
| 1428 | message: "Failed while streaming the application shell", |
| 1429 | cause, |
| 1430 | }), |
| 1431 | ), |
| 1432 | ); |
| 1433 | }, |
| 1434 | ); |
| 1435 | |
| 1436 | export const layerWsRpc = ( |
| 1437 | currentSession: EnvironmentAuth.AuthenticatedSession, |
| 1438 | clientAnalyticsProps: Readonly<Record<string, unknown>>, |
| 1439 | serverBrowser: ServerBrowser.ServerBrowser["Service"], |
| 1440 | reportProfiles: ServerBrowser.ProfileReporter, |
| 1441 | settingsClient: { readonly secretReferences: boolean }, |
| 1442 | ) => |
| 1443 | Layer.effectContext( |
| 1444 | Effect.gen(function* () { |
| 1445 | const currentSessionId = currentSession.sessionId; |
| 1446 | const sql = yield* SqlClient.SqlClient; |
| 1447 | const threadManagement = yield* ThreadManagementService.ThreadManagementService; |
| 1448 | const intakeContext = yield* Effect.context< |
| 1449 | | ThreadManagementService.ThreadManagementService |
| 1450 | | ThreadLaunchService.ThreadLaunchService |
| 1451 | | FileSystem.FileSystem |
| 1452 | | ServerConfig.ServerConfig |
| 1453 | | ServerSettings.ServerSettingsService |
| 1454 | | DocumentText.DocumentText |
| 1455 | >(); |
| 1456 | const applicationEvents = yield* OrchestrationEventStore.OrchestrationEventStore; |
| 1457 | const projectStore = yield* ProjectStore.ProjectStoreV2; |
| 1458 | const projectService = yield* ProjectService.ProjectService; |
| 1459 | const managedFolders = yield* ManagedProjectFolders.ManagedProjectFolders; |
| 1460 | const scratchThreadPromotion = yield* ScratchThreadPromotion.ScratchThreadPromotion; |
| 1461 | const eventLoopMonitor = yield* EventLoopMonitor.EventLoopMonitor; |
| 1462 | const threadSearch = yield* ThreadSearch.ThreadSearch; |
| 1463 | |
| 1464 | const providerSessionsV2 = yield* ProviderSessionManager.ProviderSessionManagerV2; |
| 1465 | const mcpAppRequests = yield* McpAppRequests.McpAppRequests; |
| 1466 | const mcpSignIn = yield* McpSignIn.McpSignIn; |
| 1467 | const analytics = yield* AnalyticsService.AnalyticsService; |
| 1468 | const originProps = clientAnalyticsProps; |
| 1469 | const recordClientCommandAnalytics = (command: OrchestrationV2Command) => { |
| 1470 | const usage = commandFeatureUsage(command); |
| 1471 | return Effect.all( |
| 1472 | [ |
| 1473 | command.type === "message.dispatch" |
| 1474 | ? analytics.record("client.turn.requested", originProps) |
| 1475 | : Effect.void, |
| 1476 | usage === undefined |
| 1477 | ? Effect.void |
| 1478 | : analytics.record("feature.used", { |
| 1479 | ...usage, |
| 1480 | ...(originProps.surface === undefined ? {} : { surface: originProps.surface }), |
| 1481 | }), |
| 1482 | ], |
| 1483 | { discard: true }, |
| 1484 | ).pipe(Effect.ignore); |
| 1485 | }; |
| 1486 | const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService; |
| 1487 | const commandOutputHub = yield* CommandOutputHub.CommandOutputHub; |
| 1488 | const threadViewers = yield* ThreadViewers.ThreadViewers; |
| 1489 | const providerSessionManager = yield* ProviderSessionManager.ProviderSessionManagerV2; |
| 1490 | const scheduledTasks = yield* ScheduledTasks.ScheduledTaskService; |
| 1491 | const secretRequests = yield* SecretRequests.SecretRequests; |
| 1492 | const guestShares = yield* GuestShareService.GuestShareService; |
| 1493 | const pullRequests = yield* PullRequestService.PullRequestService; |
| 1494 | const issues = yield* IssueService.IssueService; |
| 1495 | const threadIssues = yield* ThreadIssueService.ThreadIssueService; |
| 1496 | const issueTrackers = yield* IssueTrackerConnections.IssueTrackerConnections; |
| 1497 | const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService; |
| 1498 | const pullRequestSync = yield* PullRequestSyncReactor.PullRequestSyncReactor; |
| 1499 | const deviceService = yield* DeviceService.DeviceService; |
| 1500 | const deviceHostContext = |
| 1501 | yield* Effect.context<Effect.Services<ReturnType<typeof remoteSshDeviceHosts>>>(); |
| 1502 | const orchestrationEngine = yield* Orchestrator.OrchestratorV2; |
| 1503 | const random = yield* SecureRandom.SecureRandom; |
| 1504 | // RPC client ids are only unique within one socket; terminals share viewers across sockets. |
| 1505 | const terminalViewerPrefix = yield* random.uuidV4(); |
| 1506 | const terminalViewerId = (metadata: { readonly client: { readonly id: number } }) => |
| 1507 | `${terminalViewerPrefix}:${metadata.client.id}`; |
| 1508 | const serverCommandId = (tag: string) => |
| 1509 | random.uuidV4().pipe( |
| 1510 | Effect.orDie, |
| 1511 | Effect.map((id) => CommandId.make(`server:${tag}:${id}`)), |
| 1512 | ); |
| 1513 | const resolvePullRequestSyncKey = (reference: PullRequestRef) => |
| 1514 | reference.host !== undefined && reference.repository.includes("/") |
| 1515 | ? Effect.succeed(pullRequestSyncKey(reference)) |
| 1516 | : projectService.getShell(reference.projectId).pipe( |
| 1517 | Effect.map((project) => |
| 1518 | pullRequestSyncKey(reference, Option.getOrUndefined(project)?.repositoryIdentity), |
| 1519 | ), |
| 1520 | Effect.orElseSucceed(() => null), |
| 1521 | ); |
| 1522 | const usage = yield* UsageService.UsageService; |
| 1523 | const usageLimitSources = yield* UsageLimitSources.UsageLimitSources; |
| 1524 | const worktreeSetupTracker = yield* WorktreeSetupTracker.WorktreeSetupTracker; |
| 1525 | const projectCloneTracker = yield* ProjectCloneTracker.ProjectCloneTracker; |
| 1526 | const repositoryIdentityResolver = |
| 1527 | yield* RepositoryIdentityResolver.RepositoryIdentityResolver; |
| 1528 | const projectEnrichment = yield* ProjectEnrichmentService.ProjectEnrichmentService; |
| 1529 | const agentSessionScanner = yield* AgentSessionScanner.AgentSessionScanner; |
| 1530 | const agentSessionImporter = yield* AgentSessionImporter.AgentSessionImporter; |
| 1531 | const checkpointDiffQuery = yield* CheckpointDiffQuery.CheckpointDiffQuery; |
| 1532 | const nativeChildWork = yield* NativeChildWorkQuery.NativeChildWorkQuery; |
| 1533 | const keybindings = yield* Keybindings.Keybindings; |
| 1534 | const environmentTheme = yield* EnvironmentTheme.EnvironmentThemeService; |
| 1535 | const externalLauncher = yield* ExternalLauncher.ExternalLauncher; |
| 1536 | const remoteOpenTargets = yield* RemoteOpenTargets.RemoteOpenTargets; |
| 1537 | const directEndpoints = yield* DirectEndpoints.DirectEndpoints; |
| 1538 | const gitWorkflow = yield* GitWorkflowService.GitWorkflowService; |
| 1539 | const review = yield* ReviewService.ReviewService; |
| 1540 | const vcsProvisioning = yield* VcsProvisioningService.VcsProvisioningService; |
| 1541 | const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; |
| 1542 | const terminalManager = yield* TerminalManager.TerminalManager; |
| 1543 | const prepareTerminalLaunch = yield* makePrepareTerminalLaunch( |
| 1544 | threadManagement.getThreadShell, |
| 1545 | ); |
| 1546 | const previewManager = yield* PreviewManager.PreviewManager; |
| 1547 | const portDiscovery = yield* PortScanner.PortDiscovery; |
| 1548 | const providerRegistry = yield* ProviderRegistry.ProviderRegistry; |
| 1549 | const providerInstances = yield* ProviderInstanceRegistry.ProviderInstanceRegistry; |
| 1550 | const acpRegistryCatalog = yield* AcpRegistrySupport.AcpRegistryCatalog; |
| 1551 | const acpRegistryRuntimeCoordinator = |
| 1552 | yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; |
| 1553 | const acpRegistrySessions = yield* AcpRegistrySessions.AcpRegistrySessions; |
| 1554 | const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner; |
| 1555 | const providerAuth = yield* ProviderAuthService.ProviderAuthService; |
| 1556 | const providerInstallation = yield* ProviderInstallation.ProviderInstallation; |
| 1557 | const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate; |
| 1558 | const npmRelease = yield* NpmRelease.NpmRelease; |
| 1559 | const config = yield* ServerConfig.ServerConfig; |
| 1560 | const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents; |
| 1561 | const storageCleanup = yield* StorageCleanup.StorageCleanup; |
| 1562 | const databaseStorage = yield* DatabaseStorage.DatabaseStorage; |
| 1563 | const serverSettings = yield* ServerSettings.ServerSettingsService; |
| 1564 | const secretResolver = yield* SecretResolver.SecretResolver; |
| 1565 | const peerLinks = yield* PeerLinks.PeerLinks; |
| 1566 | const peerLinkRequests = yield* PeerLinkRequests.PeerLinkRequests; |
| 1567 | const peerThreadRelay = yield* PeerThreadRelay.PeerThreadRelay; |
| 1568 | const peerClientPairing = yield* PeerClientPairing.PeerClientPairing; |
| 1569 | const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup; |
| 1570 | const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; |
| 1571 | const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem; |
| 1572 | const serverEnvironment = yield* ServerEnvironment.ServerEnvironment; |
| 1573 | const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy; |
| 1574 | const rpcClientIds = yield* Ref.make(new Set<RpcClientId>()); |
| 1575 | yield* Effect.addFinalizer(() => |
| 1576 | Ref.get(rpcClientIds).pipe( |
| 1577 | Effect.flatMap((clientIds) => |
| 1578 | Effect.forEach( |
| 1579 | clientIds, |
| 1580 | (clientId) => backgroundPolicy.removeRpcClient(currentSessionId, clientId), |
| 1581 | { |
| 1582 | discard: true, |
| 1583 | }, |
| 1584 | ), |
| 1585 | ), |
| 1586 | Effect.ignore, |
| 1587 | ), |
| 1588 | ); |
| 1589 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 1590 | const sourceControlDiscovery = yield* SourceControlDiscovery.SourceControlDiscovery; |
| 1591 | const secretCheck = yield* SecretCheck.SecretCheck; |
| 1592 | const otlpEndpointCheck = yield* OtlpEndpointCheck.OtlpEndpointCheck; |
| 1593 | const textGenerators = yield* TextGenerators.TextGenerators; |
| 1594 | const sourceControlRepositories = |
| 1595 | yield* SourceControlRepositoryService.SourceControlRepositoryService; |
| 1596 | const sourceControlSignIn = yield* SourceControlSignIn.SourceControlSignIn; |
| 1597 | const withPullRequestViewer = pullRequests.withRoutingCredential; |
| 1598 | // The panel's reads for a pull request the user opened go out during a rate-limit pause. |
| 1599 | const openedPullRequestRead = Effect.provideService(SourceControlRateLimit.Interactive, true); |
| 1600 | const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore; |
| 1601 | const sessions = yield* SessionStore.SessionStore; |
| 1602 | const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics; |
| 1603 | const triage = yield* TriageService.TriageService; |
| 1604 | const hostResources = yield* HostResources.HostResources; |
| 1605 | const processResourceMonitor = yield* ProcessResourceMonitor.ProcessResourceMonitor; |
| 1606 | const resourceTelemetry = yield* ResourceTelemetry.ResourceTelemetry; |
| 1607 | const relayClient = yield* RelayClient.RelayClient; |
| 1608 | // Webhook URLs start agents; expose them only to operate-scoped sessions while keeping tasks readable. |
| 1609 | const withVisibleWebhookUrls = (result: ScheduledTaskListResult): ScheduledTaskListResult => |
| 1610 | currentSession.scopes.includes(AuthOrchestrationOperateScope) |
| 1611 | ? result |
| 1612 | : { |
| 1613 | ...result, |
| 1614 | tasks: result.tasks.map(({ webhook: _webhook, ...task }) => task), |
| 1615 | }; |
| 1616 | const authorizeEffect = <A, E, R>( |
| 1617 | requiredScope: AuthEnvironmentScope, |
| 1618 | effect: Effect.Effect<A, E, R>, |
| 1619 | ): Effect.Effect<A, E | EnvironmentAuthorizationError, R> => |
| 1620 | currentSession.scopes.includes(requiredScope) |
| 1621 | ? effect |
| 1622 | : Effect.fail(rpcAuthorizationError(requiredScope)); |
| 1623 | |
| 1624 | const listAcpRegistrySessions = Effect.fn("ws.acpRegistry.listSessions")(function* ( |
| 1625 | input: AcpRegistryListSessionsInput, |
| 1626 | ) { |
| 1627 | const project = yield* acpRegistrySessions.project(input.projectId); |
| 1628 | const { instance, manager } = yield* acpRegistrySessions.sessionManager(input.instanceId); |
| 1629 | const listed = yield* manager.listSessions({ |
| 1630 | cwd: project.workspaceRoot, |
| 1631 | ...(input.cursor === undefined ? {} : { cursor: input.cursor }), |
| 1632 | }); |
| 1633 | const sessions = yield* Effect.forEach( |
| 1634 | listed.sessions, |
| 1635 | (session) => { |
| 1636 | const idInput = { |
| 1637 | driver: instance.driverKind, |
| 1638 | instanceId: input.instanceId, |
| 1639 | sessionId: session.sessionId, |
| 1640 | }; |
| 1641 | return acpRegistrySessions.findOwner(idInput).pipe( |
| 1642 | Effect.flatMap((owner) => { |
| 1643 | const threadId = owner ?? AcpRegistrySessions.importedThreadId(idInput); |
| 1644 | return threadManagement.getThreadShell(threadId).pipe( |
| 1645 | Effect.map((thread) => ({ |
| 1646 | ...session, |
| 1647 | importedThreadId: thread === null ? null : threadId, |
| 1648 | ...(thread !== null && |
| 1649 | AgentSessionImporter.isNativeHistoryPending({ |
| 1650 | historyOrigin: thread.historyOrigin, |
| 1651 | hasRun: thread.latestRunId !== null, |
| 1652 | }) |
| 1653 | ? { nativeHistoryPending: true } |
| 1654 | : {}), |
| 1655 | })), |
| 1656 | Effect.mapError( |
| 1657 | (cause) => |
| 1658 | new AcpRegistryOperationError({ |
| 1659 | reason: "session_import_failed", |
| 1660 | message: "Could not inspect existing imported ACP sessions.", |
| 1661 | cause, |
| 1662 | }), |
| 1663 | ), |
| 1664 | ); |
| 1665 | }), |
| 1666 | ); |
| 1667 | }, |
| 1668 | { concurrency: 16 }, |
| 1669 | ); |
| 1670 | return { ...listed, sessions }; |
| 1671 | }); |
| 1672 | |
| 1673 | const deleteAcpRegistrySession = Effect.fn("ws.acpRegistry.deleteSession")(function* ( |
| 1674 | input: AcpRegistryDeleteSessionInput, |
| 1675 | ) { |
| 1676 | return yield* acpRegistryRuntimeCoordinator.withSessionMutation( |
| 1677 | Effect.gen(function* () { |
| 1678 | const project = yield* acpRegistrySessions.project(input.projectId); |
| 1679 | const { instance, manager } = yield* acpRegistrySessions.sessionManager( |
| 1680 | input.instanceId, |
| 1681 | ); |
| 1682 | const snapshot = yield* instance.snapshot.getSnapshot; |
| 1683 | if (snapshot.nativeSessions?.canDelete !== true) { |
| 1684 | return yield* new AcpRegistryOperationError({ |
| 1685 | reason: "session_delete_unsupported", |
| 1686 | message: "The ACP agent does not advertise session deletion.", |
| 1687 | }); |
| 1688 | } |
| 1689 | const idInput = { |
| 1690 | driver: instance.driverKind, |
| 1691 | instanceId: input.instanceId, |
| 1692 | sessionId: input.sessionId, |
| 1693 | }; |
| 1694 | const threadId = |
| 1695 | (yield* acpRegistrySessions.findOwner(idInput)) ?? |
| 1696 | AcpRegistrySessions.importedThreadId(idInput); |
| 1697 | const importedThread = yield* threadManagement.getThreadShell(threadId).pipe( |
| 1698 | Effect.mapError( |
| 1699 | (cause) => |
| 1700 | new AcpRegistryOperationError({ |
| 1701 | reason: "session_delete_failed", |
| 1702 | message: "Could not inspect the imported ACP session mapping.", |
| 1703 | cause, |
| 1704 | }), |
| 1705 | ), |
| 1706 | ); |
| 1707 | if (importedThread !== null) { |
| 1708 | return yield* new AcpRegistryOperationError({ |
| 1709 | reason: "session_delete_failed", |
| 1710 | message: "Delete the imported T3 thread before deleting its native ACP session.", |
| 1711 | }); |
| 1712 | } |
| 1713 | yield* manager.deleteSession({ |
| 1714 | cwd: project.workspaceRoot, |
| 1715 | sessionId: input.sessionId, |
| 1716 | }); |
| 1717 | return { deleted: true } as const; |
| 1718 | }), |
| 1719 | ); |
| 1720 | }); |
| 1721 | |
| 1722 | const listAcpRegistryProviders = Effect.fn("ws.acpRegistry.listProviders")(function* ( |
| 1723 | input: AcpRegistryListProvidersInput, |
| 1724 | ) { |
| 1725 | const project = yield* acpRegistrySessions.project(input.projectId); |
| 1726 | const { instance, manager } = yield* acpRegistrySessions.sessionManager(input.instanceId); |
| 1727 | const snapshot = yield* instance.snapshot.getSnapshot; |
| 1728 | if (snapshot.configurableProviders !== true) { |
| 1729 | return yield* new AcpRegistryOperationError({ |
| 1730 | reason: "providers_unsupported", |
| 1731 | message: "The ACP agent does not advertise provider configuration.", |
| 1732 | }); |
| 1733 | } |
| 1734 | return yield* manager.listProviders(project.workspaceRoot); |
| 1735 | }); |
| 1736 | |
| 1737 | const setAcpRegistryProvider = Effect.fn("ws.acpRegistry.setProvider")(function* ( |
| 1738 | input: AcpRegistrySetProviderInput, |
| 1739 | ) { |
| 1740 | const project = yield* acpRegistrySessions.project(input.projectId); |
| 1741 | const { manager } = yield* acpRegistrySessions.sessionManager(input.instanceId); |
| 1742 | if (input.headers !== undefined && Object.keys(input.headers).length > 32) { |
| 1743 | return yield* new AcpRegistryOperationError({ |
| 1744 | reason: "provider_configuration_failed", |
| 1745 | message: "ACP provider configuration accepts at most 32 headers.", |
| 1746 | }); |
| 1747 | } |
| 1748 | const listed = yield* manager.listProviders(project.workspaceRoot); |
| 1749 | const provider = listed.providers.find( |
| 1750 | (candidate) => candidate.providerId === input.providerId, |
| 1751 | ); |
| 1752 | if (provider === undefined || !provider.supported.includes(input.apiType)) { |
| 1753 | return yield* new AcpRegistryOperationError({ |
| 1754 | reason: "provider_configuration_failed", |
| 1755 | message: `Provider ${input.providerId} does not support ${input.apiType}.`, |
| 1756 | }); |
| 1757 | } |
| 1758 | yield* providerSessionManager.closeInstance(input.instanceId).pipe( |
| 1759 | Effect.mapError( |
| 1760 | (cause) => |
| 1761 | new AcpRegistryOperationError({ |
| 1762 | reason: "provider_configuration_failed", |
| 1763 | message: "Could not stop live sessions before updating the ACP provider.", |
| 1764 | cause, |
| 1765 | }), |
| 1766 | ), |
| 1767 | ); |
| 1768 | yield* manager.setProvider({ |
| 1769 | cwd: project.workspaceRoot, |
| 1770 | providerId: input.providerId, |
| 1771 | apiType: input.apiType, |
| 1772 | baseUrl: input.baseUrl, |
| 1773 | ...(input.headers === undefined ? {} : { headers: input.headers }), |
| 1774 | }); |
| 1775 | yield* providerRegistry.refreshInstance(input.instanceId); |
| 1776 | return { configured: true } as const; |
| 1777 | }); |
| 1778 | |
| 1779 | const disableAcpRegistryProvider = Effect.fn("ws.acpRegistry.disableProvider")(function* ( |
| 1780 | input: AcpRegistryDisableProviderInput, |
| 1781 | ) { |
| 1782 | const project = yield* acpRegistrySessions.project(input.projectId); |
| 1783 | const { manager } = yield* acpRegistrySessions.sessionManager(input.instanceId); |
| 1784 | const listed = yield* manager.listProviders(project.workspaceRoot); |
| 1785 | const provider = listed.providers.find( |
| 1786 | (candidate) => candidate.providerId === input.providerId, |
| 1787 | ); |
| 1788 | if (provider === undefined || provider.required) { |
| 1789 | return yield* new AcpRegistryOperationError({ |
| 1790 | reason: "provider_configuration_failed", |
| 1791 | message: |
| 1792 | provider === undefined |
| 1793 | ? `Provider ${input.providerId} was not advertised by the ACP agent.` |
| 1794 | : `Provider ${input.providerId} is required and cannot be disabled.`, |
| 1795 | }); |
| 1796 | } |
| 1797 | yield* providerSessionManager.closeInstance(input.instanceId).pipe( |
| 1798 | Effect.mapError( |
| 1799 | (cause) => |
| 1800 | new AcpRegistryOperationError({ |
| 1801 | reason: "provider_configuration_failed", |
| 1802 | message: "Could not stop live sessions before disabling the ACP provider.", |
| 1803 | cause, |
| 1804 | }), |
| 1805 | ), |
| 1806 | ); |
| 1807 | yield* manager.disableProvider({ |
| 1808 | cwd: project.workspaceRoot, |
| 1809 | providerId: input.providerId, |
| 1810 | }); |
| 1811 | yield* providerRegistry.refreshInstance(input.instanceId); |
| 1812 | return { disabled: true } as const; |
| 1813 | }); |
| 1814 | const loadAuthAccessSnapshot = () => |
| 1815 | Effect.all({ |
| 1816 | pairingLinks: serverAuth.listPairingLinks(), |
| 1817 | clientSessions: serverAuth.listClientSessions(currentSessionId), |
| 1818 | connectDevices: serverAuth.listConnectDevices(), |
| 1819 | }).pipe( |
| 1820 | Effect.mapError( |
| 1821 | (error) => |
| 1822 | new AuthAccessStreamError({ |
| 1823 | message: error.message, |
| 1824 | }), |
| 1825 | ), |
| 1826 | ); |
| 1827 | |
| 1828 | const loadServerConfig = Effect.fn("ws.loadServerConfig")(function* (options: { |
| 1829 | readonly usageLimitsCommand: boolean; |
| 1830 | readonly workspaceSnapshotsOnDemand: boolean; |
| 1831 | readonly deferNetworkDiscovery: boolean; |
| 1832 | readonly catalogsPerCwd?: ReadonlySet<string>; |
| 1833 | readonly catalogDigests?: boolean; |
| 1834 | }) { |
| 1835 | const keybindingsConfig = yield* keybindings.loadConfigState; |
| 1836 | const currentProviders = yield* providerRegistry.getProviders; |
| 1837 | const commandProviders = options.usageLimitsCommand |
| 1838 | ? withUsageLimitsCommands(currentProviders, yield* usageLimitSources.current) |
| 1839 | : currentProviders; |
| 1840 | const providers = options.workspaceSnapshotsOnDemand |
| 1841 | ? withoutWorkspaceSnapshots( |
| 1842 | commandProviders, |
| 1843 | options.catalogsPerCwd, |
| 1844 | options.catalogDigests, |
| 1845 | ) |
| 1846 | : commandProviders; |
| 1847 | const settings = ServerSettings.redactServerSettingsForClient( |
| 1848 | yield* serverSettings.getSettings, |
| 1849 | settingsClient, |
| 1850 | ); |
| 1851 | const environment = yield* serverEnvironment.getDescriptor; |
| 1852 | const auth = yield* serverAuth.getDescriptor(); |
| 1853 | const scratchWorkspaceRoot = yield* managedFolders.scratchRoot; |
| 1854 | const lastEventLoopStall = yield* eventLoopMonitor.latestNoticeableStall; |
| 1855 | const discovery = yield* resolveOpenDiscoveryForConfig({ |
| 1856 | editors: externalLauncher.resolveAvailableEditors(), |
| 1857 | fileManagerRevealKind: externalLauncher.resolveFileManagerRevealKind(), |
| 1858 | remoteOpenTargets: options.deferNetworkDiscovery |
| 1859 | ? Effect.succeed([]) |
| 1860 | : remoteOpenTargets.resolveTargets(), |
| 1861 | directEndpoints: options.deferNetworkDiscovery |
| 1862 | ? directEndpoints.resolveAvailable() |
| 1863 | : directEndpoints.resolve(), |
| 1864 | }); |
| 1865 | |
| 1866 | return { |
| 1867 | environment, |
| 1868 | auth, |
| 1869 | cwd: config.cwd, |
| 1870 | hostname: yield* HostProcess.Hostname, |
| 1871 | keybindingsConfigPath: config.keybindingsConfigPath, |
| 1872 | keybindings: keybindingsConfig.keybindings, |
| 1873 | issues: keybindingsConfig.issues, |
| 1874 | providers, |
| 1875 | ...discovery, |
| 1876 | observability: { |
| 1877 | logsDirectoryPath: config.logsDir, |
| 1878 | localTracingEnabled: true, |
| 1879 | ...(config.otlpTracesUrl !== undefined |
| 1880 | ? { |
| 1881 | otlpTracesUrl: config.otlpTracesUrl, |
| 1882 | otlpTracesSource: config.otlpTracesSource, |
| 1883 | otlpTracesVariable: config.otlpTracesVariable, |
| 1884 | } |
| 1885 | : {}), |
| 1886 | otlpTracesEnabled: config.otlpTracesUrl !== undefined, |
| 1887 | ...(config.otlpMetricsUrl !== undefined |
| 1888 | ? { |
| 1889 | otlpMetricsUrl: config.otlpMetricsUrl, |
| 1890 | otlpMetricsSource: config.otlpMetricsSource, |
| 1891 | otlpMetricsVariable: config.otlpMetricsVariable, |
| 1892 | } |
| 1893 | : {}), |
| 1894 | otlpMetricsEnabled: config.otlpMetricsUrl !== undefined, |
| 1895 | ...(config.otlpLogsUrl !== undefined |
| 1896 | ? { |
| 1897 | otlpLogsUrl: config.otlpLogsUrl, |
| 1898 | otlpLogsSource: config.otlpLogsSource, |
| 1899 | otlpLogsVariable: config.otlpLogsVariable, |
| 1900 | } |
| 1901 | : {}), |
| 1902 | otlpLogsEnabled: config.otlpLogsUrl !== undefined, |
| 1903 | }, |
| 1904 | settings, |
| 1905 | ...(serverSettings.managedPolicy === undefined |
| 1906 | ? {} |
| 1907 | : { managedPolicy: serverSettings.managedPolicy }), |
| 1908 | shellResumeCompletionMarker: true, |
| 1909 | shellThreadFamilies: true, |
| 1910 | threadLinkMetadata: true, |
| 1911 | shellOlderSettled: true, |
| 1912 | threadResumeCompletionMarker: true, |
| 1913 | threadSnapshotPagination: true, |
| 1914 | threadFind: true, |
| 1915 | threadFindProgressive: true, |
| 1916 | secretProviderSettings: true, |
| 1917 | secretReferences: true, |
| 1918 | secretRequestReferences: true, |
| 1919 | ...Option.match(scratchWorkspaceRoot, { |
| 1920 | onNone: () => ({}), |
| 1921 | onSome: (root) => ({ scratchWorkspaceRoot: root }), |
| 1922 | }), |
| 1923 | newProjectsRoot: managedFolders.namedProjectsRoot, |
| 1924 | ...(lastEventLoopStall === undefined ? {} : { lastEventLoopStall }), |
| 1925 | serverTime: DateTime.formatIso(yield* DateTime.now), |
| 1926 | }; |
| 1927 | }); |
| 1928 | |
| 1929 | const refreshGitStatus = (cwd: string) => |
| 1930 | vcsStatusBroadcaster |
| 1931 | .refreshStatus(cwd) |
| 1932 | .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid); |
| 1933 | |
| 1934 | const getOrchestrationV2ArchivedShellSnapshot = Effect.gen(function* () { |
| 1935 | const { threads, projects, snapshotSequence } = yield* loadShellSnapshotParts({ |
| 1936 | sql, |
| 1937 | readThreads: threadManagement.readShellSnapshot({ location: "archive" }), |
| 1938 | listProjects: projectStore.listShells(), |
| 1939 | latestSequence: applicationEvents.latestApplicationSequence, |
| 1940 | }); |
| 1941 | return { |
| 1942 | schemaVersion: threads.schemaVersion, |
| 1943 | snapshotSequence, |
| 1944 | projects, |
| 1945 | threads: threads.archivedThreads, |
| 1946 | } as const; |
| 1947 | }).pipe( |
| 1948 | Effect.flatMap((snapshot) => |
| 1949 | enrichProjectShells(snapshot.projects).pipe( |
| 1950 | Effect.map(({ projects }) => ({ ...snapshot, projects })), |
| 1951 | ), |
| 1952 | ), |
| 1953 | Effect.mapError( |
| 1954 | (cause) => |
| 1955 | new OrchestrationV2GetShellSnapshotError({ |
| 1956 | message: "Failed to load archived thread snapshot", |
| 1957 | cause, |
| 1958 | }), |
| 1959 | ), |
| 1960 | ); |
| 1961 | |
| 1962 | // Rows the shell can omit, read with the same snapshot sequence the shell uses. |
| 1963 | const readOmittableShellRows = Effect.fn("ws.orchestrationV2.readOmittableShellRows")( |
| 1964 | function* ( |
| 1965 | options: { readonly familyOf: ThreadId } | { readonly worktreePath: string }, |
| 1966 | message: string, |
| 1967 | ) { |
| 1968 | const { threads, snapshotSequence } = yield* loadShellSnapshotParts({ |
| 1969 | sql, |
| 1970 | readThreads: threadManagement.readShellSnapshot({ location: "active", ...options }), |
| 1971 | listProjects: Effect.succeed([]), |
| 1972 | latestSequence: applicationEvents.latestApplicationSequence, |
| 1973 | }).pipe( |
| 1974 | Effect.mapError( |
| 1975 | (cause) => new OrchestrationV2GetShellSnapshotError({ message, cause }), |
| 1976 | ), |
| 1977 | ); |
| 1978 | return { snapshotSequence, threads: threads.threads }; |
| 1979 | }, |
| 1980 | ); |
| 1981 | |
| 1982 | const mutateProject = Effect.fn("ws.projects.mutate")(function* (mutation: ProjectMutation) { |
| 1983 | return yield* mutateProjectWithClone(projectService, projectCloneTracker, mutation); |
| 1984 | }); |
| 1985 | |
| 1986 | const handlers = ServerWsRpcGroup.of({ |
| 1987 | [WS_METHODS.issuesList]: (input) => issues.list(input), |
| 1988 | [WS_METHODS.issuesDetail]: (input) => issues.detail(input), |
| 1989 | [WS_METHODS.issuesComments]: (input) => issues.comments(input), |
| 1990 | [WS_METHODS.issuesTemplates]: (input) => issues.templates(input), |
| 1991 | [WS_METHODS.issuesCandidates]: (input) => issues.candidates(input), |
| 1992 | [WS_METHODS.issuesLinkedThreads]: (input) => threadIssues.linkedThreads(input), |
| 1993 | [WS_METHODS.issuesCreate]: (input) => issues.create(input), |
| 1994 | [WS_METHODS.issuesComment]: (input) => issues.comment(input), |
| 1995 | [WS_METHODS.issuesUpdate]: (input) => issues.update(input), |
| 1996 | [WS_METHODS.issuesSetState]: (input) => issues.setState(input), |
| 1997 | [WS_METHODS.issuesReact]: (input) => issues.react(input), |
| 1998 | [WS_METHODS.issueTrackersList]: () => issueTrackers.list, |
| 1999 | [WS_METHODS.issueTrackersConnect]: (input) => issueTrackers.connect(input), |
| 2000 | [WS_METHODS.issueTrackersBindProject]: (input) => issueTrackers.bindProject(input), |
| 2001 | [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command) => |
| 2002 | Effect.annotateCurrentSpan({ |
| 2003 | "orchestration_v2.command_id": command.commandId, |
| 2004 | "orchestration_v2.command_type": command.type, |
| 2005 | "orchestration_v2.thread_id": |
| 2006 | command.type === "thread.fork" || command.type === "thread.merge_back" |
| 2007 | ? command.targetThreadId |
| 2008 | : command.type === "delegated_task.request" || |
| 2009 | command.type === "delegated_task.wake-policy" || |
| 2010 | command.type === "delegated_task.completion-delivery.acknowledge" || |
| 2011 | command.type === "delegated_task.completion-delivery.dispose" || |
| 2012 | command.type === "thread.created.record" |
| 2013 | ? command.parentThreadId |
| 2014 | : command.threadId, |
| 2015 | ...(command.type === "thread.fork" || command.type === "thread.merge_back" |
| 2016 | ? { "orchestration_v2.source_thread_id": command.sourceThreadId } |
| 2017 | : {}), |
| 2018 | }).pipe( |
| 2019 | Effect.andThen( |
| 2020 | startup |
| 2021 | .enqueueCommand( |
| 2022 | (command.type === "prepared-run.retry" |
| 2023 | ? threadLaunch.retryPreparation(command) |
| 2024 | : ThreadMessageIntake.dispatchCommand( |
| 2025 | ThreadManagementService.withCreationProvenance(command, { |
| 2026 | createdBy: "user", |
| 2027 | creationSource: |
| 2028 | "creationSource" in command ? command.creationSource : "web", |
| 2029 | }), |
| 2030 | { |
| 2031 | managesProviders: |
| 2032 | currentSession.scopes.includes(AuthProvidersManageScope), |
| 2033 | }, |
| 2034 | ) |
| 2035 | ).pipe(Effect.provide(intakeContext)), |
| 2036 | ) |
| 2037 | .pipe( |
| 2038 | Effect.tap((result) => |
| 2039 | result.replayed ? Effect.void : recordClientCommandAnalytics(command), |
| 2040 | ), |
| 2041 | Effect.map((result) => ({ sequence: result.sequence })), |
| 2042 | Effect.mapError((cause) => { |
| 2043 | if (cause._tag === "EnvironmentAuthorizationError") return cause; |
| 2044 | const detail = userFacingDispatchErrorMessage(cause); |
| 2045 | return new OrchestrationV2DispatchCommandError({ |
| 2046 | commandId: command.commandId, |
| 2047 | commandType: command.type, |
| 2048 | message: detail ?? "Failed to dispatch orchestration V2 command", |
| 2049 | ...(detail === undefined ? {} : { detail }), |
| 2050 | cause, |
| 2051 | }); |
| 2052 | }), |
| 2053 | ), |
| 2054 | ), |
| 2055 | ), |
| 2056 | [ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: (input) => threadManagement.stopWorkflow(input), |
| 2057 | [ORCHESTRATION_V2_WS_METHODS.forceStopThread]: (input) => |
| 2058 | threadManagement.forceStopThread(input), |
| 2059 | [ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: (input) => |
| 2060 | readWorkflowScript({ scriptPath: input.scriptPath }), |
| 2061 | [ORCHESTRATION_V2_WS_METHODS.getNativeChildWork]: (input) => |
| 2062 | nativeChildWork.getNativeChildWork(input), |
| 2063 | [ORCHESTRATION_V2_WS_METHODS.getTurnItem]: (input) => |
| 2064 | threadManagement.getTurnItem(input).pipe( |
| 2065 | Effect.mapError( |
| 2066 | (cause) => |
| 2067 | new OrchestrationV2GetThreadProjectionError({ |
| 2068 | threadId: input.threadId, |
| 2069 | message: "Failed to load turn item", |
| 2070 | cause, |
| 2071 | }), |
| 2072 | ), |
| 2073 | ), |
| 2074 | [ORCHESTRATION_V2_WS_METHODS.getTurnDiff]: (input) => |
| 2075 | checkpointDiffQuery.getTurnDiff(input).pipe( |
| 2076 | Effect.mapError( |
| 2077 | (cause) => |
| 2078 | new OrchestrationGetTurnDiffError({ |
| 2079 | message: "Failed to load turn diff", |
| 2080 | cause, |
| 2081 | }), |
| 2082 | ), |
| 2083 | ), |
| 2084 | [ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff]: (input) => |
| 2085 | checkpointDiffQuery.getFullThreadDiff(input).pipe( |
| 2086 | Effect.mapError( |
| 2087 | (cause) => |
| 2088 | new OrchestrationGetFullThreadDiffError({ |
| 2089 | message: "Failed to load full thread diff", |
| 2090 | cause, |
| 2091 | }), |
| 2092 | ), |
| 2093 | ), |
| 2094 | [ORCHESTRATION_V2_WS_METHODS.searchThread]: (input) => |
| 2095 | threadManagement |
| 2096 | .searchThread(input) |
| 2097 | .pipe(Effect.mapError((cause) => new OrchestrationV2SearchThreadError({ cause }))), |
| 2098 | [ORCHESTRATION_V2_WS_METHODS.searchThreadStream]: (input) => |
| 2099 | threadManagement |
| 2100 | .searchThreadStream(input) |
| 2101 | .pipe(Stream.mapError((cause) => new OrchestrationV2SearchThreadError({ cause }))), |
| 2102 | [ORCHESTRATION_V2_WS_METHODS.searchThreads]: (input) => |
| 2103 | ThreadSearch.searchThreadsWithOlderSettledRows({ |
| 2104 | request: input, |
| 2105 | search: threadSearch.search, |
| 2106 | searchOlderSettled: threadSearch.searchOlderSettled, |
| 2107 | sql, |
| 2108 | readThreads: (threadIds) => |
| 2109 | threadManagement.readShellSnapshot({ location: "active", threadIds }), |
| 2110 | latestSequence: applicationEvents.latestApplicationSequence, |
| 2111 | }).pipe( |
| 2112 | Effect.mapError( |
| 2113 | (cause) => |
| 2114 | new OrchestrationSearchThreadsError({ |
| 2115 | message: "Failed to search threads", |
| 2116 | cause, |
| 2117 | }), |
| 2118 | ), |
| 2119 | ), |
| 2120 | [ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: (_input) => |
| 2121 | getOrchestrationV2ArchivedShellSnapshot, |
| 2122 | [ORCHESTRATION_V2_WS_METHODS.getThreadFamily]: (input) => |
| 2123 | readOmittableShellRows({ familyOf: input.threadId }, "Failed to load the thread family"), |
| 2124 | [ORCHESTRATION_V2_WS_METHODS.getThreadLinkMetadata]: (input) => |
| 2125 | threadManagement.getThreadLinkMetadata(input.threadIds).pipe( |
| 2126 | Effect.mapError( |
| 2127 | (cause) => |
| 2128 | new OrchestrationV2GetShellSnapshotError({ |
| 2129 | message: "Failed to load thread link metadata", |
| 2130 | cause, |
| 2131 | }), |
| 2132 | ), |
| 2133 | ), |
| 2134 | [ORCHESTRATION_V2_WS_METHODS.getThreadTitles]: (input) => |
| 2135 | threadManagement.getThreadTitles(input.threadIds).pipe( |
| 2136 | Effect.mapError( |
| 2137 | (cause) => |
| 2138 | new OrchestrationV2GetShellSnapshotError({ |
| 2139 | message: "Failed to load thread titles", |
| 2140 | cause, |
| 2141 | }), |
| 2142 | ), |
| 2143 | ), |
| 2144 | [ORCHESTRATION_V2_WS_METHODS.getOlderSettledThreads]: (input) => |
| 2145 | loadOlderSettledThreadsPage({ |
| 2146 | sql, |
| 2147 | listThreads: threadManagement.listOlderSettledThreads(input), |
| 2148 | readThreads: (threadIds) => |
| 2149 | threadManagement.readShellSnapshot({ location: "active", threadIds }), |
| 2150 | latestSequence: applicationEvents.latestApplicationSequence, |
| 2151 | }).pipe( |
| 2152 | Effect.mapError( |
| 2153 | (cause) => |
| 2154 | new OrchestrationV2GetShellSnapshotError({ |
| 2155 | message: "Failed to load older settled threads", |
| 2156 | cause, |
| 2157 | }), |
| 2158 | ), |
| 2159 | ), |
| 2160 | [ORCHESTRATION_V2_WS_METHODS.getWorktreeThreadIds]: (input) => |
| 2161 | readOmittableShellRows( |
| 2162 | { worktreePath: input.worktreePath }, |
| 2163 | "Failed to load the worktree's threads", |
| 2164 | ).pipe(Effect.map(({ threads }) => ({ threadIds: threads.map((thread) => thread.id) }))), |
| 2165 | [ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: (input) => |
| 2166 | Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( |
| 2167 | Effect.andThen( |
| 2168 | // Bound compatibility snapshots so pre-pagination clients cannot materialize unlimited transcripts. |
| 2169 | threadManagement |
| 2170 | .getThreadSnapshotWindow(input.threadId, { |
| 2171 | rowLimit: THREAD_HISTORY_SNAPSHOT_ROW_LIMIT, |
| 2172 | }) |
| 2173 | .pipe( |
| 2174 | Effect.map( |
| 2175 | (snapshot) => |
| 2176 | buildBoundedThreadProjection({ |
| 2177 | projection: projectThreadProjectionForWire(snapshot.projection), |
| 2178 | snapshotSequence: snapshot.snapshotSequence, |
| 2179 | }).projection, |
| 2180 | ), |
| 2181 | Effect.mapError( |
| 2182 | (cause) => |
| 2183 | new OrchestrationV2GetThreadProjectionError({ |
| 2184 | threadId: input.threadId, |
| 2185 | message: `Failed to load orchestration V2 thread ${input.threadId}`, |
| 2186 | cause, |
| 2187 | }), |
| 2188 | ), |
| 2189 | ), |
| 2190 | ), |
| 2191 | ), |
| 2192 | [ORCHESTRATION_V2_WS_METHODS.launchThread]: (input) => |
| 2193 | Effect.annotateCurrentSpan({ |
| 2194 | "orchestration_v2.command_id": input.commandId, |
| 2195 | "orchestration_v2.project_id": input.projectId, |
| 2196 | }).pipe( |
| 2197 | Effect.andThen( |
| 2198 | startup |
| 2199 | .enqueueCommand( |
| 2200 | threadLaunch |
| 2201 | .checkWorktreeBase({ |
| 2202 | commandId: input.commandId, |
| 2203 | projectId: input.projectId, |
| 2204 | workspaceStrategy: input.workspaceStrategy, |
| 2205 | }) |
| 2206 | .pipe( |
| 2207 | Effect.andThen( |
| 2208 | ThreadMessageIntake.launchThread({ |
| 2209 | commandId: input.commandId, |
| 2210 | ...(input.threadId === undefined ? {} : { threadId: input.threadId }), |
| 2211 | ...(input.reuseExistingThread === undefined |
| 2212 | ? {} |
| 2213 | : { reuseExistingThread: input.reuseExistingThread }), |
| 2214 | projectId: input.projectId, |
| 2215 | title: input.title, |
| 2216 | ...(input.generateTitle === undefined |
| 2217 | ? {} |
| 2218 | : { generateTitle: input.generateTitle }), |
| 2219 | modelSelection: input.modelSelection, |
| 2220 | runtimeMode: input.runtimeMode, |
| 2221 | interactionMode: input.interactionMode, |
| 2222 | workspaceStrategy: input.workspaceStrategy, |
| 2223 | ...(input.initialMessage === undefined |
| 2224 | ? {} |
| 2225 | : { |
| 2226 | initialMessage: { |
| 2227 | ...(input.initialMessage.messageId === undefined |
| 2228 | ? {} |
| 2229 | : { messageId: input.initialMessage.messageId }), |
| 2230 | text: input.initialMessage.text, |
| 2231 | attachments: input.initialMessage.attachments, |
| 2232 | ...(input.initialMessage.context === undefined |
| 2233 | ? {} |
| 2234 | : { context: input.initialMessage.context }), |
| 2235 | }, |
| 2236 | }), |
| 2237 | createdBy: "user", |
| 2238 | creationSource: input.creationSource ?? "web", |
| 2239 | }), |
| 2240 | ), |
| 2241 | Effect.provide(intakeContext), |
| 2242 | ), |
| 2243 | ) |
| 2244 | .pipe( |
| 2245 | // A resumed launch is a retry of one already counted. |
| 2246 | Effect.tap((result) => |
| 2247 | result.resumed |
| 2248 | ? Effect.void |
| 2249 | : analytics |
| 2250 | .record("client.thread.started", { |
| 2251 | ...originProps, |
| 2252 | workspaceStrategy: input.workspaceStrategy.type, |
| 2253 | }) |
| 2254 | .pipe( |
| 2255 | Effect.andThen( |
| 2256 | input.initialMessage === undefined |
| 2257 | ? Effect.void |
| 2258 | : analytics.record("client.turn.requested", originProps), |
| 2259 | ), |
| 2260 | Effect.ignore, |
| 2261 | ), |
| 2262 | ), |
| 2263 | Effect.map((result) => ({ |
| 2264 | ...result, |
| 2265 | projection: projectThreadProjectionForWire(result.projection), |
| 2266 | })), |
| 2267 | Effect.catchTags({ |
| 2268 | AttachmentClaimError: (cause) => |
| 2269 | new OrchestrationV2ThreadLaunchError({ |
| 2270 | commandId: input.commandId, |
| 2271 | projectId: input.projectId, |
| 2272 | message: cause.message, |
| 2273 | cause, |
| 2274 | }), |
| 2275 | ThreadLaunchError: (cause) => |
| 2276 | new OrchestrationV2ThreadLaunchError({ |
| 2277 | commandId: input.commandId, |
| 2278 | projectId: input.projectId, |
| 2279 | message: "Failed to launch thread", |
| 2280 | cause, |
| 2281 | }), |
| 2282 | ServerRuntimeStartupError: (cause) => |
| 2283 | new OrchestrationV2ThreadLaunchError({ |
| 2284 | commandId: input.commandId, |
| 2285 | projectId: input.projectId, |
| 2286 | message: "Failed to launch thread", |
| 2287 | cause, |
| 2288 | }), |
| 2289 | ThreadManagementProviderInstanceDisabledError: (cause) => |
| 2290 | new OrchestrationV2ThreadLaunchError({ |
| 2291 | commandId: input.commandId, |
| 2292 | projectId: input.projectId, |
| 2293 | message: cause.message, |
| 2294 | cause, |
| 2295 | }), |
| 2296 | ThreadLaunchBaseRefError: (cause) => |
| 2297 | new OrchestrationV2ThreadLaunchError({ |
| 2298 | commandId: input.commandId, |
| 2299 | projectId: input.projectId, |
| 2300 | message: cause.message, |
| 2301 | cause, |
| 2302 | }), |
| 2303 | ThreadLaunchBranchExistsError: (cause) => |
| 2304 | new OrchestrationV2ThreadLaunchError({ |
| 2305 | commandId: input.commandId, |
| 2306 | projectId: input.projectId, |
| 2307 | message: cause.message, |
| 2308 | cause, |
| 2309 | }), |
| 2310 | ThreadLaunchBranchConflictError: (cause) => |
| 2311 | new OrchestrationV2ThreadLaunchError({ |
| 2312 | commandId: input.commandId, |
| 2313 | projectId: input.projectId, |
| 2314 | message: cause.message, |
| 2315 | cause, |
| 2316 | }), |
| 2317 | ThreadLaunchNotRepositoryError: (cause) => |
| 2318 | new OrchestrationV2ThreadLaunchError({ |
| 2319 | commandId: input.commandId, |
| 2320 | projectId: input.projectId, |
| 2321 | message: cause.message, |
| 2322 | cause, |
| 2323 | }), |
| 2324 | }), |
| 2325 | ), |
| 2326 | ), |
| 2327 | ), |
| 2328 | [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (input) => |
| 2329 | Stream.unwrap(subscribeOrchestrationV2Shell(input)), |
| 2330 | [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: (input) => |
| 2331 | Stream.unwrap( |
| 2332 | Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( |
| 2333 | Effect.andThen(threadViewers.view(input.threadId)), |
| 2334 | Effect.andThen(subscribeOrchestrationV2Thread(input)), |
| 2335 | ), |
| 2336 | ), |
| 2337 | [ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput]: (input) => |
| 2338 | Stream.unwrap( |
| 2339 | Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( |
| 2340 | Effect.as(commandOutputHub.subscribe(input)), |
| 2341 | ), |
| 2342 | ), |
| 2343 | [ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion]: (input) => |
| 2344 | providerSessionManager.subscribePromptSuggestion(input.threadId), |
| 2345 | [WS_METHODS.scheduledTasksSubscribe]: (_input) => |
| 2346 | scheduledTasks.subscribeList().pipe(Stream.map(withVisibleWebhookUrls)), |
| 2347 | [WS_METHODS.scheduledTasksUpsert]: (input) => scheduledTasks.upsert(input), |
| 2348 | [WS_METHODS.scheduledTasksSetEnabled]: (input) => |
| 2349 | Effect.annotateCurrentSpan({ "scheduled_task.id": input.id }).pipe( |
| 2350 | Effect.andThen(scheduledTasks.setEnabled(input)), |
| 2351 | ), |
| 2352 | [WS_METHODS.scheduledTasksDelete]: (input) => |
| 2353 | Effect.annotateCurrentSpan({ "scheduled_task.id": input.id }).pipe( |
| 2354 | Effect.andThen(scheduledTasks.delete(input)), |
| 2355 | ), |
| 2356 | [WS_METHODS.scheduledTasksRunNow]: (input) => |
| 2357 | Effect.annotateCurrentSpan({ "scheduled_task.id": input.id }).pipe( |
| 2358 | Effect.andThen(scheduledTasks.runNow(input)), |
| 2359 | ), |
| 2360 | [WS_METHODS.scheduledTasksRotateWebhookToken]: (input) => |
| 2361 | Effect.annotateCurrentSpan({ "scheduled_task.id": input.id }).pipe( |
| 2362 | Effect.andThen(scheduledTasks.rotateWebhookToken(input)), |
| 2363 | ), |
| 2364 | [WS_METHODS.guestShareCreate]: (input) => |
| 2365 | Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( |
| 2366 | Effect.andThen(guestShares.create(input)), |
| 2367 | ), |
| 2368 | [WS_METHODS.secretsAnswerRequest]: (input) => |
| 2369 | Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( |
| 2370 | Effect.andThen(secretRequests.answer(input)), |
| 2371 | ), |
| 2372 | [WS_METHODS.scheduledTasksListWebhookDeliveries]: (input) => |
| 2373 | Effect.annotateCurrentSpan({ "scheduled_task.id": input.id }).pipe( |
| 2374 | Effect.andThen(scheduledTasks.listWebhookDeliveries(input)), |
| 2375 | ), |
| 2376 | [WS_METHODS.scheduledTasksGetWebhookDelivery]: (input) => |
| 2377 | Effect.annotateCurrentSpan({ "scheduled_task.id": input.id }).pipe( |
| 2378 | Effect.andThen(scheduledTasks.getWebhookDelivery(input)), |
| 2379 | ), |
| 2380 | [WS_METHODS.serverProbe]: (_input) => Effect.succeed({}), |
| 2381 | [WS_METHODS.serverGetConfig]: (_input) => |
| 2382 | loadServerConfig({ |
| 2383 | usageLimitsCommand: false, |
| 2384 | workspaceSnapshotsOnDemand: false, |
| 2385 | deferNetworkDiscovery: false, |
| 2386 | }), |
| 2387 | [WS_METHODS.serverSearchAcpRegistry]: (input) => |
| 2388 | acpRegistryCatalog |
| 2389 | .search(input) |
| 2390 | .pipe(Effect.mapError(AcpRegistrySupport.toAcpRegistryOperationError)), |
| 2391 | [WS_METHODS.serverPrepareAcpRegistryAgent]: (input) => |
| 2392 | Effect.annotateCurrentSpan({ "acp_registry.agent_id": input.agentId }).pipe( |
| 2393 | Effect.andThen( |
| 2394 | acpRegistryCatalog |
| 2395 | .prepare(input) |
| 2396 | .pipe(Effect.mapError(AcpRegistrySupport.toAcpRegistryOperationError)), |
| 2397 | ), |
| 2398 | ), |
| 2399 | [WS_METHODS.serverUninstallAcpRegistryManagedBinary]: (input) => |
| 2400 | Effect.annotateCurrentSpan({ "acp_registry.agent_id": input.agentId }).pipe( |
| 2401 | Effect.andThen( |
| 2402 | acpRegistryCatalog |
| 2403 | .uninstallManagedBinary(input) |
| 2404 | .pipe(Effect.mapError(AcpRegistrySupport.toAcpRegistryOperationError)), |
| 2405 | ), |
| 2406 | ), |
| 2407 | [WS_METHODS.serverAcceptAcpRegistryUrlAuth]: (input) => |
| 2408 | Effect.annotateCurrentSpan({ "provider.instance_id": input.instanceId }).pipe( |
| 2409 | Effect.andThen( |
| 2410 | acpRegistryRuntimeCoordinator |
| 2411 | .acceptUrlAuthentication(input) |
| 2412 | .pipe(Effect.map((accepted) => ({ accepted }))), |
| 2413 | ), |
| 2414 | ), |
| 2415 | [WS_METHODS.serverListAcpRegistrySessions]: (input) => |
| 2416 | Effect.annotateCurrentSpan({ |
| 2417 | "provider.instance_id": input.instanceId, |
| 2418 | "project.id": input.projectId, |
| 2419 | }).pipe(Effect.andThen(listAcpRegistrySessions(input))), |
| 2420 | [WS_METHODS.serverImportAcpRegistrySession]: (input) => |
| 2421 | Effect.annotateCurrentSpan({ |
| 2422 | "provider.instance_id": input.instanceId, |
| 2423 | "project.id": input.projectId, |
| 2424 | }).pipe(Effect.andThen(acpRegistrySessions.importSession(input))), |
| 2425 | [WS_METHODS.serverDeleteAcpRegistrySession]: (input) => |
| 2426 | Effect.annotateCurrentSpan({ |
| 2427 | "provider.instance_id": input.instanceId, |
| 2428 | "project.id": input.projectId, |
| 2429 | }).pipe(Effect.andThen(deleteAcpRegistrySession(input))), |
| 2430 | [WS_METHODS.serverListAcpRegistryProviders]: (input) => |
| 2431 | Effect.annotateCurrentSpan({ |
| 2432 | "provider.instance_id": input.instanceId, |
| 2433 | "project.id": input.projectId, |
| 2434 | }).pipe(Effect.andThen(listAcpRegistryProviders(input))), |
| 2435 | [WS_METHODS.serverSetAcpRegistryProvider]: (input) => |
| 2436 | Effect.annotateCurrentSpan({ |
| 2437 | "provider.instance_id": input.instanceId, |
| 2438 | "project.id": input.projectId, |
| 2439 | }).pipe(Effect.andThen(setAcpRegistryProvider(input))), |
| 2440 | [WS_METHODS.serverDisableAcpRegistryProvider]: (input) => |
| 2441 | Effect.annotateCurrentSpan({ |
| 2442 | "provider.instance_id": input.instanceId, |
| 2443 | "project.id": input.projectId, |
| 2444 | }).pipe(Effect.andThen(disableAcpRegistryProvider(input))), |
| 2445 | [WS_METHODS.serverLogoutAcpRegistry]: (input) => |
| 2446 | Effect.annotateCurrentSpan({ "provider.instance_id": input.instanceId }).pipe( |
| 2447 | Effect.andThen( |
| 2448 | Effect.gen(function* () { |
| 2449 | const { instance, manager } = yield* acpRegistrySessions.sessionManager( |
| 2450 | input.instanceId, |
| 2451 | ); |
| 2452 | const snapshot = yield* instance.snapshot.getSnapshot; |
| 2453 | if (snapshot.auth.canLogout !== true) { |
| 2454 | return yield* new AcpRegistryOperationError({ |
| 2455 | reason: "logout_unsupported", |
| 2456 | message: "The ACP agent does not advertise logout.", |
| 2457 | }); |
| 2458 | } |
| 2459 | if (instance.auth) { |
| 2460 | yield* providerAuth.logout(input).pipe( |
| 2461 | Effect.mapError( |
| 2462 | (cause) => |
| 2463 | new AcpRegistryOperationError({ |
| 2464 | reason: "logout_failed", |
| 2465 | message: "Could not sign out of the ACP agent.", |
| 2466 | cause, |
| 2467 | }), |
| 2468 | ), |
| 2469 | ); |
| 2470 | } else { |
| 2471 | yield* providerSessionManager.closeInstance(input.instanceId).pipe( |
| 2472 | Effect.mapError( |
| 2473 | (cause) => |
| 2474 | new AcpRegistryOperationError({ |
| 2475 | reason: "logout_failed", |
| 2476 | message: "Could not stop live sessions before ACP logout.", |
| 2477 | cause, |
| 2478 | }), |
| 2479 | ), |
| 2480 | ); |
| 2481 | yield* manager.logout(config.cwd); |
| 2482 | } |
| 2483 | yield* providerRegistry.refreshInstance(input.instanceId); |
| 2484 | return { loggedOut: true } as const; |
| 2485 | }), |
| 2486 | ), |
| 2487 | ), |
| 2488 | [WS_METHODS.serverRefreshProviders]: |
| 2489 | /* Request instrumentation already owns the span; keep this helper in that context. */ |
| 2490 | Effect.fnUntraced(function* (input) { |
| 2491 | if (input.modelCatalogOnly === true) { |
| 2492 | yield* providerRegistry.refreshModelCatalog; |
| 2493 | return { providers: [] }; |
| 2494 | } |
| 2495 | if (input.refreshModels) { |
| 2496 | yield* providerRegistry.invalidateModelCaches({ |
| 2497 | instanceId: input.instanceId, |
| 2498 | cwd: input.cwd, |
| 2499 | fresh: input.fresh, |
| 2500 | }); |
| 2501 | } |
| 2502 | if (input.reloadSecrets === true && input.instanceId === undefined) { |
| 2503 | yield* invalidateSettingsSecrets(secretResolver, serverSettings.getSettings); |
| 2504 | } |
| 2505 | // Await refresh; RPC scope closure would interrupt a fork before the hub answered. |
| 2506 | if (input.instanceId === undefined) { |
| 2507 | yield* usageLimitSources.refresh; |
| 2508 | } |
| 2509 | let providers = yield* input.cwd !== undefined && input.instanceId !== undefined |
| 2510 | ? providerRegistry.refreshWorkspaceSnapshot({ |
| 2511 | instanceId: input.instanceId, |
| 2512 | cwd: input.cwd, |
| 2513 | scanCwd: yield* projectService.workspaceScanDirectory(input.cwd), |
| 2514 | fresh: input.fresh === true, |
| 2515 | }) |
| 2516 | : input.reloadSecrets === true |
| 2517 | ? providerRegistry.reloadSecretsAndRefresh(input.instanceId) |
| 2518 | : input.instanceId !== undefined |
| 2519 | ? providerRegistry.refreshInstance(input.instanceId) |
| 2520 | : providerRegistry.refresh(); |
| 2521 | if (input.refreshModels) { |
| 2522 | const instances = yield* providerInstances.listInstances; |
| 2523 | for (const instance of instances) { |
| 2524 | if ( |
| 2525 | !instance.refreshModels || |
| 2526 | (input.instanceId !== undefined && input.instanceId !== instance.instanceId) || |
| 2527 | !providers.some( |
| 2528 | (provider) => |
| 2529 | provider.instanceId === instance.instanceId && |
| 2530 | provider.enabled && |
| 2531 | provider.installed, |
| 2532 | ) |
| 2533 | ) |
| 2534 | continue; |
| 2535 | yield* instance.refreshModels().pipe( |
| 2536 | Effect.mapError( |
| 2537 | (error) => |
| 2538 | new ProviderSetupError({ |
| 2539 | instanceId: instance.instanceId, |
| 2540 | operation: "refresh-models", |
| 2541 | detail: error.detail, |
| 2542 | }), |
| 2543 | ), |
| 2544 | ); |
| 2545 | providers = yield* providerRegistry.refreshInstance(instance.instanceId); |
| 2546 | } |
| 2547 | } |
| 2548 | const { instanceId, cwd } = input; |
| 2549 | if (input.omitProviders === true && (instanceId === undefined || cwd === undefined)) { |
| 2550 | return { providers: [] }; |
| 2551 | } |
| 2552 | if (input.workspaceSnapshotsOnDemand !== true) return { providers }; |
| 2553 | const commandProviders = |
| 2554 | input.usageLimitsCommand === true |
| 2555 | ? withUsageLimitsCommands(providers, yield* usageLimitSources.current) |
| 2556 | : providers; |
| 2557 | if (instanceId === undefined || cwd === undefined) { |
| 2558 | return { providers: withoutWorkspaceSnapshots(commandProviders) }; |
| 2559 | } |
| 2560 | const catalogOnDemand = |
| 2561 | input.providerCatalogsOnDemand === true && |
| 2562 | (yield* providerInstances.getInstance(instanceId))?.snapshotForCwd !== undefined; |
| 2563 | return { |
| 2564 | providers: commandProviders |
| 2565 | .filter((provider) => provider.instanceId === instanceId) |
| 2566 | .map((provider) => { |
| 2567 | const catalog = |
| 2568 | catalogOnDemand && input.machineCatalog === true |
| 2569 | ? machineCatalogNames(provider) |
| 2570 | : undefined; |
| 2571 | return { |
| 2572 | ...provider, |
| 2573 | // Callers read only the cwd snapshot; the config stream carries the rest. |
| 2574 | models: [], |
| 2575 | slashCommands: catalog?.slashCommands ?? [], |
| 2576 | skills: catalog?.skills ?? [], |
| 2577 | ...(catalog === undefined |
| 2578 | ? {} |
| 2579 | : { catalogDigest: machineCatalogDigest(provider) }), |
| 2580 | workspaceSnapshots: workspaceSnapshotOrCatalog(provider, cwd, catalogOnDemand), |
| 2581 | }; |
| 2582 | }), |
| 2583 | }; |
| 2584 | }), |
| 2585 | [WS_METHODS.mcpAppsCallTool]: (input) => mcpAppRequests.callTool(input), |
| 2586 | [WS_METHODS.mcpAppsToolInfo]: (input) => mcpAppRequests.toolInfo(input), |
| 2587 | [WS_METHODS.mcpAppsUpdateModelContext]: (input) => mcpAppRequests.updateModelContext(input), |
| 2588 | [WS_METHODS.mcpAppsReadResource]: (input) => mcpAppRequests.readResource(input), |
| 2589 | [WS_METHODS.providerMcpSignInStart]: (input) => mcpSignIn.start(input), |
| 2590 | [WS_METHODS.providerMcpSignInComplete]: (input) => mcpSignIn.complete(input), |
| 2591 | [WS_METHODS.providerUploadFeedback]: |
| 2592 | /* Request instrumentation already owns the span; keep this helper in that context. */ |
| 2593 | Effect.fnUntraced( |
| 2594 | function* (input) { |
| 2595 | const projection = yield* threadManagement.getThreadRecords(input.threadId, [ |
| 2596 | "providerThreads", |
| 2597 | ]); |
| 2598 | const providerThread = |
| 2599 | projection.providerThreads.find( |
| 2600 | (candidate) => candidate.id === projection.thread.activeProviderThreadId, |
| 2601 | ) ?? projection.providerThreads.at(-1); |
| 2602 | const providerSessionId = providerThread?.providerSessionId ?? null; |
| 2603 | if (providerThread === undefined || providerSessionId === null) { |
| 2604 | return yield* new ProviderUploadFeedbackError({ |
| 2605 | threadId: input.threadId, |
| 2606 | cause: "No provider session has run in this thread yet.", |
| 2607 | }); |
| 2608 | } |
| 2609 | const runtime = Option.getOrNull(yield* providerSessionsV2.get(providerSessionId)); |
| 2610 | if (runtime === null) { |
| 2611 | return yield* new ProviderUploadFeedbackError({ |
| 2612 | threadId: input.threadId, |
| 2613 | cause: "The provider session is no longer running. Send a message first.", |
| 2614 | }); |
| 2615 | } |
| 2616 | if (runtime.uploadFeedback === undefined) { |
| 2617 | return yield* new ProviderUploadFeedbackError({ |
| 2618 | threadId: input.threadId, |
| 2619 | cause: `Provider '${runtime.driver}' does not support feedback uploads.`, |
| 2620 | }); |
| 2621 | } |
| 2622 | return yield* runtime.uploadFeedback({ |
| 2623 | providerThread, |
| 2624 | ...(input.reason === undefined ? {} : { reason: input.reason }), |
| 2625 | }); |
| 2626 | }, |
| 2627 | (effect, input) => |
| 2628 | effect.pipe( |
| 2629 | Effect.mapError((cause) => |
| 2630 | isProviderUploadFeedbackError(cause) |
| 2631 | ? cause |
| 2632 | : new ProviderUploadFeedbackError({ |
| 2633 | threadId: input.threadId, |
| 2634 | cause, |
| 2635 | }), |
| 2636 | ), |
| 2637 | ), |
| 2638 | ), |
| 2639 | [WS_METHODS.serverUpdateProvider]: (input) => |
| 2640 | providerMaintenanceRunner.updateProvider(input), |
| 2641 | [WS_METHODS.providerConsumeResetCredit]: |
| 2642 | /* Request instrumentation already owns the span; keep this helper in that context. */ |
| 2643 | Effect.fnUntraced(function* (input) { |
| 2644 | if ("sourceId" in input) return yield* usageLimitSources.consumeResetCredit(input); |
| 2645 | const instance = yield* providerInstances.getInstance(input.instanceId); |
| 2646 | if (instance === undefined || !instance.enabled) { |
| 2647 | return yield* new ProviderSetupError({ |
| 2648 | instanceId: input.instanceId, |
| 2649 | operation: "consume-reset-credit", |
| 2650 | detail: instance ? "This provider is disabled." : "Provider instance not found.", |
| 2651 | }); |
| 2652 | } |
| 2653 | if (instance.consumeResetCredit === undefined) { |
| 2654 | return yield* new ProviderSetupError({ |
| 2655 | instanceId: input.instanceId, |
| 2656 | operation: "consume-reset-credit", |
| 2657 | detail: "This provider does not bank reset credits.", |
| 2658 | }); |
| 2659 | } |
| 2660 | const outcome = yield* instance.consumeResetCredit(input.creditId).pipe( |
| 2661 | Effect.mapError( |
| 2662 | (error) => |
| 2663 | new ProviderSetupError({ |
| 2664 | instanceId: input.instanceId, |
| 2665 | operation: "consume-reset-credit", |
| 2666 | detail: error.detail, |
| 2667 | cause: error, |
| 2668 | }), |
| 2669 | ), |
| 2670 | ); |
| 2671 | return { outcome }; |
| 2672 | }), |
| 2673 | [WS_METHODS.providerAuthStart]: (input) => providerAuth.start(input, currentSessionId), |
| 2674 | [WS_METHODS.providerAuthRespond]: (input) => |
| 2675 | Effect.annotateCurrentSpan({ instanceId: input.instanceId }).pipe( |
| 2676 | Effect.andThen(providerAuth.respond(input, currentSessionId)), |
| 2677 | ), |
| 2678 | [WS_METHODS.providerAuthComplete]: (input) => |
| 2679 | providerAuth.complete(input, currentSessionId), |
| 2680 | [WS_METHODS.chatGptReconnectProfile]: (input) => providerAuth.reconnectProfile(input), |
| 2681 | [WS_METHODS.chatGptImportProfile]: (input) => providerAuth.importProfile(input), |
| 2682 | [WS_METHODS.chatGptHandoffSubscribe]: (input) => |
| 2683 | subscribeChatGptHandoff(input, currentSessionId), |
| 2684 | [WS_METHODS.providerAuthCancel]: (input) => providerAuth.cancel(input, currentSessionId), |
| 2685 | [WS_METHODS.providerAuthRemoveMethod]: (input) => providerAuth.removeMethod(input), |
| 2686 | [WS_METHODS.providerAuthLogout]: (input) => providerAuth.logout(input), |
| 2687 | [WS_METHODS.providerAuthSubscribe]: (input) => |
| 2688 | providerAuth.subscribe(input, currentSessionId), |
| 2689 | [WS_METHODS.providerInstallStart]: (input) => providerInstallation.start(input), |
| 2690 | [WS_METHODS.providerInstallCancel]: (input) => providerInstallation.cancel(input), |
| 2691 | [WS_METHODS.providerInstallSubscribe]: (input) => providerInstallation.subscribe(input), |
| 2692 | [WS_METHODS.providerInstallRemove]: (input) => providerInstallation.remove(input), |
| 2693 | [WS_METHODS.serverUpdateServer]: (input) => serverSelfUpdate.update(input), |
| 2694 | [WS_METHODS.serverGetNpmRelease]: (input) => npmRelease.get(input), |
| 2695 | [WS_METHODS.serverUpdateServerWithProgress]: (input) => |
| 2696 | ServerSelfUpdate.updateProgressStream(serverSelfUpdate, input), |
| 2697 | [WS_METHODS.serverCommitDesktopUpdate]: (input) => |
| 2698 | serverSelfUpdate.commitDesktopUpdate(input.requestId), |
| 2699 | [WS_METHODS.serverUpsertKeybinding]: |
| 2700 | /* Request instrumentation already owns the span; keep this helper in that context. */ |
| 2701 | Effect.fnUntraced(function* (rule) { |
| 2702 | return yield* keybindings.upsertKeybindingRule(rule); |
| 2703 | }), |
| 2704 | [WS_METHODS.serverRemoveKeybinding]: |
| 2705 | /* Request instrumentation already owns the span; keep this helper in that context. */ |
| 2706 | Effect.fnUntraced(function* (rule) { |
| 2707 | return yield* keybindings.removeKeybindingRule(rule); |
| 2708 | }), |
| 2709 | [WS_METHODS.serverRunStorageCleanup]: () => storageCleanup.runNow, |
| 2710 | [WS_METHODS.serverGetStorageCleanupReport]: () => storageCleanup.reports, |
| 2711 | [WS_METHODS.serverGetDatabaseStorage]: () => databaseStorage.status, |
| 2712 | [WS_METHODS.serverReclaimDatabaseSpace]: () => databaseStorage.requestReclaim, |
| 2713 | [WS_METHODS.peerLinksList]: (_input) => |
| 2714 | peerLinks.list.pipe(Effect.map((links) => ({ links }))), |
| 2715 | [WS_METHODS.peerLinksNames]: (_input) => |
| 2716 | peerLinks.names.pipe(Effect.map((links) => ({ links }))), |
| 2717 | [WS_METHODS.peerLinksLink]: (input) => peerLinks.link(input), |
| 2718 | [WS_METHODS.peerLinksUnlink]: ({ environmentId }) => |
| 2719 | peerLinks.unlink(environmentId).pipe(Effect.map((removed) => ({ removed }))), |
| 2720 | [WS_METHODS.peerLinksSubscribeThread]: (input) => peerThreadRelay.subscribe(input), |
| 2721 | [WS_METHODS.peerLinksThreadHistoryPage]: (input) => |
| 2722 | Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( |
| 2723 | Effect.andThen(peerThreadRelay.historyPage(input)), |
| 2724 | ), |
| 2725 | [WS_METHODS.peerLinksThreadItem]: (input) => |
| 2726 | Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( |
| 2727 | Effect.andThen(peerThreadRelay.item(input)), |
| 2728 | ), |
| 2729 | [WS_METHODS.peerLinksPairClient]: (input) => |
| 2730 | peerClientPairing.request(input, currentSession), |
| 2731 | [WS_METHODS.peerLinksAnswerRequest]: (input) => |
| 2732 | Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( |
| 2733 | Effect.andThen(peerLinkRequests.answer(input)), |
| 2734 | ), |
| 2735 | [WS_METHODS.serverGetSettings]: (_input) => |
| 2736 | Effect.map(serverSettings.getSettings, (settings) => |
| 2737 | ServerSettings.redactServerSettingsForClient(settings, settingsClient), |
| 2738 | ), |
| 2739 | [WS_METHODS.serverUpdateSettings]: |
| 2740 | /* Request instrumentation already owns the span; keep this helper in that context. */ |
| 2741 | Effect.fnUntraced(function* ({ patch, providerInstanceMutation }) { |
| 2742 | const deviceHosts = patch.deviceHosts |
| 2743 | ? yield* remoteSshDeviceHosts(patch.deviceHosts).pipe( |
| 2744 | Effect.provide(deviceHostContext), |
| 2745 | ) |
| 2746 | : undefined; |
| 2747 | const nextPatch = { ...patch, ...(deviceHosts ? { deviceHosts } : {}) }; |
| 2748 | const settings = yield* providerInstanceMutation === undefined |
| 2749 | ? serverSettings.updateSettings(nextPatch) |
| 2750 | : serverSettings.updateProviderInstance(providerInstanceMutation, nextPatch); |
| 2751 | return ServerSettings.redactServerSettingsForClient(settings, settingsClient); |
| 2752 | }), |
| 2753 | [WS_METHODS.serverDiscoverSourceControl]: (_input) => sourceControlDiscovery.discover, |
| 2754 | [WS_METHODS.serverCheckSecretSource]: (input) => secretCheck.check(input.source), |
| 2755 | [WS_METHODS.serverGetTraceDiagnostics]: (_input) => |
| 2756 | TraceDiagnostics.readTraceDiagnostics({ |
| 2757 | traceFilePath: config.serverTracePath, |
| 2758 | maxFiles: config.traceMaxFiles, |
| 2759 | }), |
| 2760 | [WS_METHODS.serverGetProcessDiagnostics]: (_input) => processDiagnostics.read, |
| 2761 | [WS_METHODS.serverGetHostResources]: (_input) => hostResources.read, |
| 2762 | [WS_METHODS.serverGetProcessResourceHistory]: (input) => |
| 2763 | processResourceMonitor.readHistory(input), |
| 2764 | [WS_METHODS.serverGetResourceTelemetryHistory]: (input) => |
| 2765 | resourceTelemetry.readHistory(input), |
| 2766 | [WS_METHODS.serverGetUsageSummary]: (input) => usage.readSummary(input), |
| 2767 | [WS_METHODS.serverRefreshUsageRates]: (_input) => usage.refreshRates, |
| 2768 | [WS_METHODS.serverRetryResourceTelemetry]: (_input) => resourceTelemetry.retry, |
| 2769 | [WS_METHODS.serverCheckOtlpEndpoint]: (input) => otlpEndpointCheck.check(input), |
| 2770 | [WS_METHODS.serverListTextGeneratorModels]: (input) => textGenerators.listModels(input), |
| 2771 | [WS_METHODS.serverPrepareTriage]: (input) => triage.prepare(input), |
| 2772 | [WS_METHODS.serverSignalProcess]: (input) => processDiagnostics.signal(input), |
| 2773 | [WS_METHODS.serverReportClientActivity]: (input, metadata) => |
| 2774 | Ref.update(rpcClientIds, (clientIds) => { |
| 2775 | const next = new Set(clientIds); |
| 2776 | next.add(RpcClientId.make(metadata.client.id)); |
| 2777 | return next; |
| 2778 | }).pipe( |
| 2779 | Effect.andThen( |
| 2780 | backgroundPolicy.reportClientActivity( |
| 2781 | currentSessionId, |
| 2782 | RpcClientId.make(metadata.client.id), |
| 2783 | input, |
| 2784 | ), |
| 2785 | ), |
| 2786 | ), |
| 2787 | [WS_METHODS.cloudGetRelayClientStatus]: (_input) => relayClient.resolve, |
| 2788 | [WS_METHODS.cloudInstallRelayClient]: (_input) => |
| 2789 | Stream.callback<RelayClientInstallProgressEvent, RelayClientInstallFailedError>((queue) => |
| 2790 | relayClient |
| 2791 | .installWithProgress((event) => Queue.offer(queue, event).pipe(Effect.asVoid)) |
| 2792 | .pipe( |
| 2793 | Effect.flatMap((status) => |
| 2794 | Queue.offer(queue, { |
| 2795 | type: "complete", |
| 2796 | status, |
| 2797 | }), |
| 2798 | ), |
| 2799 | Effect.catchTags({ |
| 2800 | RelayClientInstallError: (error) => |
| 2801 | Queue.fail( |
| 2802 | queue, |
| 2803 | new RelayClientInstallFailedError({ |
| 2804 | reason: error.reason, |
| 2805 | message: error.message, |
| 2806 | }), |
| 2807 | ), |
| 2808 | }), |
| 2809 | Effect.andThen(Queue.end(queue)), |
| 2810 | Effect.forkScoped, |
| 2811 | ), |
| 2812 | ), |
| 2813 | [WS_METHODS.pullRequestsList]: (input) => pullRequests.list(input), |
| 2814 | [WS_METHODS.pullRequestsListStats]: (input) => pullRequests.listStats(input), |
| 2815 | [WS_METHODS.pullRequestsFilterOptions]: (input) => pullRequests.filterOptions(input), |
| 2816 | [WS_METHODS.pullRequestsRoutingIdentity]: (input) => pullRequests.routingIdentity(input), |
| 2817 | [WS_METHODS.pullRequestsRouting]: (input) => pullRequests.routing(input), |
| 2818 | [WS_METHODS.pullRequestsSummary]: (input) => |
| 2819 | withPullRequestViewer(input, pullRequests.summary(input)), |
| 2820 | [WS_METHODS.pullRequestsStack]: (input) => |
| 2821 | withPullRequestViewer(input, pullRequests.stack(input)), |
| 2822 | [WS_METHODS.pullRequestsLinkedThreads]: (input) => |
| 2823 | resolvePullRequestSyncKey(input).pipe( |
| 2824 | Effect.flatMap((key) => |
| 2825 | key === null |
| 2826 | ? Effect.succeed({ threads: [] }) |
| 2827 | : listLinkedPullRequestThreads(key).pipe( |
| 2828 | Effect.provideService(SqlClient.SqlClient, sql), |
| 2829 | ), |
| 2830 | ), |
| 2831 | ), |
| 2832 | [WS_METHODS.pullRequestsDetail]: (input) => |
| 2833 | withPullRequestViewer(input, openedPullRequestRead(pullRequests.detail(input))), |
| 2834 | [WS_METHODS.pullRequestsPreview]: (input) => |
| 2835 | withPullRequestViewer(input, pullRequests.preview(input)), |
| 2836 | [WS_METHODS.pullRequestsChecks]: (input) => |
| 2837 | withPullRequestViewer(input, pullRequests.checks(input)), |
| 2838 | [WS_METHODS.pullRequestsActivity]: (input) => |
| 2839 | withPullRequestViewer(input, openedPullRequestRead(pullRequests.activity(input))), |
| 2840 | [WS_METHODS.pullRequestsReviewGuide]: (input) => |
| 2841 | withPullRequestViewer(input, reviewGuides.get(input)), |
| 2842 | [WS_METHODS.pullRequestsGenerateReviewGuide]: (input) => |
| 2843 | withPullRequestViewer(input, reviewGuides.generate(input)), |
| 2844 | [WS_METHODS.pullRequestsThreadComments]: (input) => |
| 2845 | withPullRequestViewer(input, pullRequests.threadComments(input)), |
| 2846 | [WS_METHODS.pullRequestsDiffFileContents]: (input) => |
| 2847 | withPullRequestViewer(input, pullRequests.diffFileContents(input)), |
| 2848 | [WS_METHODS.pullRequestsFilesViewed]: (input) => |
| 2849 | withPullRequestViewer(input, pullRequests.filesViewed(input)), |
| 2850 | [WS_METHODS.pullRequestsChangeBreakdown]: (input) => |
| 2851 | withPullRequestViewer(input, pullRequests.changeBreakdown(input)), |
| 2852 | [WS_METHODS.pullRequestsSetFilesViewed]: (input) => |
| 2853 | withPullRequestViewer(input, pullRequests.setFilesViewed(input)), |
| 2854 | [WS_METHODS.pullRequestsRunAction]: (input) => |
| 2855 | withPullRequestViewer(input, pullRequests.runAction(input)).pipe( |
| 2856 | Effect.tap(() => |
| 2857 | resolvePullRequestSyncKey(input).pipe( |
| 2858 | Effect.flatMap((key) => |
| 2859 | key === null ? Effect.void : pullRequestSync.requestSync(key), |
| 2860 | ), |
| 2861 | ), |
| 2862 | ), |
| 2863 | ), |
| 2864 | [WS_METHODS.pullRequestsUpdate]: (input) => |
| 2865 | withPullRequestViewer(input, pullRequests.update(input)), |
| 2866 | [WS_METHODS.pullRequestsComment]: (input) => |
| 2867 | withPullRequestViewer(input, pullRequests.comment(input)), |
| 2868 | [WS_METHODS.pullRequestsUpdateComment]: (input) => |
| 2869 | withPullRequestViewer(input, pullRequests.updateComment(input)), |
| 2870 | [WS_METHODS.pullRequestsSubmitReview]: (input) => |
| 2871 | withPullRequestViewer(input, pullRequests.submitReview(input)), |
| 2872 | [WS_METHODS.pullRequestsReplyToThread]: (input) => |
| 2873 | withPullRequestViewer(input, pullRequests.replyToThread(input)), |
| 2874 | [WS_METHODS.pullRequestsSetThreadResolution]: (input) => |
| 2875 | withPullRequestViewer(input, pullRequests.setThreadResolution(input)), |
| 2876 | [WS_METHODS.pullRequestsSetReaction]: (input) => |
| 2877 | withPullRequestViewer(input, pullRequests.setReaction(input)), |
| 2878 | [WS_METHODS.pullRequestsReportState]: (input) => pullRequests.reportState(input), |
| 2879 | [WS_METHODS.pullRequestsInvalidate]: (input) => |
| 2880 | pullRequests |
| 2881 | .invalidate(input, { notifyReaders: true }) |
| 2882 | .pipe( |
| 2883 | Effect.andThen( |
| 2884 | input.reference === undefined || input.filesViewedOnly === true |
| 2885 | ? Effect.void |
| 2886 | : resolvePullRequestSyncKey(input.reference).pipe( |
| 2887 | Effect.flatMap((key) => |
| 2888 | key === null ? Effect.void : pullRequestSync.requestSync(key), |
| 2889 | ), |
| 2890 | ), |
| 2891 | ), |
| 2892 | ), |
| 2893 | [WS_METHODS.pullRequestsSubscribeRefreshes]: () => pullRequests.subscribeRefreshes, |
| 2894 | [WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes]: () => |
| 2895 | pullRequests.subscribeLinkedThreadRefreshes, |
| 2896 | [WS_METHODS.pullRequestsReviewerCandidates]: (input) => |
| 2897 | withPullRequestViewer(input, pullRequests.reviewerCandidates(input)), |
| 2898 | [WS_METHODS.pullRequestsRequestReviewers]: (input) => |
| 2899 | withPullRequestViewer(input, pullRequests.requestReviewers(input)), |
| 2900 | [WS_METHODS.pullRequestsLabelCandidates]: (input) => |
| 2901 | withPullRequestViewer(input, pullRequests.labelCandidates(input)), |
| 2902 | [WS_METHODS.pullRequestsSetLabels]: (input) => |
| 2903 | withPullRequestViewer(input, pullRequests.setLabels(input)), |
| 2904 | [WS_METHODS.sourceControlLookupRepository]: (input) => |
| 2905 | sourceControlRepositories.lookupRepository(input), |
| 2906 | [WS_METHODS.sourceControlCloneRepository]: (input) => |
| 2907 | sourceControlRepositories.cloneRepository(input), |
| 2908 | [WS_METHODS.sourceControlSignInStart]: (input) => sourceControlSignIn.start(input), |
| 2909 | [WS_METHODS.sourceControlSignInWait]: (input) => sourceControlSignIn.wait(input), |
| 2910 | [WS_METHODS.sourceControlSignInCancel]: (input) => sourceControlSignIn.cancel(input), |
| 2911 | [WS_METHODS.sourceControlAppAccess]: (input) => sourceControlSignIn.access(input), |
| 2912 | [WS_METHODS.sourceControlStarred]: (input) => sourceControlSignIn.starred(input), |
| 2913 | [WS_METHODS.sourceControlStar]: (input) => sourceControlSignIn.star(input), |
| 2914 | [WS_METHODS.projectCloneStart]: (input) => |
| 2915 | projectCloneTracker.start(input, { |
| 2916 | createProject: (project) => |
| 2917 | projectService |
| 2918 | .create({ |
| 2919 | commandId: CommandId.make(`project-clone-create:${project.projectId}`), |
| 2920 | projectId: project.projectId, |
| 2921 | title: project.title, |
| 2922 | workspaceRoot: project.workspaceRoot, |
| 2923 | createWorkspaceRootIfMissing: true, |
| 2924 | }) |
| 2925 | .pipe( |
| 2926 | Effect.asVoid, |
| 2927 | Effect.mapError((cause) => |
| 2928 | cause._tag === "ProjectConflictError" |
| 2929 | ? cause |
| 2930 | : new OrchestrationDispatchCommandError({ |
| 2931 | message: "Failed to create clone project.", |
| 2932 | cause, |
| 2933 | }), |
| 2934 | ), |
| 2935 | ), |
| 2936 | onCloned: (project) => |
| 2937 | repositoryIdentityResolver.resolve(project.workspaceRoot, { refresh: true }).pipe( |
| 2938 | Effect.andThen( |
| 2939 | projectService.update({ |
| 2940 | commandId: CommandId.make(`project-clone-done:${project.projectId}`), |
| 2941 | projectId: project.projectId, |
| 2942 | }), |
| 2943 | ), |
| 2944 | Effect.andThen(refreshGitStatus(project.workspaceRoot)), |
| 2945 | // The folder was empty when the project was created, so the cached |
| 2946 | // enrichment says "no repository" and clients cannot group it yet. |
| 2947 | Effect.andThen(projectEnrichment.invalidate([project.workspaceRoot])), |
| 2948 | Effect.andThen(projectEnrichment.request(project.workspaceRoot)), |
| 2949 | Effect.ignoreCause({ log: true }), |
| 2950 | ), |
| 2951 | }), |
| 2952 | [WS_METHODS.projectsEnsureScratch]: () => |
| 2953 | managedFolders.ensureScratchProject.pipe( |
| 2954 | Effect.mapError( |
| 2955 | (cause) => new OrchestrationDispatchCommandError({ message: cause.message, cause }), |
| 2956 | ), |
| 2957 | ), |
| 2958 | [WS_METHODS.projectsCreateNew]: (input) => |
| 2959 | managedFolders |
| 2960 | .createNamedProject(input) |
| 2961 | .pipe( |
| 2962 | Effect.mapError( |
| 2963 | (cause) => new OrchestrationDispatchCommandError({ message: cause.message, cause }), |
| 2964 | ), |
| 2965 | ), |
| 2966 | [WS_METHODS.projectsCreateFromThread]: (input) => |
| 2967 | scratchThreadPromotion |
| 2968 | .promote(input) |
| 2969 | .pipe( |
| 2970 | Effect.mapError( |
| 2971 | (cause) => new OrchestrationDispatchCommandError({ message: cause.message, cause }), |
| 2972 | ), |
| 2973 | ), |
| 2974 | [WS_METHODS.projectCloneCancel]: (input) => |
| 2975 | projectCloneTracker.cancel(input.projectId).pipe(Effect.map((applied) => ({ applied }))), |
| 2976 | [WS_METHODS.projectCloneRetry]: (input) => |
| 2977 | projectCloneTracker.retry(input.projectId).pipe(Effect.map((applied) => ({ applied }))), |
| 2978 | [WS_METHODS.subscribeProjectClones]: () => projectCloneTracker.stream, |
| 2979 | [WS_METHODS.sourceControlPublishRepository]: (input) => |
| 2980 | sourceControlRepositories.publishRepository(input).pipe( |
| 2981 | // A failed push still leaves the new remote added. |
| 2982 | Effect.ensuring( |
| 2983 | repositoryIdentityResolver |
| 2984 | .resolve(input.cwd, { refresh: true }) |
| 2985 | .pipe(Effect.andThen(refreshGitStatus(input.cwd))), |
| 2986 | ), |
| 2987 | ), |
| 2988 | [WS_METHODS.projectsSearchEntries]: (input) => |
| 2989 | workspaceEntries.search(input).pipe( |
| 2990 | Effect.mapError( |
| 2991 | (cause) => |
| 2992 | new ProjectSearchEntriesError({ |
| 2993 | cwd: input.cwd, |
| 2994 | queryLength: input.query.length, |
| 2995 | limit: input.limit, |
| 2996 | ...projectEntriesFailureContext(cause), |
| 2997 | cause, |
| 2998 | }), |
| 2999 | ), |
| 3000 | ), |
| 3001 | [WS_METHODS.projectsSearchContents]: (input) => |
| 3002 | workspaceEntries.searchContents(input).pipe( |
| 3003 | Effect.mapError( |
| 3004 | (cause) => |
| 3005 | new ProjectSearchContentsError({ |
| 3006 | cwd: input.cwd, |
| 3007 | queryLength: input.query.length, |
| 3008 | limit: input.limit, |
| 3009 | ...projectEntriesFailureContext(cause), |
| 3010 | cause, |
| 3011 | }), |
| 3012 | ), |
| 3013 | ), |
| 3014 | [WS_METHODS.projectsListEntries]: (input) => |
| 3015 | workspaceEntries.list(input).pipe( |
| 3016 | Effect.mapError( |
| 3017 | (cause) => |
| 3018 | new ProjectListEntriesError({ |
| 3019 | ...input, |
| 3020 | ...projectEntriesFailureContext(cause), |
| 3021 | cause, |
| 3022 | }), |
| 3023 | ), |
| 3024 | ), |
| 3025 | [WS_METHODS.projectsListIgnoredFiles]: (input) => |
| 3026 | workspaceEntries.listIgnoredFiles(input).pipe( |
| 3027 | Effect.mapError( |
| 3028 | (cause) => |
| 3029 | new ProjectListEntriesError({ |
| 3030 | ...input, |
| 3031 | ...projectEntriesFailureContext(cause), |
| 3032 | cause, |
| 3033 | }), |
| 3034 | ), |
| 3035 | ), |
| 3036 | [WS_METHODS.projectsReadFile]: (input) => |
| 3037 | workspaceFileSystem.readFile(input).pipe( |
| 3038 | Effect.mapError( |
| 3039 | (cause) => |
| 3040 | new ProjectReadFileError({ |
| 3041 | ...input, |
| 3042 | ...projectFileFailureContext(cause), |
| 3043 | cause, |
| 3044 | }), |
| 3045 | ), |
| 3046 | ), |
| 3047 | [WS_METHODS.projectsWriteFile]: (input) => |
| 3048 | workspaceFileSystem.writeFile(input).pipe( |
| 3049 | Effect.mapError( |
| 3050 | (cause) => |
| 3051 | new ProjectWriteFileError({ |
| 3052 | cwd: input.cwd, |
| 3053 | relativePath: input.relativePath, |
| 3054 | ...projectFileFailureContext(cause), |
| 3055 | cause, |
| 3056 | }), |
| 3057 | ), |
| 3058 | ), |
| 3059 | [WS_METHODS.projectsMutate]: (mutation) => |
| 3060 | startup.enqueueCommand(mutateProject(mutation)).pipe( |
| 3061 | Effect.mapError( |
| 3062 | (cause) => |
| 3063 | new ProjectMutationError({ |
| 3064 | commandId: mutation.commandId, |
| 3065 | message: |
| 3066 | cause._tag === "ProjectNotEmptyError" || cause._tag === "ProjectInvalidError" |
| 3067 | ? cause.message |
| 3068 | : "Failed to mutate project.", |
| 3069 | cause, |
| 3070 | }), |
| 3071 | ), |
| 3072 | ), |
| 3073 | [WS_METHODS.shellOpenInEditor]: (input) => externalLauncher.launchEditor(input), |
| 3074 | [WS_METHODS.filesystemGetMetadata]: (input) => workspaceFileSystem.getMetadata(input), |
| 3075 | [WS_METHODS.filesystemBrowse]: (input) => |
| 3076 | workspaceEntries.browse(input).pipe( |
| 3077 | Effect.mapError( |
| 3078 | (cause) => |
| 3079 | new FilesystemBrowseError({ |
| 3080 | ...input, |
| 3081 | ...filesystemBrowseFailureContext(cause), |
| 3082 | cause, |
| 3083 | }), |
| 3084 | ), |
| 3085 | ), |
| 3086 | [WS_METHODS.attachmentsCreateUploadUrl]: (input) => issueAttachmentUploadUrl(input), |
| 3087 | [WS_METHODS.attachmentsDelete]: (input) => deletePendingAttachment(input.attachmentId), |
| 3088 | [WS_METHODS.agentSessionsScan]: () => agentSessionScanner.scan, |
| 3089 | [WS_METHODS.agentSessionsImport]: (input) => |
| 3090 | agentSessionImporter.importRecentAgentThreads(input), |
| 3091 | [WS_METHODS.assetsCreateUrl]: |
| 3092 | /* Request instrumentation already owns the span; keep this helper in that context. */ |
| 3093 | Effect.fnUntraced(function* (input) { |
| 3094 | const path = yield* Path.Path; |
| 3095 | if ( |
| 3096 | input.resource._tag === "attachment" || |
| 3097 | input.resource._tag === "native-app-icon" || |
| 3098 | input.resource._tag === "environment-theme-background" || |
| 3099 | input.resource._tag === "tool-output-image" || |
| 3100 | input.resource._tag === SOURCE_CONTROL_MEDIA_ASSET || |
| 3101 | // A network path is served only from the thread's project, looked up below. |
| 3102 | (input.resource._tag === "media-file" && |
| 3103 | path.isAbsolute(input.resource.path) && |
| 3104 | !isNetworkPath(input.resource.path)) |
| 3105 | ) { |
| 3106 | return yield* issueAssetUrl({ resource: input.resource }); |
| 3107 | } |
| 3108 | if (input.resource._tag === "draft-workspace-file") { |
| 3109 | return yield* issueAssetUrl({ |
| 3110 | resource: input.resource, |
| 3111 | workspaceRoot: input.resource.cwd, |
| 3112 | }); |
| 3113 | } |
| 3114 | if (input.resource._tag === "project-favicon") { |
| 3115 | const project = yield* projectStore |
| 3116 | .findActiveByWorkspaceRoot(input.resource.cwd) |
| 3117 | .pipe( |
| 3118 | Effect.mapError( |
| 3119 | (cause) => |
| 3120 | new AssetWorkspaceContextResolutionError({ |
| 3121 | resource: input.resource, |
| 3122 | cause, |
| 3123 | }), |
| 3124 | ), |
| 3125 | ); |
| 3126 | if (Option.isNone(project)) { |
| 3127 | return yield* new AssetWorkspaceContextNotFoundError({ |
| 3128 | resource: input.resource, |
| 3129 | }); |
| 3130 | } |
| 3131 | // Clone projects precede their files; clients retry asset URLs after clone completion. |
| 3132 | const clone = yield* projectCloneTracker.get(project.value.projectId); |
| 3133 | return yield* issueAssetUrl({ |
| 3134 | resource: input.resource, |
| 3135 | ...(project.value.faviconPath |
| 3136 | ? { projectFaviconPath: project.value.faviconPath } |
| 3137 | : {}), |
| 3138 | ...(clone !== null && clone.destinationPath === project.value.workspaceRoot |
| 3139 | ? { projectCheckout: clone.phase === "done" ? "cloned" : "pending" } |
| 3140 | : {}), |
| 3141 | }); |
| 3142 | } |
| 3143 | const thread = yield* threadManagement |
| 3144 | .getThreadRecords(input.resource.threadId, []) |
| 3145 | .pipe( |
| 3146 | Effect.mapError( |
| 3147 | (cause) => |
| 3148 | new AssetWorkspaceContextResolutionError({ |
| 3149 | resource: input.resource, |
| 3150 | cause, |
| 3151 | }), |
| 3152 | ), |
| 3153 | ); |
| 3154 | const project = yield* projectService.getById(thread.thread.projectId).pipe( |
| 3155 | Effect.mapError( |
| 3156 | (cause) => |
| 3157 | new AssetWorkspaceContextResolutionError({ |
| 3158 | resource: input.resource, |
| 3159 | cause, |
| 3160 | }), |
| 3161 | ), |
| 3162 | ); |
| 3163 | if (Option.isNone(project)) { |
| 3164 | return yield* new AssetWorkspaceContextNotFoundError({ |
| 3165 | resource: input.resource, |
| 3166 | }); |
| 3167 | } |
| 3168 | return yield* issueAssetUrl({ |
| 3169 | resource: input.resource, |
| 3170 | workspaceRoot: thread.thread.worktreePath ?? project.value.workspaceRoot, |
| 3171 | }); |
| 3172 | }), |
| 3173 | [WS_METHODS.assetsPersistChatAttachments]: (input) => |
| 3174 | persistChatAttachments(input).pipe(Effect.map((attachments) => ({ attachments }))), |
| 3175 | [WS_METHODS.subscribeVcsBranch]: (input) => vcsStatusBroadcaster.streamBranchStatus(input), |
| 3176 | [WS_METHODS.vcsRefreshBranch]: (input) => |
| 3177 | vcsStatusBroadcaster.refreshBranchStatus(input).pipe(Effect.asVoid), |
| 3178 | [WS_METHODS.subscribeVcsStatus]: (input) => vcsStatusBroadcaster.streamStatus(input), |
| 3179 | [WS_METHODS.subscribeWorktreeSetup]: (input) => worktreeSetupTracker.stream(input.threadId), |
| 3180 | [WS_METHODS.worktreeSetupCancel]: (input) => |
| 3181 | worktreeSetupTracker |
| 3182 | .cancel(input.threadId) |
| 3183 | .pipe(Effect.map((cancelled) => ({ cancelled }))), |
| 3184 | [WS_METHODS.vcsRefreshStatus]: (input) => |
| 3185 | vcsStatusBroadcaster.refreshStatus(input.cwd, { localOnly: input.localOnly ?? false }), |
| 3186 | [WS_METHODS.vcsPull]: (input) => |
| 3187 | gitWorkflow.pullCurrentBranch(input.cwd).pipe( |
| 3188 | Effect.matchCauseEffect({ |
| 3189 | onFailure: (cause) => Effect.failCause(cause), |
| 3190 | onSuccess: (result) => |
| 3191 | refreshGitStatus(input.cwd).pipe(Effect.ignore({ log: true }), Effect.as(result)), |
| 3192 | }), |
| 3193 | ), |
| 3194 | [WS_METHODS.gitRunStackedAction]: (input) => |
| 3195 | Stream.callback<GitActionProgressEvent, GitManagerServiceError>((queue) => |
| 3196 | gitWorkflow |
| 3197 | .runStackedAction(input, { |
| 3198 | actionId: input.actionId, |
| 3199 | progressReporter: { |
| 3200 | publish: (event) => Queue.offer(queue, event).pipe(Effect.asVoid), |
| 3201 | }, |
| 3202 | }) |
| 3203 | .pipe( |
| 3204 | Effect.matchCauseEffect({ |
| 3205 | // Earlier steps (branch, commit) may have landed before the failing one. |
| 3206 | onFailure: (cause) => |
| 3207 | refreshGitStatus(input.cwd).pipe(Effect.andThen(Queue.failCause(queue, cause))), |
| 3208 | onSuccess: (result) => |
| 3209 | (input.threadId === undefined |
| 3210 | ? Effect.void |
| 3211 | : linkCreatedPullRequest({ |
| 3212 | threadId: input.threadId, |
| 3213 | result, |
| 3214 | commandId: serverCommandId("pr-created-link"), |
| 3215 | }).pipe( |
| 3216 | Effect.provideService(Orchestrator.OrchestratorV2, orchestrationEngine), |
| 3217 | Effect.provideService(ProjectService.ProjectService, projectService), |
| 3218 | ) |
| 3219 | ).pipe( |
| 3220 | Effect.andThen( |
| 3221 | refreshPushedPullRequests(input, result).pipe( |
| 3222 | Effect.provideService(Orchestrator.OrchestratorV2, orchestrationEngine), |
| 3223 | Effect.provideService(ProjectStore.ProjectStoreV2, projectStore), |
| 3224 | Effect.provideService( |
| 3225 | PullRequestService.PullRequestService, |
| 3226 | pullRequests, |
| 3227 | ), |
| 3228 | ), |
| 3229 | ), |
| 3230 | Effect.andThen(refreshGitStatus(input.cwd)), |
| 3231 | Effect.andThen(Queue.end(queue).pipe(Effect.asVoid)), |
| 3232 | ), |
| 3233 | }), |
| 3234 | ), |
| 3235 | ), |
| 3236 | [WS_METHODS.gitResolvePullRequest]: (input) => gitWorkflow.resolvePullRequest(input), |
| 3237 | [WS_METHODS.gitPreparePullRequestThread]: (input) => |
| 3238 | gitWorkflow |
| 3239 | .preparePullRequestThread(input) |
| 3240 | .pipe(Effect.tap(() => refreshGitStatus(input.cwd))), |
| 3241 | [WS_METHODS.vcsListRefs]: (input) => gitWorkflow.listRefs(input), |
| 3242 | [WS_METHODS.vcsCreateWorktree]: (input) => |
| 3243 | gitWorkflow.createWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), |
| 3244 | [WS_METHODS.vcsRemoveWorktree]: (input) => |
| 3245 | gitWorkflow.removeWorktree(input).pipe( |
| 3246 | Effect.tap(() => refreshGitStatus(input.cwd)), |
| 3247 | // Subscribers of the removed checkout learn it is no longer a repository. |
| 3248 | Effect.tap(() => |
| 3249 | vcsStatusBroadcaster |
| 3250 | .refreshLocalStatus(input.path) |
| 3251 | .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid), |
| 3252 | ), |
| 3253 | ), |
| 3254 | [WS_METHODS.vcsCreateRef]: (input) => |
| 3255 | gitWorkflow |
| 3256 | .createRef(input) |
| 3257 | .pipe( |
| 3258 | Effect.tap(() => |
| 3259 | input.switchRef |
| 3260 | ? vcsStatusBroadcaster.refreshAfterCheckout(input.cwd) |
| 3261 | : refreshGitStatus(input.cwd), |
| 3262 | ), |
| 3263 | ), |
| 3264 | [WS_METHODS.vcsSwitchRef]: (input) => |
| 3265 | gitWorkflow |
| 3266 | .switchRef(input) |
| 3267 | .pipe(Effect.tap(() => vcsStatusBroadcaster.refreshAfterCheckout(input.cwd))), |
| 3268 | [WS_METHODS.vcsInit]: (input) => |
| 3269 | vcsProvisioning.initRepository(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), |
| 3270 | [WS_METHODS.reviewGetBranchCommits]: (input) => review.getBranchCommits(input), |
| 3271 | [WS_METHODS.reviewGetDiffPreview]: (input) => review.getDiffPreview(input), |
| 3272 | [WS_METHODS.reviewGetDiffFileContents]: (input) => review.getDiffFileContents(input), |
| 3273 | [WS_METHODS.terminalOpen]: (input) => |
| 3274 | prepareTerminalLaunch(input).pipe( |
| 3275 | Effect.flatMap((launch) => |
| 3276 | terminalManager |
| 3277 | .open(launch.input) |
| 3278 | .pipe(Effect.provideService(TerminalManager.TerminalCwdRecovery, launch.recover)), |
| 3279 | ), |
| 3280 | ), |
| 3281 | [WS_METHODS.terminalAttach]: (input, metadata) => |
| 3282 | Stream.unwrap( |
| 3283 | prepareTerminalLaunch(input).pipe( |
| 3284 | Effect.map((launch) => |
| 3285 | terminalManager |
| 3286 | .attachOutputStream(launch.input, terminalViewerId(metadata)) |
| 3287 | .pipe(Stream.provideService(TerminalManager.TerminalCwdRecovery, launch.recover)), |
| 3288 | ), |
| 3289 | ), |
| 3290 | ), |
| 3291 | [WS_METHODS.terminalWrite]: (input, metadata) => |
| 3292 | terminalManager.write(input, terminalViewerId(metadata)), |
| 3293 | [WS_METHODS.terminalResize]: (input, metadata) => |
| 3294 | terminalManager.resize(input, terminalViewerId(metadata)), |
| 3295 | [WS_METHODS.terminalClear]: (input) => terminalManager.clear(input), |
| 3296 | [WS_METHODS.terminalClose]: (input) => terminalManager.close(input), |
| 3297 | [WS_METHODS.terminalObserve]: (input) => |
| 3298 | terminalOutputStream( |
| 3299 | (listener, registerCleanup) => |
| 3300 | terminalManager.observeStream(input, listener, registerCleanup), |
| 3301 | (listener, registerCleanup) => |
| 3302 | terminalManager.resyncStream(input, listener, registerCleanup), |
| 3303 | ), |
| 3304 | [WS_METHODS.subscribeTerminalMetadata]: (_input) => |
| 3305 | Stream.callback<TerminalMetadataStreamEvent>((queue) => |
| 3306 | Effect.acquireRelease( |
| 3307 | terminalManager.subscribeMetadata((event) => Queue.offer(queue, event)), |
| 3308 | (unsubscribe) => Effect.sync(unsubscribe), |
| 3309 | ), |
| 3310 | ), |
| 3311 | [WS_METHODS.previewOpen]: (input) => previewManager.open(input), |
| 3312 | [WS_METHODS.previewResize]: (input) => previewManager.resize(input), |
| 3313 | [WS_METHODS.previewAdjust]: (input) => previewManager.adjust(input), |
| 3314 | [WS_METHODS.previewClose]: (input) => previewManager.close(input), |
| 3315 | [WS_METHODS.previewList]: (input) => previewManager.list(input), |
| 3316 | [WS_METHODS.previewClearProfile]: (input) => serverBrowser.clearProfile(input.profileId), |
| 3317 | [WS_METHODS.previewReportProfiles]: (input) => reportProfiles(input), |
| 3318 | [WS_METHODS.previewReportStatus]: (input) => previewManager.reportStatus(input), |
| 3319 | [WS_METHODS.subscribePreviewEvents]: (_input) => previewManager.events, |
| 3320 | [WS_METHODS.deviceConfigure]: (input) => deviceService.configure(input), |
| 3321 | [WS_METHODS.deviceTestHost]: (input) => deviceService.testHost(input), |
| 3322 | [WS_METHODS.deviceEasAccount]: (input) => deviceService.easAccount(input), |
| 3323 | [WS_METHODS.deviceSimlockIdentity]: (input) => deviceService.simlockIdentity(input), |
| 3324 | [WS_METHODS.deviceList]: (input) => |
| 3325 | input.inspectOnly && !input.updateTool |
| 3326 | ? deviceService.inspect |
| 3327 | : authorizeEffect( |
| 3328 | requiredScopeForDeviceList(input), |
| 3329 | input.updateTool |
| 3330 | ? deviceService.updateTool(input.updateTool) |
| 3331 | : input.retryHostId |
| 3332 | ? deviceService.retryHost(input.retryHostId) |
| 3333 | : deviceService.list, |
| 3334 | ), |
| 3335 | [WS_METHODS.deviceOpen]: (input) => |
| 3336 | threadWorkspaceRoot(input.threadId).pipe( |
| 3337 | Effect.flatMap((workspaceRoot) => deviceService.open(input, { workspaceRoot })), |
| 3338 | ), |
| 3339 | [WS_METHODS.deviceClose]: (input) => deviceService.close(input), |
| 3340 | [WS_METHODS.deviceShutdown]: (input) => deviceService.shutdown(input), |
| 3341 | [WS_METHODS.deviceDetail]: (input) => deviceService.detail(input), |
| 3342 | [WS_METHODS.deviceAction]: (input) => deviceService.action(input), |
| 3343 | [WS_METHODS.subscribeDeviceState]: (_input) => DeviceService.stateStream(deviceService), |
| 3344 | [WS_METHODS.previewStopLocalServer]: (input) => portDiscovery.stopServer(input), |
| 3345 | [WS_METHODS.subscribeDiscoveredLocalServers]: (input) => |
| 3346 | Stream.callback<DiscoveredLocalServerList>((queue) => |
| 3347 | Effect.gen(function* () { |
| 3348 | const configuredUrls = input.configuredUrls ?? []; |
| 3349 | yield* portDiscovery.retain; |
| 3350 | const initial = yield* portDiscovery.scan(configuredUrls); |
| 3351 | const initialScannedAt = DateTime.formatIso(yield* DateTime.now); |
| 3352 | yield* Queue.offer(queue, { |
| 3353 | servers: initial, |
| 3354 | scannedAt: initialScannedAt, |
| 3355 | configuredUrlProbing: true, |
| 3356 | }); |
| 3357 | yield* portDiscovery.subscribe( |
| 3358 | { configuredUrls, initialSnapshot: initial }, |
| 3359 | (servers) => |
| 3360 | Effect.gen(function* () { |
| 3361 | const scannedAt = DateTime.formatIso(yield* DateTime.now); |
| 3362 | yield* Queue.offer(queue, { |
| 3363 | servers, |
| 3364 | scannedAt, |
| 3365 | configuredUrlProbing: true, |
| 3366 | }); |
| 3367 | }), |
| 3368 | ); |
| 3369 | }), |
| 3370 | ), |
| 3371 | [WS_METHODS.subscribeServerConfig]: (input) => |
| 3372 | Stream.unwrap( |
| 3373 | Effect.gen(function* () { |
| 3374 | const usageLimitsCommand = input.usageLimitsCommand === true; |
| 3375 | const workspaceSnapshotsOnDemand = input.workspaceSnapshotsOnDemand === true; |
| 3376 | // Only providers that can scan a cwd answer the client's on-demand catalog fetch. |
| 3377 | // Read per update, since a replaced instance can change that. |
| 3378 | const currentCatalogsPerCwd = |
| 3379 | workspaceSnapshotsOnDemand && input.providerCatalogsOnDemand === true |
| 3380 | ? providerInstances.listInstances.pipe( |
| 3381 | Effect.map( |
| 3382 | (instances) => |
| 3383 | new Set( |
| 3384 | instances |
| 3385 | .filter((instance) => instance.snapshotForCwd !== undefined) |
| 3386 | .map((instance) => instance.instanceId), |
| 3387 | ), |
| 3388 | ), |
| 3389 | ) |
| 3390 | : Effect.succeed(new Set<string>()); |
| 3391 | const catalogDigests = input.providerCatalogDigests === true; |
| 3392 | // Buffer changes through discovery and the initial snapshot's send. |
| 3393 | const keybindingsChanges = yield* keybindings.subscribeChanges; |
| 3394 | const settingsChanges = yield* serverSettings.subscribeChanges; |
| 3395 | const remoteTargets = yield* Effect.forkScoped(remoteOpenTargets.resolveTargets(), { |
| 3396 | startImmediately: true, |
| 3397 | }); |
| 3398 | const directResult = yield* Effect.forkScoped( |
| 3399 | directEndpoints |
| 3400 | .resolve() |
| 3401 | .pipe(Effect.catchCause(() => directEndpoints.resolveAvailable())), |
| 3402 | { startImmediately: true }, |
| 3403 | ); |
| 3404 | const config = yield* loadServerConfig({ |
| 3405 | usageLimitsCommand, |
| 3406 | workspaceSnapshotsOnDemand, |
| 3407 | deferNetworkDiscovery: true, |
| 3408 | catalogsPerCwd: yield* currentCatalogsPerCwd, |
| 3409 | catalogDigests, |
| 3410 | }); |
| 3411 | const keybindingsUpdates = keybindingsChanges.pipe( |
| 3412 | Stream.map((event) => ({ |
| 3413 | version: 1 as const, |
| 3414 | type: "keybindingsUpdated" as const, |
| 3415 | payload: { |
| 3416 | keybindings: event.keybindings, |
| 3417 | issues: event.issues, |
| 3418 | }, |
| 3419 | })), |
| 3420 | ); |
| 3421 | const providerStatuses = Stream.zipLatestWith( |
| 3422 | // Seed the changes-only stream so early source refreshes pair with current providers. |
| 3423 | Stream.concat( |
| 3424 | Stream.fromEffect(providerRegistry.getProviders), |
| 3425 | providerRegistry.streamChanges, |
| 3426 | ), |
| 3427 | usageLimitSources.streamChanges.pipe( |
| 3428 | Stream.changesWith( |
| 3429 | usageLimitsCommand ? sameUsageLimitCommandCoverage : () => true, |
| 3430 | ), |
| 3431 | ), |
| 3432 | (providers, sources) => |
| 3433 | usageLimitsCommand ? withUsageLimitsCommands(providers, sources) : providers, |
| 3434 | ).pipe( |
| 3435 | // Stripped before the de-dupe below, so snapshot-only changes send nothing. |
| 3436 | Stream.mapEffect((commandProviders) => |
| 3437 | workspaceSnapshotsOnDemand |
| 3438 | ? currentCatalogsPerCwd.pipe( |
| 3439 | Effect.map((catalogsPerCwd) => |
| 3440 | withoutWorkspaceSnapshots( |
| 3441 | commandProviders, |
| 3442 | catalogsPerCwd, |
| 3443 | catalogDigests, |
| 3444 | ), |
| 3445 | ), |
| 3446 | ) |
| 3447 | : Effect.succeed(commandProviders), |
| 3448 | ), |
| 3449 | // Compare initial paired values with the snapshot; blindly dropping them loses changes between snapshot and subscription. |
| 3450 | (updates) => Stream.concat(rpcInitialItems([config.providers]), updates), |
| 3451 | Stream.changesWith( |
| 3452 | (previous, next) => JSON.stringify(previous) === JSON.stringify(next), |
| 3453 | ), |
| 3454 | Stream.drop(1), |
| 3455 | Stream.map((providers) => ({ |
| 3456 | version: 1 as const, |
| 3457 | type: "providerStatuses" as const, |
| 3458 | payload: { providers }, |
| 3459 | })), |
| 3460 | Stream.debounce(Duration.millis(PROVIDER_STATUS_DEBOUNCE_MS)), |
| 3461 | ); |
| 3462 | // Gate capability-specific events; older clients reject them and lose their config subscription. |
| 3463 | const environmentThemeUpdates = |
| 3464 | input.environmentThemes === true |
| 3465 | ? environmentTheme.streamChanges.pipe( |
| 3466 | Stream.map((themes) => ({ |
| 3467 | version: 1 as const, |
| 3468 | type: "environmentThemesUpdated" as const, |
| 3469 | payload: { themes }, |
| 3470 | })), |
| 3471 | ) |
| 3472 | : Stream.empty; |
| 3473 | const usageLimitSourceUpdates = |
| 3474 | input.usageLimitSources === true |
| 3475 | ? usageLimitSources.streamChanges.pipe( |
| 3476 | Stream.map((sources) => ({ |
| 3477 | version: 1 as const, |
| 3478 | type: "usageLimitSourcesUpdated" as const, |
| 3479 | payload: { sources }, |
| 3480 | })), |
| 3481 | ) |
| 3482 | : Stream.empty; |
| 3483 | const settingsUpdates = settingsChanges.pipe( |
| 3484 | Stream.map((settings) => |
| 3485 | ServerSettings.redactServerSettingsForClient(settings, settingsClient), |
| 3486 | ), |
| 3487 | Stream.map((settings) => ({ |
| 3488 | version: 1 as const, |
| 3489 | type: "settingsUpdated" as const, |
| 3490 | payload: { settings }, |
| 3491 | })), |
| 3492 | ); |
| 3493 | |
| 3494 | const liveUpdates = Stream.merge( |
| 3495 | keybindingsUpdates, |
| 3496 | Stream.merge( |
| 3497 | providerStatuses, |
| 3498 | Stream.merge( |
| 3499 | settingsUpdates, |
| 3500 | Stream.merge(environmentThemeUpdates, usageLimitSourceUpdates), |
| 3501 | ), |
| 3502 | ), |
| 3503 | ); |
| 3504 | |
| 3505 | const remoteResult = yield* Effect.sync(() => remoteTargets.pollUnsafe()); |
| 3506 | const initialConfig = |
| 3507 | remoteResult?._tag === "Success" |
| 3508 | ? { ...config, remoteOpenTargets: remoteResult.value } |
| 3509 | : config; |
| 3510 | const updates = withLateConfigDiscovery( |
| 3511 | initialConfig, |
| 3512 | liveUpdates, |
| 3513 | externalLauncher, |
| 3514 | { |
| 3515 | resolveTargets: () => Fiber.join(remoteTargets), |
| 3516 | }, |
| 3517 | { resolve: () => Fiber.join(directResult) }, |
| 3518 | ); |
| 3519 | return Stream.concat( |
| 3520 | rpcInitialItems([ |
| 3521 | { version: 1 as const, type: "snapshot" as const, config: initialConfig }, |
| 3522 | ]), |
| 3523 | input.providerStatusDeltas === true |
| 3524 | ? updates.pipe(withProviderStatusDeltas(initialConfig.providers)) |
| 3525 | : updates, |
| 3526 | ); |
| 3527 | }), |
| 3528 | ), |
| 3529 | [WS_METHODS.subscribeServerLifecycle]: (_input) => |
| 3530 | Stream.unwrap( |
| 3531 | Effect.gen(function* () { |
| 3532 | const liveBuffer = yield* Queue.unbounded<ServerLifecycleStreamEvent>(); |
| 3533 | yield* Effect.forkScoped( |
| 3534 | lifecycleEvents.stream.pipe( |
| 3535 | Stream.runForEach((event) => Queue.offer(liveBuffer, event)), |
| 3536 | ), |
| 3537 | { startImmediately: true }, |
| 3538 | ); |
| 3539 | const snapshot = yield* lifecycleEvents.snapshot; |
| 3540 | const snapshotEvents = Array.from(snapshot.events).toSorted( |
| 3541 | (left, right) => left.sequence - right.sequence, |
| 3542 | ); |
| 3543 | const liveEvents = Stream.fromQueue(liveBuffer).pipe( |
| 3544 | Stream.filter((event) => event.sequence > snapshot.sequence), |
| 3545 | ); |
| 3546 | return Stream.concat(rpcInitialItems(snapshotEvents), liveEvents); |
| 3547 | }), |
| 3548 | ), |
| 3549 | [WS_METHODS.subscribeAuthAccess]: (_input) => |
| 3550 | Stream.unwrap( |
| 3551 | Effect.gen(function* () { |
| 3552 | const liveBuffer = yield* Queue.unbounded< |
| 3553 | PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange |
| 3554 | >(); |
| 3555 | // Each store subscribes only when consumed, so start both before the snapshot read. |
| 3556 | yield* Effect.forkScoped( |
| 3557 | Stream.runForEach(bootstrapCredentials.streamChanges, (change) => |
| 3558 | Queue.offer(liveBuffer, change), |
| 3559 | ), |
| 3560 | { startImmediately: true }, |
| 3561 | ); |
| 3562 | yield* Effect.forkScoped( |
| 3563 | Stream.runForEach(sessions.streamChanges, (change) => |
| 3564 | Queue.offer(liveBuffer, change), |
| 3565 | ), |
| 3566 | { startImmediately: true }, |
| 3567 | ); |
| 3568 | const initialSnapshot = yield* loadAuthAccessSnapshot(); |
| 3569 | const revisionRef = yield* Ref.make(1); |
| 3570 | |
| 3571 | const liveEvents: Stream.Stream<AuthAccessStreamEvent, AuthAccessStreamError> = |
| 3572 | Stream.fromQueue(liveBuffer).pipe( |
| 3573 | Stream.mapEffect((change) => |
| 3574 | Ref.updateAndGet(revisionRef, (revision) => revision + 1).pipe( |
| 3575 | Effect.flatMap((revision) => |
| 3576 | // Device trust has no incremental event older clients could decode. |
| 3577 | change.type === "connectDevicesChanged" |
| 3578 | ? loadAuthAccessSnapshot().pipe( |
| 3579 | Effect.map((payload): AuthAccessStreamEvent => ({ |
| 3580 | version: 1, |
| 3581 | revision, |
| 3582 | type: "snapshot", |
| 3583 | payload, |
| 3584 | })), |
| 3585 | ) |
| 3586 | : Effect.succeed( |
| 3587 | toAuthAccessStreamEvent(change, revision, currentSessionId), |
| 3588 | ), |
| 3589 | ), |
| 3590 | ), |
| 3591 | ), |
| 3592 | ); |
| 3593 | |
| 3594 | return Stream.concat( |
| 3595 | rpcInitialItems([ |
| 3596 | { |
| 3597 | version: 1 as const, |
| 3598 | revision: 1, |
| 3599 | type: "snapshot" as const, |
| 3600 | payload: initialSnapshot, |
| 3601 | }, |
| 3602 | ]), |
| 3603 | liveEvents, |
| 3604 | ); |
| 3605 | }), |
| 3606 | ), |
| 3607 | [WS_METHODS.subscribeResourceTelemetry]: (_input) => |
| 3608 | Stream.unwrap( |
| 3609 | Effect.map(resourceTelemetry.subscribe, ({ latest, changes }) => |
| 3610 | Stream.concat(Stream.make(latest), changes), |
| 3611 | ), |
| 3612 | ), |
| 3613 | }); |
| 3614 | const splitHandlers: Pick<typeof handlers, SplitWsRpc["_tag"]> = handlers; |
| 3615 | const otherHandlers: Pick<typeof handlers, Exclude<ServerWsRpc, SplitWsRpc>["_tag"]> = |
| 3616 | handlers; |
| 3617 | return Context.merge( |
| 3618 | yield* SplitWsRpcGroup.toHandlers(splitHandlers), |
| 3619 | yield* OtherWsRpcGroup.toHandlers(otherHandlers), |
| 3620 | ); |
| 3621 | }), |
| 3622 | ); |
| 3623 | |
| 3624 | // Default socket-level Defect frames end every pending client request. |
| 3625 | export const WS_RPC_SERVER_OPTIONS = { |
| 3626 | disableTracing: true, |
| 3627 | disableFatalDefects: true, |
| 3628 | } as const; |
| 3629 | |
| 3630 | export const layer = Layer.unwrap( |
| 3631 | Effect.gen(function* () { |
| 3632 | const serverBrowser = yield* ServerBrowser.ServerBrowser; |
| 3633 | const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate; |
| 3634 | const npmRelease = yield* NpmRelease.NpmRelease; |
| 3635 | const pullRequests = yield* PullRequestService.PullRequestService; |
| 3636 | const issues = yield* IssueService.IssueService; |
| 3637 | const threadIssues = yield* ThreadIssueService.ThreadIssueService; |
| 3638 | const issueTrackers = yield* IssueTrackerConnections.IssueTrackerConnections; |
| 3639 | const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService; |
| 3640 | const peerLinks = yield* PeerLinks.PeerLinks; |
| 3641 | const peerLinkRequests = yield* PeerLinkRequests.PeerLinkRequests; |
| 3642 | const peerThreadRelay = yield* PeerThreadRelay.PeerThreadRelay; |
| 3643 | const peerClientPairing = yield* PeerClientPairing.PeerClientPairing; |
| 3644 | const sql = yield* SqlClient.SqlClient; |
| 3645 | return HttpRouter.add( |
| 3646 | "GET", |
| 3647 | "/ws", |
| 3648 | Effect.gen(function* () { |
| 3649 | const request = yield* HttpServerRequest.HttpServerRequest; |
| 3650 | const url = requestUrl(request); |
| 3651 | if (Option.isNone(url) || !hasCompatibleOrchestrationProtocol(url.value)) { |
| 3652 | return HttpServerResponse.jsonUnsafe( |
| 3653 | { |
| 3654 | code: "orchestration_protocol_incompatible", |
| 3655 | message: `Update this client to one that supports orchestration protocol ${ORCHESTRATION_PROTOCOL_VERSION}.`, |
| 3656 | orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION, |
| 3657 | }, |
| 3658 | { status: 426 }, |
| 3659 | ); |
| 3660 | } |
| 3661 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 3662 | const sessions = yield* SessionStore.SessionStore; |
| 3663 | const analytics = yield* AnalyticsService.AnalyticsService; |
| 3664 | const session = yield* serverAuth.authenticateWebSocketUpgrade(request, "rpc").pipe( |
| 3665 | Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) => |
| 3666 | failEnvironmentAuthInvalid( |
| 3667 | EnvironmentAuth.serverAuthCredentialReason(error), |
| 3668 | EnvironmentAuth.serverAuthDpopFailureReason(error), |
| 3669 | ), |
| 3670 | ), |
| 3671 | Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) => |
| 3672 | failEnvironmentInternal("internal_error", error), |
| 3673 | ), |
| 3674 | ); |
| 3675 | // Desktop bootstrap sessions connect to their own backend, including same-machine WSL. |
| 3676 | if (session.subject === "desktop-bootstrap") { |
| 3677 | delete NodeHttpServerRequest.toIncomingMessage(request).headers[ |
| 3678 | "sec-websocket-extensions" |
| 3679 | ]; |
| 3680 | } |
| 3681 | const clientAnalyticsProps = readClientAnalyticsProps(request); |
| 3682 | yield* analytics.recordOwners(readClientOwners(request), "client"); |
| 3683 | const reportProfiles = yield* serverBrowser.profileReporter; |
| 3684 | const rpcWebSocketHttpEffect = yield* Effect.gen(function* () { |
| 3685 | const { protocol, httpEffect } = yield* RpcServer.makeProtocolWithHttpEffectWebsocket; |
| 3686 | yield* RpcServer.make(ServerWsRpcGroup, WS_RPC_SERVER_OPTIONS).pipe( |
| 3687 | Effect.provideService(RpcServer.Protocol, withOutputWindow(protocol)), |
| 3688 | Effect.provide( |
| 3689 | Layer.merge( |
| 3690 | RpcAuthorization.layer(session.scopes, (method, payload) => { |
| 3691 | // Anonymous product signal: the feature and its enum variant, |
| 3692 | // credited to the connecting client's surface only. |
| 3693 | const usage = featureUsage(method, payload); |
| 3694 | return usage === undefined |
| 3695 | ? Effect.void |
| 3696 | : analytics |
| 3697 | .record("feature.used", { |
| 3698 | ...usage, |
| 3699 | ...(clientAnalyticsProps.surface === undefined |
| 3700 | ? {} |
| 3701 | : { surface: clientAnalyticsProps.surface }), |
| 3702 | }) |
| 3703 | .pipe(Effect.ignore); |
| 3704 | }), |
| 3705 | rpcInstrumentationLayer, |
| 3706 | ), |
| 3707 | ), |
| 3708 | Effect.forkScoped, |
| 3709 | ); |
| 3710 | return httpEffect; |
| 3711 | }).pipe( |
| 3712 | Effect.provide( |
| 3713 | layerWsRpc( |
| 3714 | session, |
| 3715 | clientAnalyticsProps, |
| 3716 | serverBrowser, |
| 3717 | reportProfiles, |
| 3718 | readSettingsClient(url.value), |
| 3719 | ).pipe( |
| 3720 | Layer.provideMerge(RpcSerialization.layerJson), |
| 3721 | // Handler-context reporters see only request defects, not server-wide defects. |
| 3722 | Layer.provide(DefectReporter.layer), |
| 3723 | Layer.provide(AcpRegistrySessions.layer), |
| 3724 | Layer.provide(Layer.succeed(SqlClient.SqlClient, sql)), |
| 3725 | Layer.provide(ProviderMaintenanceRunner.layer), |
| 3726 | Layer.provide(Layer.succeed(NpmRelease.NpmRelease, npmRelease)), |
| 3727 | Layer.provide(Layer.succeed(ServerSelfUpdate.ServerSelfUpdate, serverSelfUpdate)), |
| 3728 | // Share server-lifetime PR caches so WS mutations invalidate every client's HTTP diffs. |
| 3729 | Layer.provide(Layer.succeed(PullRequestService.PullRequestService, pullRequests)), |
| 3730 | Layer.provide(Layer.succeed(IssueService.IssueService, issues)), |
| 3731 | Layer.provide(Layer.succeed(ThreadIssueService.ThreadIssueService, threadIssues)), |
| 3732 | Layer.provide( |
| 3733 | Layer.succeed(IssueTrackerConnections.IssueTrackerConnections, issueTrackers), |
| 3734 | ), |
| 3735 | Layer.provide(OtlpEndpointCheck.layer), |
| 3736 | Layer.provide( |
| 3737 | Layer.succeed( |
| 3738 | PullRequestReviewGuideService.PullRequestReviewGuideService, |
| 3739 | reviewGuides, |
| 3740 | ), |
| 3741 | ), |
| 3742 | Layer.provide(Layer.succeed(PeerLinks.PeerLinks, peerLinks)), |
| 3743 | Layer.provide(Layer.succeed(PeerLinkRequests.PeerLinkRequests, peerLinkRequests)), |
| 3744 | Layer.provide(Layer.succeed(PeerThreadRelay.PeerThreadRelay, peerThreadRelay)), |
| 3745 | Layer.provide(Layer.succeed(PeerClientPairing.PeerClientPairing, peerClientPairing)), |
| 3746 | Layer.provide( |
| 3747 | SourceControlDiscovery.layer.pipe( |
| 3748 | Layer.provide( |
| 3749 | SourceControlProviderRegistry.layer.pipe( |
| 3750 | Layer.provide(SourceControlBuiltInDrivers.layer), |
| 3751 | Layer.provideMerge(GitVcsDriver.layer), |
| 3752 | Layer.provide( |
| 3753 | VcsDriverRegistry.layer.pipe(Layer.provide(VcsProjectConfig.layer)), |
| 3754 | ), |
| 3755 | ), |
| 3756 | ), |
| 3757 | ), |
| 3758 | ), |
| 3759 | ), |
| 3760 | ), |
| 3761 | ); |
| 3762 | const framedRpcWebSocketHttpEffect = url.value.searchParams.has( |
| 3763 | SOCKET_FRAME_PARTS_QUERY_PARAM, |
| 3764 | ) |
| 3765 | ? rpcWebSocketHttpEffect.pipe( |
| 3766 | Effect.provideService( |
| 3767 | HttpServerRequest.HttpServerRequest, |
| 3768 | // The RPC server upgrades the request itself, so its socket is |
| 3769 | // wrapped through the request it reads. |
| 3770 | Object.create(request, { |
| 3771 | upgrade: { value: Effect.map(request.upgrade, splitLargeSocketFrames) }, |
| 3772 | }), |
| 3773 | ), |
| 3774 | ) |
| 3775 | : rpcWebSocketHttpEffect; |
| 3776 | return yield* Effect.acquireUseRelease( |
| 3777 | sessions.markConnected(session.sessionId), |
| 3778 | () => |
| 3779 | Effect.raceFirst( |
| 3780 | framedRpcWebSocketHttpEffect, |
| 3781 | sessions.awaitInvalidation(session.sessionId, session.proofKeyThumbprint).pipe( |
| 3782 | Effect.as(HttpServerResponse.empty()), |
| 3783 | Effect.catchTags({ |
| 3784 | SessionCredentialVerificationError: (error) => |
| 3785 | failEnvironmentInternal("internal_error", error), |
| 3786 | }), |
| 3787 | ), |
| 3788 | ), |
| 3789 | () => sessions.markDisconnected(session.sessionId), |
| 3790 | ); |
| 3791 | }).pipe( |
| 3792 | Effect.catchTags({ |
| 3793 | EnvironmentAuthInvalidError: HttpServerRespondable.toResponse, |
| 3794 | EnvironmentInternalError: HttpServerRespondable.toResponse, |
| 3795 | }), |
| 3796 | ), |
| 3797 | ); |
| 3798 | }), |
| 3799 | ).pipe(Layer.provide(NpmRelease.layer)); |