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

server.ts

816 lines34.6 KB

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