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

server.ts

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