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

server.ts

848 lines36.5 KB

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