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