Open History to see the last commit
1import {
2 ProviderOptionDescriptor,
3 type ProviderInstanceId,
4 type ServerProvider,
5 type ServerProviderModel,
6 type ServerSettings,
7} from "@t3tools/contracts";
8import { createModelCapabilities } from "@t3tools/shared/model";
9import * as Digest from "effect/crypto/Digest";
10import * as Effect from "effect/Effect";
11import * as Hex from "effect/encoding/Hex";
12import * as Equal from "effect/Equal";
13import * as FileSystem from "effect/FileSystem";
14import * as Path from "effect/Path";
15import * as Ref from "effect/Ref";
16import * as Schema from "effect/Schema";
17import * as Semaphore from "effect/Semaphore";
18
19import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
20import type { AcpRegistrySettings } from "../settings.ts";
21import type { AcpRegistryLiveConfiguration } from "./probe.ts";
22
23/** The options an ACP agent reports for one model only (thought_level, model_config), by model. */
24export type AcpRegistryLearnedModelOptions = ReadonlyMap<
25 string,
26 ReadonlyArray<ProviderOptionDescriptor>
27>;
28
29const decodeStored = Schema.decodeUnknownEffect(
30 Schema.fromJsonString(
31 Schema.Struct({
32 binding: Schema.String,
33 version: Schema.NullOr(Schema.String),
34 models: Schema.Record(Schema.String, Schema.Array(ProviderOptionDescriptor)),
35 }),
36 ),
37);
38const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
39const hash = Effect.fn("AcpRegistryLearnedModelOptions.hash")(function* (value: unknown) {
40 const crypto = yield* Digest.Digest;
41 const json = yield* encodeJson(value).pipe(Effect.orDie);
42 const digest = yield* crypto
43 .digest(Digest.sha256, new TextEncoder().encode(json))
44 .pipe(Effect.orDie);
45 return Hex.encode(digest);
46});
47
48interface LearnedState {
49 readonly version: string | null;
50 readonly models: AcpRegistryLearnedModelOptions;
51 readonly saved:
52 | { readonly version: string | null; readonly models: AcpRegistryLearnedModelOptions }
53 | undefined;
54}
55
56/**
57 * Per-model options kept on disk, trusted only for the agent version they were read from.
58 * Live sessions replace an entry; discovery only fills models nothing has reported yet.
59 */
60export const makeAcpRegistryLearnedModelOptionsStore = Effect.fn(
61 "makeAcpRegistryLearnedModelOptionsStore",
62)(function* (input: {
63 readonly cacheDir: string;
64 readonly instanceId: ProviderInstanceId;
65 readonly settings: AcpRegistrySettings;
66}) {
67 const fs = yield* FileSystem.FileSystem;
68 const path = yield* Path.Path;
69 const filePath = path.join(
70 input.cacheDir,
71 `acp-model-options-${yield* hash(input.instanceId)}.json`,
72 );
73 const binding = yield* hash({
74 source: input.settings.source,
75 agentId: input.settings.agentId,
76 commandPath: input.settings.commandPath,
77 commandArgs: input.settings.commandArgs,
78 distribution: input.settings.distribution,
79 });
80 const saved = yield* fs.readFileString(filePath).pipe(
81 Effect.flatMap(decodeStored),
82 Effect.orElseSucceed(() => undefined),
83 );
84 const state = yield* Ref.make<LearnedState>({
85 version: null,
86 models: new Map(),
87 saved:
88 saved?.binding === binding
89 ? { version: saved.version, models: new Map(Object.entries(saved.models)) }
90 : undefined,
91 });
92 const lock = yield* Semaphore.make(1);
93 const persist = (current: LearnedState) =>
94 writeFileStringAtomically({
95 filePath,
96 contents: JSON.stringify({
97 binding,
98 version: current.version,
99 models: Object.fromEntries(current.models),
100 }),
101 }).pipe(
102 Effect.provideService(FileSystem.FileSystem, fs),
103 Effect.provideService(Path.Path, path),
104 Effect.tapError(() => Effect.logWarning("Could not save ACP model options.")),
105 Effect.ignore,
106 );
107 const update = (next: (current: LearnedState) => LearnedState) =>
108 lock.withPermit(
109 Ref.modify(state, (current) => {
110 const updated = next(current);
111 return [updated === current ? undefined : updated, updated] as const;
112 }).pipe(
113 Effect.flatMap((updated) => (updated === undefined ? Effect.void : persist(updated))),
114 ),
115 );
116
117 return {
118 get: Ref.get(state).pipe(Effect.map((current) => current.models)),
119 setVersion: (version: string | null) =>
120 update((current) => {
121 if (version === null || version === current.version) return current;
122 // Options learned before the version was known came from this same binary.
123 const learnedThisRun = current.version === null ? current.models : new Map();
124 const stored =
125 current.saved?.version === version ? current.saved.models : new Map<string, never>();
126 return { version, models: new Map([...stored, ...learnedThisRun]), saved: undefined };
127 }),
128 learn: (
129 modelId: string,
130 options: ReadonlyArray<ProviderOptionDescriptor>,
131 source: "live" | "discovered",
132 ) =>
133 update((current) => {
134 const existing = current.models.get(modelId);
135 if (
136 existing !== undefined &&
137 (source === "discovered" || Equal.equals(existing, options))
138 ) {
139 return current;
140 }
141 return { ...current, models: new Map(current.models).set(modelId, options) };
142 }),
143 clear: update((current) => ({ ...current, models: new Map(), saved: undefined })),
144 };
145});
146
147/** The model-specific options a session reported for its current model. */
148export function acpRegistryCurrentModelOptions(
149 configuration: AcpRegistryLiveConfiguration,
150):
151 | { readonly modelId: string; readonly options: ReadonlyArray<ProviderOptionDescriptor> }
152 | undefined {
153 // An empty report without a model select is a placeholder, not a statement about the model.
154 if (
155 configuration.currentModelId === null ||
156 (configuration.configOptions.length === 0 && configuration.modelsFromModelSelect !== true)
157 ) {
158 return undefined;
159 }
160 const modelOptionIds = new Set(configuration.modelOptionIds ?? []);
161 return {
162 modelId: configuration.currentModelId,
163 options: configuration.configOptions.filter((option) => modelOptionIds.has(option.id)),
164 };
165}
166
167/** Adds learned options to models that are not the session's own and lack them. */
168export function withAcpRegistryLearnedModelOptions(
169 provider: ServerProvider,
170 learned: AcpRegistryLearnedModelOptions,
171): ServerProvider {
172 if (learned.size === 0) return provider;
173 let changed = false;
174 const models = provider.models.map((model): ServerProviderModel => {
175 const options = learned.get(model.slug);
176 if (model.isCustom || model.isDefault === true || options === undefined) return model;
177 const current = model.capabilities?.optionDescriptors ?? [];
178 // Levels the model advertises itself (`_meta`) keep their place.
179 const missing = options.filter((option) => !current.some(({ id }) => id === option.id));
180 if (missing.length === 0) return model;
181 changed = true;
182 return {
183 ...model,
184 capabilities: createModelCapabilities({ optionDescriptors: [...current, ...missing] }),
185 };
186 });
187 return changed ? { ...provider, models } : provider;
188}
189
190/**
191 * Visible models whose options no session has reported yet: favorites first, then the
192 * user's model order, then the agent's. Models that advertise their levels are skipped.
193 */
194export function acpRegistryModelsToDiscover(input: {
195 readonly provider: Pick<ServerProvider, "instanceId" | "models">;
196 readonly settings: Pick<ServerSettings, "favorites" | "providerModelPreferences">;
197 readonly learned: AcpRegistryLearnedModelOptions;
198}): ReadonlyArray<string> {
199 const { provider, settings, learned } = input;
200 const preferences = settings.providerModelPreferences?.[provider.instanceId];
201 const hidden = new Set(preferences?.hiddenModels ?? []);
202 const rank = (slugs: ReadonlyArray<string>) =>
203 new Map(slugs.map((slug, index) => [slug, index] as const));
204 const favoriteRank = rank(
205 (settings.favorites ?? [])
206 .filter((favorite) => favorite.provider === provider.instanceId)
207 .map((favorite) => favorite.model),
208 );
209 const orderRank = rank(preferences?.modelOrder ?? []);
210 const catalogRank = rank(provider.models.map((model) => model.slug));
211 const ranked = (ranks: ReadonlyMap<string, number>, slug: string) =>
212 ranks.get(slug) ?? Number.POSITIVE_INFINITY;
213 return provider.models
214 .filter(
215 (model) =>
216 !model.isCustom &&
217 model.isDefault !== true &&
218 !hidden.has(model.slug) &&
219 !learned.has(model.slug) &&
220 !(model.capabilities?.optionDescriptors ?? []).some(
221 (option) => option.type === "select" && option.role === "reasoning",
222 ),
223 )
224 .map((model) => model.slug)
225 .toSorted(
226 (a, b) =>
227 ranked(favoriteRank, a) - ranked(favoriteRank, b) ||
228 ranked(orderRank, a) - ranked(orderRank, b) ||
229 ranked(catalogRank, a) - ranked(catalogRank, b),
230 );
231}