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

server.ts

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