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.
- package/README-CN.md +1 -1
- package/README.md +1 -1
- package/dist/control-ui/da0bba63a04b1e6c889671add02041d1452ec068e8cc9ae624aba6a5c8429f40/index.js +163 -0
- package/dist/model-fetch.d.ts +12 -0
- package/dist/model-fetch.js +347 -68
- package/dist/operations.d.ts +4 -2
- package/dist/operations.js +118 -37
- package/openclaw.plugin.json +3 -3
- package/package.json +1 -1
- package/dist/control-ui/b32b248d77fbc02925de3596562c26e19920fe4fabbae88d261043b7d0cc2625/index.js +0 -163
- /package/dist/control-ui/{b32b248d77fbc02925de3596562c26e19920fe4fabbae88d261043b7d0cc2625 → da0bba63a04b1e6c889671add02041d1452ec068e8cc9ae624aba6a5c8429f40}/index.css +0 -0
package/dist/model-fetch.js
CHANGED
|
@@ -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
|
|
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)
|
|
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
|
-
|
|
117
|
-
...entry,
|
|
118
|
-
|
|
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.
|
|
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
|
|
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
|
-
|
|
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;
|
|
@@ -605,6 +705,18 @@ export function migrateModelRefEntries(draft, pairs, options = {}) {
|
|
|
605
705
|
continue;
|
|
606
706
|
const moved = container[from];
|
|
607
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
|
+
}
|
|
608
720
|
// The surviving spelling wins on conflict so an alias already set for it
|
|
609
721
|
// is not overwritten by the stale one.
|
|
610
722
|
container[to] =
|
|
@@ -738,7 +850,8 @@ export function collectModelReferenceUsages(config, providerId, modelIds) {
|
|
|
738
850
|
if (targets.size === 0)
|
|
739
851
|
return [];
|
|
740
852
|
forEachExplicitModelReference(config, (ref, path) => {
|
|
741
|
-
const
|
|
853
|
+
const aliases = collectModelAliases(config, agentIdForReferencePath(config, path));
|
|
854
|
+
const usage = targets.get(ref) ?? targets.get(aliases.get(ref.toLowerCase()) ?? "");
|
|
742
855
|
if (!usage)
|
|
743
856
|
return;
|
|
744
857
|
if (!usage.references.includes(path))
|
|
@@ -839,20 +952,22 @@ export function resolveDefaultModelRef(config) {
|
|
|
839
952
|
};
|
|
840
953
|
const defaults = asOptionalRecord(agents.defaults);
|
|
841
954
|
const defaultPrimary = readPrimary(defaults);
|
|
955
|
+
const resolveAlias = (ref, agentId) => collectModelAliases(config, agentId).get(ref.toLowerCase()) ?? ref;
|
|
842
956
|
if (defaultPrimary)
|
|
843
|
-
return defaultPrimary;
|
|
957
|
+
return resolveAlias(defaultPrimary);
|
|
844
958
|
if (isRecord(agents.entries)) {
|
|
845
959
|
for (const agentId of Object.keys(agents.entries).sort((left, right) => left.localeCompare(right))) {
|
|
846
960
|
const primary = readPrimary(agents.entries[agentId]);
|
|
847
961
|
if (primary)
|
|
848
|
-
return primary;
|
|
962
|
+
return resolveAlias(primary, agentId);
|
|
849
963
|
}
|
|
850
964
|
}
|
|
851
965
|
if (Array.isArray(agents.list)) {
|
|
852
966
|
for (const entry of agents.list) {
|
|
853
967
|
const primary = readPrimary(entry);
|
|
968
|
+
const agentId = isRecord(entry) && typeof entry.id === "string" ? entry.id : undefined;
|
|
854
969
|
if (primary)
|
|
855
|
-
return primary;
|
|
970
|
+
return resolveAlias(primary, agentId);
|
|
856
971
|
}
|
|
857
972
|
}
|
|
858
973
|
return undefined;
|
|
@@ -863,6 +978,11 @@ function normalizeBaseUrl(baseUrl) {
|
|
|
863
978
|
function joinUrl(baseUrl, path) {
|
|
864
979
|
return `${normalizeBaseUrl(baseUrl)}${path}`;
|
|
865
980
|
}
|
|
981
|
+
function withQueryParam(url, name, value) {
|
|
982
|
+
const parsed = new URL(url);
|
|
983
|
+
parsed.searchParams.set(name, value);
|
|
984
|
+
return parsed.toString();
|
|
985
|
+
}
|
|
866
986
|
export function buildModelsEndpoint(providerId, provider) {
|
|
867
987
|
const api = provider.api;
|
|
868
988
|
const base = normalizeBaseUrl(provider.baseUrl);
|
|
@@ -873,11 +993,6 @@ export function buildModelsEndpoint(providerId, provider) {
|
|
|
873
993
|
if (api === "anthropic-messages") {
|
|
874
994
|
return joinUrl(/\/v1$/i.test(base) ? base : `${base}/v1`, "/models");
|
|
875
995
|
}
|
|
876
|
-
const isOpenRouter = providerId.toLowerCase() === "openrouter" ||
|
|
877
|
-
base.toLowerCase().endsWith("openrouter.ai/api/v1");
|
|
878
|
-
if (isOpenRouter) {
|
|
879
|
-
return joinUrl(base.endsWith("/api/v1") ? base : "https://openrouter.ai/api/v1", "/models");
|
|
880
|
-
}
|
|
881
996
|
return joinUrl(base.replace(/\/models$/i, ""), "/models");
|
|
882
997
|
}
|
|
883
998
|
function readNumber(value) {
|
|
@@ -885,11 +1000,38 @@ function readNumber(value) {
|
|
|
885
1000
|
? Math.floor(value)
|
|
886
1001
|
: undefined;
|
|
887
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
|
+
}
|
|
888
1026
|
function readContextWindow(row) {
|
|
889
1027
|
const direct = readNumber(row.context_window) ??
|
|
890
1028
|
readNumber(row.contextWindow) ??
|
|
891
1029
|
readNumber(row.context_length) ??
|
|
892
|
-
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);
|
|
893
1035
|
if (direct !== undefined)
|
|
894
1036
|
return direct;
|
|
895
1037
|
if (isRecord(row.top_provider))
|
|
@@ -898,6 +1040,81 @@ function readContextWindow(row) {
|
|
|
898
1040
|
return readNumber(row.details.context_length);
|
|
899
1041
|
return undefined;
|
|
900
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
|
+
}
|
|
901
1118
|
export function mapFetchedRows(providerId, provider, rows) {
|
|
902
1119
|
const models = [];
|
|
903
1120
|
const seen = new Set();
|
|
@@ -905,34 +1122,70 @@ export function mapFetchedRows(providerId, provider, rows) {
|
|
|
905
1122
|
for (const row of rows) {
|
|
906
1123
|
if (!isRecord(row))
|
|
907
1124
|
continue;
|
|
908
|
-
const rawId = isOllama
|
|
1125
|
+
const rawId = isOllama
|
|
1126
|
+
? (readString(row.name) ?? readString(row.model) ?? row.id)
|
|
1127
|
+
: (readString(row.id) ?? readString(row.model) ?? readString(row.name));
|
|
909
1128
|
if (typeof rawId !== "string" || !rawId.trim())
|
|
910
1129
|
continue;
|
|
911
1130
|
const id = rawId.trim();
|
|
912
1131
|
if (seen.has(id))
|
|
913
1132
|
continue;
|
|
914
1133
|
seen.add(id);
|
|
915
|
-
const
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
: 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);
|
|
920
1138
|
const contextWindow = readContextWindow(row);
|
|
921
1139
|
if (contextWindow !== undefined)
|
|
922
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;
|
|
923
1149
|
models.push(model);
|
|
924
1150
|
}
|
|
925
1151
|
return models;
|
|
926
1152
|
}
|
|
927
|
-
function
|
|
928
|
-
if (
|
|
929
|
-
return
|
|
930
|
-
if (
|
|
931
|
-
|
|
932
|
-
|
|
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 };
|
|
933
1186
|
}
|
|
934
1187
|
export async function fetchProviderModels({ providerId, provider, apiKey, signal, guardedFetch = fetchWithSsrFGuard, }) {
|
|
935
|
-
|
|
1188
|
+
let endpoint = buildModelsEndpoint(providerId, provider);
|
|
936
1189
|
const headers = {
|
|
937
1190
|
Accept: "application/json",
|
|
938
1191
|
};
|
|
@@ -944,33 +1197,49 @@ export async function fetchProviderModels({ providerId, provider, apiKey, signal
|
|
|
944
1197
|
}
|
|
945
1198
|
if (provider.api === "anthropic-messages")
|
|
946
1199
|
headers["anthropic-version"] = "2023-06-01";
|
|
947
|
-
const
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
const snippet = buffer.toString("utf8").slice(0, 500);
|
|
959
|
-
throw new Error(`Model list request failed with HTTP ${guarded.response.status}: ${snippet}`);
|
|
960
|
-
}
|
|
961
|
-
const buffer = await readResponseWithLimit(guarded.response, RESPONSE_LIMIT_BYTES, { signal });
|
|
962
|
-
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
|
+
});
|
|
963
1211
|
try {
|
|
964
|
-
|
|
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);
|
|
965
1237
|
}
|
|
966
|
-
|
|
967
|
-
|
|
1238
|
+
finally {
|
|
1239
|
+
await guarded.release();
|
|
968
1240
|
}
|
|
969
|
-
return mapFetchedRows(providerId, provider, extractRows(body, provider));
|
|
970
|
-
}
|
|
971
|
-
finally {
|
|
972
|
-
await guarded.release();
|
|
973
1241
|
}
|
|
1242
|
+
throw new Error(`Model list exceeded the ${MAX_MODEL_PAGES}-page safety limit.`);
|
|
974
1243
|
}
|
|
975
1244
|
export function getProvider(config, providerId) {
|
|
976
1245
|
const cfg = config;
|
|
@@ -1021,7 +1290,7 @@ export async function runModelFetch({ api, toolContext, factoryConfig, fetchMode
|
|
|
1021
1290
|
selected,
|
|
1022
1291
|
filter: effectiveFilter,
|
|
1023
1292
|
});
|
|
1024
|
-
|
|
1293
|
+
let protection = applyModelReferenceProtection({
|
|
1025
1294
|
existing,
|
|
1026
1295
|
merged: merge.models,
|
|
1027
1296
|
providerId,
|
|
@@ -1029,6 +1298,7 @@ export async function runModelFetch({ api, toolContext, factoryConfig, fetchMode
|
|
|
1029
1298
|
});
|
|
1030
1299
|
let persisted = false;
|
|
1031
1300
|
let configPath = CONFIG_PATH;
|
|
1301
|
+
let removed = Math.max(0, merge.removed - protection.protectedModels.length);
|
|
1032
1302
|
if (!params.dryRun) {
|
|
1033
1303
|
const runtime = api.runtime;
|
|
1034
1304
|
const result = await runtime.config.mutateConfigFile({
|
|
@@ -1039,6 +1309,15 @@ export async function runModelFetch({ api, toolContext, factoryConfig, fetchMode
|
|
|
1039
1309
|
cfg.models ??= {};
|
|
1040
1310
|
cfg.models.providers ??= {};
|
|
1041
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;
|
|
1042
1321
|
target.models = protection.models;
|
|
1043
1322
|
cfg.models.providers[providerId] = target;
|
|
1044
1323
|
const targetAgents = resolveProviderTargetAgents(providerId, cfg, factoryConfig);
|
|
@@ -1060,7 +1339,7 @@ export async function runModelFetch({ api, toolContext, factoryConfig, fetchMode
|
|
|
1060
1339
|
protectedModels: protection.protectedModels,
|
|
1061
1340
|
added: merge.added,
|
|
1062
1341
|
unchanged: merge.unchanged,
|
|
1063
|
-
removed
|
|
1342
|
+
removed,
|
|
1064
1343
|
replace: effectiveFilter.replace === true,
|
|
1065
1344
|
dryRun: params.dryRun === true,
|
|
1066
1345
|
configPath,
|
package/dist/operations.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { OpenClawPluginApi } from "openclaw/plugin-sdk/core";
|
|
2
|
-
import
|
|
2
|
+
import * as sessionStoreRuntime from "openclaw/plugin-sdk/session-store-runtime";
|
|
3
3
|
import { fetchProviderModels, type ModelFetchConfig } from "./model-fetch.js";
|
|
4
4
|
import type { ApplyStrategyInput, ApplyStrategyOutput, FetchModelsOutput, ListProvidersOutput, ModelFetchParams, PreviewApplyOutput, SaveStrategyInput, SaveStrategyOutput } from "./schemas.js";
|
|
5
5
|
type SessionSelectionScope = {
|
|
@@ -9,8 +9,10 @@ type SessionSelectionScope = {
|
|
|
9
9
|
type SessionStoreRuntime = {
|
|
10
10
|
getSessionEntryAsync: typeof getSessionEntryAsync;
|
|
11
11
|
patchSessionEntry: typeof patchSessionEntry;
|
|
12
|
-
listSessionEntries: typeof listSessionEntries
|
|
12
|
+
listSessionEntries: (params: Parameters<typeof sessionStoreRuntime.listSessionEntries>[0]) => ReturnType<typeof sessionStoreRuntime.listSessionEntries> | ReturnType<typeof sessionStoreRuntime.listSessionEntriesAsync>;
|
|
13
13
|
};
|
|
14
|
+
declare const getSessionEntryAsync: typeof sessionStoreRuntime.getSessionEntryAsync;
|
|
15
|
+
declare const patchSessionEntry: typeof sessionStoreRuntime.patchSessionEntry;
|
|
14
16
|
export type ModelFetchOperations = ReturnType<typeof createModelFetchOperations>;
|
|
15
17
|
export declare function createModelFetchOperations({ api, factoryConfig, fetchModels, now, sessionStore, }: {
|
|
16
18
|
api: OpenClawPluginApi;
|