feat: integrate task-bound REA research and portable runtime
This commit is contained in:
+14
-2
@@ -7,6 +7,7 @@ import { DiagnosticsPanel } from './DiagnosticsPanel';
|
||||
import { TaskPanel } from './TaskPanel';
|
||||
import { CodeIndexPanel } from './CodeIndexPanel';
|
||||
import { ChangesInspector } from './ChangesInspector';
|
||||
import { ResearchPanel } from './ResearchPanel';
|
||||
|
||||
const activeStates = ['running', 'awaiting_approval', 'stopping'];
|
||||
const defaultConfig: Config = { mode: 'demo', baseUrl: 'http://127.0.0.1:11434/v1', model: '', contextLimit: 16000, maxSteps: 12, maxOutputTokens: 2048, hasKey: false, maxRunDurationMs: 600000, maxRunTokens: 200000, maxTaskTokens: 1000000 };
|
||||
@@ -60,6 +61,7 @@ export default function App() {
|
||||
const [projectInput, setProjectInput] = useState('');
|
||||
const [toast, setToast] = useState('');
|
||||
const [researchOpen, setResearchOpen] = useState(false);
|
||||
const [reaOpen, setReaOpen] = useState(false);
|
||||
const [researchDocs, setResearchDocs] = useState<ResearchDoc[]>([]);
|
||||
const [report, setReport] = useState<{ title: string; content: string } | null>(null);
|
||||
const chatEnd = useRef<HTMLDivElement>(null);
|
||||
@@ -81,7 +83,8 @@ export default function App() {
|
||||
const isRunning = !!session && (activeStates.includes(session.status) || session.execution?.checks.some(job => ['queued', 'running'].includes(job.status)) === true
|
||||
|| session.execution?.deliveries?.some(job => ['queued', 'preparing', 'prepared', 'publishing', 'committed', 'reporting'].includes(job.status)) === true
|
||||
|| session.execution?.changeSets?.some(set => ['applying', 'rolling_back'].includes(set.status)) === true
|
||||
|| session.execution?.workspaces?.some(value => ['creating', 'verifying', 'registering'].includes(value.status)) === true);
|
||||
|| session.execution?.workspaces?.some(value => ['creating', 'verifying', 'registering'].includes(value.status)) === true
|
||||
|| session.execution?.researchJobs?.some(value => ['queued', 'connecting', 'analyzing', 'stopping'].includes(value.status)) === true);
|
||||
const anyRunning = isRunning || briefs.some(item => activeStates.includes(item.status));
|
||||
const pending = session?.changes.filter(change => ['pending', 'conflict'].includes(change.status)) || [];
|
||||
const reviewedRun = session?.execution?.run;
|
||||
@@ -119,7 +122,7 @@ export default function App() {
|
||||
function failure(error: unknown) { notify(error instanceof Error ? error.message : String(error)); }
|
||||
function selectSession(id: string) {
|
||||
if (selectedSessionRef.current === id) return;
|
||||
workspaceRequest.current++; selectedSessionRef.current = id; setSessionId(id); setSession(null); setToast('');
|
||||
workspaceRequest.current++; selectedSessionRef.current = id; setSessionId(id); setSession(null); setToast(''); setReaOpen(false);
|
||||
localStorage.setItem('awb-session', id); setChangeId(''); setEventId('');
|
||||
}
|
||||
function acceptSession(updated: Session) {
|
||||
@@ -342,6 +345,13 @@ export default function App() {
|
||||
try { setResearchDocs(await api<ResearchDoc[]>('/research')); setReport(await api('/research/overview')); setResearchOpen(true); }
|
||||
catch (error) { failure(error); }
|
||||
}
|
||||
async function openRea() {
|
||||
const originProject = selectedProjectRef.current, originSession = selectedSessionRef.current;
|
||||
try {
|
||||
const target = session || await newSession();
|
||||
if (target && selectedProjectRef.current === originProject && selectedSessionRef.current === target.id) setReaOpen(true);
|
||||
} catch (error) { if (selectedProjectRef.current === originProject && selectedSessionRef.current === originSession) failure(error); }
|
||||
}
|
||||
async function loadReport(id: string) {
|
||||
const request = ++reportRequest.current;
|
||||
try { const document = await api<{ title: string; content: string }>('/research/' + id); if (request === reportRequest.current) setReport(document); }
|
||||
@@ -485,6 +495,7 @@ export default function App() {
|
||||
<div className="task-toolbar"><span className="task-local"><GitBranch size={13} />本地项目</span>{session ? <Status value={session.status} /> : <span className="subtle">等待新任务</span>}<div className="toolbar-actions">
|
||||
<IconButton label="运行诊断" onClick={() => openDiagnostics()}><Activity size={15} /></IconButton>
|
||||
<IconButton label="查看任务记录" onClick={() => showInspector('task')}><ClipboardCheck size={15} /></IconButton>
|
||||
<IconButton label="REA 工件研究" onClick={() => void openRea()} disabled={!selectedProject || creatingSession}><BookOpenText size={15} /></IconButton>
|
||||
{narrow && <><IconButton label="查看文件" onClick={() => showInspector('file')}><FileCode2 size={16} /></IconButton><IconButton label="查看改动" onClick={() => showInspector('changes')}><GitBranch size={16} /></IconButton><IconButton label="查看执行轨迹" onClick={() => showInspector('trace')}><SquareTerminal size={16} /></IconButton></>}
|
||||
{pending.length > 0 && <button className="text-button review-toolbar" onClick={() => { setChangeId(pending[0].id); showInspector('changes'); }}><FileCode2 size={13} />审核 {pending.length} 项</button>}
|
||||
{session && <><IconButton label="导出会话" onClick={() => exportSession(session.id).catch(failure)}><ArrowDownToLine size={15} /></IconButton>
|
||||
@@ -522,6 +533,7 @@ export default function App() {
|
||||
{settings.mode === 'compatible' && <><div className="connection-presets"><button type="button" onClick={() => setSettings(previous => ({ ...previous, baseUrl: 'http://127.0.0.1:11434/v1' }))}>Ollama</button><button type="button" onClick={() => setSettings(previous => ({ ...previous, baseUrl: 'http://127.0.0.1:8000/v1' }))}>vLLM</button><span>Chat Completions 兼容接口</span></div><label className="form-field">接口根地址<input type="url" value={settings.baseUrl} onChange={event => setSettings(previous => ({ ...previous, baseUrl: event.target.value }))} placeholder="http://127.0.0.1:11434/v1" /></label><label className="form-field">API Key(按服务要求填写)<input type="password" autoComplete="off" value={keyValue} onChange={event => { setKeyValue(event.target.value); setClearKey(false); }} placeholder={config.hasKey ? '本次运行已设置,留空保留' : '本地服务可以不填'} /></label><div className="key-note"><span>只在本次服务内存中使用,不写入会话与配置。</span>{config.hasKey && <button type="button" onClick={() => { setClearKey(true); setKeyValue(''); }}>{clearKey ? '保存后清除' : '清除 Key'}</button>}</div><div className="model-field"><label className="form-field">模型名称<input list="model-list" value={settings.model} onChange={event => setSettings(previous => ({ ...previous, model: event.target.value }))} placeholder="例如 qwen3:8b" /><datalist id="model-list">{models.map(model => <option key={model} value={model} />)}</datalist></label><button className="button secondary" type="button" onClick={readModels} disabled={settingsBusy || anyRunning}>{settingsBusy ? <LoaderCircle size={14} className="spin" /> : <Search size={14} />}读取模型列表</button></div><div className="model-test-row"><span>填写服务提供的接口根地址。</span><button type="button" className="button secondary" onClick={testModel} disabled={settingsBusy || anyRunning || !settings.model}><Activity size={14} />验证模型响应</button></div>{modelCheck && <div className={'model-check model-check-' + modelCheck.kind} role="status">{modelCheck.message}</div>}</>}
|
||||
<details className="budget-settings"><summary>上下文与任务预算<ChevronDown size={13} /></summary><div className="budget-fields"><label>上下文预算<input type="number" min={1000} max={200000} value={settings.contextLimit} onChange={event => setSettings(previous => ({ ...previous, contextLimit: Number(event.target.value) }))} /></label><label>最大工具轮次<input type="number" min={1} max={30} value={settings.maxSteps} onChange={event => setSettings(previous => ({ ...previous, maxSteps: Number(event.target.value) }))} /></label><label>输出上限<input type="number" min={256} max={16000} value={settings.maxOutputTokens} onChange={event => setSettings(previous => ({ ...previous, maxOutputTokens: Number(event.target.value) }))} /></label><label>运行时间(分钟)<input aria-label="运行时间预算" type="number" min={1} max={60} value={settings.maxRunDurationMs / 60000} onChange={event => setSettings(previous => ({ ...previous, maxRunDurationMs: Number(event.target.value) * 60000 }))} /></label><label>单次运行 tokens<input aria-label="单次运行token预算" type="number" min={1000} max={2000000} value={settings.maxRunTokens} onChange={event => setSettings(previous => ({ ...previous, maxRunTokens: Number(event.target.value) }))} /></label><label>任务累计 tokens<input aria-label="任务累计token预算" type="number" min={1000} max={10000000} value={settings.maxTaskTokens} onChange={event => setSettings(previous => ({ ...previous, maxTaskTokens: Number(event.target.value) }))} /></label></div><p>上下文使用本地估算;实际用量与未知用量分开保存。达到预算会暂停,已完成的工具结果保留。</p></details>{anyRunning && <p className="form-warning">有任务在执行,请先停止任务再改变连接。</p>}<div className="modal-actions"><button type="button" className="button secondary" onClick={() => setSettingsOpen(false)}>取消</button><button type="submit" className="button primary" disabled={settingsBusy || anyRunning}><Check size={15} />保存连接</button></div></form></Modal>}
|
||||
{diagnosticsOpen && <Modal title="运行诊断" description="查看工作台的模型连接、终端环境、最近错误和文件实际状态。" wide onClose={() => setDiagnosticsOpen(false)}><DiagnosticsPanel value={diagnostics} busy={diagnosticsBusy} onRefresh={() => openDiagnostics()} /></Modal>}
|
||||
{reaOpen && session && selectedProject && <Modal title="REA 工件研究" description="原分析与同一项目、任务和运行绑定。" wide onClose={() => setReaOpen(false)}><ResearchPanel key={session.id} project={selectedProject} session={session} onSession={acceptSession} onError={failure} busy={isRunning} /></Modal>}
|
||||
{researchOpen && <Modal title="机制研究与独立设计" description="从分发客户端的静态证据提炼产品机制。运行时与远端服务的未知部分在报告中说明。" wide onClose={() => setResearchOpen(false)}><div className="research-layout"><nav>{researchDocs.map(document => <button className={report?.title === document.title ? 'selected' : ''} key={document.id} onClick={() => loadReport(document.id)}><BookOpenText size={15} /><span><strong>{document.title}</strong><small>{document.description}</small></span></button>)}</nav><article className="research-document">{report && <ResearchContent content={report.content} />}</article></div></Modal>}
|
||||
{toast && <div className="toast" role="status"><span>{toast}</span><IconButton label="关闭提示" onClick={() => setToast('')}><X size={14} /></IconButton></div>}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
.rea-panel { color: var(--ink); min-width: 0; }
|
||||
.rea-heading { display: flex; justify-content: space-between; align-items: flex-start; gap: 24px; margin-bottom: 22px; }
|
||||
.rea-heading > div:first-child { max-width: 570px; }
|
||||
.rea-eyebrow { color: var(--teal); font-size: 11px; letter-spacing: .04em; }
|
||||
.rea-heading h3 { font-size: 23px; letter-spacing: -.04em; line-height: 1.4; margin: 5px 0 8px; font-weight: 650; }
|
||||
.rea-heading p, .rea-hint, .rea-empty { color: var(--muted); font-size: 12px; line-height: 1.8; }
|
||||
.rea-availability { display: flex; align-items: flex-end; flex-direction: column; gap: 9px; flex-shrink: 0; padding-top: 5px; }
|
||||
.rea-availability > span { color: #8b5734; font-size: 11px; padding: 5px 9px; border: 1px solid #e8dccc; border-radius: 5px; }
|
||||
.rea-availability > span.found { color: var(--teal); border-color: #c6ded4; background: #eff7f3; }
|
||||
.rea-install-note { padding: 12px 15px; border: 1px solid #e6d6c4; background: #fbf6ee; line-height: 1.8; margin-bottom: 18px; }
|
||||
.rea-grid { display: grid; grid-template-columns: minmax(240px, .82fr) minmax(0, 1.45fr); gap: 24px; }
|
||||
.rea-registration, .rea-results { min-width: 0; }
|
||||
.rea-registration form { padding: 18px; background: var(--paper); border: 1px solid var(--line); border-radius: 7px; }
|
||||
.rea-panel h4 { font-size: 13px; font-weight: 650; display: flex; gap: 8px; align-items: center; margin-bottom: 14px; }
|
||||
.rea-registration form .form-field { margin-bottom: 14px; }
|
||||
.rea-registration textarea { resize: vertical; min-height: 77px; width: 100%; border: 1px solid var(--line); border-radius: 6px; background: #fff; padding: 10px 11px; color: var(--ink); font-size: 12px; line-height: 1.7; }
|
||||
.rea-hint { margin: -2px 0 15px; }
|
||||
.rea-targets { padding-top: 21px; }
|
||||
.rea-targets h4 span { color: var(--muted); font-size: 11px; font-weight: 400; }
|
||||
.rea-target { border-top: 1px solid var(--line); padding: 14px 0 16px; min-width: 0; }
|
||||
.rea-target strong { display: block; font-size: 12px; }
|
||||
.rea-target small { display: block; overflow-wrap: anywhere; color: var(--muted); line-height: 1.65; margin: 7px 0; }
|
||||
.rea-target > code { display: block; color: #526a66; font-size: 10px; overflow-wrap: anywhere; line-height: 1.65; }
|
||||
.rea-target-actions { display: flex; gap: 8px; margin-top: 12px; align-items: center; }
|
||||
.rea-target-actions select { min-width: 0; flex: 1; padding: 7px 8px; border: 1px solid var(--line); border-radius: 5px; background: var(--paper); font-size: 11px; }
|
||||
.rea-results-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
|
||||
.rea-empty-result { border: 1px dashed #cbdcd3; padding: 42px 24px; display: flex; flex-direction: column; align-items: flex-start; color: var(--muted); gap: 12px; border-radius: 7px; }
|
||||
.rea-empty-result strong { color: var(--ink); font-size: 15px; font-weight: 550; }
|
||||
.rea-empty-result p { line-height: 1.8; font-size: 12px; max-width: 380px; }
|
||||
.rea-job { border: 1px solid var(--line); background: var(--paper); padding: 17px; border-radius: 7px; margin-bottom: 13px; min-width: 0; }
|
||||
.rea-job.verified { border-left: 3px solid #5b9886; padding-left: 15px; }
|
||||
.rea-job-heading { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; }
|
||||
.rea-job-heading > div { min-width: 0; }
|
||||
.rea-job-heading strong { font-size: 13px; display: block; overflow-wrap: anywhere; }
|
||||
.rea-job-heading > div > span { font-size: 11px; color: var(--muted); display: block; margin-top: 5px; }
|
||||
.rea-job-state { display: inline-flex; align-items: center; gap: 5px; font-size: 10px; color: #766449; flex-shrink: 0; padding-top: 2px; }
|
||||
.rea-job-state.completed { color: var(--teal); }
|
||||
.rea-job-state.failed, .rea-job-state.stale, .rea-job-state.unknown { color: #a34d35; }
|
||||
.rea-job-summary { color: var(--muted); line-height: 1.85; margin: 13px 0; font-size: 12px; overflow-wrap: anywhere; }
|
||||
.rea-source-chain { display: flex; align-items: center; justify-content: space-between; gap: 7px; border-top: 1px solid #e3ece7; border-bottom: 1px solid #e3ece7; padding: 13px 0; margin-bottom: 12px; color: #42685e; }
|
||||
.rea-source-chain > div { display: flex; align-items: center; gap: 7px; min-width: 0; }
|
||||
.rea-source-chain span { font-size: 9px; display: block; color: var(--muted); }
|
||||
.rea-source-chain code { color: var(--teal); display: block; margin-top: 4px; font-size: 10px; overflow-wrap: anywhere; }
|
||||
.rea-job-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 8px 11px; }
|
||||
.rea-job-actions .button { font-size: 11px; padding: 7px 9px; }
|
||||
.rea-job-actions .text-button { font-size: 11px; }
|
||||
.rea-reused { color: #587867; font-size: 11px; margin: 3px 0 12px; line-height: 1.7; }
|
||||
.rea-origin { margin-top: 14px; border-top: 1px solid var(--line); padding-top: 10px; color: var(--muted); font-size: 10px; }
|
||||
.rea-origin summary { cursor: pointer; }
|
||||
.rea-origin dl { display: grid; grid-template-columns: 74px minmax(0, 1fr); gap: 9px; margin: 14px 0 0; }
|
||||
.rea-origin dt, .rea-origin dd { margin: 0; min-width: 0; overflow-wrap: anywhere; line-height: 1.65; }
|
||||
.rea-evidence-view { min-width: 0; }
|
||||
.rea-evidence-meta { border-bottom: 1px solid var(--line); padding-bottom: 12px; color: var(--muted); font-size: 11px; }
|
||||
.rea-evidence-meta code { display: block; overflow-wrap: anywhere; margin-top: 7px; font-size: 10px; }
|
||||
.rea-pointer { display: flex; justify-content: space-between; gap: 12px; align-items: center; padding: 14px 0; min-width: 0; }
|
||||
.rea-pointer code { color: var(--teal); overflow-wrap: anywhere; min-width: 0; }
|
||||
.rea-field-picker { display: flex; flex-wrap: wrap; gap: 7px; margin-bottom: 15px; }
|
||||
.rea-field-picker button { font-family: "Cascadia Code", Consolas, monospace; font-size: 10px; display: inline-flex; align-items: center; gap: 7px; padding: 5px 8px; border: 1px solid var(--line); border-radius: 4px; overflow-wrap: anywhere; max-width: 100%; }
|
||||
.rea-field-picker button:hover { color: var(--teal); background: #ecf5ef; }
|
||||
.rea-original-content { margin: 0; padding: 17px; background: #f1f5f2; border: 1px solid var(--line); border-radius: 5px; line-height: 1.8; font-size: 11px; max-height: 44vh; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.rea-page-controls { display: flex; align-items: center; gap: 9px; margin-top: 14px; flex-wrap: wrap; font-size: 11px; color: var(--muted); }
|
||||
.rea-page-controls > span { margin-right: auto; }
|
||||
@media (max-width: 800px) {
|
||||
.rea-grid { grid-template-columns: minmax(0, 1fr); gap: 26px; }
|
||||
.rea-registration form { padding: 15px; }
|
||||
}
|
||||
@media (max-width: 620px) {
|
||||
.rea-heading { display: block; margin-bottom: 18px; }
|
||||
.rea-heading h3 { font-size: 21px; }
|
||||
.rea-availability { flex-direction: row; align-items: center; justify-content: space-between; padding-top: 14px; }
|
||||
.rea-job { padding: 13px; }
|
||||
.rea-job.verified { padding-left: 11px; }
|
||||
.rea-job-heading { flex-wrap: wrap; gap: 8px; }
|
||||
.rea-job-state { padding-top: 0; }
|
||||
.rea-source-chain { gap: 4px; }
|
||||
.rea-source-chain > div { gap: 4px; }
|
||||
.rea-source-chain code { font-size: 9px; }
|
||||
.rea-source-chain > div > svg { display: none; }
|
||||
.rea-pointer { align-items: flex-start; flex-wrap: wrap; }
|
||||
.rea-original-content { padding: 12px; max-height: 42vh; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { .rea-panel .spin { animation: none; } }
|
||||
@@ -0,0 +1,127 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { ArrowRight, ArrowUpLeft, Download, FileSearch, Fingerprint, LoaderCircle, Play, RefreshCw, ShieldCheck, Square } from 'lucide-react';
|
||||
import { api, downloadArtifact, downloadResearchDocument } from './api';
|
||||
import { Modal } from './components';
|
||||
import type { ArtifactPreview, Project, ReaAvailability, ResearchJob, ResearchPage, ResearchTarget, Session } from './types';
|
||||
import './ResearchPanel.css';
|
||||
|
||||
const active = ['queued', 'connecting', 'analyzing', 'stopping'];
|
||||
const operations = [
|
||||
{ id: 'javascript', extensions: ['.asar'], label: 'JavaScript / Electron' },
|
||||
{ id: 'pe-imports', extensions: ['.exe', '.dll'], label: 'PE 导入表' },
|
||||
{ id: 'pe-resources', extensions: ['.exe', '.dll'], label: 'PE 静态资源' },
|
||||
];
|
||||
const states: Record<string, string> = { queued: '已排队', connecting: '核对 REA 连接', analyzing: '正在静态分析', stopping: '正在停止', completed: '原证据已核验', stale: '工件版本变化', unverified: '原响应尚未核验', failed: '分析未完成', cancelled: '已停止', unknown: '结果待核对', interrupted: '已中断' };
|
||||
const date = (value: string) => new Date(value).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
|
||||
const escapeField = (value: string) => value.replace(/~/g, '~0').replace(/\//g, '~1');
|
||||
type Preview = { job: ResearchJob; kind: 'evidence' | 'raw' | 'trace'; page: ResearchPage };
|
||||
|
||||
export function ResearchPanel({ project, session, busy, onSession, onError }: { project: Project; session: Session; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void }) {
|
||||
const [availability, setAvailability] = useState<ReaAvailability | null>(null);
|
||||
const [filename, setFilename] = useState(''), [label, setLabel] = useState(''), [goal, setGoal] = useState('');
|
||||
const [choices, setChoices] = useState<Record<string, string>>({});
|
||||
const [pending, setPending] = useState(false), [checking, setChecking] = useState(false), [viewBusy, setViewBusy] = useState(false);
|
||||
const [retry, setRetry] = useState<ResearchJob | null>(null), [preview, setPreview] = useState<Preview | null>(null);
|
||||
const mounted = useRef(true), request = useRef(0), scope = useRef(0), viewRequest = useRef(0);
|
||||
const taskId = session.execution?.task?.id ?? null;
|
||||
const targets = session.execution?.researchTargets ?? [], jobs = (session.execution?.researchJobs ?? []).slice().reverse();
|
||||
const running = jobs.some(job => active.includes(job.status)), disabled = busy || running || pending;
|
||||
useEffect(() => { mounted.current = true; return () => { mounted.current = false; request.current++; scope.current++; viewRequest.current++; }; }, []);
|
||||
useEffect(() => { scope.current++; viewRequest.current++; setPreview(null); setRetry(null); setPending(false); setViewBusy(false); }, [taskId]);
|
||||
useEffect(() => { void detect(); }, []);
|
||||
async function detect() {
|
||||
const current = ++request.current; setChecking(true);
|
||||
try { const value = await api<ReaAvailability>('/research/availability'); if (mounted.current && current === request.current) setAvailability(value); }
|
||||
catch (error) { if (mounted.current && current === request.current) onError(error); }
|
||||
finally { if (mounted.current && current === request.current) setChecking(false); }
|
||||
}
|
||||
async function register() {
|
||||
const current = scope.current; setPending(true);
|
||||
try {
|
||||
const value = await api<{ target: ResearchTarget; session: Session }>('/sessions/' + session.id + '/research/targets',
|
||||
{ path: filename.trim(), ...(label.trim() ? { label: label.trim() } : {}), ...(goal.trim() ? { goal: goal.trim() } : {}) });
|
||||
if (!mounted.current || current !== scope.current) return;
|
||||
onSession(value.session); setFilename(''); setLabel(''); setGoal('');
|
||||
} catch (error) { if (mounted.current && current === scope.current) onError(error); }
|
||||
finally { if (mounted.current && current === scope.current) setPending(false); }
|
||||
}
|
||||
async function analyze(targetId: string, operation: string, refresh = false) {
|
||||
const current = scope.current; setPending(true);
|
||||
try {
|
||||
const value = await api<{ job: ResearchJob; session: Session }>('/sessions/' + session.id + '/research/jobs', { targetId, operation, refresh });
|
||||
if (mounted.current && current === scope.current) { onSession(value.session); setRetry(null); }
|
||||
} catch (error) { if (mounted.current && current === scope.current) onError(error); }
|
||||
finally { if (mounted.current && current === scope.current) setPending(false); }
|
||||
}
|
||||
async function stop() {
|
||||
const current = scope.current; setPending(true);
|
||||
try { const value = await api<Session>('/sessions/' + session.id + '/research/stop', {}); if (mounted.current && current === scope.current) onSession(value); }
|
||||
catch (error) { if (mounted.current && current === scope.current) onError(error); }
|
||||
finally { if (mounted.current && current === scope.current) setPending(false); }
|
||||
}
|
||||
async function openView(job: ResearchJob, kind: Preview['kind'] = 'evidence', pointer = '/normalized_result', offset = 0) {
|
||||
const current = ++viewRequest.current, currentScope = scope.current; setViewBusy(true);
|
||||
try {
|
||||
let page: ResearchPage;
|
||||
if (kind === 'trace') {
|
||||
const value = await api<ArtifactPreview>('/artifacts/' + job.traceArtifactId + '?session=' + session.id + '&offset=' + offset + '&limit=4000');
|
||||
page = { content: value.content, offset: value.offset, next_offset: value.offset + value.content.length, total_characters: value.totalCharacters,
|
||||
truncated: value.truncated, source_document_sha256: value.sha256 };
|
||||
} else page = await api<ResearchPage>('/sessions/' + session.id + '/research/jobs/' + job.id + '/' + (kind === 'raw' ? 'raw' : 'evidence')
|
||||
+ '?pointer=' + encodeURIComponent(pointer) + '&offset=' + offset + '&limit=4000');
|
||||
if (mounted.current && currentScope === scope.current && current === viewRequest.current) setPreview({ job, kind, page });
|
||||
} catch (error) { if (mounted.current && currentScope === scope.current && current === viewRequest.current) onError(error); }
|
||||
finally { if (mounted.current && currentScope === scope.current && current === viewRequest.current) setViewBusy(false); }
|
||||
}
|
||||
async function download(job: ResearchJob, kind: Preview['kind']) {
|
||||
const current = scope.current;
|
||||
try { if (kind === 'trace' && job.traceArtifactId) await downloadArtifact(session.id, job.traceArtifactId, 'agent-workbench-rea-transport-' + job.id + '.json');
|
||||
else await downloadResearchDocument(session.id, job.id, kind === 'raw' ? 'raw' : 'bundle'); }
|
||||
catch (error) { if (mounted.current && current === scope.current) onError(error); }
|
||||
}
|
||||
return <div className="rea-panel">
|
||||
<header className="rea-heading"><div><span className="rea-eyebrow">{project.name} · 当前任务</span><h3>从工件取得原证据</h3><p>登记一个本地工件,分析其代码、导入或资源,再把原依据交给同一编程任务。</p></div>
|
||||
<div className="rea-availability"><span className={availability?.status === 'available' ? 'found' : ''}>{checking ? '正在检测' : availability?.status === 'available' ? '已找到 REA ' + availability.version : 'REA 尚未就绪'}</span>
|
||||
<button type="button" className="text-button" onClick={() => void detect()} disabled={checking}><RefreshCw size={13} />重新检测</button></div></header>
|
||||
{availability && availability.status !== 'available' && <div className="rea-install-note">{availability.status === 'unsupported' ? '当前分析契约使用 REA 6.8.0,请使用匹配的发行包。' : '请使用包含 REA 的工作台发行包,再重新检测本地安装。'}</div>}
|
||||
<div className="rea-grid"><section className="rea-registration">
|
||||
<form onSubmit={event => { event.preventDefault(); void register(); }}>
|
||||
<h4><FileSearch size={16} />登记研究工件</h4>
|
||||
<label className="form-field">本地工件路径<input aria-label="REA工件路径" value={filename} onChange={event => setFilename(event.target.value)} placeholder="D:\Applications\app.asar" required disabled={disabled} /></label>
|
||||
<label className="form-field">工件名称<input aria-label="REA工件名称" value={label} onChange={event => setLabel(event.target.value)} placeholder="例如:代理客户端发行包" maxLength={160} disabled={disabled} /></label>
|
||||
<label className="form-field">研究问题(选填)<textarea aria-label="REA研究问题" value={goal} onChange={event => setGoal(event.target.value)} placeholder="例如:工具执行与取消如何协作?" rows={3} disabled={disabled} /></label>
|
||||
<p className="rea-hint">支持 ASAR、EXE 和 DLL。名称与 SHA256 将保存在本任务;首次登记会创建研究任务。</p>
|
||||
<button type="submit" className="button primary" disabled={disabled || !filename.trim()}>{pending ? <LoaderCircle size={14} className="spin" /> : <Fingerprint size={14} />}登记工件</button>
|
||||
</form>
|
||||
<div className="rea-targets"><h4>本任务工件 <span>{targets.length}</span></h4>
|
||||
{!targets.length && <p className="rea-empty">登记后,模型可以选择这个工件进行静态分析。</p>}
|
||||
{targets.map(target => { const choicesForFile = operations.filter(operation => operation.extensions.includes(target.extension)), operation = choices[target.id] ?? choicesForFile[0]?.id;
|
||||
return <article className="rea-target" key={target.id}><strong>{target.label}</strong><small>{target.path}</small><code title={target.sha256}>SHA256 {target.sha256}</code>
|
||||
<div className="rea-target-actions"><select aria-label={'分析方式 ' + target.label} value={operation} onChange={event => setChoices(previous => ({ ...previous, [target.id]: event.target.value }))} disabled={disabled}>{choicesForFile.map(value => <option key={value.id} value={value.id}>{value.label}</option>)}</select>
|
||||
<button type="button" className="button secondary" onClick={() => void analyze(target.id, operation)} disabled={disabled || availability?.status !== 'available'}><Play size={13} />分析</button></div></article>; })}
|
||||
</div>
|
||||
</section><section className="rea-results"><div className="rea-results-heading"><h4>分析与原依据</h4>{running && <button type="button" className="text-button" onClick={() => void stop()} disabled={pending}><Square size={13} />停止分析</button>}</div>
|
||||
{!jobs.length && <div className="rea-empty-result"><FileSearch size={28} /><strong>原结果将在这里保留</strong><p>分析完成后可选择原字段、查看限制并下载完整 Evidence Bundle。</p></div>}
|
||||
{jobs.map(job => { const target = targets.find(value => value.id === job.targetId), verified = job.status === 'completed' && job.evidenceBinding?.verified;
|
||||
return <article className={'rea-job ' + (verified ? 'verified' : '')} key={job.id} data-research-job={job.id}><div className="rea-job-heading"><div><strong>{target?.label ?? '历史工件'}</strong><span>{operations.find(value => value.id === job.operationId)?.label ?? job.operation}</span></div><span className={'rea-job-state ' + job.status}>{active.includes(job.status) && <LoaderCircle size={12} className="spin" />}{states[job.status] ?? job.status}</span></div>
|
||||
<p className="rea-job-summary">{job.summary}</p>
|
||||
{verified && <div className="rea-source-chain" aria-label="已核验原证据来源"><div><Fingerprint size={13} /><span>工件 SHA<code>{job.targetSha256.slice(0, 12)}</code></span></div><ArrowRight size={12} /><div><ShieldCheck size={13} /><span>REA<code>{job.installation.version}</code></span></div><ArrowRight size={12} /><div><FileSearch size={13} /><span>原 Evidence<code>{job.evidenceId?.slice(3, 15)}</code></span></div></div>}
|
||||
{job.reusedFromJobId && <p className="rea-reused">复用既有原证据,本次没有再次调用 REA。</p>}
|
||||
<div className="rea-job-actions">{verified && <><button type="button" className="button secondary" onClick={() => void openView(job)} disabled={viewBusy}><FileSearch size={13} />查看原字段</button><button type="button" className="text-button" onClick={() => void openView(job, 'evidence', '/limitations')} disabled={viewBusy}>原限制</button><button type="button" className="text-button" onClick={() => void download(job, 'evidence')}><Download size={13} />完整证据</button></>}
|
||||
{job.raw && <button type="button" className="text-button" onClick={() => void openView(job, 'raw')} disabled={viewBusy}>原响应</button>}
|
||||
{job.traceArtifactId && <button type="button" className="text-button" onClick={() => void openView(job, 'trace')} disabled={viewBusy}>连接记录</button>}
|
||||
{!active.includes(job.status) && !verified && target && <button type="button" className="text-button" onClick={() => setRetry(job)} disabled={disabled}><RefreshCw size={13} />重新分析</button>}</div>
|
||||
<details className="rea-origin"><summary>{date(job.startedAt)} · 静态工件观测</summary><dl><dt>Task</dt><dd><code>{job.taskId}</code></dd><dt>Run</dt><dd><code>{job.runId}</code></dd><dt>目标 SHA256</dt><dd><code>{job.targetSha256}</code></dd>{job.evidenceId && <><dt>原 Evidence</dt><dd><code>{job.evidenceId}</code></dd></>}<dt>进程关闭</dt><dd>{job.cleanup ? job.cleanup.rootExited ? '所属根进程已退出' : '关闭结果待核对' : job.reusedFromJobId ? '复用原依据,没有新进程' : '尚未记录关闭结果'}</dd></dl></details>
|
||||
</article>; })}
|
||||
</section></div>
|
||||
{retry && <Modal title="重新运行静态分析" description="这会创建新的分析记录。此前停止、失败或未知的原记录仍会保留。" onClose={() => setRetry(null)}><p>{targets.find(value => value.id === retry.targetId)?.label} · {operations.find(value => value.id === retry.operationId)?.label}</p><div className="modal-actions"><button className="button secondary" onClick={() => setRetry(null)}>返回原记录</button><button className="button primary" onClick={() => void analyze(retry.targetId, retry.operationId, true)} disabled={disabled}>确认重新分析</button></div></Modal>}
|
||||
{preview && <Modal title={preview.kind === 'evidence' ? '原 Evidence 字段' : preview.kind === 'raw' ? 'REA 原响应' : 'REA 连接记录'} description={preview.kind === 'evidence' ? '原字段与完整证据来源已经校验。静态关系及未知覆盖以原限制为准。' : '此处保留当次实际返回记录;记录存在不表示分析已经核验完成。'} wide onClose={() => { viewRequest.current++; setPreview(null); setViewBusy(false); }}>
|
||||
<div className="rea-evidence-view"><div className="rea-evidence-meta"><span>原文 SHA256</span><code>{preview.page.source_document_sha256}</code></div>
|
||||
{preview.kind === 'evidence' && <><div className="rea-pointer"><code>{preview.page.pointer}</code>{preview.page.pointer !== '/normalized_result' && <button className="text-button" onClick={() => void openView(preview.job)} disabled={viewBusy}><ArrowUpLeft size={13} />返回分析字段</button>}</div>
|
||||
{!!preview.page.available_fields?.length && <div className="rea-field-picker" aria-label="原Evidence字段">{preview.page.available_fields.map(field => <button key={field} type="button" onClick={() => void openView(preview.job, 'evidence', preview.page.pointer + '/' + escapeField(field))} disabled={viewBusy}>{field}<ArrowRight size={11} /></button>)}</div>}</>}
|
||||
<pre className="rea-original-content" aria-label="原Evidence内容">{preview.page.content}</pre><div className="rea-page-controls"><span>{preview.page.offset.toLocaleString()}–{preview.page.next_offset.toLocaleString()} / {preview.page.total_characters.toLocaleString()} 字符</span>
|
||||
<button className="button secondary" onClick={() => void openView(preview.job, preview.kind, preview.page.pointer, 0)} disabled={viewBusy || preview.page.offset === 0}>回到首页</button><button className="button secondary" onClick={() => void openView(preview.job, preview.kind, preview.page.pointer, preview.page.next_offset)} disabled={viewBusy || !preview.page.truncated}>{viewBusy ? <LoaderCircle className="spin" size={13} /> : <ArrowRight size={13} />}下一页</button></div>
|
||||
<div className="modal-actions"><button className="button secondary" onClick={() => void download(preview.job, preview.kind)}><Download size={14} />{preview.kind === 'evidence' ? '下载完整 Evidence Bundle' : '下载完整原记录'}</button></div>
|
||||
</div></Modal>}
|
||||
</div>;
|
||||
}
|
||||
@@ -24,6 +24,11 @@ export async function downloadArtifact(sessionId: string, artifactId: string, na
|
||||
}
|
||||
downloadBlob(await response.blob(), name);
|
||||
}
|
||||
export async function downloadResearchDocument(sessionId: string, jobId: string, kind: 'bundle' | 'raw' = 'bundle') {
|
||||
const response = await fetch('/api/sessions/' + sessionId + '/research/jobs/' + jobId + '/download?kind=' + kind, { headers: { 'X-Workbench-Token': accessToken } });
|
||||
if (!response.ok) { const value = await response.json().catch(() => ({})); throw new Error(value.error || '研究证据下载失败。'); }
|
||||
downloadBlob(await response.blob(), 'agent-workbench-rea-' + kind + '-' + jobId + '.json');
|
||||
}
|
||||
export function downloadBlob(blob: Blob, name: string) {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a'); link.href = url; link.download = name; link.click();
|
||||
|
||||
@@ -29,6 +29,8 @@ export function Modal({ title, description, children, onClose, wide = false }: {
|
||||
const previous = document.activeElement as HTMLElement | null;
|
||||
panel.current?.querySelector<HTMLElement>('input, select, textarea, button')?.focus();
|
||||
const handle = (event: KeyboardEvent) => {
|
||||
const dialogs = document.querySelectorAll('[role="dialog"][aria-modal="true"]');
|
||||
if (dialogs[dialogs.length - 1] !== panel.current) return;
|
||||
if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); close.current(); }
|
||||
if (event.key === 'Tab') {
|
||||
const elements = Array.from(panel.current?.querySelectorAll<HTMLElement>('button, input, select, textarea, a[href]') || [])
|
||||
@@ -39,7 +41,7 @@ export function Modal({ title, description, children, onClose, wide = false }: {
|
||||
}
|
||||
};
|
||||
document.addEventListener('keydown', handle);
|
||||
return () => { document.removeEventListener('keydown', handle); previous?.focus(); };
|
||||
return () => { document.removeEventListener('keydown', handle); if (previous?.isConnected) previous.focus(); };
|
||||
}, []);
|
||||
return createPortal(<div className="modal-backdrop" onMouseDown={event => { if (event.target === event.currentTarget) onClose(); }}>
|
||||
<div ref={panel} role="dialog" aria-modal="true" aria-label={title} className={'modal ' + (wide ? 'modal-wide' : '')}>
|
||||
|
||||
+12
-1
@@ -130,4 +130,15 @@ export interface ChangeSet {
|
||||
snapshotArtifactId: string; sourceRunId: string; restoreError?: string }[];
|
||||
observations?: { path: string; state: string; exists: boolean | null; actualSha256: string | null; problem?: string }[];
|
||||
}
|
||||
export interface ExecutionSnapshot { schemaVersion: number; task: Task | null; run: Run | null; runs: RunBrief[]; progress: { totalTools: number; completedTools: number; requiresVerification: { id: string; tool: string; state: string; callId: string }[] }; artifacts: Artifact[]; checks: CheckJob[]; plans?: CheckPlan[]; deliveries?: DeliveryJob[]; deliveryPlans?: DeliveryPlan[]; changeSets?: ChangeSet[]; contextPlans?: ContextPlan[]; workspaces?: WorkspaceRecord[]; workspaceIdentity?: WorkspaceIdentity; accountedTaskTokens: number }
|
||||
export interface ExecutionSnapshot { schemaVersion: number; task: Task | null; run: Run | null; runs: RunBrief[]; progress: { totalTools: number; completedTools: number; requiresVerification: { id: string; tool: string; state: string; callId: string }[] }; artifacts: Artifact[]; checks: CheckJob[]; plans?: CheckPlan[]; deliveries?: DeliveryJob[]; deliveryPlans?: DeliveryPlan[]; changeSets?: ChangeSet[]; contextPlans?: ContextPlan[]; workspaces?: WorkspaceRecord[]; researchTargets?: ResearchTarget[]; researchJobs?: ResearchJob[]; workspaceIdentity?: WorkspaceIdentity; accountedTaskTokens: number }
|
||||
export interface ReaAvailability { status: string; version?: string; declaredVersion?: string; message?: string; packageRoot?: string; protocolVersion?: string; operations?: { id: string; name: string; extensions: string[]; label: string }[] }
|
||||
export interface ResearchTarget { id: string; taskId: string; runId: string; projectId: string; sessionId: string; path: string; sha256: string; bytes: number; extension: string; label: string; source: string; registeredAt: string }
|
||||
export interface ResearchJob {
|
||||
id: string; taskId: string; runId: string; targetId: string; targetSha256: string; operation: string; operationId: string;
|
||||
status: string; summary: string; startedAt: string; finishedAt: string | null; evidenceId?: string; reusedFromJobId?: string;
|
||||
evidenceBinding?: { verified: boolean; statistics?: Record<string, unknown>; limitations: string[]; scope: string } | null;
|
||||
installation: ReaAvailability; before?: { path: string }; raw?: { id: string; documentSha256: string }; traceArtifactId?: string;
|
||||
cleanup?: { rootExited: boolean }; requiresVerification: boolean;
|
||||
}
|
||||
export interface ResearchPage { content: string; offset: number; next_offset: number; total_characters: number; truncated: boolean; pointer?: string;
|
||||
evidence_id?: string; target_sha256?: string; source_document_sha256: string; available_fields?: string[] }
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { ReaAdapter, REA_OPERATIONS, resolveReaInstallation } from './tools/rea-adapter.mjs';
|
||||
import { RESEARCH_ACTIVE, researchError, researchFileIdentity, researchTargetContract, bindReaEvidence,
|
||||
researchPointer, sealResearchDocument, readResearchDocument } from '../shared/contracts/research.mjs';
|
||||
import { artifactPage } from './context/read-budget.mjs';
|
||||
|
||||
const at = () => new Date().toISOString();
|
||||
const sha = text => createHash('sha256').update(text, 'utf8').digest('hex');
|
||||
const jobContract = job => ({ schemaVersion: 1, id: job.id, sessionId: job.sessionId, projectId: job.projectId,
|
||||
taskId: job.taskId, runId: job.runId, targetId: job.targetId, targetSha256: job.targetSha256, operation: job.operation,
|
||||
evidenceId: job.evidenceId, evidence: job.evidence, bundle: job.bundle, raw: job.raw, contractArtifactId: job.contractArtifactId,
|
||||
contractSha256: job.contractSha256, installation: job.installation, before: job.before, after: job.after, reusedFromJobId: job.reusedFromJobId ?? null });
|
||||
|
||||
export class ResearchManager {
|
||||
constructor(store, { appDirectory = process.cwd(), installation = null, adapterFactory = (profile, options) => new ReaAdapter(profile, options),
|
||||
projectBusy = () => false, redact = value => String(value), timeoutMs = 60000 } = {}) {
|
||||
this.store = store; this.appDirectory = appDirectory; this.installation = installation; this.adapterFactory = adapterFactory;
|
||||
this.projectBusy = projectBusy; this.redact = redact; this.timeoutMs = timeoutMs;
|
||||
this.active = new Map(); this.projects = new Map();
|
||||
}
|
||||
availability() { return this.installation ?? resolveReaInstallation(this.appDirectory); }
|
||||
isActive(sessionId) { return [...this.active.values()].some(value => value.sessionId === sessionId); }
|
||||
projectActive(projectId) { return this.projects.has(projectId); }
|
||||
reserve(session, id, { source = 'user', signal } = {}) {
|
||||
if (this.projectActive(session.projectId) || this.projectBusy(session.projectId, source === 'agent' ? session.id : null)) throw researchError('当前项目还有任务或研究在执行,请等待结束。');
|
||||
const controller = new AbortController(), combined = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
|
||||
const active = { sessionId: session.id, projectId: session.projectId, controller, signal: combined };
|
||||
this.active.set(id, active); this.projects.set(session.projectId, id); return active;
|
||||
}
|
||||
release(id, active) { this.active.delete(id); if (this.projects.get(active.projectId) === id) this.projects.delete(active.projectId); }
|
||||
async register(session, input) {
|
||||
if (!input || typeof input.path !== 'string' || input.label !== undefined && (typeof input.label !== 'string' || input.label.length > 160)
|
||||
|| input.goal !== undefined && (typeof input.goal !== 'string' || !input.goal.trim() || input.goal.length > 20000)) throw researchError('请输入工件路径,名称最多160字,研究目标最多20000字。', 400);
|
||||
const id = randomUUID(), active = this.reserve(session, id), identity = { taskId: session.taskId, runId: session.runId };
|
||||
active.promise = (async () => {
|
||||
const file = await researchFileIdentity(input.path, { signal: active.signal }); active.signal.throwIfAborted();
|
||||
if (session.taskId !== identity.taskId || session.runId !== identity.runId) throw researchError('登记期间任务已经切换,请重新登记。');
|
||||
let task = this.store.core.task.get(session.taskId);
|
||||
if (!task || ['completed', 'idle'].includes(task.status)) {
|
||||
const goal = input.goal?.trim() ?? '静态研究登记工件 ' + (input.label?.trim() || path.basename(file.path)) + ' 的功能与代理机制,并以原Evidence为依据。';
|
||||
const run = this.store.beginRun(session, goal, false, this.store.config);
|
||||
run.engine = 'rea-stdio'; run.origin = 'user-research-registration';
|
||||
this.store.message(session, 'user', goal); session.providerMessages.push({ role: 'user', content: goal });
|
||||
session.status = 'paused'; this.store.finishRun(session, run, 'research_ready');
|
||||
task = this.store.core.task.get(session.taskId);
|
||||
if (session.title === '新任务') session.title = ('静态研究 · ' + (input.label?.trim() || path.basename(file.path))).slice(0, 28);
|
||||
} else if (input.goal) task.instructions.push({ id: randomUUID(), content: input.goal.trim(), source: 'user-research-registration', createdAt: at() });
|
||||
const run = this.store.owned('run', session.runId, session.id);
|
||||
const target = { schemaVersion: 1, id: randomUUID(), sessionId: session.id, projectId: session.projectId,
|
||||
taskId: task.id, runId: run.id, ...file, label: input.label?.trim() || path.basename(file.path),
|
||||
source: 'user-registration', status: 'registered', registeredAt: at() };
|
||||
const contract = this.store.artifactStore.write(session, run, researchTargetContract(target), { kind: 'research-target' });
|
||||
this.store.core.artifact.set(contract.id, contract); target.contractArtifactId = contract.id; target.contractSha256 = contract.sha256;
|
||||
return this.store.putRecord('research_target', session, target, 'research.target_registered');
|
||||
})().finally(() => this.release(id, active));
|
||||
return active.promise;
|
||||
}
|
||||
targets(session) { return [...this.store.core.research_target.values()].filter(target => target.sessionId === session.id && target.taskId === session.taskId).slice(-32); }
|
||||
jobs(session) { return [...this.store.core.research_job.values()].filter(job => job.sessionId === session.id).slice(-30); }
|
||||
targetFor(session, id) {
|
||||
const target = this.store.owned('research_target', id, session.id);
|
||||
if (target.taskId !== session.taskId) throw researchError('工件属于此前Task,请在当前任务重新登记。');
|
||||
const artifact = this.store.owned('artifact', target.contractArtifactId, session.id);
|
||||
if (artifact.kind !== 'research-target' || artifact.taskId !== target.taskId || artifact.sha256 !== target.contractSha256
|
||||
|| this.store.artifactStore.read(artifact) !== JSON.stringify(researchTargetContract(target))) throw researchError('登记工件与封存身份不一致。');
|
||||
return target;
|
||||
}
|
||||
start(session, targetId, operation, options = {}) {
|
||||
const target = this.targetFor(session, targetId), spec = REA_OPERATIONS[operation];
|
||||
if (!spec || !spec.extensions.includes(target.extension)) throw researchError('所选静态分析不适用于这个工件。', 400);
|
||||
if (options.refresh && options.source === 'agent') throw researchError('重新执行分析需要用户从研究面板明确发起。');
|
||||
const previous = this.jobs(session).filter(job => job.taskId === session.taskId && job.targetId === targetId && job.operationId === operation).at(-1);
|
||||
if (previous && previous.status !== 'completed' && !options.refresh) throw researchError('此前分析没有可复用的完成Evidence,请查看原结果,再由用户选择重新分析。');
|
||||
const id = randomUUID(), active = this.reserve(session, id, options), run = this.store.owned('run', session.runId, session.id);
|
||||
const job = { schemaVersion: 1, id, sessionId: session.id, projectId: session.projectId, taskId: run.taskId, runId: run.id,
|
||||
targetId, targetSha256: target.sha256, operationId: operation, operation: spec.name, status: 'queued', source: options.source ?? 'user',
|
||||
startedAt: at(), finishedAt: null, requiresVerification: false, summary: '已登记分析范围,尚未调用REA。',
|
||||
scope: 'static-artifact-analysis; no target execution', installation: this.availability() };
|
||||
active.job = job;
|
||||
const event = this.store.event(session, { kind: 'research', label: spec.label, tool: spec.name, phase: 'queued',
|
||||
input: { targetId, path: target.path, sha256: target.sha256, operation } }); job.eventId = event.id;
|
||||
try {
|
||||
this.store.putRecord('research_job', session, job, 'research.queued');
|
||||
active.promise = this.execute(session, target, job, run, active, options).finally(() => this.release(id, active));
|
||||
active.promise.catch(() => {}); return { job, promise: active.promise };
|
||||
} catch (error) { this.release(id, active); throw error; }
|
||||
}
|
||||
async execute(session, target, job, run, active, options) {
|
||||
let adapter, returned = false;
|
||||
const event = session.events.find(value => value.id === job.eventId);
|
||||
const phase = (status, summary) => { job.status = status; job.summary = summary; event.phase = status; event.output = summary; this.store.save(session, { type: 'research.' + status, detail: { jobId: job.id } }); };
|
||||
try {
|
||||
job.before = await researchFileIdentity(target.path, { signal: active.signal }); active.signal.throwIfAborted();
|
||||
if (job.before.sha256 !== target.sha256 || job.before.bytes !== target.bytes) throw researchError('工件在登记后变化,请按新版本重新登记。');
|
||||
const reusable = !options.refresh && [...this.store.core.research_job.values()].findLast(value => value.id !== job.id && value.sessionId === session.id
|
||||
&& value.taskId === job.taskId && value.targetId === target.id && value.operationId === job.operationId && value.status === 'completed' && value.evidenceBinding?.verified);
|
||||
if (reusable) {
|
||||
this.verifiedEvidence(session, reusable);
|
||||
for (const key of ['evidence', 'bundle', 'raw', 'contractArtifactId', 'contractSha256', 'evidenceId', 'evidenceBinding', 'installation']) job[key] = structuredClone(reusable[key]);
|
||||
job.reusedFromJobId = reusable.id; job.after = job.before; job.summary = '已复用原完整Evidence,登记工件SHA256仍一致;没有再次调用REA。';
|
||||
} else {
|
||||
const scratchRoot = path.join(this.store.directory, 'research-operations'); fs.mkdirSync(scratchRoot, { recursive: true });
|
||||
if (fs.lstatSync(scratchRoot).isSymbolicLink()) throw researchError('研究执行目录不能是链接。');
|
||||
const scratch = path.join(scratchRoot, job.id); fs.mkdirSync(scratch); job.outputDirectory = scratch;
|
||||
adapter = this.adapterFactory(job.installation, { cwd: scratch, timeoutMs: this.timeoutMs,
|
||||
onClient: client => { active.client = client; job.connection = { id: client.id, pid: client.pid ?? null, startedAt: client.startedAt }; this.store.save(session, { type: 'research.connection_owned', detail: { jobId: job.id } }); } });
|
||||
phase('connecting', '正在核对REA握手和实际工具契约。');
|
||||
const contract = await adapter.connect(active.signal);
|
||||
const contractArtifact = this.store.artifactStore.write(session, run, contract, { kind: 'research-rea-contract' });
|
||||
this.store.core.artifact.set(contractArtifact.id, contractArtifact); job.contractArtifactId = contractArtifact.id; job.contractSha256 = contractArtifact.sha256;
|
||||
phase('analyzing', 'REA正在静态读取登记工件,完整原Evidence将独立封存。'); job.analysisDispatched = true;
|
||||
const received = await adapter.analyze(target, job.operationId, { signal: active.signal }); returned = true;
|
||||
const { bundleText, evidence, ...raw } = received;
|
||||
job.raw = sealResearchDocument(this.store, session, run, JSON.stringify(raw), 'research-raw-response');
|
||||
if (!evidence || !bundleText || received.result?.isError || received.exportResult?.isError) throw Object.assign(researchError('REA没有返回原完整Evidence;原响应已保留。'), { outcome: 'unverified' });
|
||||
job.bundle = sealResearchDocument(this.store, session, run, bundleText, 'research-evidence-bundle');
|
||||
job.evidence = sealResearchDocument(this.store, session, run, JSON.stringify(evidence), 'research-evidence');
|
||||
job.evidenceBinding = bindReaEvidence({ structuredContent: evidence }, target, job.operation); job.evidenceId = evidence.evidence_id;
|
||||
job.after = await researchFileIdentity(target.path, { signal: active.signal }); active.signal.throwIfAborted();
|
||||
if (job.after.sha256 !== target.sha256 || job.after.bytes !== target.bytes) throw researchError('分析期间工件变化,原响应保留但不作为登记版本的已核验结果。');
|
||||
job.summary = '原完整Evidence与登记工件、分析前后SHA256均已核对。静态候选和未知范围见原限制。';
|
||||
}
|
||||
const binding = this.store.artifactStore.write(session, run, jobContract(job), { kind: 'research-binding' });
|
||||
this.store.core.artifact.set(binding.id, binding); job.bindingArtifactId = binding.id; job.bindingSha256 = binding.sha256;
|
||||
job.status = 'completed';
|
||||
} catch (error) {
|
||||
job.errorCode = error.code ?? null; job.summary = this.redact(error.message ?? String(error));
|
||||
job.status = active.signal.aborted ? 'cancelled' : error.outcome ?? (error.code && job.analysisDispatched && !returned ? 'unknown' : error.status === 409 ? 'stale' : 'failed');
|
||||
job.requiresVerification = job.status === 'unknown'; job.evidenceBinding = null;
|
||||
} finally {
|
||||
if (adapter) {
|
||||
try { job.cleanup = await adapter.close({ force: active.signal.aborted || !!job.errorCode }); }
|
||||
catch (error) { job.cleanup = { rootExited: false, message: this.redact(error.message) }; }
|
||||
const trace = { trace: active.client?.trace ?? [], stderr: this.redact(active.client?.stderr ?? ''), cleanup: job.cleanup };
|
||||
const artifact = this.store.artifactStore.write(session, run, trace, { kind: 'research-transport' }); this.store.core.artifact.set(artifact.id, artifact); job.traceArtifactId = artifact.id;
|
||||
if (!job.cleanup.rootExited) { job.status = 'unknown'; job.requiresVerification = true; job.evidenceBinding = null; job.summary += ' 所属REA进程关闭结果尚未确认。'; }
|
||||
}
|
||||
job.finishedAt = at(); event.phase = job.status; event.finishedAt = job.finishedAt; event.output = job.summary;
|
||||
this.store.save(session, { type: 'research.result', detail: { jobId: job.id, status: job.status } });
|
||||
}
|
||||
return job;
|
||||
}
|
||||
verifiedEvidence(session, job) {
|
||||
if (job.status !== 'completed' || !job.evidenceBinding?.verified || !job.bindingArtifactId) throw researchError('这个分析尚没有已核验的原完整Evidence。');
|
||||
const binding = this.store.owned('artifact', job.bindingArtifactId, session.id);
|
||||
if (binding.sha256 !== job.bindingSha256 || this.store.artifactStore.read(binding) !== JSON.stringify(jobContract(job))) throw researchError('研究结果与封存绑定不匹配。');
|
||||
const target = this.store.owned('research_target', job.targetId, session.id);
|
||||
const targetArtifact = this.store.owned('artifact', target.contractArtifactId, session.id);
|
||||
if (targetArtifact.sha256 !== target.contractSha256 || this.store.artifactStore.read(targetArtifact) !== JSON.stringify(researchTargetContract(target)) || target.sha256 !== job.targetSha256) throw researchError('原研究工件身份与Evidence不匹配。');
|
||||
const contract = this.store.owned('artifact', job.contractArtifactId, session.id);
|
||||
if (contract.sha256 !== job.contractSha256) throw researchError('REA契约与封存引用不匹配。'); this.store.artifactStore.read(contract);
|
||||
const evidence = JSON.parse(readResearchDocument(this.store, session, job.evidence)), bundle = JSON.parse(readResearchDocument(this.store, session, job.bundle));
|
||||
const bound = bindReaEvidence({ structuredContent: evidence }, target, job.operation);
|
||||
if (bound.evidenceId !== job.evidenceId || JSON.stringify(bound) !== JSON.stringify(job.evidenceBinding)
|
||||
|| !bundle.records?.some(record => JSON.stringify(record) === JSON.stringify(evidence))) throw researchError('原完整Evidence不在封存的Bundle中。');
|
||||
readResearchDocument(this.store, session, job.raw); return evidence;
|
||||
}
|
||||
readEvidence(session, jobId, { pointer = '/normalized_result', offset = 0, limit = 4000, maximumMessageBytes = 30000, callId = '' } = {}) {
|
||||
const job = this.store.owned('research_job', jobId, session.id), evidence = this.verifiedEvidence(session, job), value = researchPointer(evidence, pointer);
|
||||
const text = JSON.stringify(value, null, 2), viewSha256 = sha(text);
|
||||
const metadata = { research_job_id: job.id, evidence_id: job.evidenceId, target_sha256: job.targetSha256,
|
||||
pointer, view_sha256: viewSha256, source_artifact_id: job.evidence.id, source_document_sha256: job.evidence.documentSha256,
|
||||
available_fields: value && typeof value === 'object' ? Object.keys(value).slice(0, 32) : [],
|
||||
navigation: 'Use read_research_evidence with the same research_job_id and pointer, then next_offset.', scope: job.scope };
|
||||
const frameBytes = object => Buffer.byteLength(JSON.stringify({ role: 'tool', tool_call_id: callId, content: JSON.stringify(object) }), 'utf8');
|
||||
const reserve = frameBytes(metadata) + 128;
|
||||
if (maximumMessageBytes - reserve < 1024) throw researchError('当前完整请求没有足够的Evidence页预算,请使用已返回摘要或缩小请求范围。');
|
||||
const page = artifactPage({ id: job.evidence.id, sha256: viewSha256, kind: 'research-evidence-view' }, text, { offset, limit }, { maximumMessageBytes: maximumMessageBytes - reserve, callId });
|
||||
delete page.artifact_id;
|
||||
const result = { ...page, ...metadata, maximum_message_bytes: maximumMessageBytes };
|
||||
if (frameBytes(result) > maximumMessageBytes) throw researchError('Evidence页超过当前完整协议预算,未返回超限页面。');
|
||||
return result;
|
||||
}
|
||||
result(job) {
|
||||
const summary = job.evidenceBinding?.summary ?? null, statistics = job.evidenceBinding?.statistics ?? null;
|
||||
const summaryFits = Buffer.byteLength(JSON.stringify(summary), 'utf8') <= 2400;
|
||||
return { status: job.status === 'completed' ? 'completed' : 'failed', research_status: job.status, research_job_id: job.id,
|
||||
target_id: job.targetId, target_sha256: job.targetSha256, evidence_id: job.evidenceId ?? null, evidence_verified: !!job.evidenceBinding?.verified,
|
||||
evidence_artifact_id: job.evidence?.id ?? null, bundle_artifact_id: job.bundle?.id ?? null, raw_artifact_id: job.raw?.id ?? null,
|
||||
reused_from_job_id: job.reusedFromJobId ?? null, summary: summaryFits ? summary : null, summary_complete: summaryFits,
|
||||
summary_excerpt: summaryFits ? null : JSON.stringify(summary).slice(0, 2400),
|
||||
statistics: Buffer.byteLength(JSON.stringify(statistics), 'utf8') <= 1200 ? statistics : null,
|
||||
limitations: (job.evidenceBinding?.limitations ?? []).slice(0, 12).map(value => value.slice(0, 280)),
|
||||
limitations_complete: (job.evidenceBinding?.limitations ?? []).length <= 12 && (job.evidenceBinding?.limitations ?? []).every(value => value.length <= 280),
|
||||
message: job.summary.slice(0, 1500), requires_review: job.requiresVerification, scope: job.scope };
|
||||
}
|
||||
originalDocument(session, job, kind = 'bundle') {
|
||||
if (!['bundle', 'raw'].includes(kind) || !job[kind]) throw researchError('这个操作尚未保存所选原文。', 404);
|
||||
if (kind === 'bundle') this.verifiedEvidence(session, job);
|
||||
else if (job.reusedFromJobId) this.verifiedEvidence(session, job);
|
||||
else {
|
||||
const artifact = this.store.owned('artifact', job.raw.id, session.id);
|
||||
if (artifact.taskId !== job.taskId || artifact.runId !== job.runId) throw researchError('原响应不属于这次研究运行。');
|
||||
}
|
||||
return readResearchDocument(this.store, session, job[kind]);
|
||||
}
|
||||
async stop(sessionId) {
|
||||
const pending = [...this.active.values()].filter(value => value.sessionId === sessionId);
|
||||
for (const active of pending) { if (active.job && RESEARCH_ACTIVE.has(active.job.status)) active.job.status = 'stopping'; active.controller.abort(new Error('用户停止了所属研究操作。')); }
|
||||
await Promise.allSettled(pending.map(value => value.promise));
|
||||
}
|
||||
async stopAll() { await Promise.all([...new Set([...this.active.values()].map(value => value.sessionId))].map(id => this.stop(id))); }
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { spawn, execFile } from 'node:child_process';
|
||||
import { StringDecoder } from 'node:string_decoder';
|
||||
import { promisify } from 'node:util';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
||||
const failure = (code, message, dispatched = false) => Object.assign(new Error(message), { code, dispatched });
|
||||
|
||||
// One owned stdio connection. The caller chooses a fixed executable/profile;
|
||||
// target content never becomes a shell command or a server-request approval.
|
||||
export class McpStdio extends EventEmitter {
|
||||
constructor(launch, { timeoutMs = 45000, maximumFrameBytes = 8 * 1024 * 1024 } = {}) {
|
||||
super(); this.id = randomUUID(); this.pending = new Map(); this.sequence = 0; this.trace = [];
|
||||
this.timeoutMs = timeoutMs; this.maximumFrameBytes = maximumFrameBytes; this.stderr = ''; this.buffer = '';
|
||||
this.child = spawn(launch.executable, launch.args, { cwd: launch.cwd, env: launch.env,
|
||||
shell: false, windowsHide: true, detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe'] });
|
||||
this.pid = this.child.pid; this.startedAt = new Date().toISOString(); this.exited = false;
|
||||
this.exit = new Promise(resolve => { this.resolveExit = resolve; });
|
||||
const decoder = new StringDecoder('utf8');
|
||||
this.child.stdout.on('data', bytes => { this.buffer += decoder.write(bytes); this.consume(); });
|
||||
this.child.stderr.on('data', bytes => { this.stderr = (this.stderr + bytes.toString('utf8')).slice(-32000); });
|
||||
this.child.stdin.on('error', error => this.fail(failure('MCP_INPUT_CLOSED', error.message, true)));
|
||||
this.child.once('error', error => {
|
||||
this.exited = true; this.resolveExit({ code: null, signal: null, spawnError: error.message });
|
||||
this.fail(failure('MCP_START_FAILED', error.message));
|
||||
});
|
||||
this.child.once('exit', (code, signal) => {
|
||||
this.exited = true; this.resolveExit({ code, signal });
|
||||
});
|
||||
// The exit event precedes drained stdout. A final valid response can still
|
||||
// be delivered before close, and must not be replaced by a disconnect.
|
||||
this.child.once('close', () => this.fail(failure('MCP_DISCONNECTED', 'MCP进程已退出,未收到的结果不能推断为完成。', true)));
|
||||
}
|
||||
fail(error) {
|
||||
this.protocolError ??= error;
|
||||
for (const id of [...this.pending.keys()]) this.settle(id, error);
|
||||
}
|
||||
consume() {
|
||||
let newline;
|
||||
while ((newline = this.buffer.indexOf('\n')) >= 0) {
|
||||
const line = this.buffer.slice(0, newline); this.buffer = this.buffer.slice(newline + 1);
|
||||
if (!line.trim()) continue;
|
||||
if (Buffer.byteLength(line) > this.maximumFrameBytes) return this.fail(failure('MCP_FRAME_LIMIT', 'MCP结果超过工件接收上限。', true));
|
||||
let message;
|
||||
try { message = JSON.parse(line); } catch { return this.fail(failure('MCP_INVALID_FRAME', 'MCP返回了无效JSON帧。', true)); }
|
||||
if (!message || message.jsonrpc !== '2.0') return this.fail(failure('MCP_INVALID_FRAME', 'MCP返回了无效协议帧。', true));
|
||||
if (message.method) {
|
||||
if (message.id !== undefined) this.write({ jsonrpc: '2.0', id: message.id,
|
||||
error: { code: -32601, message: 'This profile does not grant server-initiated operations.' } });
|
||||
else this.emit('notification', message);
|
||||
continue;
|
||||
}
|
||||
if (!this.pending.has(message.id)) continue;
|
||||
if (('error' in message) === ('result' in message)) return this.fail(failure('MCP_INVALID_FRAME', 'MCP响应缺少唯一结果或错误字段。', true));
|
||||
if (message.error) this.settle(message.id, failure('MCP_REMOTE_ERROR', JSON.stringify(message.error), true));
|
||||
else this.settle(message.id, null, message.result);
|
||||
}
|
||||
if (Buffer.byteLength(this.buffer) > this.maximumFrameBytes) this.fail(failure('MCP_FRAME_LIMIT', 'MCP未结束帧超过接收上限。', true));
|
||||
}
|
||||
write(message, callback) {
|
||||
if (this.exited || this.child.stdin.destroyed) {
|
||||
callback?.(failure('MCP_INPUT_CLOSED', 'MCP连接已经关闭。')); return;
|
||||
}
|
||||
this.child.stdin.write(JSON.stringify(message) + '\n', 'utf8', callback);
|
||||
}
|
||||
notify(method, params) { this.write({ jsonrpc: '2.0', method, ...(params === undefined ? {} : { params }) }); }
|
||||
settle(id, error, result) {
|
||||
const pending = this.pending.get(id); if (!pending) return;
|
||||
this.pending.delete(id); clearTimeout(pending.timer); pending.signal?.removeEventListener('abort', pending.abort);
|
||||
pending.record.finishedAt = new Date().toISOString(); pending.record.status = error ? 'failed' : 'completed';
|
||||
pending.record.resultSha256 = error ? null : digest(result); pending.record.errorCode = error?.code ?? null;
|
||||
if (error?.dispatched === false) pending.record.dispatched = false;
|
||||
error ? pending.reject(error) : pending.resolve(result);
|
||||
}
|
||||
request(method, params = {}, { signal, timeoutMs = this.timeoutMs } = {}) {
|
||||
if (signal?.aborted) return Promise.reject(failure('MCP_CANCELLED', 'MCP请求在发送前已停止。'));
|
||||
if (this.exited || this.protocolError) return Promise.reject(this.protocolError ?? failure('MCP_DISCONNECTED', 'MCP进程未运行。'));
|
||||
return new Promise((resolve, reject) => {
|
||||
const id = ++this.sequence, record = { connectionId: this.id, id, method, parametersSha256: digest(params),
|
||||
startedAt: new Date().toISOString(), finishedAt: null, status: 'requesting', dispatched: true };
|
||||
this.trace.push(record);
|
||||
const abort = () => {
|
||||
this.notify('notifications/cancelled', { requestId: id, reason: 'Owned Workbench operation stopped.' });
|
||||
this.settle(id, failure('MCP_CANCELLED', '分析已请求停止,尚未返回的结果不算完成。', true));
|
||||
};
|
||||
const timer = setTimeout(() => {
|
||||
this.notify('notifications/cancelled', { requestId: id, reason: 'Owned Workbench request deadline.' });
|
||||
this.settle(id, failure('MCP_TIMEOUT', 'MCP请求到达等待上限,没有自动重试。', true));
|
||||
}, timeoutMs);
|
||||
this.pending.set(id, { resolve, reject, timer, abort, signal, record }); signal?.addEventListener('abort', abort, { once: true });
|
||||
this.write({ jsonrpc: '2.0', id, method, params }, error => { if (error) this.settle(id, failure('MCP_WRITE_FAILED', error.message, true)); });
|
||||
});
|
||||
}
|
||||
async close({ force = false } = {}) {
|
||||
if (this.closing) return this.closing;
|
||||
this.closing = this.finishClose(force); return this.closing;
|
||||
}
|
||||
async finishClose(force) {
|
||||
let killError = null;
|
||||
if (!this.exited && !force) {
|
||||
this.child.stdin.end();
|
||||
await Promise.race([this.exit, new Promise(resolve => setTimeout(resolve, 1000))]);
|
||||
}
|
||||
if (!this.exited && Number.isInteger(this.pid)) {
|
||||
try {
|
||||
if (process.platform === 'win32') await execute('taskkill.exe', ['/PID', String(this.pid), '/T', '/F'], { windowsHide: true, timeout: 5000 });
|
||||
else { try { process.kill(-this.pid, 'SIGTERM'); } catch { this.child.kill('SIGTERM'); }
|
||||
await Promise.race([this.exit, new Promise(resolve => setTimeout(resolve, 500))]);
|
||||
if (!this.exited) { try { process.kill(-this.pid, 'SIGKILL'); } catch { this.child.kill('SIGKILL'); } } }
|
||||
} catch (error) { killError = error.message; }
|
||||
await Promise.race([this.exit, new Promise(resolve => setTimeout(resolve, 2000))]);
|
||||
}
|
||||
this.fail(failure('MCP_CLOSED', '所属MCP连接已关闭,未知结果不重放。', true));
|
||||
if (this.exited) { this.child.stdout.destroy(); this.child.stderr.destroy(); this.child.stdin.destroy(); }
|
||||
return { connectionId: this.id, pid: this.pid ?? null, rootExited: this.exited, forced: force, killError,
|
||||
exit: this.exited ? await this.exit : null, scope: 'owned-stdio-process', finishedAt: new Date().toISOString() };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
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' }); }
|
||||
}
|
||||
@@ -86,6 +86,7 @@ return async (request, response) => {
|
||||
session: session ? { ...sessionSnapshot(session, store.project(session.projectId), store.config, value => provider.redact(value)), execution: store.executionSnapshot(session) } : null,
|
||||
});
|
||||
}
|
||||
if (method === 'GET' && route === '/api/research/availability') return json(response, runtime.researchManager().availability());
|
||||
if (method === 'GET' && route === '/api/events') {
|
||||
const cursor = Math.max(cursorNumber(url.searchParams.get('after')), cursorNumber(request.headers['last-event-id']));
|
||||
if (cursor > store.eventCursor) throw Object.assign(new Error('事件游标超出当前历史,请重新加载工作台。'), { status: 409 });
|
||||
@@ -146,6 +147,37 @@ return async (request, response) => {
|
||||
const session = store.session(id);
|
||||
if (method === 'GET' && !action) return json(response, store.publicSession(session));
|
||||
if (method === 'GET' && action === 'execution') return json(response, store.executionSnapshot(session));
|
||||
if (method === 'GET' && action === 'research') {
|
||||
const manager = runtime.researchManager(); return json(response, { availability: manager.availability(), targets: manager.targets(session), jobs: manager.jobs(session) });
|
||||
}
|
||||
if (method === 'POST' && action === 'research/targets') {
|
||||
const target = await runtime.researchManager().register(session, await body(request));
|
||||
return json(response, { target, session: store.publicSession(session) }, 201);
|
||||
}
|
||||
if (method === 'POST' && action === 'research/jobs') {
|
||||
const input = await body(request);
|
||||
if (input.refresh !== undefined && typeof input.refresh !== 'boolean') throw Object.assign(new Error('重新分析选项需要布尔值。'), { status: 400 });
|
||||
const started = runtime.researchManager().start(session, input.targetId, input.operation, { source: 'user', refresh: input.refresh === true });
|
||||
return json(response, { job: started.job, session: store.publicSession(session) }, 202);
|
||||
}
|
||||
if (method === 'POST' && action === 'research/stop') { await runtime.researchManager().stop(id); return json(response, store.publicSession(session)); }
|
||||
const researchJob = action.match(/^research\/jobs\/([a-f0-9-]+)(?:\/(evidence|raw|download))?$/);
|
||||
if (method === 'GET' && researchJob) {
|
||||
const manager = runtime.researchManager(), job = store.owned('research_job', researchJob[1], id);
|
||||
if (!researchJob[2]) return json(response, job);
|
||||
if (researchJob[2] === 'evidence') return json(response, manager.readEvidence(session, job.id, { pointer: url.searchParams.get('pointer') ?? '/normalized_result',
|
||||
offset: cursorNumber(url.searchParams.get('offset')), limit: Math.min(16000, Math.max(1, cursorNumber(url.searchParams.get('limit')) || 4000)), maximumMessageBytes: 100000 }));
|
||||
if (researchJob[2] === 'raw') {
|
||||
const text = manager.originalDocument(session, job, 'raw'), offset = cursorNumber(url.searchParams.get('offset')),
|
||||
limit = Math.min(16000, Math.max(1, cursorNumber(url.searchParams.get('limit')) || 4000));
|
||||
return json(response, { content: text.slice(offset, offset + limit), offset, next_offset: Math.min(text.length, offset + limit),
|
||||
total_characters: text.length, truncated: offset + limit < text.length, source_document_sha256: job.raw.documentSha256 });
|
||||
}
|
||||
const kind = url.searchParams.get('kind') ?? 'bundle', original = manager.originalDocument(session, job, kind);
|
||||
response.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store',
|
||||
'X-Content-Type-Options': 'nosniff', 'Content-Disposition': 'attachment; filename="agent-workbench-rea-' + job.id + '.json"' });
|
||||
response.end(original); return;
|
||||
}
|
||||
if (method === 'GET' && action === 'workspaces') return json(response, store.executionSnapshot(session).workspaces);
|
||||
if (method === 'POST' && action === 'workspaces') {
|
||||
const input = await body(request);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { randomUUID, createHash } from 'node:crypto';
|
||||
|
||||
export const APP_VERSION = '1.7.0';
|
||||
export const APP_VERSION = '1.8.0';
|
||||
|
||||
export function executionEnvironment() {
|
||||
const windows = process.platform === 'win32';
|
||||
|
||||
@@ -11,13 +11,13 @@ import { APP_VERSION } from './diagnostics.mjs';
|
||||
export function installUpgrade(context, { appDirectory, updateServiceInfo = true }) {
|
||||
const { server, store, provider, runtime, token, clients, started, exampleProject, shutdown } = context;
|
||||
if (!server?.listening || !store || !provider || !runtime || !clients || !token) throw new Error('The existing Workbench context is incomplete.');
|
||||
if (runtime.active.size || runtime.waiters.size || runtime.checks?.active.size || runtime.deliveries?.active.size || runtime.changeSets?.projects.size || runtime.workspaces?.projects.size || runtime.workspaces?.pending.size) throw new Error('Wait for active tasks, checks, Git deliveries, file batches, workspaces and approvals to finish before upgrading.');
|
||||
if (runtime.active.size || runtime.waiters.size || runtime.checks?.active.size || runtime.deliveries?.active.size || runtime.changeSets?.projects.size || runtime.workspaces?.projects.size || runtime.workspaces?.pending.size || runtime.research?.active.size) throw new Error('Wait for active tasks, checks, Git deliveries, file batches, workspaces, research and approvals to finish before upgrading.');
|
||||
const root = fs.realpathSync.native(path.resolve(appDirectory));
|
||||
if (!fs.existsSync(path.join(root, 'dist-client', 'index.html'))) throw new Error('The new client bundle is missing.');
|
||||
const oldHandlers = server.listeners('request');
|
||||
const oldPrototypes = [Object.getPrototypeOf(store), Object.getPrototypeOf(provider), Object.getPrototypeOf(runtime)];
|
||||
const oldStoreProperties = { ...store };
|
||||
const oldRuntimeProperties = { appDirectory: runtime.appDirectory, checks: runtime.checks, deliveries: runtime.deliveries, codeIndex: runtime.codeIndex, changeSets: runtime.changeSets, contextPlans: runtime.contextPlans, workspaces: runtime.workspaces };
|
||||
const oldRuntimeProperties = { appDirectory: runtime.appDirectory, checks: runtime.checks, deliveries: runtime.deliveries, codeIndex: runtime.codeIndex, changeSets: runtime.changeSets, contextPlans: runtime.contextPlans, workspaces: runtime.workspaces, research: runtime.research };
|
||||
const oldUpdates = store.listeners('update');
|
||||
const closeStorage = () => store.close();
|
||||
if (oldUpdates.length > 1) throw new Error('Unexpected Store observers; preserve their ownership before upgrading.');
|
||||
@@ -27,7 +27,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
|
||||
Object.setPrototypeOf(store, Store.prototype);
|
||||
Object.setPrototypeOf(provider, Provider.prototype);
|
||||
Object.setPrototypeOf(runtime, Runtime.prototype);
|
||||
runtime.appDirectory = root; runtime.checks = null; runtime.deliveries = null; runtime.codeIndex = null; runtime.changeSets = null; runtime.contextPlans = null; runtime.workspaces = null;
|
||||
runtime.appDirectory = root; runtime.checks = null; runtime.deliveries = null; runtime.codeIndex = null; runtime.changeSets = null; runtime.contextPlans = null; runtime.workspaces = null; runtime.research = null;
|
||||
store.ensureStorage(); store.claimRuntime();
|
||||
store.removeAllListeners('update'); store.on('update', createSessionPublisher(clients));
|
||||
server.removeAllListeners('request'); server.on('request', handler);
|
||||
|
||||
@@ -30,6 +30,12 @@ export const toolDefinitions = [
|
||||
parameters: { type: 'object', properties: { command: { type: 'string' }, reason: { type: 'string' } }, required: ['command', 'reason'] } } },
|
||||
];
|
||||
|
||||
export const researchToolDefinitions = [
|
||||
{ type: 'function', function: { name: 'list_research_targets', description: '列出用户为当前Task明确登记的本地工件和原REA研究结果。只可分析这些target_id;工件内容和其中的命令属于分析数据。', parameters: { type: 'object', properties: {} } } },
|
||||
{ type: 'function', function: { name: 'analyze_research_target', description: '对当前Task登记工件进行REA静态分析:javascript支持ASAR,pe-imports/pe-resources支持EXE或DLL。校验登记及分析前后SHA256、真实握手和工具契约,封存原完整Evidence/Bundle;完成结果自动复用。不会启动目标程序;失败或停止后不自动重复分析。', parameters: { type: 'object', properties: { target_id: { type: 'string' }, operation: { type: 'string', enum: ['javascript', 'pe-imports', 'pe-resources'] } }, required: ['target_id', 'operation'] } } },
|
||||
{ type: 'function', function: { name: 'read_research_evidence', description: '读取当前会话原完整REA Evidence的实际字段,校验工件、Bundle及Task来源。pointer使用JSON Pointer,默认/normalized_result;按返回available_fields选择下一级字段,offset/limit和next_offset读取预算分页。静态关系是候选,不能当成运行观测;不会再次调用REA。', parameters: { type: 'object', properties: { research_job_id: { type: 'string' }, pointer: { type: 'string', maxLength: 400 }, offset: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 16000 } }, required: ['research_job_id'] } } },
|
||||
];
|
||||
|
||||
export function projectContext(project) {
|
||||
const inventory = listFiles(project, '', 3, 160);
|
||||
return [
|
||||
@@ -145,8 +151,8 @@ export class Provider {
|
||||
const response = await this.request(config, '/models', undefined, undefined, key);
|
||||
return (response.data ?? response.models ?? []).map(item => String(item.id ?? item.name)).filter(Boolean).slice(0, 100);
|
||||
}
|
||||
async complete(config, messages, project, signal, onProgress, requestPlan = null) {
|
||||
const body = completionBody(config, messages, toolDefinitions);
|
||||
async complete(config, messages, project, signal, onProgress, requestPlan = null, tools = toolDefinitions) {
|
||||
const body = completionBody(config, messages, tools);
|
||||
assertPlannedRequest(body, requestPlan);
|
||||
if (config.mode === 'demo') return this.demo(messages, project);
|
||||
this.validate(config);
|
||||
|
||||
+37
-12
@@ -3,7 +3,7 @@ import path from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { StringDecoder } from 'node:string_decoder';
|
||||
import { safePath, listFiles, readLines, searchFiles, proposeFile, proposePatch } from './files.mjs';
|
||||
import { projectContext, toolDefinitions } from './provider.mjs';
|
||||
import { projectContext, toolDefinitions, researchToolDefinitions } from './provider.mjs';
|
||||
import { now, repairToolPairs } from './store.mjs';
|
||||
import { executionEnvironment, sessionContext, sessionSnapshot } from './diagnostics.mjs';
|
||||
import { BudgetExceeded, checkBudget } from '../shared/contracts/execution.mjs';
|
||||
@@ -18,14 +18,26 @@ import { assertChangeSetsResolved } from '../shared/contracts/change-sets.mjs';
|
||||
import { pendingDeliveryReview } from '../shared/contracts/delivery-review.mjs';
|
||||
import { WorkspaceManager, verifyWorkspaceProject } from '../core/workspaces/git-workspaces.mjs';
|
||||
import { assertWorkspacesResolved, projectWorkspaceIdentity } from '../shared/contracts/workspaces.mjs';
|
||||
import { ResearchManager } from '../core/research-manager.mjs';
|
||||
|
||||
const labels = { inspect_session: '核对工作台运行记录', inspect_project: '识别工程与Git基线', index_project: '建立工程符号索引', query_code: '定位工程符号与导入', propose_patch: '准备精确补丁', plan_checks: '准备工程检查计划', run_checks: '执行工程检查', plan_delivery: '准备Git交付预览', delivery_report: '生成工程证据报告', read_artifact: '读取执行日志工件', list_files: '查看项目文件', read_file: '读取文件', search_files: '搜索项目', propose_file: '准备文件改动', run_command: '运行终端命令' };
|
||||
|
||||
labels.prepare_change_set = '准备多文件变更集';
|
||||
labels.list_research_targets = '查看本任务登记工件';
|
||||
labels.analyze_research_target = 'REA静态分析登记工件';
|
||||
labels.read_research_evidence = '读取原REA Evidence字段';
|
||||
|
||||
export function validateToolArgs(tool, args) {
|
||||
if (!Object.hasOwn(labels, tool)) throw new Error('当前能力表没有工具:' + tool);
|
||||
if (!args || typeof args !== 'object' || Array.isArray(args)) throw new Error('工具参数必须是 JSON 对象。');
|
||||
if (['list_research_targets', 'analyze_research_target', 'read_research_evidence'].includes(tool)) {
|
||||
if (tool === 'analyze_research_target' && (typeof args.target_id !== 'string' || !['javascript', 'pe-imports', 'pe-resources'].includes(args.operation))) throw new Error('REA分析需要登记target_id和实际支持的静态分析方式。');
|
||||
if (tool === 'read_research_evidence' && (typeof args.research_job_id !== 'string' || args.pointer !== undefined && typeof args.pointer !== 'string')) throw new Error('Evidence读取需要research_job_id及有效字段。');
|
||||
if (args.refresh !== undefined || args.path !== undefined) throw new Error('模型只能使用已登记工件,重新分析由用户发起。');
|
||||
for (const field of ['offset', 'limit']) if (args[field] !== undefined && (!Number.isInteger(args[field]) || args[field] < (field === 'limit' ? 1 : 0) || field === 'limit' && args[field] > 16000)) throw new Error('Evidence分页范围无效。');
|
||||
if (args.pointer !== undefined && args.pointer.length > 400) throw new Error('Evidence字段超过400字符。');
|
||||
return;
|
||||
}
|
||||
if (tool === 'prepare_change_set') {
|
||||
if (!Array.isArray(args.change_ids) || !args.change_ids.length || args.change_ids.length > 32
|
||||
|| args.change_ids.some(id => typeof id !== 'string' || !/^[a-f0-9-]{36}$/i.test(id))
|
||||
@@ -50,32 +62,36 @@ export class Runtime {
|
||||
this.appDirectory = appDirectory;
|
||||
this.active = new Map(); this.waiters = new Map();
|
||||
}
|
||||
isActive(id) { return this.active.has(id) || !!this.checks?.isActive(id) || !!this.deliveries?.isActive(id) || !!this.changeSets?.isActive(id) || !!this.workspaces?.isActive(id); }
|
||||
hasActivity() { return this.active.size > 0 || (this.checks?.active.size ?? 0) > 0 || (this.deliveries?.active.size ?? 0) > 0 || (this.changeSets?.projects.size ?? 0) > 0 || (this.workspaces?.projects.size ?? 0) > 0 || (this.workspaces?.pending.size ?? 0) > 0; }
|
||||
isActive(id) { return this.active.has(id) || !!this.checks?.isActive(id) || !!this.deliveries?.isActive(id) || !!this.changeSets?.isActive(id) || !!this.workspaces?.isActive(id) || !!this.research?.isActive(id); }
|
||||
hasActivity() { return this.active.size > 0 || (this.checks?.active.size ?? 0) > 0 || (this.deliveries?.active.size ?? 0) > 0 || (this.changeSets?.projects.size ?? 0) > 0 || (this.workspaces?.projects.size ?? 0) > 0 || (this.workspaces?.pending.size ?? 0) > 0 || (this.research?.active.size ?? 0) > 0; }
|
||||
projectIndexer() { return this.codeIndex ??= new ProjectIndex(); }
|
||||
requestPlanner() { return this.contextPlans ??= new RequestPlanner(this.store); }
|
||||
researchManager() {
|
||||
return this.research ??= new ResearchManager(this.store, { appDirectory: this.appDirectory,
|
||||
redact: value => this.provider.redact(value), projectBusy: (projectId, exceptId) => this.projectHasActivity(projectId, exceptId) });
|
||||
}
|
||||
projectHasActivity(projectId, exceptSessionId = null) {
|
||||
return [...this.active.entries()].some(([id, run]) => id !== exceptSessionId && run.project.id === projectId) || !!this.checks?.projectActive(projectId) || !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId);
|
||||
return [...this.active.entries()].some(([id, run]) => id !== exceptSessionId && run.project.id === projectId) || !!this.checks?.projectActive(projectId) || !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) || !!this.research?.projectActive(projectId);
|
||||
}
|
||||
workspaceManager() {
|
||||
return this.workspaces ??= new WorkspaceManager(this.store, { initialize: this.store.core.workspace.size === 0,
|
||||
redact: value => this.provider.redact(value), projectBusy: projectId =>
|
||||
[...this.active.values()].some(run => run.project.id === projectId) || !!this.checks?.projectActive(projectId)
|
||||
|| !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) });
|
||||
|| !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.research?.projectActive(projectId) });
|
||||
}
|
||||
changeSetManager() {
|
||||
return this.changeSets ??= new ChangeSetManager(this.store, { projectBusy: (projectId, exceptId) =>
|
||||
[...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId)
|
||||
|| !!this.checks?.projectActive(projectId) || !!this.deliveries?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) });
|
||||
|| !!this.checks?.projectActive(projectId) || !!this.deliveries?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) || !!this.research?.projectActive(projectId) });
|
||||
}
|
||||
checkRunner() {
|
||||
return this.checks ??= new CheckRunner(this.store, { redact: value => this.provider.redact(value), runtimeDirectory: this.appDirectory ? path.join(this.appDirectory, 'runtime') : null,
|
||||
pythonRunnerPath: path.join(this.appDirectory ?? process.cwd(), 'scripts', 'python-check-runner.py'),
|
||||
projectBusy: (projectId, exceptId) => [...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId) || !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) });
|
||||
projectBusy: (projectId, exceptId) => [...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId) || !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) || !!this.research?.projectActive(projectId) });
|
||||
}
|
||||
gitDelivery() {
|
||||
return this.deliveries ??= new GitDelivery(this.store, { redact: value => this.provider.redact(value),
|
||||
projectBusy: (projectId, exceptId) => [...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId) || !!this.checks?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) });
|
||||
projectBusy: (projectId, exceptId) => [...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId) || !!this.checks?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) || !!this.research?.projectActive(projectId) });
|
||||
}
|
||||
start(id, content, resume = false, { instructionSource = null } = {}) {
|
||||
const session = this.store.session(id);
|
||||
@@ -149,7 +165,9 @@ export class Runtime {
|
||||
}) + '\n结果未知的调用,不得假定成功或重放:' + JSON.stringify(unknown)
|
||||
+ '\n' + sessionContext(session, run.project, config, value => this.provider.redact(value))
|
||||
+ (task.readProgress?.warning ? '\n当前读取进展:' + task.readProgress.warning : ''));
|
||||
const planned = this.requestPlanner().prepare(session, run.record, config, { system: context, tools: toolDefinitions, stepId: stepRecord.id });
|
||||
const tools = [...this.store.core.research_target.values()].some(target => target.sessionId === session.id && target.taskId === run.taskId)
|
||||
? [...toolDefinitions, ...researchToolDefinitions] : toolDefinitions;
|
||||
const planned = this.requestPlanner().prepare(session, run.record, config, { system: context, tools, stepId: stepRecord.id });
|
||||
if (planned.record.archivedGroups && !projectionLogged) {
|
||||
projectionLogged = true; session.compactions++;
|
||||
this.store.event(session, { kind: 'context', label: '整理请求上下文', phase: 'completed', contextPlanId: planned.record.id,
|
||||
@@ -174,7 +192,7 @@ export class Runtime {
|
||||
if (progress.durationMs !== undefined) requestEvent.durationMs = progress.durationMs;
|
||||
if (['completed', 'failed'].includes(progress.phase)) requestEvent.finishedAt = now();
|
||||
this.store.save(session);
|
||||
}, planned.record);
|
||||
}, planned.record, tools);
|
||||
this.requestPlanner().finish(session, planned.record, { response, attempts: planned.record.requestAttempts });
|
||||
} catch (error) {
|
||||
this.requestPlanner().finish(session, planned.record, { error: Object.assign(new Error(this.provider.redact(error.message ?? String(error))), { name: signal.aborted ? 'AbortError' : error.name }), attempts: planned.record.requestAttempts });
|
||||
@@ -274,6 +292,13 @@ export class Runtime {
|
||||
if (!['run_command', 'run_checks'].includes(tool)) this.store.invocationState(session, event, 'running');
|
||||
else this.store.save(session);
|
||||
if (tool === 'inspect_session') result = { ...sessionSnapshot(session, run.project, run.config, value => this.provider.redact(value)), execution: this.store.executionSnapshot(session) };
|
||||
else if (tool === 'list_research_targets') result = { targets: this.researchManager().targets(session), jobs: this.researchManager().jobs(session).filter(job => job.taskId === run.taskId).map(job => this.researchManager().result(job)) };
|
||||
else if (tool === 'analyze_research_target') {
|
||||
const manager = this.researchManager(), started = manager.start(session, args.target_id, args.operation, { source: 'agent', signal: run.controller.signal });
|
||||
result = manager.result(await started.promise);
|
||||
}
|
||||
else if (tool === 'read_research_evidence') result = this.researchManager().readEvidence(session, args.research_job_id,
|
||||
{ ...args, maximumMessageBytes: run.readMessageBytes ?? 16000, callId: call.id });
|
||||
else if (tool === 'inspect_project') result = await inspectProject(run.project);
|
||||
else if (tool === 'index_project') {
|
||||
const index = await this.projectIndexer().refresh(run.project);
|
||||
@@ -435,11 +460,11 @@ export class Runtime {
|
||||
}
|
||||
async stop(sessionId) {
|
||||
const run = this.active.get(sessionId);
|
||||
if (!run) { await this.checks?.stop(sessionId); await this.deliveries?.stop(sessionId); await this.changeSets?.stop(sessionId); await this.workspaces?.stop(sessionId); return; }
|
||||
if (!run) { await this.checks?.stop(sessionId); await this.deliveries?.stop(sessionId); await this.changeSets?.stop(sessionId); await this.workspaces?.stop(sessionId); await this.research?.stop(sessionId); return; }
|
||||
const session = this.store.session(sessionId);
|
||||
session.status = 'stopping'; this.store.save(session);
|
||||
run.controller.abort(new Error('用户停止任务'));
|
||||
await run.promise;
|
||||
}
|
||||
async stopAll() { await Promise.all([...this.active.keys()].map(id => this.stop(id))); await this.checks?.stopAll(); await this.deliveries?.stopAll(); await this.changeSets?.stopAll(); await this.workspaces?.stopAll(); }
|
||||
async stopAll() { await Promise.all([...this.active.keys()].map(id => this.stop(id))); await this.checks?.stopAll(); await this.deliveries?.stopAll(); await this.changeSets?.stopAll(); await this.workspaces?.stopAll(); await this.research?.stopAll(); }
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { ArtifactStore } from '../core/storage/artifact-store.mjs';
|
||||
import { collectLegacy, cleanConfig } from '../core/storage/legacy-import.mjs';
|
||||
import { ACTIVE_STATES, CORE_KINDS, createTask, createRun, ownedRecord, emptyUsage, accumulateUsage, accountedTokens, isId } from '../shared/contracts/execution.mjs';
|
||||
import { WORKSPACE_ACTIVE, projectWorkspaceIdentity, assertWorkspacePath } from '../shared/contracts/workspaces.mjs';
|
||||
import { RESEARCH_ACTIVE } from '../shared/contracts/research.mjs';
|
||||
|
||||
export const now = () => new Date().toISOString();
|
||||
|
||||
@@ -216,6 +217,13 @@ export class Store extends EventEmitter {
|
||||
workspace.summary = '隔离工作区创建中断,请核对实际目录、分支和Git登记。不会重放创建、删除或重置。';
|
||||
session.status = 'paused'; session.recoveryNotice = workspace.summary; changed = true;
|
||||
}
|
||||
for (const job of this.core.research_job.values()) if (job.sessionId === session.id && RESEARCH_ACTIVE.has(job.status)) {
|
||||
job.status = job.analysisDispatched ? 'unknown' : 'interrupted'; job.requiresVerification = !!job.analysisDispatched; job.finishedAt = now();
|
||||
job.evidenceBinding = null; job.summary = '研究连接中断,未保存可核验完成结果。原进程关闭状态未知;不会根据历史PID停止进程或重放分析。';
|
||||
const event = session.events.find(value => value.id === job.eventId);
|
||||
if (event) { event.phase = job.status; event.finishedAt = job.finishedAt; event.output = job.summary; }
|
||||
changed = true;
|
||||
}
|
||||
for (const event of session.events ?? []) {
|
||||
if (['running', 'waiting', 'retrying'].includes(event.phase)) {
|
||||
const invocation = [...this.core.tool.values()].find(item => item.sessionId === session.id && item.callId === event.toolCallId);
|
||||
@@ -512,6 +520,8 @@ export class Store extends EventEmitter {
|
||||
progress: { totalTools: tools.length, completedTools: tools.filter(value => value.state === 'completed').length,
|
||||
requiresVerification: tools.filter(value => value.requiresVerification).map(value => ({ id: value.id, tool: value.tool, callId: value.callId, state: value.state })) },
|
||||
artifacts, checks: jobs,
|
||||
researchTargets: [...this.core.research_target.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-32),
|
||||
researchJobs: [...this.core.research_job.values()].filter(value => value.sessionId === session.id && (value.taskId === task?.id || value.requiresVerification)).slice(-20),
|
||||
contextPlans: [...this.core.context_plan.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-30),
|
||||
changeSets: [...this.core.change_set.values()].filter(value => value.sessionId === session.id && (value.taskId === task?.id || value.requiresVerification)).slice(-12),
|
||||
plans: [...this.core.check_plan.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-5),
|
||||
|
||||
@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto';
|
||||
|
||||
export const EXECUTION_SCHEMA = 1;
|
||||
export const ACTIVE_STATES = new Set(['running', 'awaiting_approval', 'stopping']);
|
||||
export const CORE_KINDS = ['task', 'run', 'step', 'tool', 'artifact', 'check_plan', 'check_job', 'delivery_plan', 'delivery_job', 'change_set', 'context_plan', 'workspace'];
|
||||
export const CORE_KINDS = ['task', 'run', 'step', 'tool', 'artifact', 'check_plan', 'check_job', 'delivery_plan', 'delivery_job', 'change_set', 'context_plan', 'workspace', 'research_target', 'research_job'];
|
||||
export const timestamp = () => new Date().toISOString();
|
||||
export const isId = value => typeof value === 'string' && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(value);
|
||||
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
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 } = {}) {
|
||||
if (typeof filename !== 'string' || !filename.trim() || filename.length > 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 > 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 > 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') {
|
||||
if (typeof pointer !== 'string' || pointer.length > 400 || !pointer.startsWith('/') || pointer.split('/').length > 12) throw researchError('Evidence字段需要有效JSON Pointer,最多10层。', 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 > 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 > 160
|
||||
|| manifest.bytes > 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;
|
||||
}
|
||||
Reference in New Issue
Block a user