openclaw-plugin-model-fetch 0.2.6 → 0.2.8

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.
@@ -60,6 +60,38 @@ export declare function mergeModels({ existing, selected, filter, }: {
60
60
  selected: ModelDefinitionLike[];
61
61
  filter: ModelFilterConfig;
62
62
  }): ModelMergeResult;
63
+ /**
64
+ * Rewrites the explicit model references that name `fromRef` to `toRef`.
65
+ *
66
+ * The reference collector only reads, so the walk is repeated here with a
67
+ * writable setter. `forEachExplicitModelReference` reports the exact path of
68
+ * every reference it finds, so the setter mirrors that path shape.
69
+ */
70
+ export declare function rewriteModelReferences(draft: unknown, fromRef: string, toRef: string): {
71
+ changed: boolean;
72
+ paths: string[];
73
+ };
74
+ type ModelRefPair = {
75
+ fromRef: string;
76
+ toRef: string;
77
+ };
78
+ /**
79
+ * Moves the config entries that OpenClaw keys by model reference from one
80
+ * spelling to another.
81
+ *
82
+ * `agents.*.models` carries per-model metadata such as `alias`, and
83
+ * `modelPolicy.allow` names models by reference. A provider can hold the same
84
+ * model under two letter-case spellings, so retiring the stale spelling has to
85
+ * move those entries to the surviving one. Dropping them instead would throw
86
+ * the alias away and leave the metadata attached to a model that no longer
87
+ * exists.
88
+ */
89
+ export declare function migrateModelRefEntries(draft: unknown, pairs: readonly ModelRefPair[], options?: {
90
+ targetAgents?: readonly string[];
91
+ }): {
92
+ changed: boolean;
93
+ paths: string[];
94
+ };
63
95
  /**
64
96
  * Reports which of `modelIds` are still named by a non-agent model consumer,
65
97
  * together with the config paths that reference them.
@@ -78,6 +110,26 @@ export declare function applyModelReferenceProtection({ existing, merged, provid
78
110
  models: ModelDefinitionLike[];
79
111
  protectedModels: ProtectedModel[];
80
112
  };
113
+ /**
114
+ * Finds removal candidates that only differ from a surviving model by letter
115
+ * case.
116
+ *
117
+ * A provider list can hold both `auto/MiniMax-M3` and `auto/minimax-m3`. The
118
+ * filter keeps one of them and drops the other, so the two entries point at
119
+ * the same remote model and the deletion plan can say so instead of leaving
120
+ * the user with two look-alike ids.
121
+ */
122
+ export declare function collectCaseVariantRelations(removedIds: readonly string[], survivingIds: readonly string[]): {
123
+ removedId: string;
124
+ survivingModelId: string;
125
+ }[];
126
+ /**
127
+ * The model OpenClaw falls back to when an agent has no explicit selection.
128
+ *
129
+ * Agents can override the default, so the first agent that names a primary
130
+ * model wins. The value is the bare `provider/model` reference.
131
+ */
132
+ export declare function resolveDefaultModelRef(config: unknown): string | undefined;
81
133
  export declare function buildModelsEndpoint(providerId: string, provider: ProviderLike): string;
82
134
  export declare function mapFetchedRows(providerId: string, provider: ProviderLike, rows: unknown[]): ModelDefinitionLike[];
83
135
  type GuardedFetch = (params: GuardedFetchOptions) => Promise<GuardedFetchResult>;
@@ -413,6 +413,277 @@ function forEachExplicitModelReference(config, visit) {
413
413
  }
414
414
  }
415
415
  }
