openclaw-plugin-model-fetch 0.2.7 → 0.2.9

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.
@@ -6,6 +6,7 @@ export const MODEL_FETCH_TOOL_NAME = "model_fetch";
6
6
  const CONFIG_PATH = "models.providers.<providerId>.models";
7
7
  const RESPONSE_LIMIT_BYTES = 2 * 1024 * 1024;
8
8
  const REQUEST_TIMEOUT_MS = 30_000;
9
+ const MAX_MODEL_PAGES = 100;
9
10
  export { modelFetchConfigSchema, modelFetchFilterSchema, modelFetchParameters, modelFetchResultSchema, };
10
11
  function toModelRef(providerId, modelId) {
11
12
  return `${providerId}/${modelId}`;
@@ -96,29 +97,23 @@ export function syncConfiguredModelPolicyAllow(draft, providerId, models, option
96
97
  cfg.agents.defaults.modelPolicy.allow = defaultsResult.next;
97
98
  defaultsUpdated = true;
98
99
  }
99
- const agentEntries = cfg.agents?.entries;
100
- if (!agentEntries) {
101
- return { defaultsUpdated, syncedAgents: [] };
102
- }
103
100
  const selectedAgents = normalizeAgentIds(options.targetAgents);
104
101
  const forcedAgentSet = selectedAgents.length > 0 ? new Set(selectedAgents) : null;
105
102
  const syncedAgents = [];
106
- for (const [agentId, entry] of Object.entries(agentEntries)) {
103
+ for (const { id: agentId, entry } of listConfiguredAgentEntries(cfg)) {
107
104
  if (!entry?.modelPolicy)
108
105
  continue;
109
106
  const normalized = normalizeAllowList(entry.modelPolicy.allow);
110
- const shouldSync = forcedAgentSet?.has(agentId) ?? hasProviderScopedRule(normalized, providerId);
107
+ const shouldSync = forcedAgentSet?.has(agentId) === true ||
108
+ hasProviderScopedRule(normalized, providerId);
111
109
  if (!shouldSync)
112
110
  continue;
113
111
  const result = reconcileModelRefs(entry.modelPolicy.allow, providerId, modelRefs);
114
112
  const selectedWithAllowlist = forcedAgentSet?.has(agentId) === true && normalized.length > 0;
115
113
  if (result.changed) {
116
- agentEntries[agentId] = {
117
- ...entry,
118
- modelPolicy: {
119
- ...entry.modelPolicy,
120
- allow: result.next,
121
- },
114
+ entry.modelPolicy = {
115
+ ...entry.modelPolicy,
116
+ allow: result.next,
122
117
  };
123
118
  }
124
119
  if (result.changed || selectedWithAllowlist) {
@@ -133,12 +128,10 @@ export function syncAgentModelEntries(draft, providerId, models, options = {}) {
133
128
  const selectedAgents = normalizeAgentIds(options.targetAgents);
134
129
  if (selectedAgents.length === 0)
135
130
  return { syncedAgents: [] };
136
- const agentEntries = cfg.agents?.entries;
137
- if (!agentEntries)
138
- return { syncedAgents: [] };
131
+ const agentEntries = new Map(listConfiguredAgentEntries(cfg).map(({ id, entry }) => [id, entry]));
139
132
  const syncedAgents = [];
140
133
  for (const agentId of selectedAgents) {
141
- const entry = agentEntries[agentId];
134
+ const entry = agentEntries.get(agentId);
142
135
  if (!entry)
143
136
  continue;
144
137
  const selectedRefs = new Set(modelRefs);
@@ -159,10 +152,7 @@ export function syncAgentModelEntries(draft, providerId, models, options = {}) {
159
152
  }
160
153
  if (!changed)
161
154
  continue;
162
- agentEntries[agentId] = {
163
- ...entry,
164
- models: modelsConfig,
165
- };
155
+ entry.models = modelsConfig;
166
156
  syncedAgents.push(agentId);
167
157
  }
168
158
  return { syncedAgents };
@@ -170,6 +160,84 @@ export function syncAgentModelEntries(draft, providerId, models, options = {}) {
170
160
  function isRecord(value) {
171
161
  return typeof value === "object" && value !== null && !Array.isArray(value);
172
162
  }
163
+ export function listConfiguredAgentEntries(config) {
164
+ const cfg = config;
165
+ const agents = cfg?.agents;
166
+ if (!agents)
167
+ return [];
168
+ if (isRecord(agents.entries)) {
169
+ const entries = Object.entries(agents.entries)
170
+ .filter(([id, entry]) => id.trim().length > 0 && isRecord(entry))
171
+ .sort(([left], [right]) => left.localeCompare(right))
172
+ .map(([id, entry]) => ({ id, entry: entry }));
173
+ if (entries.length > 0 || !Array.isArray(agents.list))
174
+ return entries;
175
+ }
176
+ if (!Array.isArray(agents.list))
177
+ return [];
178
+ const entries = [];
179
+ for (const entry of agents.list) {
180
+ if (!isRecord(entry))
181
+ continue;
182
+ const id = typeof entry.id === "string" ? entry.id.trim() : "";
183
+ if (!id)
184
+ continue;
185
+ entries.push({ id, entry: entry });
186
+ }
187
+ return entries.sort((left, right) => left.id.localeCompare(right.id));
188
+ }
189
+ function collectModelAliases(config, agentId) {
190
+ const aliases = new Map();
191
+ const addModels = (models) => {
192
+ if (!isRecord(models))
193
+ return;
194
+ for (const [rawRef, value] of Object.entries(models)) {
195
+ if (!isRecord(value) || typeof value.alias !== "string")
196
+ continue;
197
+ const alias = value.alias.trim().toLowerCase();
198
+ const modelRef = rawRef.trim();
199
+ if (!alias || !modelRef || modelRef.endsWith("/*"))
200
+ continue;
201
+ aliases.set(alias, modelRef);
202
+ const provider = modelRef.split("/", 1)[0]?.trim();
203
+ if (provider) {
204
+ aliases.set(`${provider}/${alias}`.toLowerCase(), modelRef);
205
+ }
206
+ }
207
+ };
208
+ const cfg = config;
209
+ addModels(cfg?.agents?.defaults?.models);
210
+ const normalizedAgentId = agentId?.trim().toLowerCase();
211
+ if (normalizedAgentId) {
212
+ const agent = listConfiguredAgentEntries(cfg).find(({ id }) => id.toLowerCase() === normalizedAgentId);
213
+ addModels(agent?.entry.models);
214
+ }
215
+ return aliases;
216
+ }
217
+ function agentIdForReferencePath(config, path) {
218
+ const cfg = config;
219
+ const agents = cfg?.agents;
220
+ if (!agents)
221
+ return undefined;
222
+ if (isRecord(agents.entries)) {
223
+ const prefix = "agents.entries.";
224
+ if (path.startsWith(prefix)) {
225
+ return Object.keys(agents.entries)
226
+ .filter((id) => path.startsWith(`${prefix}${id}.`))
227
+ .sort((left, right) => right.length - left.length)[0];
228
+ }
229
+ }
230
+ if (Array.isArray(agents.list)) {
231
+ const match = /^agents\.list\[(\d+)\]\./.exec(path);
232
+ if (!match)
233
+ return undefined;
234
+ const entry = agents.list[Number(match[1])];
235
+ return isRecord(entry) && typeof entry.id === "string"
236
+ ? entry.id.trim() || undefined
237
+ : undefined;
238
+ }
239
+ return undefined;
240
+ }
173
241
  function parseFilter(value) {
174
242
  if (!isRecord(value))
175
243
  return {};
@@ -351,6 +419,17 @@ function forEachExplicitModelReference(config, visit) {
351
419
  for (const capability of ["image", "audio", "video"]) {
352
420
  readModelRefScalar(asOptionalRecord(tools.media[capability])?.preferredModel, `tools.media.${capability}.preferredModel`, visit);
353
421
  }
422
+ if (Array.isArray(tools.media.models)) {
423
+ 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
+ }
431
+ });
432
+ }
354
433
  }
355
434
  }
356
435
  const agents = isRecord(config.agents) ? config.agents : undefined;
@@ -464,6 +543,20 @@ export function rewriteModelReferences(draft, fromRef, toRef) {
464
543
  changed.push(`${basePath}.${field}.fallbacks[${index}]`);
465
544
  });
466
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
+ };
467
560
  const tools = isRecord(draft.tools) ? draft.tools : undefined;
468
561
  if (tools) {
469
562
  const exec = asOptionalRecord(tools.exec);
@@ -477,6 +570,13 @@ export function rewriteModelReferences(draft, fromRef, toRef) {
477
570
  continue;
478
571
  writeScalar(media, "preferredModel", `tools.media.${capability}`);
479
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
+ }
480
580
  }
481
581
  }
482
582
  const agents = isRecord(draft.agents) ? draft.agents : undefined;
@@ -574,6 +674,128 @@ function rewriteDiscordVoiceModelReferences(voice, basePath, writeScalar, writeS
574
674
  writeSetting(voiceConfig, "model", basePath);
575
675
  writeSetting(asOptionalRecord(voiceConfig.tts), "summaryModel", `${basePath}.tts`);
576
676
  }
677
+ /**
678
+ * Moves the config entries that OpenClaw keys by model reference from one
679
+ * spelling to another.
680
+ *
681
+ * `agents.*.models` carries per-model metadata such as `alias`, and
682
+ * `modelPolicy.allow` names models by reference. A provider can hold the same
683
+ * model under two letter-case spellings, so retiring the stale spelling has to
684
+ * move those entries to the surviving one. Dropping them instead would throw
685
+ * the alias away and leave the metadata attached to a model that no longer
686
+ * exists.
687
+ */
688
+ export function migrateModelRefEntries(draft, pairs, options = {}) {
689
+ const replacements = new Map();
690
+ for (const pair of pairs) {
691
+ const from = pair.fromRef.trim();
692
+ const to = pair.toRef.trim();
693
+ if (!from || !to || from === to)
694
+ continue;
695
+ replacements.set(from, to);
696
+ }
697
+ if (replacements.size === 0)
698
+ return { changed: false, paths: [] };
699
+ const changed = [];
700
+ const moveEntry = (container, basePath) => {
701
+ if (!isRecord(container))
702
+ return;
703
+ for (const [from, to] of replacements) {
704
+ if (!Object.prototype.hasOwnProperty.call(container, from))
705
+ continue;
706
+ const moved = container[from];
707
+ const existing = container[to];
708
+ const movedAlias = isRecord(moved) && typeof moved.alias === "string"
709
+ ? moved.alias.trim()
710
+ : "";
711
+ const existingAlias = isRecord(existing) && typeof existing.alias === "string"
712
+ ? existing.alias.trim()
713
+ : "";
714
+ if (options.onAliasConflict === "error" &&
715
+ movedAlias &&
716
+ existingAlias &&
717
+ movedAlias !== existingAlias) {
718
+ throw new Error(`Cannot move model entry ${from} to ${to}: both models define different aliases. Keep ${from} or choose another rewrite target.`);
719
+ }
720
+ // The surviving spelling wins on conflict so an alias already set for it
721
+ // is not overwritten by the stale one.
722
+ container[to] =
723
+ isRecord(moved) && isRecord(existing) ? { ...moved, ...existing } : (existing ?? moved);
724
+ delete container[from];
725
+ changed.push(`${basePath}.${to}`);
726
+ }
727
+ };
728
+ const rewriteAllowList = (container, field, basePath) => {
729
+ if (!isRecord(container))
730
+ return;
731
+ const list = container[field];
732
+ if (!Array.isArray(list))
733
+ return;
734
+ const next = [];
735
+ const seen = new Set();
736
+ let touched = false;
737
+ for (const item of list) {
738
+ if (typeof item !== "string") {
739
+ next.push(item);
740
+ continue;
741
+ }
742
+ const trimmed = item.trim();
743
+ const mapped = replacements.get(trimmed) ?? trimmed;
744
+ if (mapped !== trimmed)
745
+ touched = true;
746
+ if (seen.has(mapped)) {
747
+ touched = true;
748
+ continue;
749
+ }
750
+ seen.add(mapped);
751
+ next.push(mapped);
752
+ }
753
+ if (!touched)
754
+ return;
755
+ container[field] = next;
756
+ changed.push(`${basePath}.${field}`);
757
+ };
758
+ if (!isRecord(draft) || !isRecord(draft.agents)) {
759
+ return { changed: false, paths: [] };
760
+ }
761
+ const agents = draft.agents;
762
+ const defaults = asOptionalRecord(agents.defaults);
763
+ if (defaults) {
764
+ moveEntry(defaults.models, "agents.defaults.models");
765
+ rewriteAllowList(defaults.modelPolicy, "allow", "agents.defaults.modelPolicy");
766
+ }
767
+ const requestedAgents = (options.targetAgents ?? [])
768
+ .map((agentId) => agentId.trim())
769
+ .filter(Boolean);
770
+ const agentScope = requestedAgents.length > 0 ? new Set(requestedAgents) : null;
771
+ const migrateAgent = (entry, basePath) => {
772
+ const agent = asOptionalRecord(entry);
773
+ if (!agent)
774
+ return;
775
+ moveEntry(agent.models, `${basePath}.models`);
776
+ rewriteAllowList(agent.modelPolicy, "allow", `${basePath}.modelPolicy`);
777
+ };
778
+ if (isRecord(agents.entries)) {
779
+ for (const agentId of Object.keys(agents.entries).sort((left, right) => left.localeCompare(right))) {
780
+ if (agentScope && !agentScope.has(agentId))
781
+ continue;
782
+ migrateAgent(agents.entries[agentId], `agents.entries.${agentId}`);
783
+ }
784
+ }
785
+ else if (Array.isArray(agents.list)) {
786
+ agents.list.forEach((entry, index) => {
787
+ const agent = asOptionalRecord(entry);
788
+ const agentId = typeof agent?.id === "string" && agent.id.trim() ? agent.id.trim() : undefined;
789
+ if (agentScope && (!agentId || !agentScope.has(agentId)))
790
+ return;
791
+ migrateAgent(agent, `agents.list[${index}]`);
792
+ });
793
+ }
794
+ return {
795
+ changed: changed.length > 0,
796
+ paths: changed.sort((left, right) => left.localeCompare(right)),
797
+ };
798
+ }
577
799
  function visitAgentModelReferences(path, agent, includeEntrySelectors, visit) {
578
800
  readModelRefSetting(agent.model, `${path}.model`, visit);
579
801
  readModelRefScalar(agent.utilityModel, `${path}.utilityModel`, visit);
@@ -628,7 +850,8 @@ export function collectModelReferenceUsages(config, providerId, modelIds) {
628
850
  if (targets.size === 0)
629
851
  return [];
630
852
  forEachExplicitModelReference(config, (ref, path) => {
631
- const usage = targets.get(ref);
853
+ const aliases = collectModelAliases(config, agentIdForReferencePath(config, path));
854
+ const usage = targets.get(ref) ?? targets.get(aliases.get(ref.toLowerCase()) ?? "");
632
855
  if (!usage)
633
856
  return;
634
857
  if (!usage.references.includes(path))
@@ -729,20 +952,22 @@ export function resolveDefaultModelRef(config) {
729
952
  };
730
953
  const defaults = asOptionalRecord(agents.defaults);
731
954
  const defaultPrimary = readPrimary(defaults);
955
+ const resolveAlias = (ref, agentId) => collectModelAliases(config, agentId).get(ref.toLowerCase()) ?? ref;
732
956
  if (defaultPrimary)
733
- return defaultPrimary;
957
+ return resolveAlias(defaultPrimary);
734
958
  if (isRecord(agents.entries)) {
735
959
  for (const agentId of Object.keys(agents.entries).sort((left, right) => left.localeCompare(right))) {
736
960
  const primary = readPrimary(agents.entries[agentId]);
737
961
  if (primary)
738
- return primary;
962
+ return resolveAlias(primary, agentId);
739
963
  }
740
964
  }
741
965
  if (Array.isArray(agents.list)) {
742
966
  for (const entry of agents.list) {
743
967
  const primary = readPrimary(entry);
968
+ const agentId = isRecord(entry) && typeof entry.id === "string" ? entry.id : undefined;
744
969
  if (primary)
745
- return primary;
970
+ return resolveAlias(primary, agentId);
746
971
  }
747
972
  }
748
973
  return undefined;
@@ -753,6 +978,11 @@ function normalizeBaseUrl(baseUrl) {
753
978
  function joinUrl(baseUrl, path) {
754
979
  return `${normalizeBaseUrl(baseUrl)}${path}`;
755
980
  }
981
+ function withQueryParam(url, name, value) {
982
+ const parsed = new URL(url);
983
+ parsed.searchParams.set(name, value);
984
+ return parsed.toString();
985
+ }
756
986
  export function buildModelsEndpoint(providerId, provider) {
757
987
  const api = provider.api;
758
988
  const base = normalizeBaseUrl(provider.baseUrl);
@@ -763,11 +993,6 @@ export function buildModelsEndpoint(providerId, provider) {
763
993
  if (api === "anthropic-messages") {
764
994
  return joinUrl(/\/v1$/i.test(base) ? base : `${base}/v1`, "/models");
765
995
  }
766
- const isOpenRouter = providerId.toLowerCase() === "openrouter" ||
767
- base.toLowerCase().endsWith("openrouter.ai/api/v1");
768
- if (isOpenRouter) {
769
- return joinUrl(base.endsWith("/api/v1") ? base : "https://openrouter.ai/api/v1", "/models");
770
- }
771
996
  return joinUrl(base.replace(/\/models$/i, ""), "/models");
772
997
  }
773
998
  function readNumber(value) {
@@ -775,11 +1000,38 @@ function readNumber(value) {
775
1000
  ? Math.floor(value)
776
1001
  : undefined;
777
1002
  }
1003
+ function readNonNegativeNumber(value) {
1004
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
1005
+ return value;
1006
+ }
1007
+ if (typeof value !== "string" || !value.trim())
1008
+ return undefined;
1009
+ const parsed = Number(value);
1010
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
1011
+ }
1012
+ function readString(value) {
1013
+ if (typeof value !== "string")
1014
+ return undefined;
1015
+ const trimmed = value.trim();
1016
+ return trimmed || undefined;
1017
+ }
1018
+ function readStringList(value) {
1019
+ return Array.isArray(value)
1020
+ ? value
1021
+ .filter((entry) => typeof entry === "string")
1022
+ .map((entry) => entry.trim().toLowerCase())
1023
+ .filter(Boolean)
1024
+ : [];
1025
+ }
778
1026
  function readContextWindow(row) {
779
1027
  const direct = readNumber(row.context_window) ??
780
1028
  readNumber(row.contextWindow) ??
781
1029
  readNumber(row.context_length) ??
782
- readNumber(row.contextLength);
1030
+ readNumber(row.contextLength) ??
1031
+ readNumber(row.max_context_length) ??
1032
+ readNumber(row.maxContextLength) ??
1033
+ readNumber(row.max_model_len) ??
1034
+ readNumber(row.context_size);
783
1035
  if (direct !== undefined)
784
1036
  return direct;
785
1037
  if (isRecord(row.top_provider))
@@ -788,6 +1040,81 @@ function readContextWindow(row) {
788
1040
  return readNumber(row.details.context_length);
789
1041
  return undefined;
790
1042
  }
1043
+ function readMaxTokens(row) {
1044
+ const direct = readNumber(row.max_completion_tokens) ??
1045
+ readNumber(row.max_output_tokens) ??
1046
+ readNumber(row.maxTokens) ??
1047
+ readNumber(row.max_tokens);
1048
+ if (direct !== undefined)
1049
+ return direct;
1050
+ if (isRecord(row.top_provider)) {
1051
+ return readNumber(row.top_provider.max_completion_tokens);
1052
+ }
1053
+ return undefined;
1054
+ }
1055
+ function readInputModalities(row) {
1056
+ const architecture = asOptionalRecord(row.architecture);
1057
+ const modalities = asOptionalRecord(row.modalities);
1058
+ const values = new Set([
1059
+ ...readStringList(row.input),
1060
+ ...readStringList(architecture?.input_modalities),
1061
+ ...readStringList(architecture?.inputModalities),
1062
+ ...readStringList(modalities?.input),
1063
+ ]);
1064
+ const capabilities = readStringList(row.capabilities);
1065
+ const input = ["text"];
1066
+ if (row.supports_vision === true ||
1067
+ values.has("image") ||
1068
+ values.has("vision") ||
1069
+ capabilities.includes("vision") ||
1070
+ capabilities.includes("image")) {
1071
+ input.push("image");
1072
+ }
1073
+ return input;
1074
+ }
1075
+ function readReasoningSupport(row) {
1076
+ if (typeof row.reasoning === "boolean")
1077
+ return row.reasoning;
1078
+ const supported = readStringList(row.supported_parameters);
1079
+ const capabilities = readStringList(row.capabilities);
1080
+ return (supported.includes("reasoning") ||
1081
+ supported.includes("include_reasoning") ||
1082
+ capabilities.includes("reasoning") ||
1083
+ capabilities.includes("thinking"));
1084
+ }
1085
+ function readCostFields(pricing, scale) {
1086
+ const input = readNonNegativeNumber(pricing.input) ??
1087
+ readNonNegativeNumber(pricing.prompt);
1088
+ const output = readNonNegativeNumber(pricing.output) ??
1089
+ readNonNegativeNumber(pricing.completion);
1090
+ const cacheRead = readNonNegativeNumber(pricing.cacheRead) ??
1091
+ readNonNegativeNumber(pricing.cache_read) ??
1092
+ readNonNegativeNumber(pricing.input_cache_read);
1093
+ const cacheWrite = readNonNegativeNumber(pricing.cacheWrite) ??
1094
+ readNonNegativeNumber(pricing.cache_write) ??
1095
+ readNonNegativeNumber(pricing.input_cache_write);
1096
+ if (input === undefined &&
1097
+ output === undefined &&
1098
+ cacheRead === undefined &&
1099
+ cacheWrite === undefined) {
1100
+ return undefined;
1101
+ }
1102
+ return {
1103
+ input: (input ?? 0) * scale,
1104
+ output: (output ?? 0) * scale,
1105
+ cacheRead: (cacheRead ?? 0) * scale,
1106
+ cacheWrite: (cacheWrite ?? 0) * scale,
1107
+ };
1108
+ }
1109
+ function readCost(row) {
1110
+ // OpenClaw model costs are USD per million tokens. OpenRouter-shaped model
1111
+ // feeds publish per-token rates under `pricing`; `cost` is already normalized.
1112
+ const normalized = asOptionalRecord(row.cost);
1113
+ if (normalized)
1114
+ return readCostFields(normalized, 1);
1115
+ const pricing = asOptionalRecord(row.pricing);
1116
+ return pricing ? readCostFields(pricing, 1_000_000) : undefined;
1117
+ }
791
1118
  export function mapFetchedRows(providerId, provider, rows) {
792
1119
  const models = [];
793
1120
  const seen = new Set();
@@ -795,34 +1122,70 @@ export function mapFetchedRows(providerId, provider, rows) {
795
1122
  for (const row of rows) {
796
1123
  if (!isRecord(row))
797
1124
  continue;
798
- const rawId = isOllama ? row.name : row.id;
1125
+ const rawId = isOllama
1126
+ ? (readString(row.name) ?? readString(row.model) ?? row.id)
1127
+ : (readString(row.id) ?? readString(row.model) ?? readString(row.name));
799
1128
  if (typeof rawId !== "string" || !rawId.trim())
800
1129
  continue;
801
1130
  const id = rawId.trim();
802
1131
  if (seen.has(id))
803
1132
  continue;
804
1133
  seen.add(id);
805
- const model = createDefaultModel(id, typeof row.name === "string" && row.name.trim()
806
- ? row.name
807
- : typeof row.display_name === "string"
808
- ? row.display_name
809
- : undefined);
1134
+ const displayName = readString(row.display_name) ??
1135
+ readString(row.displayName) ??
1136
+ (!isOllama && readString(row.name) !== id ? readString(row.name) : undefined);
1137
+ const model = createDefaultModel(id, displayName);
810
1138
  const contextWindow = readContextWindow(row);
811
1139
  if (contextWindow !== undefined)
812
1140
  model.contextWindow = contextWindow;
1141
+ const maxTokens = readMaxTokens(row);
1142
+ if (maxTokens !== undefined)
1143
+ model.maxTokens = maxTokens;
1144
+ model.reasoning = readReasoningSupport(row);
1145
+ model.input = readInputModalities(row);
1146
+ const cost = readCost(row);
1147
+ if (cost)
1148
+ model.cost = cost;
813
1149
  models.push(model);
814
1150
  }
815
1151
  return models;
816
1152
  }
817
- function extractRows(body, provider) {
818
- if (!isRecord(body))
819
- return [];
820
- if (provider.api === "ollama")
821
- return Array.isArray(body.models) ? body.models : [];
822
- return Array.isArray(body.data) ? body.data : [];
1153
+ function extractModelPage(body, provider) {
1154
+ if (Array.isArray(body))
1155
+ return { rows: body };
1156
+ if (!isRecord(body)) {
1157
+ throw new Error("Model list response was not a JSON object or array.");
1158
+ }
1159
+ const rows = provider.api === "ollama" && Array.isArray(body.models)
1160
+ ? body.models
1161
+ : Array.isArray(body.data)
1162
+ ? body.data
1163
+ : Array.isArray(body.models)
1164
+ ? body.models
1165
+ : Array.isArray(body.results)
1166
+ ? body.results
1167
+ : undefined;
1168
+ if (!rows) {
1169
+ throw new Error("Model list response did not contain a supported models array (data, models, or results).");
1170
+ }
1171
+ if (provider.api === "ollama" || body.has_more !== true) {
1172
+ return { rows };
1173
+ }
1174
+ const pageRows = rows.filter(isRecord);
1175
+ const lastRow = pageRows.at(-1);
1176
+ const nextCursor = readString(body.last_id) ??
1177
+ readString(body.next_cursor) ??
1178
+ readString(body.nextCursor) ??
1179
+ (lastRow
1180
+ ? (readString(lastRow.id) ?? readString(lastRow.name) ?? readString(lastRow.model))
1181
+ : undefined);
1182
+ if (nextCursor === undefined) {
1183
+ throw new Error("Model list response reported more pages but did not include a cursor.");
1184
+ }
1185
+ return { rows, nextCursor };
823
1186
  }
824
1187
  export async function fetchProviderModels({ providerId, provider, apiKey, signal, guardedFetch = fetchWithSsrFGuard, }) {
825
- const endpoint = buildModelsEndpoint(providerId, provider);
1188
+ let endpoint = buildModelsEndpoint(providerId, provider);
826
1189
  const headers = {
827
1190
  Accept: "application/json",
828
1191
  };
@@ -834,33 +1197,49 @@ export async function fetchProviderModels({ providerId, provider, apiKey, signal
834
1197
  }
835
1198
  if (provider.api === "anthropic-messages")
836
1199
  headers["anthropic-version"] = "2023-06-01";
837
- const guarded = await guardedFetch({
838
- url: endpoint,
839
- init: { method: "GET", headers },
840
- timeoutMs: REQUEST_TIMEOUT_MS,
841
- signal,
842
- policy: ssrfPolicyFromAllowPrivateNetwork(provider.request?.allowPrivateNetwork === true),
843
- auditContext: "model-fetch.models",
844
- });
845
- try {
846
- if (!guarded.response.ok) {
847
- const buffer = await readResponseWithLimit(guarded.response, 4096, { signal });
848
- const snippet = buffer.toString("utf8").slice(0, 500);
849
- throw new Error(`Model list request failed with HTTP ${guarded.response.status}: ${snippet}`);
850
- }
851
- const buffer = await readResponseWithLimit(guarded.response, RESPONSE_LIMIT_BYTES, { signal });
852
- let body;
1200
+ const rows = [];
1201
+ const seenCursors = new Set();
1202
+ for (let page = 0; page < MAX_MODEL_PAGES; page += 1) {
1203
+ const guarded = await guardedFetch({
1204
+ url: endpoint,
1205
+ init: { method: "GET", headers },
1206
+ timeoutMs: REQUEST_TIMEOUT_MS,
1207
+ signal,
1208
+ policy: ssrfPolicyFromAllowPrivateNetwork(provider.request?.allowPrivateNetwork === true),
1209
+ auditContext: "model-fetch.models",
1210
+ });
853
1211
  try {
854
- body = JSON.parse(buffer.toString("utf8"));
1212
+ if (!guarded.response.ok) {
1213
+ const buffer = await readResponseWithLimit(guarded.response, 4096, { signal });
1214
+ const snippet = buffer.toString("utf8").slice(0, 500);
1215
+ throw new Error(`Model list request failed with HTTP ${guarded.response.status}: ${snippet}`);
1216
+ }
1217
+ const buffer = await readResponseWithLimit(guarded.response, RESPONSE_LIMIT_BYTES, {
1218
+ signal,
1219
+ });
1220
+ let body;
1221
+ try {
1222
+ body = JSON.parse(buffer.toString("utf8"));
1223
+ }
1224
+ catch {
1225
+ throw new Error("Model list response was not valid JSON.");
1226
+ }
1227
+ const extracted = extractModelPage(body, provider);
1228
+ rows.push(...extracted.rows);
1229
+ if (extracted.nextCursor === undefined) {
1230
+ return mapFetchedRows(providerId, provider, rows);
1231
+ }
1232
+ if (seenCursors.has(extracted.nextCursor)) {
1233
+ throw new Error(`Model list pagination repeated cursor "${extracted.nextCursor}".`);
1234
+ }
1235
+ seenCursors.add(extracted.nextCursor);
1236
+ endpoint = withQueryParam(endpoint, "after_id", extracted.nextCursor);
855
1237
  }
856
- catch {
857
- throw new Error("Model list response was not valid JSON.");
1238
+ finally {
1239
+ await guarded.release();
858
1240
  }
859
- return mapFetchedRows(providerId, provider, extractRows(body, provider));
860
- }
861
- finally {
862
- await guarded.release();
863
1241
  }
1242
+ throw new Error(`Model list exceeded the ${MAX_MODEL_PAGES}-page safety limit.`);
864
1243
  }
865
1244
  export function getProvider(config, providerId) {
866
1245
  const cfg = config;
@@ -911,7 +1290,7 @@ export async function runModelFetch({ api, toolContext, factoryConfig, fetchMode
911
1290
  selected,
912
1291
  filter: effectiveFilter,
913
1292
  });
914
- const protection = applyModelReferenceProtection({
1293
+ let protection = applyModelReferenceProtection({
915
1294
  existing,
916
1295
  merged: merge.models,
917
1296
  providerId,
@@ -919,6 +1298,7 @@ export async function runModelFetch({ api, toolContext, factoryConfig, fetchMode
919
1298
  });
920
1299
  let persisted = false;
921
1300
  let configPath = CONFIG_PATH;
1301
+ let removed = Math.max(0, merge.removed - protection.protectedModels.length);
922
1302
  if (!params.dryRun) {
923
1303
  const runtime = api.runtime;
924
1304
  const result = await runtime.config.mutateConfigFile({
@@ -929,6 +1309,15 @@ export async function runModelFetch({ api, toolContext, factoryConfig, fetchMode
929
1309
  cfg.models ??= {};
930
1310
  cfg.models.providers ??= {};
931
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;
932
1321
  target.models = protection.models;
933
1322
  cfg.models.providers[providerId] = target;
934
1323
  const targetAgents = resolveProviderTargetAgents(providerId, cfg, factoryConfig);
@@ -950,7 +1339,7 @@ export async function runModelFetch({ api, toolContext, factoryConfig, fetchMode
950
1339
  protectedModels: protection.protectedModels,
951
1340
  added: merge.added,
952
1341
  unchanged: merge.unchanged,
953
- removed: Math.max(0, merge.removed - protection.protectedModels.length),
1342
+ removed,
954
1343
  replace: effectiveFilter.replace === true,
955
1344
  dryRun: params.dryRun === true,
956
1345
  configPath,