Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

server.ts

574 lines23.5 KB

1import { EnvironmentHttpApi } from "@t3tools/contracts";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Schedule from "effect/Schedule";
6import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http";
7import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
8​
9import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
10import * as HostPowerMonitor from "./background/HostPowerMonitor.ts";
11import * as ServerConfig from "./config.ts";
12import * as HttpResponseCompression from "./httpCompression/HttpResponseCompression.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 { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
25import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
26import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
27import * as OpenCodeRuntime from "./provider/opencodeRuntime.ts";
28import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
29import * as CheckpointStore from "./checkpointing/CheckpointStore.ts";
30import * as AzureDevOpsCli from "./sourceControl/AzureDevOpsCli.ts";
31import * as BitbucketApi from "./sourceControl/BitbucketApi.ts";
32import * as GitHubCli from "./sourceControl/GitHubCli.ts";
33import * as GitLabCli from "./sourceControl/GitLabCli.ts";
34import * as TextGeneration from "./textGeneration/TextGeneration.ts";
35import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/ProviderInstanceRegistryHydration.ts";
36import { layer as ProviderEventLoggersLive } from "./provider/Layers/ProviderEventLoggers.ts";
37import * as TerminalManager from "./terminal/Manager.ts";
38import * as McpHttpServer from "./mcp/McpHttpServer.ts";
39import * as McpSessionRegistry from "./mcp/McpSessionRegistry.ts";
40import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
41import * as PreviewManager from "./preview/Manager.ts";
42import * as PortScanner from "./preview/PortScanner.ts";
43import * as ProcessRunner from "./processRunner.ts";
44import * as GitManager from "./git/GitManager.ts";
45import * as Keybindings from "./keybindings.ts";
46import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
47import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
48import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
49import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry.ts";
50import * as ServerSettings from "./serverSettings.ts";
51import * as ProjectEnrichmentService from "./project/ProjectEnrichmentService.ts";
52import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts";
53import * as T3ProjectFileLoader from "./project/T3ProjectFileLoader.ts";
54import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
55import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
56import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
57import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
58import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
59import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";
60import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";
61import * as VcsProcess from "./vcs/VcsProcess.ts";
62import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
63import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
64import * as GitWorkflowService from "./git/GitWorkflowService.ts";
65import * as ReviewService from "./review/ReviewService.ts";
66import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
67import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
68import { ObservabilityLive } from "./observability/Layers/Observability.ts";
69import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
70import { authHttpApiLayer, environmentAuthenticatedAuthLayer } from "./auth/http.ts";
71import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
72import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
73import {
74 connectHttpApiLayer,
75 reconcileDesiredCloudLink,
76 releaseManagedTunnelOnShutdown,
77} from "./cloud/http.ts";
78import { serverRelayBrokerTracingLayer } from "./cloud/relayTracing.ts";
79import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts";
80import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts";
81import * as CloudCliState from "./cloud/CliState.ts";
82import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
83import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
84import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
85import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
86import {
87 OrchestrationV2ProductionLayerLive,
88 ProjectSetupScriptRunnerLayerLive,
89} from "./orchestration-v2/runtimeLayer.ts";
90import * as ResourceCleanupService from "./orchestration-v2/ResourceCleanupService.ts";
91import * as RunFinalizationService from "./orchestration-v2/RunFinalizationService.ts";
92import * as DesktopTelemetryReceiver from "./resourceTelemetry/DesktopTelemetryReceiver.ts";
93import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClient.ts";
94import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts";
95import * as ResourceMonitorBinary from "./resourceTelemetry/ResourceMonitorBinary.ts";
96import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
97import {
98 clearPersistedServerRuntimeState,
99 makePersistedServerRuntimeState,
100 persistServerRuntimeState,
101} from "./serverRuntimeState.ts";
102import { orchestrationHttpApiLayer } from "./orchestration-v2/http.ts";
103import { projectHttpApiLayer } from "./project/http.ts";
104import * as NetService from "@t3tools/shared/Net";
105import * as RelayClient from "@t3tools/shared/relayClient";
106import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale";
107​
108// Effect's default preemptive shutdown waits 20s before finalizing request scopes.
109// T3's primary transport is long-lived WebSocket RPC, whose Effect scope finalizer
110// already closes the websocket gracefully. Do not add an artificial drain before
111// those finalizers get a chance to run.
112const HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS = 0;
113const ResourceAttributionLayerLive = ResourceAttribution.layer;
114const ApplicationObservabilityLive = ObservabilityLive.pipe(
115 Layer.provideMerge(ResourceAttributionLayerLive),
116);
117​
118const PtyAdapterLive = Layer.unwrap(
119 Effect.gen(function* () {
120 if (typeof Bun !== "undefined") {
121 const BunPtyAdapter = yield* Effect.promise(() => import("./terminal/BunPtyAdapter.ts"));
122 return BunPtyAdapter.layer;
123 } else {
124 const NodePtyAdapter = yield* Effect.promise(() => import("./terminal/NodePtyAdapter.ts"));
125 return NodePtyAdapter.layer;
126 }
127 }),
128);
129​
130const ServerSettingsLayerLive = ServerSettings.layer.pipe(Layer.provide(ServerSecretStore.layer));
131​
132const NativeTelemetryLayerLive = NativeTelemetryClient.layer.pipe(
133 Layer.provide(ResourceMonitorBinary.layer),
134);
135const DesktopTelemetryReceiverLayerLive = DesktopTelemetryReceiver.layer.pipe(
136 Layer.provideMerge(ServerSettingsLayerLive),
137);
138​
139const ResourceTelemetryLayerLive = ResourceTelemetry.layer.pipe(
140 Layer.provideMerge(NativeTelemetryLayerLive),
141 Layer.provideMerge(DesktopTelemetryReceiverLayerLive),
142);
143​
144const HostPowerMonitorLayerLive = HostPowerMonitor.layer.pipe(
145 Layer.provide(DesktopTelemetryReceiverLayerLive),
146);
147​
148const BackgroundLayerLive = BackgroundPolicy.layer.pipe(
149 Layer.provide(HostPowerMonitorLayerLive),
150 Layer.provideMerge(ServerSettingsLayerLive),
151);
152​
153const ResourceDiagnosticsLayerLive = Layer.mergeAll(
154 ResourceTelemetryLayerLive,
155 ProcessDiagnostics.layer.pipe(Layer.provide(ResourceTelemetryLayerLive)),
156 ProcessResourceMonitor.layer.pipe(Layer.provide(ResourceTelemetryLayerLive)),
157);
158​
159const RelayClientLive = Layer.unwrap(
160 Effect.gen(function* () {
161 const config = yield* ServerConfig.ServerConfig;
162 return RelayClient.layerCloudflared({ baseDir: config.baseDir });
163 }),
164);
165​
166const HttpServerLive = Layer.unwrap(
167 Effect.gen(function* () {
168 const config = yield* ServerConfig.ServerConfig;
169 if (typeof Bun !== "undefined") {
170 const BunHttpServer = yield* Effect.promise(
171 () => import("@effect/platform-bun/BunHttpServer"),
172 );
173 return BunHttpServer.layer({
174 port: config.port,
175 hostname: config.host ?? "127.0.0.1",
176 gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
177 });
178 } else {
179 const [NodeHttpServer, NodeHttp] = yield* Effect.all([
180 Effect.promise(() => import("@effect/platform-node/NodeHttpServer")),
181 Effect.promise(() => import("node:http")),
182 ]);
183 return NodeHttpServer.layer(NodeHttp.createServer, {
184 host: config.host ?? "127.0.0.1",
185 port: config.port,
186 gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
187 });
188 }
189 }),
190);
191​
192const HttpResponseCompressionLive =
193 typeof Bun !== "undefined" ? HttpResponseCompression.layerBun : HttpResponseCompression.layerNode;
194​
195const PlatformServicesLive = Layer.unwrap(
196 Effect.gen(function* () {
197 if (typeof Bun !== "undefined") {
198 const { layer } = yield* Effect.promise(() => import("@effect/platform-bun/BunServices"));
199 return layer;
200 } else {
201 const { layer } = yield* Effect.promise(() => import("@effect/platform-node/NodeServices"));
202 return layer;
203 }
204 }),
205);
206​
207const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive));
208​
209const VcsDriverRegistryLayerLive = VcsDriverRegistry.layer.pipe(
210 Layer.provide(VcsProjectConfig.layer),
211);
212​
213const SourceControlProviderRegistryLayerLive = SourceControlProviderRegistry.layer.pipe(
214 Layer.provide(
215 Layer.mergeAll(AzureDevOpsCli.layer, BitbucketApi.layer, GitHubCli.layer, GitLabCli.layer),
216 ),
217 Layer.provideMerge(GitVcsDriver.layer),
218 Layer.provideMerge(VcsDriverRegistryLayerLive),
219);
220​
221const GitManagerLayerLive = GitManager.layer.pipe(
222 Layer.provideMerge(ProjectSetupScriptRunnerLayerLive),
223 Layer.provideMerge(GitVcsDriver.layer),
224 Layer.provideMerge(SourceControlProviderRegistryLayerLive),
225 Layer.provideMerge(TextGeneration.layer),
226);
227​
228const GitLayerLive = Layer.empty.pipe(
229 Layer.provideMerge(GitManagerLayerLive),
230 Layer.provideMerge(GitVcsDriver.layer),
231);
232​
233const GitWorkflowLayerLive = GitWorkflowService.layer.pipe(
234 Layer.provideMerge(VcsDriverRegistryLayerLive),
235 Layer.provideMerge(GitLayerLive),
236);
237​
238const SourceControlRepositoryServiceLayerLive = SourceControlRepositoryService.layer.pipe(
239 Layer.provideMerge(GitVcsDriver.layer),
240 Layer.provideMerge(SourceControlProviderRegistryLayerLive),
241);
242​
243const ReviewLayerLive = ReviewService.layer.pipe(
244 Layer.provideMerge(GitVcsDriver.layer),
245 Layer.provideMerge(VcsDriverRegistryLayerLive),
246);
247​
248const VcsLayerLive = Layer.empty.pipe(
249 Layer.provideMerge(VcsProjectConfig.layer),
250 Layer.provideMerge(VcsDriverRegistryLayerLive),
251 Layer.provideMerge(VcsProvisioningService.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
252 Layer.provideMerge(GitWorkflowLayerLive),
253 Layer.provideMerge(ReviewLayerLive),
254 Layer.provideMerge(SourceControlRepositoryServiceLayerLive),
255 Layer.provideMerge(VcsStatusBroadcaster.layer.pipe(Layer.provide(GitWorkflowLayerLive))),
256);
257​
258const CheckpointStoreLayerLive = CheckpointStore.layer.pipe(
259 Layer.provide(VcsDriverRegistryLayerLive),
260);
261​
262const PortScannerLayerLive = PortScanner.layer.pipe(Layer.provide(ProcessRunner.layer));
263​
264const TerminalLayerLive = TerminalManager.layer.pipe(
265 Layer.provide(PtyAdapterLive),
266 Layer.provide(PortScannerLayerLive),
267);
268​
269const PreviewLayerLive = Layer.empty.pipe(
270 Layer.provideMerge(PreviewManager.layer),
271 Layer.provideMerge(PortScannerLayerLive),
272);
273​
274const WorkspaceEntriesLayerLive = WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePaths.layer));
275​
276const WorkspaceFileSystemLayerLive = WorkspaceFileSystem.layer.pipe(
277 Layer.provide(WorkspacePaths.layer),
278 Layer.provide(WorkspaceEntriesLayerLive),
279);
280​
281const WorkspaceLayerLive = Layer.mergeAll(
282 WorkspacePaths.layer,
283 WorkspaceEntriesLayerLive,
284 WorkspaceFileSystemLayerLive,
285);
286​
287const ProjectFaviconResolverLayerLive = ProjectFaviconResolver.layer.pipe(
288 Layer.provide(WorkspacePaths.layer),
289 Layer.provide(T3ProjectFileLoader.layer),
290);
291​
292const AuthLayerLive = EnvironmentAuth.layer.pipe(
293 Layer.provideMerge(PersistenceLayerLive),
294 Layer.provide(ServerSecretStore.layer),
295);
296​
297const CloudManagedEndpointRuntimeLive = Layer.mergeAll(
298 RelayClientLive,
299 CloudManagedEndpointRuntime.layer.pipe(
300 Layer.provide(ServerSecretStore.layer),
301 Layer.provide(RelayClientLive),
302 ),
303);
304​
305const OrchestrationV2RuntimeLayerLive = OrchestrationV2ProductionLayerLive.pipe(
306 Layer.provide(CheckpointStoreLayerLive),
307 Layer.provide(ResourceCleanupService.live),
308 Layer.provide(RunFinalizationService.observerLive),
309);
310​
311const OrchestrationApplicationLayerLive = CheckpointDiffQuery.layer.pipe(
312 Layer.provideMerge(CheckpointStoreLayerLive),
313 Layer.provideMerge(OrchestrationV2RuntimeLayerLive),
314);
315​
316const RuntimeCoreDependenciesBaseLive = AgentAwarenessRelay.layer.pipe(
317 // Core Services
318 Layer.provideMerge(OrchestrationApplicationLayerLive),
319 Layer.provideMerge(ServerSettingsLayerLive),
320 Layer.provideMerge(SourceControlProviderRegistryLayerLive),
321 Layer.provideMerge(GitLayerLive),
322 Layer.provideMerge(VcsLayerLive),
323 Layer.provideMerge(Layer.mergeAll(TerminalLayerLive, PreviewLayerLive)),
324 Layer.provideMerge(PersistenceLayerLive),
325 Layer.provideMerge(Keybindings.layer),
326 Layer.provideMerge(ProviderRegistryLive),
327 // The instance registry is the new routing keystone — text generation,
328 // adapter lookup, and runtime ingestion all resolve `ProviderInstanceId`
329 // through this layer. Built-in drivers come from `BUILT_IN_DRIVERS`;
330 // `providerInstances` hydration merges `settings.providers.<kind>`
331 // with explicit `providerInstances` entries on boot.
332 Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
333);
334​
335const RuntimeCoreDependenciesLive = RuntimeCoreDependenciesBaseLive.pipe(
336 // Shared native/canonical NDJSON writers used by both the per-instance
337 // V2 drivers and the orchestration runtime. Provide resource attribution so
338 // the rewritten telemetry pipeline can account for logical NDJSON writes.
339 // Provided once at the runtime level so every consumer sees the same
340 // logger instances.
341 Layer.provideMerge(ProviderEventLoggersLive),
342 // `OpenCodeDriver.create()` yields `OpenCodeRuntime`; previously the old
343 // `ProviderRegistryLive` pulled `OpenCodeRuntimeLive` in for itself, but
344 // the rewritten registry reads snapshots off the instance registry and
345 // no longer transitively provides it. Exposing it at the runtime level
346 // keeps a single Live for all opencode consumers.
347 Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
348 Layer.provideMerge(WorkspaceLayerLive),
349 Layer.provideMerge(ProjectEnrichmentService.layer),
350 Layer.provideMerge(ProjectFaviconResolverLayerLive),
351 Layer.provideMerge(RepositoryIdentityResolver.layer),
352 Layer.provideMerge(ServerEnvironment.layer),
353 Layer.provideMerge(AuthLayerLive),
354 Layer.provideMerge(ServerSecretStore.layer),
355 Layer.provideMerge(
356 Layer.mergeAll(
357 CloudCliTokenManager.layer.pipe(
358 Layer.provide(ServerSecretStore.layer),
359 Layer.provide(ExternalLauncher.layer),
360 ),
361 CloudManagedEndpointRuntimeLive,
362 ),
363 ),
364);
365​
366const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
367 // Misc.
368 Layer.provideMerge(BackgroundLayerLive),
369 Layer.provideMerge(ResourceDiagnosticsLayerLive),
370 Layer.provideMerge(TraceDiagnostics.layer),
371 Layer.provideMerge(AnalyticsService.layer),
372 Layer.provideMerge(ExternalLauncher.layer),
373 Layer.provideMerge(ServerLifecycleEvents.layer),
374 Layer.provide(NetService.layer),
375);
376​
377const RuntimeServicesLive = ServerRuntimeStartup.layer.pipe(
378 Layer.provideMerge(RuntimeDependenciesLive),
379);
380​
381export const makeRoutesLayer = Layer.mergeAll(
382 Layer.mergeAll(
383 HttpApiBuilder.layer(EnvironmentHttpApi).pipe(
384 Layer.provide(authHttpApiLayer),
385 Layer.provide(connectHttpApiLayer),
386 Layer.provide(orchestrationHttpApiLayer),
387 Layer.provide(projectHttpApiLayer),
388 Layer.provide(serverEnvironmentHttpApiLayer),
389 Layer.provide(environmentAuthenticatedAuthLayer),
390 ),
391 otlpTracesProxyRouteLayer,
392 assetRouteLayer,
393 staticAndDevRouteLayer,
394 websocketRpcRouteLayer,
395 ),
396 McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer)),
397).pipe(
398 Layer.provide(PreviewAutomationBroker.layer),
399 Layer.provide(ServerSelfUpdate.layer),
400 Layer.provide(browserApiCorsLayer),
401 Layer.provide(httpCompressionLayer),
402);
403​
404export const makeServerLayer = Layer.unwrap(
405 Effect.gen(function* () {
406 const config = yield* ServerConfig.ServerConfig;
407​
408 yield* fixPath();
409​
410 const httpListeningLayer = Layer.effectDiscard(
411 Effect.gen(function* () {
412 yield* HttpServer.HttpServer;
413 const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
414 yield* startup.markHttpListening;
415 }),
416 );
417 const runtimeStateLayer = Layer.effectDiscard(
418 Effect.acquireRelease(
419 Effect.gen(function* () {
420 const server = yield* HttpServer.HttpServer;
421 const address = server.address;
422 if (typeof address === "string" || !("port" in address)) {
423 return;
424 }
425​
426 const state = yield* makePersistedServerRuntimeState({
427 config,
428 port: address.port,
429 });
430 yield* persistServerRuntimeState({
431 path: config.serverRuntimeStatePath,
432 state,
433 });
434 }),
435 () => clearPersistedServerRuntimeState(config.serverRuntimeStatePath),
436 ),
437 );
438 const tailscaleServeLayer = config.tailscaleServeEnabled
439 ? Layer.effectDiscard(
440 Effect.acquireRelease(
441 Effect.gen(function* () {
442 const server = yield* HttpServer.HttpServer;
443 const address = server.address;
444 if (typeof address === "string" || !("port" in address)) {
445 return null;
446 }
447​
448 const localPort = address.port;
449 return yield* ensureTailscaleServe({
450 localPort,
451 servePort: config.tailscaleServePort,
452 localHost: "127.0.0.1",
453 }).pipe(
454 Effect.as({ localPort, servePort: config.tailscaleServePort }),
455 Effect.tap(() =>
456 Effect.logInfo("Tailscale Serve configured", {
457 localPort,
458 servePort: config.tailscaleServePort,
459 }),
460 ),
461 Effect.catch((cause) =>
462 Effect.logWarning("Failed to configure Tailscale Serve", {
463 cause,
464 localPort,
465 servePort: config.tailscaleServePort,
466 }).pipe(Effect.as(null)),
467 ),
468 );
469 }),
470 (configured) =>
471 configured
472 ? disableTailscaleServe({ servePort: configured.servePort }).pipe(
473 Effect.tap(() =>
474 Effect.logInfo("Tailscale Serve disabled", {
475 servePort: configured.servePort,
476 }),
477 ),
478 Effect.catch((cause) =>
479 Effect.logWarning("Failed to disable Tailscale Serve", {
480 cause,
481 servePort: configured.servePort,
482 }),
483 ),
484 )
485 : Effect.void,
486 ),
487 )
488 : Layer.empty;
489 const cloudDesiredLinkReconcileLayer = Layer.effectDiscard(
490 Effect.gen(function* () {
491 if (!hasCloudPublicConfig) return;
492 // Idle Cloudflare tunnels are billed, so a stopping server releases its
493 // tunnel; the persisted desired link brings one back — same hostname,
494 // fresh tunnel — when the environment starts again. Registered even
495 // when no link is desired yet: a client can link a running server, and
496 // that tunnel needs the same disposal on shutdown.
497 yield* Effect.addFinalizer(() =>
498 releaseManagedTunnelOnShutdown().pipe(
499 Effect.timeout("10 seconds"),
500 Effect.tap((released) =>
501 released ? Effect.logInfo("Released the managed tunnel on shutdown") : Effect.void,
502 ),
503 Effect.catchCause((cause) =>
504 Effect.logWarning(
505 "Failed to release the managed tunnel on shutdown; the next link reuses it",
506 { cause },
507 ),
508 ),
509 Effect.asVoid,
510 ),
511 );
512 if (!(yield* CloudCliState.readCliDesiredCloudLink)) return;
513 const server = yield* HttpServer.HttpServer;
514 const address = server.address;
515 if (typeof address === "string" || !("port" in address)) return;
516 yield* Effect.forkScoped(
517 Effect.sleep("250 millis").pipe(
518 Effect.andThen(reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`)),
519 // On reboot this races NIC/DNS bring-up, so back off exponentially
520 // (capped at 30s) instead of burning all retries in a second.
521 // Bounded overall so a permanently broken setup still surfaces the
522 // warning below. Bad-request/unauthorized/conflict are
523 // deterministic failures (malformed origin, not linked yet, linked
524 // to a different cloud account) that no amount of retrying
525 // converges.
526 Effect.retry({
527 while: (error) =>
528 error._tag !== "EnvironmentHttpBadRequestError" &&
529 error._tag !== "EnvironmentHttpUnauthorizedError" &&
530 error._tag !== "EnvironmentHttpConflictError",
531 schedule: Schedule.exponential("1 second").pipe(
532 Schedule.modifyDelay(({ duration }) =>
533 Effect.succeed(Duration.min(duration, Duration.seconds(30))),
534 ),
535 Schedule.upTo({ duration: "10 minutes" }),
536 ),
537 }),
538 Effect.tap(() => Effect.logInfo("T3 Connect desired link reconciled on startup")),
539 Effect.catch((cause) =>
540 Effect.logWarning("Failed to reconcile T3 Connect desired link on startup", {
541 cause,
542 }),
543 ),
544 ),
545 );
546 }),
547 );
548​
549 const serverApplicationLayer = Layer.mergeAll(
550 HttpRouter.serve(makeRoutesLayer, {
551 disableLogger: !config.logWebSocketEvents,
552 }),
553 httpListeningLayer,
554 runtimeStateLayer,
555 tailscaleServeLayer,
556 cloudDesiredLinkReconcileLayer,
557 );
558​
559 return serverApplicationLayer.pipe(
560 Layer.provideMerge(RuntimeServicesLive),
561 Layer.provideMerge(McpSessionRegistry.layer.pipe(Layer.provide(ServerEnvironment.layer))),
562 Layer.provideMerge(serverRelayBrokerTracingLayer),
563 Layer.provideMerge(HttpResponseCompressionLive),
564 Layer.provideMerge(HttpServerLive),
565 Layer.provide(ApplicationObservabilityLive),
566 Layer.provideMerge(FetchHttpClient.layer),
567 Layer.provideMerge(VcsProcess.layer),
568 Layer.provideMerge(PlatformServicesLive),
569 );
570 }),
571);
572​
573// Important: Only `ServerConfig` should be provided by the CLI layer!!! Don't let other requirements leak into the launch layer.
574export const runServer = Layer.launch(makeServerLayer);