@vessel-agent/model-registry 0.0.0-stage → 2.3.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,453 @@
1
+ /**
2
+ * @vessel-agent/model-registry — 官方 in-process 模型管理插件(两面重构 §8)。
3
+ *
4
+ * 契约:docs/dev/design/model-registry-two-face-design.md §3/§4/§8(取代上位契约 §3)。
5
+ * 管理 API(models 块读改写)+ 加密凭证库 + 连通性测试。机制在 harness:装配层经
6
+ * registerInProcessPlugin 把本插件的 `rpc` 注册进同一个 PluginRpcRegistry
7
+ * (canonical `plugin.model-registry.<name>`,同一 DTO 校验);这里只实现 handler 语义,
8
+ * 不自造注册路径。
9
+ *
10
+ * RPC 8 方法:list / model_set / model_remove / default_set / credential_set /
11
+ * credential_remove / credentials_list / test(vendor_set/remove、alias_set/remove 已删;
12
+ * 别称随 model_set 写入)。
13
+ *
14
+ * 生效语义:写路径只落盘(config.yaml models 块 / credentials.json),热应用由
15
+ * config-watch + applier 完成——「已保存,下一具 body/run 生效」。
16
+ * 明文纪律:credential value 只在 credential_set 写入瞬间存在;RPC 结果永不回显。
17
+ */
18
+
19
+ import type { ModelEntry, ModelRegistrySnapshot } from '@vessel-agent/config';
20
+ import {
21
+ CREDENTIAL_ID_RE,
22
+ readMigrationReport,
23
+ resolveEffectiveApiKey,
24
+ resolveModelRef,
25
+ } from '@vessel-agent/config';
26
+ import type { Plugin } from '@vessel-agent/core';
27
+ import { defaultBaseUrlFor, testConnectivity } from './connectivity';
28
+ import { CredentialStore, resolveDataDir } from './credential-store';
29
+ import {
30
+ credentialReferences,
31
+ credentialRemoveMeta,
32
+ credentialSetMeta,
33
+ defaultSet,
34
+ entryReferences,
35
+ modelRemove,
36
+ modelSet,
37
+ modelsToCamel,
38
+ readRegistry,
39
+ } from './registry-store';
40
+
41
+ function isRecord(value: unknown): value is Record<string, unknown> {
42
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
43
+ }
44
+
45
+ function invalidParams(message: string): Error {
46
+ return new Error(`invalid_params: ${message}`);
47
+ }
48
+
49
+ function requireString(params: Record<string, unknown>, key: string): string {
50
+ const value = params[key];
51
+ if (typeof value !== 'string' || value.trim() === '') {
52
+ throw invalidParams(`${key} must be a non-empty string`);
53
+ }
54
+ return value;
55
+ }
56
+
57
+ function optionalString(params: Record<string, unknown>, key: string): string | undefined {
58
+ const value = params[key];
59
+ if (value === undefined) return undefined;
60
+ if (typeof value !== 'string' || value.trim() === '') {
61
+ throw invalidParams(`${key} must be a non-empty string when set`);
62
+ }
63
+ return value;
64
+ }
65
+
66
+ /**
67
+ * model DTO 形状收敛(未知键拒绝,对齐 KNOWN_BLOCK_KEYS['models.entries']);
68
+ * 语义校验(credential 命中 / alias 唯一 / mode 相容 / pricing / param / info)= validateModels。
69
+ */
70
+ function parseModelEntry(raw: unknown): ModelEntry {
71
+ if (!isRecord(raw)) throw invalidParams('entry must be an object');
72
+ const knownKeys = new Set([
73
+ 'name',
74
+ 'alias',
75
+ 'provider',
76
+ 'mode',
77
+ 'credential',
78
+ 'pricing',
79
+ 'param',
80
+ 'info',
81
+ ]);
82
+ for (const key of Object.keys(raw)) {
83
+ if (!knownKeys.has(key)) throw invalidParams(`entry.${key} is not a known model field`);
84
+ }
85
+ const credential = raw.credential;
86
+ if (typeof credential !== 'string' || credential.trim() === '') {
87
+ throw invalidParams('entry.credential is required (a models.credentials.<id> reference)');
88
+ }
89
+ const entry: ModelEntry = { credential };
90
+ for (const field of ['name', 'alias', 'provider'] as const) {
91
+ const value = raw[field];
92
+ if (value === undefined) continue;
93
+ if (typeof value !== 'string' || value.trim() === '') {
94
+ throw invalidParams(`entry.${field} must be a non-empty string when set`);
95
+ }
96
+ entry[field] = value;
97
+ }
98
+ if (raw.mode !== undefined) {
99
+ if (typeof raw.mode !== 'string' || raw.mode.trim() === '') {
100
+ throw invalidParams('entry.mode must be a non-empty string when set');
101
+ }
102
+ // 枚举相容性(chat/responses/messages × provider)在 validateModels 语义校验。
103
+ entry.mode = raw.mode as ModelEntry['mode'];
104
+ }
105
+ if (raw.pricing !== undefined) {
106
+ if (!isRecord(raw.pricing)) throw invalidParams('entry.pricing must be an object');
107
+ const pricing: Record<string, unknown> = {};
108
+ for (const key of [
109
+ 'inputPerMillion',
110
+ 'outputPerMillion',
111
+ 'cacheReadPerMillion',
112
+ 'cacheWritePerMillion',
113
+ ]) {
114
+ const value = raw.pricing[key];
115
+ if (value === undefined) continue;
116
+ if (typeof value !== 'number') {
117
+ throw invalidParams(`entry.pricing.${key} must be a number when set`);
118
+ }
119
+ pricing[key] = value;
120
+ }
121
+ for (const key of Object.keys(raw.pricing)) {
122
+ if (!(key in pricing)) throw invalidParams(`entry.pricing.${key} is not a known price field`);
123
+ }
124
+ entry.pricing = pricing as unknown as ModelEntry['pricing'];
125
+ }
126
+ if (raw.param !== undefined) {
127
+ if (!isRecord(raw.param)) throw invalidParams('entry.param must be an object');
128
+ const param: Record<string, unknown> = {};
129
+ for (const key of ['temperature', 'maxTokens', 'topP']) {
130
+ const value = raw.param[key];
131
+ if (value === undefined) continue;
132
+ if (typeof value !== 'number') throw invalidParams(`entry.param.${key} must be a number`);
133
+ param[key] = value;
134
+ }
135
+ if (raw.param.promptCache !== undefined) {
136
+ if (typeof raw.param.promptCache !== 'boolean') {
137
+ throw invalidParams('entry.param.promptCache must be a boolean');
138
+ }
139
+ param.promptCache = raw.param.promptCache;
140
+ }
141
+ if (raw.param.extra !== undefined) {
142
+ if (!isRecord(raw.param.extra)) throw invalidParams('entry.param.extra must be an object');
143
+ param.extra = raw.param.extra;
144
+ }
145
+ for (const key of Object.keys(raw.param)) {
146
+ if (!(key in param)) throw invalidParams(`entry.param.${key} is not a known param field`);
147
+ }
148
+ entry.param = param as ModelEntry['param'];
149
+ }
150
+ if (raw.info !== undefined) {
151
+ if (!isRecord(raw.info)) throw invalidParams('entry.info must be an object');
152
+ entry.info = raw.info as ModelEntry['info'];
153
+ }
154
+ return entry;
155
+ }
156
+
157
+ /**
158
+ * 有效默认(与装配 resolveModel 同口径,§2.6 冻结):VESSEL_MODEL 非空则以其为 ref
159
+ * (env 赢 models.default),否则走默认链。无效配置(default/别称未命中)时返回
160
+ * undefined——list 仍回 registry 本身供 UI 修复,不整体报错。
161
+ */
162
+ function effectiveOf(
163
+ snapshot: ModelRegistrySnapshot,
164
+ ): { entryId: string; wireModel: string } | undefined {
165
+ const envModel = process.env.VESSEL_MODEL;
166
+ const ref = envModel !== undefined && envModel.trim() !== '' ? envModel : undefined;
167
+ try {
168
+ const resolved = resolveModelRef(snapshot, ref);
169
+ if (resolved === undefined) return undefined;
170
+ return { entryId: resolved.entryId, wireModel: resolved.wireModel };
171
+ } catch {
172
+ return undefined;
173
+ }
174
+ }
175
+
176
+ /** 凭证 DTO(§3.3):yaml 元数据 ∪ 加密库元数据;值永不回显。 */
177
+ async function credentialDtos(
178
+ config: Parameters<typeof resolveDataDir>[0],
179
+ snapshot: ModelRegistrySnapshot,
180
+ ): Promise<Record<string, unknown>[]> {
181
+ const store = new CredentialStore(resolveDataDir(config));
182
+ const metas = await store.list();
183
+ const metaById = new Map(metas.map((meta) => [meta.id, meta]));
184
+ const ids = new Set<string>([
185
+ ...Object.values(snapshot.credentials)
186
+ .filter((cred) => !cred.legacy)
187
+ .map((cred) => cred.id),
188
+ ...metas.map((meta) => meta.id),
189
+ ]);
190
+ return [...ids].sort().map((id) => {
191
+ const cred = snapshot.credentials[id];
192
+ const meta = metaById.get(id);
193
+ return {
194
+ id,
195
+ ...(cred?.baseUrl !== undefined ? { baseUrl: cred.baseUrl } : {}),
196
+ ...(cred?.apiKeyEnv !== undefined ? { apiKeyEnv: cred.apiKeyEnv } : {}),
197
+ hasValue: meta !== undefined,
198
+ ...(meta !== undefined ? { createdAt: meta.createdAt, updatedAt: meta.updatedAt } : {}),
199
+ usedBy: credentialReferences(snapshot, id),
200
+ };
201
+ });
202
+ }
203
+
204
+ async function handleList(): Promise<Record<string, unknown>> {
205
+ const { config, snapshot, legacyPresent } = await readRegistry();
206
+ const entries = Object.values(snapshot.entries).map((entry) => ({
207
+ id: entry.id,
208
+ name: entry.wireModel,
209
+ ...(entry.alias !== undefined ? { alias: entry.alias } : {}),
210
+ provider: entry.provider,
211
+ mode: entry.mode,
212
+ ...(entry.credentialRef !== undefined ? { credential: entry.credentialRef } : {}),
213
+ ...(entry.baseUrl !== undefined ? { baseUrl: entry.baseUrl } : {}),
214
+ ...(entry.pricing !== undefined ? { pricing: entry.pricing } : {}),
215
+ ...(entry.param !== undefined ? { param: entry.param } : {}),
216
+ ...(entry.info !== undefined ? { info: entry.info } : {}),
217
+ inUse: entryReferences(snapshot, entry.id).length > 0,
218
+ legacy: entry.legacy,
219
+ }));
220
+ const effective = effectiveOf(snapshot);
221
+ // §7.5:一次性迁移报告(迁移完成后为空 = 无报告文件)。
222
+ const migration = await readMigrationReport(resolveDataDir(config));
223
+ return {
224
+ credentials: await credentialDtos(config, snapshot),
225
+ entries,
226
+ ...(snapshot.defaultRef !== undefined ? { default: snapshot.defaultRef } : {}),
227
+ ...(effective !== undefined ? { effective } : {}),
228
+ legacyPresent,
229
+ ...(migration !== undefined ? { migration } : {}),
230
+ };
231
+ }
232
+
233
+ async function handleModelSet(params: Record<string, unknown>): Promise<Record<string, unknown>> {
234
+ const id = requireString(params, 'id');
235
+ const entry = parseModelEntry(params.entry);
236
+ const { models: readBack, warnings } = await modelSet(id, entry);
237
+ const written = modelsToCamel(readBack).entries?.[id];
238
+ if (written === undefined) {
239
+ throw new Error(`model_set_readback_missing: "${id}" not found after write`);
240
+ }
241
+ return { ok: true, entry: written, ...(warnings.length > 0 ? { warnings } : {}) };
242
+ }
243
+
244
+ async function handleDefaultSet(params: Record<string, unknown>): Promise<Record<string, unknown>> {
245
+ const ref = requireString(params, 'ref');
246
+ await defaultSet(ref);
247
+ // 写后读回:重新合并(user/project/env)再解析 effective。
248
+ const { snapshot } = await readRegistry();
249
+ const effective = effectiveOf(snapshot);
250
+ return { ok: true, ...(effective !== undefined ? { effective } : {}) };
251
+ }
252
+
253
+ /**
254
+ * credential_set:一次写两处(§3.3)——先加密库值、后 yaml 元数据(withConfigLock 内)。
255
+ * id 形状在写值前 fail-fast 校验(无效 id 不再产生孤儿值);值失败不写 yaml;
256
+ * yaml 失败仍可能留孤儿值(credentials_list 可见未引用条目,可经 credential_remove 清除)。
257
+ * apiKey 缺省 = 不改值(编辑态);baseUrl 必填。明文纪律:值永不回显。
258
+ */
259
+ async function handleCredentialSet(
260
+ params: Record<string, unknown>,
261
+ ): Promise<Record<string, unknown>> {
262
+ const id = requireString(params, 'id');
263
+ // fail-fast:id 形状与 validateCredentialsBlock 同口径,先于 store.set——
264
+ // 否则加密库值已落盘而 yaml 校验拒绝,留下 credential_remove 曾删不掉的孤儿。
265
+ if (id.startsWith('legacy:')) {
266
+ throw invalidParams(`id "${id}" uses the reserved "legacy:" prefix`);
267
+ }
268
+ if (!CREDENTIAL_ID_RE.test(id)) {
269
+ throw invalidParams(
270
+ 'id must match ^[a-zA-Z0-9][a-zA-Z0-9-]{0,63}$ (letters, digits, hyphens; up to 64 chars)',
271
+ );
272
+ }
273
+ const baseUrl = requireString(params, 'baseUrl');
274
+ const apiKeyEnv = optionalString(params, 'apiKeyEnv');
275
+ // 迁移期兼容:旧 UI/CLI 的 value 参数 = apiKey(C6 UI 收敛后删除)。
276
+ const apiKey = optionalString(params, 'apiKey') ?? optionalString(params, 'value');
277
+ const { config } = await readRegistry();
278
+ let updatedAt: string | undefined;
279
+ if (apiKey !== undefined) {
280
+ const store = new CredentialStore(resolveDataDir(config));
281
+ updatedAt = (await store.set(id, apiKey)).updatedAt;
282
+ }
283
+ await credentialSetMeta(id, { baseUrl, ...(apiKeyEnv !== undefined ? { apiKeyEnv } : {}) });
284
+ return { ok: true, ...(updatedAt !== undefined ? { updatedAt } : {}) };
285
+ }
286
+
287
+ async function handleCredentialRemove(
288
+ params: Record<string, unknown>,
289
+ ): Promise<Record<string, unknown>> {
290
+ const id = requireString(params, 'id');
291
+ const { config, snapshot } = await readRegistry();
292
+ const refs = credentialReferences(snapshot, id);
293
+ if (refs.length > 0) {
294
+ throw new Error(
295
+ `credential_in_use: "${id}" is referenced by entries: ${refs.join(', ')}; ` +
296
+ 'remove those references first',
297
+ );
298
+ }
299
+ // 先删 yaml 元数据,再删库值。两侧缺失各自容忍:yaml 无 = store-only 孤儿
300
+ // (credential_set 先值后 yaml 的失败窗口遗留),库值无 = env-only 凭证;
301
+ // 两处皆无才报 unknown_credential。
302
+ let metaAbsent = false;
303
+ try {
304
+ await credentialRemoveMeta(id);
305
+ } catch (error) {
306
+ if (!(error instanceof Error && error.message.startsWith('unknown_credential'))) throw error;
307
+ metaAbsent = true;
308
+ }
309
+ const store = new CredentialStore(resolveDataDir(config));
310
+ try {
311
+ await store.remove(id);
312
+ } catch (error) {
313
+ if (!(error instanceof Error && error.message.startsWith('unknown_credential'))) throw error;
314
+ if (metaAbsent) {
315
+ throw new Error(
316
+ `unknown_credential: "${id}" is in neither the yaml models.credentials block nor the credential store`,
317
+ );
318
+ }
319
+ }
320
+ return { ok: true };
321
+ }
322
+
323
+ async function handleCredentialsList(): Promise<Record<string, unknown>[]> {
324
+ const { config, snapshot } = await readRegistry();
325
+ return credentialDtos(config, snapshot);
326
+ }
327
+
328
+ /** 凭证值解析:库值优先(D10 解密失败 fail-loud);缺值回落 env 间接;legacy 走 provider.*。 */
329
+ async function apiKeyForCredential(
330
+ config: Parameters<typeof resolveDataDir>[0],
331
+ credentialId: string,
332
+ apiKeyEnv: string | undefined,
333
+ legacy: boolean,
334
+ ): Promise<string> {
335
+ if (legacy) return resolveEffectiveApiKey(config) ?? '';
336
+ const store = new CredentialStore(resolveDataDir(config));
337
+ try {
338
+ return await store.reveal(credentialId);
339
+ } catch (error) {
340
+ if (error instanceof Error && error.message.startsWith('unknown_credential')) {
341
+ if (apiKeyEnv !== undefined) {
342
+ const value = process.env[apiKeyEnv];
343
+ if (typeof value === 'string' && value.trim() !== '') return value;
344
+ }
345
+ return '';
346
+ }
347
+ throw error;
348
+ }
349
+ }
350
+
351
+ /**
352
+ * test(§8.1 换形):{ entry }(注册模型:provider+凭证+name 齐备)或
353
+ * { credential, provider?, model? }(凭证级 ping;无 model → GET /models 探测)。
354
+ * 端点恒取凭证 baseUrl(defaultBaseUrlFor 仅 test 兜底);明文 key 不出现在 test 参数。
355
+ */
356
+ async function handleTest(params: Record<string, unknown>): Promise<Record<string, unknown>> {
357
+ const entryId = optionalString(params, 'entry');
358
+ const credentialId = optionalString(params, 'credential');
359
+ const { config, snapshot } = await readRegistry();
360
+
361
+ let protocol: string;
362
+ let baseUrl: string | undefined;
363
+ let model: string | undefined;
364
+ let apiKey: string;
365
+
366
+ if (entryId !== undefined) {
367
+ const entry = Object.hasOwn(snapshot.entries, entryId) ? snapshot.entries[entryId] : undefined;
368
+ if (entry === undefined) {
369
+ throw new Error(`unknown_entry: "${entryId}" is not registered; save the model first`);
370
+ }
371
+ protocol = entry.provider;
372
+ baseUrl = entry.baseUrl ?? defaultBaseUrlFor(protocol);
373
+ model = entry.legacy ? (optionalString(params, 'model') ?? entry.wireModel) : entry.wireModel;
374
+ const cred =
375
+ entry.credentialRef !== undefined ? snapshot.credentials[entry.credentialRef] : undefined;
376
+ apiKey = await apiKeyForCredential(
377
+ config,
378
+ entry.credentialRef ?? '',
379
+ entry.apiKeyEnv ?? cred?.apiKeyEnv,
380
+ entry.legacy || (entry.credentialRef?.startsWith('legacy:') ?? false),
381
+ );
382
+ } else if (credentialId !== undefined) {
383
+ const cred = Object.hasOwn(snapshot.credentials, credentialId)
384
+ ? snapshot.credentials[credentialId]
385
+ : undefined;
386
+ if (cred === undefined) {
387
+ throw new Error(`unknown_credential: "${credentialId}" is not registered; save it first`);
388
+ }
389
+ protocol = optionalString(params, 'provider') ?? 'openai';
390
+ baseUrl = cred.baseUrl ?? defaultBaseUrlFor(protocol);
391
+ model = optionalString(params, 'model');
392
+ apiKey = await apiKeyForCredential(config, credentialId, cred.apiKeyEnv, cred.legacy);
393
+ } else {
394
+ throw invalidParams('test requires { entry } or { credential, provider?, model? }');
395
+ }
396
+
397
+ if (baseUrl === undefined) {
398
+ throw new Error(
399
+ `unsupported_protocol: connectivity test supports openai-compatible ` +
400
+ `(openai/openai-compatible/gemini/google/mistral/ollama/cohere) and anthropic protocols; ` +
401
+ `"${protocol}" is a custom provider plugin protocol`,
402
+ );
403
+ }
404
+ if (apiKey.trim() === '') {
405
+ throw new Error(
406
+ `no_credential: "${entryId ?? credentialId}" has no usable credential value; ` +
407
+ 'record it via credential_set or set an api_key_env first',
408
+ );
409
+ }
410
+ if (protocol === 'anthropic' && (model === undefined || model === '')) {
411
+ throw new Error('no_model: anthropic connectivity test requires a model (no /models endpoint)');
412
+ }
413
+
414
+ const result = await testConnectivity({
415
+ protocol,
416
+ baseUrl,
417
+ apiKey,
418
+ ...(model !== undefined && model !== '' ? { model } : {}),
419
+ });
420
+ return { ...result };
421
+ }
422
+
423
+ const plugin: Plugin = {
424
+ name: 'model-registry',
425
+ // RPC-only 能力插件:无 tool/provider 注册;rpc handler 由装配层 registerInProcessPlugin
426
+ // 接进宿主 PluginRpcRegistry(install 之后),这里无需消费 host。
427
+ install() {},
428
+ async rpc(name: string, params: Record<string, unknown>): Promise<unknown> {
429
+ switch (name) {
430
+ case 'list':
431
+ return handleList();
432
+ case 'model_set':
433
+ return handleModelSet(params);
434
+ case 'model_remove':
435
+ await modelRemove(requireString(params, 'id'));
436
+ return { ok: true };
437
+ case 'default_set':
438
+ return handleDefaultSet(params);
439
+ case 'credential_set':
440
+ return handleCredentialSet(params);
441
+ case 'credential_remove':
442
+ return handleCredentialRemove(params);
443
+ case 'credentials_list':
444
+ return handleCredentialsList();
445
+ case 'test':
446
+ return handleTest(params);
447
+ default:
448
+ throw new Error(`unknown_method: ${name}`);
449
+ }
450
+ },
451
+ };
452
+
453
+ export default plugin;
@@ -0,0 +1,223 @@
1
+ /**
2
+ * model-registry 插件:`~/.vessel/config.yaml` models 块读改写(两面重构 §3.3 / §8)。
3
+ *
4
+ * 契约:docs/dev/design/model-registry-two-face-design.md §3/§4/§8(取代上位契约 §3.3)。
5
+ * - 写经 withConfigLock(跨进程锁,与 config.set / TUI 写路径共用),lock 内 read-modify-write;
6
+ * **写前 validateModels 预校验**(fail-fast RPC 错误,不落无效配置);RPC 返回 = 写后读回。
7
+ * - 磁盘形状 = snake_case(loader 的 snakeToCamel + preserveConfigMapKeys 是唯一映射口径,
8
+ * 凭证 id / 条目键 / wire model id 是 map 键,原样保留);RPC DTO = camelCase。
9
+ * - 引用检查 = registry 内部引用(models.default / entry.credential),不读 agent store
10
+ * (dangling pin 由 doctor 只读交叉检查)。
11
+ * - 只改 models 块;根对象与其它块原样保留。生效异步(config-watch),这里不做热应用。
12
+ * - 凭证值不在本模块:credential_set 的加密库值写入在 index.ts(先值后元数据,§3.3);
13
+ * yaml 半失败可能留 store-only 孤儿值,credential_remove 容忍 yaml 缺失并清掉库值。
14
+ */
15
+
16
+ import {
17
+ type ConfigValidationError,
18
+ type ConfigValidationWarning,
19
+ credentialToYaml,
20
+ entryToYaml,
21
+ getUserConfigPath,
22
+ loadConfig,
23
+ type ModelEntry,
24
+ type ModelRegistrySnapshot,
25
+ type ModelsConfig,
26
+ preserveConfigMapKeys,
27
+ readUserConfigRoot,
28
+ snakeToCamel,
29
+ synthesizeLegacyRegistry,
30
+ type VesselConfig,
31
+ validateModels,
32
+ withConfigLock,
33
+ writeUserConfigRoot,
34
+ } from '@vessel-agent/config';
35
+
36
+ function isRecord(value: unknown): value is Record<string, unknown> {
37
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
38
+ }
39
+
40
+ /** 一次 registry 读取:合并后 config(user/project/env 层叠)+ 快照 + legacy 存在性。 */
41
+ export interface RegistryRead {
42
+ config: VesselConfig;
43
+ snapshot: ModelRegistrySnapshot;
44
+ /** provider.* 有非 default 层来源(user/project/env/cli;含 legacy 键折叠) */
45
+ legacyPresent: boolean;
46
+ }
47
+
48
+ /** 读当前合并 config 并合成 registry 快照(list / 引用检查 / effective 的唯一读路径)。 */
49
+ export async function readRegistry(): Promise<RegistryRead> {
50
+ const { config, sources } = await loadConfig();
51
+ const legacyPresent = Object.entries(sources).some(
52
+ ([key, source]) => (key === 'provider' || key.startsWith('provider.')) && source !== 'default',
53
+ );
54
+ const snapshot = synthesizeLegacyRegistry(config, legacyPresent);
55
+ return { config, snapshot, legacyPresent };
56
+ }
57
+
58
+ /** 条目的内部引用:models.default(别称展开后按条目键判)。别称是条目自有字段,随条目删。 */
59
+ export function entryReferences(snapshot: ModelRegistrySnapshot, entryId: string): string[] {
60
+ const refs: string[] = [];
61
+ const defaultRef = snapshot.defaultRef;
62
+ if (defaultRef !== undefined && defaultRef !== '') {
63
+ const expanded = Object.hasOwn(snapshot.aliases, defaultRef)
64
+ ? (snapshot.aliases[defaultRef] as string)
65
+ : defaultRef;
66
+ if (expanded === entryId) refs.push('models.default');
67
+ }
68
+ return refs;
69
+ }
70
+
71
+ /** credential 的内部引用:entry.credential 指向它的条目键列表(多对一共享)。 */
72
+ export function credentialReferences(
73
+ snapshot: ModelRegistrySnapshot,
74
+ credentialId: string,
75
+ ): string[] {
76
+ return Object.values(snapshot.entries)
77
+ .filter((entry) => entry.credentialRef === credentialId)
78
+ .map((entry) => entry.id);
79
+ }
80
+
81
+ /** 磁盘 models 块(snake_case)→ camelCase(复用 loader 映射口径,map 键原样保留)。 */
82
+ export function modelsToCamel(models: Record<string, unknown>): ModelsConfig {
83
+ const wrapped = snakeToCamel<{ models?: ModelsConfig }>(
84
+ { models },
85
+ { preserveKey: preserveConfigMapKeys },
86
+ );
87
+ return wrapped.models ?? {};
88
+ }
89
+
90
+ /**
91
+ * 写前预校验:validateModels(camelCase 口径);有错即抛,不落盘。
92
+ * credential 引用命中按合并后 credentials 判(project 层凭证可被 user 层条目引用);
93
+ * 返回 warnings(H4 同 wire 价格冲突等)供 RPC 回传。
94
+ */
95
+ function assertModelsValid(
96
+ candidate: Record<string, unknown>,
97
+ merged: VesselConfig,
98
+ ): ConfigValidationWarning[] {
99
+ const errors: ConfigValidationError[] = [];
100
+ const warnings: ConfigValidationWarning[] = [];
101
+ const camel = modelsToCamel(candidate);
102
+ const forValidation = {
103
+ ...camel,
104
+ credentials: { ...(merged.models?.credentials ?? {}), ...(camel.credentials ?? {}) },
105
+ };
106
+ validateModels(
107
+ forValidation as unknown as Record<string, unknown>,
108
+ merged.provider,
109
+ errors,
110
+ warnings,
111
+ );
112
+ if (errors.length > 0) {
113
+ throw new Error(`models_invalid: ${errors.map((e) => `${e.path}: ${e.message}`).join('; ')}`);
114
+ }
115
+ return warnings;
116
+ }
117
+
118
+ /** 删空 credentials/entries map,避免在 yaml 里留空壳。 */
119
+ function pruneEmptyMaps(models: Record<string, unknown>): void {
120
+ for (const key of ['credentials', 'entries']) {
121
+ const value = models[key];
122
+ if (isRecord(value) && Object.keys(value).length === 0) delete models[key];
123
+ }
124
+ }
125
+
126
+ /**
127
+ * models 块写事务:lock 内 读合并 config(provider 校验口径)→ 读 YAML 根 → 改目标块 →
128
+ * 预校验 → 原子写 → 读回。返回读回的 models 块(snake_case;块被清空时为 {})+ warnings。
129
+ */
130
+ async function mutateModels(
131
+ mutate: (models: Record<string, unknown>, merged: VesselConfig) => void,
132
+ ): Promise<{ models: Record<string, unknown>; warnings: ConfigValidationWarning[] }> {
133
+ const configPath = getUserConfigPath();
134
+ return withConfigLock(configPath, async () => {
135
+ const { config: merged } = await loadConfig();
136
+ const root = await readUserConfigRoot(configPath);
137
+ // 既有块形状非法 → fail-fast,不静默替换(避免把用户的手写内容覆盖掉)。
138
+ for (const [key, value] of [
139
+ ['models', root.models],
140
+ ['models.credentials', isRecord(root.models) ? root.models.credentials : undefined],
141
+ ['models.entries', isRecord(root.models) ? root.models.entries : undefined],
142
+ ] as const) {
143
+ if (value !== undefined && !isRecord(value)) {
144
+ throw new Error(`models_invalid: existing ${key} block is not an object; fix it first`);
145
+ }
146
+ }
147
+ const models = isRecord(root.models) ? { ...root.models } : {};
148
+ mutate(models, merged);
149
+ pruneEmptyMaps(models);
150
+ const warnings = assertModelsValid(models, merged);
151
+ const nextRoot = { ...root };
152
+ if (Object.keys(models).length === 0) delete nextRoot.models;
153
+ else nextRoot.models = models;
154
+ await writeUserConfigRoot(configPath, nextRoot);
155
+ const readBack = await readUserConfigRoot(configPath);
156
+ return { models: isRecord(readBack.models) ? readBack.models : {}, warnings };
157
+ });
158
+ }
159
+
160
+ /** model_set:整条替换(增改合一,继承 vendorSet 纪律)。返回写后读回 + warnings。 */
161
+ export async function modelSet(
162
+ id: string,
163
+ entry: ModelEntry,
164
+ ): Promise<{ models: Record<string, unknown>; warnings: ConfigValidationWarning[] }> {
165
+ return mutateModels((models) => {
166
+ const entries = isRecord(models.entries) ? { ...models.entries } : {};
167
+ entries[id] = entryToYaml(entry);
168
+ models.entries = entries;
169
+ });
170
+ }
171
+
172
+ /** model_remove:用户层存在性 + 合并 registry 引用检查(被引用 → 报错列引用,不级联删)。 */
173
+ export async function modelRemove(id: string): Promise<void> {
174
+ await mutateModels((models, merged) => {
175
+ const entries = isRecord(models.entries) ? models.entries : {};
176
+ if (!Object.hasOwn(entries, id)) {
177
+ throw new Error(`unknown_entry: "${id}" is not in the user config models.entries block`);
178
+ }
179
+ const refs = entryReferences(synthesizeLegacyRegistry(merged), id);
180
+ if (refs.length > 0) {
181
+ throw new Error(
182
+ `entry_in_use: "${id}" is referenced by ${refs.join(', ')}; remove those references first`,
183
+ );
184
+ }
185
+ const next = { ...entries };
186
+ delete next[id];
187
+ models.entries = next;
188
+ });
189
+ }
190
+
191
+ /** default_set:ref 必须命中注册条目(validateModels 严格面)。 */
192
+ export async function defaultSet(ref: string): Promise<void> {
193
+ await mutateModels((models) => {
194
+ models.default = ref;
195
+ });
196
+ }
197
+
198
+ /** credential_set 的 yaml 元数据半(值半在 index.ts 先写;§3.3 事务顺序)。 */
199
+ export async function credentialSetMeta(
200
+ id: string,
201
+ meta: { baseUrl: string; apiKeyEnv?: string },
202
+ ): Promise<void> {
203
+ await mutateModels((models) => {
204
+ const credentials = isRecord(models.credentials) ? { ...models.credentials } : {};
205
+ credentials[id] = credentialToYaml(meta);
206
+ models.credentials = credentials;
207
+ });
208
+ }
209
+
210
+ /** credential_remove 的 yaml 元数据半(引用检查在 index.ts;库值半随后删)。 */
211
+ export async function credentialRemoveMeta(id: string): Promise<void> {
212
+ await mutateModels((models) => {
213
+ const credentials = isRecord(models.credentials) ? models.credentials : {};
214
+ if (!Object.hasOwn(credentials, id)) {
215
+ throw new Error(
216
+ `unknown_credential: "${id}" is not in the user config models.credentials block`,
217
+ );
218
+ }
219
+ const next = { ...credentials };
220
+ delete next[id];
221
+ models.credentials = next;
222
+ });
223
+ }