fix(models): preserve cache usage categories and receipt sources

This commit is contained in:
Agent Workbench Dev
2026-11-07 11:20:02 +08:00
parent ea2559df7d
commit cb60fb1149
13 changed files with 502 additions and 10 deletions
+7 -4
View File
@@ -461,10 +461,10 @@ export class RequestPlanner {
return { messages, body, record };
}
finish(session, record, { response = null, error = null, attempts = 0 } = {}) {
finish(session, record, { response = null, error = null, attempts = 0, usage = response?.usage ?? null } = {}) {
this.store.owned('context_plan', record.id, session.id);
record.status = error ? error.name === 'AbortError' || session.status === 'stopping' ? 'interrupted' : 'failed' : 'completed';
record.finishedAt = new Date().toISOString(); record.actualUsage = response?.usage ?? null;
record.finishedAt = new Date().toISOString(); record.actualUsage = usage;
record.responseSha256 = response?.message ? hash(response.message) : null; record.requestAttempts = attempts;
if (error) record.error = String(error.message ?? error).slice(0, 800);
this.store.save(session, { type: 'context.' + record.status, detail: { recordId: record.id } });
@@ -482,10 +482,13 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
const runModel = store.owned('run', plan.runId, session.id).model;
if(plan.tokenReservation)verifyModelReservation(store,session,plan.taskId,{...store.owned('run',plan.runId,session.id).model,
modelRouting:store.owned('run',plan.runId,session.id).model.routing},body,plan.tokenReservation);
const invalidOutput = body.kind === 'model-route-plan' && runModel.capacityMode === 'model'
// Passthrough can carry explicit native output settings and Messages' required
// max_tokens without a local reservation. The wire SHA and frozen budget are
// still checked below; a protocol field is not a local budget.
const invalidOutput = !isPassthrough(runModel) && (body.kind === 'model-route-plan' && runModel.capacityMode === 'model'
? body.variants.some(variant => outputReservation(variant.body) !== runModel.routing?.members.find(member => member.id === variant.connectionId)?.maxOutputTokens)
|| Math.max(...requestVariants(body).map(outputReservation)) !== plan.budget.outputReservation
: requestVariants(body).some(value => outputReservation(value) !== plan.budget.outputReservation);
: requestVariants(body).some(value => outputReservation(value) !== plan.budget.outputReservation));
if (metrics.bytes !== plan.requestBytes || metrics.estimatedInputTokens !== plan.estimatedInputTokens
|| invalidOutput || plan.budget.inputBudget !== null && metrics.estimatedInputTokens > plan.budget.inputBudget) throw new Error('请求预算与原正文不匹配。');
historyGroups(requestHistory(body));
+6
View File
@@ -1,5 +1,6 @@
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
import { ModelRequestError } from '../../server/diagnostics.mjs';
import { withTokenAccounting } from '../../shared/contracts/model-usage.mjs';
export const protocolFailure = (message, kind = 'protocol', extra = null) => new ModelRequestError({ kind, source: 'model_connection', origin: 'local', stage: 'model_request',
title: '模型响应未通过完整性核对', message, retryable: false, occurredAt: new Date().toISOString(), ...(extra ? extra : {}) });
@@ -12,6 +13,10 @@ export const outputTruncatedFailure = (kind = 'protocol') => protocolFailure(OUT
export { protocolRoute } from '../../shared/contracts/model-endpoint.mjs';
export function reportedUsage(config, value) {
return withTokenAccounting(baseReportedUsage(config, value));
}
function baseReportedUsage(config, value) {
const raw = value?.usage;
if (!raw || typeof raw !== 'object') return null;
if (config.protocol === 'anthropic-messages') {
@@ -30,6 +35,7 @@ export function reportedUsage(config, value) {
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;
if (!valid(raw.total_tokens) && !valid(input + 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;