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

ProviderInstanceRegistryHydration.ts

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