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