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