Files
t3code/apps/server/src/server.ts
T
Julius Marminge 661dbc96d4 Handle preparing turns across provider orchestration
- Treat preparing as an active turn state in mobile and server flows
- Tighten ACP model option validation and selection reconfiguration
- Add coverage for turn mapping, raw protocol logging, and recovery paths
2026-08-15 16:49:40 +02:00

656 lines
28 KiB
TypeScript

import { EnvironmentHttpApi } from "@t3tools/contracts";
import * as Duration from "effect/Duration";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schedule from "effect/Schedule";
import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http";
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
import * as HostPowerMonitor from "./background/HostPowerMonitor.ts";
import * as ServerConfig from "./config.ts";
import {
otlpTracesProxyRouteLayer,
assetRouteLayer,
serverEnvironmentHttpApiLayer,
staticAndDevRouteLayer,
browserApiCorsLayer,
httpCompressionLayer,
} from "./http.ts";
import { guardHttpResponseWriteErrors } from "./httpResponseErrorGuard.ts";
import { fixPath } from "./os-jank.ts";
import { websocketRpcRouteLayer } from "./ws.ts";
import * as ExternalLauncher from "./process/externalLauncher.ts";
import { pullRequestHttpApiLayer } from "./pullRequest/http.ts";
import * as PullRequestProviderRegistry from "./pullRequest/PullRequestProviderRegistry.ts";
import * as PullRequestService from "./pullRequest/PullRequestService.ts";
import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
import * as OpenCodeRuntime from "./provider/opencodeRuntime.ts";
import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
import * as CheckpointStore from "./checkpointing/CheckpointStore.ts";
import * as AzureDevOpsCli from "./sourceControl/AzureDevOpsCli.ts";
import * as BitbucketApi from "./sourceControl/BitbucketApi.ts";
import * as GitHubCli from "./sourceControl/GitHubCli.ts";
import * as GitLabCli from "./sourceControl/GitLabCli.ts";
import * as TextGeneration from "./textGeneration/TextGeneration.ts";
import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/ProviderInstanceRegistryHydration.ts";
import { ProviderEventLoggersLive } from "./provider/Layers/ProviderEventLoggers.ts";
import * as TerminalManager from "./terminal/Manager.ts";
import * as McpHttpServer from "./mcp/McpHttpServer.ts";
import * as McpSessionRegistry from "./mcp/McpSessionRegistry.ts";
import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
import * as PreviewManager from "./preview/Manager.ts";
import * as PortScanner from "./preview/PortScanner.ts";
import * as ProcessRunner from "./processRunner.ts";
import * as GitManager from "./git/GitManager.ts";
import * as Keybindings from "./keybindings.ts";
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry.ts";
import * as ServerSettings from "./serverSettings.ts";
import * as ProjectEnrichmentService from "./project/ProjectEnrichmentService.ts";
import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts";
import * as T3ProjectFileLoader from "./project/T3ProjectFileLoader.ts";
import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";
import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";
import * as VcsProcess from "./vcs/VcsProcess.ts";
import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
import * as ReviewService from "./review/ReviewService.ts";
import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
import { ObservabilityLive } from "./observability/Layers/Observability.ts";
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";
import { authHttpApiLayer, environmentAuthenticatedAuthLayer } from "./auth/http.ts";
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import {
connectHttpApiLayer,
pendingServiceUpdateExists,
reconcileDesiredCloudLink,
releaseManagedTunnelOnShutdown,
} from "./cloud/http.ts";
import { serverRelayBrokerTracingLayer } from "./cloud/relayTracing.ts";
import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts";
import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts";
import * as CloudCliState from "./cloud/CliState.ts";
import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
import * as DesktopTelemetryReceiver from "./resourceTelemetry/DesktopTelemetryReceiver.ts";
import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClient.ts";
import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts";
import * as ResourceMonitorBinary from "./resourceTelemetry/ResourceMonitorBinary.ts";
import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
import * as UsageService from "./usage/UsageService.ts";
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
import {
OrchestrationV2ProductionLayerLive,
ProjectSetupScriptRunnerLayerLive,
} from "./orchestration-v2/runtimeLayer.ts";
import * as ResourceCleanupService from "./orchestration-v2/ResourceCleanupService.ts";
import * as RunFinalizationService from "./orchestration-v2/RunFinalizationService.ts";
import {
clearPersistedServerRuntimeState,
makePersistedServerRuntimeState,
persistServerRuntimeState,
} from "./serverRuntimeState.ts";
import { projectHttpApiLayer } from "./project/http.ts";
import * as NetService from "@t3tools/shared/Net";
import * as RelayClient from "@t3tools/shared/relayClient";
import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale";
// Effect's default preemptive shutdown waits 20s before finalizing request scopes.
// T3's primary transport is long-lived WebSocket RPC, whose Effect scope finalizer
// already closes the websocket gracefully. Do not add an artificial drain before
// those finalizers get a chance to run.
const HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS = 0;
const PtyAdapterLive = Layer.unwrap(
Effect.gen(function* () {
if (typeof Bun !== "undefined") {
const BunPtyAdapter = yield* Effect.promise(() => import("./terminal/BunPtyAdapter.ts"));
return BunPtyAdapter.layer;
} else {
const NodePtyAdapter = yield* Effect.promise(() => import("./terminal/NodePtyAdapter.ts"));
return NodePtyAdapter.layer;
}
}),
);
const ServerSettingsLayerLive = ServerSettings.layer.pipe(Layer.provide(ServerSecretStore.layer));
const NativeTelemetryLayerLive = NativeTelemetryClient.layer.pipe(
Layer.provide(ResourceMonitorBinary.layer),
);
const DesktopTelemetryReceiverLayerLive = DesktopTelemetryReceiver.layer.pipe(
Layer.provideMerge(ServerSettingsLayerLive),
);
const ResourceTelemetryLayerLive = ResourceTelemetry.layer.pipe(
Layer.provideMerge(NativeTelemetryLayerLive),
Layer.provideMerge(DesktopTelemetryReceiverLayerLive),
);
const HostPowerMonitorLayerLive = HostPowerMonitor.layer.pipe(
Layer.provide(DesktopTelemetryReceiverLayerLive),
);
const BackgroundLayerLive = BackgroundPolicy.layer.pipe(
Layer.provide(HostPowerMonitorLayerLive),
Layer.provideMerge(ServerSettingsLayerLive),
);
const UsageLayerLive = UsageService.layer.pipe(Layer.provide(ServerSettingsLayerLive));
const ResourceDiagnosticsLayerLive = Layer.mergeAll(
ResourceTelemetryLayerLive,
ProcessDiagnostics.layer.pipe(Layer.provide(ResourceTelemetryLayerLive)),
ProcessResourceMonitor.layer.pipe(Layer.provide(ResourceTelemetryLayerLive)),
);
const RelayClientLive = Layer.unwrap(
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
return RelayClient.layerCloudflared({ baseDir: config.baseDir });
}),
);
const HttpServerLive = Layer.unwrap(
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
if (typeof Bun !== "undefined") {
const BunHttpServer = yield* Effect.promise(
() => import("@effect/platform-bun/BunHttpServer"),
);
return BunHttpServer.layer({
port: config.port,
hostname: config.host ?? "127.0.0.1",
gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
websocket: {
// Negotiate permessage-deflate with clients that offer it; clients
// that don't still get uncompressed frames on their connection. A
// dedicated compressor keeps a per-connection sliding window
// (context takeover) so the compression dictionary is shared across
// server-to-client frames. Decompression uses the shared
// decompressor: uWebSockets' dedicated decompressor path can abort
// connections (close 1006) on valid DEFLATE input — see
// https://github.com/uNetworking/uWebSockets.js/issues/633.
perMessageDeflate: {
compress: "dedicated",
decompress: "shared",
},
},
});
} else {
const [NodeHttpServer, NodeHttp] = yield* Effect.all([
Effect.promise(() => import("@effect/platform-node/NodeHttpServer")),
Effect.promise(() => import("node:http")),
]);
return NodeHttpServer.layer(() => guardHttpResponseWriteErrors(NodeHttp.createServer()), {
host: config.host ?? "127.0.0.1",
port: config.port,
gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
// Negotiate permessage-deflate with clients that offer it; clients
// that don't still get uncompressed frames on their connection.
// Context takeover stays enabled (ws default) so the compression
// window is shared across frames — that also makes small frames cheap
// to compress, so no size threshold is set (ws only honors
// `threshold` when context takeover is disabled).
websocket: { perMessageDeflate: true },
});
}
}),
);
const PlatformServicesLive = Layer.unwrap(
Effect.gen(function* () {
if (typeof Bun !== "undefined") {
const { layer } = yield* Effect.promise(() => import("@effect/platform-bun/BunServices"));
return layer;
} else {
const { layer } = yield* Effect.promise(() => import("@effect/platform-node/NodeServices"));
return layer;
}
}),
);
const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive));
const VcsDriverRegistryLayerLive = VcsDriverRegistry.layer.pipe(
Layer.provide(VcsProjectConfig.layer),
);
const SourceControlProviderRegistryLayerLive = SourceControlProviderRegistry.layer.pipe(
Layer.provide(
Layer.mergeAll(AzureDevOpsCli.layer, BitbucketApi.layer, GitHubCli.layer, GitLabCli.layer),
),
Layer.provideMerge(GitVcsDriver.layer),
Layer.provideMerge(VcsDriverRegistryLayerLive),
);
const GitManagerLayerLive = GitManager.layer.pipe(
Layer.provideMerge(ProjectSetupScriptRunnerLayerLive),
Layer.provideMerge(GitVcsDriver.layer),
Layer.provideMerge(SourceControlProviderRegistryLayerLive),
Layer.provideMerge(TextGeneration.layer),
);
const GitLayerLive = Layer.empty.pipe(
Layer.provideMerge(GitManagerLayerLive),
Layer.provideMerge(GitVcsDriver.layer),
);
const GitWorkflowLayerLive = GitWorkflowService.layer.pipe(
Layer.provideMerge(VcsDriverRegistryLayerLive),
Layer.provideMerge(GitLayerLive),
);
const SourceControlRepositoryServiceLayerLive = SourceControlRepositoryService.layer.pipe(
Layer.provideMerge(GitVcsDriver.layer),
Layer.provideMerge(SourceControlProviderRegistryLayerLive),
);
const ReviewLayerLive = ReviewService.layer.pipe(
Layer.provideMerge(GitVcsDriver.layer),
Layer.provideMerge(VcsDriverRegistryLayerLive),
);
const VcsLayerLive = Layer.empty.pipe(
Layer.provideMerge(VcsProjectConfig.layer),
Layer.provideMerge(VcsDriverRegistryLayerLive),
Layer.provideMerge(VcsProvisioningService.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
Layer.provideMerge(GitWorkflowLayerLive),
Layer.provideMerge(ReviewLayerLive),
Layer.provideMerge(SourceControlRepositoryServiceLayerLive),
Layer.provideMerge(VcsStatusBroadcaster.layer.pipe(Layer.provide(GitWorkflowLayerLive))),
);
const CheckpointStoreLayerLive = CheckpointStore.layer.pipe(
Layer.provide(VcsDriverRegistryLayerLive),
);
const PortScannerLayerLive = PortScanner.layer.pipe(Layer.provide(ProcessRunner.layer));
const TerminalLayerLive = TerminalManager.layer.pipe(
Layer.provide(PtyAdapterLive),
Layer.provide(PortScannerLayerLive),
);
const PreviewLayerLive = Layer.empty.pipe(
Layer.provideMerge(PreviewManager.layer),
Layer.provideMerge(PortScannerLayerLive),
);
const WorkspaceEntriesLayerLive = WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePaths.layer));
const WorkspaceFileSystemLayerLive = WorkspaceFileSystem.layer.pipe(
Layer.provide(WorkspacePaths.layer),
Layer.provide(WorkspaceEntriesLayerLive),
);
const WorkspaceLayerLive = Layer.mergeAll(
WorkspacePaths.layer,
WorkspaceEntriesLayerLive,
WorkspaceFileSystemLayerLive,
);
const OrchestrationV2RuntimeLayerLive = OrchestrationV2LayerLive.pipe(
Layer.provide(CheckpointStoreLive),
Layer.provide(GitCoreLive),
Layer.provide(PersistenceLayerLive),
Layer.provide(ServerSettingsLive),
);
const AuthLayerLive = ServerAuthLive.pipe(
Layer.provideMerge(PersistenceLayerLive),
Layer.provide(ServerSecretStore.layer),
);
const CloudManagedEndpointRuntimeLive = Layer.mergeAll(
RelayClientLive,
CloudManagedEndpointRuntime.layer.pipe(
Layer.provide(ServerSecretStore.layer),
Layer.provide(RelayClientLive),
),
);
const OrchestrationV2RuntimeLayerLive = OrchestrationV2ProductionLayerLive.pipe(
Layer.provide(CheckpointStoreLayerLive),
Layer.provide(ResourceCleanupService.live),
Layer.provide(RunFinalizationService.observerLive),
);
const OrchestrationApplicationLayerLive = CheckpointDiffQuery.layer.pipe(
Layer.provideMerge(CheckpointStoreLayerLive),
Layer.provideMerge(OrchestrationV2RuntimeLayerLive),
);
const RuntimeCoreDependenciesBaseLive = AgentAwarenessRelay.layer.pipe(
// Core Services
Layer.provideMerge(OrchestrationApplicationLayerLive),
Layer.provideMerge(SourceControlProviderRegistryLayerLive),
Layer.provideMerge(GitLayerLive),
Layer.provideMerge(VcsLayerLive),
Layer.provideMerge(Layer.mergeAll(TerminalLayerLive, PreviewLayerLive)),
Layer.provideMerge(PersistenceLayerLive),
Layer.provideMerge(Keybindings.layer),
Layer.provideMerge(ProviderRegistryLive),
// The instance registry is the new routing keystone — text generation,
// adapter lookup, and runtime ingestion all resolve `ProviderInstanceId`
// through this layer. Built-in drivers come from `BUILT_IN_DRIVERS`;
// `providerInstances` hydration merges `settings.providers.<kind>`
// with explicit `providerInstances` entries on boot.
Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
);
const RuntimeCoreDependenciesLive = RuntimeCoreDependenciesBaseLive.pipe(
Layer.provideMerge(ProviderEventLoggersLive),
// `OpenCodeDriver.create()` yields `OpenCodeRuntime`; previously the old
// `ProviderRegistryLive` pulled `OpenCodeRuntimeLive` in for itself, but
// the rewritten registry reads snapshots off the instance registry and
// no longer transitively provides it. Exposing it at the runtime level
// keeps a single Live for all opencode consumers.
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
Layer.provideMerge(WorkspaceLayerLive),
Layer.provideMerge(ProjectEnrichmentService.layer),
Layer.provideMerge(ProjectFaviconResolverLayerLive),
Layer.provideMerge(RepositoryIdentityResolver.layer),
Layer.provideMerge(ServerEnvironment.layer),
Layer.provideMerge(AuthLayerLive),
Layer.provideMerge(OrchestrationV2RuntimeLayerLive),
// Misc.
Layer.provideMerge(AnalyticsServiceLayerLive),
Layer.provideMerge(OpenLive),
Layer.provideMerge(ServerLifecycleEventsLive),
);
const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
// Misc.
Layer.provideMerge(BackgroundLayerLive),
Layer.provideMerge(ResourceDiagnosticsLayerLive),
Layer.provideMerge(UsageLayerLive),
Layer.provideMerge(TraceDiagnostics.layer),
Layer.provideMerge(AnalyticsService.layer),
Layer.provideMerge(ExternalLauncher.layer),
Layer.provideMerge(RemoteOpenTargets.layer),
Layer.provideMerge(ServerLifecycleEvents.layer),
Layer.provide(NetService.layer),
);
const commandReadinessLayer = HttpRouter.middleware(
(httpEffect) =>
Effect.flatMap(ServerRuntimeStartup.ServerRuntimeStartup, (startup) =>
startup.awaitCommandReady.pipe(Effect.orDie, Effect.andThen(httpEffect)),
),
{ global: true },
);
const PullRequestServiceLive = PullRequestService.layer.pipe(
// One registry entry per supported host; the service only knows the registry.
Layer.provide(PullRequestProviderRegistry.layer),
Layer.provide(SourceControlProviderRegistryLayerLive),
Layer.provide(VcsProcess.layer),
);
export const makeRoutesLayer = Layer.mergeAll(
Layer.mergeAll(
HttpApiBuilder.layer(EnvironmentHttpApi).pipe(
Layer.provide(authHttpApiLayer),
Layer.provide(connectHttpApiLayer),
Layer.provide(orchestrationHttpApiLayer),
Layer.provide(pullRequestHttpApiLayer),
Layer.provide(projectHttpApiLayer),
Layer.provide(serverEnvironmentHttpApiLayer),
Layer.provide(environmentAuthenticatedAuthLayer),
),
otlpTracesProxyRouteLayer,
assetRouteLayer,
staticAndDevRouteLayer,
websocketRpcRouteLayer,
),
// The MCP session registry is provided globally (shared with V2 provider
// sessions) rather than inline here.
McpHttpServer.layer,
).pipe(
// Both transports consume the same service instance, so caches single-flight across clients
// and mutations observed on WebSocket invalidate patches subsequently read over HTTP.
Layer.provide(PullRequestServiceLive),
Layer.provide(PreviewAutomationBroker.layer),
Layer.provide(ServerSelfUpdate.layer),
Layer.provide(commandReadinessLayer),
Layer.provide(browserApiCorsLayer),
Layer.provide(httpCompressionLayer),
);
export const makeServerLayer = Layer.unwrap(
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const activation = yield* Deferred.make<void>();
const awaitActivation = Deferred.await(activation);
const activationLayer = Layer.succeed(ServerActivation, awaitActivation);
const runtimeStateParked = yield* Deferred.make<void>();
const tailscaleParked = yield* Deferred.make<void>();
const cloudLinkParked = yield* Deferred.make<void>();
const routesReady = yield* Deferred.make<void>();
const launcherLayer = ServiceLauncherClient.layer;
yield* fixPath();
const httpListeningLayer = Layer.effectDiscard(
Effect.gen(function* () {
yield* HttpServer.HttpServer;
const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
yield* startup.markHttpListening;
}),
);
const runtimeStateLayer = Layer.effectDiscard(
Effect.acquireRelease(
Effect.gen(function* () {
yield* Deferred.succeed(runtimeStateParked, undefined).pipe(Effect.orDie);
yield* awaitActivation;
const server = yield* HttpServer.HttpServer;
const address = server.address;
if (typeof address === "string" || !("port" in address)) {
return;
}
const state = yield* makePersistedServerRuntimeState({
config,
port: address.port,
});
yield* persistServerRuntimeState({
path: config.serverRuntimeStatePath,
state,
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("Failed to persist server runtime state", { cause }),
),
);
}),
() =>
clearPersistedServerRuntimeState(config.serverRuntimeStatePath).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("Failed to clear server runtime state", { cause }),
),
),
),
);
const tailscaleServeLayer = config.tailscaleServeEnabled
? Layer.effectDiscard(
Effect.acquireRelease(
Effect.gen(function* () {
yield* Deferred.succeed(tailscaleParked, undefined).pipe(Effect.orDie);
yield* awaitActivation;
const server = yield* HttpServer.HttpServer;
const address = server.address;
if (typeof address === "string" || !("port" in address)) {
return null;
}
const localPort = address.port;
return yield* ensureTailscaleServe({
localPort,
servePort: config.tailscaleServePort,
localHost: "127.0.0.1",
}).pipe(
Effect.as({ localPort, servePort: config.tailscaleServePort }),
Effect.tap(() =>
Effect.logInfo("Tailscale Serve configured", {
localPort,
servePort: config.tailscaleServePort,
}),
),
Effect.catch((cause) =>
Effect.logWarning("Failed to configure Tailscale Serve", {
cause,
localPort,
servePort: config.tailscaleServePort,
}).pipe(Effect.as(null)),
),
);
}),
(configured) =>
configured
? disableTailscaleServe({ servePort: configured.servePort }).pipe(
Effect.tap(() =>
Effect.logInfo("Tailscale Serve disabled", {
servePort: configured.servePort,
}),
),
Effect.catch((cause) =>
Effect.logWarning("Failed to disable Tailscale Serve", {
cause,
servePort: configured.servePort,
}),
),
)
: Effect.void,
),
)
: Layer.empty;
const cloudDesiredLinkReconcileLayer = Layer.effectDiscard(
Effect.gen(function* () {
if (!hasCloudPublicConfig) {
yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);
return;
}
const releaseManagedTunnel = releaseManagedTunnelOnShutdown().pipe(
Effect.timeout("10 seconds"),
Effect.tap((released) =>
released ? Effect.logInfo("Released the managed tunnel on shutdown") : Effect.void,
),
Effect.catchCause((cause) =>
Effect.logWarning(
"Failed to release the managed tunnel on shutdown; the next link reuses it",
{ cause },
),
),
Effect.asVoid,
);
// A launcher trial can be stopped before activation. The previous
// server is already gone, so the trial owns cleanup immediately; the
// pending-state check keeps the tunnel for normal commit or rollback,
// while the launcher's explicit-stop marker allows it to be released.
// Other runtimes wait for activation so a failed standby cannot tear
// down the active runtime's tunnel.
const cleanupBeforeActivation = yield* pendingServiceUpdateExists;
if (cleanupBeforeActivation) {
yield* Effect.addFinalizer(() => releaseManagedTunnel);
}
yield* forkParked(
Effect.gen(function* () {
if (!cleanupBeforeActivation) {
yield* Effect.addFinalizer(() => releaseManagedTunnel);
}
if (!(yield* CloudCliState.readCliDesiredCloudLink)) return;
const server = yield* HttpServer.HttpServer;
const address = server.address;
if (typeof address === "string" || !("port" in address)) return;
// No settling delay before the first attempt: routes are already
// serving by the time activation opens this gate (the startup
// sequence awaits routesReady), and the retry schedule below
// covers anything this sleep used to hedge against. Every
// millisecond here is dead time on the path to remote
// reachability after a restart.
yield* reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`).pipe(
Effect.retry({
while: (error) =>
error._tag !== "EnvironmentHttpBadRequestError" &&
error._tag !== "EnvironmentHttpUnauthorizedError" &&
error._tag !== "EnvironmentHttpConflictError",
schedule: Schedule.exponential("1 second").pipe(
Schedule.modifyDelay(({ duration }) =>
Effect.succeed(Duration.min(duration, Duration.seconds(30))),
),
Schedule.upTo({ duration: "10 minutes" }),
),
}),
Effect.tap(() => Effect.logInfo("T3 Connect desired link reconciled on startup")),
Effect.catch((cause) =>
Effect.logWarning("Failed to reconcile T3 Connect desired link on startup", {
cause,
}),
),
);
}),
);
yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);
}),
);
const runtimeServicesLive = ServerRuntimeStartup.layerWithOptions({
activate: Deferred.succeed(activation, undefined).pipe(Effect.asVoid),
abort: (error) => Deferred.die(activation, error).pipe(Effect.asVoid),
awaitAuxiliaryParked: Effect.all(
[
Deferred.await(runtimeStateParked),
Deferred.await(cloudLinkParked),
Deferred.await(routesReady),
...(config.tailscaleServeEnabled ? [Deferred.await(tailscaleParked)] : []),
],
{ concurrency: "unbounded" },
).pipe(Effect.asVoid),
}).pipe(Layer.provideMerge(RuntimeDependenciesLive), Layer.provide(launcherLayer));
const routesLayer = HttpRouter.serve(makeRoutesLayer.pipe(Layer.provide(launcherLayer)), {
disableLogger: !config.logWebSocketEvents,
}).pipe(Layer.tap(() => Deferred.succeed(routesReady, undefined).pipe(Effect.orDie)));
const serverApplicationLayer = Layer.mergeAll(
routesLayer,
httpListeningLayer,
runtimeStateLayer,
tailscaleServeLayer,
cloudDesiredLinkReconcileLayer,
);
return serverApplicationLayer.pipe(
Layer.provideMerge(RuntimeServicesLive),
Layer.provideMerge(McpSessionRegistry.layer.pipe(Layer.provide(ServerEnvironment.layer))),
Layer.provideMerge(serverRelayBrokerTracingLayer),
Layer.provideMerge(HttpServerLive),
Layer.provide(ApplicationObservabilityLive),
Layer.provideMerge(FetchHttpClient.layer),
Layer.provideMerge(VcsProcess.layer),
Layer.provideMerge(PlatformServicesLive),
);
}),
);
// The CLI supplies configuration.
export const runServer = Layer.launch(makeServerLayer);