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

server.ts

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