openclaw-plugin-model-fetch 0.2.10 → 0.2.11

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,9 +1,7 @@
1
1
  import { fetchWithSsrFGuard, ssrfPolicyFromAllowPrivateNetwork, } from "openclaw/plugin-sdk/ssrf-runtime";
2
2
  import { readResponseWithLimit } from "openclaw/plugin-sdk/media-runtime";
3
- import { jsonResult } from "openclaw/plugin-sdk/tool-results";
4
3
  import { modelFetchConfigSchema, modelFetchFilterSchema, modelFetchParameters, modelFetchResultSchema, } from "./schemas.js";
5
4
  export const MODEL_FETCH_TOOL_NAME = "model_fetch";
6
- const CONFIG_PATH = "models.providers.<providerId>.models";
7
5
  const RESPONSE_LIMIT_BYTES = 2 * 1024 * 1024;
8
6
  const REQUEST_TIMEOUT_MS = 30_000;
9
7
  const MAX_MODEL_PAGES = 100;
@@ -379,26 +377,80 @@ export function mergeModels({ existing, selected, filter, }) {
379
377
  function asOptionalRecord(value) {
380
378
  return isRecord(value) ? value : undefined;
381
379
  }
382
- function readModelRefScalar(value, path, visit) {
383
- if (typeof value !== "string")
380
+ function visitModelRefScalar(container, field, path, visit) {
381
+ if (!isRecord(container))
384
382
  return;
385
- const ref = value.trim();
386
- if (ref)
387
- visit(ref, path);
383
+ const referencePath = `${path}.${field}`;
384
+ visit({
385
+ path: referencePath,
386
+ read: () => {
387
+ const value = container[field];
388
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
389
+ },
390
+ write: (target) => {
391
+ if (typeof container[field] !== "string")
392
+ return false;
393
+ container[field] = target;
394
+ return true;
395
+ },
396
+ });
388
397
  }
389
398
  /** Model settings accept either a bare `provider/model` string or `{ primary, fallbacks[] }`. */
390
- function readModelRefSetting(value, path, visit) {
399
+ function visitModelRefSetting(container, field, basePath, visit) {
400
+ if (!isRecord(container))
401
+ return;
402
+ const value = container[field];
403
+ const path = `${basePath}.${field}`;
391
404
  if (typeof value === "string") {
392
- readModelRefScalar(value, path, visit);
405
+ visitModelRefScalar(container, field, basePath, visit);
393
406
  return;
394
407
  }
395
408
  if (!isRecord(value))
396
409
  return;
397
- readModelRefScalar(value.primary, `${path}.primary`, visit);
410
+ visitModelRefScalar(value, "primary", path, visit);
398
411
  if (!Array.isArray(value.fallbacks))
399
412
  return;
400
- value.fallbacks.forEach((fallback, index) => {
401
- readModelRefScalar(fallback, `${path}.fallbacks[${index}]`, visit);
413
+ const fallbacks = value.fallbacks;
414
+ fallbacks.forEach((fallback, index) => {
415
+ if (typeof fallback !== "string")
416
+ return;
417
+ visit({
418
+ path: `${path}.fallbacks[${index}]`,
419
+ read: () => {
420
+ const current = fallbacks[index];
421
+ return typeof current === "string" && current.trim() ? current.trim() : undefined;
422
+ },
423
+ write: (target) => {
424
+ if (typeof fallbacks[index] !== "string")
425
+ return false;
426
+ fallbacks[index] = target;
427
+ return true;
428
+ },
429
+ });
430
+ });
431
+ }
432
+ function visitProviderModelReference(container, path, visit) {
433
+ if (!isRecord(container))
434
+ return;
435
+ visit({
436
+ path,
437
+ read: () => {
438
+ const provider = typeof container.provider === "string" ? container.provider.trim() : "";
439
+ const model = typeof container.model === "string" ? container.model.trim() : "";
440
+ return provider && model ? `${provider}/${model}` : undefined;
441
+ },
442
+ write: (target) => {
443
+ const separator = target.indexOf("/");
444
+ if (separator <= 0 ||
445
+ separator === target.length - 1 ||
446
+ typeof container.provider !== "string" ||
447
+ typeof container.model !== "string") {
448
+ return false;
449
+ }
450
+ container.provider = target.slice(0, separator);
451
+ container.model = target.slice(separator + 1);
452
+ return true;
453
+ },
402
454
  });
403
455
  }
404
456
  /**
@@ -414,20 +466,14 @@ function forEachExplicitModelReference(config, visit) {
414
466
  if (tools) {
415
467
  const exec = asOptionalRecord(tools.exec);
416
468
  const reviewer = asOptionalRecord(exec?.reviewer);
417
- readModelRefSetting(reviewer?.model, "tools.exec.reviewer.model", visit);
469
+ visitModelRefSetting(reviewer, "model", "tools.exec.reviewer", visit);
418
470
  if (isRecord(tools.media)) {
419
471
  for (const capability of ["image", "audio", "video"]) {
420
- readModelRefScalar(asOptionalRecord(tools.media[capability])?.preferredModel, `tools.media.${capability}.preferredModel`, visit);
472
+ visitModelRefScalar(asOptionalRecord(tools.media[capability]), "preferredModel", `tools.media.${capability}`, visit);
421
473
  }
422
474
  if (Array.isArray(tools.media.models)) {
423
475
  tools.media.models.forEach((entry, index) => {
424
- if (!isRecord(entry))
425
- return;
426
- const provider = typeof entry.provider === "string" ? entry.provider.trim() : "";
427
- const model = typeof entry.model === "string" ? entry.model.trim() : "";
428
- if (provider && model) {
429
- visit(`${provider}/${model}`, `tools.media.models[${index}].model`);
430
- }
476
+ visitProviderModelReference(entry, `tools.media.models[${index}].model`, visit);
431
477
  });
432
478
  }
433
479
  }
@@ -453,18 +499,18 @@ function forEachExplicitModelReference(config, visit) {
453
499
  }
454
500
  const tts = asOptionalRecord(config.tts);
455
501
  if (tts) {
456
- readModelRefSetting(tts.summaryModel, "tts.summaryModel", visit);
502
+ visitModelRefSetting(tts, "summaryModel", "tts", visit);
457
503
  }
458
504
  const hooks = isRecord(config.hooks) ? config.hooks : undefined;
459
505
  if (hooks) {
460
506
  if (isRecord(hooks.gmail)) {
461
- readModelRefScalar(hooks.gmail.model, "hooks.gmail.model", visit);
507
+ visitModelRefScalar(hooks.gmail, "model", "hooks.gmail", visit);
462
508
  }
463
509
  if (Array.isArray(hooks.mappings)) {
464
510
  hooks.mappings.forEach((mapping, index) => {
465
511
  if (!isRecord(mapping))
466
512
  return;
467
- readModelRefScalar(mapping.model, `hooks.mappings[${index}].model`, visit);
513
+ visitModelRefScalar(mapping, "model", `hooks.mappings[${index}]`, visit);
468
514
  });
469
515
  }
470
516
  }
@@ -477,7 +523,7 @@ function forEachExplicitModelReference(config, visit) {
477
523
  if (!isRecord(channelMap))
478
524
  continue;
479
525
  for (const targetId of Object.keys(channelMap).sort((left, right) => left.localeCompare(right))) {
480
- readModelRefSetting(channelMap[targetId], `channels.modelByChannel.${channelId}.${targetId}`, visit);
526
+ visitModelRefSetting(channelMap, targetId, `channels.modelByChannel.${channelId}`, visit);
481
527
  }
482
528
  }
483
529
  }
@@ -492,13 +538,7 @@ function forEachExplicitModelReference(config, visit) {
492
538
  }
493
539
  }
494
540
  }
495
- /**
496
- * Rewrites the explicit model references that name `fromRef` to `toRef`.
497
- *
498
- * The reference collector only reads, so the walk is repeated here with a
499
- * writable setter. `forEachExplicitModelReference` reports the exact path of
500
- * every reference it finds, so the setter mirrors that path shape.
501
- */
541
+ /** Rewrites references discovered by the shared read/write walker. */
502
542
  export function rewriteModelReferences(draft, fromRef, toRef) {
503
543
  if (!isRecord(draft))
504
544
  return { changed: false, paths: [] };
@@ -507,173 +547,14 @@ export function rewriteModelReferences(draft, fromRef, toRef) {
507
547
  if (!source || !target || source === target)
508
548
  return { changed: false, paths: [] };
509
549
  const changed = [];
510
- const writeScalar = (container, field, basePath) => {
511
- if (!isRecord(container))
512
- return;
513
- const current = container[field];
514
- if (typeof current !== "string" || current.trim() !== source)
515
- return;
516
- container[field] = target;
517
- changed.push(`${basePath}.${field}`);
518
- };
519
- const writeSetting = (container, field, basePath) => {
520
- if (!isRecord(container))
521
- return;
522
- const current = container[field];
523
- if (typeof current === "string") {
524
- if (current.trim() !== source)
525
- return;
526
- container[field] = target;
527
- changed.push(`${basePath}.${field}`);
528
- return;
529
- }
530
- if (!isRecord(current))
531
- return;
532
- if (typeof current.primary === "string" && current.primary.trim() === source) {
533
- current.primary = target;
534
- changed.push(`${basePath}.${field}.primary`);
535
- }
536
- const fallbacks = current.fallbacks;
537
- if (!Array.isArray(fallbacks))
550
+ forEachExplicitModelReference(draft, (reference) => {
551
+ if (reference.read() !== source)
538
552
  return;
539
- fallbacks.forEach((fallback, index) => {
540
- if (typeof fallback !== "string" || fallback.trim() !== source)
541
- return;
542
- fallbacks[index] = target;
543
- changed.push(`${basePath}.${field}.fallbacks[${index}]`);
544
- });
545
- };
546
- const writeProviderModel = (container, basePath) => {
547
- if (!isRecord(container))
548
- return;
549
- const provider = typeof container.provider === "string" ? container.provider.trim() : "";
550
- const model = typeof container.model === "string" ? container.model.trim() : "";
551
- if (!provider || !model || `${provider}/${model}` !== source)
552
- return;
553
- const separator = target.indexOf("/");
554
- if (separator <= 0 || separator === target.length - 1)
555
- return;
556
- container.provider = target.slice(0, separator);
557
- container.model = target.slice(separator + 1);
558
- changed.push(`${basePath}.model`);
559
- };
560
- const tools = isRecord(draft.tools) ? draft.tools : undefined;
561
- if (tools) {
562
- const exec = asOptionalRecord(tools.exec);
563
- const reviewer = asOptionalRecord(exec?.reviewer);
564
- if (isRecord(reviewer))
565
- writeSetting(reviewer, "model", "tools.exec.reviewer");
566
- if (isRecord(tools.media)) {
567
- for (const capability of ["image", "audio", "video"]) {
568
- const media = asOptionalRecord(tools.media[capability]);
569
- if (!media)
570
- continue;
571
- writeScalar(media, "preferredModel", `tools.media.${capability}`);
572
- }
573
- if (Array.isArray(tools.media.models)) {
574
- tools.media.models.forEach((entry, index) => {
575
- if (!isRecord(entry))
576
- return;
577
- writeProviderModel(entry, `tools.media.models[${index}]`);
578
- });
579
- }
580
- }
581
- }
582
- const agents = isRecord(draft.agents) ? draft.agents : undefined;
583
- const defaults = asOptionalRecord(agents?.defaults);
584
- if (defaults)
585
- rewriteAgentModelReferences(defaults, "agents.defaults", false, writeScalar, writeSetting);
586
- if (agents && isRecord(agents.entries)) {
587
- for (const agentId of Object.keys(agents.entries).sort((left, right) => left.localeCompare(right))) {
588
- const entry = agents.entries[agentId];
589
- if (!isRecord(entry))
590
- continue;
591
- rewriteAgentModelReferences(entry, `agents.entries.${agentId}`, true, writeScalar, writeSetting);
592
- }
593
- }
594
- else if (agents && Array.isArray(agents.list)) {
595
- agents.list.forEach((entry, index) => {
596
- if (!isRecord(entry))
597
- return;
598
- rewriteAgentModelReferences(entry, `agents.list[${index}]`, true, writeScalar, writeSetting);
599
- });
600
- }
601
- const tts = asOptionalRecord(draft.tts);
602
- if (tts)
603
- writeSetting(tts, "summaryModel", "tts");
604
- const hooks = isRecord(draft.hooks) ? draft.hooks : undefined;
605
- if (hooks) {
606
- if (isRecord(hooks.gmail))
607
- writeScalar(hooks.gmail, "model", "hooks.gmail");
608
- if (Array.isArray(hooks.mappings)) {
609
- hooks.mappings.forEach((mapping, index) => {
610
- if (!isRecord(mapping))
611
- return;
612
- writeScalar(mapping, "model", `hooks.mappings[${index}]`);
613
- });
614
- }
615
- }
616
- const channels = isRecord(draft.channels) ? draft.channels : undefined;
617
- if (channels) {
618
- const modelByChannel = isRecord(channels.modelByChannel) ? channels.modelByChannel : undefined;
619
- if (modelByChannel) {
620
- for (const channelId of Object.keys(modelByChannel).sort((left, right) => left.localeCompare(right))) {
621
- const channelMap = modelByChannel[channelId];
622
- if (!isRecord(channelMap))
623
- continue;
624
- for (const targetId of Object.keys(channelMap).sort((left, right) => left.localeCompare(right))) {
625
- writeSetting(channelMap, targetId, `channels.modelByChannel.${channelId}`);
626
- }
627
- }
628
- }
629
- const discord = asOptionalRecord(channels.discord);
630
- if (discord) {
631
- rewriteDiscordVoiceModelReferences(discord.voice, "channels.discord.voice", writeScalar, writeSetting);
632
- if (isRecord(discord.accounts)) {
633
- for (const accountId of Object.keys(discord.accounts).sort((left, right) => left.localeCompare(right))) {
634
- rewriteDiscordVoiceModelReferences(asOptionalRecord(discord.accounts[accountId])?.voice, `channels.discord.accounts.${accountId}.voice`, writeScalar, writeSetting);
635
- }
636
- }
637
- }
638
- }
553
+ if (reference.write(target))
554
+ changed.push(reference.path);
555
+ });
639
556
  return { changed: changed.length > 0, paths: changed.sort((left, right) => left.localeCompare(right)) };
640
557
  }
641
- function rewriteAgentModelReferences(agent, basePath, includeEntrySelectors, writeScalar, writeSetting) {
642
- writeSetting(agent, "model", basePath);
643
- writeScalar(agent, "utilityModel", basePath);
644
- writeScalar(agent, "decisionModel", basePath);
645
- writeSetting(agent, "imageModel", basePath);
646
- writeSetting(agent, "voiceModel", basePath);
647
- writeSetting(agent, "pdfModel", basePath);
648
- const mediaModels = asOptionalRecord(agent.mediaModels);
649
- if (mediaModels) {
650
- for (const capability of ["image", "video", "music"]) {
651
- writeSetting(mediaModels, capability, `${basePath}.mediaModels`);
652
- }
653
- }
654
- const cyberFailover = asOptionalRecord(asOptionalRecord(agent.embeddedAgent)?.cyberFailover);
655
- if (cyberFailover)
656
- writeSetting(cyberFailover, "model", `${basePath}.embeddedAgent.cyberFailover`);
657
- writeSetting(asOptionalRecord(agent.heartbeat), "model", `${basePath}.heartbeat`);
658
- writeSetting(asOptionalRecord(agent.subagents), "model", `${basePath}.subagents`);
659
- const compaction = asOptionalRecord(agent.compaction);
660
- if (compaction) {
661
- writeSetting(compaction, "model", `${basePath}.compaction`);
662
- writeSetting(asOptionalRecord(compaction.memoryFlush), "model", `${basePath}.compaction.memoryFlush`);
663
- }
664
- if (!includeEntrySelectors)
665
- return;
666
- const exec = asOptionalRecord(asOptionalRecord(agent.tools)?.exec);
667
- writeSetting(asOptionalRecord(exec?.reviewer), "model", `${basePath}.tools.exec.reviewer`);
668
- writeSetting(asOptionalRecord(agent.tts), "summaryModel", `${basePath}.tts`);
669
- }
670
- function rewriteDiscordVoiceModelReferences(voice, basePath, writeScalar, writeSetting) {
671
- const voiceConfig = asOptionalRecord(voice);
672
- if (!voiceConfig)
673
- return;
674
- writeSetting(voiceConfig, "model", basePath);
675
- writeSetting(asOptionalRecord(voiceConfig.tts), "summaryModel", `${basePath}.tts`);
676
- }
677
558
  /**
678
559
  * Moves the config entries that OpenClaw keys by model reference from one
679
560
  * spelling to another.
@@ -797,41 +678,41 @@ export function migrateModelRefEntries(draft, pairs, options = {}) {
797
678
  };
798
679
  }
799
680
  function visitAgentModelReferences(path, agent, includeEntrySelectors, visit) {
800
- readModelRefSetting(agent.model, `${path}.model`, visit);
801
- readModelRefScalar(agent.utilityModel, `${path}.utilityModel`, visit);
802
- readModelRefScalar(agent.decisionModel, `${path}.decisionModel`, visit);
803
- readModelRefSetting(agent.imageModel, `${path}.imageModel`, visit);
804
- readModelRefSetting(agent.voiceModel, `${path}.voiceModel`, visit);
805
- readModelRefSetting(agent.pdfModel, `${path}.pdfModel`, visit);
681
+ visitModelRefSetting(agent, "model", path, visit);
682
+ visitModelRefScalar(agent, "utilityModel", path, visit);
683
+ visitModelRefScalar(agent, "decisionModel", path, visit);
684
+ visitModelRefSetting(agent, "imageModel", path, visit);
685
+ visitModelRefSetting(agent, "voiceModel", path, visit);
686
+ visitModelRefSetting(agent, "pdfModel", path, visit);
806
687
  const mediaModels = asOptionalRecord(agent.mediaModels);
807
688
  if (mediaModels) {
808
689
  for (const capability of ["image", "video", "music"]) {
809
- readModelRefSetting(mediaModels[capability], `${path}.mediaModels.${capability}`, visit);
690
+ visitModelRefSetting(mediaModels, capability, `${path}.mediaModels`, visit);
810
691
  }
811
692
  }
812
693
  const cyberFailover = asOptionalRecord(asOptionalRecord(agent.embeddedAgent)?.cyberFailover);
813
694
  if (cyberFailover) {
814
- readModelRefSetting(cyberFailover.model, `${path}.embeddedAgent.cyberFailover.model`, visit);
695
+ visitModelRefSetting(cyberFailover, "model", `${path}.embeddedAgent.cyberFailover`, visit);
815
696
  }
816
- readModelRefSetting(asOptionalRecord(agent.heartbeat)?.model, `${path}.heartbeat.model`, visit);
817
- readModelRefSetting(asOptionalRecord(agent.subagents)?.model, `${path}.subagents.model`, visit);
697
+ visitModelRefSetting(asOptionalRecord(agent.heartbeat), "model", `${path}.heartbeat`, visit);
698
+ visitModelRefSetting(asOptionalRecord(agent.subagents), "model", `${path}.subagents`, visit);
818
699
  const compaction = asOptionalRecord(agent.compaction);
819
700
  if (compaction) {
820
- readModelRefSetting(compaction.model, `${path}.compaction.model`, visit);
821
- readModelRefSetting(asOptionalRecord(compaction.memoryFlush)?.model, `${path}.compaction.memoryFlush.model`, visit);
701
+ visitModelRefSetting(compaction, "model", `${path}.compaction`, visit);
702
+ visitModelRefSetting(asOptionalRecord(compaction.memoryFlush), "model", `${path}.compaction.memoryFlush`, visit);
822
703
  }
823
704
  if (!includeEntrySelectors)
824
705
  return;
825
706
  const exec = asOptionalRecord(asOptionalRecord(agent.tools)?.exec);
826
- readModelRefSetting(asOptionalRecord(exec?.reviewer)?.model, `${path}.tools.exec.reviewer.model`, visit);
827
- readModelRefSetting(asOptionalRecord(agent.tts)?.summaryModel, `${path}.tts.summaryModel`, visit);
707
+ visitModelRefSetting(asOptionalRecord(exec?.reviewer), "model", `${path}.tools.exec.reviewer`, visit);
708
+ visitModelRefSetting(asOptionalRecord(agent.tts), "summaryModel", `${path}.tts`, visit);
828
709
  }
829
710
  function visitDiscordVoiceModelReferences(path, voice, visit) {
830
711
  const voiceConfig = asOptionalRecord(voice);
831
712
  if (!voiceConfig)
832
713
  return;
833
- readModelRefSetting(voiceConfig.model, `${path}.model`, visit);
834
- readModelRefSetting(asOptionalRecord(voiceConfig.tts)?.summaryModel, `${path}.tts.summaryModel`, visit);
714
+ visitModelRefSetting(voiceConfig, "model", path, visit);
715
+ visitModelRefSetting(asOptionalRecord(voiceConfig.tts), "summaryModel", `${path}.tts`, visit);
835
716
  }
836
717
  /**
837
718
  * Reports which of `modelIds` are still named by a non-agent model consumer,
@@ -849,13 +730,16 @@ export function collectModelReferenceUsages(config, providerId, modelIds) {
849
730
  }
850
731
  if (targets.size === 0)
851
732
  return [];
852
- forEachExplicitModelReference(config, (ref, path) => {
853
- const aliases = collectModelAliases(config, agentIdForReferencePath(config, path));
733
+ forEachExplicitModelReference(config, (reference) => {
734
+ const ref = reference.read();
735
+ if (!ref)
736
+ return;
737
+ const aliases = collectModelAliases(config, agentIdForReferencePath(config, reference.path));
854
738
  const usage = targets.get(ref) ?? targets.get(aliases.get(ref.toLowerCase()) ?? "");
855
739
  if (!usage)
856
740
  return;
857
- if (!usage.references.includes(path))
858
- usage.references.push(path);
741
+ if (!usage.references.includes(reference.path))
742
+ usage.references.push(reference.path);
859
743
  });
860
744
  const usages = [...targets.values()].filter((usage) => usage.references.length > 0);
861
745
  for (const usage of usages) {
@@ -1252,12 +1136,6 @@ export function getProvider(config, providerId) {
1252
1136
  }
1253
1137
  return provider;
1254
1138
  }
1255
- function currentConfig(api, toolContext) {
1256
- return (toolContext?.getRuntimeConfig?.() ??
1257
- toolContext?.runtimeConfig ??
1258
- toolContext?.config ??
1259
- api.runtime.config.current());
1260
- }
1261
1139
  export async function resolveApiKey(api, providerId, provider, config) {
1262
1140
  if (provider.api === "ollama")
1263
1141
  return undefined;
@@ -1268,100 +1146,3 @@ export async function resolveApiKey(api, providerId, provider, config) {
1268
1146
  const auth = await resolver({ provider: providerId, cfg: config });
1269
1147
  return auth.apiKey;
1270
1148
  }
1271
- export async function runModelFetch({ api, toolContext, factoryConfig, fetchModels = fetchProviderModels, params, signal, }) {
1272
- const providerId = params.provider.trim();
1273
- if (!providerId)
1274
- throw new Error("Provider id is required.");
1275
- const config = currentConfig(api, toolContext);
1276
- const provider = getProvider(config, providerId);
1277
- const persistedFilter = resolveProviderFilter(providerId, config, factoryConfig);
1278
- const effectiveFilter = resolveEffectiveFilter(persistedFilter, params);
1279
- const apiKey = await resolveApiKey(api, providerId, provider, config);
1280
- const fetched = await fetchModels({
1281
- providerId,
1282
- provider,
1283
- apiKey,
1284
- signal,
1285
- });
1286
- const selected = selectFetchedModels(fetched, effectiveFilter);
1287
- const existing = provider.models ?? [];
1288
- const merge = mergeModels({
1289
- existing,
1290
- selected,
1291
- filter: effectiveFilter,
1292
- });
1293
- let protection = applyModelReferenceProtection({
1294
- existing,
1295
- merged: merge.models,
1296
- providerId,
1297
- config,
1298
- });
1299
- let persisted = false;
1300
- let configPath = CONFIG_PATH;
1301
- let removed = Math.max(0, merge.removed - protection.protectedModels.length);
1302
- if (!params.dryRun) {
1303
- const runtime = api.runtime;
1304
- const result = await runtime.config.mutateConfigFile({
1305
- base: "source",
1306
- afterWrite: { mode: "auto" },
1307
- mutate: (draft) => {
1308
- const cfg = draft;
1309
- cfg.models ??= {};
1310
- cfg.models.providers ??= {};
1311
- const target = cfg.models.providers[providerId] ?? { ...provider };
1312
- const latestExisting = target.models ?? [];
1313
- protection = applyModelReferenceProtection({
1314
- existing: latestExisting,
1315
- merged: merge.models,
1316
- providerId,
1317
- config: cfg,
1318
- });
1319
- const finalIds = new Set(protection.models.map((model) => model.id));
1320
- removed = latestExisting.filter((model) => !finalIds.has(model.id)).length;
1321
- target.models = protection.models;
1322
- cfg.models.providers[providerId] = target;
1323
- const targetAgents = resolveProviderTargetAgents(providerId, cfg, factoryConfig);
1324
- const syncResult = syncConfiguredModelPolicyAllow(cfg, providerId, protection.models, {
1325
- targetAgents,
1326
- });
1327
- syncAgentModelEntries(cfg, providerId, protection.models, {
1328
- targetAgents: syncResult.syncedAgents,
1329
- });
1330
- },
1331
- });
1332
- configPath = result.path;
1333
- persisted = true;
1334
- }
1335
- return {
1336
- provider: providerId,
1337
- fetched: fetched.length,
1338
- selected: merge.selectedIds,
1339
- protectedModels: protection.protectedModels,
1340
- added: merge.added,
1341
- unchanged: merge.unchanged,
1342
- removed,
1343
- replace: effectiveFilter.replace === true,
1344
- dryRun: params.dryRun === true,
1345
- configPath,
1346
- persisted,
1347
- };
1348
- }
1349
- export function createModelFetchTool({ api, toolContext, factoryConfig, fetchModels = fetchProviderModels, }) {
1350
- return {
1351
- name: MODEL_FETCH_TOOL_NAME,
1352
- label: "Fetch Provider Models",
1353
- description: "Fetch a configured provider's model list, apply that provider's independent regex/manual selection strategy, and persist the selected models to OpenClaw config for WebUI use.",
1354
- parameters: modelFetchParameters,
1355
- resultContentSource: "network",
1356
- execute: async (_toolCallId, params, signal) => {
1357
- return jsonResult(await runModelFetch({
1358
- api,
1359
- toolContext,
1360
- factoryConfig,
1361
- fetchModels,
1362
- params,
1363
- signal,
1364
- }));
1365
- },
1366
- };
1367
- }
@@ -0,0 +1,29 @@
1
+ import type { OpenClawPluginApi } from "openclaw/plugin-sdk/core";
2
+ import type { CaseVariant, ProtectedModel } from "./schemas.js";
3
+ import { type ModelDefinitionLike, type ProviderLike } from "./model-fetch.js";
4
+ export type NormalizedRewrite = {
5
+ protectedModelId: string;
6
+ fromRef: string;
7
+ toRef: string;
8
+ };
9
+ export type ProviderModelReplacement = {
10
+ providerId: string;
11
+ provider: ProviderLike;
12
+ existingModels: readonly ModelDefinitionLike[];
13
+ mergedModels: readonly ModelDefinitionLike[];
14
+ rewrites?: readonly NormalizedRewrite[];
15
+ caseVariants?: readonly CaseVariant[];
16
+ targetAgents: readonly string[];
17
+ };
18
+ export type ProviderModelReplacementResult = {
19
+ finalModels: ModelDefinitionLike[];
20
+ removedIds: string[];
21
+ protectedModels: ProtectedModel[];
22
+ rewrittenReferences: string[];
23
+ syncedAgents: string[];
24
+ };
25
+ export declare function mutateConfigFileWithRetry(runtime: OpenClawPluginApi["runtime"], params: Parameters<OpenClawPluginApi["runtime"]["config"]["mutateConfigFile"]>[0]): Promise<Awaited<ReturnType<OpenClawPluginApi["runtime"]["config"]["mutateConfigFile"]>>>;
26
+ /** Compare authored source fields without mistaking runtime defaults for drift. */
27
+ export declare function sameProviderModels(sourceProvider: ProviderLike, sourceModels: readonly ModelDefinitionLike[], runtimeProvider: ProviderLike, runtimeModels: readonly ModelDefinitionLike[]): boolean;
28
+ /** Apply one replacement against the final source draft shared by tool and UI. */
29
+ export declare function replaceProviderModels(draft: unknown, replacement: ProviderModelReplacement): ProviderModelReplacementResult;