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