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