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

server.ts

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