The best way to control Claude Code, Codex and more from any computer or phone

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