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

server.ts

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