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

server.ts

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