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

server.ts

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