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