Open History to see the last commit
1import { EnvironmentHttpApi } from "@t3tools/contracts";
2import * as Duration from "effect/Duration";
3import * as Deferred from "effect/Deferred";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Schedule from "effect/Schedule";
7import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http";
8import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
9
10import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
11import * as HostPowerMonitor from "./background/HostPowerMonitor.ts";
12import * as ServerConfig from "./config.ts";
13import {
14 otlpTracesProxyRouteLayer,
15 assetRouteLayer,
16 serverEnvironmentHttpApiLayer,
17 staticAndDevRouteLayer,
18 browserApiCorsLayer,
19 httpCompressionLayer,
20} from "./http.ts";
21import { guardHttpResponseWriteErrors } from "./httpResponseErrorGuard.ts";
22import { fixPath } from "./os-jank.ts";
23import { websocketRpcRouteLayer } from "./ws.ts";
24import * as ExternalLauncher from "./process/externalLauncher.ts";
25import { pullRequestHttpApiLayer } from "./pullRequest/http.ts";
26import * as PullRequestProviderRegistry from "./pullRequest/PullRequestProviderRegistry.ts";
27import * as PullRequestService from "./pullRequest/PullRequestService.ts";
28import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
29import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
30import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
31import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory.ts";
32import * as ProviderSessionRuntime from "./persistence/ProviderSessionRuntime.ts";
33import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry.ts";
34import * as ProviderEventLoggers from "./provider/Layers/ProviderEventLoggers.ts";
35import { ProviderServiceLive } from "./provider/Layers/ProviderService.ts";
36import { ProviderSessionReaperLive } from "./provider/Layers/ProviderSessionReaper.ts";
37import * as OpenCodeRuntime from "./provider/opencodeRuntime.ts";
38import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
39import * as CheckpointStore from "./checkpointing/CheckpointStore.ts";
40import * as AzureDevOpsCli from "./sourceControl/AzureDevOpsCli.ts";
41import * as BitbucketApi from "./sourceControl/BitbucketApi.ts";
42import * as GitHubCli from "./sourceControl/GitHubCli.ts";
43import * as GitLabCli from "./sourceControl/GitLabCli.ts";
44import * as TextGeneration from "./textGeneration/TextGeneration.ts";
45import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/ProviderInstanceRegistryHydration.ts";
46import * as TerminalManager from "./terminal/Manager.ts";
47import * as McpHttpServer from "./mcp/McpHttpServer.ts";
48import * as McpSessionRegistry from "./mcp/McpSessionRegistry.ts";
49import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
50import * as PreviewManager from "./preview/Manager.ts";
51import * as PortScanner from "./preview/PortScanner.ts";
52import * as ProcessRunner from "./processRunner.ts";
53import * as GitManager from "./git/GitManager.ts";
54import * as Keybindings from "./keybindings.ts";
55import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
56import { OrchestrationReactorLive } from "./orchestration/Layers/OrchestrationReactor.ts";
57import { RuntimeReceiptBusLive } from "./orchestration/Layers/RuntimeReceiptBus.ts";
58import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion.ts";
59import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderCommandReactor.ts";
60import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor.ts";
61import { ThreadDeletionReactorLive } from "./orchestration/Layers/ThreadDeletionReactor.ts";
62import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
63import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
64import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry.ts";
65import * as ServerSettings from "./serverSettings.ts";
66import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts";
67import * as T3ProjectFileLoader from "./project/T3ProjectFileLoader.ts";
68import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
69import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
70import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
71import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
72import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
73import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";
74import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";
75import * as VcsProcess from "./vcs/VcsProcess.ts";
76import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
77import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
78import * as GitWorkflowService from "./git/GitWorkflowService.ts";
79import * as ReviewService from "./review/ReviewService.ts";
80import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
81import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
82import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts";
83import { ObservabilityLive } from "./observability/Layers/Observability.ts";
84import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
85import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";
86import { authHttpApiLayer, environmentAuthenticatedAuthLayer } from "./auth/http.ts";
87import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
88import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
89import {
90 connectHttpApiLayer,
91 pendingServiceUpdateExists,
92 reconcileDesiredCloudLink,
93 releaseManagedTunnelOnShutdown,
94} from "./cloud/http.ts";
95import { serverRelayBrokerTracingLayer } from "./cloud/relayTracing.ts";
96import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts";
97import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts";
98import * as CloudCliState from "./cloud/CliState.ts";
99import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
100import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
101import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
102import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
103import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
104import * as DesktopTelemetryReceiver from "./resourceTelemetry/DesktopTelemetryReceiver.ts";
105import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClient.ts";
106import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts";
107import * as ResourceMonitorBinary from "./resourceTelemetry/ResourceMonitorBinary.ts";
108import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
109import * as UsageService from "./usage/UsageService.ts";
110import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
111import {
112 clearPersistedServerRuntimeState,
113 makePersistedServerRuntimeState,
114 persistServerRuntimeState,
115} from "./serverRuntimeState.ts";
116import { orchestrationHttpApiLayer } from "./orchestration/http.ts";
117import * as NetService from "@t3tools/shared/Net";
118import * as RelayClient from "@t3tools/shared/relayClient";
119import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale";
120import { forkParked, ServerActivation } from "./serverActivation.ts";
121
122// Effect's default preemptive shutdown waits 20s before finalizing request scopes.
123// T3's primary transport is long-lived WebSocket RPC, whose Effect scope finalizer
124// already closes the websocket gracefully. Do not add an artificial drain before
125// those finalizers get a chance to run.
126const HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS = 0;
127const ResourceAttributionLayerLive = ResourceAttribution.layer;
128const ApplicationObservabilityLive = ObservabilityLive.pipe(
129 Layer.provideMerge(ResourceAttributionLayerLive),
130);
131
132const PtyAdapterLive = Layer.unwrap(
133 Effect.gen(function* () {
134 if (typeof Bun !== "undefined") {
135 const BunPtyAdapter = yield* Effect.promise(() => import("./terminal/BunPtyAdapter.ts"));
136 return BunPtyAdapter.layer;
137 } else {
138 const NodePtyAdapter = yield* Effect.promise(() => import("./terminal/NodePtyAdapter.ts"));
139 return NodePtyAdapter.layer;
140 }
141 }),
142);
143
144const ServerSettingsLayerLive = ServerSettings.layer.pipe(Layer.provide(ServerSecretStore.layer));
145
146const NativeTelemetryLayerLive = NativeTelemetryClient.layer.pipe(
147 Layer.provide(ResourceMonitorBinary.layer),
148);
149const DesktopTelemetryReceiverLayerLive = DesktopTelemetryReceiver.layer.pipe(
150 Layer.provideMerge(ServerSettingsLayerLive),
151);
152
153const ResourceTelemetryLayerLive = ResourceTelemetry.layer.pipe(
154 Layer.provideMerge(NativeTelemetryLayerLive),
155 Layer.provideMerge(DesktopTelemetryReceiverLayerLive),
156);
157
158const HostPowerMonitorLayerLive = HostPowerMonitor.layer.pipe(
159 Layer.provide(DesktopTelemetryReceiverLayerLive),
160);
161
162const BackgroundLayerLive = BackgroundPolicy.layer.pipe(
163 Layer.provide(HostPowerMonitorLayerLive),
164 Layer.provideMerge(ServerSettingsLayerLive),
165);
166
167const UsageLayerLive = UsageService.layer.pipe(Layer.provide(ServerSettingsLayerLive));
168
169const ResourceDiagnosticsLayerLive = Layer.mergeAll(
170 ResourceTelemetryLayerLive,
171 ProcessDiagnostics.layer.pipe(Layer.provide(ResourceTelemetryLayerLive)),
172 ProcessResourceMonitor.layer.pipe(Layer.provide(ResourceTelemetryLayerLive)),
173);
174
175const RelayClientLive = Layer.unwrap(
176 Effect.gen(function* () {
177 const config = yield* ServerConfig.ServerConfig;
178 return RelayClient.layerCloudflared({ baseDir: config.baseDir });
179 }),
180);
181
182const HttpServerLive = Layer.unwrap(
183 Effect.gen(function* () {
184 const config = yield* ServerConfig.ServerConfig;
185 if (typeof Bun !== "undefined") {
186 const BunHttpServer = yield* Effect.promise(
187 () => import("@effect/platform-bun/BunHttpServer"),
188 );
189 return BunHttpServer.layer({
190 port: config.port,
191 hostname: config.host ?? "127.0.0.1",
192 gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
193 websocket: {
194 // Negotiate permessage-deflate with clients that offer it; clients
195 // that don't still get uncompressed frames on their connection. A
196 // dedicated compressor keeps a per-connection sliding window
197 // (context takeover) so the compression dictionary is shared across
198 // server-to-client frames. Decompression uses the shared
199 // decompressor: uWebSockets' dedicated decompressor path can abort
200 // connections (close 1006) on valid DEFLATE input — see
201 // https://github.com/uNetworking/uWebSockets.js/issues/633.
202 perMessageDeflate: {
203 compress: "dedicated",
204 decompress: "shared",
205 },
206 },
207 });
208 } else {
209 const [NodeHttpServer, NodeHttp] = yield* Effect.all([
210 Effect.promise(() => import("@effect/platform-node/NodeHttpServer")),
211 Effect.promise(() => import("node:http")),
212 ]);
213 return NodeHttpServer.layer(() => guardHttpResponseWriteErrors(NodeHttp.createServer()), {
214 host: config.host ?? "127.0.0.1",
215 port: config.port,
216 gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
217 // Negotiate permessage-deflate with clients that offer it; clients
218 // that don't still get uncompressed frames on their connection.
219 // Context takeover stays enabled (ws default) so the compression
220 // window is shared across frames — that also makes small frames cheap
221 // to compress, so no size threshold is set (ws only honors
222 // `threshold` when context takeover is disabled).
223 websocket: { perMessageDeflate: true },
224 });
225 }
226 }),
227);
228
229const PlatformServicesLive = Layer.unwrap(
230 Effect.gen(function* () {
231 if (typeof Bun !== "undefined") {
232 const { layer } = yield* Effect.promise(() => import("@effect/platform-bun/BunServices"));
233 return layer;
234 } else {
235 const { layer } = yield* Effect.promise(() => import("@effect/platform-node/NodeServices"));
236 return layer;
237 }
238 }),
239);
240
241const ReactorLayerLive = Layer.empty.pipe(
242 Layer.provideMerge(OrchestrationReactorLive),
243 Layer.provideMerge(ProviderRuntimeIngestionLive),
244 Layer.provideMerge(ProviderCommandReactorLive),
245 Layer.provideMerge(CheckpointReactorLive),
246 Layer.provideMerge(ThreadDeletionReactorLive),
247 Layer.provideMerge(AgentAwarenessRelay.layer.pipe(Layer.provide(ServerSecretStore.layer))),
248 Layer.provideMerge(RuntimeReceiptBusLive),
249);
250
251const ProviderSessionDirectoryLayerLive = ProviderSessionDirectoryLive.pipe(
252 Layer.provide(ProviderSessionRuntime.layer),
253);
254
255// `ProviderAdapterRegistryLive` is now a facade that resolves kind → adapter
256// by looking up the default `ProviderInstance` per driver in the instance
257// registry. Adapter construction itself moved inside each driver's
258// `create()`; `ProviderEventLoggers.layer` owns the shared native/canonical
259// NDJSON writers and is provided at the outer runtime layer so both
260// `ProviderService` and the per-instance drivers read the same logger pair.
261const ProviderLayerLive = ProviderServiceLive.pipe(
262 Layer.provide(ProviderAdapterRegistryLive),
263 Layer.provideMerge(ProviderSessionDirectoryLayerLive),
264);
265
266const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive));
267
268const VcsDriverRegistryLayerLive = VcsDriverRegistry.layer.pipe(
269 Layer.provide(VcsProjectConfig.layer),
270);
271
272const SourceControlProviderRegistryLayerLive = SourceControlProviderRegistry.layer.pipe(
273 Layer.provide(
274 Layer.mergeAll(AzureDevOpsCli.layer, BitbucketApi.layer, GitHubCli.layer, GitLabCli.layer),
275 ),
276 Layer.provideMerge(GitVcsDriver.layer),
277 Layer.provideMerge(VcsDriverRegistryLayerLive),
278);
279
280const GitManagerLayerLive = GitManager.layer.pipe(
281 Layer.provideMerge(ProjectSetupScriptRunner.layer),
282 Layer.provideMerge(GitVcsDriver.layer),
283 Layer.provideMerge(SourceControlProviderRegistryLayerLive),
284 Layer.provideMerge(TextGeneration.layer),
285);
286
287const GitLayerLive = Layer.empty.pipe(
288 Layer.provideMerge(GitManagerLayerLive),
289 Layer.provideMerge(GitVcsDriver.layer),
290);
291
292const GitWorkflowLayerLive = GitWorkflowService.layer.pipe(
293 Layer.provideMerge(VcsDriverRegistryLayerLive),
294 Layer.provideMerge(GitLayerLive),
295);
296
297const SourceControlRepositoryServiceLayerLive = SourceControlRepositoryService.layer.pipe(
298 Layer.provideMerge(GitVcsDriver.layer),
299 Layer.provideMerge(SourceControlProviderRegistryLayerLive),
300);
301
302const ReviewLayerLive = ReviewService.layer.pipe(
303 Layer.provideMerge(GitVcsDriver.layer),
304 Layer.provideMerge(VcsDriverRegistryLayerLive),
305);
306
307const VcsLayerLive = Layer.empty.pipe(
308 Layer.provideMerge(VcsProjectConfig.layer),
309 Layer.provideMerge(VcsDriverRegistryLayerLive),
310 Layer.provideMerge(VcsProvisioningService.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
311 Layer.provideMerge(GitWorkflowLayerLive),
312 Layer.provideMerge(ReviewLayerLive),
313 Layer.provideMerge(SourceControlRepositoryServiceLayerLive),
314 Layer.provideMerge(VcsStatusBroadcaster.layer.pipe(Layer.provide(GitWorkflowLayerLive))),
315);
316
317const CheckpointingLayerLive = Layer.empty.pipe(
318 Layer.provideMerge(CheckpointDiffQuery.layer),
319 Layer.provideMerge(CheckpointStore.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
320);
321
322const PortScannerLayerLive = PortScanner.layer.pipe(Layer.provide(ProcessRunner.layer));
323
324const TerminalLayerLive = TerminalManager.layer.pipe(
325 Layer.provide(PtyAdapterLive),
326 Layer.provide(PortScannerLayerLive),
327);
328
329const PreviewLayerLive = Layer.empty.pipe(
330 Layer.provideMerge(PreviewManager.layer),
331 Layer.provideMerge(PortScannerLayerLive),
332);
333
334const WorkspaceEntriesLayerLive = WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePaths.layer));
335
336const WorkspaceFileSystemLayerLive = WorkspaceFileSystem.layer.pipe(
337 Layer.provide(WorkspacePaths.layer),
338 Layer.provide(WorkspaceEntriesLayerLive),
339);
340
341const WorkspaceLayerLive = Layer.mergeAll(
342 WorkspacePaths.layer,
343 WorkspaceEntriesLayerLive,
344 WorkspaceFileSystemLayerLive,
345);
346
347const ProjectFaviconResolverLayerLive = ProjectFaviconResolver.layer.pipe(
348 Layer.provide(WorkspacePaths.layer),
349 Layer.provide(T3ProjectFileLoader.layer),
350);
351
352const AuthLayerLive = EnvironmentAuth.layer.pipe(
353 Layer.provideMerge(PersistenceLayerLive),
354 Layer.provide(ServerSecretStore.layer),
355);
356
357const CloudManagedEndpointRuntimeLive = Layer.mergeAll(
358 RelayClientLive,
359 CloudManagedEndpointRuntime.layer.pipe(
360 Layer.provide(ServerSecretStore.layer),
361 Layer.provide(RelayClientLive),
362 ),
363);
364
365const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(
366 Layer.provideMerge(ProviderLayerLive),
367 Layer.provideMerge(OrchestrationLayerLive),
368);
369
370const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
371 // Core Services
372 Layer.provideMerge(ServerSettingsLayerLive),
373 Layer.provideMerge(CheckpointingLayerLive),
374 Layer.provideMerge(SourceControlProviderRegistryLayerLive),
375 Layer.provideMerge(GitLayerLive),
376 Layer.provideMerge(VcsLayerLive),
377 Layer.provideMerge(ProviderRuntimeLayerLive),
378 Layer.provideMerge(Layer.mergeAll(TerminalLayerLive, PreviewLayerLive)),
379 Layer.provideMerge(PersistenceLayerLive),
380 Layer.provideMerge(Keybindings.layer),
381 Layer.provideMerge(ProviderRegistryLive),
382 // The instance registry is the new routing keystone — text generation,
383 // adapter lookup, and runtime ingestion all resolve `ProviderInstanceId`
384 // through this layer. Built-in drivers come from `BUILT_IN_DRIVERS`;
385 // `providerInstances` hydration merges `settings.providers.<kind>`
386 // with explicit `providerInstances` entries on boot.
387 Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
388 // Shared native/canonical NDJSON writers used by both the per-instance
389 // drivers (native stream, written from inside each `<X>Adapter`) and
390 // `ProviderService` (canonical stream, written after event normalization).
391 // Provided once at the runtime level so every consumer sees the same
392 // logger instances.
393 Layer.provideMerge(ProviderEventLoggers.layer),
394 // `OpenCodeDriver.create()` yields `OpenCodeRuntime`; previously the old
395 // `ProviderRegistryLive` pulled `OpenCodeRuntimeLive` in for itself, but
396 // the rewritten registry reads snapshots off the instance registry and
397 // no longer transitively provides it. Exposing it at the runtime level
398 // keeps a single Live for all opencode consumers.
399 Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
400 Layer.provideMerge(WorkspaceLayerLive),
401 Layer.provideMerge(ProjectFaviconResolverLayerLive),
402 Layer.provideMerge(RepositoryIdentityResolver.layer),
403 Layer.provideMerge(ServerEnvironment.layer),
404 Layer.provideMerge(AuthLayerLive),
405 Layer.provideMerge(ServerSecretStore.layer),
406 Layer.provideMerge(
407 Layer.mergeAll(
408 CloudCliTokenManager.layer.pipe(
409 Layer.provide(ServerSecretStore.layer),
410 Layer.provide(ExternalLauncher.layer),
411 ),
412 CloudManagedEndpointRuntimeLive,
413 ),
414 ),
415);
416
417const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
418 // Misc.
419 Layer.provideMerge(BackgroundLayerLive),
420 Layer.provideMerge(ResourceDiagnosticsLayerLive),
421 Layer.provideMerge(UsageLayerLive),
422 Layer.provideMerge(TraceDiagnostics.layer),
423 Layer.provideMerge(AnalyticsService.layer),
424 Layer.provideMerge(ExternalLauncher.layer),
425 Layer.provideMerge(RemoteOpenTargets.layer),
426 Layer.provideMerge(ServerLifecycleEvents.layer),
427 Layer.provide(NetService.layer),
428);
429
430const commandReadinessLayer = HttpRouter.middleware(
431 (httpEffect) =>
432 Effect.flatMap(ServerRuntimeStartup.ServerRuntimeStartup, (startup) =>
433 startup.awaitCommandReady.pipe(Effect.orDie, Effect.andThen(httpEffect)),
434 ),
435 { global: true },
436);
437
438const PullRequestServiceLive = PullRequestService.layer.pipe(
439 // One registry entry per supported host; the service only knows the registry.
440 Layer.provide(PullRequestProviderRegistry.layer),
441 Layer.provide(SourceControlProviderRegistryLayerLive),
442 Layer.provide(VcsProcess.layer),
443);
444
445export const makeRoutesLayer = Layer.mergeAll(
446 Layer.mergeAll(
447 HttpApiBuilder.layer(EnvironmentHttpApi).pipe(
448 Layer.provide(authHttpApiLayer),
449 Layer.provide(connectHttpApiLayer),
450 Layer.provide(orchestrationHttpApiLayer),
451 Layer.provide(pullRequestHttpApiLayer),
452 Layer.provide(serverEnvironmentHttpApiLayer),
453 Layer.provide(environmentAuthenticatedAuthLayer),
454 ),
455 otlpTracesProxyRouteLayer,
456 assetRouteLayer,
457 staticAndDevRouteLayer,
458 websocketRpcRouteLayer,
459 ),
460 McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer)),
461).pipe(
462 // Both transports consume the same service instance, so caches single-flight across clients
463 // and mutations observed on WebSocket invalidate patches subsequently read over HTTP.
464 Layer.provide(PullRequestServiceLive),
465 Layer.provide(PreviewAutomationBroker.layer),
466 Layer.provide(ServerSelfUpdate.layer),
467 Layer.provide(commandReadinessLayer),
468 Layer.provide(browserApiCorsLayer),
469 Layer.provide(httpCompressionLayer),
470);
471
472export const makeServerLayer = Layer.unwrap(
473 Effect.gen(function* () {
474 const config = yield* ServerConfig.ServerConfig;
475 const activation = yield* Deferred.make<void>();
476 const awaitActivation = Deferred.await(activation);
477 const activationLayer = Layer.succeed(ServerActivation, awaitActivation);
478 const runtimeStateParked = yield* Deferred.make<void>();
479 const tailscaleParked = yield* Deferred.make<void>();
480 const cloudLinkParked = yield* Deferred.make<void>();
481 const routesReady = yield* Deferred.make<void>();
482 const launcherLayer = ServiceLauncherClient.layer;
483
484 yield* fixPath();
485
486 const httpListeningLayer = Layer.effectDiscard(
487 Effect.gen(function* () {
488 yield* HttpServer.HttpServer;
489 const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
490 yield* startup.markHttpListening;
491 }),
492 );
493 const runtimeStateLayer = Layer.effectDiscard(
494 Effect.acquireRelease(
495 Effect.gen(function* () {
496 yield* Deferred.succeed(runtimeStateParked, undefined).pipe(Effect.orDie);
497 yield* awaitActivation;
498 const server = yield* HttpServer.HttpServer;
499 const address = server.address;
500 if (typeof address === "string" || !("port" in address)) {
501 return;
502 }
503
504 const state = yield* makePersistedServerRuntimeState({
505 config,
506 port: address.port,
507 });
508 yield* persistServerRuntimeState({
509 path: config.serverRuntimeStatePath,
510 state,
511 }).pipe(
512 Effect.catchCause((cause) =>
513 Effect.logWarning("Failed to persist server runtime state", { cause }),
514 ),
515 );
516 }),
517 () =>
518 clearPersistedServerRuntimeState(config.serverRuntimeStatePath).pipe(
519 Effect.catchCause((cause) =>
520 Effect.logWarning("Failed to clear server runtime state", { cause }),
521 ),
522 ),
523 ),
524 );
525 const tailscaleServeLayer = config.tailscaleServeEnabled
526 ? Layer.effectDiscard(
527 Effect.acquireRelease(
528 Effect.gen(function* () {
529 yield* Deferred.succeed(tailscaleParked, undefined).pipe(Effect.orDie);
530 yield* awaitActivation;
531 const server = yield* HttpServer.HttpServer;
532 const address = server.address;
533 if (typeof address === "string" || !("port" in address)) {
534 return null;
535 }
536
537 const localPort = address.port;
538 return yield* ensureTailscaleServe({
539 localPort,
540 servePort: config.tailscaleServePort,
541 localHost: "127.0.0.1",
542 }).pipe(
543 Effect.as({ localPort, servePort: config.tailscaleServePort }),
544 Effect.tap(() =>
545 Effect.logInfo("Tailscale Serve configured", {
546 localPort,
547 servePort: config.tailscaleServePort,
548 }),
549 ),
550 Effect.catch((cause) =>
551 Effect.logWarning("Failed to configure Tailscale Serve", {
552 cause,
553 localPort,
554 servePort: config.tailscaleServePort,
555 }).pipe(Effect.as(null)),
556 ),
557 );
558 }),
559 (configured) =>
560 configured
561 ? disableTailscaleServe({ servePort: configured.servePort }).pipe(
562 Effect.tap(() =>
563 Effect.logInfo("Tailscale Serve disabled", {
564 servePort: configured.servePort,
565 }),
566 ),
567 Effect.catch((cause) =>
568 Effect.logWarning("Failed to disable Tailscale Serve", {
569 cause,
570 servePort: configured.servePort,
571 }),
572 ),
573 )
574 : Effect.void,
575 ),
576 )
577 : Layer.empty;
578 const cloudDesiredLinkReconcileLayer = Layer.effectDiscard(
579 Effect.gen(function* () {
580 if (!hasCloudPublicConfig) {
581 yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);
582 return;
583 }
584 const releaseManagedTunnel = releaseManagedTunnelOnShutdown().pipe(
585 Effect.timeout("10 seconds"),
586 Effect.tap((released) =>
587 released ? Effect.logInfo("Released the managed tunnel on shutdown") : Effect.void,
588 ),
589 Effect.catchCause((cause) =>
590 Effect.logWarning(
591 "Failed to release the managed tunnel on shutdown; the next link reuses it",
592 { cause },
593 ),
594 ),
595 Effect.asVoid,
596 );
597 // A launcher trial can be stopped before activation. The previous
598 // server is already gone, so the trial owns cleanup immediately; the
599 // pending-state check keeps the tunnel for normal commit or rollback,
600 // while the launcher's explicit-stop marker allows it to be released.
601 // Other runtimes wait for activation so a failed standby cannot tear
602 // down the active runtime's tunnel.
603 const cleanupBeforeActivation = yield* pendingServiceUpdateExists;
604 if (cleanupBeforeActivation) {
605 yield* Effect.addFinalizer(() => releaseManagedTunnel);
606 }
607 yield* forkParked(
608 Effect.gen(function* () {
609 if (!cleanupBeforeActivation) {
610 yield* Effect.addFinalizer(() => releaseManagedTunnel);
611 }
612 if (!(yield* CloudCliState.readCliDesiredCloudLink)) return;
613 const server = yield* HttpServer.HttpServer;
614 const address = server.address;
615 if (typeof address === "string" || !("port" in address)) return;
616 // No settling delay before the first attempt: routes are already
617 // serving by the time activation opens this gate (the startup
618 // sequence awaits routesReady), and the retry schedule below
619 // covers anything this sleep used to hedge against. Every
620 // millisecond here is dead time on the path to remote
621 // reachability after a restart.
622 yield* reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`).pipe(
623 Effect.retry({
624 while: (error) =>
625 error._tag !== "EnvironmentHttpBadRequestError" &&
626 error._tag !== "EnvironmentHttpUnauthorizedError" &&
627 error._tag !== "EnvironmentHttpConflictError",
628 schedule: Schedule.exponential("1 second").pipe(
629 Schedule.modifyDelay(({ duration }) =>
630 Effect.succeed(Duration.min(duration, Duration.seconds(30))),
631 ),
632 Schedule.upTo({ duration: "10 minutes" }),
633 ),
634 }),
635 Effect.tap(() => Effect.logInfo("T3 Connect desired link reconciled on startup")),
636 Effect.catch((cause) =>
637 Effect.logWarning("Failed to reconcile T3 Connect desired link on startup", {
638 cause,
639 }),
640 ),
641 );
642 }),
643 );
644 yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);
645 }),
646 );
647
648 const runtimeServicesLive = ServerRuntimeStartup.layerWithOptions({
649 activate: Deferred.succeed(activation, undefined).pipe(Effect.asVoid),
650 abort: (error) => Deferred.die(activation, error).pipe(Effect.asVoid),
651 awaitAuxiliaryParked: Effect.all(
652 [
653 Deferred.await(runtimeStateParked),
654 Deferred.await(cloudLinkParked),
655 Deferred.await(routesReady),
656 ...(config.tailscaleServeEnabled ? [Deferred.await(tailscaleParked)] : []),
657 ],
658 { concurrency: "unbounded" },
659 ).pipe(Effect.asVoid),
660 }).pipe(Layer.provideMerge(RuntimeDependenciesLive), Layer.provide(launcherLayer));
661
662 const routesLayer = HttpRouter.serve(makeRoutesLayer.pipe(Layer.provide(launcherLayer)), {
663 disableLogger: !config.logWebSocketEvents,
664 }).pipe(Layer.tap(() => Deferred.succeed(routesReady, undefined).pipe(Effect.orDie)));
665 const serverApplicationLayer = Layer.mergeAll(
666 routesLayer,
667 httpListeningLayer,
668 runtimeStateLayer,
669 tailscaleServeLayer,
670 cloudDesiredLinkReconcileLayer,
671 );
672
673 return serverApplicationLayer.pipe(
674 Layer.provideMerge(runtimeServicesLive),
675 Layer.provide(activationLayer),
676 Layer.provideMerge(serverRelayBrokerTracingLayer),
677 Layer.provideMerge(HttpServerLive),
678 Layer.provide(ApplicationObservabilityLive),
679 Layer.provideMerge(FetchHttpClient.layer),
680 Layer.provideMerge(VcsProcess.layer),
681 Layer.provideMerge(PlatformServicesLive),
682 );
683 }),
684);
685
686// The CLI supplies configuration.
687export const runServer = Layer.launch(makeServerLayer);