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

server.ts

836 lines35.5 KB

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