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

server.ts

810 lines34.9 KB

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 Layer.provideMerge(
489 Layer.mergeAll(SourceControlProviderRegistryLayerLive, PullRequestServiceLive),
490 ),
491 Layer.provideMerge(GitLayerLive),
492 Layer.provideMerge(VcsLayerLive),
493 Layer.provideMerge(ProviderRuntimeLayerLive),
494 Layer.provideMerge(Layer.mergeAll(TerminalLayerLive, PreviewLayerLive, DeviceLayerLive)),
495 Layer.provideMerge(PersistenceLayerLive),
496 // Both read a user-owned file out of the state directory and stream changes
497 // to clients; neither depends on the other.
498 Layer.provideMerge(
499 Layer.mergeAll(Keybindings.layer, EnvironmentTheme.layer, UsageLimitSources.layer),
500 ),
501 Layer.provideMerge(ProviderRegistryLive),
502 // The instance registry is the new routing keystone — text generation,
503 // adapter lookup, and runtime ingestion all resolve `ProviderInstanceId`
504 // through this layer. Built-in drivers come from `BUILT_IN_DRIVERS`;
505 // `providerInstances` hydration merges `settings.providers.<kind>`
506 // with explicit `providerInstances` entries on boot.
507 Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
508).pipe(
509 Layer.provideMerge(AntigravityInstallation.layer),
510 // Shared native/canonical NDJSON writers used by both the per-instance
511 // drivers (native stream, written from inside each `<X>Adapter`) and
512 // `ProviderService` (canonical stream, written after event normalization).
513 // Provided once at the runtime level so every consumer sees the same
514 // logger instances.
515 // `ModelManifest.layer` is the legacy-model classification data, refreshed
516 // from the repo's `model-manifest.json` on `main` and applied by the
517 // Codex/Claude drivers.
518 Layer.provideMerge(
519 Layer.mergeAll(ProviderEventLoggers.layer, ModelManifest.layer, CodexResetCredit.layer),
520 ),
521 // `OpenCodeDriver.create()` yields `OpenCodeRuntime`; previously the old
522 // `ProviderRegistryLive` pulled `OpenCodeRuntimeLive` in for itself, but
523 // the rewritten registry reads snapshots off the instance registry and
524 // no longer transitively provides it. Exposing it at the runtime level
525 // keeps a single Live for all opencode consumers.
526 Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
527 Layer.provideMerge(WorkspaceLayerLive),
528 Layer.provideMerge(Layer.mergeAll(NativeAppIconResolver.layer, ProjectFaviconResolverLayerLive)),
529 Layer.provideMerge(RepositoryIdentityResolverLayerLive),
530 Layer.provideMerge(ServerEnvironmentLayerLive),
531 Layer.provideMerge(AuthLayerLive),
532 Layer.provideMerge(ServerSecretStore.layer),
533 Layer.provideMerge(
534 Layer.mergeAll(
535 CloudCliTokenManager.layer.pipe(
536 Layer.provide(ServerSecretStore.layer),
537 Layer.provide(ExternalLauncher.layer),
538 ),
539 CloudManagedEndpointRuntimeLive,
540 ),
541 ),
542);
543​
544const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
545 // Misc.
546 Layer.provideMerge(BackgroundLayerLive),
547 Layer.provideMerge(ResourceDiagnosticsLayerLive),
548 Layer.provideMerge(UsageLayerLive),
549 Layer.provideMerge(TraceDiagnostics.layer),
550 Layer.provideMerge(AnalyticsService.layer),
551 Layer.provideMerge(ExternalLauncher.layer),
552 Layer.provideMerge(RemoteOpenTargets.layer),
553 Layer.provideMerge(ServerLifecycleEvents.layer),
554 Layer.provide(NetService.layer),
555);
556​
557const commandReadinessLayer = HttpRouter.middleware(
558 (httpEffect) =>
559 Effect.flatMap(ServerRuntimeStartup.ServerRuntimeStartup, (startup) =>
560 startup.awaitCommandReady.pipe(Effect.orDie, Effect.andThen(httpEffect)),
561 ),
562 { global: true },
563);
564​
565export const makeRoutesLayer = Layer.mergeAll(
566 Layer.mergeAll(
567 HttpApiBuilder.layer(EnvironmentHttpApi).pipe(
568 Layer.provide(authHttpApiLayer),
569 Layer.provide(connectHttpApiLayer),
570 Layer.provide(orchestrationHttpApiLayer),
571 Layer.provide(pullRequestHttpApiLayer),
572 Layer.provide(serverEnvironmentHttpApiLayer),
573 Layer.provide(environmentAuthenticatedAuthLayer),
574 ),
575 otlpTracesProxyRouteLayer,
576 assetRouteLayer,
577 attachmentUploadRouteLayer,
578 deviceHubProxyRouteLayer,
579 staticAndDevRouteLayer,
580 websocketRpcRouteLayer,
581 ),
582 McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer)),
583).pipe(
584 // Both transports consume the same service instance, so caches single-flight across clients
585 // and mutations observed on WebSocket invalidate patches subsequently read over HTTP.
586 Layer.provide(PullRequestServiceLive),
587 Layer.provide(PreviewAutomationBroker.layer),
588 Layer.provide(ServerSelfUpdate.layer.pipe(Layer.provide(DesktopAppUpdateLayerLive))),
589 Layer.provide(commandReadinessLayer),
590 Layer.provide(browserApiCorsLayer),
591 Layer.provide(httpCompressionLayer),
592);
593​
594const makeServerLayer = Layer.unwrap(
595 Effect.gen(function* () {
596 const config = yield* ServerConfig.ServerConfig;
597 const activation = yield* Deferred.make<void>();
598 const awaitActivation = Deferred.await(activation);
599 const activationLayer = Layer.succeed(ServerActivation, awaitActivation);
600 const runtimeStateParked = yield* Deferred.make<void>();
601 const tailscaleParked = yield* Deferred.make<void>();
602 const cloudLinkParked = yield* Deferred.make<void>();
603 const routesReady = yield* Deferred.make<void>();
604 const launcherLayer = ServiceLauncherClient.layer;
605​
606 yield* fixPath();
607​
608 const httpListeningLayer = Layer.effectDiscard(
609 Effect.gen(function* () {
610 yield* HttpServer.HttpServer;
611 const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
612 yield* startup.markHttpListening;
613 }),
614 );
615 const runtimeStateLayer = Layer.effectDiscard(
616 Effect.acquireRelease(
617 Effect.gen(function* () {
618 yield* Deferred.succeed(runtimeStateParked, undefined).pipe(Effect.orDie);
619 yield* awaitActivation;
620 const server = yield* HttpServer.HttpServer;
621 const address = server.address;
622 if (typeof address === "string" || !("port" in address)) {
623 return;
624 }
625​
626 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
627 const state = yield* makePersistedServerRuntimeState({
628 config,
629 port: address.port,
630 serviceManaged: launcher.managed,
631 });
632 yield* persistServerRuntimeState({
633 path: config.serverRuntimeStatePath,
634 state,
635 }).pipe(
636 Effect.catchCause((cause) =>
637 Effect.logWarning("Failed to persist server runtime state", { cause }),
638 ),
639 );
640 }),
641 () =>
642 clearPersistedServerRuntimeState(config.serverRuntimeStatePath).pipe(
643 Effect.catchCause((cause) =>
644 Effect.logWarning("Failed to clear server runtime state", { cause }),
645 ),
646 ),
647 ),
648 );
649 const tailscaleServeLayer = config.tailscaleServeEnabled
650 ? Layer.effectDiscard(
651 Effect.acquireRelease(
652 Effect.gen(function* () {
653 yield* Deferred.succeed(tailscaleParked, undefined).pipe(Effect.orDie);
654 yield* awaitActivation;
655 const server = yield* HttpServer.HttpServer;
656 const address = server.address;
657 if (typeof address === "string" || !("port" in address)) {
658 return null;
659 }
660​
661 const localPort = address.port;
662 return yield* ensureTailscaleServe({
663 localPort,
664 servePort: config.tailscaleServePort,
665 localHost: "127.0.0.1",
666 }).pipe(
667 Effect.as({ localPort, servePort: config.tailscaleServePort }),
668 Effect.tap(() =>
669 Effect.logInfo("Tailscale Serve configured", {
670 localPort,
671 servePort: config.tailscaleServePort,
672 }),
673 ),
674 Effect.catch((cause) =>
675 Effect.logWarning("Failed to configure Tailscale Serve", {
676 cause,
677 localPort,
678 servePort: config.tailscaleServePort,
679 }).pipe(Effect.as(null)),
680 ),
681 );
682 }),
683 (configured) =>
684 configured
685 ? disableTailscaleServe({ servePort: configured.servePort }).pipe(
686 Effect.tap(() =>
687 Effect.logInfo("Tailscale Serve disabled", {
688 servePort: configured.servePort,
689 }),
690 ),
691 Effect.catch((cause) =>
692 Effect.logWarning("Failed to disable Tailscale Serve", {
693 cause,
694 servePort: configured.servePort,
695 }),
696 ),
697 )
698 : Effect.void,
699 ),
700 )
701 : Layer.empty;
702 const cloudDesiredLinkReconcileLayer = Layer.effectDiscard(
703 Effect.gen(function* () {
704 if (!hasCloudPublicConfig) {
705 yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);
706 return;
707 }
708 const releaseManagedTunnel = releaseManagedTunnelOnShutdown().pipe(
709 Effect.timeout("10 seconds"),
710 Effect.tap((released) =>
711 released ? Effect.logInfo("Released the managed tunnel on shutdown") : Effect.void,
712 ),
713 Effect.catchCause((cause) =>
714 Effect.logWarning(
715 "Failed to release the managed tunnel on shutdown; the next link reuses it",
716 { errors: Cause.prettyErrors(cause).map((error) => error.message) },
717 ),
718 ),
719 Effect.asVoid,
720 );
721 // A launcher trial can be stopped before activation. The previous
722 // server is already gone, so the trial owns cleanup immediately; the
723 // pending-state check keeps the tunnel for normal commit or rollback,
724 // while the launcher's explicit-stop marker allows it to be released.
725 // Other runtimes wait for activation so a failed standby cannot tear
726 // down the active runtime's tunnel.
727 const cleanupBeforeActivation = yield* pendingServiceUpdateExists;
728 if (cleanupBeforeActivation) {
729 yield* Effect.addFinalizer(() => releaseManagedTunnel);
730 }
731 yield* forkParked(
732 Effect.gen(function* () {
733 if (!cleanupBeforeActivation) {
734 yield* Effect.addFinalizer(() => releaseManagedTunnel);
735 }
736 if (!(yield* CloudCliState.readCliDesiredCloudLink)) return;
737 const server = yield* HttpServer.HttpServer;
738 const address = server.address;
739 if (typeof address === "string" || !("port" in address)) return;
740 // No settling delay before the first attempt: routes are already
741 // serving by the time activation opens this gate (the startup
742 // sequence awaits routesReady), and the retry schedule below
743 // covers anything this sleep used to hedge against. Every
744 // millisecond here is dead time on the path to remote
745 // reachability after a restart.
746 yield* reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`).pipe(
747 Effect.retry({
748 while: shouldRetryCloudLink,
749 schedule: Schedule.exponential("1 second").pipe(
750 Schedule.modifyDelay(({ duration }) =>
751 Effect.succeed(Duration.min(duration, Duration.seconds(30))),
752 ),
753 Schedule.upTo({ duration: "10 minutes" }),
754 ),
755 }),
756 Effect.tap(() => Effect.logInfo("T3 Connect desired link reconciled on startup")),
757 Effect.catch((cause) =>
758 Effect.logWarning("Failed to reconcile T3 Connect desired link on startup", {
759 message: cause.message,
760 }),
761 ),
762 );
763 }),
764 );
765 yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);
766 }),
767 );
768​
769 const runtimeServicesLive = ServerRuntimeStartup.layerWithOptions({
770 activate: Deferred.succeed(activation, undefined).pipe(Effect.asVoid),
771 abort: (error) => Deferred.die(activation, error).pipe(Effect.asVoid),
772 awaitAuxiliaryParked: Effect.all(
773 [
774 Deferred.await(runtimeStateParked),
775 Deferred.await(cloudLinkParked),
776 Deferred.await(routesReady),
777 ...(config.tailscaleServeEnabled ? [Deferred.await(tailscaleParked)] : []),
778 ],
779 { concurrency: "unbounded" },
780 ).pipe(Effect.asVoid),
781 }).pipe(Layer.provideMerge(RuntimeDependenciesLive), Layer.provide(launcherLayer));
782​
783 const routesLayer = HttpRouter.serve(makeRoutesLayer.pipe(Layer.provide(launcherLayer)), {
784 disableLogger: !config.logWebSocketEvents,
785 routerConfig: HTTP_ROUTER_CONFIG,
786 }).pipe(Layer.tap(() => Deferred.succeed(routesReady, undefined).pipe(Effect.orDie)));
787 const serverApplicationLayer = Layer.mergeAll(
788 routesLayer,
789 httpListeningLayer,
790 runtimeStateLayer.pipe(Layer.provide(launcherLayer)),
791 tailscaleServeLayer,
792 cloudDesiredLinkReconcileLayer,
793 );
794​
795 return serverApplicationLayer.pipe(
796 Layer.provideMerge(runtimeServicesLive),
797 Layer.provide(activationLayer),
798 Layer.provideMerge(serverRelayBrokerTracingLayer),
799 Layer.provideMerge(HttpServerLive),
800 Layer.provide(ApplicationObservabilityLive),
801 Layer.provideMerge(FetchHttpClient.layer),
802 // PR reads, Git operations, and WebSocket discovery share one process limiter.
803 Layer.provide(VcsProcess.layer),
804 Layer.provideMerge(PlatformServicesLive),
805 );
806 }),
807);
808​
809// The CLI supplies configuration.
810export const runServer = Layer.launch(makeServerLayer);