openclaw-plugin-model-fetch 0.2.8 → 0.2.10

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.
@@ -1,8 +1,8 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { Value } from "typebox/value";
3
- import { getSessionEntryAsync, listSessionEntries, patchSessionEntry, } from "openclaw/plugin-sdk/session-store-runtime";
3
+ import * as sessionStoreRuntime from "openclaw/plugin-sdk/session-store-runtime";
4
4
  import { modelFetchContract } from "./contract.js";
5
- import { applyModelReferenceProtection, collectCaseVariantRelations, collectModelReferenceUsages, fetchProviderModels, getProvider, mergeModels, migrateModelRefEntries, resolveDefaultModelRef, resolveApiKey, resolveProviderFilter, resolveProviderTargetAgents, rewriteModelReferences, runModelFetch, selectFetchedModels, syncAgentModelEntries, syncConfiguredModelPolicyAllow, } from "./model-fetch.js";
5
+ import { applyModelReferenceProtection, collectCaseVariantRelations, collectModelReferenceUsages, fetchProviderModels, getProvider, listConfiguredAgentEntries, 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
@@ -33,6 +33,16 @@ async function mutateConfigFileWithRetry(runtime, params) {
33
33
  }
34
34
  const AFFECTED_SESSION_LIMIT = 2_000;
35
35
  const DEFAULT_AGENT_ID = "main";
36
+ const getSessionEntryAsync = sessionStoreRuntime.getSessionEntryAsync;
37
+ const patchSessionEntry = sessionStoreRuntime.patchSessionEntry;
38
+ async function listSessionEntriesCompat(params) {
39
+ if (typeof sessionStoreRuntime.listSessionEntriesAsync === "function") {
40
+ return sessionStoreRuntime.listSessionEntriesAsync({
41
+ agentId: params?.agentId ?? DEFAULT_AGENT_ID,
42
+ });
43
+ }
44
+ return sessionStoreRuntime.listSessionEntries(params);
45
+ }
36
46
  function isRecord(value) {
37
47
  return typeof value === "object" && value !== null && !Array.isArray(value);
38
48
  }
@@ -111,6 +121,14 @@ function normalizeReferenceRewrites(requested, computed) {
111
121
  toRef: targetRef,
112
122
  });
113
123
  }
124
+ const rewrittenProtectedIds = new Set(result.map((entry) => entry.protectedModelId));
125
+ for (const entry of result) {
126
+ const targetId = entry.toRef.slice(providerPrefix.length);
127
+ if (targetId !== entry.protectedModelId &&
128
+ rewrittenProtectedIds.has(targetId)) {
129
+ throw new Error(`引用改写目标 ${entry.toRef} 也会在本次操作中被改写,已取消写入。请改为一个最终保留的模型。`);
130
+ }
131
+ }
114
132
  return result;
115
133
  }
116
134
  function planFingerprint(input) {
@@ -118,8 +136,8 @@ function planFingerprint(input) {
118
136
  .update(JSON.stringify({
119
137
  provider: input.providerId,
120
138
  filter: input.filter,
121
- fetched: input.fetchedIds,
122
- existing: input.existingIds,
139
+ fetched: input.fetched,
140
+ existing: input.existing,
123
141
  selected: input.selectedIds,
124
142
  added: input.addedIds,
125
143
  removed: input.removedIds,
@@ -127,6 +145,7 @@ function planFingerprint(input) {
127
145
  modelId: entry.modelId,
128
146
  references: entry.references,
129
147
  })),
148
+ defaultModelRef: input.defaultModelRef,
130
149
  }))
131
150
  .digest("hex");
132
151
  }
@@ -139,6 +158,51 @@ function sameStringSets(left, right) {
139
158
  return (leftSorted.length === rightSorted.length &&
140
159
  leftSorted.every((value, index) => value === rightSorted[index]));
141
160
  }
