Open History to see the last commit
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 NodeUtil from "node:util";
12
13import * as HostProcess from "@t3tools/shared/HostProcess";
14import type * as SecureRandom from "effect/crypto/SecureRandom";
15import * as Effect from "effect/Effect";
16import * as FileSystem from "effect/FileSystem";
17import * as Layer from "effect/Layer";
18import * as Path from "effect/Path";
19import * as Stream from "effect/Stream";
20
21import * as ManagedProviders from "../policy/managedProviders.ts";
22import * as Settings from "../serverSettings.ts";
23import * as SecretResolver from "../secrets/SecretResolver.ts";
24import { BUILT_IN_DRIVERS, type BuiltInDriversEnv } from "./builtInDrivers.ts";
25import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
26import * as ProviderInstanceRegistryMutator from "./ProviderInstanceRegistryMutator.ts";
27import * as ProviderOrchestrationAdapterInfrastructure from "./ProviderOrchestrationAdapterInfrastructure.ts";
28import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRegistrySupport";
29import * as ProviderHostLive from "./ProviderHostLive.ts";
30import type * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
31import type * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
32import * as ServerConfig from "../config.ts";
33import type * as PortScanner from "../preview/PortScanner.ts";
34
35type ProviderInstanceRegistryHydrationEnv =
36 | Exclude<
37 BuiltInDriversEnv,
38 | ProviderOrchestrationAdapterInfrastructure.ProviderOrchestrationAdapterInfrastructure
39 | AcpRegistrySupport.AcpRegistryCatalog
40 | ProviderHost.ProviderHost
41 >
42 | Settings.ServerSettingsService
43 | BackgroundPolicy.BackgroundPolicy
44 | ServerConfig.ServerConfig
45 | Path.Path
46 | FileSystem.FileSystem
47 // Secret provider reads.
48 | SecureRandom.SecureRandom
49 // The Claude runner counts its CLIs as running agents for port discovery.
50 | PortScanner.PortDiscovery;
51
52export const deriveProviderInstanceConfigMap = (
53 settings: ServerSettings,
54): ProviderInstanceConfigMap => {
55 const merged: Record<string, ProviderInstanceConfig> = { ...settings.providerInstances };
56
57 for (const driver of BUILT_IN_DRIVERS) {
58 if (driver.metadata.hasDefaultInstance === false) continue;
59 const instanceId = defaultInstanceIdForDriver(driver.driverKind);
60 if (instanceId in merged) continue;
61 merged[instanceId] = { driver: driver.driverKind };
62 }
63
64 // Probe project-enabled instances even if disabled machine-wide; project threads can still route to them.
65 for (const overrides of Object.values(settings.projectSettingsOverrides)) {
66 for (const [rawInstanceId, projectOverride] of Object.entries(
67 overrides?.providerInstances ?? {},
68 )) {
69 if (projectOverride.enabled !== true) continue;
70 const instanceId = rawInstanceId as ProviderInstanceId;
71 const existing = merged[instanceId];
72 if (existing === undefined || resolveProviderInstanceEnabled(existing)) continue;
73 merged[instanceId] = {
74 ...existing,
75 enabled: true,
76 ...(providerInstanceConfigEnabledFlag(existing.config) === false
77 ? { config: { ...(existing.config as Record<string, unknown>), enabled: true } }
78 : {}),
79 };
80 }
81 }
82
83 return merged as ProviderInstanceConfigMap;
84};
85
86export const DEV_REPLAY_INSTANCE_ID = ProviderInstanceId.make("devReplay");
87
88/**
89 * Dev servers run from source keep a free ACP agent that replays recorded turns, so UI checks
90 * need no paid model. Bundled servers, such as desktop dev, have no agent script and skip it.
91 */
92export const seedDevReplayInstance = Effect.fn(
93 "ProviderInstanceRegistryHydration.seedDevReplayInstance",
94)(function* () {
95 const config = yield* ServerConfig.ServerConfig;
96 if (config.devUrl === undefined) return;
97 const path = yield* Path.Path;
98 const agentPath = yield* path.fromFileUrl(
99 new URL("../../scripts/dev-replay-agent.ts", import.meta.url),
100 );
101 if (!(yield* (yield* FileSystem.FileSystem).exists(agentPath))) return;
102 const commandPath = yield* HostProcess.ExecutablePath;
103 const serverSettings = yield* Settings.ServerSettingsService;
104 const existing = (yield* serverSettings.getSettings).providerInstances[DEV_REPLAY_INSTANCE_ID];
105 const existingConfig = existing?.config as Record<string, unknown> | undefined;
106 // Rewritten only when stale: the node and checkout paths can move.
107 if (
108 existingConfig?.commandPath === commandPath &&
109 (existingConfig.commandArgs as ReadonlyArray<unknown> | undefined)?.[0] === agentPath
110 ) {
111 return;
112 }
113 // Keeps user edits, such as turning the provider off.
114 const instance: ProviderInstanceConfig = {
115 displayName: "Replay (dev)",
116 ...existing,
117 driver: ProviderDriverKind.make("acpRegistry"),
118 config: { ...existingConfig, source: "local", commandPath, commandArgs: [agentPath] },
119 };
120 yield* serverSettings.updateProviderInstance({
121 operation: "upsert",
122 instanceId: DEV_REPLAY_INSTANCE_ID,
123 instance,
124 });
125});
126
127// A label is display-only, so only kind and config can change what a vault returns.
128const vaultConfigs = (settings: ServerSettings) =>
129 Object.entries(settings.secretProviders).map(([id, { kind, config }]) => [id, kind, config]);
130
131export const layerSettingsWatcher = (
132 settingsChanges: Stream.Stream<ServerSettings>,
133 // The settings the registry was built from: a change queued during startup differs from these.
134 initialSettings: ServerSettings | undefined,
135) =>
136 Layer.effectDiscard(
137 Effect.gen(function* () {
138 const mutator = yield* ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator;
139 const serverSettings = yield* Settings.ServerSettingsService;
140 let secretProviders = initialSettings && vaultConfigs(initialSettings);
141 yield* settingsChanges.pipe(
142 Stream.runForEach(() =>
143 // The subscription predates the seed read, so a queued change can be
144 // older than the seed. A failed current read must leave the registry intact.
145 serverSettings.getSettings.pipe(
146 Effect.flatMap((current) =>
147 Effect.gen(function* () {
148 yield* mutator.reconcile(deriveProviderInstanceConfigMap(current));
149 // Reconcile leaves instances parked on an unreadable secret alone,
150 // and a corrected secret provider is what can make them readable.
151 const next = vaultConfigs(current);
152 if (!NodeUtil.isDeepStrictEqual(secretProviders, next)) {
153 secretProviders = next;
154 yield* mutator.reloadSecrets();
155 }
156 }),
157 ),
158 Effect.catchCause((cause) =>
159 Effect.logError("ProviderInstanceRegistry reconcile failed", cause),
160 ),
161 ),
162 ),
163 Effect.forkScoped,
164 );
165 }),
166 );
167
168export const layer: Layer.Layer<
169 | ProviderInstanceRegistry.ProviderInstanceRegistry
170 | ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator,
171 never,
172 ProviderInstanceRegistryHydrationEnv
173> = Layer.unwrap(
174 Effect.gen(function* () {
175 const serverSettings = yield* Settings.ServerSettingsService;
176 yield* seedDevReplayInstance().pipe(
177 Effect.catchCause((cause) => Effect.logWarning("Dev replay agent unavailable", cause)),
178 );
179 // Subscribe before the seed read so saves during registry construction are queued.
180 const settingsChanges = yield* serverSettings.subscribeChanges;
181 const initialSettings: ServerSettings | undefined = yield* serverSettings.getSettings.pipe(
182 Effect.orElseSucceed(() => undefined),
183 );
184 const initialConfigMap =
185 initialSettings === undefined
186 ? ({} as ProviderInstanceConfigMap)
187 : deriveProviderInstanceConfigMap(initialSettings);
188
189 // Drivers launch from the host environment, minus launch overrides a policy ignores.
190 const hostEnvironment = ManagedProviders.providerHostEnvironment(
191 serverSettings.managedPolicy,
192 yield* HostProcess.Environment,
193 );
194 // Instances of drivers the policy leaves out stay listed, as unavailable, so their threads
195 // explain why instead of losing their provider.
196 const layerMutable = ProviderInstanceRegistry.layer({
197 drivers: BUILT_IN_DRIVERS,
198 configMap: initialConfigMap,
199 blockedReason: (driver) =>
200 ManagedProviders.disallowedDriverReason(serverSettings.managedPolicy, driver),
201 }).pipe(
202 Layer.provide(ProviderOrchestrationAdapterInfrastructure.layer),
203 Layer.provide(AcpRegistrySupport.layerFromHost),
204 Layer.provide(ProviderHostLive.layer),
205 Layer.provide(Layer.succeed(HostProcess.Environment, hostEnvironment)),
206 Layer.provide(SecretResolver.layer),
207 );
208
209 return layerSettingsWatcher(settingsChanges, initialSettings).pipe(
210 Layer.provideMerge(layerMutable),
211 );
212 }),
213) as Layer.Layer<
214 | ProviderInstanceRegistry.ProviderInstanceRegistry
215 | ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator,
216 never,
217 ProviderInstanceRegistryHydrationEnv
218>;