openclaw-plugin-model-fetch 0.2.0 → 0.2.2

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.
@@ -308,6 +308,138 @@ export function mergeModels({ existing, selected, filter, }) {
308
308
  selectedIds,
309
309
  };
310
310
  }
311
+ function readModelRefScalar(value, path, visit) {
312
+ if (typeof value !== "string")
313
+ return;
314
+ const ref = value.trim();
315
+ if (ref)
316
+ visit(ref, path);
317
+ }
318
+ /** Model settings accept either a bare `provider/model` string or `{ primary, fallbacks[] }`. */
319
+ function readModelRefSetting(value, path, visit) {
320
+ if (typeof value === "string") {
321
+ readModelRefScalar(value, path, visit);
322
+ return;
323
+ }
324
+ if (!isRecord(value))
325
+ return;
326
+ readModelRefScalar(value.primary, `${path}.primary`, visit);
327
+ if (!Array.isArray(value.fallbacks))
328
+ return;
329
+ value.fallbacks.forEach((fallback, index) => {
330
+ readModelRefScalar(fallback, `${path}.fallbacks[${index}]`, visit);
331
+ });
332
+ }
333
+ /**
334
+ * Walks the explicit model references that live outside the agent allowlist and
335
+ * agent `models` sync: utility/decision models, media, voice, pdf, embedded agent
336
+ * cyber failover, and hook models. Deleting a model named here would leave a
337
+ * dangling `provider/model` reference behind.
338
+ */
339
+ function forEachExplicitModelReference(config, visit) {
340
+ if (!isRecord(config))
341
+ return;
342
+ const agents = isRecord(config.agents) ? config.agents : undefined;
343
+ const defaults = agents && isRecord(agents.defaults) ? agents.defaults : undefined;
344
+ if (defaults) {
345
+ readModelRefScalar(defaults.utilityModel, "agents.defaults.utilityModel", visit);
346
+ readModelRefScalar(defaults.decisionModel, "agents.defaults.decisionModel", visit);
347
+ readModelRefSetting(defaults.imageModel, "agents.defaults.imageModel", visit);
348
+ readModelRefSetting(defaults.voiceModel, "agents.defaults.voiceModel", visit);
349
+ readModelRefSetting(defaults.pdfModel, "agents.defaults.pdfModel", visit);
350
+ if (isRecord(defaults.mediaModels)) {
351
+ readModelRefSetting(defaults.mediaModels.image, "agents.defaults.mediaModels.image", visit);
352
+ readModelRefSetting(defaults.mediaModels.video, "agents.defaults.mediaModels.video", visit);
353
+ readModelRefSetting(defaults.mediaModels.music, "agents.defaults.mediaModels.music", visit);
354
+ }
355
+ const embeddedAgent = isRecord(defaults.embeddedAgent) ? defaults.embeddedAgent : undefined;
356
+ if (embeddedAgent && isRecord(embeddedAgent.cyberFailover)) {
357
+ readModelRefScalar(embeddedAgent.cyberFailover.model, "agents.defaults.embeddedAgent.cyberFailover.model", visit);
358
+ }
359
+ }
360
+ const entries = agents && isRecord(agents.entries) ? agents.entries : undefined;
361
+ if (entries) {
362
+ for (const agentId of Object.keys(entries).sort((left, right) => left.localeCompare(right))) {
363
+ if (agentId.includes("."))
364
+ continue;
365
+ const entry = entries[agentId];
366
+ if (!isRecord(entry))
367
+ continue;
368
+ readModelRefScalar(entry.utilityModel, `agents.entries.${agentId}.utilityModel`, visit);
369
+ readModelRefScalar(entry.decisionModel, `agents.entries.${agentId}.decisionModel`, visit);
370
+ }
371
+ }
372
+ const hooks = isRecord(config.hooks) ? config.hooks : undefined;
373
+ if (hooks) {
374
+ if (isRecord(hooks.gmail)) {
375
+ readModelRefScalar(hooks.gmail.model, "hooks.gmail.model", visit);
376
+ }
377
+ if (Array.isArray(hooks.mappings)) {
378
+ hooks.mappings.forEach((mapping, index) => {
379
+ if (!isRecord(mapping))
380
+ return;
381
+ readModelRefScalar(mapping.model, `hooks.mappings[${index}].model`, visit);
382
+ });
383
+ }
384
+ }
385
+ }
386
+ /**
387
+ * Reports which of `modelIds` are still named by a non-agent model consumer,
388
+ * together with the config paths that reference them.
389
+ */
390
+ export function collectModelReferenceUsages(config, providerId, modelIds) {
391
+ const targets = new Map();
392
+ for (const modelId of modelIds) {
393
+ const trimmed = modelId.trim();
394
+ if (!trimmed)
395
+ continue;
396
+ const ref = toModelRef(providerId, trimmed);
397
+ if (!targets.has(ref))
398
+ targets.set(ref, { modelId: trimmed, ref, references: [] });
399
+ }
400
+ if (targets.size === 0)
401
+ return [];
402
+ forEachExplicitModelReference(config, (ref, path) => {
403
+ const usage = targets.get(ref);
404
+ if (!usage)
405
+ return;
406
+ if (!usage.references.includes(path))
407
+ usage.references.push(path);
408
+ });
409
+ const usages = [...targets.values()].filter((usage) => usage.references.length > 0);
410
+ for (const usage of usages) {
411
+ usage.references.sort((left, right) => left.localeCompare(right));
412
+ }
413
+ return usages.sort((left, right) => left.modelId.localeCompare(right.modelId));
414
+ }
415
+ /**
416
+ * Keeps referenced models in the replacement list instead of deleting them, and
417
+ * returns the reference paths so the deletion plan can show what was protected.
418
+ */
419
+ export function applyModelReferenceProtection({ existing, merged, providerId, config, }) {
420
+ const mergedIds = new Set(merged.map((model) => model.id));
421
+ const pendingIds = [];
422
+ const seen = new Set();
423
+ for (const model of existing) {
424
+ if (mergedIds.has(model.id) || seen.has(model.id))
425
+ continue;
426
+ seen.add(model.id);
427
+ pendingIds.push(model.id);
428
+ }
429
+ const protectedModels = collectModelReferenceUsages(config, providerId, pendingIds);
430
+ if (protectedModels.length === 0)
431
+ return { models: [...merged], protectedModels };
432
+ const protectedIds = new Set(protectedModels.map((entry) => entry.modelId));
433
+ const models = [...merged];
434
+ const restored = new Set();
435
+ for (const model of existing) {
436
+ if (!protectedIds.has(model.id) || restored.has(model.id))
437
+ continue;
438
+ restored.add(model.id);
439
+ models.push(model);
440
+ }
441
+ return { models, protectedModels };
442
+ }
311
443
  function normalizeBaseUrl(baseUrl) {
312
444
  return baseUrl.trim().replace(/\/+$/, "");
313
445
  }