161
+ /**
162
+ * Runtime config resolution fills Provider-level model defaults (notably
163
+ * `api`, reasoning metadata, token limits, and zero costs) into each model,
164
+ * while the source config used by a write keeps those fields implicit.
165
+ * Compare each authored source field against the runtime materialization so
166
+ * externally changed fields still fail without treating generated defaults as
167
+ * configuration drift.
168
+ */
169
+ function sameProviderModels(sourceProvider, sourceModels, runtimeProvider, runtimeModels) {
170
+ if (sourceModels.length !== runtimeModels.length)
171
+ return false;
172
+ const sourceValueMatches = (source, runtime) => {
173
+ if (source === undefined)
174
+ return true;
175
+ if (Array.isArray(source)) {
176
+ return (Array.isArray(runtime) &&
177
+ source.length === runtime.length &&
178
+ source.every((entry, index) => sourceValueMatches(entry, runtime[index])));
179
+ }
180
+ if (isRecord(source)) {
181
+ if (!isRecord(runtime))
182
+ return false;
183
+ return Object.entries(source).every(([key, entry]) => entry === undefined ||
184
+ (Object.prototype.hasOwnProperty.call(runtime, key) &&
185
+ sourceValueMatches(entry, runtime[key])));
186
+ }
187
+ return Object.is(source, runtime);
188
+ };
189
+ const sourceShape = (provider, model) => {
190
+ const sourceModel = { ...model };
191
+ if (sourceModel.api !== undefined && sourceModel.api === provider.api) {
192
+ delete sourceModel.api;
193
+ }
194
+ if (sourceModel.baseUrl !== undefined && sourceModel.baseUrl === provider.baseUrl) {
195
+ delete sourceModel.baseUrl;
196
+ }
197
+ return sourceModel;
198
+ };
199
+ return sourceModels.every((sourceModel, index) => {
200
+ const runtimeModel = runtimeModels[index];
201
+ if (!runtimeModel || sourceModel.id !== runtimeModel.id)
202
+ return false;
203
+ return sourceValueMatches(sourceShape(sourceProvider, sourceModel), sourceShape(runtimeProvider, runtimeModel));
204
+ });
205
+ }
142
206
  function staleOverrideMatches(entry, providerId, removedIds) {
143
207
  if (entry.providerOverride) {
144
208
  return entry.providerOverride === providerId && removedIds.includes(entry.modelOverride ?? "");
@@ -240,7 +304,11 @@ function ensurePluginEntry(draft, providerId, filter, targetAgents = []) {
240
304
  entry.config = pluginConfig;
241
305
  draft.plugins.entries["model-fetch"] = entry;
242
306
  }
243
- export function createModelFetchOperations({ api, factoryConfig, fetchModels = fetchProviderModels, now = () => new Date(), sessionStore = { getSessionEntryAsync, patchSessionEntry, listSessionEntries }, }) {
307
+ export function createModelFetchOperations({ api, factoryConfig, fetchModels = fetchProviderModels, now = () => new Date(), sessionStore = {
308
+ getSessionEntryAsync,
309
+ patchSessionEntry,
310
+ listSessionEntries: listSessionEntriesCompat,
311
+ }, }) {
244
312
  const runtime = api.runtime;
245
313
  function currentConfig() {
246
314
  return runtime.config.current();
@@ -252,8 +320,7 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
252
320
  return normalizeTargetAgents(resolveProviderTargetAgents(providerId, config, factoryConfig));
253
321
  }
254
322
  function configuredAgentIds(config = currentConfig()) {
255
- const entries = config?.agents?.entries ?? {};
256
- return Object.keys(entries).filter((agentId) => agentId.trim().length > 0);
323
+ return listConfiguredAgentEntries(config).map(({ id }) => id);
257
324
  }
258
325
  /**
259
326
  * Lists the sessions of every candidate agent. `listSessionEntries` is
@@ -405,7 +472,7 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
405
472
  }
406
473
  async function computePlan(providerId) {
407
474
  const { provider, fetched, fetchedAt, config } = await fetchModelsForProvider(providerId);
408
- const filter = savedFilter(providerId);
475
+ const filter = savedFilter(providerId, config);
409
476
  selectFetchedModels(fetched, filter);
410
477
  const existing = provider.models ?? [];
411
478
  const selected = selectFetchedModels(fetched, filter);
@@ -434,18 +501,19 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
434
501
  visibleIds.add(model.id);
435
502
  }
436
503
  }
504
+ const defaultModelRef = resolveDefaultModelRef(config);
437
505
  const fingerprint = planFingerprint({
438
506
  providerId,
439
507
  filter,
440
- fetchedIds: fetched.map((model) => model.id),
441
- existingIds,
508
+ fetched,
509
+ existing,
442
510
  selectedIds: merge.selectedIds,
443
511
  addedIds,
444
512
  removedIds,
445
513
  protectedModels: protection.protectedModels,
514
+ defaultModelRef,
446
515
  });
447
516
  const caseVariants = collectCaseVariantRelations(removedIds, protection.models.map((model) => model.id));
448
- const defaultModelRef = resolveDefaultModelRef(config);
449
517
  return {
450
518
  providerId,
451
519
  provider,
@@ -471,11 +539,9 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
471
539
  const config = currentConfig();
472
540
  const providers = config?.models?.providers ?? {};
473
541
  const result = [];
474
- const agentEntries = config?.agents?.entries ?? {};
475
- const agents = Object.entries(agentEntries)
476
- .filter(([agentId]) => typeof agentId === "string" && agentId.trim().length > 0)
477
- .map(([agentId, entry]) => ({
478
- id: agentId,
542
+ const agents = listConfiguredAgentEntries(config)
543
+ .map(({ id, entry }) => ({
544
+ id,
479
545
  hasModelAllowlist: Array.isArray(entry?.modelPolicy?.allow) && entry.modelPolicy.allow.length > 0,
480
546
  }))
481
547
  .sort((left, right) => left.id.localeCompare(right.id));
@@ -546,7 +612,9 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
546
612
  removedIds: computed.removedIds,
547
613
  protectedModels: computed.protectedModels,
548
614
  caseVariants: computed.caseVariants,
549
- defaultModelRef: computed.defaultModelRef,
615
+ ...(computed.defaultModelRef !== undefined
616
+ ? { defaultModelRef: computed.defaultModelRef }
617
+ : {}),
550
618
  selectedIds: computed.selectedIds,
551
619
  unchangedCount: computed.unchangedCount,
552
620
  affectedSessions,
@@ -569,14 +637,19 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
569
637
  const nextTargetAgents = normalizeTargetAgents(targetAgents ?? savedTargetAgents(provider));
570
638
  let syncedAgents = [];
571
639
  const rewrittenReferences = [];
640
+ let removedIds = computed.removedIds;
641
+ let finalProtectedModels = computed.protectedModels;
572
642
  const result = await mutateConfigFileWithRetry(runtime, {
573
643
  base: "source",
574
644
  afterWrite: { mode: "auto" },
575
645
  mutate: (draft) => {
646
+ rewrittenReferences.length = 0;
647
+ syncedAgents = [];
648
+ removedIds = computed.removedIds;
649
+ finalProtectedModels = computed.protectedModels;
576
650
  const config = draft;
577
651
  const target = getProvider(config, provider);
578
- const currentExistingIds = (target.models ?? []).map((model) => model.id);
579
- if (!sameStringSets(currentExistingIds, computed.existingIds)) {
652
+ if (!sameProviderModels(target, target.models ?? [], computed.provider, computed.existingModels)) {
580
653
  throw new Error("Provider 配置在确认后发生变化,已取消写入。请重新预览。");
581
654
  }
582
655
  const currentFilter = normalizeFilter(resolveProviderFilter(provider, config, factoryConfig));
@@ -596,18 +669,21 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
596
669
  // walker above leaves them alone. A case-only rename has to move them
597
670
  // to the surviving spelling; otherwise the alias and the allowlist
598
671
  // 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);
672
+ // Explicit reference rewrites can change an alias definition used by
673
+ // any agent, so those entries are migrated across the full roster.
674
+ const rewriteEntryMigration = migrateModelRefEntries(config, rewrites.map((rewrite) => ({
675
+ fromRef: rewrite.fromRef,
676
+ toRef: rewrite.toRef,
677
+ })), { onAliasConflict: "error" });
678
+ if (rewriteEntryMigration.changed) {
679
+ rewrittenReferences.push(...rewriteEntryMigration.paths);
680
+ }
681
+ const caseEntryMigration = migrateModelRefEntries(config, computed.caseVariants.map((variant) => ({
682
+ fromRef: `${provider}/${variant.removedId}`,
683
+ toRef: `${provider}/${variant.survivingModelId}`,
684
+ })), { targetAgents: nextTargetAgents });
685
+ if (caseEntryMigration.changed) {
686
+ rewrittenReferences.push(...caseEntryMigration.paths);
611
687
  }
612
688
  // The rewrites may have released the references that kept a model in
613
689
  // the list, so the final list is recomputed against the rewritten
@@ -620,8 +696,13 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
620
696
  config,
621
697
  }).models
622
698
  : computed.finalModels;
699
+ const finalIds = new Set(finalModels.map((model) => model.id));
700
+ removedIds = computed.existingIds.filter((id) => !finalIds.has(id));
701
+ finalProtectedModels = collectModelReferenceUsages(config, provider, computed.protectedModels.map((entry) => entry.modelId));
623
702
  target.models = finalModels;
624
- ensurePluginEntry(config, provider, computed.filter, nextTargetAgents);
703
+ // Applying replaces the Provider model list; it must not rewrite this
704
+ // plugin's saved strategy. A plugin-config write triggers a runtime
705
+ // reload and invalidates the session action that is still returning.
625
706
  const syncResult = syncConfiguredModelPolicyAllow(config, provider, finalModels, {
626
707
  targetAgents: nextTargetAgents,
627
708
  });
@@ -635,7 +716,7 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
635
716
  // latest state and honours locks taken since the preview.
636
717
  const affectedSessions = await affectedSessionsFor({
637
718
  providerId: provider,
638
- removedIds: computed.removedIds,
719
+ removedIds,
639
720
  scope,
640
721
  });
641
722
  const resetSessionKeys = await resetStaleSessionSelections({
@@ -644,7 +725,7 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
644
725
  agentId: session.agentId,
645
726
  })),
646
727
  providerId: provider,
647
- removedIds: computed.removedIds,
728
+ removedIds,
648
729
  sessionStore,
649
730
  });
650
731
  return {
@@ -655,10 +736,10 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
655
736
  fetchedCount: computed.fetched.length,
656
737
  added: computed.addedIds.length,
657
738
  unchanged: computed.unchangedCount,
658
- removed: computed.removedIds.length,
739
+ removed: removedIds.length,
659
740
  selectedIds: computed.selectedIds,
660
- protectedModels: computed.protectedModels,
661
- rewrittenReferences,
741
+ protectedModels: finalProtectedModels,
742
+ rewrittenReferences: [...new Set(rewrittenReferences)].sort((left, right) => left.localeCompare(right)),
662
743
  targetAgents: nextTargetAgents,
663
744
  syncedAgents,
664
745
  sessionSelectionResets: resetSessionKeys.length,
@@ -2,7 +2,7 @@
2
2
  "id": "model-fetch",
3
3
  "name": "Model Fetch",
4
4
  "description": "Fetch and refresh configured provider model lists into OpenClaw config with independent per-provider filters.",
5
- "version": "0.2.8",
5
+ "version": "0.2.10",
6
6
  "configSchema": {
7
7
  "type": "object",
8
8
  "properties": {
@@ -65,9 +65,9 @@
65
65
  "navigation"
66
66
  ],
67
67
  "controlUi": {
68
- "entry": "dist/control-ui/b32b248d77fbc02925de3596562c26e19920fe4fabbae88d261043b7d0cc2625/index.js",
68
+ "entry": "dist/control-ui/da0bba63a04b1e6c889671add02041d1452ec068e8cc9ae624aba6a5c8429f40/index.js",
69
69
  "styles": [
70
- "dist/control-ui/b32b248d77fbc02925de3596562c26e19920fe4fabbae88d261043b7d0cc2625/index.css"
70
+ "dist/control-ui/da0bba63a04b1e6c889671add02041d1452ec068e8cc9ae624aba6a5c8429f40/index.css"
71
71
  ]
72
72
  },
73
73
  "contracts": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openclaw-plugin-model-fetch",
3
- "version": "0.2.8",
3
+ "version": "0.2.10",
4
4
  "description": "OpenClaw plugin tool that refreshes configured provider model lists into OpenClaw config with independent per-provider filters.",
5
5
  "license": "MIT",
6
6
  "repository": {