fix(runtime): preserve model capacity history and cache evidence with resumable file proposals
This commit is contained in:
@@ -35,6 +35,8 @@ export class ConfigImporter {
|
||||
...(item.outputTokenField !== undefined ? { outputTokenField: item.outputTokenField } : {}),
|
||||
...(item.parameterProfile !== undefined ? { parameterProfile: item.parameterProfile } : {}),
|
||||
...(item.protocol === 'anthropic-messages' ? { messagesAuth: item.messagesAuth ?? 'api-key' } : {}),
|
||||
...(item.contextLimit !== undefined ? { contextLimit: item.contextLimit } : {}),
|
||||
...(item.maxOutputTokens !== undefined ? { maxOutputTokens: item.maxOutputTokens } : {}),
|
||||
baseUrl: item.baseUrl, apiKey: item.apiKey, requiresKey: item.requiresKey !== false, brand: item.brand });
|
||||
}
|
||||
} else if (source === 'ccswitch') {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { randomUUID, createHash } from 'node:crypto';
|
||||
import { catalogPage, catalogRoute } from '../../shared/contracts/model-catalog.mjs';
|
||||
import { messagesAuthSettings, validateProtocolEndpoint } from '../../shared/contracts/model-endpoint.mjs';
|
||||
import { modelProtocol, capabilityDeclarations } from '../../shared/contracts/model-capabilities.mjs';
|
||||
import { DEFAULT_MODEL_CAPACITY } from '../../shared/contracts/model-capacity.mjs';
|
||||
|
||||
const fail = (message, status = 400) => Object.assign(new Error(message), { status });
|
||||
const stamp = () => new Date().toISOString();
|
||||
@@ -128,8 +129,8 @@ export class ModelCatalog {
|
||||
protocol: value.connection.protocol, baseUrl: value.connection.baseUrl, brand: value.connection.brand, messagesAuth: value.connection.messagesAuth,
|
||||
requiresKey: value.connection.requiresKey, concurrency: value.connection.concurrency, parameterProfile: value.connection.parameterProfile ?? 'auto',
|
||||
capabilityDeclarations: Object.fromEntries(Object.entries(model.capabilityDeclarations).map(([key, state]) => [key, state === 'unknown' ? declarations[key] : state])), streaming: false,
|
||||
contextLimit: Math.min(value.connection.contextLimit ?? 16000, model.contextLimit ?? 200000),
|
||||
maxOutputTokens: Math.min(value.connection.maxOutputTokens ?? 2048, model.maxOutputTokens ?? 16000),
|
||||
contextLimit: model.contextLimit ?? value.connection.contextLimit ?? DEFAULT_MODEL_CAPACITY.contextLimit,
|
||||
maxOutputTokens: model.maxOutputTokens ?? value.connection.maxOutputTokens ?? DEFAULT_MODEL_CAPACITY.maxOutputTokens,
|
||||
...(!owner && value.explicitKey ? { apiKey: value.explicitKey, persistKey: input.persistKey === true } : {}) });
|
||||
const connection = hub.connection(profile.id); connection.upstreamModel = upstreamModel; connection.source = 'upstream-catalog';
|
||||
if (!owner) owner = connection;
|
||||
|
||||
@@ -13,6 +13,7 @@ import { assertModelParameterSupport } from '../../shared/contracts/model-parame
|
||||
import { modelIdentitySettings } from '../../shared/contracts/model-identity.mjs';
|
||||
import { NetworkDiagnostics } from './network-diagnostics.mjs';
|
||||
import { ModelCatalog, credentialScope } from './model-catalog.mjs';
|
||||
import { capacitySettings, routedCapacity } from '../../shared/contracts/model-capacity.mjs';
|
||||
|
||||
const legacyId = 'legacy-default';
|
||||
const stamp = () => new Date().toISOString();
|
||||
@@ -217,7 +218,7 @@ export class ModelHub {
|
||||
capabilitySchema: 1, capabilityDeclarations: declarations, streaming, ...(native ?? {}), ...modelIdentitySettings(input, previous ?? {}),
|
||||
...messagesAuthSettings(protocol, input.messagesAuth ?? previous?.messagesAuth),
|
||||
baseUrl: validateProtocolEndpoint(protocol, modelEndpoint(input.baseUrl)), enabled: input.enabled !== false, requiresKey: input.requiresKey !== false,
|
||||
contextLimit: bounded(input.contextLimit, 16000, 1000, 200000), maxOutputTokens: bounded(input.maxOutputTokens, 2048, 256, 16000),
|
||||
...capacitySettings(input, previous ?? undefined),
|
||||
concurrency: bounded(input.concurrency, 1, 1, 8), revision: (previous?.revision ?? 0) + 1,
|
||||
source: previous?.source ?? 'manual', ...(previous?.importOrigin ? { importOrigin: previous.importOrigin, importRevision: previous.importRevision } : {}),
|
||||
createdAt: previous?.createdAt ?? stamp(), updatedAt: stamp() };
|
||||
@@ -291,7 +292,7 @@ export class ModelHub {
|
||||
return { ...config, ...messagesAuthSettings(members[0].protocol, members[0].messagesAuth), baseUrl: members[0].baseUrl, model: members[0].model, protocol: modelProtocol(members[0].protocol), streaming: members[0].streaming === true,
|
||||
nativeParameters: members[0].nativeParameters ?? {}, outputTokenField: members[0].outputTokenField, parameterProfile: members[0].parameterProfile,
|
||||
modelConnectionId: members[0].id, modelCredentialRevision: members[0].credentialRevision,
|
||||
contextLimit: Math.min(config.contextLimit, ...members.map(value => value.contextLimit)), maxOutputTokens: Math.min(config.maxOutputTokens, ...members.map(value => value.maxOutputTokens)),
|
||||
...routedCapacity(config, members),
|
||||
modelRouting: { type: selection.type, id: selection.id, revision: pool?.revision ?? members[0].revision,
|
||||
strategy: pool?.strategy ?? 'round-robin', sticky: pool?.sticky ?? true, maxAttempts: pool?.maxAttempts ?? 1, queueTimeoutMs: pool?.queueTimeoutMs ?? 15000, members } };
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ export const protocolFailure = (message, kind = 'protocol', extra = null) => new
|
||||
// even a syntactically complete leading tool call is dropped, because any later call in
|
||||
// the same turn may be cut mid-argument. The diagnostic must tell the model what happened
|
||||
// and how to proceed, instead of a generic incompleteness message it cannot act on.
|
||||
export const OUTPUT_TRUNCATED_HINT = '模型输出达到单次 output token 上限(finish_reason=length),本次响应整体未执行任何工具(即使其中一个工具参数已完整也不执行,避免应用被截断的半成品)。请减少单次响应的工具数量:把多文件提案拆成每次一个文件的 propose_file/propose_patch,或分多轮 prepare_change_set,不要在一个响应里堆叠多个大参数工具。';
|
||||
export const OUTPUT_TRUNCATED_HINT = '上游模型在本次配置的输出额度处停止(finish_reason=length),本次响应整体未执行工具,原响应和用量已保留。请拆分输出:已有文件使用propose_patch;单个长文件用propose_file_chunk分多轮追加较短的完整片段,最后complete=true生成完整提案。已有成功片段使用原draft_id/next_offset/draft_sha256继续,不从头重复。不要在一个响应中堆叠多个大工具参数。原目标和已读依据保留。';
|
||||
export const outputTruncatedFailure = (kind = 'protocol') => protocolFailure(OUTPUT_TRUNCATED_HINT, kind, { reason: 'output_truncated' });
|
||||
export { protocolRoute } from '../../shared/contracts/model-endpoint.mjs';
|
||||
|
||||
@@ -20,14 +20,22 @@ export function reportedUsage(config, value) {
|
||||
const input = raw.input_tokens + cached + created, total = input + raw.output_tokens;
|
||||
if (!Number.isSafeInteger(total)) return null;
|
||||
return { prompt_tokens: input, completion_tokens: raw.output_tokens, total_tokens: total,
|
||||
prompt_tokens_details: { cached_tokens: cached, cache_creation_tokens: created }, raw: structuredClone(raw), protocol: 'anthropic-messages' };
|
||||
...(raw.cache_read_input_tokens !== undefined || raw.cache_creation_input_tokens !== undefined ? { prompt_tokens_details: {
|
||||
...(raw.cache_read_input_tokens !== undefined ? { cached_tokens: cached } : {}),
|
||||
...(raw.cache_creation_input_tokens !== undefined ? { cache_creation_tokens: created } : {}) } } : {}),
|
||||
raw: structuredClone(raw), protocol: 'anthropic-messages' };
|
||||
}
|
||||
const input = config.protocol === 'responses' ? raw.input_tokens : raw.prompt_tokens;
|
||||
const output = config.protocol === 'responses' ? raw.output_tokens : raw.completion_tokens;
|
||||
const valid = number => Number.isSafeInteger(number) && number >= 0;
|
||||
if (!valid(raw.total_tokens) && !(valid(input) && valid(output))) return null;
|
||||
const cached = config.protocol === 'responses' ? raw.input_tokens_details?.cached_tokens : raw.prompt_tokens_details?.cached_tokens ?? raw.prompt_cache_hit_tokens;
|
||||
const cacheDetails = valid(cached) && valid(input) && cached <= input ? { cached_tokens: cached } : null;
|
||||
const reasoning = config.protocol === 'responses' ? raw.output_tokens_details?.reasoning_tokens : raw.completion_tokens_details?.reasoning_tokens;
|
||||
return { ...(valid(input) ? { prompt_tokens: input } : {}), ...(valid(output) ? { completion_tokens: output } : {}),
|
||||
total_tokens: valid(raw.total_tokens) ? raw.total_tokens : input + output };
|
||||
total_tokens: valid(raw.total_tokens) ? raw.total_tokens : input + output,
|
||||
...(cacheDetails ? { prompt_tokens_details: cacheDetails } : {}), ...(valid(reasoning) && valid(output) && reasoning <= output ? { completion_tokens_details: { reasoning_tokens: reasoning } } : {}),
|
||||
raw: structuredClone(raw), protocol: config.protocol ?? 'chat-completions' };
|
||||
}
|
||||
|
||||
function acceptsEmptyObject(tools, name) {
|
||||
@@ -84,9 +92,10 @@ export function normalizeProtocolResponse(config, value) {
|
||||
}
|
||||
if (config.protocol !== 'responses') {
|
||||
const received = value?.choices?.[0]?.message;
|
||||
if (received?.reasoning_content === undefined || received.reasoning_content === null) return value;
|
||||
if (received?.reasoning_content === undefined || received.reasoning_content === null) return { ...value, usage: reportedUsage(config, value) };
|
||||
if (typeof received.reasoning_content !== 'string') throw protocolFailure('Chat reasoning_content必须为字符串,原响应未用于执行工具。');
|
||||
const normalized = structuredClone(value), target = normalized.choices[0].message;
|
||||
normalized.usage = reportedUsage(config, value);
|
||||
delete target.reasoning_content;
|
||||
target.providerState = { protocol: 'chat-completions', endpoint: config.baseUrl, model: config.model,
|
||||
connectionId: config.modelConnectionId ?? null, credentialRevision: config.modelCredentialRevision ?? null, reasoningContent: received.reasoning_content };
|
||||
@@ -109,8 +118,7 @@ export function normalizeProtocolResponse(config, value) {
|
||||
}
|
||||
} else if (item.type !== 'reasoning') throw protocolFailure('Responses包含当前尚未接入的服务端工具或输出类型:' + String(item.type ?? '未标注').slice(0, 100) + '。');
|
||||
}
|
||||
const raw = value.usage, usage = raw ? { prompt_tokens: raw.input_tokens, completion_tokens: raw.output_tokens,
|
||||
...(raw.total_tokens !== undefined ? { total_tokens: raw.total_tokens } : {}), raw, protocol: 'responses' } : null;
|
||||
const usage = reportedUsage(config, value);
|
||||
return { choices: [{ message: { role: 'assistant', content: texts.join(''), ...(calls.length ? { tool_calls: calls } : {}),
|
||||
providerState: { protocol: 'responses', endpoint: config.baseUrl, model: config.model, responseId: value.id ?? null, items: value.output } }, finish_reason: calls.length ? 'tool_calls' : 'stop' }], usage };
|
||||
}
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
import { CAPACITY_RANGES, capacityMode } from '../../shared/contracts/model-capacity.mjs';
|
||||
|
||||
const ranges = {
|
||||
contextLimit: [1000, 200000], maxOutputTokens: [256, 16000], maxSteps: [1, 30],
|
||||
...CAPACITY_RANGES, maxSteps: [1, 30],
|
||||
maxRunDurationMs: [1000, 3600000], maxRunTokens: [1000, 2000000], maxTaskTokens: [1000, 10000000],
|
||||
};
|
||||
|
||||
// Budget-only edits cannot change the selected route, endpoint or credential.
|
||||
export function validateRuntimeBudgets(input) {
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input) || !Object.keys(input).length
|
||||
|| Object.keys(input).some(key => !Object.hasOwn(ranges, key))) throw new Error('只接受运行预算字段;模型连接请在模型选择中切换。');
|
||||
|| Object.keys(input).some(key => !['capacityMode', 'historyPolicy'].includes(key) && !Object.hasOwn(ranges, key))) throw new Error('只接受运行预算字段;模型连接请在模型选择中切换。');
|
||||
for (const [key, value] of Object.entries(input)) {
|
||||
if (key === 'capacityMode') { capacityMode(value); continue; }
|
||||
if (key === 'historyPolicy') { if (!['preserve', 'compact'].includes(value)) throw new Error('请选择完整传递或允许整理历史。'); continue; }
|
||||
const [min, max] = ranges[key];
|
||||
if (!Number.isSafeInteger(value) || value < min || value > max) throw new Error(key + ' 需填写范围内的整数。');
|
||||
}
|
||||
return { ...input };
|
||||
return { ...input, ...(!Object.hasOwn(input, 'capacityMode') && ['contextLimit', 'maxOutputTokens'].some(key => Object.hasOwn(input, key)) ? { capacityMode: 'manual' } : {}) };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user