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