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

server.ts

772 lines33.2 KB

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