Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

server.ts

1,032 lines45.0 KB

1import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay";
2import * as Clock from "effect/Clock";
3import * as Random from "effect/Random";
4import * as Semaphore from "effect/Semaphore";
5import * as StorageCleanup from "./storageCleanup.ts";
6import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts";
7// @effect-diagnostics nodeBuiltinImport:off
8import * as NodeHttp from "node:http";
9​
10import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
11import * as NodeServices from "@effect/platform-node/NodeServices";
12import { EnvironmentHttpApi, type RepositoryIdentity } from "@t3tools/contracts";
13import * as Cause from "effect/Cause";
14import * as Duration from "effect/Duration";
15import * as Deferred from "effect/Deferred";
16import * as Effect from "effect/Effect";
17import * as Layer from "effect/Layer";
18import * as Stream from "effect/Stream";
19import * as Schedule from "effect/Schedule";
20import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http";
21import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
22​
23import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
24import * as HostPowerMonitor from "./background/HostPowerMonitor.ts";
25import * as ServerConfig from "./config.ts";
26import {
27 otlpTracesProxyRouteLayer,
28 assetRouteLayer,
29 attachmentUploadRouteLayer,
30 serverEnvironmentHttpApiLayer,
31 staticAndDevRouteLayer,
32 browserApiCorsLayer,
33 httpCompressionLayer,
34 untracedRequestsLayer,
35} from "./http.ts";
36import { guardHttpResponseWriteErrors } from "./httpResponseErrorGuard.ts";
37import { fixPath } from "./os-jank.ts";
38import { websocketRpcRouteLayer } from "./ws.ts";
39import * as ExternalLauncher from "./process/externalLauncher.ts";
40import * as NodePtyAdapter from "./terminal/NodePtyAdapter.ts";
41import { pullRequestHttpApiLayer } from "./pullRequest/http.ts";
42import * as PullRequestProviderRegistry from "./pullRequest/PullRequestProviderRegistry.ts";
43import * as PullRequestService from "./pullRequest/PullRequestService.ts";
44import * as SqlitePersistence from "./persistence/Layers/Sqlite.ts";
45import * as PullRequestFilesViewed from "./persistence/PullRequestFilesViewed.ts";
46import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
47import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
48import * as ProviderEventIngestor from "./orchestration-v2/ProviderEventIngestor.ts";
49import * as ModelManifest from "./provider/ModelManifest.ts";
50import * as ResetCreditCoordinator from "./provider/Layers/resetCreditCoordinator.ts";
51import * as ProviderEventLoggers from "./provider/Layers/ProviderEventLoggers.ts";
52import * as OpenCodeRuntime from "./provider/opencodeRuntime.ts";
53import * as OpenCodeServerLedger from "./provider/OpenCodeServerLedger.ts";
54import { AcpRegistryCatalogLive } from "./provider/Layers/AcpRegistryCatalog.ts";
55import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
56import * as CheckpointStore from "./checkpointing/CheckpointStore.ts";
57import * as AzureDevOpsCli from "./sourceControl/AzureDevOpsCli.ts";
58import * as BitbucketApi from "./sourceControl/BitbucketApi.ts";
59import * as GitHubCli from "./sourceControl/GitHubCli.ts";
60import * as GitLabCli from "./sourceControl/GitLabCli.ts";
61import * as ForgejoCli from "./sourceControl/ForgejoCli.ts";
62import * as TextGeneration from "./textGeneration/TextGeneration.ts";
63import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/ProviderInstanceRegistryHydration.ts";
64import * as TerminalManager from "./terminal/Manager.ts";
65import * as McpHttpServer from "./mcp/McpHttpServer.ts";
66import * as McpSessionRegistry from "./mcp/McpSessionRegistry.ts";
67import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
68import * as DeviceService from "./device/DeviceService.ts";
69import { deviceHubProxyRouteLayer } from "./device/DeviceHubProxy.ts";
70import * as PreviewManager from "./preview/Manager.ts";
71import * as PortScanner from "./preview/PortScanner.ts";
72import * as ProcessRunner from "./processRunner.ts";
73import * as GitManager from "./git/GitManager.ts";
74import * as EnvironmentTheme from "./environmentTheme.ts";
75import * as Keybindings from "./keybindings.ts";
76import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
77import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
78import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
79import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry.ts";
80import * as ServerSettings from "./serverSettings.ts";
81import * as ProjectEnrichmentService from "./project/ProjectEnrichmentService.ts";
82import * as NativeAppIconResolver from "./assets/NativeAppIconResolver.ts";
83import * as AntigravityInstallation from "./provider/AntigravityInstallation.ts";
84import * as CodexInstallation from "./provider/CodexInstallation.ts";
85import * as ProviderInstanceRegistry from "./provider/Services/ProviderInstanceRegistry.ts";
86import * as ProviderAdapterRegistry from "./orchestration-v2/ProviderAdapterRegistry.ts";
87import * as ProviderRegistry from "./provider/Services/ProviderRegistry.ts";
88import { ProviderUsageLimitsIngestionLive } from "./provider/Layers/ProviderUsageLimitsIngestion.ts";
89import * as UsageLimitSources from "./usage/UsageLimitSources.ts";
90import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts";
91import * as T3ProjectFileLoader from "./project/T3ProjectFileLoader.ts";
92import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
93import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
94import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
95import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
96import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
97import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";
98import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";
99import * as VcsProcess from "./vcs/VcsProcess.ts";
100import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
101import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
102import * as ProjectCloneTracker from "./project/ProjectCloneTracker.ts";
103import * as GitWorkflowService from "./git/GitWorkflowService.ts";
104import * as ReviewService from "./review/ReviewService.ts";
105import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
106import * as PullRequestReadCache from "./pullRequest/PullRequestReadCache.ts";
107import * as SourceControlRateLimit from "./sourceControl/SourceControlRateLimit.ts";
108import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
109import * as WorktreeSetupTracker from "./project/WorktreeSetupTracker.ts";
110import { ObservabilityLive } from "./observability/Layers/Observability.ts";
111import * as HeapSnapshot from "./observability/HeapSnapshot.ts";
112import * as EventLoopMonitor from "./observability/EventLoopMonitor.ts";
113import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
114import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";
115import { authHttpApiLayer, environmentAuthenticatedAuthLayer } from "./auth/http.ts";
116import * as ReplayMarkers from "./auth/replayMarkers.ts";
117import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
118import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
119import {
120 connectHttpApiLayer,
121 pendingServiceUpdateExists,
122 reconcileDesiredCloudLinkIfStillDesired,
123 recoverManagedCloudTunnel,
124 registerManagedCloudTunnelRecovery,
125 startManagedCloudTunnelIfOriginConfirmed,
126 releaseManagedTunnelOnShutdown,
127} from "./cloud/http.ts";
128import { serverRelayBrokerTracingLayer } from "./cloud/relayTracing.ts";
129import { shouldRetryCloudLink } from "./cloud/relayResponse.ts";
130import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts";
131import {
132 MANAGED_TUNNEL_FIRST_REGISTRATION_JITTER,
133 MANAGED_TUNNEL_RECOVERY_COOLDOWN,
134 managedTunnelStartupAction,
135 retryManagedTunnelRegistration,
136} from "./cloud/managedTunnelStartup.ts";
137import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts";
138import * as CloudCliState from "./cloud/CliState.ts";
139import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
140import * as DesktopAppUpdate from "./desktopUpdate/DesktopAppUpdate.ts";
141import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
142import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
143import * as HostResources from "./resourceTelemetry/HostResources.ts";
144import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
145import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
146import * as DesktopTelemetryReceiver from "./resourceTelemetry/DesktopTelemetryReceiver.ts";
147import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClient.ts";
148import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts";
149import * as ResourceMonitorBinary from "./resourceTelemetry/ResourceMonitorBinary.ts";
150import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
151import * as UsageService from "./usage/UsageService.ts";
152import {
153 OrchestrationEventInfrastructureLayerLive,
154 OrchestrationV2ProductionLayerLive,
155 ProjectServiceLayerLive,
156 ProjectSetupScriptRunnerLayerLive,
157} from "./orchestration-v2/runtimeLayer.ts";
158import * as ProjectStore from "./orchestration-v2/ProjectStore.ts";
159import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts";
160import * as ResourceCleanupService from "./orchestration-v2/ResourceCleanupService.ts";
161import * as ThreadSettlementService from "./orchestration-v2/ThreadSettlementService.ts";
162import * as ThreadPullRequestService from "./orchestration-v2/ThreadPullRequestService.ts";
163import * as RunFinalizationService from "./orchestration-v2/RunFinalizationService.ts";
164import * as ProjectionStoreV2 from "./orchestration-v2/ProjectionStore.ts";
165import {
166 clearPersistedServerRuntimeState,
167 makePersistedServerRuntimeState,
168 persistServerRuntimeState,
169} from "./serverRuntimeState.ts";
170import { orchestrationHttpApiLayer } from "./orchestration-v2/http.ts";
171import { projectHttpApiLayer } from "./project/http.ts";
172import * as NetService from "@t3tools/shared/Net";
173import * as RelayClient from "@t3tools/shared/relayClient";
174import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale";
175import * as ServerActivation from "./serverActivation.ts";
176​
177// MCP handoff thread IDs include escaped provenance and can exceed find-my-way's
178// 100-character default for one path segment.
179const HTTP_ROUTER_CONFIG = {
180 maxParamLength: 512,
181} as const;
182​
183// Effect's default preemptive shutdown waits 20s before finalizing request scopes.
184// T3's primary transport is long-lived WebSocket RPC, whose Effect scope finalizer
185// already closes the websocket gracefully. Do not add an artificial drain before
186// those finalizers get a chance to run.
187const HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS = 0;
188const ResourceAttributionLayerLive = ResourceAttribution.layer;
189const ApplicationObservabilityLive = EventLoopMonitor.layer.pipe(
190 Layer.provideMerge(ObservabilityLive),
191 Layer.provideMerge(ResourceAttributionLayerLive),
192);
193​
194const PtyAdapterLive = NodePtyAdapter.layer;
195​
196const ServerSettingsLayerLive = ServerSettings.layer.pipe(
197 Layer.provide(ServerSecretStore.layer),
198 Layer.provideMerge(SqlitePersistence.layerConfig),
199);
200​
201const NativeTelemetryLayerLive = NativeTelemetryClient.layer.pipe(
202 Layer.provide(ResourceMonitorBinary.layer),
203);
204const DesktopTelemetryReceiverLayerLive = DesktopTelemetryReceiver.layer.pipe(
205 Layer.provideMerge(ServerSettingsLayerLive),
206);
207​
208const ResourceTelemetryLayerLive = ResourceTelemetry.layer.pipe(
209 Layer.provideMerge(NativeTelemetryLayerLive),
210 Layer.provideMerge(DesktopTelemetryReceiverLayerLive),
211);
212​
213const HostPowerMonitorLayerLive = HostPowerMonitor.layer.pipe(
214 Layer.provide(DesktopTelemetryReceiverLayerLive),
215);
216​
217// Reuses DesktopTelemetryReceiverLayerLive: a fresh receiver layer here
218// would open a second reader on the desktop telemetry fd.
219const DesktopAppUpdateLayerLive = DesktopAppUpdate.layer.pipe(
220 Layer.provide(DesktopTelemetryReceiverLayerLive),
221);
222​
223const BackgroundLayerLive = BackgroundPolicy.layer.pipe(
224 Layer.provide(HostPowerMonitorLayerLive),
225 Layer.provideMerge(ServerSettingsLayerLive),
226);
227​
228const UsageLayerLive = UsageService.layer.pipe(Layer.provide(ServerSettingsLayerLive));
229​
230const ResourceDiagnosticsLayerLive = Layer.mergeAll(
231 HostResources.layer,
232 ResourceTelemetryLayerLive,
233 ProcessDiagnostics.layer.pipe(Layer.provide(ResourceTelemetryLayerLive)),
234 ProcessResourceMonitor.layer.pipe(Layer.provide(ResourceTelemetryLayerLive)),
235);
236​
237const RelayClientLive = Layer.unwrap(
238 Effect.gen(function* () {
239 const config = yield* ServerConfig.ServerConfig;
240 return RelayClient.layerCloudflared({ baseDir: config.baseDir });
241 }),
242);
243​
244const HttpServerLive = Layer.unwrap(
245 Effect.gen(function* () {
246 const config = yield* ServerConfig.ServerConfig;
247 return NodeHttpServer.layer(() => guardHttpResponseWriteErrors(NodeHttp.createServer()), {
248 host: config.host ?? "127.0.0.1",
249 port: config.port,
250 gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
251 // Negotiate permessage-deflate with clients that offer it; clients
252 // that don't still get uncompressed frames on their connection.
253 // Context takeover stays enabled (ws default) so the compression
254 // window is shared across frames — that also makes small frames cheap
255 // to compress, so no size threshold is set (ws only honors
256 // `threshold` when context takeover is disabled).
257 websocket: { perMessageDeflate: true },
258 });
259 }),
260);
261​
262const PlatformServicesLive = NodeServices.layer;
263​
264const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistence.layerConfig));
265​
266const VcsDriverRegistryLayerLive = VcsDriverRegistry.layer.pipe(
267 Layer.provide(VcsProjectConfig.layer),
268);
269​
270const SourceControlProviderRegistryLayerLive = SourceControlProviderRegistry.layer.pipe(
271 Layer.provide(
272 Layer.mergeAll(
273 AzureDevOpsCli.layer,
274 BitbucketApi.layer,
275 GitHubCli.layer,
276 GitLabCli.layer,
277 ForgejoCli.layer,
278 ),
279 ),
280 Layer.provideMerge(GitVcsDriver.layer),
281 Layer.provideMerge(VcsDriverRegistryLayerLive),
282);
283​
284const RepositoryIdentityResolverLayerLive = Layer.effect(
285 RepositoryIdentityResolver.RepositoryIdentityResolver,
286 Effect.gen(function* () {
287 const registry = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
288 return yield* RepositoryIdentityResolver.make({
289 refine: Effect.fn(function* (identity: RepositoryIdentity) {
290 const remote = ForgejoCli.parseForgejoRemote(identity.locator.remoteUrl);
291 if (
292 !remote ||
293 !identity.rootPath ||
294 (identity.provider !== undefined &&
295 identity.provider !== "unknown" &&
296 identity.provider !== "forgejo")
297 )
298 return identity;
299 const handle = yield* registry.resolveHandle({
300 cwd: identity.rootPath,
301 context: {
302 provider: { kind: "unknown", name: "Unknown", baseUrl: "" },
303 remoteName: identity.locator.remoteName,
304 remoteUrl: identity.locator.remoteUrl,
305 },
306 });
307 if (handle.context?.provider.kind !== "forgejo") return identity;
308 const baseUrl = handle.context.provider.baseUrl.replace(/\/+$/, "");
309 const basePath = new URL(baseUrl).pathname.replace(/^\/+|\/+$/g, "");
310 const path =
311 !remote.ssh && basePath && remote.path.startsWith(`${basePath}/`)
312 ? remote.path.slice(basePath.length + 1)
313 : remote.path;
314 return { ...identity, provider: "forgejo", webUrl: `${baseUrl}/${path}` };
315 }),
316 });
317 }),
318).pipe(Layer.provide(SourceControlProviderRegistryLayerLive), Layer.provide(ProcessRunner.layer));
319​
320const PullRequestServiceLive = PullRequestService.layer.pipe(
321 Layer.provide(PullRequestProviderRegistry.layer),
322 // Where the viewed-file marks live for a host that keeps none of its own.
323 Layer.provide(PullRequestFilesViewed.layer),
324 Layer.provide(PullRequestReadCache.layer),
325 Layer.provide(SourceControlProviderRegistryLayerLive),
326 Layer.provide(SourceControlRateLimit.layer),
327);
328​
329const GitManagerLayerLive = GitManager.layer.pipe(
330 // Per-project git settings resolve the acting thread's project.
331 Layer.provide(Layer.merge(ProjectionStoreV2.layer, ProjectStore.layer)),
332 Layer.provideMerge(ProjectSetupScriptRunnerLayerLive),
333 Layer.provideMerge(WorktreeSetupTracker.layer),
334 Layer.provideMerge(GitVcsDriver.layer),
335 Layer.provideMerge(SourceControlProviderRegistryLayerLive),
336 Layer.provideMerge(
337 TextGeneration.layer.pipe(Layer.provide(SourceControlProviderRegistryLayerLive)),
338 ),
339);
340​
341const GitLayerLive = Layer.empty.pipe(
342 Layer.provideMerge(GitManagerLayerLive),
343 Layer.provideMerge(GitVcsDriver.layer),
344);
345​
346const GitWorkflowLayerLive = GitWorkflowService.layer.pipe(
347 Layer.provideMerge(VcsDriverRegistryLayerLive),
348 Layer.provideMerge(GitLayerLive),
349);
350​
351const SourceControlRepositoryServiceLayerLive = SourceControlRepositoryService.layer.pipe(
352 Layer.provideMerge(GitVcsDriver.layer),
353 Layer.provideMerge(SourceControlProviderRegistryLayerLive),
354);
355​
356const ProjectCloneTrackerLayerLive = ProjectCloneTracker.layer.pipe(
357 Layer.provide(SourceControlRepositoryServiceLayerLive),
358);
359​
360const ReviewLayerLive = ReviewService.layer.pipe(
361 Layer.provideMerge(GitVcsDriver.layer),
362 Layer.provideMerge(VcsDriverRegistryLayerLive),
363);
364​
365const VcsLayerLive = Layer.empty.pipe(
366 Layer.provideMerge(VcsProjectConfig.layer),
367 Layer.provideMerge(VcsDriverRegistryLayerLive),
368 Layer.provideMerge(VcsProvisioningService.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
369 Layer.provideMerge(GitWorkflowLayerLive),
370 Layer.provideMerge(ReviewLayerLive),
371 Layer.provideMerge(SourceControlRepositoryServiceLayerLive),
372 Layer.provideMerge(ProjectCloneTrackerLayerLive),
373 Layer.provideMerge(
374 VcsStatusBroadcaster.layer.pipe(
375 Layer.provide(GitWorkflowLayerLive),
376 // Auto-pull reads the project row. The orchestration runtime also
377 // consumes the broadcaster (run finalization), so the policy cannot read
378 // the store from the runtime's output.
379 Layer.provide(
380 VcsStatusBroadcaster.autoPullPolicyLayer.pipe(Layer.provide(ProjectStore.layer)),
381 ),
382 ),
383 ),
384);
385​
386const CheckpointStoreLayerLive = CheckpointStore.layer.pipe(
387 Layer.provide(VcsDriverRegistryLayerLive),
388);
389​
390const PortScannerLayerLive = PortScanner.layer.pipe(Layer.provide(ProcessRunner.layer));
391​
392const TerminalLayerLive = TerminalManager.layer.pipe(
393 Layer.provide(PtyAdapterLive),
394 Layer.provide(PortScannerLayerLive),
395 Layer.provide(NativeTelemetryLayerLive),
396);
397​
398const PreviewLayerLive = Layer.empty.pipe(
399 Layer.provideMerge(PreviewManager.layer),
400 Layer.provideMerge(PortScannerLayerLive),
401);
402​
403const DeviceLayerLive = DeviceService.layer.pipe(
404 Layer.provide(ServerSettingsLayerLive),
405 Layer.provide(ProcessRunner.layer),
406 Layer.provide(NetService.layer),
407);
408​
409const WorkspaceEntriesLayerLive = WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePaths.layer));
410​
411const WorkspaceFileSystemLayerLive = WorkspaceFileSystem.layer.pipe(
412 Layer.provide(WorkspacePaths.layer),
413 Layer.provide(WorkspaceEntriesLayerLive),
414);
415​
416const WorkspaceLayerLive = Layer.mergeAll(
417 WorkspacePaths.layer,
418 WorkspaceEntriesLayerLive,
419 WorkspaceFileSystemLayerLive,
420);
421​
422const ProjectFaviconResolverLayerLive = ProjectFaviconResolver.layer.pipe(
423 Layer.provide(WorkspacePaths.layer),
424 Layer.provide(T3ProjectFileLoader.layer),
425);
426​
427const ServerEnvironmentLayerLive = ServerEnvironment.layer.pipe(
428 Layer.provide(ServerSecretStore.layer),
429);
430​
431const AuthLayerLive = EnvironmentAuth.layer.pipe(
432 Layer.provideMerge(PersistenceLayerLive),
433 Layer.provide(ServerEnvironmentLayerLive),
434 Layer.provide(ServerSecretStore.layer),
435);
436​
437const CloudManagedEndpointRuntimeLive = Layer.mergeAll(
438 RelayClientLive,
439 CloudManagedEndpointRuntime.layer.pipe(
440 Layer.provide(ServerSecretStore.layer),
441 Layer.provide(RelayClientLive),
442 ),
443);
444​
445const OrchestrationV2RuntimeLayerLive = OrchestrationV2ProductionLayerLive.pipe(
446 Layer.provide(ProviderEventIngestor.analyticsLive),
447 Layer.provide(CheckpointStoreLayerLive),
448 Layer.provide(GitWorkflowLayerLive),
449 Layer.provide(ResourceCleanupService.live),
450 Layer.provide(
451 RunFinalizationService.observerLive.pipe(
452 Layer.provide(ProjectionStoreV2.layer),
453 Layer.provide(PullRequestServiceLive),
454 Layer.provide(ProjectServiceLayerLive),
455 ),
456 ),
457);
458​
459const OrchestrationApplicationLayerLive = CheckpointDiffQuery.layer.pipe(
460 Layer.provideMerge(CheckpointStoreLayerLive),
461 Layer.provideMerge(OrchestrationV2RuntimeLayerLive),
462);
463​
464// Automatic thread settlement (#8600): a server-owned sweep evaluates
465// inactivity and merged pull requests, then settles through the orchestrator
466// so every client sees the same shelf.
467const ThreadSettlementWorkerLive = Layer.effectDiscard(
468 ThreadSettlementService.make.pipe(Effect.flatMap((service) => service.start())),
469).pipe(Layer.provide(PullRequestServiceLive), Layer.provide(ProjectionStoreV2.layer));
470​
471const ThreadPullRequestWorkerLive = Layer.effectDiscard(
472 ThreadPullRequestService.make.pipe(Effect.flatMap((service) => service.start())),
473).pipe(Layer.provide(PullRequestServiceLive));
474​
475const ProviderInstallationRefreshLive = Layer.effectDiscard(
476 Effect.gen(function* () {
477 const antigravity = yield* AntigravityInstallation.AntigravityInstallation;
478 const codex = yield* CodexInstallation.CodexInstallation;
479 const instances = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
480 const providers = yield* ProviderRegistry.ProviderRegistry;
481 yield* Stream.merge(
482 antigravity.changes.pipe(
483 Stream.changesWith((a, b) => a.installedVersion === b.installedVersion),
484 Stream.drop(1),
485 ),
486 codex.changes.pipe(
487 Stream.changesWith((a, b) => a.installedVersion === b.installedVersion),
488 Stream.drop(1),
489 ),
490 ).pipe(
491 Stream.runForEach((state) =>
492 instances.listInstances.pipe(
493 Effect.flatMap((entries) =>
494 Effect.forEach(
495 entries.filter((instance) => instance.driverKind === state.driver),
496 (instance) => providers.refreshInstance(instance.instanceId),
497 { discard: true },
498 ),
499 ),
500 ),
501 ),
502 Effect.forkScoped,
503 );
504 }),
505);
506​
507const RuntimeCoreDependenciesBaseLive = Layer.mergeAll(
508 AgentAwarenessRelay.layer,
509 ThreadSettlementWorkerLive,
510 Layer.effectDiscard(StorageCleanup.make.pipe(Effect.flatMap((service) => service.start()))).pipe(
511 Layer.provide(ProjectionStoreV2.layer),
512 ),
513 ThreadPullRequestWorkerLive,
514 Layer.effectDiscard(
515 Effect.gen(function* () {
516 const service = yield* PullRequestSyncReactor.PullRequestSyncReactor;
517 yield* service.start();
518 }),
519 ).pipe(
520 Layer.provideMerge(PullRequestSyncReactor.layer),
521 Layer.provide(PullRequestServiceLive),
522 Layer.provide(ProjectionStoreV2.layer),
523 ),
524 // Subscribes to `account.rate-limits.updated` so usage bars track live
525 // telemetry instead of waiting for the next status probe.
526 ProviderUsageLimitsIngestionLive,
527 ProviderInstallationRefreshLive,
528 ReplayMarkers.layer,
529).pipe(
530 // Core Services
531 Layer.provideMerge(OrchestrationApplicationLayerLive),
532 Layer.provideMerge(OrchestrationEventInfrastructureLayerLive),
533 Layer.provideMerge(Layer.merge(ProjectStore.layer, ThreadSearch.layer)),
534 Layer.provideMerge(ServerSettingsLayerLive),
535 // The asset route uses the registry's GitHub credential for private PR media.
536 Layer.provideMerge(Layer.mergeAll(SourceControlProviderRegistryLayerLive, GitHubCli.layer)),
537 Layer.provideMerge(GitLayerLive),
538 Layer.provideMerge(VcsLayerLive),
539 Layer.provideMerge(Layer.mergeAll(TerminalLayerLive, PreviewLayerLive, DeviceLayerLive)),
540 Layer.provideMerge(PersistenceLayerLive),
541 // Both read a user-owned file out of the state directory and stream changes
542 // to clients; neither depends on the other.
543 Layer.provideMerge(
544 Layer.mergeAll(Keybindings.layer, EnvironmentTheme.layer, UsageLimitSources.layer),
545 ),
546 Layer.provideMerge(ProviderRegistryLive),
547 // The instance registry is the new routing keystone — text generation,
548 // adapter lookup, and runtime ingestion all resolve `ProviderInstanceId`
549 // through this layer. Built-in drivers come from `BUILT_IN_DRIVERS`;
550 // `providerInstances` hydration merges `settings.providers.<kind>`
551 // with explicit `providerInstances` entries on boot.
552 Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
553 Layer.provideMerge(
554 Layer.mergeAll(
555 AntigravityInstallation.AntigravityInstallation.layer,
556 CodexInstallation.CodexInstallation.layer,
557 ),
558 ),
559);
560​
561const RuntimeCoreDependenciesLive = RuntimeCoreDependenciesBaseLive.pipe(
562 Layer.provideMerge(PtyAdapterLive),
563 // Search, prepare, status inspection, and turn launch share one registry
564 // cache so every client and provider instance sees the same prepared agents.
565 Layer.provideMerge(AcpRegistryCatalogLive),
566 // Shared native/canonical NDJSON writers used by both the per-instance
567 // V2 drivers and the orchestration runtime. Provide resource attribution so
568 // the rewritten telemetry pipeline can account for logical NDJSON writes.
569 // Provided once at the runtime level so every consumer sees the same
570 // logger instances.
571 // `ModelManifest.layer` is the legacy-model classification data, refreshed
572 // from the repo's `model-manifest.json` on `main` and applied by the
573 // Codex/Claude drivers.
574 Layer.provideMerge(
575 Layer.mergeAll(ProviderEventLoggers.layer, ModelManifest.layer, ResetCreditCoordinator.layer),
576 ),
577 // `OpenCodeDriver.create()` yields `OpenCodeRuntime`; previously the old
578 // `ProviderRegistryLive` pulled `OpenCodeRuntimeLive` in for itself, but
579 // the rewritten registry reads snapshots off the instance registry and
580 // no longer transitively provides it. Exposing it at the runtime level
581 // keeps a single Live for all opencode consumers.
582 Layer.provideMerge(
583 OpenCodeRuntime.OpenCodeRuntimeLive.pipe(Layer.provide(OpenCodeServerLedger.layer)),
584 ),
585 Layer.provideMerge(WorkspaceLayerLive),
586 Layer.provideMerge(ProjectEnrichmentService.layer),
587 Layer.provideMerge(Layer.mergeAll(NativeAppIconResolver.layer, ProjectFaviconResolverLayerLive)),
588 Layer.provideMerge(RepositoryIdentityResolverLayerLive),
589 Layer.provideMerge(ServerEnvironmentLayerLive),
590 Layer.provideMerge(AuthLayerLive),
591 Layer.provideMerge(ServerSecretStore.layer),
592 Layer.provideMerge(
593 Layer.mergeAll(
594 CloudCliTokenManager.layer.pipe(
595 Layer.provide(ServerSecretStore.layer),
596 Layer.provide(ExternalLauncher.layer),
597 ),
598 CloudManagedEndpointRuntimeLive,
599 ),
600 ),
601);
602​
603const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
604 // Misc.
605 Layer.provideMerge(BackgroundLayerLive),
606 Layer.provideMerge(ResourceDiagnosticsLayerLive),
607 Layer.provideMerge(UsageLayerLive),
608 Layer.provideMerge(TraceDiagnostics.layer),
609 Layer.provideMerge(AnalyticsService.layer),
610 Layer.provideMerge(ExternalLauncher.layer),
611 Layer.provideMerge(RemoteOpenTargets.layer),
612 Layer.provideMerge(ServerLifecycleEvents.layer),
613 Layer.provide(NetService.layer),
614);
615​
616const commandReadinessLayer = HttpRouter.middleware(
617 (httpEffect) =>
618 Effect.flatMap(ServerRuntimeStartup.ServerRuntimeStartup, (startup) =>
619 startup.awaitCommandReady.pipe(Effect.orDie, Effect.andThen(httpEffect)),
620 ),
621 { global: true },
622);
623​
624const makeRoutesLayer = Layer.mergeAll(
625 Layer.mergeAll(
626 HttpApiBuilder.layer(EnvironmentHttpApi).pipe(
627 Layer.provide(authHttpApiLayer),
628 Layer.provide(connectHttpApiLayer),
629 Layer.provide(orchestrationHttpApiLayer),
630 Layer.provide(pullRequestHttpApiLayer),
631 Layer.provide(projectHttpApiLayer),
632 Layer.provide(serverEnvironmentHttpApiLayer),
633 Layer.provide(environmentAuthenticatedAuthLayer),
634 ),
635 otlpTracesProxyRouteLayer,
636 assetRouteLayer,
637 attachmentUploadRouteLayer,
638 deviceHubProxyRouteLayer,
639 staticAndDevRouteLayer,
640 websocketRpcRouteLayer,
641 ),
642 // The MCP session registry is provided globally (shared with V2 provider
643 // sessions) rather than inline here. The orchestrator toolkit resolves
644 // delegation targets through the same live adapter facade the V2
645 // orchestrator uses, so MCP capability reporting can never drift from
646 // what dispatch can actually serve.
647 McpHttpServer.layer.pipe(
648 Layer.provide(ProviderAdapterRegistry.layerFromProviderInstanceRegistry),
649 ),
650 // Last, so no route layer can replace the server's one TracerDisabledWhen.
651 untracedRequestsLayer,
652).pipe(
653 // Both transports consume the same service instance, so caches single-flight across clients
654 // and mutations observed on WebSocket invalidate patches subsequently read over HTTP.
655 Layer.provide(PullRequestServiceLive),
656 Layer.provide(PreviewAutomationBroker.layer),
657 Layer.provide(ServerSelfUpdate.layer.pipe(Layer.provide(DesktopAppUpdateLayerLive))),
658 Layer.provide(commandReadinessLayer),
659 Layer.provide(browserApiCorsLayer),
660 Layer.provide(httpCompressionLayer),
661);
662​
663const makeServerLayer = Layer.unwrap(
664 Effect.gen(function* () {
665 const config = yield* ServerConfig.ServerConfig;
666 const activation = yield* Deferred.make<void>();
667 const awaitActivation = Deferred.await(activation);
668 const activationLayer = Layer.succeed(ServerActivation.ServerActivation, awaitActivation);
669 const runtimeStateParked = yield* Deferred.make<void>();
670 const tailscaleParked = yield* Deferred.make<void>();
671 const cloudLinkParked = yield* Deferred.make<void>();
672 const routesReady = yield* Deferred.make<void>();
673 const launcherLayer = ServiceLauncherClient.layer;
674​
675 yield* fixPath();
676​
677 const httpListeningLayer = Layer.effectDiscard(
678 Effect.gen(function* () {
679 yield* HttpServer.HttpServer;
680 const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
681 yield* startup.markHttpListening;
682 }),
683 );
684 const runtimeStateLayer = Layer.effectDiscard(
685 Effect.acquireRelease(
686 Effect.gen(function* () {
687 yield* Deferred.succeed(runtimeStateParked, undefined).pipe(Effect.orDie);
688 yield* awaitActivation;
689 const server = yield* HttpServer.HttpServer;
690 const address = server.address;
691 if (typeof address === "string" || !("port" in address)) {
692 return;
693 }
694​
695 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
696 const state = yield* makePersistedServerRuntimeState({
697 config,
698 port: address.port,
699 serviceManaged: launcher.managed,
700 });
701 yield* persistServerRuntimeState({
702 path: config.serverRuntimeStatePath,
703 state,
704 }).pipe(
705 Effect.catchCause((cause) =>
706 Effect.logWarning("Failed to persist server runtime state", { cause }),
707 ),
708 );
709 }),
710 () =>
711 clearPersistedServerRuntimeState(config.serverRuntimeStatePath).pipe(
712 Effect.catchCause((cause) =>
713 Effect.logWarning("Failed to clear server runtime state", { cause }),
714 ),
715 ),
716 ),
717 );
718 const tailscaleServeLayer = config.tailscaleServeEnabled
719 ? Layer.effectDiscard(
720 Effect.acquireRelease(
721 Effect.gen(function* () {
722 yield* Deferred.succeed(tailscaleParked, undefined).pipe(Effect.orDie);
723 yield* awaitActivation;
724 const server = yield* HttpServer.HttpServer;
725 const address = server.address;
726 if (typeof address === "string" || !("port" in address)) {
727 return null;
728 }
729​
730 const localPort = address.port;
731 return yield* ensureTailscaleServe({
732 localPort,
733 servePort: config.tailscaleServePort,
734 localHost: "127.0.0.1",
735 }).pipe(
736 Effect.as({ localPort, servePort: config.tailscaleServePort }),
737 Effect.tap(() =>
738 Effect.logInfo("Tailscale Serve configured", {
739 localPort,
740 servePort: config.tailscaleServePort,
741 }),
742 ),
743 Effect.catch((cause) =>
744 Effect.logWarning("Failed to configure Tailscale Serve", {
745 cause,
746 localPort,
747 servePort: config.tailscaleServePort,
748 }).pipe(Effect.as(null)),
749 ),
750 );
751 }),
752 (configured) =>
753 configured
754 ? disableTailscaleServe({ servePort: configured.servePort }).pipe(
755 Effect.tap(() =>
756 Effect.logInfo("Tailscale Serve disabled", {
757 servePort: configured.servePort,
758 }),
759 ),
760 Effect.catch((cause) =>
761 Effect.logWarning("Failed to disable Tailscale Serve", {
762 cause,
763 servePort: configured.servePort,
764 }),
765 ),
766 )
767 : Effect.void,
768 ),
769 )
770 : Layer.empty;
771 const cloudDesiredLinkReconcileLayer = Layer.effectDiscard(
772 Effect.gen(function* () {
773 const releaseManagedTunnel = releaseManagedTunnelOnShutdown().pipe(
774 Effect.timeout("10 seconds"),
775 Effect.tap((released) =>
776 released ? Effect.logInfo("Released the managed tunnel on shutdown") : Effect.void,
777 ),
778 Effect.catchCause((cause) =>
779 Effect.logWarning(
780 "Failed to release the managed tunnel on shutdown; the next link reuses it",
781 { errors: Cause.prettyErrors(cause).map((error) => error.message) },
782 ),
783 ),
784 Effect.asVoid,
785 );
786 // A launcher trial can be stopped before activation. The previous
787 // server is already gone, so the trial owns cleanup immediately; the
788 // pending-state check keeps the tunnel for normal commit or rollback,
789 // while the launcher's explicit-stop marker allows it to be released.
790 // Other runtimes wait for activation so a failed standby cannot tear
791 // down the active runtime's tunnel.
792 const cleanupBeforeActivation = yield* pendingServiceUpdateExists;
793 if (cleanupBeforeActivation) {
794 yield* Effect.addFinalizer(() => releaseManagedTunnel);
795 }
796 yield* ServerActivation.forkParked(
797 Effect.gen(function* () {
798 if (!cleanupBeforeActivation) {
799 yield* Effect.addFinalizer(() => releaseManagedTunnel);
800 }
801 const server = yield* HttpServer.HttpServer;
802 const address = server.address;
803 if (typeof address === "string" || !("port" in address)) return;
804 const localOrigin = `http://127.0.0.1:${address.port}`;
805 const endpointRuntime = yield* CloudManagedEndpointRuntime.CloudManagedEndpointRuntime;
806 const recoveryLock = yield* Semaphore.make(1);
807 let lastRecoveryAtMillis = 0;
808 const recoverManagedTunnel = (config: RelayManagedEndpointRuntimeConfig) =>
809 recoveryLock.withPermits(1)(
810 Effect.gen(function* () {
811 const elapsed = (yield* Clock.currentTimeMillis) - lastRecoveryAtMillis;
812 const wait = Duration.toMillis(MANAGED_TUNNEL_RECOVERY_COOLDOWN) - elapsed;
813 if (wait > 0) yield* Effect.sleep(Duration.millis(wait));
814 lastRecoveryAtMillis = yield* Clock.currentTimeMillis;
815 }).pipe(
816 Effect.andThen(
817 recoverManagedCloudTunnel(localOrigin, config, {
818 retryRuntimeFailures: true,
819 }),
820 ),
821 Effect.retry({
822 while: (error) =>
823 shouldRetryCloudLink(error) &&
824 error._tag !== "EnvironmentCloudEndpointUnavailableError",
825 schedule: Schedule.exponential("1 second").pipe(
826 Schedule.modifyDelay(({ duration }) =>
827 Effect.succeed(Duration.min(duration, Duration.seconds(30))),
828 ),
829 Schedule.jittered,
830 ),
831 }),
832 Effect.tap((recovered) =>
833 recovered ? Effect.logInfo("T3 Connect managed tunnel recovered") : Effect.void,
834 ),
835 Effect.catchCause((cause) =>
836 Cause.hasInterrupts(cause)
837 ? Effect.interrupt
838 : Effect.logWarning("Failed to recover the T3 Connect managed tunnel", {
839 cause,
840 }),
841 ),
842 ),
843 );
844 yield* endpointRuntime.recoveryRequests.pipe(
845 Stream.runForEach(recoverManagedTunnel),
846 Effect.forkScoped,
847 );
848 // No settling delay before the first attempt: routes are already
849 // serving by the time activation opens this gate (the startup
850 // sequence awaits routesReady), and the retry schedule below
851 // covers anything this sleep used to hedge against. Every
852 // millisecond here is dead time on the path to remote
853 // reachability after a restart.
854 const wantsCliLink = hasCloudPublicConfig
855 ? yield* CloudCliState.readCliDesiredCloudLink.pipe(
856 Effect.catch((cause) =>
857 Effect.logWarning("Failed to read the desired T3 Connect link", { cause }).pipe(
858 Effect.as(false),
859 ),
860 ),
861 )
862 : false;
863 // A failed read must not end this fiber before it registers
864 // recovery and starts consuming recovery requests. "managed" is
865 // what a missing value means, so it is the safe fallback.
866 const desiredCliLinkMode = wantsCliLink
867 ? yield* CloudCliState.readCliDesiredLinkMode.pipe(
868 Effect.catch((cause) =>
869 Effect.logWarning("Failed to read the desired T3 Connect link mode", {
870 cause,
871 }).pipe(Effect.as("managed" as const)),
872 ),
873 )
874 : null;
875 // A publish-only link must not expose the host, even if a managed
876 // config from an earlier link is still stored.
877 const startedConfirmed =
878 desiredCliLinkMode === "publish_only"
879 ? false
880 : yield* startManagedCloudTunnelIfOriginConfirmed(localOrigin).pipe(
881 Effect.catch((cause) =>
882 Effect.logWarning("Failed to start the confirmed T3 Connect tunnel", {
883 cause,
884 }).pipe(Effect.as(false)),
885 ),
886 );
887 const startStoredManagedTunnel = startManagedCloudTunnelIfOriginConfirmed(localOrigin, {
888 requireConfirmedOrigin: false,
889 }).pipe(
890 Effect.tap((started) =>
891 started
892 ? Effect.logWarning(
893 "T3 Connect started the stored tunnel without relay confirmation",
894 )
895 : Effect.void,
896 ),
897 Effect.catch((cause) =>
898 Effect.logWarning("Failed to start the stored T3 Connect tunnel", { cause }),
899 ),
900 Effect.asVoid,
901 );
902 const registerManagedTunnel = retryManagedTunnelRegistration(
903 registerManagedCloudTunnelRecovery(localOrigin, {
904 retryRuntimeFailures: true,
905 }),
906 (error) =>
907 shouldRetryCloudLink(error) &&
908 error._tag !== "EnvironmentCloudEndpointUnavailableError",
909 startedConfirmed ? Effect.void : startStoredManagedTunnel,
910 ).pipe(
911 Effect.tap((result) =>
912 result.status === "ready"
913 ? Effect.logInfo("T3 Connect managed tunnel recovery registered")
914 : Effect.void,
915 ),
916 Effect.catchCause((cause) =>
917 Cause.hasInterrupts(cause)
918 ? Effect.interrupt
919 : Effect.logWarning("Failed to register T3 Connect managed tunnel recovery", {
920 cause,
921 }).pipe(Effect.as({ status: "unavailable" as const })),
922 ),
923 );
924 // A host without a confirmed marker is on its first boot after the
925 // upgrade. Spread those registrations so an auto-update wave does
926 // not hit the relay all at once.
927 if (!startedConfirmed && desiredCliLinkMode !== "publish_only") {
928 const jitter = yield* Random.nextIntBetween(
929 0,
930 Duration.toMillis(MANAGED_TUNNEL_FIRST_REGISTRATION_JITTER),
931 );
932 yield* Effect.sleep(Duration.millis(jitter));
933 }
934 const registration =
935 desiredCliLinkMode === "publish_only"
936 ? { status: "not_linked" as const }
937 : yield* registerManagedTunnel;
938 // A terminal registration failure also allows the stored config
939 // to start. Transient outages use the fallback above and keep
940 // registration retrying in this scoped startup fiber.
941 if (registration.status === "unavailable" && !startedConfirmed) {
942 yield* startStoredManagedTunnel;
943 }
944 const startupAction = managedTunnelStartupAction({ wantsCliLink, registration });
945 if (startupAction.action === "request_recovery") {
946 yield* endpointRuntime.requestRecovery(startupAction.config);
947 }
948 if (startupAction.action === "reconcile_link") {
949 const reconciledMode = yield* reconcileDesiredCloudLinkIfStillDesired(
950 localOrigin,
951 ).pipe(
952 Effect.retry({
953 while: shouldRetryCloudLink,
954 schedule: Schedule.exponential("1 second").pipe(
955 Schedule.modifyDelay(({ duration }) =>
956 Effect.succeed(Duration.min(duration, Duration.seconds(30))),
957 ),
958 Schedule.upTo({ duration: "10 minutes" }),
959 ),
960 }),
961 Effect.tap((mode) =>
962 mode === null
963 ? Effect.void
964 : Effect.logInfo("T3 Connect desired link reconciled on startup"),
965 ),
966 Effect.catch((cause) =>
967 Effect.logWarning("Failed to reconcile T3 Connect desired link on startup", {
968 cause,
969 }).pipe(Effect.as(null)),
970 ),
971 );
972 if (reconciledMode === "managed") {
973 const afterReconcile = yield* registerManagedTunnel;
974 if (afterReconcile.status === "recovery_required") {
975 yield* endpointRuntime.requestRecovery(afterReconcile.config);
976 }
977 }
978 }
979 }),
980 );
981 yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);
982 }),
983 );
984​
985 const runtimeServicesLive = ServerRuntimeStartup.layerWithOptions({
986 activate: Deferred.succeed(activation, undefined).pipe(Effect.asVoid),
987 abort: (error) => Deferred.die(activation, error).pipe(Effect.asVoid),
988 awaitAuxiliaryParked: Effect.all(
989 [
990 Deferred.await(runtimeStateParked),
991 Deferred.await(cloudLinkParked),
992 Deferred.await(routesReady),
993 ...(config.tailscaleServeEnabled ? [Deferred.await(tailscaleParked)] : []),
994 ],
995 { concurrency: "unbounded" },
996 ).pipe(Effect.asVoid),
997 }).pipe(Layer.provideMerge(RuntimeDependenciesLive), Layer.provide(launcherLayer));
998​
999 const routesLayer = HttpRouter.serve(makeRoutesLayer.pipe(Layer.provide(launcherLayer)), {
1000 disableLogger: !config.logWebSocketEvents,
1001 routerConfig: HTTP_ROUTER_CONFIG,
1002 }).pipe(Layer.tap(() => Deferred.succeed(routesReady, undefined).pipe(Effect.orDie)));
1003 const serverApplicationLayer = Layer.mergeAll(
1004 routesLayer,
1005 httpListeningLayer,
1006 runtimeStateLayer.pipe(Layer.provide(launcherLayer)),
1007 tailscaleServeLayer,
1008 cloudDesiredLinkReconcileLayer,
1009 HeapSnapshot.layer,
1010 );
1011​
1012 return serverApplicationLayer.pipe(
1013 Layer.provideMerge(runtimeServicesLive),
1014 Layer.provideMerge(
1015 McpSessionRegistry.layer.pipe(
1016 Layer.provide(ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer))),
1017 ),
1018 ),
1019 Layer.provide(activationLayer),
1020 Layer.provideMerge(serverRelayBrokerTracingLayer),
1021 Layer.provideMerge(HttpServerLive),
1022 Layer.provide(ApplicationObservabilityLive),
1023 Layer.provideMerge(FetchHttpClient.layer),
1024 // PR reads, Git operations, and WebSocket discovery share one process limiter.
1025 Layer.provide(VcsProcess.layer),
1026 Layer.provideMerge(PlatformServicesLive),
1027 );
1028 }),
1030​
1031// The CLI supplies configuration.
1032export const runServer = Layer.launch(makeServerLayer);