@@ -466,11 +598,18 @@ export async function runModelFetch({ api, toolContext, factoryConfig, fetchMode
466
598
  signal,
467
599
  });
468
600
  const selected = selectFetchedModels(fetched, effectiveFilter);
601
+ const existing = provider.models ?? [];
469
602
  const merge = mergeModels({
470
- existing: provider.models ?? [],
603
+ existing,
471
604
  selected,
472
605
  filter: effectiveFilter,
473
606
  });
607
+ const protection = applyModelReferenceProtection({
608
+ existing,
609
+ merged: merge.models,
610
+ providerId,
611
+ config,
612
+ });
474
613
  let persisted = false;
475
614
  let configPath = CONFIG_PATH;
476
615
  if (!params.dryRun) {
@@ -483,13 +622,13 @@ export async function runModelFetch({ api, toolContext, factoryConfig, fetchMode
483
622
  cfg.models ??= {};
484
623
  cfg.models.providers ??= {};
485
624
  const target = cfg.models.providers[providerId] ?? { ...provider };
486
- target.models = merge.models;
625
+ target.models = protection.models;
487
626
  cfg.models.providers[providerId] = target;
488
627
  const targetAgents = resolveProviderTargetAgents(providerId, cfg, factoryConfig);
489
- const syncResult = syncConfiguredModelPolicyAllow(cfg, providerId, merge.models, {
628
+ const syncResult = syncConfiguredModelPolicyAllow(cfg, providerId, protection.models, {
490
629
  targetAgents,
491
630
  });
492
- syncAgentModelEntries(cfg, providerId, merge.models, {
631
+ syncAgentModelEntries(cfg, providerId, protection.models, {
493
632
  targetAgents: syncResult.syncedAgents,
494
633
  });
495
634
  },
@@ -501,9 +640,10 @@ export async function runModelFetch({ api, toolContext, factoryConfig, fetchMode
501
640
  provider: providerId,
502
641
  fetched: fetched.length,
503
642
  selected: merge.selectedIds,
643
+ protectedModels: protection.protectedModels,
504
644
  added: merge.added,
505
645
  unchanged: merge.unchanged,
506
- removed: merge.removed,
646
+ removed: Math.max(0, merge.removed - protection.protectedModels.length),
507
647
  replace: effectiveFilter.replace === true,
508
648
  dryRun: params.dryRun === true,
509
649
  configPath,
@@ -17,6 +17,11 @@ export declare function createModelFetchOperations({ api, factoryConfig, fetchMo
17
17
  provider: string;
18
18
  fetched: number;
19
19
  selected: string[];
20
+ protectedModels: {
21
+ modelId: string;
22
+ ref: string;
23
+ references: string[];
24
+ }[];
20
25
  added: number;
21
26
  unchanged: number;
22
27
  removed: number;
@@ -1,7 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { Value } from "typebox/value";
3
3
  import { modelFetchContract } from "./contract.js";
4
- import { fetchProviderModels, getProvider, mergeModels, resolveApiKey, resolveProviderFilter, resolveProviderTargetAgents, runModelFetch, selectFetchedModels, syncAgentModelEntries, syncConfiguredModelPolicyAllow, } from "./model-fetch.js";
4
+ import { applyModelReferenceProtection, collectModelReferenceUsages, fetchProviderModels, getProvider, mergeModels, resolveApiKey, resolveProviderFilter, resolveProviderTargetAgents, runModelFetch, selectFetchedModels, syncAgentModelEntries, syncConfiguredModelPolicyAllow, } from "./model-fetch.js";
5
5
  function isRecord(value) {
6
6
  return typeof value === "object" && value !== null && !Array.isArray(value);
7
7
  }
@@ -48,6 +48,10 @@ function planFingerprint(input) {
48
48
  selected: input.selectedIds,
49
49
  added: input.addedIds,
50
50
  removed: input.removedIds,
51
+ protected: input.protectedModels.map((entry) => ({
52
+ modelId: entry.modelId,
53
+ references: entry.references,
54
+ })),
51
55
  }))
52
56
  .digest("hex");
53
57
  }
@@ -88,6 +92,19 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
88
92
  function savedTargetAgents(providerId, config = currentConfig()) {
89
93
  return normalizeTargetAgents(resolveProviderTargetAgents(providerId, config, factoryConfig));
90
94
  }
95
+ /**
96
+ * Models kept only because of a reference are absent from `removedIds`, so the
97
+ * protection set has to be recomputed over removals plus protected models.
98
+ * Called against the write draft, this also catches references that appeared
99
+ * after the user confirmed the preview.
100
+ */
101
+ function referenceProtectionDrift(config, providerId, computed) {
102
+ const current = collectModelReferenceUsages(config, providerId, [
103
+ ...computed.removedIds,
104
+ ...computed.protectedModels.map((entry) => entry.modelId),
105
+ ]);
106
+ return JSON.stringify(current) !== JSON.stringify(computed.protectedModels);
107
+ }
91
108
  async function fetchModelsForProvider(providerId) {
92
109
  const config = currentConfig();
93
110
  const provider = getProvider(config, providerId);
@@ -105,14 +122,20 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
105
122
  };
106
123
  }
107
124
  async function computePlan(providerId) {
108
- const { provider, fetched, fetchedAt } = await fetchModelsForProvider(providerId);
125
+ const { provider, fetched, fetchedAt, config } = await fetchModelsForProvider(providerId);
109
126
  const filter = savedFilter(providerId);
110
127
  selectFetchedModels(fetched, filter);
111
128
  const existing = provider.models ?? [];
112
129
  const selected = selectFetchedModels(fetched, filter);
113
130
  const merge = mergeModels({ existing, selected, filter });
131
+ const protection = applyModelReferenceProtection({
132
+ existing,
133
+ merged: merge.models,
134
+ providerId,
135
+ config,
136
+ });
114
137
  const existingIds = existing.map((model) => model.id);
115
- const finalIds = new Set(merge.models.map((model) => model.id));
138
+ const finalIds = new Set(protection.models.map((model) => model.id));
116
139
  const existingSet = new Set(existingIds);
117
140
  const removedIds = existingIds.filter((id) => !finalIds.has(id));
118
141
  const addedIds = merge.models
@@ -121,8 +144,10 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
121
144
  const models = fetched.map(toModelView);
122
145
  const visibleIds = new Set(models.map((model) => model.id));
123
146
  const manualIds = new Set(filter.manualIds ?? []);
147
+ const protectedIds = new Set(protection.protectedModels.map((entry) => entry.modelId));
124
148
  for (const model of existing) {
125
- if (manualIds.has(model.id) && !visibleIds.has(model.id)) {
149
+ const keepVisible = manualIds.has(model.id) || protectedIds.has(model.id);
150
+ if (keepVisible && !visibleIds.has(model.id)) {
126
151
  models.push(toModelView(model));
127
152
  visibleIds.add(model.id);
128
153
  }
@@ -135,6 +160,7 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
135
160
  selectedIds: merge.selectedIds,
136
161
  addedIds,
137
162
  removedIds,
163
+ protectedModels: protection.protectedModels,
138
164
  });
139
165
  return {
140
166
  providerId,
@@ -147,9 +173,10 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
147
173
  removedIds,
148
174
  selectedIds: merge.selectedIds,
149
175
  unchangedCount: merge.unchanged,
176
+ protectedModels: protection.protectedModels,
150
177
  models,
151
178
  fingerprint,
152
- finalModels: merge.models,
179
+ finalModels: protection.models,
153
180
  };
154
181
  }
155
182
  async function listProviders() {
@@ -224,6 +251,7 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
224
251
  fetchedCount: computed.fetched.length,
225
252
  addedIds: computed.addedIds,
226
253
  removedIds: computed.removedIds,
254
+ protectedModels: computed.protectedModels,
227
255
  selectedIds: computed.selectedIds,
228
256
  unchangedCount: computed.unchangedCount,
229
257
  };
@@ -257,6 +285,9 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
257
285
  if (JSON.stringify(currentFilter) !== JSON.stringify(computed.filter)) {
258
286
  throw new Error("Provider 筛选策略在确认后发生变化,已取消写入。请重新预览。");
259
287
  }
288
+ if (referenceProtectionDrift(config, provider, computed)) {
289
+ throw new Error("模型引用在确认后发生变化,已取消写入。请重新预览。");
290
+ }
260
291
  target.models = computed.finalModels;
261
292
  ensurePluginEntry(config, provider, computed.filter, nextTargetAgents);
262
293
  const syncResult = syncConfiguredModelPolicyAllow(config, provider, computed.finalModels, {
@@ -278,6 +309,7 @@ export function createModelFetchOperations({ api, factoryConfig, fetchModels = f
278
309
  unchanged: computed.unchangedCount,
279
310
  removed: computed.removedIds.length,
280
311
  selectedIds: computed.selectedIds,
312
+ protectedModels: computed.protectedModels,
281
313
  targetAgents: nextTargetAgents,
282
314
  syncedAgents,
283
315
  models: computed.models,
package/dist/schemas.d.ts CHANGED
@@ -27,10 +27,25 @@ export declare const modelFetchParameters: Type.TObject<{
27
27
  dryRun: Type.TOptional<Type.TBoolean>;
28
28
  }>;
29
29
  export type ModelFetchParams = Static<typeof modelFetchParameters>;
30
+ /**
31
+ * A model kept in the provider list because a non-agent config consumer still
32
+ * references it, with the config paths that pinned it.
33
+ */
34
+ export declare const protectedModelSchema: Type.TObject<{
35
+ modelId: Type.TString;
36
+ ref: Type.TString;
37
+ references: Type.TArray<Type.TString>;
38
+ }>;
39
+ export type ProtectedModel = Static<typeof protectedModelSchema>;
30
40
  export declare const modelFetchResultSchema: Type.TObject<{
31
41
  provider: Type.TString;
32
42
  fetched: Type.TInteger;
33
43
  selected: Type.TArray<Type.TString>;
44
+ protectedModels: Type.TArray<Type.TObject<{
45
+ modelId: Type.TString;
46
+ ref: Type.TString;
47
+ references: Type.TArray<Type.TString>;
48
+ }>>;
34
49
  added: Type.TInteger;
35
50
  unchanged: Type.TInteger;
36
51
  removed: Type.TInteger;
@@ -141,6 +156,11 @@ export declare const applyPlanSchema: Type.TObject<{
141
156
  fetchedCount: Type.TInteger;
142
157
  addedIds: Type.TArray<Type.TString>;
143
158
  removedIds: Type.TArray<Type.TString>;
159
+ protectedModels: Type.TArray<Type.TObject<{
160
+ modelId: Type.TString;
161
+ ref: Type.TString;
162
+ references: Type.TArray<Type.TString>;
163
+ }>>;
144
164
  selectedIds: Type.TArray<Type.TString>;
145
165
  unchangedCount: Type.TInteger;
146
166
  }>;
@@ -153,6 +173,11 @@ export declare const previewApplyOutputSchema: Type.TObject<{
153
173
  fetchedCount: Type.TInteger;
154
174
  addedIds: Type.TArray<Type.TString>;
155
175
  removedIds: Type.TArray<Type.TString>;
176
+ protectedModels: Type.TArray<Type.TObject<{
177
+ modelId: Type.TString;
178
+ ref: Type.TString;
179
+ references: Type.TArray<Type.TString>;
180
+ }>>;
156
181
  selectedIds: Type.TArray<Type.TString>;
157
182
  unchangedCount: Type.TInteger;
158
183
  }>;
@@ -180,6 +205,11 @@ export declare const applyStrategyOutputSchema: Type.TObject<{
180
205
  unchanged: Type.TInteger;
181
206
  removed: Type.TInteger;
182
207
  selectedIds: Type.TArray<Type.TString>;
208
+ protectedModels: Type.TArray<Type.TObject<{
209
+ modelId: Type.TString;
210
+ ref: Type.TString;
211
+ references: Type.TArray<Type.TString>;
212
+ }>>;
183
213
  targetAgents: Type.TArray<Type.TString>;
184
214
  syncedAgents: Type.TArray<Type.TString>;
185
215
  models: Type.TArray<Type.TObject<{
package/dist/schemas.js CHANGED
@@ -48,10 +48,20 @@ export const modelFetchParameters = Type.Object({
48
48
  description: "Compute and return the planned model list without writing configuration.",
49
49
  })),
50
50
  }, { additionalProperties: false });
51
+ /**
52
+ * A model kept in the provider list because a non-agent config consumer still
53
+ * references it, with the config paths that pinned it.
54
+ */
55
+ export const protectedModelSchema = Type.Object({
56
+ modelId: Type.String({ minLength: 1, maxLength: 512 }),
57
+ ref: Type.String({ minLength: 1, maxLength: 1_024 }),
58
+ references: Type.Array(Type.String({ maxLength: 1_024 }), { maxItems: 256 }),
59
+ }, { additionalProperties: false });
51
60
  export const modelFetchResultSchema = Type.Object({
52
61
  provider: providerIdSchema,
53
62
  fetched: Type.Integer({ minimum: 0 }),
54
63
  selected: Type.Array(Type.String({ maxLength: 512 }), { maxItems: 1_000 }),
64
+ protectedModels: Type.Array(protectedModelSchema, { maxItems: 2_000 }),
55
65
  added: Type.Integer({ minimum: 0 }),
56
66
  unchanged: Type.Integer({ minimum: 0 }),
57
67
  removed: Type.Integer({ minimum: 0 }),
@@ -117,6 +127,7 @@ export const applyPlanSchema = Type.Object({
117
127
  fetchedCount: Type.Integer({ minimum: 0 }),
118
128
  addedIds: Type.Array(Type.String({ maxLength: 512 }), { maxItems: 2_000 }),
119
129
  removedIds: Type.Array(Type.String({ maxLength: 512 }), { maxItems: 2_000 }),
130
+ protectedModels: Type.Array(protectedModelSchema, { maxItems: 2_000 }),
120
131
  selectedIds: Type.Array(Type.String({ maxLength: 512 }), { maxItems: 2_000 }),
121
132
  unchangedCount: Type.Integer({ minimum: 0 }),
122
133
  }, { additionalProperties: false });
@@ -144,6 +155,7 @@ export const applyStrategyOutputSchema = Type.Object({
144
155
  unchanged: Type.Integer({ minimum: 0 }),
145
156
  removed: Type.Integer({ minimum: 0 }),
146
157
  selectedIds: Type.Array(Type.String({ maxLength: 512 }), { maxItems: 2_000 }),
158
+ protectedModels: Type.Array(protectedModelSchema, { maxItems: 2_000 }),
147
159
  targetAgents: Type.Array(Type.String({ minLength: 1, maxLength: 128 }), {
148
160
  maxItems: 256,
149
161
  uniqueItems: true,
@@ -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.0",
5
+ "version": "0.2.2",
6
6
  "configSchema": {
7
7
  "type": "object",
8
8
  "properties": {
@@ -61,9 +61,9 @@
61
61
  "onStartup": true
62
62
  },
63
63
  "controlUi": {
64
- "entry": "dist/control-ui/e7b2a8a372a676495b78ec52dbe12cb5154970f64d64c776a96aec3116b20a23/index.js",
64
+ "entry": "dist/control-ui/564d9a090ebaa5338954b64f9d9da0d1a37954ca0d8c72f5a4c92fc016ccb38e/index.js",
65
65
  "styles": [
66
- "dist/control-ui/e7b2a8a372a676495b78ec52dbe12cb5154970f64d64c776a96aec3116b20a23/index.css"
66
+ "dist/control-ui/564d9a090ebaa5338954b64f9d9da0d1a37954ca0d8c72f5a4c92fc016ccb38e/index.css"
67
67
  ]
68
68
  },
69
69
  "contracts": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openclaw-plugin-model-fetch",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
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": {
@@ -25,7 +25,8 @@
25
25
  "files": [
26
26
  "dist",
27
27
  "openclaw.plugin.json",
28
- "README.md"
28
+ "README.md",
29
+ "README-CN.md"
29
30
  ],
30
31
  "type": "module",
31
32
  "scripts": {