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

server.ts

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