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