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

server.ts

781 lines33.7 KB

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