import fs from 'node:fs'; import path from 'node:path'; import { createHash, randomUUID } from 'node:crypto'; import { McpStdio } from './mcp-stdio.mjs'; export const REA_VERSION = '6.8.0'; export const REA_PROTOCOL = '2025-03-26'; export const REA_OPERATIONS = { javascript: { name: 'analyze_javascript_application', extensions: ['.asar'], label: 'JavaScript / Electron静态分析' }, 'pe-imports': { name: 'inspect_pe_imports', extensions: ['.exe', '.dll'], label: 'PE导入表' }, 'pe-resources': { name: 'inspect_pe_resources', extensions: ['.exe', '.dll'], label: 'PE静态资源' }, }; const sha = bytes => createHash('sha256').update(bytes).digest('hex'); const fileIdentity = filename => ({ path: fs.realpathSync.native(filename), sha256: sha(fs.readFileSync(filename)) }); const canonical = value => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])])) : value; export const schemaDigest = value => sha(Buffer.from(JSON.stringify(canonical(value)))); export function resolveReaInstallation(appDirectory = process.cwd(), { packageRoot = process.env.AGENT_WORKBENCH_REA_PACKAGE_ROOT } = {}) { const candidates = []; if (packageRoot) candidates.push(path.resolve(packageRoot)); else for (let root = path.resolve(appDirectory), depth = 0; depth < 8; depth++) { candidates.push(path.join(root, 'runtime/node_modules/rea-agents')); const next = path.dirname(root); if (next === root) break; root = next; } for (const root of candidates) { const metadata = path.join(root, 'package.json'), entry = path.join(root, 'scripts/rea.mjs'); if (!fs.existsSync(metadata) || !fs.existsSync(entry)) continue; try { const pkg = JSON.parse(fs.readFileSync(metadata, 'utf8')); if (pkg.name !== 'rea-agents' || pkg.version !== REA_VERSION) return { status: 'unsupported', declaredVersion: pkg.version, message: '当前接入契约固定REA ' + REA_VERSION + ';需要核对新版本工具契约后再接入。' }; return { status: 'available', version: pkg.version, packageRoot: fs.realpathSync.native(root), entry: fileIdentity(entry), metadata: fileIdentity(metadata), protocolVersion: REA_PROTOCOL, mcpEntry: fs.existsSync(path.join(root, 'dist/mcp/main.js')) ? fileIdentity(path.join(root, 'dist/mcp/main.js')) : null, node: { path: process.execPath, version: process.versions.node }, inputSchemaProfile: 'compact', outputSchemaProfile: 'off', operations: Object.entries(REA_OPERATIONS).map(([id, value]) => ({ id, ...value })), identityScope: 'package declaration, entry files and actual MCP handshake; not a full installation equivalence claim' }; } catch (error) { return { status: 'unavailable', message: 'REA安装身份无法读取:' + error.message }; } } return { status: 'missing', message: '未找到本地REA ' + REA_VERSION + '。可设置AGENT_WORKBENCH_REA_PACKAGE_ROOT后重新检测。', operations: Object.entries(REA_OPERATIONS).map(([id, value]) => ({ id, ...value })) }; } export class ReaAdapter { constructor(installation, { cwd, onClient = () => {}, timeoutMs = 45000 } = {}) { this.installation = installation; this.cwd = cwd; this.onClient = onClient; this.timeoutMs = timeoutMs; } async connect(signal) { if (this.installation.status !== 'available') throw new Error(this.installation.message ?? 'REA尚未就绪。'); for (const identity of [this.installation.entry, this.installation.metadata, this.installation.mcpEntry].filter(Boolean)) { if (fileIdentity(identity.path).sha256 !== identity.sha256) throw new Error('REA入口身份在准备后变化,请重新检测接入契约。'); } const allowed = /^(path|pathext|systemroot|systemdrive|windir|comspec|temp|tmp|userprofile|appdata|localappdata|programfiles(?:\(x86\))?|homedrive|homepath)$/i; const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => allowed.test(name))); Object.assign(env, { REA_MCP_INPUT_SCHEMA_PROFILE: 'compact', REA_MCP_OUTPUT_SCHEMA_PROFILE: 'off' }); this.client = new McpStdio({ executable: this.installation.node.path, args: [this.installation.entry.path, 'mcp'], cwd: this.cwd, env }, { timeoutMs: this.timeoutMs }); this.onClient(this.client); const initialize = await this.client.request('initialize', { protocolVersion: REA_PROTOCOL, capabilities: {}, clientInfo: { name: 'agent-workbench-research-adapter', version: '1.8.0' } }, { signal }); if (initialize.protocolVersion !== REA_PROTOCOL || initialize.serverInfo?.name !== 'rea' || initialize.serverInfo.version !== REA_VERSION) throw new Error('REA实际握手版本与锁定契约不匹配。'); this.client.notify('notifications/initialized'); const pages = [], tools = [], cursors = new Set(); let cursor; do { const page = await this.client.request('tools/list', cursor ? { cursor } : {}, { signal }); pages.push(page); if (!Array.isArray(page.tools) || pages.length > 10) throw new Error('REA工具发现返回了无效分页。'); tools.push(...page.tools); if (tools.length > 500) throw new Error('REA工具发现超过当前接入范围。'); cursor = page.nextCursor; if (cursor && cursors.has(cursor)) throw new Error('REA工具发现分页没有推进。'); if (cursor) cursors.add(cursor); } while (cursor); if (new Set(tools.map(tool => tool.name)).size !== tools.length) throw new Error('REA工具身份重复,不能按名称猜测契约。'); this.tools = tools; this.contract = { version: REA_VERSION, protocolVersion: REA_PROTOCOL, initialize, catalog: pages, advertisedTools: tools.length, enabled: Object.entries(REA_OPERATIONS).filter(([, operation]) => tools.some(tool => tool.name === operation.name)) .map(([id, operation]) => { const tool = tools.find(tool => tool.name === operation.name); return { id, name: tool.name, schemaSha256: schemaDigest(tool.inputSchema), inputSchema: tool.inputSchema }; }) }; return this.contract; } async analyze(target, operation, { signal } = {}) { const spec = REA_OPERATIONS[operation]; if (!spec || !spec.extensions.includes(path.extname(target.path).toLowerCase())) throw new Error('分析方式不适用于这个登记工件。'); const tool = this.tools.find(tool => tool.name === spec.name); if (!tool) throw new Error('当前REA没有提供所选工具。'); if (!this.tools.some(value => value.name === 'export_evidence_bundle')) throw new Error('REA没有提供完整Evidence导出,尚未调用分析工具。'); const args = operation === 'javascript' ? { input_path: target.path, format: 'asar', integrity_policy: 'fail', detail: 'summary', max_heap_mb: 256, max_semantic_nodes: 10000, max_semantic_nodes_per_file: 2000, analysis_timeout_ms: 30000 } : { path: target.path, max_file_bytes: 512 * 1024 * 1024, ...(operation === 'pe-imports' ? { max_dlls: 256, max_functions: 10000 } : { max_entries: 10000 }) }; const request = { name: tool.name, arguments: args }, result = await this.client.request('tools/call', request, { signal }); const received = { request, result, operation: spec.name, schemaSha256: schemaDigest(tool.inputSchema) }; if (result.isError || !result.structuredContent) return received; const originalId = result.structuredContent.normalized_result?.parent_evidence_id ?? result.structuredContent.evidence_id; const destination = path.join(this.cwd, 'evidence-' + randomUUID() + '.json'); const exportRequest = { name: 'export_evidence_bundle', arguments: { path: destination, overwrite: false } }; const exportResult = await this.client.request('tools/call', exportRequest, { signal }); received.exportRequest = exportRequest; received.exportResult = exportResult; if (exportResult.isError) return received; const stat = fs.lstatSync(destination); if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 64 * 1024 * 1024) throw new Error('REA导出超过64MiB接收范围或不是常规文件。'); const bytes = fs.readFileSync(destination), text = bytes.toString('utf8'); if (!Buffer.from(text, 'utf8').equals(bytes)) throw new Error('REA导出不是有效UTF-8,原导出留在所属任务目录。'); const bundle = JSON.parse(text); if (!Array.isArray(bundle.records) || bundle.records.length > 500 || new Set(bundle.records.map(record => record.evidence_id)).size !== bundle.records.length) throw new Error('REA导出记录身份无效。'); const evidence = bundle.records.find(record => record.evidence_id === originalId && record.operation === spec.name); if (!evidence) throw new Error('REA导出缺少原分析Evidence,不能用摘要替代。'); return { ...received, bundleText: text, evidence }; } close(options) { return this.client?.close(options) ?? Promise.resolve({ rootExited: true, pid: null, scope: 'not-started' }); } }