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