Open History to see the last commit
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/unstable/http";
22import * as HttpApiBuilder from "effect/unstable/httpapi/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 untracedRequestsLayer,
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 RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";
116import { authHttpApiLayer, environmentAuthenticatedAuthLayer } from "./auth/http.ts";
117import * as ReplayMarkers from "./auth/replayMarkers.ts";
118import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
119import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
120import {
121 connectHttpApiLayer,
122 pendingServiceUpdateExists,
123 reconcileDesiredCloudLinkIfStillDesired,
124 recoverManagedCloudTunnel,
125 registerManagedCloudTunnelRecovery,
126 startManagedCloudTunnelIfOriginConfirmed,
127 releaseManagedTunnelOnShutdown,
128} from "./cloud/http.ts";
129import { serverRelayBrokerTracingLayer } from "./cloud/relayTracing.ts";
130import { shouldRetryCloudLink } from "./cloud/relayResponse.ts";
131import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts";
132import {
133 MANAGED_TUNNEL_FIRST_REGISTRATION_JITTER,
134 MANAGED_TUNNEL_RECOVERY_COOLDOWN,
135 managedTunnelStartupAction,
136 retryManagedTunnelRegistration,
137} from "./cloud/managedTunnelStartup.ts";
138import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts";
139import * as CloudCliState from "./cloud/CliState.ts";
140import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
141import * as DesktopAppUpdate from "./desktopUpdate/DesktopAppUpdate.ts";
142import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
143import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
144import * as HostResources from "./resourceTelemetry/HostResources.ts";
145import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
146import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
147import * as DesktopTelemetryReceiver from "./resourceTelemetry/DesktopTelemetryReceiver.ts";
148import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClient.ts";
149import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts";
150import * as ResourceMonitorBinary from "./resourceTelemetry/ResourceMonitorBinary.ts";
151import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
152import * as UsageService from "./usage/UsageService.ts";
153import {
154 OrchestrationEventInfrastructureLayerLive,
155 OrchestrationV2ProductionLayerLive,
156 ProjectServiceLayerLive,
157 ProjectSetupScriptRunnerLayerLive,
158} from "./orchestration-v2/runtimeLayer.ts";
159import * as ProjectStore from "./orchestration-v2/ProjectStore.ts";
160import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts";
161import * as ResourceCleanupService from "./orchestration-v2/ResourceCleanupService.ts";
162import * as ThreadSettlementService from "./orchestration-v2/ThreadSettlementService.ts";
163import * as ThreadPullRequestService from "./orchestration-v2/ThreadPullRequestService.ts";
164import * as RunFinalizationService from "./orchestration-v2/RunFinalizationService.ts";
165import * as ProjectionStoreV2 from "./orchestration-v2/ProjectionStore.ts";
166import {
167 clearPersistedServerRuntimeState,
168 makePersistedServerRuntimeState,
169 persistServerRuntimeState,
170} from "./serverRuntimeState.ts";
171import { orchestrationHttpApiLayer } from "./orchestration-v2/http.ts";
172import { projectHttpApiLayer } from "./project/http.ts";
173import * as NetService from "@t3tools/shared/Net";
174import * as RelayClient from "@t3tools/shared/relayClient";
175import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale";
176import * as ServerActivation from "./serverActivation.ts";
177
178// MCP handoff thread IDs include escaped provenance and can exceed find-my-way's
179// 100-character default for one path segment.
180const HTTP_ROUTER_CONFIG = {
181 maxParamLength: 512,
182} as const;
183
184// Effect's default preemptive shutdown waits 20s before finalizing request scopes.
185// T3's primary transport is long-lived WebSocket RPC, whose Effect scope finalizer
186// already closes the websocket gracefully. Do not add an artificial drain before
187// those finalizers get a chance to run.
188const HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS = 0;
189const ResourceAttributionLayerLive = ResourceAttribution.layer;
190const ApplicationObservabilityLive = EventLoopMonitor.layer.pipe(
191 Layer.provideMerge(ObservabilityLive),
192 Layer.provideMerge(ResourceAttributionLayerLive),
193);
194
195const PtyAdapterLive = NodePtyAdapter.layer;
196
197const ServerSettingsLayerLive = ServerSettings.layer.pipe(
198 Layer.provide(ServerSecretStore.layer),
199 Layer.provideMerge(SqlitePersistence.layerConfig),
200);
201
202const NativeTelemetryLayerLive = NativeTelemetryClient.layer.pipe(
203 Layer.provide(ResourceMonitorBinary.layer),
204);
205const DesktopTelemetryReceiverLayerLive = DesktopTelemetryReceiver.layer.pipe(
206 Layer.provideMerge(ServerSettingsLayerLive),
207);
208
209const ResourceTelemetryLayerLive = ResourceTelemetry.layer.pipe(
210 Layer.provideMerge(NativeTelemetryLayerLive),
211 Layer.provideMerge(DesktopTelemetryReceiverLayerLive),
212);
213
214const HostPowerMonitorLayerLive = HostPowerMonitor.layer.pipe(
215 Layer.provide(DesktopTelemetryReceiverLayerLive),
216);
217
218// Reuses DesktopTelemetryReceiverLayerLive: a fresh receiver layer here
219// would open a second reader on the desktop telemetry fd.
220const DesktopAppUpdateLayerLive = DesktopAppUpdate.layer.pipe(
221 Layer.provide(DesktopTelemetryReceiverLayerLive),
222);
223
224const BackgroundLayerLive = BackgroundPolicy.layer.pipe(
225 Layer.provide(HostPowerMonitorLayerLive),
226 Layer.provideMerge(ServerSettingsLayerLive),
227);
228
229const UsageLayerLive = UsageService.layer.pipe(Layer.provide(ServerSettingsLayerLive));
230
231const ResourceDiagnosticsLayerLive = Layer.mergeAll(
232 HostResources.layer,
233 ResourceTelemetryLayerLive,
234 ProcessDiagnostics.layer.pipe(Layer.provide(ResourceTelemetryLayerLive)),
235 ProcessResourceMonitor.layer.pipe(Layer.provide(ResourceTelemetryLayerLive)),
236);
237
238const RelayClientLive = Layer.unwrap(
239 Effect.gen(function* () {
240 const config = yield* ServerConfig.ServerConfig;
241 return RelayClient.layerCloudflared({ baseDir: config.baseDir });
242 }),
243);
244
245const HttpServerLive = Layer.unwrap(
246 Effect.gen(function* () {
247 const config = yield* ServerConfig.ServerConfig;
248 return NodeHttpServer.layer(() => guardHttpResponseWriteErrors(NodeHttp.createServer()), {
249 host: config.host ?? "127.0.0.1",
250 port: config.port,
251 gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
252 // Negotiate permessage-deflate with clients that offer it; clients
253 // that don't still get uncompressed frames on their connection.
254 // Context takeover stays enabled (ws default) so the compression
255 // window is shared across frames — that also makes small frames cheap
256 // to compress, so no size threshold is set (ws only honors
257 // `threshold` when context takeover is disabled).
258 websocket: { perMessageDeflate: true },
259 });
260 }),
261);
262
263const PlatformServicesLive = NodeServices.layer;
264
265const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistence.layerConfig));
266
267const VcsDriverRegistryLayerLive = VcsDriverRegistry.layer.pipe(
268 Layer.provide(VcsProjectConfig.layer),
269);
270
271const SourceControlProviderRegistryLayerLive = SourceControlProviderRegistry.layer.pipe(
272 Layer.provide(
273 Layer.mergeAll(
274 AzureDevOpsCli.layer,
275 BitbucketApi.layer,
276 GitHubCli.layer,
277 GitLabCli.layer,
278 ForgejoCli.layer,
279 ),
280 ),
281 Layer.provideMerge(GitVcsDriver.layer),
282 Layer.provideMerge(VcsDriverRegistryLayerLive),
283);
284
285const RepositoryIdentityResolverLayerLive = Layer.effect(
286 RepositoryIdentityResolver.RepositoryIdentityResolver,
287 Effect.gen(function* () {
288 const registry = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
289 return yield* RepositoryIdentityResolver.make({
290 refine: Effect.fn(function* (identity: RepositoryIdentity) {
291 const remote = ForgejoCli.parseForgejoRemote(identity.locator.remoteUrl);
292 if (
293 !remote ||
294 !identity.rootPath ||
295 (identity.provider !== undefined &&
296 identity.provider !== "unknown" &&
297 identity.provider !== "forgejo")
298 )
299 return identity;
300 const handle = yield* registry.resolveHandle({
301 cwd: identity.rootPath,
302 context: {
303 provider: { kind: "unknown", name: "Unknown", baseUrl: "" },
304 remoteName: identity.locator.remoteName,
305 remoteUrl: identity.locator.remoteUrl,
306 },
307 });
308 if (handle.context?.provider.kind !== "forgejo") return identity;
309 const baseUrl = handle.context.provider.baseUrl.replace(/\/+$/, "");
310 const basePath = new URL(baseUrl).pathname.replace(/^\/+|\/+$/g, "");
311 const path =
312 !remote.ssh && basePath && remote.path.startsWith(`${basePath}/`)
313 ? remote.path.slice(basePath.length + 1)
314 : remote.path;
315 return { ...identity, provider: "forgejo", webUrl: `${baseUrl}/${path}` };
316 }),
317 });
318 }),
319).pipe(Layer.provide(SourceControlProviderRegistryLayerLive), Layer.provide(ProcessRunner.layer));
320
321const PullRequestServiceLive = PullRequestService.layer.pipe(
322 Layer.provide(PullRequestProviderRegistry.layer),
323 // Where the viewed-file marks live for a host that keeps none of its own.
324 Layer.provide(PullRequestFilesViewed.layer),
325 Layer.provide(PullRequestReadCache.layer),
326 Layer.provide(SourceControlProviderRegistryLayerLive),
327 Layer.provide(SourceControlRateLimit.layer),
328);
329
330const GitManagerLayerLive = GitManager.layer.pipe(
331 // Per-project git settings resolve the acting thread's project.
332 Layer.provide(Layer.merge(ProjectionStoreV2.layer, ProjectStore.layer)),
333 Layer.provideMerge(ProjectSetupScriptRunnerLayerLive),
334 Layer.provideMerge(WorktreeSetupTracker.layer),
335 Layer.provideMerge(GitVcsDriver.layer),
336 Layer.provideMerge(SourceControlProviderRegistryLayerLive),
337 Layer.provideMerge(
338 TextGeneration.layer.pipe(Layer.provide(SourceControlProviderRegistryLayerLive)),
339 ),
340);
341
342const GitLayerLive = Layer.empty.pipe(
343 Layer.provideMerge(GitManagerLayerLive),
344 Layer.provideMerge(GitVcsDriver.layer),
345);
346
347const GitWorkflowLayerLive = GitWorkflowService.layer.pipe(
348 Layer.provideMerge(VcsDriverRegistryLayerLive),
349 Layer.provideMerge(GitLayerLive),
350);
351
352const SourceControlRepositoryServiceLayerLive = SourceControlRepositoryService.layer.pipe(
353 Layer.provideMerge(GitVcsDriver.layer),
354 Layer.provideMerge(SourceControlProviderRegistryLayerLive),
355);
356
357const ProjectCloneTrackerLayerLive = ProjectCloneTracker.layer.pipe(
358 Layer.provide(SourceControlRepositoryServiceLayerLive),
359);
360
361const ReviewLayerLive = ReviewService.layer.pipe(
362 Layer.provideMerge(GitVcsDriver.layer),
363 Layer.provideMerge(VcsDriverRegistryLayerLive),
364);
365
366const VcsLayerLive = Layer.empty.pipe(
367 Layer.provideMerge(VcsProjectConfig.layer),
368 Layer.provideMerge(VcsDriverRegistryLayerLive),
369 Layer.provideMerge(VcsProvisioningService.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
370 Layer.provideMerge(GitWorkflowLayerLive),
371 Layer.provideMerge(ReviewLayerLive),
372 Layer.provideMerge(SourceControlRepositoryServiceLayerLive),
373 Layer.provideMerge(ProjectCloneTrackerLayerLive),
374 Layer.provideMerge(
375 VcsStatusBroadcaster.layer.pipe(
376 Layer.provide(GitWorkflowLayerLive),
377 // Auto-pull reads the project row. The orchestration runtime also
378 // consumes the broadcaster (run finalization), so the policy cannot read
379 // the store from the runtime's output.
380 Layer.provide(
381 VcsStatusBroadcaster.autoPullPolicyLayer.pipe(Layer.provide(ProjectStore.layer)),
382 ),
383 ),
384 ),
385);
386
387const CheckpointStoreLayerLive = CheckpointStore.layer.pipe(
388 Layer.provide(VcsDriverRegistryLayerLive),
389);
390
391const PortScannerLayerLive = PortScanner.layer.pipe(Layer.provide(ProcessRunner.layer));
392
393const TerminalLayerLive = TerminalManager.layer.pipe(
394 Layer.provide(PtyAdapterLive),
395 Layer.provide(PortScannerLayerLive),
396 Layer.provide(NativeTelemetryLayerLive),
397);
398
399const PreviewLayerLive = Layer.empty.pipe(
400 Layer.provideMerge(PreviewManager.layer),
401 Layer.provideMerge(PortScannerLayerLive),
402);
403
404const DeviceLayerLive = DeviceService.layer.pipe(
405 Layer.provide(ServerSettingsLayerLive),
406 Layer.provide(ProcessRunner.layer),
407 Layer.provide(NetService.layer),
408);
409
410const WorkspaceEntriesLayerLive = WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePaths.layer));
411
412const WorkspaceFileSystemLayerLive = WorkspaceFileSystem.layer.pipe(
413 Layer.provide(WorkspacePaths.layer),
414 Layer.provide(WorkspaceEntriesLayerLive),
415);
416
417const WorkspaceLayerLive = Layer.mergeAll(
418 WorkspacePaths.layer,
419 WorkspaceEntriesLayerLive,
420 WorkspaceFileSystemLayerLive,
421);
422
423const ProjectFaviconResolverLayerLive = ProjectFaviconResolver.layer.pipe(
424 Layer.provide(WorkspacePaths.layer),
425 Layer.provide(T3ProjectFileLoader.layer),
426);
427
428const ServerEnvironmentLayerLive = ServerEnvironment.layer.pipe(
429 Layer.provide(ServerSecretStore.layer),
430);
431
432const AuthLayerLive = EnvironmentAuth.layer.pipe(
433 Layer.provideMerge(PersistenceLayerLive),
434 Layer.provide(ServerEnvironmentLayerLive),
435 Layer.provide(ServerSecretStore.layer),
436);
437
438const CloudManagedEndpointRuntimeLive = Layer.mergeAll(
439 RelayClientLive,
440 CloudManagedEndpointRuntime.layer.pipe(
441 Layer.provide(ServerSecretStore.layer),
442 Layer.provide(RelayClientLive),
443 ),
444);
445
446const OrchestrationV2RuntimeLayerLive = OrchestrationV2ProductionLayerLive.pipe(
447 Layer.provide(ProviderEventIngestor.analyticsLive),
448 Layer.provide(CheckpointStoreLayerLive),
449 Layer.provide(GitWorkflowLayerLive),
450 Layer.provide(ResourceCleanupService.live),
451 Layer.provide(
452 RunFinalizationService.observerLive.pipe(
453 Layer.provide(ProjectionStoreV2.layer),
454 Layer.provide(PullRequestServiceLive),
455 Layer.provide(ProjectServiceLayerLive),
456 ),
457 ),
458);
459
460const OrchestrationApplicationLayerLive = CheckpointDiffQuery.layer.pipe(
461 Layer.provideMerge(CheckpointStoreLayerLive),
462 Layer.provideMerge(OrchestrationV2RuntimeLayerLive),
463);
464
465// Automatic thread settlement (#8600): a server-owned sweep evaluates
466// inactivity and merged pull requests, then settles through the orchestrator
467// so every client sees the same shelf.
468const ThreadSettlementWorkerLive = Layer.effectDiscard(
469 ThreadSettlementService.make.pipe(Effect.flatMap((service) => service.start())),
470).pipe(Layer.provide(PullRequestServiceLive), Layer.provide(ProjectionStoreV2.layer));
471
472const ThreadPullRequestWorkerLive = Layer.effectDiscard(
473 ThreadPullRequestService.make.pipe(Effect.flatMap((service) => service.start())),
474).pipe(Layer.provide(PullRequestServiceLive));
475
476const ProviderInstallationRefreshLive = Layer.effectDiscard(
477 Effect.gen(function* () {
478 const antigravity = yield* AntigravityInstallation.AntigravityInstallation;
479 const codex = yield* CodexInstallation.CodexInstallation;
480 const instances = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
481 const providers = yield* ProviderRegistry.ProviderRegistry;
482 yield* Stream.merge(
483 antigravity.changes.pipe(
484 Stream.changesWith((a, b) => a.installedVersion === b.installedVersion),
485 Stream.drop(1),
486 ),
487 codex.changes.pipe(
488 Stream.changesWith((a, b) => a.installedVersion === b.installedVersion),
489 Stream.drop(1),
490 ),
491 ).pipe(
492 Stream.runForEach((state) =>
493 instances.listInstances.pipe(
494 Effect.flatMap((entries) =>
495 Effect.forEach(
496 entries.filter((instance) => instance.driverKind === state.driver),
497 (instance) => providers.refreshInstance(instance.instanceId),
498 { discard: true },
499 ),
500 ),
501 ),
502 ),
503 Effect.forkScoped,
504 );
505 }),
506);
507
508const RuntimeCoreDependenciesBaseLive = Layer.mergeAll(
509 AgentAwarenessRelay.layer,
510 ThreadSettlementWorkerLive,
511 Layer.effectDiscard(StorageCleanup.make.pipe(Effect.flatMap((service) => service.start()))).pipe(
512 Layer.provide(ProjectionStoreV2.layer),
513 ),
514 ThreadPullRequestWorkerLive,
515 Layer.effectDiscard(
516 Effect.gen(function* () {
517 const service = yield* PullRequestSyncReactor.PullRequestSyncReactor;
518 yield* service.start();
519 }),
520 ).pipe(
521 Layer.provideMerge(PullRequestSyncReactor.layer),
522 Layer.provide(PullRequestServiceLive),
523 Layer.provide(ProjectionStoreV2.layer),
524 ),
525 Layer.effectDiscard(
526 Effect.gen(function* () {
527 const service = yield* PullRequestWatchReactor.PullRequestWatchReactor;
528 yield* service.start();
529 }),
530 ).pipe(
531 Layer.provide(PullRequestWatchReactor.layer),
532 Layer.provide(PullRequestServiceLive),
533 Layer.provide(ProjectionStoreV2.layer),
534 ),
535 // Subscribes to `account.rate-limits.updated` so usage bars track live
536 // telemetry instead of waiting for the next status probe.
537 ProviderUsageLimitsIngestionLive,
538 ProviderInstallationRefreshLive,
539 ReplayMarkers.layer,
540).pipe(
541 // Core Services
542 Layer.provideMerge(OrchestrationApplicationLayerLive),
543 Layer.provideMerge(OrchestrationEventInfrastructureLayerLive),
544 Layer.provideMerge(Layer.merge(ProjectStore.layer, ThreadSearch.layer)),
545 Layer.provideMerge(ServerSettingsLayerLive),
546 // The asset route uses the registry's GitHub credential for private PR media.
547 Layer.provideMerge(Layer.mergeAll(SourceControlProviderRegistryLayerLive, GitHubCli.layer)),
548 Layer.provideMerge(GitLayerLive),
549 Layer.provideMerge(VcsLayerLive),
550 Layer.provideMerge(Layer.mergeAll(TerminalLayerLive, PreviewLayerLive, DeviceLayerLive)),
551 Layer.provideMerge(PersistenceLayerLive),
552 // Both read a user-owned file out of the state directory and stream changes
553 // to clients; neither depends on the other.
554 Layer.provideMerge(
555 Layer.mergeAll(Keybindings.layer, EnvironmentTheme.layer, UsageLimitSources.layer),
556 ),
557 Layer.provideMerge(ProviderRegistryLive),
558 // The instance registry is the new routing keystone — text generation,
559 // adapter lookup, and runtime ingestion all resolve `ProviderInstanceId`
560 // through this layer. Built-in drivers come from `BUILT_IN_DRIVERS`;
561 // `providerInstances` hydration merges `settings.providers.<kind>`
562 // with explicit `providerInstances` entries on boot.
563 Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
564 Layer.provideMerge(
565 Layer.mergeAll(
566 AntigravityInstallation.AntigravityInstallation.layer,
567 CodexInstallation.CodexInstallation.layer,
568 ),
569 ),
570);
571
572const RuntimeCoreDependenciesLive = RuntimeCoreDependenciesBaseLive.pipe(
573 Layer.provideMerge(PtyAdapterLive),
574 // Search, prepare, status inspection, and turn launch share one registry
575 // cache so every client and provider instance sees the same prepared agents.
576 Layer.provideMerge(AcpRegistryCatalogLive),
577 // Shared native/canonical NDJSON writers used by both the per-instance
578 // V2 drivers and the orchestration runtime. Provide resource attribution so
579 // the rewritten telemetry pipeline can account for logical NDJSON writes.
580 // Provided once at the runtime level so every consumer sees the same
581 // logger instances.
582 // `ModelManifest.layer` is the legacy-model classification data, refreshed
583 // from the repo's `model-manifest.json` on `main` and applied by the
584 // Codex/Claude drivers.
585 Layer.provideMerge(
586 Layer.mergeAll(ProviderEventLoggers.layer, ModelManifest.layer, ResetCreditCoordinator.layer),
587 ),
588 // `OpenCodeDriver.create()` yields `OpenCodeRuntime`; previously the old
589 // `ProviderRegistryLive` pulled `OpenCodeRuntimeLive` in for itself, but
590 // the rewritten registry reads snapshots off the instance registry and
591 // no longer transitively provides it. Exposing it at the runtime level
592 // keeps a single Live for all opencode consumers.
593 Layer.provideMerge(
594 OpenCodeRuntime.OpenCodeRuntimeLive.pipe(Layer.provide(OpenCodeServerLedger.layer)),
595 ),
596 Layer.provideMerge(WorkspaceLayerLive),
597 Layer.provideMerge(ProjectEnrichmentService.layer),
598 Layer.provideMerge(Layer.mergeAll(NativeAppIconResolver.layer, ProjectFaviconResolverLayerLive)),
599 Layer.provideMerge(RepositoryIdentityResolverLayerLive),
600 Layer.provideMerge(ServerEnvironmentLayerLive),
601 Layer.provideMerge(AuthLayerLive),
602 Layer.provideMerge(ServerSecretStore.layer),
603 Layer.provideMerge(
604 Layer.mergeAll(
605 CloudCliTokenManager.layer.pipe(
606 Layer.provide(ServerSecretStore.layer),
607 Layer.provide(ExternalLauncher.layer),
608 ),
609 CloudManagedEndpointRuntimeLive,
610 ),
611 ),
612);
613
614const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
615 // Misc.
616 Layer.provideMerge(BackgroundLayerLive),
617 Layer.provideMerge(ResourceDiagnosticsLayerLive),
618 Layer.provideMerge(UsageLayerLive),
619 Layer.provideMerge(TraceDiagnostics.layer),
620 Layer.provideMerge(AnalyticsService.layer),
621 Layer.provideMerge(ExternalLauncher.layer),
622 Layer.provideMerge(RemoteOpenTargets.layer),
623 Layer.provideMerge(ServerLifecycleEvents.layer),
624 Layer.provide(NetService.layer),
625);
626
627const commandReadinessLayer = HttpRouter.middleware(
628 (httpEffect) =>
629 Effect.flatMap(ServerRuntimeStartup.ServerRuntimeStartup, (startup) =>
630 startup.awaitCommandReady.pipe(Effect.orDie, Effect.andThen(httpEffect)),
631 ),
632 { global: true },
633);
634
635const makeRoutesLayer = Layer.mergeAll(
636 Layer.mergeAll(
637 HttpApiBuilder.layer(EnvironmentHttpApi).pipe(
638 Layer.provide(authHttpApiLayer),
639 Layer.provide(connectHttpApiLayer),
640 Layer.provide(orchestrationHttpApiLayer),
641 Layer.provide(pullRequestHttpApiLayer),
642 Layer.provide(projectHttpApiLayer),
643 Layer.provide(serverEnvironmentHttpApiLayer),
644 Layer.provide(environmentAuthenticatedAuthLayer),
645 ),
646 otlpTracesProxyRouteLayer,
647 assetRouteLayer,
648 attachmentUploadRouteLayer,
649 deviceHubProxyRouteLayer,
650 staticAndDevRouteLayer,
651 websocketRpcRouteLayer,
652 ),
653 // The MCP session registry is provided globally (shared with V2 provider
654 // sessions) rather than inline here. The orchestrator toolkit resolves
655 // delegation targets through the same live adapter facade the V2
656 // orchestrator uses, so MCP capability reporting can never drift from
657 // what dispatch can actually serve.
658 McpHttpServer.layer.pipe(
659 Layer.provide(ProviderAdapterRegistry.layerFromProviderInstanceRegistry),
660 ),
661 // Last, so no route layer can replace the server's one TracerDisabledWhen.
662 untracedRequestsLayer,
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(
1000 [
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(Layer.tap(() => Deferred.succeed(routesReady, undefined).pipe(Effect.orDie)));
1014 const serverApplicationLayer = Layer.mergeAll(
1015 routesLayer,
1016 httpListeningLayer,
1017 runtimeStateLayer.pipe(Layer.provide(launcherLayer)),
1018 tailscaleServeLayer,
1019 cloudDesiredLinkReconcileLayer,
1020 HeapSnapshot.layer,
1021 );
1022
1023 return serverApplicationLayer.pipe(
1024 Layer.provideMerge(runtimeServicesLive),
1025 Layer.provideMerge(
1026 McpSessionRegistry.layer.pipe(
1027 Layer.provide(ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer))),
1028 ),
1029 ),
1030 Layer.provide(activationLayer),
1031 Layer.provideMerge(serverRelayBrokerTracingLayer),
1032 Layer.provideMerge(HttpServerLive),
1033 Layer.provide(ApplicationObservabilityLive),
1034 Layer.provideMerge(FetchHttpClient.layer),
1035 // PR reads, Git operations, and WebSocket discovery share one process limiter.
1036 Layer.provide(VcsProcess.layer),
1037 Layer.provideMerge(PlatformServicesLive),
1038 );
1039 }),
1040);
1041
1042// The CLI supplies configuration.
1043export const runServer = Layer.launch(makeServerLayer);