Files
Agent-Workbench/src/shared/contracts/research.mjs
T

86 lines
6.9 KiB
JavaScript

import fs from 'node:fs';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { ceiling } from './execution-policy.mjs';
export const MAXIMUM_RESEARCH_BYTES = 512 * 1024 * 1024;
export const RESEARCH_ACTIVE = new Set(['queued', 'connecting', 'analyzing', 'stopping']);
export const researchError = (message, status = 409) => Object.assign(new Error(message), { status });
export async function researchFileIdentity(filename, { signal, config = {} } = {}) {
if (typeof filename !== 'string' || !filename.trim() || filename.length > ceiling(config, 3000) || filename.includes('\0')) throw researchError('需要一个本地工件的完整路径。', 400);
const input = filename.trim().replace(/^"(.*)"$/, '$1');
if (!path.isAbsolute(input)) throw researchError('研究工件路径需要是绝对路径。', 400);
const initial = await fs.promises.lstat(input);
if (!initial.isFile() || initial.isSymbolicLink()) throw researchError('首批研究入口支持常规ASAR、EXE和DLL文件。', 400);
const resolved = await fs.promises.realpath(input), before = await fs.promises.stat(resolved);
if (!['.asar', '.exe', '.dll'].includes(path.extname(resolved).toLowerCase())) throw researchError('当前入口支持ASAR、EXE和DLL工件。', 400);
if (before.size > ceiling(config, MAXIMUM_RESEARCH_BYTES)) throw researchError('工件超过当前512MiB登记上限。', 400);
const hash = createHash('sha256'); let bytes = 0;
for await (const chunk of fs.createReadStream(resolved, { signal })) { bytes += chunk.length; if (bytes > ceiling(config, MAXIMUM_RESEARCH_BYTES)) throw researchError('工件读取期间超过登记上限。'); hash.update(chunk); }
const after = await fs.promises.stat(resolved);
if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ino !== after.ino || bytes !== before.size) throw researchError('工件在登记期间变化,需要按新版本重新登记。');
return { path: resolved, sha256: hash.digest('hex'), bytes, modifiedAt: after.mtime.toISOString(), extension: path.extname(resolved).toLowerCase() };
}
export function bindReaEvidence(result, target, operation) {
if (!result || result.isError === true || !result.structuredContent) throw researchError('REA没有返回完整可核验的Evidence;原响应和限制已保存。');
const evidence = result.structuredContent;
if (!/^ev_[a-f0-9]{64}$/.test(evidence.evidence_id ?? '') || evidence.operation !== operation || !evidence.normalized_result) throw researchError('REA Evidence身份或操作不匹配。');
const normalized = evidence.normalized_result;
const candidates = [normalized.root_artifact_sha256, normalized.artifact_sha256, normalized.sha256,
normalized.file_sha256, evidence.subject?.artifact_sha256, evidence.subject?.sha256, evidence.subject?.digest?.sha256];
if (!candidates.includes(target.sha256)) throw researchError('REA Evidence不能与登记工件SHA256核对。');
return { evidenceId: evidence.evidence_id, operation: evidence.operation, targetSha256: target.sha256,
summary: normalized.summary ?? null, statistics: normalized.statistics ?? null,
limitations: [...new Set([...(evidence.limitations ?? []), ...(normalized.limitations ?? [])].map(item => typeof item === 'string' ? item : JSON.stringify(item)))],
authority: evidence.authority, confidence: evidence.confidence,
scope: 'static-artifact-analysis; no target execution', verified: true };
}
export const researchTargetContract = target => ({ schemaVersion: 1, id: target.id, sessionId: target.sessionId,
projectId: target.projectId, taskId: target.taskId, runId: target.runId, path: target.path, sha256: target.sha256,
bytes: target.bytes, extension: target.extension, label: target.label, source: target.source, registeredAt: target.registeredAt });
export function researchPointer(value, pointer = '/normalized_result', config = {}) {
if (typeof pointer !== 'string' || pointer.length > ceiling(config, 400) || !pointer.startsWith('/') || pointer.split('/').length > ceiling(config, 12)) throw researchError('Evidence字段需要有效JSON Pointer。', 400);
for (const raw of pointer.slice(1).split('/')) {
if (/~(?:[^01]|$)/.test(raw)) throw researchError('Evidence字段转义无效。', 400);
const key = raw.replace(/~1/g, '/').replace(/~0/g, '~');
if (['__proto__', 'prototype', 'constructor'].includes(key) || value === null || typeof value !== 'object' || !Object.hasOwn(value, key)) throw researchError('原Evidence没有这个字段。', 404);
value = value[key];
}
return value;
}
export function sealResearchDocument(store, session, run, text, kind) {
const bytes = Buffer.byteLength(text, 'utf8');
if (bytes > ceiling(store, 64 * 1024 * 1024)) throw researchError('完整研究证据超过当前64MiB接收范围。');
const parts = [];
for (let start = 0; start < text.length;) {
let end = Math.min(text.length, start + 500000);
if (end < text.length && /[\uD800-\uDBFF]/.test(text[end - 1]) && /[\uDC00-\uDFFF]/.test(text[end])) end--;
const artifact = store.artifactStore.write(session, run, text.slice(start, end), { kind: kind + '-part', mediaType: 'text/plain' });
store.core.artifact.set(artifact.id, artifact); parts.push({ id: artifact.id, sha256: artifact.sha256, bytes: artifact.bytes }); start = end;
}
const manifest = { schemaVersion: 1, kind: 'research-document', documentKind: kind, bytes,
sha256: createHash('sha256').update(text, 'utf8').digest('hex'), parts };
const artifact = store.artifactStore.write(session, run, manifest, { kind }); store.core.artifact.set(artifact.id, artifact);
return { id: artifact.id, sha256: artifact.sha256, documentSha256: manifest.sha256, bytes };
}
export function readResearchDocument(store, session, reference) {
const artifact = store.owned('artifact', reference.id, session.id);
if (artifact.sha256 !== reference.sha256) throw researchError('研究证据清单与封存引用不匹配。');
const manifest = JSON.parse(store.artifactStore.read(artifact));
if (manifest.kind !== 'research-document' || manifest.schemaVersion !== 1 || !Array.isArray(manifest.parts) || manifest.parts.length > ceiling(store, 160)
|| manifest.bytes > ceiling(store, 64 * 1024 * 1024) || manifest.bytes !== reference.bytes || manifest.sha256 !== reference.documentSha256) throw researchError('研究证据清单无效。');
const parts = manifest.parts.map(part => {
const source = store.owned('artifact', part.id, session.id);
if (source.taskId !== artifact.taskId || source.runId !== artifact.runId || source.sha256 !== part.sha256 || source.bytes !== part.bytes) throw researchError('研究证据分片的来源不匹配。');
return store.artifactStore.read(source);
});
const text = parts.join('');
if (Buffer.byteLength(text, 'utf8') !== manifest.bytes || createHash('sha256').update(text, 'utf8').digest('hex') !== manifest.sha256) throw researchError('研究证据全文校验失败。');
return text;
}