Files
Agent-Workbench/src/shared/contracts/model-catalog.mjs
T

91 lines
7.7 KiB
JavaScript

import { modelProtocol } from './model-capabilities.mjs';
import { ceiling, unrestricted } from './execution-policy.mjs';
const fail = message => Object.assign(new Error(message), { status: 400 });
const text = (value, max = 200) => typeof value === 'string' ? value.trim().slice(0, max) : '';
const supported = value => typeof value === 'boolean' ? value ? 'supported' : 'unsupported'
: typeof value?.supported === 'boolean' ? value.supported ? 'supported' : 'unsupported'
: ['supported', 'unsupported', 'unknown'].includes(value) ? value : 'unknown';
const positive = value => Number.isSafeInteger(value) && value > 0 ? value : null;
const object = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
const strings = value => Array.isArray(value) ? [...new Set(value.filter(item => typeof item === 'string' && item && !/[\x00-\x1f\x7f]/.test(item)))] : [];
const sensitiveFields = /^(?:api[-_]?key|access[-_]?token|refresh[-_]?token|authorization|x-api-key|secret|password|credential)$/i;
function rawDeclaration(value) {
if (Array.isArray(value)) return value.map(rawDeclaration);
if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, data]) => [key, sensitiveFields.test(key) ? '[redacted]' : rawDeclaration(data)]));
return value;
}
export function catalogRoute(config) {
const protocol = modelProtocol(config.protocol);
return protocol === 'anthropic-messages' && !/\/v1$/i.test(new URL(config.baseUrl).pathname.replace(/\/+$/, ''))
? '/v1/models' : '/models';
}
// Metadata is an upstream declaration, never capability-test evidence. Keep
// unsupported adapter features visible. Retain unknown vendor fields as a
// redacted declaration; none of those fields is copied into a model request.
export function catalogModel(item, config = {}) {
if (typeof item === 'string') item = { id: item };
if (!item || typeof item !== 'object' || Array.isArray(item)) throw fail('上游模型目录含无效条目。');
const field = (value, maximum = 200) => text(value, ceiling(config, maximum));
const id = field(item.id ?? item.name);
if (!id || id.length !== String(item.id ?? item.name).trim().length || /[\x00-\x1f\x7f]/.test(id)) throw fail('上游模型名称为空、过长或含控制字符。');
const caps = object(item.capabilities), reportedFields = [];
const declarations = Object.fromEntries(['text', 'tools', 'streaming', 'vision', 'audio'].map(key => [key,
supported(caps[key] ?? (key === 'vision' ? caps.image_input : key === 'tools' ? caps.tool_calling ?? caps.function_calling : undefined))]));
const input = item.input_modalities ?? item.architecture?.input_modalities ?? item.modalities?.input;
const output = item.output_modalities ?? item.architecture?.output_modalities ?? item.modalities?.output;
if (Array.isArray(input)) {
if (input.includes('image') && declarations.vision === 'unknown') declarations.vision = 'supported';
if (input.includes('audio') && declarations.audio === 'unknown') declarations.audio = 'supported';
}
if (Array.isArray(output) && output.includes('text') && declarations.text === 'unknown') declarations.text = 'supported';
const parameters = Array.isArray(item.supported_parameters) ? [...new Set(item.supported_parameters.filter(value => typeof value === 'string' && (unrestricted(config) || value.length <= 80)))].slice(0, ceiling(config, 80)) : [];
if (declarations.tools === 'unknown' && parameters.includes('tools')) declarations.tools = 'supported';
const effortDeclaration = item.effort ?? caps.effort;
const reportedEfforts = effortDeclaration?.supported_levels ?? item.reasoning_efforts;
const reportedModes = caps.thinking?.supported_types ?? item.thinking?.supported_types;
const effortSupport = Object.fromEntries([...new Set(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', ...Object.keys(object(caps.effort)), ...strings(reportedEfforts)])]
.filter(value => !['supported', 'supported_levels', 'default_level'].includes(value)).map(value => [value, supported(caps.effort?.[value])]));
const modeSupport = Object.fromEntries([...new Set(['disabled', 'enabled', 'adaptive', 'between_tools', ...Object.keys(object(caps.thinking?.types)), ...strings(reportedModes)])]
.map(value => [value, supported(caps.thinking?.types?.[value])]));
if (Array.isArray(reportedEfforts)) {
reportedFields.push('efforts');
for (const value of strings(reportedEfforts)) if (effortSupport[value] !== 'unsupported') effortSupport[value] = 'supported';
}
if (Array.isArray(reportedModes)) {
reportedFields.push('modes');
for (const value of strings(reportedModes)) if (modeSupport[value] !== 'unsupported') modeSupport[value] = 'supported';
}
const efforts = (Array.isArray(reportedEfforts) ? strings(reportedEfforts) : Object.keys(effortSupport)).filter(value => effortSupport[value] === 'supported');
const modes = (Array.isArray(reportedModes) ? strings(reportedModes) : Object.keys(modeSupport)).filter(value => modeSupport[value] === 'supported');
const features = Object.fromEntries(['thinking', 'effort', 'pdf_input', 'structured_outputs', 'json_output', 'prompt_caching', 'server_tools', 'code_execution', 'batch', 'citations', 'context_management'].map(key => [key, supported(caps[key])]));
if (features.effort === 'unknown' && Array.isArray(reportedEfforts)) features.effort = reportedEfforts.length ? 'supported' : 'unsupported';
return { id, name: field(item.display_name ?? item.displayName ?? item.name ?? id), owner: field(item.owned_by ?? item.provider, 100),
lifecycle: ['active', 'deprecated', 'retired'].includes(item.lifecycle) ? item.lifecycle : null,
contextLimit: positive(item.context_length ?? item.context_window), maxInputTokens: positive(item.max_input_tokens ?? item.inputTokenLimit),
maxOutputTokens: positive(item.max_output_tokens ?? item.max_tokens ?? item.top_provider?.max_completion_tokens ?? item.outputTokenLimit),
capabilityDeclarations: declarations, features, efforts, modes, effortSupport, modeSupport, parameters,
...(typeof effortDeclaration?.default_level === 'string' ? { defaultEffort: effortDeclaration.default_level } : {}),
...(typeof item.thinking?.default_type === 'string' ? { defaultMode: item.thinking.default_type } : {}),
...(Array.isArray(input) ? { inputModalities: strings(input) } : {}), ...(Array.isArray(output) ? { outputModalities: strings(output) } : {}),
...(Array.isArray(item.native_tools) ? { nativeTools: strings(item.native_tools) } : {}),
apiCapabilities: structuredClone(object(item.api_capabilities)), reportedFields,
rawItem: rawDeclaration(item), rawRepresentation: 'parsed-redacted-item-json-v1', metadataSource: 'upstream-model-list' };
}
export function catalogPage(response, config = {}) {
const data = response?.data ?? response?.models;
if (!Array.isArray(data)) throw fail('上游未返回 data 或 models 模型列表;可核对接口或使用手动兼容入口。');
const entries = data.map(item => catalogModel(item, config));
const pageToken = response.nextPageToken ?? response.next_page_token;
const hasMore = response.has_more === true || typeof pageToken === 'string' && pageToken.length > 0;
const cursorParameter = typeof pageToken === 'string' && pageToken ? 'pageToken' : 'after_id';
const value = hasMore ? cursorParameter === 'pageToken' ? pageToken : response.last_id ?? entries.at(-1)?.id : '';
const cursor = text(value, ceiling(config, 200));
if (hasMore && (typeof value !== 'string' || cursor.length !== value.trim().length || /[\x00-\x1f\x7f]/.test(cursor))) throw fail('上游下一页游标无效。');
if (hasMore && !cursor) throw fail('上游声明还有下一页,却未提供有效游标。');
return { entries, hasMore, cursor, cursorParameter };
}