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

server.ts

785 lines33.9 KB

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