416
+ /**
417
+ * Rewrites the explicit model references that name `fromRef` to `toRef`.
418
+ *
419
+ * The reference collector only reads, so the walk is repeated here with a
420
+ * writable setter. `forEachExplicitModelReference` reports the exact path of
421
+ * every reference it finds, so the setter mirrors that path shape.
422
+ */
423
+ export function rewriteModelReferences(draft, fromRef, toRef) {
424
+ if (!isRecord(draft))
425
+ return { changed: false, paths: [] };
426
+ const source = fromRef.trim();
427
+ const target = toRef.trim();
428
+ if (!source || !target || source === target)
429
+ return { changed: false, paths: [] };
430
+ const changed = [];
431
+ const writeScalar = (container, field, basePath) => {
432
+ if (!isRecord(container))
433
+ return;
434
+ const current = container[field];
435
+ if (typeof current !== "string" || current.trim() !== source)
436
+ return;
437
+ container[field] = target;
438
+ changed.push(`${basePath}.${field}`);
439
+ };
440
+ const writeSetting = (container, field, basePath) => {
441
+ if (!isRecord(container))
442
+ return;
443
+ const current = container[field];
444
+ if (typeof current === "string") {
445
+ if (current.trim() !== source)
446
+ return;
447
+ container[field] = target;
448
+ changed.push(`${basePath}.${field}`);
449
+ return;
450
+ }
451
+ if (!isRecord(current))
452
+ return;
453
+ if (typeof current.primary === "string" && current.primary.trim() === source) {
454
+ current.primary = target;
455
+ changed.push(`${basePath}.${field}.primary`);
456
+ }
457
+ const fallbacks = current.fallbacks;
458
+ if (!Array.isArray(fallbacks))
459
+ return;
460
+ fallbacks.forEach((fallback, index) => {
461
+ if (typeof fallback !== "string" || fallback.trim() !== source)
462
+ return;
463
+ fallbacks[index] = target;
464
+ changed.push(`${basePath}.${field}.fallbacks[${index}]`);
465
+ });
466
+ };
467
+ const tools = isRecord(draft.tools) ? draft.tools : undefined;
468
+ if (tools) {
469
+ const exec = asOptionalRecord(tools.exec);
470
+ const reviewer = asOptionalRecord(exec?.reviewer);
471
+ if (isRecord(reviewer))
472
+ writeSetting(reviewer, "model", "tools.exec.reviewer");
473
+ if (isRecord(tools.media)) {
474
+ for (const capability of ["image", "audio", "video"]) {
475
+ const media = asOptionalRecord(tools.media[capability]);
476
+ if (!media)
477
+ continue;
478
+ writeScalar(media, "preferredModel", `tools.media.${capability}`);
479
+ }
480
+ }
481
+ }
482
+ const agents = isRecord(draft.agents) ? draft.agents : undefined;
483
+ const defaults = asOptionalRecord(agents?.defaults);
484
+ if (defaults)
485
+ rewriteAgentModelReferences(defaults, "agents.defaults", false, writeScalar, writeSetting);
486
+ if (agents && isRecord(agents.entries)) {
487
+ for (const agentId of Object.keys(agents.entries).sort((left, right) => left.localeCompare(right))) {
488
+ const entry = agents.entries[agentId];
489
+ if (!isRecord(entry))
490
+ continue;
491
+ rewriteAgentModelReferences(entry, `agents.entries.${agentId}`, true, writeScalar, writeSetting);
492
+ }
493
+ }
494
+ else if (agents && Array.isArray(agents.list)) {
495
+ agents.list.forEach((entry, index) => {
496
+ if (!isRecord(entry))
497
+ return;
498
+ rewriteAgentModelReferences(entry, `agents.list[${index}]`, true, writeScalar, writeSetting);
499
+ });
500
+ }
501
+ const tts = asOptionalRecord(draft.tts);
502
+ if (tts)
503
+ writeSetting(tts, "summaryModel", "tts");
504
+ const hooks = isRecord(draft.hooks) ? draft.hooks : undefined;
505
+ if (hooks) {
506
+ if (isRecord(hooks.gmail))
507
+ writeScalar(hooks.gmail, "model", "hooks.gmail");
508
+ if (Array.isArray(hooks.mappings)) {
509
+ hooks.mappings.forEach((mapping, index) => {
510
+ if (!isRecord(mapping))
511
+ return;
512
+ writeScalar(mapping, "model", `hooks.mappings[${index}]`);
513
+ });
514
+ }
515
+ }
516
+ const channels = isRecord(draft.channels) ? draft.channels : undefined;
517
+ if (channels) {
518
+ const modelByChannel = isRecord(channels.modelByChannel) ? channels.modelByChannel : undefined;
519
+ if (modelByChannel) {
520
+ for (const channelId of Object.keys(modelByChannel).sort((left, right) => left.localeCompare(right))) {
521
+ const channelMap = modelByChannel[channelId];
522
+ if (!isRecord(channelMap))
523
+ continue;
524
+ for (const targetId of Object.keys(channelMap).sort((left, right) => left.localeCompare(right))) {
525
+ writeSetting(channelMap, targetId, `channels.modelByChannel.${channelId}`);
526
+ }
527
+ }
528
+ }
529
+ const discord = asOptionalRecord(channels.discord);
530
+ if (discord) {
531
+ rewriteDiscordVoiceModelReferences(discord.voice, "channels.discord.voice", writeScalar, writeSetting);
532
+ if (isRecord(discord.accounts)) {
533
+ for (const accountId of Object.keys(discord.accounts).sort((left, right) => left.localeCompare(right))) {
534
+ rewriteDiscordVoiceModelReferences(asOptionalRecord(discord.accounts[accountId])?.voice, `channels.discord.accounts.${accountId}.voice`, writeScalar, writeSetting);
535
+ }
536
+ }
537
+ }
538
+ }
539
+ return { changed: changed.length > 0, paths: changed.sort((left, right) => left.localeCompare(right)) };
540
+ }
541
+ function rewriteAgentModelReferences(agent, basePath, includeEntrySelectors, writeScalar, writeSetting) {
542
+ writeSetting(agent, "model", basePath);
543
+ writeScalar(agent, "utilityModel", basePath);
544
+ writeScalar(agent, "decisionModel", basePath);
545
+ writeSetting(agent, "imageModel", basePath);
546
+ writeSetting(agent, "voiceModel", basePath);
547
+ writeSetting(agent, "pdfModel", basePath);
548
+ const mediaModels = asOptionalRecord(agent.mediaModels);
549
+ if (mediaModels) {
550
+ for (const capability of ["image", "video", "music"]) {
551
+ writeSetting(mediaModels, capability, `${basePath}.mediaModels`);
552
+ }
553
+ }
554
+ const cyberFailover = asOptionalRecord(asOptionalRecord(agent.embeddedAgent)?.cyberFailover);
555
+ if (cyberFailover)
556
+ writeSetting(cyberFailover, "model", `${basePath}.embeddedAgent.cyberFailover`);
557
+ writeSetting(asOptionalRecord(agent.heartbeat), "model", `${basePath}.heartbeat`);
558
+ writeSetting(asOptionalRecord(agent.subagents), "model", `${basePath}.subagents`);
559
+ const compaction = asOptionalRecord(agent.compaction);
560
+ if (compaction) {
561
+ writeSetting(compaction, "model", `${basePath}.compaction`);
562
+ writeSetting(asOptionalRecord(compaction.memoryFlush), "model", `${basePath}.compaction.memoryFlush`);
563
+ }
564
+ if (!includeEntrySelectors)
565
+ return;
566
+ const exec = asOptionalRecord(asOptionalRecord(agent.tools)?.exec);
567
+ writeSetting(asOptionalRecord(exec?.reviewer), "model", `${basePath}.tools.exec.reviewer`);
568
+ writeSetting(asOptionalRecord(agent.tts), "summaryModel", `${basePath}.tts`);
569
+ }
570
+ function rewriteDiscordVoiceModelReferences(voice, basePath, writeScalar, writeSetting) {
571
+ const voiceConfig = asOptionalRecord(voice);
572
+ if (!voiceConfig)
573
+ return;
574
+ writeSetting(voiceConfig, "model", basePath);
575
+ writeSetting(asOptionalRecord(voiceConfig.tts), "summaryModel", `${basePath}.tts`);
576
+ }
577
+ /**
578
+ * Moves the config entries that OpenClaw keys by model reference from one
579
+ * spelling to another.
580
+ *
581
+ * `agents.*.models` carries per-model metadata such as `alias`, and
582
+ * `modelPolicy.allow` names models by reference. A provider can hold the same
583
+ * model under two letter-case spellings, so retiring the stale spelling has to
584
+ * move those entries to the surviving one. Dropping them instead would throw
585
+ * the alias away and leave the metadata attached to a model that no longer
586
+ * exists.
587
+ */
588
+ export function migrateModelRefEntries(draft, pairs, options = {}) {
589
+ const replacements = new Map();
590
+ for (const pair of pairs) {
591
+ const from = pair.fromRef.trim();
592
+ const to = pair.toRef.trim();
593
+ if (!from || !to || from === to)
594
+ continue;
595
+ replacements.set(from, to);
596
+ }
597
+ if (replacements.size === 0)
598
+ return { changed: false, paths: [] };
599
+ const changed = [];
600
+ const moveEntry = (container, basePath) => {
601
+ if (!isRecord(container))
602
+ return;
603
+ for (const [from, to] of replacements) {
604
+ if (!Object.prototype.hasOwnProperty.call(container, from))
605
+ continue;
606
+ const moved = container[from];
607
+ const existing = container[to];
608
+ // The surviving spelling wins on conflict so an alias already set for it
609
+ // is not overwritten by the stale one.
610
+ container[to] =
611
+ isRecord(moved) && isRecord(existing) ? { ...moved, ...existing } : (existing ?? moved);
612
+ delete container[from];
613
+ changed.push(`${basePath}.${to}`);
614
+ }
615
+ };
616
+ const rewriteAllowList = (container, field, basePath) => {
617
+ if (!isRecord(container))
618
+ return;
619
+ const list = container[field];
620
+ if (!Array.isArray(list))
621
+ return;
622
+ const next = [];
623
+ const seen = new Set();
624
+ let touched = false;
625
+ for (const item of list) {
626
+ if (typeof item !== "string") {
627
+ next.push(item);
628
+ continue;
629
+ }
630
+ const trimmed = item.trim();
631
+ const mapped = replacements.get(trimmed) ?? trimmed;
632
+ if (mapped !== trimmed)
633
+ touched = true;
634
+ if (seen.has(mapped)) {
635
+ touched = true;
636
+ continue;
637
+ }
638
+ seen.add(mapped);
639
+ next.push(mapped);
640
+ }
641
+ if (!touched)
642
+ return;
643
+ container[field] = next;
644
+ changed.push(`${basePath}.${field}`);
645
+ };
646
+ if (!isRecord(draft) || !isRecord(draft.agents)) {
647
+ return { changed: false, paths: [] };
648
+ }
649
+ const agents = draft.agents;
650
+ const defaults = asOptionalRecord(agents.defaults);
651
+ if (defaults) {
652
+ moveEntry(defaults.models, "agents.defaults.models");
653
+ rewriteAllowList(defaults.modelPolicy, "allow", "agents.defaults.modelPolicy");
654
+ }
655
+ const requestedAgents = (options.targetAgents ?? [])
656
+ .map((agentId) => agentId.trim())
657
+ .filter(Boolean);
658
+ const agentScope = requestedAgents.length > 0 ? new Set(requestedAgents) : null;
659
+ const migrateAgent = (entry, basePath) => {
660
+ const agent = asOptionalRecord(entry);
661
+ if (!agent)
662
+ return;
663
+ moveEntry(agent.models, `${basePath}.models`);
664
+ rewriteAllowList(agent.modelPolicy, "allow", `${basePath}.modelPolicy`);
665
+ };
666
+ if (isRecord(agents.entries)) {
667
+ for (const agentId of Object.keys(agents.entries).sort((left, right) => left.localeCompare(right))) {
668
+ if (agentScope && !agentScope.has(agentId))
669
+ continue;
670
+ migrateAgent(agents.entries[agentId], `agents.entries.${agentId}`);
671
+ }
672
+ }
673
+ else if (Array.isArray(agents.list)) {
674
+ agents.list.forEach((entry, index) => {
675
+ const agent = asOptionalRecord(entry);
676
+ const agentId = typeof agent?.id === "string" && agent.id.trim() ? agent.id.trim() : undefined;
677
+ if (agentScope && (!agentId || !agentScope.has(agentId)))
678
+ return;
679
+ migrateAgent(agent, `agents.list[${index}]`);
680
+ });
681
+ }
682
+ return {
683
+ changed: changed.length > 0,
684
+ paths: changed.sort((left, right) => left.localeCompare(right)),
685
+ };
686
+ }
416
687
  function visitAgentModelReferences(path, agent, includeEntrySelectors, visit) {
417
688
  readModelRefSetting(agent.model, `${path}.model`, visit);
418
689
  readModelRefScalar(agent.utilityModel, `${path}.utilityModel`, visit);
@@ -507,6 +778,85 @@ export function applyModelReferenceProtection({ existing, merged, providerId, co
507
778
  }
508
779
  return { models, protectedModels };
509
780
  }
781
+ /**
782
+ * Finds removal candidates that only differ from a surviving model by letter
783
+ * case.
784
+ *
785
+ * A provider list can hold both `auto/MiniMax-M3` and `auto/minimax-m3`. The
786
+ * filter keeps one of them and drops the other, so the two entries point at
787
+ * the same remote model and the deletion plan can say so instead of leaving
788
+ * the user with two look-alike ids.
789
+ */
790
+ export function collectCaseVariantRelations(removedIds, survivingIds) {
791
+ const byLowerId = new Map();
792
+ for (const id of survivingIds) {
793
+ const key = id.toLowerCase();
794
+ const bucket = byLowerId.get(key);
795
+ if (bucket)
796
+ bucket.push(id);
797
+ else
798
+ byLowerId.set(key, [id]);
799
+ }
800
+ const relations = [];
801
+ for (const removedId of removedIds) {
802
+ const bucket = byLowerId.get(removedId.toLowerCase());
803
+ if (!bucket)
804
+ continue;
805
+ const match = bucket.find((id) => id !== removedId);
806
+ if (!match)
807
+ continue;
808
+ relations.push({ removedId, survivingModelId: match });
809
+ }
810
+ return relations.sort((left, right) => left.removedId.localeCompare(right.removedId));
811
+ }
812
+ /**
813
+ * The model OpenClaw falls back to when an agent has no explicit selection.
814
+ *
815
+ * Agents can override the default, so the first agent that names a primary
816
+ * model wins. The value is the bare `provider/model` reference.
817
+ */
818
+ export function resolveDefaultModelRef(config) {
819
+ if (!isRecord(config))
820
+ return undefined;
821
+ const agents = isRecord(config.agents) ? config.agents : undefined;
822
+ if (!agents)
823
+ return undefined;
824
+ const readPrimary = (agent) => {
825
+ if (!isRecord(agent))
826
+ return undefined;
827
+ const model = agent.model;
828
+ if (typeof model === "string") {
829
+ const trimmed = model.trim();
830
+ return trimmed ? trimmed : undefined;
831
+ }
832
+ if (!isRecord(model))
833
+ return undefined;
834
+ const primary = model.primary;
835
+ if (typeof primary !== "string")
836
+ return undefined;
837
+ const trimmed = primary.trim();
838
+ return trimmed ? trimmed : undefined;
839
+ };
840
+ const defaults = asOptionalRecord(agents.defaults);
841
+ const defaultPrimary = readPrimary(defaults);
842
+ if (defaultPrimary)
843
+ return defaultPrimary;
844
+ if (isRecord(agents.entries)) {
845
+ for (const agentId of Object.keys(agents.entries).sort((left, right) => left.localeCompare(right))) {
846
+ const primary = readPrimary(agents.entries[agentId]);
847
+ if (primary)
848
+ return primary;
849
+ }
850
+ }
851
+ if (Array.isArray(agents.list)) {
852
+ for (const entry of agents.list) {
853
+ const primary = readPrimary(entry);
854
+ if (primary)
855
+ return primary;
856
+ }
857
+ }
858
+ return undefined;
859
+ }
510
860
  function normalizeBaseUrl(baseUrl) {
511
861
  return baseUrl.trim().replace(/\/+$/, "");
512
862
  }
@@ -23,7 +23,7 @@ export declare function createModelFetchOperations({ api, factoryConfig, fetchMo
23
23
  fetchModels: (providerId: string) => Promise<FetchModelsOutput>;
24
24
  saveStrategy: ({ provider, filter, targetAgents, }: SaveStrategyInput) => Promise<SaveStrategyOutput>;
25
25
  previewApply: (provider: string, scope?: SessionSelectionScope) => Promise<PreviewApplyOutput>;
26
- applyStrategy: ({ provider, fingerprint, expectedRemovals, targetAgents, }: ApplyStrategyInput, scope?: SessionSelectionScope) => Promise<ApplyStrategyOutput>;
26
+ applyStrategy: ({ provider, fingerprint, expectedRemovals, referenceRewrites, targetAgents, }: ApplyStrategyInput, scope?: SessionSelectionScope) => Promise<ApplyStrategyOutput>;
27
27
  refreshProvider: (params: ModelFetchParams) => Promise<{
28
28
  provider: string;
29
29
  fetched: number;
@@ -2,7 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { Value } from "typebox/value";
3
3
  import { getSessionEntryAsync, listSessionEntries, patchSessionEntry, } from "openclaw/plugin-sdk/session-store-runtime";
4
4
  import { modelFetchContract } from "./contract.js";
5
- import { applyModelReferenceProtection, collectModelReferenceUsages, fetchProviderModels, getProvider, mergeModels, resolveApiKey, resolveProviderFilter, resolveProviderTargetAgents, runModelFetch, selectFetchedModels, syncAgentModelEntries, syncConfiguredModelPolicyAllow, } from "./model-fetch.js";
5
+ import { applyModelReferenceProtection, collectCaseVariantRelations, collectModelReferenceUsages, fetchProviderModels, getProvider, mergeModels, migrateModelRefEntries, resolveDefaultModelRef, resolveApiKey, resolveProviderFilter, resolveProviderTargetAgents, rewriteModelReferences, runModelFetch, selectFetchedModels, syncAgentModelEntries, syncConfiguredModelPolicyAllow, } from "./model-fetch.js";
6
6
  /**
7
7
  * The host exposes a single-attempt config mutation to plugins, so a write
8
8
  * that loses the race against another writer (for example an OpenClaw upgrade
@@ -69,6 +69,50 @@ function normalizeTargetAgents(targetAgents) {
69
69
  function configPath(providerId) {
70
70
  return `models.providers.${providerId}.models`;
71
71
  }
72
+ /**
73
+ * Validates the requested reference rewrites against the plan.
74
+ *
75
+ * A rewrite may only retarget a model that the plan protects, and it may only
76
+ * point at a model that survives the replacement. Rewriting to a model that is
77
+ * itself removed would leave the config with a dangling reference, so the
78
+ * whole plan is rejected instead.
79
+ */
80
+ function normalizeReferenceRewrites(requested, computed) {
81
+ if (!requested || requested.length === 0)
82
+ return [];
83
+ const protectedIds = new Set(computed.protectedModels.map((entry) => entry.modelId));
84
+ const survivingIds = new Set(computed.finalModels.map((model) => model.id));
85
+ const removedIds = new Set(computed.removedIds);
86
+ const providerPrefix = `${computed.providerId}/`;
87
+ const result = [];
88
+ const seen = new Set();
89
+ for (const entry of requested) {
90
+ const protectedModelId = entry.protectedModelId.trim();
91
+ if (!protectedIds.has(protectedModelId)) {
92
+ throw new Error(`引用改写目标 ${protectedModelId} 不在本次保留列表中,已取消写入。请重新预览。`);
93
+ }
94
+ if (seen.has(protectedModelId))
95
+ continue;
96
+ const targetRef = entry.targetRef.trim();
97
+ if (!targetRef.startsWith(providerPrefix)) {
98
+ throw new Error(`引用改写目标 ${targetRef} 不属于当前 Provider,已取消写入。请重新预览。`);
99
+ }
100
+ const targetId = targetRef.slice(providerPrefix.length);
101
+ if (!targetId) {
102
+ throw new Error(`引用改写目标 ${targetRef} 无效,已取消写入。请重新预览。`);
103
+ }
104
+ if (removedIds.has(targetId) || !survivingIds.has(targetId)) {
105
+ throw new Error(`引用改写目标 ${targetRef} 也会被删除,已取消写入。请重新预览。`);
106
+ }
107
+ seen.add(protectedModelId);
108
+ result.push({
109
+ protectedModelId,
110
+ fromRef: `${computed.providerId}/${protectedModelId}`,
111
+ toRef: targetRef,
112
+ });
113
+ }
114
+ return result;
115
+ }
72
116
  function planFingerprint(input) {
73
117
  return createHash("sha256")
74
118
  .update(JSON.stringify({
@@ -400,6 +444,8 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
400
444
  removedIds,
401
445
  protectedModels: protection.protectedModels,
402
446
  });
447
+ const caseVariants = collectCaseVariantRelations(removedIds, protection.models.map((model) => model.id));
448
+ const defaultModelRef = resolveDefaultModelRef(config);
403
449
  return {
404
450
  providerId,
405
451
  provider,
@@ -412,9 +458,13 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
412
458
  selectedIds: merge.selectedIds,
413
459
  unchangedCount: merge.unchanged,
414
460
  protectedModels: protection.protectedModels,
461
+ caseVariants,
462
+ defaultModelRef,
415
463
  models,
416
464
  fingerprint,
417
465
  finalModels: protection.models,
466
+ existingModels: existing,
467
+ mergedModels: merge.models,
418
468
  };
419
469
  }
420
470
  async function listProviders() {
@@ -495,6 +545,8 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
495
545
  addedIds: computed.addedIds,
496
546
  removedIds: computed.removedIds,
497
547
  protectedModels: computed.protectedModels,
548
+ caseVariants: computed.caseVariants,
549
+ defaultModelRef: computed.defaultModelRef,
498
550
  selectedIds: computed.selectedIds,
499
551
  unchangedCount: computed.unchangedCount,
500
552
  affectedSessions,
@@ -505,7 +557,7 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
505
557
  models: computed.models,
506
558
  };
507
559
  }
508
- async function applyStrategy({ provider, fingerprint, expectedRemovals, targetAgents, }, scope = {}) {
560
+ async function applyStrategy({ provider, fingerprint, expectedRemovals, referenceRewrites, targetAgents, }, scope = {}) {
509
561
  const computed = await computePlan(provider);
510
562
  if (computed.fingerprint !== fingerprint) {
511
563
  throw new Error("模型列表或筛选策略已变化,请重新预览后再确认应用。");
@@ -513,8 +565,10 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
513
565
  if (!sameStringSets(computed.removedIds, expectedRemovals)) {
514
566
  throw new Error("待删除模型与确认列表不一致,已取消写入。请重新预览。");
515
567
  }
568
+ const rewrites = normalizeReferenceRewrites(referenceRewrites, computed);
516
569
  const nextTargetAgents = normalizeTargetAgents(targetAgents ?? savedTargetAgents(provider));
517
570
  let syncedAgents = [];
571
+ const rewrittenReferences = [];
518
572
  const result = await mutateConfigFileWithRetry(runtime, {
519
573
  base: "source",
520
574
  afterWrite: { mode: "auto" },
@@ -532,13 +586,47 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
532
586
  if (referenceProtectionDrift(config, provider, computed)) {
533
587
  throw new Error("模型引用在确认后发生变化,已取消写入。请重新预览。");
534
588
  }
535
- target.models = computed.finalModels;
589
+ for (const rewrite of rewrites) {
590
+ const result = rewriteModelReferences(config, rewrite.fromRef, rewrite.toRef);
591
+ if (result.changed)
592
+ rewrittenReferences.push(...result.paths);
593
+ }
594
+ // `agents.*.models` (which carries `alias`) and `modelPolicy.allow`
595
+ // are keyed by model reference but are not model references, so the
596
+ // walker above leaves them alone. A case-only rename has to move them
597
+ // to the surviving spelling; otherwise the alias and the allowlist
598
+ // entry are dropped along with the stale id.
599
+ const entryMigration = migrateModelRefEntries(config, [
600
+ ...rewrites.map((rewrite) => ({
601
+ fromRef: rewrite.fromRef,
602
+ toRef: rewrite.toRef,
603
+ })),
604
+ ...computed.caseVariants.map((variant) => ({
605
+ fromRef: `${provider}/${variant.removedId}`,
606
+ toRef: `${provider}/${variant.survivingModelId}`,
607
+ })),
608
+ ], { targetAgents: nextTargetAgents });
609
+ if (entryMigration.changed) {
610
+ rewrittenReferences.push(...entryMigration.paths);
611
+ }
612
+ // The rewrites may have released the references that kept a model in
613
+ // the list, so the final list is recomputed against the rewritten
614
+ // draft instead of reusing the previewed one.
615
+ const finalModels = rewrites.length > 0
616
+ ? applyModelReferenceProtection({
617
+ existing: computed.existingModels,
618
+ merged: computed.mergedModels,
619
+ providerId: provider,
620
+ config,
621
+ }).models
622
+ : computed.finalModels;
623
+ target.models = finalModels;
536
624
  ensurePluginEntry(config, provider, computed.filter, nextTargetAgents);
537
- const syncResult = syncConfiguredModelPolicyAllow(config, provider, computed.finalModels, {
625
+ const syncResult = syncConfiguredModelPolicyAllow(config, provider, finalModels, {
538
626
  targetAgents: nextTargetAgents,
539
627
  });
540
628
  syncedAgents = syncResult.syncedAgents;
541
- syncAgentModelEntries(config, provider, computed.finalModels, {
629
+ syncAgentModelEntries(config, provider, finalModels, {
542
630
  targetAgents: syncedAgents,
543
631
  });
544
632
  },
@@ -570,6 +658,7 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
570
658
  removed: computed.removedIds.length,
571
659
  selectedIds: computed.selectedIds,
572
660
  protectedModels: computed.protectedModels,
661
+ rewrittenReferences,
573
662
  targetAgents: nextTargetAgents,
574
663
  syncedAgents,
575
664
  sessionSelectionResets: resetSessionKeys.length,
package/dist/schemas.d.ts CHANGED
@@ -37,6 +37,27 @@ export declare const protectedModelSchema: Type.TObject<{
37
37
  references: Type.TArray<Type.TString>;
38
38
  }>;
39
39
  export type ProtectedModel = Static<typeof protectedModelSchema>;
40
+ /**
41
+ * A removal candidate that only differs from a surviving model by letter case.
42
+ */
43
+ export declare const caseVariantSchema: Type.TObject<{
44
+ removedId: Type.TString;
45
+ survivingModelId: Type.TString;
46
+ }>;
47
+ export type CaseVariant = Static<typeof caseVariantSchema>;
48
+ /**
49
+ * The replacement a protected model's references are rewritten to.
50
+ *
51
+ * `targetRef` is the full `provider/model` reference written into the config.
52
+ * `useDefaultModel` marks the case where the target is the agent default
53
+ * model, which the UI shows without naming a concrete provider model.
54
+ */
55
+ export declare const referenceRewriteSchema: Type.TObject<{
56
+ protectedModelId: Type.TString;
57
+ targetRef: Type.TString;
58
+ useDefaultModel: Type.TBoolean;
59
+ }>;
60
+ export type ReferenceRewrite = Static<typeof referenceRewriteSchema>;
40
61
  export declare const modelFetchResultSchema: Type.TObject<{
41
62
  provider: Type.TString;
42
63
  fetched: Type.TInteger;
@@ -171,6 +192,11 @@ export declare const applyPlanSchema: Type.TObject<{
171
192
  ref: Type.TString;
172
193
  references: Type.TArray<Type.TString>;
173
194
  }>>;
195
+ caseVariants: Type.TArray<Type.TObject<{
196
+ removedId: Type.TString;
197
+ survivingModelId: Type.TString;
198
+ }>>;
199
+ defaultModelRef: Type.TOptional<Type.TString>;
174
200
  selectedIds: Type.TArray<Type.TString>;
175
201
  unchangedCount: Type.TInteger;
176
202
  affectedSessions: Type.TArray<Type.TObject<{
@@ -193,6 +219,11 @@ export declare const previewApplyOutputSchema: Type.TObject<{
193
219
  ref: Type.TString;
194
220
  references: Type.TArray<Type.TString>;
195
221
  }>>;
222
+ caseVariants: Type.TArray<Type.TObject<{
223
+ removedId: Type.TString;
224
+ survivingModelId: Type.TString;
225
+ }>>;
226
+ defaultModelRef: Type.TOptional<Type.TString>;
196
227
  selectedIds: Type.TArray<Type.TString>;
197
228
  unchangedCount: Type.TInteger;
198
229
  affectedSessions: Type.TArray<Type.TObject<{
@@ -212,6 +243,11 @@ export declare const applyStrategyInputSchema: Type.TObject<{
212
243
  provider: Type.TString;
213
244
  fingerprint: Type.TString;
214
245
  expectedRemovals: Type.TArray<Type.TString>;
246
+ referenceRewrites: Type.TOptional<Type.TArray<Type.TObject<{
247
+ protectedModelId: Type.TString;
248
+ targetRef: Type.TString;
249
+ useDefaultModel: Type.TBoolean;
250
+ }>>>;
215
251
  targetAgents: Type.TOptional<Type.TArray<Type.TString>>;
216
252
  }>;
217
253
  export type ApplyStrategyInput = Static<typeof applyStrategyInputSchema>;
@@ -230,6 +266,7 @@ export declare const applyStrategyOutputSchema: Type.TObject<{
230
266
  ref: Type.TString;
231
267
  references: Type.TArray<Type.TString>;
232
268
  }>>;
269
+ rewrittenReferences: Type.TArray<Type.TString>;
233
270
  targetAgents: Type.TArray<Type.TString>;
234
271
  syncedAgents: Type.TArray<Type.TString>;
235
272
  sessionSelectionResets: Type.TInteger;