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