import { engineError, engineCanonicalDigest as controlledDigest } from './engines.mjs'; import { completionBody, requestMetrics, requestVariants, outputReservation } from './model-request.mjs'; import { engineContextIndex,engineContextEvidence,engineContextView,engineSeedPrompt } from './engine-context.mjs'; import { verifyModelReservation } from './model-reservation.mjs'; export const ENGINE_RUN_ACTIVE = new Set(['queued', 'starting', 'initializing', 'running', 'waiting_tool', 'closing', 'stopping']); export function selectedEngineInput(input) { if (!input || typeof input !== 'object' || Array.isArray(input) || Object.keys(input).some(key => !['id', 'root', 'controlledSha256', 'strategy'].includes(key)) || input.id !== 'deepseek-harness' || typeof input.root !== 'string' || !/^[a-f0-9]{64}$/.test(input.controlledSha256 ?? '')) throw engineError('请选择已经检测并封存身份的受控DeepSeek引擎。', 400); return structuredClone(input); } export function engineRunInput(job) { return { schemaVersion: 1, id: job.id, sessionId: job.sessionId, projectId: job.projectId, taskId: job.taskId, runId: job.runId, workerId: job.workerId, collaborationId: job.collaborationId, installation: job.installation, sdkSessionId: job.sdkSessionId, directory: job.directory, model: job.model, budget: job.budget, tools: job.tools, sourceContextPlanId: job.sourceContextPlanId, sourceRequestSha256: job.sourceRequestSha256, ...(job.seedContext?{seedContext:job.seedContext}:{}) }; } export function engineRunReport(job) { return { schemaVersion: 1, owner: { sessionId: job.sessionId, projectId: job.projectId, taskId: job.taskId, runId: job.runId, jobId: job.id }, inputSha256: job.inputSha256, installationSha256: job.installation.controlledSha256, sdkSessionId: job.sdkSessionId, outcome: job.originalOutcome, native: job.native, requests: job.requests, calls: job.calls, ...(job.reviewHandoff ? { reviewHandoff: job.reviewHandoff } : {}), ...(job.inputRejections?{inputRejections:job.inputRejections}:{}) }; } export function publicEngineRun(job) { const { native, requests, calls, ...view } = job; return { ...view, nativeSummary: { status: native?.status ?? null, pid: native?.process?.pid ?? job.pid ?? null, rootExited: native?.cleanup?.rootExited ?? null, treeConfirmed: native?.cleanup?.treeConfirmed ?? null, receipt: native?.receipt ?? null, notifications: native?.notifications?.length ?? job.notificationCount ?? 0 }, modelRequests: requests?.length ?? 0, toolRequests: calls?.length ?? 0 }; } export function verifyEngineInput(store, session, job) { store.owned('engine_run', job.id, session.id); const input = store.owned('artifact', job.inputArtifactId, session.id); if (input.kind !== 'engine-run-input' || input.taskId !== job.taskId || input.runId !== job.runId || input.sha256 !== job.inputSha256 || store.artifactStore.read(input) !== JSON.stringify(engineRunInput(job))) throw engineError('受控引擎与原任务/范围/程序输入不一致。'); if(job.seedContext){ const artifact=store.owned('artifact',job.seedContext.artifactId,session.id),seed=JSON.parse(store.artifactStore.read(artifact)); const config={...job.model,modelRouting:job.model.routing}; if(job.seedContext.schemaVersion!==1||artifact.kind!=='engine-seed-context'||artifact.taskId!==job.taskId||artifact.runId!==job.runId||artifact.sha256!==job.seedContext.sha256 ||seed.schemaVersion!==1||seed.sourceContextPlanId!==job.sourceContextPlanId||seed.sourceRequestSha256!==job.sourceRequestSha256 ||seed.prompt!==engineSeedPrompt(seed.messages)||requestMetrics(completionBody(config,seed.messages,job.tools)).sha256!==job.sourceRequestSha256)throw engineError('原生任务种子与外层请求来源不一致。'); } return input; } export function originalEngineRun(store, session, job) { verifyEngineInput(store, session, job); const artifact = store.owned('artifact', job.reportArtifactId, session.id); if (artifact.kind !== 'engine-run-report' || artifact.taskId !== job.taskId || artifact.runId !== job.runId || artifact.sha256 !== job.reportSha256) { throw engineError('受控引擎原报告身份无效。'); } const bytes = store.artifactStore.read(artifact); if (bytes !== JSON.stringify(engineRunReport(job))) throw engineError('受控引擎原报告与当前账本不一致。'); return bytes; } export function verifyEngineModelInput(store, session, job, request) { if(job.seedContext)verifyEngineInput(store,session,job); const artifact = store.owned('artifact', request.inputArtifactId, session.id); if (artifact.kind !== 'engine-model-input' || artifact.taskId !== job.taskId || artifact.runId !== job.runId || artifact.sha256 !== request.inputSha256) throw engineError('原引擎模型输入工件归属无效。'); const input = JSON.parse(store.artifactStore.read(artifact)), metrics = requestMetrics(input.body); for (const key of ['id', 'bridgeTraceId', 'sourceSha256', 'requestSha256', 'requestBytes', 'estimatedInputTokens', 'reservedPerAttempt', 'maxAttempts']) { if (input.plan[key] !== request[key]) throw engineError('原引擎模型请求或尝试预算与封存输入不一致。'); } if(request.contextViewVersion!==undefined&&(request.contextViewVersion!==1||input.plan.contextViewVersion!==request.contextViewVersion||!input.view))throw engineError('原生模型上下文视图版本缺失或不匹配。'); if(request.reservationVersion!==undefined){ if(request.reservationVersion!==1||input.plan.reservationVersion!==1||controlledDigest(request.tokenReservation)!==controlledDigest(input.plan.tokenReservation))throw engineError('原生用量预留版本或输入不一致。'); verifyModelReservation(store,session,job.taskId,{...job.model,modelRouting:job.model.routing},input.body,request.tokenReservation); }else if(input.plan.reservationVersion!==undefined||input.plan.tokenReservation!==undefined)throw engineError('原生用量预留版本缺失。'); if (input.owner.sessionId !== job.sessionId || input.owner.taskId !== job.taskId || input.owner.runId !== job.runId || input.owner.projectId !== job.projectId || controlledDigest(input.native) !== request.sourceSha256 || metrics.sha256 !== request.requestSha256 || metrics.bytes !== request.requestBytes || !Number.isSafeInteger(request.maxAttempts) || request.maxAttempts < 1 || request.maxAttempts > 8 || (job.model.capacityMode !== 'passthrough' && (!Number.isSafeInteger(input.native.maxTokens) || input.native.maxTokens < 1)) || !requestVariants(input.body).every(body => outputReservation(body) === (job.model.capacityMode === 'passthrough' ? null : input.native.maxTokens)) || request.reservedPerAttempt !== (request.reservationVersion===1?request.tokenReservation.reservedTokens:metrics.estimatedInputTokens + 128 + input.native.maxTokens)) throw engineError('原引擎模型输入、归属或预算核对失败。'); if(input.view){ const view=input.view,source=store.owned('artifact',view.sourceArtifactId,session.id),sourceValue=JSON.parse(store.artifactStore.read(source)); if(view.schemaVersion!==1||sourceValue.schemaVersion!==1||source.kind!=='engine-native-input'||source.taskId!==job.taskId||source.runId!==job.runId||source.sha256!==view.sourceSha256 ||controlledDigest(sourceValue.native)!==request.sourceSha256||controlledDigest(sourceValue.owner)!==controlledDigest(input.owner))throw engineError('原生上下文来源或视图身份不匹配。'); const messages=nativeMessagesToChat(input.native);let index=null,reference={id:null,sha256:null}; if(job.seedContext){ const seed=JSON.parse(store.artifactStore.read(store.owned('artifact',job.seedContext.artifactId,session.id))); if(messages.find(message=>message.role==='user')?.content!==seed.prompt)throw engineError('原生输入未承载原任务种子。'); } if(view.indexArtifactId){ reference=store.owned('artifact',view.indexArtifactId,session.id);index=JSON.parse(store.artifactStore.read(reference)); const expected=engineContextIndex(messages,engineContextEvidence(store,session,job,messages),{artifact_id:source.id,sha256:source.sha256,owner:input.owner}); if(reference.kind!=='engine-history-index'||reference.taskId!==job.taskId||reference.runId!==job.runId||reference.sha256!==view.indexSha256 ||controlledDigest(index)!==controlledDigest(expected))throw engineError('原生历史索引与实际工具依据不符。'); } const config={...job.model,modelRouting:job.model.routing,maxOutputTokens:input.native.maxTokens}; const projected=engineContextView(messages,input.native.tools.map(tool=>({type:'function',function:tool})),config,index,reference); const expectedView={schemaVersion:1,mode:projected.mode,sourceArtifactId:source.id,sourceSha256:source.sha256, indexArtifactId:projected.indexArtifactId,indexSha256:projected.indexSha256,beforeInputTokens:projected.before.estimatedInputTokens, inputBudget:projected.inputBudget,safetyTokens:projected.safetyTokens,retainedGroups:projected.retainedGroups,archivedGroups:projected.archivedGroups}; if(controlledDigest(view)!==controlledDigest(expectedView)||controlledDigest(projected.body)!==controlledDigest(input.body) ||projected.inputBudget!==null&&projected.metrics.estimatedInputTokens>projected.inputBudget)throw engineError('原生上下文发送视图或预算不匹配。'); } return input; } export function assertEngineWorkerResult(store, session, worker) { if (!worker.engine) return; const job = [...store.core.engine_run.values()].findLast(value => value.sessionId === session.id && value.runId === worker.currentRunId); if (!job || job.status !== 'completed' || job.requiresVerification || !job.verified || job.installation.controlledSha256 !== worker.engine.controlledSha256) throw engineError('原引擎运行缺少完整协议、停止和账本依据。'); originalEngineRun(store, session, job); if (job.calls.some(call => call.status !== 'returned' || !call.invocationId) || job.requests.some(request => request.status !== 'completed')) throw engineError('引擎原调用或模型请求尚未完整核对。'); for (const call of job.calls) { const tool = store.owned('tool', call.invocationId, session.id), result = store.savedToolResult(session.id, call.callId); if (tool.runId !== job.runId || tool.callId !== call.callId || tool.requiresVerification || controlledDigest(result) !== call.resultSha256) { throw engineError('引擎原工具结果与自有执行账本不一致。'); } const artifact = store.owned('artifact', call.outputArtifactId, session.id); if (artifact.kind !== 'engine-tool-output' || artifact.taskId !== job.taskId || artifact.runId !== job.runId || artifact.sha256 !== call.outputSha256 || store.artifactStore.read(artifact) !== JSON.stringify(result)) throw engineError('反馈给原引擎的工具结果工件不一致。'); } for (const request of job.requests) { verifyEngineModelInput(store, session, job, request); const artifact = store.owned('artifact', request.responseArtifactId, session.id); if (artifact.kind !== 'engine-model-output' || artifact.taskId !== job.taskId || artifact.runId !== job.runId || artifact.sha256 !== request.responseSha256 || !JSON.parse(store.artifactStore.read(artifact)).message || request.accountedAttempts !== request.actualAttemptsFinal) throw engineError('原引擎模型输出或尝试账本未完整核对。'); } } export function nativeMessagesToChat(input) { if (!input || !Array.isArray(input.messages)) throw engineError('原引擎模型输入没有消息数组。'); const messages = input.messages.map(message => { if (!message || !['system', 'developer', 'user', 'assistant', 'tool'].includes(message.role) || !Array.isArray(message.content)) { throw engineError('原引擎消息不符合已验证的文本协议。'); } const text = [], calls = []; for (const block of message.content) { if (block?.type === 'text' && typeof block.text === 'string') text.push(block.text); else if (block?.type === 'reasoning' && typeof block.text === 'string') { // Reasoning is not promoted into user-visible text or a tool request. } else if (block?.type === 'tool-call' && message.role === 'assistant' && typeof block.id === 'string' && typeof block.name === 'string' && typeof block.arguments === 'string') { JSON.parse(block.arguments); calls.push({ id: block.id, type: 'function', function: { name: block.name, arguments: block.arguments } }); } else throw engineError('当前受控桥只接入文本和完整工具调用,原内容类型尚未验证。'); } if (message.role === 'tool') { if (typeof message.toolCallId !== 'string' || !message.toolCallId) throw engineError('原工具消息缺少toolCallId。'); return { role: 'tool', tool_call_id: message.toolCallId, content: text.join('') }; } return { role: message.role, content: text.join(''), ...(calls.length ? { tool_calls: calls } : {}) }; }); if (input.system !== null && input.system !== undefined) { if (typeof input.system !== 'string') throw engineError('原单次系统提示格式无效。'); messages.unshift({ role: 'system', content: input.system }); } return messages; }