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

server.ts

632 lines26.2 KB

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