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

server.ts

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