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

server.ts

841 lines36.1 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 { 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 // The asset route uses the registry's GitHub credential for private PR media.
505 Layer.provideMerge(Layer.mergeAll(SourceControlProviderRegistryLayerLive, GitHubCli.layer)),
506 Layer.provideMerge(GitLayerLive),
507 Layer.provideMerge(VcsLayerLive),
508 Layer.provideMerge(Layer.mergeAll(TerminalLayerLive, PreviewLayerLive, DeviceLayerLive)),
509 Layer.provideMerge(PersistenceLayerLive),
510 // Both read a user-owned file out of the state directory and stream changes
511 // to clients; neither depends on the other.
512 Layer.provideMerge(
513 Layer.mergeAll(Keybindings.layer, EnvironmentTheme.layer, UsageLimitSources.layer),
514 ),
515 Layer.provideMerge(ProviderRegistryLive),
516 // The instance registry is the new routing keystone — text generation,
517 // adapter lookup, and runtime ingestion all resolve `ProviderInstanceId`
518 // through this layer. Built-in drivers come from `BUILT_IN_DRIVERS`;
519 // `providerInstances` hydration merges `settings.providers.<kind>`
520 // with explicit `providerInstances` entries on boot.
521 Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
522 Layer.provideMerge(AntigravityInstallation.layer),
523);
524​
525const RuntimeCoreDependenciesLive = RuntimeCoreDependenciesBaseLive.pipe(
526 // Search, prepare, status inspection, and turn launch share one registry
527 // cache so every client and provider instance sees the same prepared agents.
528 Layer.provideMerge(AcpRegistryCatalogLive),
529 // Shared native/canonical NDJSON writers used by both the per-instance
530 // V2 drivers and the orchestration runtime. Provide resource attribution so
531 // the rewritten telemetry pipeline can account for logical NDJSON writes.
532 // Provided once at the runtime level so every consumer sees the same
533 // logger instances.
534 // `ModelManifest.layer` is the legacy-model classification data, refreshed
535 // from the repo's `model-manifest.json` on `main` and applied by the
536 // Codex/Claude drivers.
537 Layer.provideMerge(
538 Layer.mergeAll(ProviderEventLoggers.layer, ModelManifest.layer, CodexResetCredit.layer),
539 ),
540 // `OpenCodeDriver.create()` yields `OpenCodeRuntime`; previously the old
541 // `ProviderRegistryLive` pulled `OpenCodeRuntimeLive` in for itself, but
542 // the rewritten registry reads snapshots off the instance registry and
543 // no longer transitively provides it. Exposing it at the runtime level
544 // keeps a single Live for all opencode consumers.
545 Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
546 Layer.provideMerge(WorkspaceLayerLive),
547 Layer.provideMerge(ProjectEnrichmentService.layer),
548 Layer.provideMerge(Layer.mergeAll(NativeAppIconResolver.layer, ProjectFaviconResolverLayerLive)),
549 Layer.provideMerge(RepositoryIdentityResolverLayerLive),
550 Layer.provideMerge(ServerEnvironmentLayerLive),
551 Layer.provideMerge(AuthLayerLive),
552 Layer.provideMerge(ServerSecretStore.layer),
553 Layer.provideMerge(
554 Layer.mergeAll(
555 CloudCliTokenManager.layer.pipe(
556 Layer.provide(ServerSecretStore.layer),
557 Layer.provide(ExternalLauncher.layer),
558 ),
559 CloudManagedEndpointRuntimeLive,
560 ),
561 ),
562);
563​
564const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
565 // Misc.
566 Layer.provideMerge(BackgroundLayerLive),
567 Layer.provideMerge(ResourceDiagnosticsLayerLive),
568 Layer.provideMerge(UsageLayerLive),
569 Layer.provideMerge(TraceDiagnostics.layer),
570 Layer.provideMerge(AnalyticsService.layer),
571 Layer.provideMerge(ExternalLauncher.layer),
572 Layer.provideMerge(RemoteOpenTargets.layer),
573 Layer.provideMerge(ServerLifecycleEvents.layer),
574 Layer.provide(NetService.layer),
575);
576​
577const commandReadinessLayer = HttpRouter.middleware(
578 (httpEffect) =>
579 Effect.flatMap(ServerRuntimeStartup.ServerRuntimeStartup, (startup) =>
580 startup.awaitCommandReady.pipe(Effect.orDie, Effect.andThen(httpEffect)),
581 ),
582 { global: true },
583);
584​
585const makeRoutesLayer = Layer.mergeAll(
586 Layer.mergeAll(
587 HttpApiBuilder.layer(EnvironmentHttpApi).pipe(
588 Layer.provide(authHttpApiLayer),
589 Layer.provide(connectHttpApiLayer),
590 Layer.provide(orchestrationHttpApiLayer),
591 Layer.provide(pullRequestHttpApiLayer),
592 Layer.provide(projectHttpApiLayer),
593 Layer.provide(serverEnvironmentHttpApiLayer),
594 Layer.provide(environmentAuthenticatedAuthLayer),
595 ),
596 otlpTracesProxyRouteLayer,
597 assetRouteLayer,
598 attachmentUploadRouteLayer,
599 deviceHubProxyRouteLayer,
600 staticAndDevRouteLayer,
601 websocketRpcRouteLayer,
602 ),
603 // The MCP session registry is provided globally (shared with V2 provider
604 // sessions) rather than inline here. The orchestrator toolkit resolves
605 // delegation targets through the same live adapter facade the V2
606 // orchestrator uses, so MCP capability reporting can never drift from
607 // what dispatch can actually serve.
608 McpHttpServer.layer.pipe(Layer.provide(providerAdapterRegistryLayerFromProviderInstances)),
609).pipe(
610 // Both transports consume the same service instance, so caches single-flight across clients
611 // and mutations observed on WebSocket invalidate patches subsequently read over HTTP.
612 Layer.provide(PullRequestServiceLive),
613 Layer.provide(PreviewAutomationBroker.layer),
614 Layer.provide(ServerSelfUpdate.layer.pipe(Layer.provide(DesktopAppUpdateLayerLive))),
615 Layer.provide(commandReadinessLayer),
616 Layer.provide(browserApiCorsLayer),
617 Layer.provide(httpCompressionLayer),
618);
619​
620const makeServerLayer = Layer.unwrap(
621 Effect.gen(function* () {
622 const config = yield* ServerConfig.ServerConfig;
623 const activation = yield* Deferred.make<void>();
624 const awaitActivation = Deferred.await(activation);
625 const activationLayer = Layer.succeed(ServerActivation, awaitActivation);
626 const runtimeStateParked = yield* Deferred.make<void>();
627 const tailscaleParked = yield* Deferred.make<void>();
628 const cloudLinkParked = yield* Deferred.make<void>();
629 const routesReady = yield* Deferred.make<void>();
630 const launcherLayer = ServiceLauncherClient.layer;
631​
632 yield* fixPath();
633​
634 const httpListeningLayer = Layer.effectDiscard(
635 Effect.gen(function* () {
636 yield* HttpServer.HttpServer;
637 const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
638 yield* startup.markHttpListening;
639 }),
640 );
641 const runtimeStateLayer = Layer.effectDiscard(
642 Effect.acquireRelease(
643 Effect.gen(function* () {
644 yield* Deferred.succeed(runtimeStateParked, undefined).pipe(Effect.orDie);
645 yield* awaitActivation;
646 const server = yield* HttpServer.HttpServer;
647 const address = server.address;
648 if (typeof address === "string" || !("port" in address)) {
649 return;
650 }
651​
652 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
653 const state = yield* makePersistedServerRuntimeState({
654 config,
655 port: address.port,
656 serviceManaged: launcher.managed,
657 });
658 yield* persistServerRuntimeState({
659 path: config.serverRuntimeStatePath,
660 state,
661 }).pipe(
662 Effect.catchCause((cause) =>
663 Effect.logWarning("Failed to persist server runtime state", { cause }),
664 ),
665 );
666 }),
667 () =>
668 clearPersistedServerRuntimeState(config.serverRuntimeStatePath).pipe(
669 Effect.catchCause((cause) =>
670 Effect.logWarning("Failed to clear server runtime state", { cause }),
671 ),
672 ),
673 ),
674 );
675 const tailscaleServeLayer = config.tailscaleServeEnabled
676 ? Layer.effectDiscard(
677 Effect.acquireRelease(
678 Effect.gen(function* () {
679 yield* Deferred.succeed(tailscaleParked, undefined).pipe(Effect.orDie);
680 yield* awaitActivation;
681 const server = yield* HttpServer.HttpServer;
682 const address = server.address;
683 if (typeof address === "string" || !("port" in address)) {
684 return null;
685 }
686​
687 const localPort = address.port;
688 return yield* ensureTailscaleServe({
689 localPort,
690 servePort: config.tailscaleServePort,
691 localHost: "127.0.0.1",
692 }).pipe(
693 Effect.as({ localPort, servePort: config.tailscaleServePort }),
694 Effect.tap(() =>
695 Effect.logInfo("Tailscale Serve configured", {
696 localPort,
697 servePort: config.tailscaleServePort,
698 }),
699 ),
700 Effect.catch((cause) =>
701 Effect.logWarning("Failed to configure Tailscale Serve", {
702 cause,
703 localPort,
704 servePort: config.tailscaleServePort,
705 }).pipe(Effect.as(null)),
706 ),
707 );
708 }),
709 (configured) =>
710 configured
711 ? disableTailscaleServe({ servePort: configured.servePort }).pipe(
712 Effect.tap(() =>
713 Effect.logInfo("Tailscale Serve disabled", {
714 servePort: configured.servePort,
715 }),
716 ),
717 Effect.catch((cause) =>
718 Effect.logWarning("Failed to disable Tailscale Serve", {
719 cause,
720 servePort: configured.servePort,
721 }),
722 ),
723 )
724 : Effect.void,
725 ),
726 )
727 : Layer.empty;
728 const cloudDesiredLinkReconcileLayer = Layer.effectDiscard(
729 Effect.gen(function* () {
730 if (!hasCloudPublicConfig) {
731 yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);
732 return;
733 }
734 const releaseManagedTunnel = releaseManagedTunnelOnShutdown().pipe(
735 Effect.timeout("10 seconds"),
736 Effect.tap((released) =>
737 released ? Effect.logInfo("Released the managed tunnel on shutdown") : Effect.void,
738 ),
739 Effect.catchCause((cause) =>
740 Effect.logWarning(
741 "Failed to release the managed tunnel on shutdown; the next link reuses it",
742 { errors: Cause.prettyErrors(cause).map((error) => error.message) },
743 ),
744 ),
745 Effect.asVoid,
746 );
747 // A launcher trial can be stopped before activation. The previous
748 // server is already gone, so the trial owns cleanup immediately; the
749 // pending-state check keeps the tunnel for normal commit or rollback,
750 // while the launcher's explicit-stop marker allows it to be released.
751 // Other runtimes wait for activation so a failed standby cannot tear
752 // down the active runtime's tunnel.
753 const cleanupBeforeActivation = yield* pendingServiceUpdateExists;
754 if (cleanupBeforeActivation) {
755 yield* Effect.addFinalizer(() => releaseManagedTunnel);
756 }
757 yield* forkParked(
758 Effect.gen(function* () {
759 if (!cleanupBeforeActivation) {
760 yield* Effect.addFinalizer(() => releaseManagedTunnel);
761 }
762 if (!(yield* CloudCliState.readCliDesiredCloudLink)) return;
763 const server = yield* HttpServer.HttpServer;
764 const address = server.address;
765 if (typeof address === "string" || !("port" in address)) return;
766 // No settling delay before the first attempt: routes are already
767 // serving by the time activation opens this gate (the startup
768 // sequence awaits routesReady), and the retry schedule below
769 // covers anything this sleep used to hedge against. Every
770 // millisecond here is dead time on the path to remote
771 // reachability after a restart.
772 yield* reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`).pipe(
773 Effect.retry({
774 while: shouldRetryCloudLink,
775 schedule: Schedule.exponential("1 second").pipe(
776 Schedule.modifyDelay(({ duration }) =>
777 Effect.succeed(Duration.min(duration, Duration.seconds(30))),
778 ),
779 Schedule.upTo({ duration: "10 minutes" }),
780 ),
781 }),
782 Effect.tap(() => Effect.logInfo("T3 Connect desired link reconciled on startup")),
783 Effect.catch((cause) =>
784 Effect.logWarning("Failed to reconcile T3 Connect desired link on startup", {
785 message: cause.message,
786 }),
787 ),
788 );
789 }),
790 );
791 yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);
792 }),
793 );
794​
795 const runtimeServicesLive = ServerRuntimeStartup.layerWithOptions({
796 activate: Deferred.succeed(activation, undefined).pipe(Effect.asVoid),
797 abort: (error) => Deferred.die(activation, error).pipe(Effect.asVoid),
798 awaitAuxiliaryParked: Effect.all(
799 [
800 Deferred.await(runtimeStateParked),
801 Deferred.await(cloudLinkParked),
802 Deferred.await(routesReady),
803 ...(config.tailscaleServeEnabled ? [Deferred.await(tailscaleParked)] : []),
804 ],
805 { concurrency: "unbounded" },
806 ).pipe(Effect.asVoid),
807 }).pipe(Layer.provideMerge(RuntimeDependenciesLive), Layer.provide(launcherLayer));
808​
809 const routesLayer = HttpRouter.serve(makeRoutesLayer.pipe(Layer.provide(launcherLayer)), {
810 disableLogger: !config.logWebSocketEvents,
811 routerConfig: HTTP_ROUTER_CONFIG,
812 }).pipe(Layer.tap(() => Deferred.succeed(routesReady, undefined).pipe(Effect.orDie)));
813 const serverApplicationLayer = Layer.mergeAll(
814 routesLayer,
815 httpListeningLayer,
816 runtimeStateLayer.pipe(Layer.provide(launcherLayer)),
817 tailscaleServeLayer,
818 cloudDesiredLinkReconcileLayer,
819 );
820​
821 return serverApplicationLayer.pipe(
822 Layer.provideMerge(runtimeServicesLive),
823 Layer.provideMerge(
824 McpSessionRegistry.layer.pipe(
825 Layer.provide(ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer))),
826 ),
827 ),
828 Layer.provide(activationLayer),
829 Layer.provideMerge(serverRelayBrokerTracingLayer),
830 Layer.provideMerge(HttpServerLive),
831 Layer.provide(ApplicationObservabilityLive),
832 Layer.provideMerge(FetchHttpClient.layer),
833 // PR reads, Git operations, and WebSocket discovery share one process limiter.
834 Layer.provide(VcsProcess.layer),
835 Layer.provideMerge(PlatformServicesLive),
836 );
837 }),
838);
839​
840// The CLI supplies configuration.
841export const runServer = Layer.launch(makeServerLayer);