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

server.ts

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