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

ProviderInstanceRegistryHydration.ts

185 lines7.4 KB

1import {
2 defaultInstanceIdForDriver,
3 ProviderDriverKind,
4 ProviderInstanceId,
5 providerInstanceConfigEnabledFlag,
6 resolveProviderInstanceEnabled,
7 type ProviderInstanceConfig,
8 type ProviderInstanceConfigMap,
9 ServerSettings,
10} from "@t3tools/contracts";
11import * as HostProcess from "@t3tools/shared/HostProcess";
12import type * as Crypto from "effect/Crypto";
13import * as Effect from "effect/Effect";
14import * as FileSystem from "effect/FileSystem";
15import * as Layer from "effect/Layer";
16import * as Path from "effect/Path";
17import * as Stream from "effect/Stream";
18​
19import * as Settings from "../serverSettings.ts";
20import * as SecretResolver from "../secrets/SecretResolver.ts";
21import { BUILT_IN_DRIVERS, type BuiltInDriversEnv } from "./builtInDrivers.ts";
22import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
23import * as ProviderInstanceRegistryMutator from "./ProviderInstanceRegistryMutator.ts";
24import * as ProviderOrchestrationAdapterInfrastructure from "./ProviderOrchestrationAdapterInfrastructure.ts";
25import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRegistrySupport";
26import * as ProviderHostLive from "./ProviderHostLive.ts";
27import type * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
28import type * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
29import * as ServerConfig from "../config.ts";
30import type * as PortScanner from "../preview/PortScanner.ts";
31​
32type ProviderInstanceRegistryHydrationEnv =
33 | Exclude<
34 BuiltInDriversEnv,
35 | ProviderOrchestrationAdapterInfrastructure.ProviderOrchestrationAdapterInfrastructure
36 | AcpRegistrySupport.AcpRegistryCatalog
37 | ProviderHost.ProviderHost
38 >
39 | Settings.ServerSettingsService
40 | BackgroundPolicy.BackgroundPolicy
41 | ServerConfig.ServerConfig
42 | Path.Path
43 | FileSystem.FileSystem
44 // Secret provider reads.
45 | Crypto.Crypto
46 // The Claude runner counts its CLIs as running agents for port discovery.
47 | PortScanner.PortDiscovery;
48​
49export const deriveProviderInstanceConfigMap = (
50 settings: ServerSettings,
51): ProviderInstanceConfigMap => {
52 const merged: Record<string, ProviderInstanceConfig> = { ...settings.providerInstances };
53​
54 for (const driver of BUILT_IN_DRIVERS) {
55 if (driver.metadata.hasDefaultInstance === false) continue;
56 const instanceId = defaultInstanceIdForDriver(driver.driverKind);
57 if (instanceId in merged) continue;
58 merged[instanceId] = { driver: driver.driverKind };
59 }
60​
61 // Probe project-enabled instances even if disabled machine-wide; project threads can still route to them.
62 for (const overrides of Object.values(settings.projectSettingsOverrides)) {
63 for (const [rawInstanceId, projectOverride] of Object.entries(
64 overrides?.providerInstances ?? {},
65 )) {
66 if (projectOverride.enabled !== true) continue;
67 const instanceId = rawInstanceId as ProviderInstanceId;
68 const existing = merged[instanceId];
69 if (existing === undefined || resolveProviderInstanceEnabled(existing)) continue;
70 merged[instanceId] = {
71 ...existing,
72 enabled: true,
73 ...(providerInstanceConfigEnabledFlag(existing.config) === false
74 ? { config: { ...(existing.config as Record<string, unknown>), enabled: true } }
75 : {}),
76 };
77 }
78 }
79​
80 return merged as ProviderInstanceConfigMap;
81};
82​
83export const DEV_REPLAY_INSTANCE_ID = ProviderInstanceId.make("devReplay");
84​
85/**
86 * Dev servers run from source keep a free ACP agent that replays recorded turns, so UI checks
87 * need no paid model. Bundled servers, such as desktop dev, have no agent script and skip it.
88 */
89export const seedDevReplayInstance = Effect.fn(
90 "ProviderInstanceRegistryHydration.seedDevReplayInstance",
91)(function* () {
92 const config = yield* ServerConfig.ServerConfig;
93 if (config.devUrl === undefined) return;
94 const path = yield* Path.Path;
95 const agentPath = yield* path.fromFileUrl(
96 new URL("../../scripts/dev-replay-agent.ts", import.meta.url),
97 );
98 if (!(yield* (yield* FileSystem.FileSystem).exists(agentPath))) return;
99 const commandPath = yield* HostProcess.ExecutablePath;
100 const serverSettings = yield* Settings.ServerSettingsService;
101 const existing = (yield* serverSettings.getSettings).providerInstances[DEV_REPLAY_INSTANCE_ID];
102 const existingConfig = existing?.config as Record<string, unknown> | undefined;
103 // Rewritten only when stale: the node and checkout paths can move.
104 if (
105 existingConfig?.commandPath === commandPath &&
106 (existingConfig.commandArgs as ReadonlyArray<unknown> | undefined)?.[0] === agentPath
107 ) {
108 return;
109 }
110 // Keeps user edits, such as turning the provider off.
111 const instance: ProviderInstanceConfig = {
112 displayName: "Replay (dev)",
113 ...existing,
114 driver: ProviderDriverKind.make("acpRegistry"),
115 config: { ...existingConfig, source: "local", commandPath, commandArgs: [agentPath] },
116 };
117 yield* serverSettings.updateProviderInstance({
118 operation: "upsert",
119 instanceId: DEV_REPLAY_INSTANCE_ID,
120 instance,
121 });
122});
123​
124const layerSettingsWatcher = (settingsChanges: Stream.Stream<ServerSettings>) =>
125 Layer.effectDiscard(
126 Effect.gen(function* () {
127 const mutator = yield* ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator;
128 const serverSettings = yield* Settings.ServerSettingsService;
129 yield* settingsChanges.pipe(
130 Stream.runForEach(() =>
131 // The subscription predates the seed read, so a queued change can be
132 // older than the seed. A failed current read must leave the registry intact.
133 serverSettings.getSettings.pipe(
134 Effect.flatMap((current) =>
135 mutator.reconcile(deriveProviderInstanceConfigMap(current)),
136 ),
137 Effect.catchCause((cause) =>
138 Effect.logError("ProviderInstanceRegistry reconcile failed", cause),
139 ),
140 ),
141 ),
142 Effect.forkScoped,
143 );
144 }),
145 );
146​
147export const layer: Layer.Layer<
148 | ProviderInstanceRegistry.ProviderInstanceRegistry
149 | ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator,
150 never,
151 ProviderInstanceRegistryHydrationEnv
152> = Layer.unwrap(
153 Effect.gen(function* () {
154 const serverSettings = yield* Settings.ServerSettingsService;
155 yield* seedDevReplayInstance().pipe(
156 Effect.catchCause((cause) => Effect.logWarning("Dev replay agent unavailable", cause)),
157 );
158 // Subscribe before the seed read so saves during registry construction are queued.
159 const settingsChanges = yield* serverSettings.subscribeChanges;
160 const initialSettings: ServerSettings | undefined = yield* serverSettings.getSettings.pipe(
161 Effect.orElseSucceed(() => undefined),
162 );
163 const initialConfigMap =
164 initialSettings === undefined
165 ? ({} as ProviderInstanceConfigMap)
166 : deriveProviderInstanceConfigMap(initialSettings);
167​
168 const layerMutable = ProviderInstanceRegistry.layer({
169 drivers: BUILT_IN_DRIVERS,
170 configMap: initialConfigMap,
171 }).pipe(
172 Layer.provide(ProviderOrchestrationAdapterInfrastructure.layer),
173 Layer.provide(AcpRegistrySupport.layerFromHost),
174 Layer.provide(ProviderHostLive.layer),
175 Layer.provide(SecretResolver.layer),
176 );
177​
178 return layerSettingsWatcher(settingsChanges).pipe(Layer.provideMerge(layerMutable));
179 }),
180) as Layer.Layer<
181 | ProviderInstanceRegistry.ProviderInstanceRegistry
182 | ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator,
183 never,
184 ProviderInstanceRegistryHydrationEnv
185>;