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