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

server.ts

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