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