fix(models): retain upstream identity and pause strict mismatches

This commit is contained in:
Agent Workbench Dev
2026-11-03 11:53:07 +08:00
parent 410b347894
commit 3659f5e858
25 changed files with 427 additions and 35 deletions
+13 -1
View File
@@ -11,6 +11,7 @@ import { currentBrowserVerification, verifyBrowserJob } from './browser/browser-
import { TaskPlanManager } from './tasks/task-plan-manager.mjs';
import { FileResults } from './tasks/file-results.mjs';
import { taskContract } from '../shared/contracts/task-control.mjs';
import { modelIdentityLabel } from '../shared/contracts/model-identity.mjs';
const labels = { verified_committed: '检查通过并已提交', verified_uncommitted: '检查通过,等待提交', needs_review: '等待改动或交付审查',
existing_verified: '当前成果已核对,无新增修改', files_delivered: '当前文件已交付,按约定未测试', needs_results: '当前文件成果仍需核对',
@@ -143,6 +144,7 @@ export class DeliveryReporter {
source: { fingerprint: inspection.sourceFingerprint, scope: inspection.scope, gitHead: inspection.git.head, branch: inspection.git.branch },
runs: [...this.store.core.run.values()].filter(value => value.taskId === taskId).map(value => ({ id: value.id, resumeOf: value.resumeOf,
engine: value.engine, status: value.status, model: value.model, startedAt: value.startedAt, finishedAt: value.finishedAt, usage: value.usage, stopReason: value.stopReason,
consumption: structuredClone(value.consumption ?? []),
...(value.workspaceIdentity ? { workspaceIdentity: value.workspaceIdentity } : {}) })),
usage: { ...task.usage, priceStatus: 'not_configured', amount: null, currency: null },
changes: changes.map(value => ({ id: value.id, path: value.path, status: value.status, reason: value.reason, baseSha256: value.baseSha256,
@@ -246,9 +248,19 @@ export function renderDeliveryMarkdown(report) {
if (!report.deliveries.length) lines.push('尚无内置Git提交记录。');
for (const delivery of report.deliveries) lines.push('- ' + delivery.status + ' · ' + (delivery.commit ?? '实际结果未确认') + ' · ' + delivery.paths.join(', '),
' ' + (delivery.summary ?? ''));
lines.push('', '## 模型与用量', '', '| Run | 模型 | 状态 | 已报告tokens |', '| --- | --- | --- | --- |');
lines.push('', '## 模型与用量', '', 'Run型号为启动配置;每次实际发送与返回型号见下表。型号标识或登记映射不认证底层模型权重。', '', '| Run | 启动型号 | 状态 | 已报告tokens |', '| --- | --- | --- | --- |');
for (const run of report.runs) lines.push('| ' + [run.id, run.model?.mode === 'demo' ? '离线固定演示' : run.model?.model ?? '未记录',
run.status, run.usage?.totalTokens ?? 0].map(escapeCell).join(' | ') + ' |');
lines.push('', '| 尝试 | 请求型号 | 上游报告型号 | 核对结果 | 原响应 SHA256 |', '| --- | --- | --- | --- | --- |');
for (const run of report.runs) {
for (const receipt of run.consumption ?? []) {
const identity = receipt.modelIdentity;
lines.push('| ' + [receipt.attemptId, identity?.requestedModel ?? receipt.model ?? '未记录', identity?.reportedModels?.join(', ') || '未记录',
modelIdentityLabel(identity), identity?.responseSource?.sha256 ?? '未记录'].map(escapeCell).join(' | ') + ' |');
if (identity?.mapping) lines.push('', '用户登记的映射依据:' + escapeCell(identity.mapping.source));
}
if (!run.consumption?.length && run.usage?.requests) lines.push('', 'Run ' + run.id + ' 的历史记录未保存返回型号核对,不能从启动配置补推。');
}
lines.push('', '累计已报告:' + (report.usage.totalTokens ?? 0) + ' tokens;未报告请求:' + (report.usage.unknownRequests ?? 0) + '。费用:未知。', '', '## 尚待确认', '');
if (report.contextPlans?.length) {
const at = lines.length - 2;
+17 -1
View File
@@ -12,6 +12,7 @@ import { completionBody, requestMetrics } from '../../shared/contracts/model-req
import { workerForSession } from '../../shared/contracts/workers.mjs';
import { selectPurgeStrategy, assertPurgeModelInput } from './purge-strategy.mjs';
import { engineHistoryGroups,engineContextEvidence,engineContextIndex,engineContextView,engineSeedPrompt } from '../../shared/contracts/engine-context.mjs';
import { sanitizeModelText } from '../models/upstream-error.mjs';
const at = () => new Date().toISOString();
const deferred = () => {
@@ -249,10 +250,23 @@ class EngineRunDriver {
dispatched = true;
const response = await this.provider.complete(selected, messages, this.run.project, signal, progress => {
if (progress.consumption) {
if (progress.consumption.modelIdentity) request.modelIdentity = modelEvent.modelIdentity = progress.consumption.modelIdentity;
const recorded = this.store.recordConsumption(this.session, this.run.record, { ...progress.consumption, requestId: request.id }, estimate);
if (recorded) request.accountedAttempts++;
this.save('model_consumption'); return;
}
if (progress.streamCapture !== undefined || progress.responseCapture !== undefined) {
const raw = progress.streamCapture ?? progress.responseCapture, decoded = raw.toString('utf8');
const redacted = sanitizeModelText(decoded, value => this.provider.redact(value));
const artifact = this.store.artifactStore.write(this.session, this.run.record, redacted === decoded ? raw : Buffer.from(redacted, 'utf8'),
{ kind: progress.streamCapture !== undefined ? 'model-stream-response' : 'model-http-response', mediaType: 'text/plain' });
this.store.core.artifact.set(artifact.id, artifact);
if (progress.modelIdentity) progress.modelIdentity.responseSource = { artifactId: artifact.id, sha256: artifact.sha256, sessionId: this.session.id,
scope: progress.streamCapture !== undefined ? 'sse-stream' : 'http-body' };
if (progress.upstream) Object.assign(progress.upstream, { artifactId: artifact.id, artifactSha256: artifact.sha256, sessionId: this.session.id });
this.save('model_response_source'); return;
}
if (progress.modelIdentity) request.modelIdentity = modelEvent.modelIdentity = progress.modelIdentity;
if (progress.phase === 'running') {
const attempt = progress.attempt ?? 1;
if (!Number.isSafeInteger(attempt) || attempt < 1 || attempt > request.maxAttempts) throw engineError('模型尝试超出原引擎封存预算。');
@@ -288,7 +302,9 @@ class EngineRunDriver {
if (dispatched) while (request.accountedAttempts < request.actualAttemptsFinal) {
request.accountedAttempts++; this.store.recordResponse(this.session, this.run.record, null, request.reservedPerAttempt);
}
request.status = signal.aborted ? 'interrupted' : 'failed'; request.error = this.provider.redact(error.message); request.finishedAt = at(); this.save('model_failed');
request.status = signal.aborted ? 'interrupted' : 'failed'; request.error = this.provider.redact(error.message);
if (error.diagnostic) request.diagnostic = JSON.parse(this.provider.redact(JSON.stringify(error.diagnostic)));
request.finishedAt = at(); this.save('model_failed');
const event = this.session.events.find(value => value.id === request.eventId);
if (event) { event.phase = request.status; event.finishedAt = at(); event.output = request.error; this.save('model_event_failed'); }
}
+8 -3
View File
@@ -8,6 +8,7 @@ import { actualRequest, requestVariants } from '../../shared/contracts/model-req
import { modelWaitSettings } from './request-deadline.mjs';
import { sanitizeModelText } from './upstream-error.mjs';
import { nativeParameterSettings } from '../../shared/contracts/native-parameters.mjs';
import { modelIdentitySettings } from '../../shared/contracts/model-identity.mjs';
const legacyId = 'legacy-default';
const stamp = () => new Date().toISOString();
@@ -178,7 +179,7 @@ export class ModelHub {
const name = label(input.name), model = label(input.model, 200);
if (!name || !model) throw error('请填写连接名称和实际模型名称。');
const connection = { id: previous?.id ?? randomUUID(), name, brand: label(input.brand || '自定义', 40), protocol, model,
capabilitySchema: 1, capabilityDeclarations: declarations, streaming, ...(native ?? {}),
capabilitySchema: 1, capabilityDeclarations: declarations, streaming, ...(native ?? {}), ...modelIdentitySettings(input, previous ?? {}),
baseUrl: 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),
concurrency: bounded(input.concurrency, 1, 1, 8), revision: (previous?.revision ?? 0) + 1,
@@ -325,9 +326,11 @@ export class ModelHub {
}
this.attempts.push(attempt); this.saveAttempts();
const progress = event => {
if (event.modelIdentity) attempt.modelIdentity = event.modelIdentity;
if (event.wireAttemptId) attempt.wireAttemptId = event.wireAttemptId;
if (event.upstreamResponse) attempt.upstreamResponse = event.upstreamResponse;
if (event.consumption) {
if (event.consumption.modelIdentity) attempt.modelIdentity = event.consumption.modelIdentity;
attempt.usage = event.consumption.usage; attempt.usageStatus = event.consumption.usageStatus;
onProgress?.({ consumption: { ...event.consumption, wireAttemptId: event.consumption.attemptId, attemptId: attempt.id,
connectionId: member.id, connectionName: member.name }, connectionId: member.id, model: member.model, modelAttemptId: attempt.id });
@@ -343,6 +346,8 @@ export class ModelHub {
const artifact = this.store.artifactStore.write(session, run, captured, { kind: event.streamCapture !== undefined ? 'model-stream-response' : 'model-http-response',
mediaType: event.streamCapture !== undefined ? 'text/event-stream' : 'text/plain' });
this.store.core.artifact.set(artifact.id, artifact); attempt.responseArtifactId = artifact.id;
if (attempt.modelIdentity) attempt.modelIdentity.responseSource = { artifactId: artifact.id, sha256: artifact.sha256, sessionId: session.id,
scope: event.streamCapture !== undefined ? 'sse-stream' : 'http-body' };
attempt.responseSha256 = artifact.sha256; attempt.responseRedacted = redacted !== decoded || event.upstream?.capture?.redacted === true; this.store.save(session);
if (event.upstream) Object.assign(event.upstream, { artifactId: artifact.id, artifactSha256: artifact.sha256,
artifactScope: event.streamCapture !== undefined ? 'sse-stream' : 'http-body', sessionId: session.id });
@@ -355,7 +360,7 @@ export class ModelHub {
if (event.stream) attempt.stream = event.stream;
onProgress?.({ ...event, attempt: count, maxAttempts: routing.maxAttempts, connectionId: member.id, connectionName: member.name, protocol: modelProtocol(member.protocol), model: member.model, modelAttemptId: attempt.id });
};
const result = await execute({ ...config, baseUrl: member.baseUrl, model: member.model, protocol: modelProtocol(member.protocol), streaming: member.streaming === true }, credential?.key ?? '', actualBody, progress);
const result = await execute({ ...config, ...modelIdentitySettings(member), baseUrl: member.baseUrl, model: member.model, protocol: modelProtocol(member.protocol), streaming: member.streaming === true }, credential?.key ?? '', actualBody, progress);
attempt.status = 'completed'; attempt.usage = result.usage ?? attempt.usage; attempt.usageStatus = attempt.usage ? 'reported' : 'unknown';
if (result.compatibility?.length) attempt.compatibility = result.compatibility;
this.health.set(this.identity(member), { state: 'responded', lastSuccessAt: stamp(), cooldownUntil: 0, failures: 0 });
@@ -371,7 +376,7 @@ export class ModelHub {
// the attempt, release its lease, and leave the connection eligible.
this.health.set(this.identity(member), { ...health, state: 'interrupted', lastInterruptedAt: stamp() });
} else {
const blocked = [401, 403].includes(attempt.httpStatus) || diagnostic?.kind === 'quota';
const blocked = [401, 403].includes(attempt.httpStatus) || ['quota', 'model_identity'].includes(diagnostic?.kind);
const failedAt = Date.now();
this.health.set(this.identity(member), { state: blocked ? 'needs_attention' : 'failed', blocked, lastFailureAt: new Date(failedAt).toISOString(),
failures: (health.failures ?? 0) + 1, cooldownUntil: failedAt + (diagnostic?.retryAfterMs ?? Math.min(60000, 1000 * 2 ** Math.min(health.failures ?? 0, 5))), reason: attempt.reason });
+2 -1
View File
@@ -5,7 +5,7 @@ import { upstreamCapture } from './upstream-error.mjs';
// Only a fully terminated and validated stream produces a dispatchable message.
// Progress is cumulative, bounded and explicitly not a tool invocation.
export async function readModelStream(response, config, signal, onProgress, tools, onBytes, redact = String) {
export async function readModelStream(response, config, signal, onProgress, tools, onBytes, redact = String, observeIdentity) {
if (!response.headers.get('content-type')?.toLowerCase().includes('text/event-stream') || !response.body) throw protocolFailure('服务未返回所选协议的事件流,请核对流式配置。');
const reader = response.body.getReader(), decoder = new TextDecoder('utf-8', { fatal: true }), hash = createHash('sha256');
const chunks = [];
@@ -33,6 +33,7 @@ export async function readModelStream(response, config, signal, onProgress, tool
if (raw === '[DONE]') { if (config.protocol === 'responses') throw protocolFailure('Responses缺少正式终结事件。'); done = true; return; }
let event;
try { event = JSON.parse(raw); } catch { throw protocolFailure('模型事件流包含无效JSON。'); }
observeIdentity?.(event);
if (event.usage) usage = event.usage;
const failUpstream = () => {
usage = event.response?.usage ?? usage;