feat: verify owned DeepSeek engine connections and responsive task execution

This commit is contained in:
Agent Workbench Dev
2026-10-30 07:25:09 +08:00
parent 1d8abaceab
commit 91981c1400
69 changed files with 4068 additions and 50 deletions
+8 -3
View File
@@ -8,13 +8,14 @@ import { TaskPanel } from './TaskPanel';
import { CodeIndexPanel } from './CodeIndexPanel';
import { ChangesInspector } from './ChangesInspector';
import { ResearchPanel } from './ResearchPanel';
import { EnginePanel } from './EnginePanel';
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 };
export default function App() {
const [token, setAccess] = useState('');
const [version, setVersion] = useState('1.7.0');
const [version, setVersion] = useState('1.9.0');
const [diagnosticsOpen, setDiagnosticsOpen] = useState(false);
const [diagnostics, setDiagnostics] = useState<RuntimeDiagnostics | null>(null);
const [diagnosticsBusy, setDiagnosticsBusy] = useState(false);
@@ -62,6 +63,7 @@ export default function App() {
const [toast, setToast] = useState('');
const [researchOpen, setResearchOpen] = useState(false);
const [reaOpen, setReaOpen] = useState(false);
const [engineOpen, setEngineOpen] = useState(false);
const [researchDocs, setResearchDocs] = useState<ResearchDoc[]>([]);
const [report, setReport] = useState<{ title: string; content: string } | null>(null);
const chatEnd = useRef<HTMLDivElement>(null);
@@ -84,7 +86,8 @@ export default function App() {
|| 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?.researchJobs?.some(value => ['queued', 'connecting', 'analyzing', 'stopping'].includes(value.status)) === true);
|| session.execution?.researchJobs?.some(value => ['queued', 'connecting', 'analyzing', 'stopping'].includes(value.status)) === true
|| session.execution?.engineJobs?.some(value => ['queued', 'starting', 'initializing', 'checking', '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;
@@ -122,7 +125,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(''); setReaOpen(false);
workspaceRequest.current++; selectedSessionRef.current = id; setSessionId(id); setSession(null); setToast(''); setReaOpen(false); setEngineOpen(false);
localStorage.setItem('awb-session', id); setChangeId(''); setEventId('');
}
function acceptSession(updated: Session) {
@@ -495,6 +498,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="本地代理引擎" onClick={() => setEngineOpen(true)} disabled={!session}><Link2 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>}
@@ -534,6 +538,7 @@ export default function App() {
<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>}
{engineOpen && session && selectedProject && <Modal title="本地代理引擎" description="本地安装、实际连接与原检查记录。" wide onClose={() => setEngineOpen(false)}><EnginePanel 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>
+73
View File
@@ -0,0 +1,73 @@
.engine-panel { color: var(--ink); min-width: 0; }
.engine-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 24px; margin-bottom: 23px; }
.engine-eyebrow { color: var(--teal); font-size: 11px; letter-spacing: .04em; }
.engine-heading h3 { font-size: 23px; font-weight: 650; letter-spacing: -.035em; line-height: 1.4; margin: 5px 0 8px; }
.engine-heading p { color: var(--muted); font-size: 12px; line-height: 1.8; max-width: 570px; }
.engine-install-state { color: #8b5734; font-size: 11px; border: 1px solid #e8dccc; border-radius: 5px; padding: 6px 9px; flex-shrink: 0; margin-top: 7px; }
.engine-install-state.found { color: var(--teal); background: #eff7f3; border-color: #c6ded4; }
.engine-layout { display: grid; grid-template-columns: minmax(240px, .82fr) minmax(0, 1.45fr); gap: 24px; }
.engine-connection, .engine-results { min-width: 0; }
.engine-panel h4 { display: flex; align-items: center; gap: 8px; font-size: 13px; font-weight: 650; margin-bottom: 14px; }
.engine-connection form { border: 1px solid var(--line); border-radius: 7px; background: var(--paper); padding: 18px; }
.engine-connection .form-field { margin-bottom: 13px; }
.engine-detection-note { font-size: 12px; line-height: 1.8; color: #8b5734; margin: 13px 0; overflow-wrap: anywhere; }
.engine-detection-note.available { color: var(--teal); }
.engine-install-details { display: grid; grid-template-columns: 70px minmax(0, 1fr); gap: 10px; font-size: 11px; margin: 16px 0; }
.engine-install-details dt { color: var(--muted); }
.engine-install-details dd { margin: 0; line-height: 1.7; overflow-wrap: anywhere; }
.engine-start { margin-top: 14px; }
.engine-scope { padding: 23px 2px 0; }
.engine-scope > p { display: flex; align-items: center; gap: 7px; color: var(--teal); font-size: 12px; margin-bottom: 12px; }
.engine-scope-next { border-top: 1px solid var(--line); margin-top: 19px; padding-top: 15px; }
.engine-scope-next > span { font-size: 11px; color: #59706b; }
.engine-scope-next p, .engine-scope details p { font-size: 12px; color: var(--muted); line-height: 1.85; margin-top: 8px; }
.engine-scope details { margin-top: 17px; font-size: 11px; color: var(--muted); }
.engine-scope summary { cursor: pointer; }
.engine-results-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
.engine-results-heading h4 span { color: var(--muted); font-size: 11px; font-weight: 400; }
.engine-empty { border: 1px dashed #cbdcd3; border-radius: 7px; padding: 41px 24px; display: flex; flex-direction: column; gap: 12px; align-items: flex-start; color: var(--muted); }
.engine-empty strong { font-size: 15px; font-weight: 550; color: var(--ink); }
.engine-empty p { font-size: 12px; line-height: 1.85; max-width: 380px; }
.engine-job { border: 1px solid var(--line); background: var(--paper); padding: 17px; margin-bottom: 13px; border-radius: 7px; min-width: 0; }
.engine-job.verified { border-left: 3px solid #5b9886; padding-left: 15px; }
.engine-job-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
.engine-job-heading strong { font-size: 13px; display: block; }
.engine-job-heading small { display: block; color: var(--muted); font-size: 11px; margin-top: 5px; }
.engine-job-state { display: inline-flex; align-items: center; gap: 5px; font-size: 10px; color: #766449; padding-top: 2px; flex-shrink: 0; }
.engine-job-state.completed { color: var(--teal); }
.engine-job-state.failed, .engine-job-state.unknown { color: #a34d35; }
.engine-job-summary { color: var(--muted); font-size: 12px; line-height: 1.85; margin: 13px 0; overflow-wrap: anywhere; }
.engine-proof { display: flex; align-items: center; justify-content: space-between; gap: 7px; padding: 13px 0; margin-bottom: 13px; border-block: 1px solid #e3ece7; color: #859892; }
.engine-proof > div { display: flex; align-items: center; gap: 7px; min-width: 0; }
.engine-proof > div.observed { color: var(--teal); }
.engine-proof span { font-size: 9px; }
.engine-proof code { display: block; font-size: 10px; margin-top: 5px; overflow-wrap: anywhere; }
.engine-job-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 9px 12px; }
.engine-job-actions .button { padding: 7px 9px; font-size: 11px; }
.engine-job-actions .text-button { font-size: 11px; }
.engine-origin { border-top: 1px solid var(--line); padding-top: 10px; margin-top: 15px; font-size: 10px; color: var(--muted); }
.engine-origin summary { cursor: pointer; }
.engine-origin dl { display: grid; grid-template-columns: 87px minmax(0, 1fr); gap: 9px; margin-top: 14px; }
.engine-origin dt, .engine-origin dd { margin: 0; line-height: 1.7; min-width: 0; overflow-wrap: anywhere; }
.engine-retry-note { overflow-wrap: anywhere; margin-bottom: 14px; color: var(--teal); font-size: 12px; }
.engine-record-meta { font-size: 11px; color: var(--muted); border-bottom: 1px solid var(--line); padding-bottom: 13px; margin-bottom: 16px; }
.engine-record-meta code { display: block; overflow-wrap: anywhere; margin-top: 7px; font-size: 10px; }
.engine-original { margin: 0; padding: 17px; background: #f1f5f2; border: 1px solid var(--line); border-radius: 5px; font-size: 11px; line-height: 1.8; max-height: 44vh; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; }
.engine-page-controls { display: flex; align-items: center; gap: 9px; flex-wrap: wrap; margin-top: 14px; font-size: 11px; color: var(--muted); }
.engine-page-controls > span { margin-right: auto; }
@media (max-width: 800px) { .engine-layout { grid-template-columns: minmax(0, 1fr); gap: 26px; } }
@media (max-width: 620px) {
.engine-heading { display: block; margin-bottom: 20px; }
.engine-heading h3 { font-size: 21px; }
.engine-install-state { display: inline-block; margin-top: 14px; }
.engine-connection form { padding: 15px; }
.engine-job { padding: 13px; }
.engine-job.verified { padding-left: 11px; }
.engine-job-heading { flex-wrap: wrap; gap: 8px; }
.engine-proof { gap: 4px; }
.engine-proof > div { gap: 4px; }
.engine-proof > div > svg { display: none; }
.engine-proof code { font-size: 9px; }
.engine-original { padding: 12px; max-height: 42vh; }
}
@media (prefers-reduced-motion: reduce) { .engine-panel .spin { animation: none; } }
+123
View File
@@ -0,0 +1,123 @@
import { useEffect, useRef, useState } from 'react';
import { ArrowRight, Check, Download, Fingerprint, Link2, LoaderCircle, Play, RefreshCw, Square, Unplug } from 'lucide-react';
import { api, downloadEngineReport } from './api';
import { Modal } from './components';
import type { ArtifactPreview, EngineAvailability, EngineJob, Project, Session } from './types';
import './EnginePanel.css';
const active = ['queued', 'starting', 'initializing', 'checking', 'stopping'];
const states: Record<string, string> = { queued: '等待启动', starting: '原程序启动中', initializing: '正在连接', checking: '正在核验',
stopping: '正在停止', completed: '连接通过', failed: '连接未通过', cancelled: '已停止', unknown: '结果待核对' };
const date = (value: string) => new Date(value).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
type Preview = { job: EngineJob; page: ArtifactPreview };
export function EnginePanel({ project, session, busy, onSession, onError }: {
project: Project; session: Session; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void;
}) {
const [root, setRoot] = useState(''), [installation, setInstallation] = useState<EngineAvailability | null>(null);
const [checking, setChecking] = useState(false), [pending, setPending] = useState(false);
const [retry, setRetry] = useState<EngineJob | null>(null), [preview, setPreview] = useState<Preview | null>(null);
const [viewBusy, setViewBusy] = useState(false), [notice, setNotice] = useState('');
const mounted = useRef(true), detection = useRef(0), scope = useRef(0), viewRequest = useRef(0);
const taskId = session.execution?.task?.id ?? null;
const jobs = (session.execution?.engineJobs ?? []).slice().reverse();
const running = jobs.some(job => active.includes(job.status)), disabled = busy || running || pending;
useEffect(() => { mounted.current = true; return () => { mounted.current = false; detection.current++; scope.current++; viewRequest.current++; }; }, []);
useEffect(() => { scope.current++; viewRequest.current++; setPreview(null); setRetry(null); setViewBusy(false); setPending(false); setNotice(''); }, [taskId]);
useEffect(() => { void detect(); }, []);
async function detect(candidate = root) {
const current = ++detection.current; setChecking(true); setNotice('');
try {
const value = await api<EngineAvailability>('/engines/deepseek/availability' + (candidate.trim() ? '?root=' + encodeURIComponent(candidate.trim()) : ''));
if (mounted.current && current === detection.current) { setInstallation(value); if (!candidate.trim() && value.root) setRoot(value.root); }
} catch (error) { if (mounted.current && current === detection.current) onError(error); }
finally { if (mounted.current && current === detection.current) setChecking(false); }
}
function editRoot(value: string) { detection.current++; setRoot(value); setInstallation(null); setChecking(false); setNotice('目录已改变,请先检测这个安装。'); }
async function start(previous?: EngineJob) {
const current = scope.current; setPending(true); setNotice('');
try {
const value = await api<{ job: EngineJob; session: Session }>('/sessions/' + session.id + '/engines/jobs', {
root: previous?.installation.root ?? installation?.root ?? root.trim(),
...(previous ? { retry: true } : { identitySha256: installation?.identitySha256 }),
});
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 + '/engines/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 openRecord(job: EngineJob, offset = 0) {
const current = ++viewRequest.current, currentScope = scope.current; setViewBusy(true);
try {
const page = await api<ArtifactPreview>('/sessions/' + session.id + '/engines/jobs/' + job.id + '/report?offset=' + offset + '&limit=4000');
if (mounted.current && currentScope === scope.current && current === viewRequest.current) setPreview({ job, 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: EngineJob) {
const current = scope.current;
try { await downloadEngineReport(session.id, job.id); }
catch (error) { if (mounted.current && current === scope.current) onError(error); }
}
return <div className="engine-panel">
<header className="engine-heading"><div><span className="engine-eyebrow">{project.name} · 当前任务</span><h3>连接本地代理引擎</h3>
<p>核对本机的 DeepSeek Harness,并将实际检查记录保存到这个任务。</p></div>
<span className={'engine-install-state ' + (installation?.status === 'available' ? 'found' : '')} aria-live="polite">
{checking ? '正在检测安装' : installation?.status === 'available' ? '已找到 ' + installation.version : '等待检测'}</span></header>
<div className="engine-layout"><section className="engine-connection">
<form onSubmit={event => { event.preventDefault(); void detect(); }}>
<h4><Link2 size={16} />DeepSeek Harness</h4>
<label className="form-field">本地安装目录<input aria-label="DeepSeek安装目录" value={root} onChange={event => editRoot(event.target.value)}
placeholder="D:\Ai-project\DeepSeek-Harness-Desktop\deepseek-harness" disabled={disabled} /></label>
<button type="submit" className="button secondary" disabled={checking || disabled}><RefreshCw size={14} className={checking ? 'spin' : ''} />检测安装</button>
{installation && <p className={'engine-detection-note ' + installation.status} role="status">{installation.message}</p>}
{notice && <p className="engine-detection-note" role="status">{notice}</p>}
{installation?.status === 'available' && <dl className="engine-install-details"><dt>发行版本</dt><dd>{installation.version}</dd><dt>连接范围</dt><dd>启动、协议、会话目录与停止</dd>
<dt>运行环境</dt><dd>Node.js {installation.node?.version}</dd></dl>}
<button type="button" className="button primary engine-start" onClick={() => void start()} disabled={disabled || checking || installation?.status !== 'available'}>
{pending ? <LoaderCircle size={14} className="spin" /> : <Play size={14} />}核验连接</button>
</form>
<div className="engine-scope"><h4>当前可用能力</h4><p><Check size={14} />原程序连接与独立进程停止</p><p><Check size={14} />同任务保存原记录与来源</p>
<div className="engine-scope-next"><span>工程执行接入中</span><p>本次检查不发送模型任务。完成连接核验后,继续接入工程工具与交付流程。</p></div>
<details><summary>连接与执行范围</summary><p>每次检查启动一个独立进程。停止只作用于这个检查;SDK 会话目录、协议版本与完整错误保存在原记录。当前版本没有开放外部引擎修改工程。</p></details></div>
</section><section className="engine-results"><div className="engine-results-heading"><h4>本任务连接记录 <span>{jobs.length}</span></h4>
{running && <button type="button" className="button secondary" onClick={() => void stop()} disabled={pending}><Square size={13} />停止检查</button>}</div>
{!jobs.length && <div className="engine-empty"><Unplug size={25} /><strong>先验证这个安装能否连接</strong><p>检查完成后,可以查看实际启动、协议返回和进程结束记录;检查不会调用已配置的模型。</p></div>}
{jobs.map(job => { const verified = job.status === 'completed' && job.verification?.verified === true;
return <article key={job.id} data-engine-job={job.id} className={'engine-job ' + (verified ? 'verified' : '')}>
<div className="engine-job-heading"><div><strong>DeepSeek Harness {job.installation.version}</strong><small>{date(job.startedAt)}</small></div>
<span className={'engine-job-state ' + job.status}>{active.includes(job.status) && <LoaderCircle size={12} className="spin" />}{states[job.status] ?? job.status}</span></div>
<p className="engine-job-summary">{job.summary}</p>
<div className="engine-proof" aria-label="引擎实际检查依据">
<div className={job.installation.identitySha256 ? 'observed' : ''}><Fingerprint size={15} /><span>安装身份<code>{job.installation.identitySha256?.slice(0, 12) ?? '等待核对'}</code></span></div>
<ArrowRight size={12} /><div className={job.readiness ? 'observed' : ''}><span>启动完成<code>{job.readiness ? 'PID ' + job.readiness.pid : '尚无信号'}</code></span></div>
<ArrowRight size={12} /><div className={job.serverInfo ? 'observed' : ''}><span>协议返回<code>{job.serverInfo?.version ?? '尚无返回'}</code></span></div>
<ArrowRight size={12} /><div className={job.reportSummary?.rootExited ? 'observed' : ''}><span>进程结束<code>{job.reportSummary?.rootExited ? '已核对' : job.finishedAt ? '待核对' : '检查中'}</code></span></div>
</div>
<div className="engine-job-actions"><button className="button secondary" onClick={() => void openRecord(job)} disabled={!job.reportArtifactId || viewBusy}><Fingerprint size={13} />查看原记录</button>
<button className="text-button" onClick={() => void download(job)} disabled={!job.reportArtifactId}><Download size={13} />下载完整记录</button>
{!active.includes(job.status) && <button className="text-button" onClick={() => setRetry(job)} disabled={disabled}><RefreshCw size={13} />重新核验</button>}</div>
<details className="engine-origin"><summary>任务与安装来源</summary><dl><dt>项目</dt><dd>{project.name}</dd><dt>Task</dt><dd>{job.taskId}</dd><dt>Run</dt><dd>{job.runId}</dd>
<dt>SDK 会话</dt><dd>{job.sdkSessionId}</dd><dt>安装目录</dt><dd>{job.installation.root}</dd><dt>安装 SHA256</dt><dd>{job.installation.identitySha256}</dd>
<dt>原记录 SHA256</dt><dd>{job.reportSha256 ?? '尚未封存'}</dd><dt>模型请求</dt><dd>{job.reportSummary?.modelRequests ?? '尚未核对'}</dd></dl></details>
</article>;
})}
</section></div>
{retry && <Modal title="重新核验引擎连接" description="启动一个新的独立检查;原检查记录继续保留。" onClose={() => setRetry(null)}>
<p className="engine-retry-note">{retry.installation.root}</p><p>将重新核对当前安装、启动完成、SDK 返回和进程关闭。本次不会发送模型任务。</p>
<div className="modal-actions"><button className="button secondary" onClick={() => setRetry(null)}>返回记录</button><button className="button primary" disabled={disabled} onClick={() => void start(retry)}><RefreshCw size={14} />开始新的核验</button></div></Modal>}
{preview && <Modal title="引擎原检查记录" description="核对封存的安装、任务身份和原记录 SHA256 后读取。" wide onClose={() => { viewRequest.current++; setPreview(null); setViewBusy(false); }}>
<div className="engine-record-meta"><span>原记录 SHA256</span><code>{preview.page.sha256}</code></div>
<pre className="engine-original" aria-label="引擎原记录内容">{preview.page.content}</pre>
<div className="engine-page-controls"><span>{preview.page.offset.toLocaleString()}–{(preview.page.offset + preview.page.content.length).toLocaleString()} / {preview.page.totalCharacters.toLocaleString()} 字符</span>
<button className="button secondary" onClick={() => void openRecord(preview.job, 0)} disabled={viewBusy || preview.page.offset === 0}>回到首页</button>
<button className="button secondary" onClick={() => void openRecord(preview.job, preview.page.offset + preview.page.content.length)} disabled={viewBusy || !preview.page.truncated}><ArrowRight size={13} />下一页</button></div>
<div className="modal-actions"><button className="button secondary" onClick={() => void download(preview.job)}><Download size={14} />下载完整记录</button></div>
</Modal>}
</div>;
}
+6
View File
@@ -34,3 +34,9 @@ export function downloadBlob(blob: Blob, name: string) {
const link = document.createElement('a'); link.href = url; link.download = name; link.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
export async function downloadEngineReport(sessionId: string, jobId: string) {
const response = await fetch('/api/sessions/' + sessionId + '/engines/jobs/' + jobId + '/download', { 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-engine-' + jobId + '.json');
}
+16 -1
View File
@@ -130,7 +130,22 @@ 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[]; researchTargets?: ResearchTarget[]; researchJobs?: ResearchJob[]; 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[]; engineJobs?: EngineJob[]; workspaceIdentity?: WorkspaceIdentity; accountedTaskTokens: number }
export interface EngineAvailability {
engineId: string; name: string; status: string; root: string | null; profile: string; expectedVersion: string; version?: string; message: string;
identitySha256?: string; node?: { path: string; version: string; sha256: string };
serverInfo?: { name: string; version: string }; limitations: string[];
capabilities: { connectionProbe: boolean; projectExecution: boolean; prompt: boolean; singleSessionCancel: boolean; cancellationUnit: string; tokenStreaming: boolean };
}
export interface EngineJob {
id: string; sessionId: string; projectId: string; taskId: string; runId: string; engineId: string; scope: string;
installation: EngineAvailability; sdkSessionId: string; status: string; summary: string; requiresVerification: boolean;
startedAt: string; finishedAt: string | null; pid?: number; connectionId?: string;
readiness?: { pid: number; signal: string; readyAt: string }; serverInfo?: { name: string; version: string };
verification?: { verified: boolean; rootExited: boolean; modelRequests: number } | null;
reportArtifactId?: string; reportSha256?: string; contractSha256: string;
reportSummary?: { status: string; modelRequests: number | null; observedResponses: number; rootExited: boolean | null } | null;
}
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 {
+148
View File
@@ -0,0 +1,148 @@
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { randomUUID } from 'node:crypto';
import { DeepSeekAdapter } from './engines/deepseek-adapter.mjs';
import { resolveDeepSeekInstallation } from './engines/deepseek-installation.mjs';
import { ENGINE_ACTIVE, ENGINE_SCOPE, ENGINE_LIMITS, engineInput, engineReportContract, engineError } from '../shared/contracts/engines.mjs';
const at = () => new Date().toISOString();
export class EngineManager {
constructor(store, { appDirectory = process.cwd(), adapterFactory = installation => new DeepSeekAdapter(installation),
projectBusy = () => false, redact = value => String(value), directoryRoot = null } = {}) {
this.store = store; this.appDirectory = appDirectory; this.adapterFactory = adapterFactory;
this.projectBusy = projectBusy; this.redact = redact; this.directoryRoot = directoryRoot;
this.active = new Map(); this.projects = new Map();
}
availability(root) { return resolveDeepSeekInstallation(this.appDirectory, root); }
isActive(sessionId) { return [...this.active.values()].some(value => value.sessionId === sessionId); }
projectActive(projectId) { return this.projects.has(projectId); }
jobs(session) { return [...this.store.core.engine_job.values()].filter(value => value.sessionId === session.id).slice(-20); }
inputFor(session, job) {
this.store.owned('engine_job', job.id, session.id);
const input = this.store.owned('artifact', job.contractArtifactId, session.id);
if (input.kind !== 'engine-input' || input.taskId !== job.taskId || input.runId !== job.runId || input.sha256 !== job.contractSha256
|| this.store.artifactStore.read(input) !== JSON.stringify(engineInput(job))) throw engineError('引擎检查与封存的任务、安装或会话身份不一致。');
return input;
}
originalReport(session, job) {
this.inputFor(session, job);
const artifact = this.store.owned('artifact', job.reportArtifactId, session.id);
if (artifact.kind !== 'engine-report' || artifact.sha256 !== job.reportSha256 || artifact.taskId !== job.taskId || artifact.runId !== job.runId) throw engineError('引擎原记录不属于这次检查。');
const text = this.store.artifactStore.read(artifact);
if (text !== JSON.stringify(engineReportContract(job))) throw engineError('引擎原记录与当前封存状态不一致。');
return text;
}
summary(session, job) {
let verified = false, message = job.summary;
try {
if (job.reportArtifactId) { this.originalReport(session, job); verified = job.status === 'completed' && job.report?.status === 'verified' && job.verification?.verified === true; }
else this.inputFor(session, job);
} catch (error) { message = this.redact(error.message); }
return { engine_job_id: job.id, engine_id: job.engineId, task_id: job.taskId, run_id: job.runId,
engine_status: job.status === 'completed' && !verified ? 'unknown' : job.status, evidence_verified: verified,
installation_sha256: job.installation.identitySha256, package_version: job.installation.version, profile: job.installation.profile,
sdk_session_id: job.sdkSessionId, pid: job.pid ?? null, connection_id: job.connectionId ?? null,
report_artifact_id: job.reportArtifactId ?? null, report_sha256: job.reportSha256 ?? null,
model_requests: job.report?.modelRequests ?? null, provider_requests: 0,
requires_verification: job.requiresVerification || job.status === 'completed' && !verified,
message, scope: job.scope, limitations: ENGINE_LIMITS };
}
start(session, input = {}) {
if (!input || typeof input !== 'object' || Array.isArray(input) || Object.keys(input).some(key => !['root', 'retry', 'identitySha256'].includes(key))
|| input.retry !== undefined && typeof input.retry !== 'boolean'
|| input.identitySha256 !== undefined && (typeof input.identitySha256 !== 'string' || !/^[a-f0-9]{64}$/.test(input.identitySha256))) throw engineError('连接核验只接受本地安装目录、检测身份和明确的重新验证选项。', 400);
if (session.archived || this.projectActive(session.projectId) || this.projectBusy(session.projectId)) throw engineError('当前项目有任务、审批或检查在执行,请等待结束。');
const installation = this.availability(input.root);
if (installation.status !== 'available') throw engineError(installation.message, 409, 'ENGINE_UNAVAILABLE');
if (input.identitySha256 !== undefined && input.identitySha256 !== installation.identitySha256) throw engineError('引擎安装与刚才的检测结果不一致,请重新检测后再核验连接。', 409, 'ENGINE_INPUT_CHANGED');
const previous = this.jobs(session).filter(job => job.taskId === session.taskId && job.installation.root === installation.root).at(-1);
if (previous && previous.status !== 'completed' && !input.retry) throw engineError('此前连接检查没有完成,请查看原记录后明确选择重新验证。');
const id = randomUUID(), controller = new AbortController(), active = { sessionId: session.id, projectId: session.projectId, controller };
this.active.set(id, active); this.projects.set(session.projectId, id);
try {
if (!this.store.core.task.get(session.taskId)) {
const goal = '核对本地DeepSeek Harness的启动、SDK连接、会话目录与进程结束,保存原检查记录。';
const run = this.store.beginRun(session, goal, false, this.store.config);
run.engine = 'deepseek-sdk-probe'; run.origin = 'user-engine-check';
this.store.message(session, 'user', goal); session.providerMessages.push({ role: 'user', content: goal });
session.status = 'paused'; this.store.finishRun(session, run, 'engine_probe_ready');
if (session.title === '新任务') session.title = '外部引擎连接';
}
const run = this.store.owned('run', session.runId, session.id);
const base = path.resolve(this.directoryRoot ?? path.join(os.tmpdir(), 'AgentWorkbench-Engines'));
fs.mkdirSync(base, { recursive: true });
if (fs.lstatSync(base).isSymbolicLink()) throw engineError('所属引擎探针目录不能是链接。');
const directory = path.join(base, id);
if (fs.existsSync(directory)) throw engineError('引擎探针目录已存在,不能复用或覆盖。');
const job = { schemaVersion: 1, id, sessionId: session.id, projectId: session.projectId, taskId: run.taskId, runId: run.id,
engineId: 'deepseek-harness', scope: ENGINE_SCOPE, source: 'user', installation, sdkSessionId: randomUUID(), directory,
status: 'queued', startedAt: at(), finishedAt: null, requiresVerification: false, verification: null,
summary: '已登记本地安装和检查范围,尚未启动原程序。', report: null };
active.job = job;
const artifact = this.store.artifactStore.write(session, run, engineInput(job), { kind: 'engine-input' });
this.store.core.artifact.set(artifact.id, artifact); job.contractArtifactId = artifact.id; job.contractSha256 = artifact.sha256;
const event = this.store.event(session, { kind: 'engine', tool: 'deepseek-sdk-probe', label: '核验外部引擎连接', phase: 'queued',
input: { engineId: job.engineId, root: installation.root, version: installation.version, profile: installation.profile, modelRequestsAllowed: 0 } });
job.eventId = event.id; this.store.putRecord('engine_job', session, job, 'engine.queued');
active.promise = this.execute(session, run, job, active).finally(() => {
this.active.delete(id); if (this.projects.get(session.projectId) === id) this.projects.delete(session.projectId);
});
active.promise.catch(() => {}); return { job, promise: active.promise };
} catch (error) { this.active.delete(id); this.projects.delete(session.projectId); throw error; }
}
async execute(session, run, job, active) {
let report;
try {
this.inputFor(session, job);
active.adapter = this.adapterFactory(job.installation);
report = await active.adapter.probe({ directory: job.directory, sdkSessionId: job.sdkSessionId, signal: active.controller.signal,
onState: (status, detail) => {
if (active.controller.signal.aborted) return;
if (!['starting', 'initializing', 'checking'].includes(status)) throw engineError('引擎状态不符合检查契约。');
this.inputFor(session, job); job.status = status;
for (const field of ['pid', 'connectionId', 'readiness', 'serverInfo']) if (detail?.[field] !== undefined) job[field] = detail[field];
job.summary = status === 'starting' ? '原程序已启动,正在等待所属启动完成信号。' : status === 'initializing' ? '启动已完成,正在核对一次SDK初始化。' : 'SDK身份已返回,正在核对会话目录、错误与关闭。';
this.store.putRecord('engine_job', session, job, 'engine.' + status);
} });
this.inputFor(session, job);
if (report.status !== 'verified' || report.scope !== job.scope || report.sdkSessionId !== job.sdkSessionId
|| report.before?.identitySha256 !== job.installation.identitySha256 || report.after?.identitySha256 !== job.installation.identitySha256
|| report.process?.pid !== report.readiness?.pid || !report.cleanup?.rootExited || report.cleanup.exit?.code !== 0
|| report.modelRequests !== 0 || report.providerRequests !== 0 || report.responses?.length !== 6 || !report.workspace?.unchanged) throw engineError('引擎返回缺少完整的身份、原协议或关闭依据。');
job.status = 'completed'; job.summary = '连接通过,启动、协议返回、会话目录与进程结束均已核对。';
job.verification = { verified: true, installationSha256: job.installation.identitySha256, readySignal: 'appReady',
sdkSessionId: job.sdkSessionId, connectionId: report.process.connectionId, rootExited: true, modelRequests: 0 };
} catch (error) {
report = error.report ?? report ?? { schemaVersion: 1, scope: job.scope, sdkSessionId: job.sdkSessionId,
status: active.controller.signal.aborted ? 'cancelled' : 'failed', error: { code: error.code ?? 'ENGINE_CHECK_FAILED', message: this.redact(error.message) },
modelRequests: null, providerRequests: 0, responses: [], cleanup: null };
job.status = report.status === 'unknown' ? 'unknown' : active.controller.signal.aborted ? 'cancelled' : 'failed';
job.requiresVerification = job.status === 'unknown'; job.verification = null;
job.summary = this.redact(report.error?.message ?? error.message); job.error = { code: report.error?.code ?? error.code ?? 'ENGINE_CHECK_FAILED', message: job.summary };
}
job.report = report; job.finishedAt = at();
try {
const artifact = this.store.artifactStore.write(session, run, engineReportContract(job), { kind: 'engine-report' });
this.store.core.artifact.set(artifact.id, artifact); job.reportArtifactId = artifact.id; job.reportSha256 = artifact.sha256;
const event = session.events.find(value => value.id === job.eventId);
if (event) { event.phase = job.status; event.finishedAt = job.finishedAt; event.output = job.summary; }
this.store.putRecord('engine_job', session, job, 'engine.finished');
} catch (error) {
job.status = 'unknown'; job.verification = null; job.requiresVerification = true; job.summary = '引擎原结果没有完成封存,请核对所属原记录:' + this.redact(error.message);
this.store.putRecord('engine_job', session, job, 'engine.seal_failed');
}
return job;
}
async stop(sessionId) {
const active = [...this.active.values()].filter(value => value.sessionId === sessionId);
for (const value of active) {
if (ENGINE_ACTIVE.has(value.job.status)) value.job.status = 'stopping';
value.controller.abort(new Error('用户停止了所属外部引擎连接检查。'));
this.store.putRecord('engine_job', this.store.session(sessionId), value.job, 'engine.stopping');
}
await Promise.allSettled(active.map(value => value.promise));
}
async stopAll() { await Promise.all([...new Set([...this.active.values()].map(value => value.sessionId))].map(sessionId => this.stop(sessionId))); }
}
+146
View File
@@ -0,0 +1,146 @@
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import { randomUUID } from 'node:crypto';
import { McpStdio } from '../tools/mcp-stdio.mjs';
import { engineDigest, engineError, ENGINE_SCOPE } from '../../shared/contracts/engines.mjs';
import { assertDeepSeekInstallation, engineFileIdentity } from './deepseek-installation.mjs';
export const DEEPSEEK_READY_PLUGIN = `import fs from 'node:fs';
export const name = 'agent-workbench-sdk-ready';
export const inject = ['appReady'];
export function apply(ctx, config) {
const ready = ctx.get('appReady');
if (!ready || typeof ready.onReady !== 'function') throw new Error('The fixed SDK launcher has no appReady service.');
const stop = ready.onReady(() => {
const value = { schemaVersion: 1, nonce: config.nonce, pid: process.pid, signal: 'appReady', readyAt: new Date().toISOString() };
const temporary = config.marker + '.writing';
fs.writeFileSync(temporary, JSON.stringify(value), { flag: 'wx' });
fs.renameSync(temporary, config.marker);
});
ctx.effect(() => stop, 'workbench.sdk-ready');
}
`;
const allowedEnvironment = /^(path|pathext|systemroot|systemdrive|windir|comspec|temp|tmp|userprofile|appdata|localappdata|programfiles(?:\(x86\))?|homedrive|homepath)$/i;
const at = () => new Date().toISOString();
const fail = (message, code = 'ENGINE_PROTOCOL') => engineError(message, 409, code);
export class DeepSeekAdapter {
constructor(installation, { timeoutMs = 15000, clientFactory = (launch, options) => new McpStdio(launch, options) } = {}) {
this.installation = installation; this.timeoutMs = timeoutMs; this.clientFactory = clientFactory;
}
async waitReady(marker, nonce, signal) {
const deadline = Date.now() + this.timeoutMs;
while (true) {
signal?.throwIfAborted();
if (fs.existsSync(marker)) {
const readiness = JSON.parse(fs.readFileSync(marker, 'utf8'));
if (readiness.schemaVersion !== 1 || readiness.nonce !== nonce || readiness.pid !== this.client.pid
|| readiness.signal !== 'appReady' || !Number.isFinite(Date.parse(readiness.readyAt))) throw fail('启动完成信号与所属进程不一致。');
return { ...readiness, artifact: engineFileIdentity(marker) };
}
if (this.client.exited || this.client.protocolError) throw fail('原程序在启动完成前关闭或返回无效协议。');
if (Date.now() >= deadline) throw fail('原程序未在等待范围内报告启动完成,尚未发送initialize。', 'ENGINE_START_TIMEOUT');
await new Promise(resolve => setTimeout(resolve, 15));
}
}
async probe({ directory, sdkSessionId, signal, onState = () => {} }) {
const report = { schemaVersion: 1, scope: ENGINE_SCOPE, sdkSessionId, startedAt: at(), finishedAt: null,
responses: [], notifications: [], unownedNotifications: [], rejectedServerRequests: [], networkRequests: [], networkRequestCount: 0,
modelRequests: 0, providerRequests: 0, process: null, cleanup: null, readiness: null };
let guard, problem = null;
const cwd = path.join(directory, 'project'), home = path.join(directory, 'home'), agents = path.join(directory, 'agents');
try {
signal?.throwIfAborted(); report.before = assertDeepSeekInstallation(this.installation);
fs.mkdirSync(directory, { recursive: false });
for (const folder of [cwd, home, agents]) fs.mkdirSync(folder);
const readme = path.join(cwd, 'README.md'), bytes = Buffer.from('# Agent Workbench owned engine connection probe\n');
fs.writeFileSync(readme, bytes, { flag: 'wx' });
report.workspace = { root: cwd, before: engineFileIdentity(readme) };
const nonce = randomUUID(), marker = path.join(directory, 'ready.json'), plugin = path.join(directory, 'ready.mjs'), patch = path.join(directory, 'ready.patch.json');
fs.writeFileSync(plugin, DEEPSEEK_READY_PLUGIN, { flag: 'wx' });
fs.writeFileSync(patch, JSON.stringify([{ insert: [{ id: 'agent-workbench-sdk-ready', name: plugin, config: { marker, nonce } }] }]), { flag: 'wx' });
report.launchInputs = { plugin: engineFileIdentity(plugin), patch: engineFileIdentity(patch), profile: this.installation.profile };
guard = http.createServer((request, response) => {
report.networkRequestCount++;
if (report.networkRequests.length < 128) report.networkRequests.push({ method: request.method, path: request.url.slice(0, 2000), receivedAt: at() });
response.writeHead(409, { Connection: 'close' }); response.end('This owned connection probe accepts no model requests.');
});
await new Promise((resolve, reject) => { guard.once('error', reject); guard.listen(0, '127.0.0.1', resolve); });
const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => allowedEnvironment.test(name)));
Object.assign(env, { DSH_HOME: home, DSH_AGENTS_HOME: agents, DSH_TELEMETRY_DISABLED: 'true',
DEEPSEEK_API_KEY: 'agent-workbench-owned-protocol-fixture', DEEPSEEK_BASE_URL: 'http://127.0.0.1:' + guard.address().port });
signal?.throwIfAborted(); assertDeepSeekInstallation(this.installation);
this.client = this.clientFactory({ executable: this.installation.node.path,
args: [this.installation.entry, '--profile', this.installation.profile, '--patch', patch], cwd, env },
{ timeoutMs: this.timeoutMs, maximumFrameBytes: 4 * 1024 * 1024, cancellationMethod: null });
report.process = { pid: this.client.pid, connectionId: this.client.id, startedAt: this.client.startedAt, ownership: 'one-process-per-engine-check' };
onState('starting', { pid: this.client.pid, connectionId: this.client.id });
let notificationBytes = 0;
this.client.on('server-request', value => {
if (report.rejectedServerRequests.length >= 32) { this.client.fail(fail('引擎反向请求超过连接核验范围。')); return; }
report.rejectedServerRequests.push({ id: value.id, method: value.method, parametersSha256: engineDigest(value.params ?? {}) });
});
this.client.on('notification', value => {
notificationBytes += Buffer.byteLength(JSON.stringify(value), 'utf8');
if (notificationBytes > 1024 * 1024 || report.notifications.length + report.unownedNotifications.length >= 128) {
this.client.fail(fail('引擎事件超过连接核验的接收范围。')); return;
}
const owned = value.params?.sessionId === sdkSessionId;
(owned ? report.notifications : report.unownedNotifications).push(value);
});
report.readiness = await this.waitReady(marker, nonce, signal);
if (engineFileIdentity(plugin).sha256 !== report.launchInputs.plugin.sha256 || engineFileIdentity(patch).sha256 !== report.launchInputs.patch.sha256) throw fail('启动期间所属就绪插件或profile叠加输入发生变化。');
onState('initializing', { readiness: report.readiness });
const request = async (method, params = {}, expectError = false) => {
let result, error;
try { result = await this.client.request(method, params, { signal }); }
catch (failure) {
if (!expectError || failure.code !== 'MCP_REMOTE_ERROR') throw failure;
try { error = JSON.parse(failure.message); } catch { throw fail('原程序错误返回不是可核对的协议错误。'); }
}
const trace = this.client.trace.at(-1);
const observation = { method, id: trace.id, parameters: params, parametersSha256: trace.parametersSha256,
...(error ? { error } : { result }), startedAt: trace.startedAt, finishedAt: trace.finishedAt };
report.responses.push(observation);
if (expectError && (!error || typeof error.code !== 'number' || typeof error.message !== 'string')) throw fail('原程序没有按协议拒绝这个未存在的会话操作。');
return error ?? result;
};
const initialized = await request('initialize', { cwd, provider: 'deepseek-official', model: 'deepseek-flash', reasoningEffort: 'off', maxTokens: 256 });
if (initialized?.serverInfo?.name !== this.installation.serverInfo.name || initialized?.serverInfo?.version !== this.installation.serverInfo.version) throw fail('SDK返回身份不符合固定发行契约。');
onState('checking', { serverInfo: initialized.serverInfo });
const workingDirectory = await request('session/working-directory/get', { sessionId: sdkSessionId });
if (typeof workingDirectory?.cwd !== 'string' || fs.realpathSync.native(workingDirectory.cwd) !== fs.realpathSync.native(cwd)) throw fail('SDK会话目录与所属探针目录不一致。');
const missing = randomUUID();
for (const method of ['session/wait', 'session/resume', 'session/cancel']) {
const error = await request(method, { sessionId: missing }, true);
if (method === 'session/cancel' && !error.message.includes('unknown DeepSeek Harness SDK runtime method: session/cancel')) throw fail('SDK取消能力与已锁定协议不一致。');
if (method !== 'session/cancel' && !error.message.includes(missing)) throw fail('SDK错误没有保留所核对的会话身份。');
}
const shutdown = await request('shutdown');
if (!shutdown || typeof shutdown !== 'object' || Array.isArray(shutdown) || Object.keys(shutdown).length) throw fail('SDK关闭响应不符合固定契约。');
report.workspace.after = engineFileIdentity(readme);
report.workspace.unchanged = fs.readFileSync(readme).equals(bytes) && fs.readdirSync(cwd).length === 1;
if (!report.workspace.unchanged) throw fail('原程序修改了连接探针输入,不能记为核验通过。');
report.after = assertDeepSeekInstallation(this.installation);
} catch (error) { problem = error; }
finally {
if (this.client) {
try { report.cleanup = await this.client.close({ force: !!problem || signal?.aborted === true }); }
catch (error) { problem ??= error; }
report.trace = this.client.trace; report.stderr = this.client.stderr;
}
if (guard) { guard.closeAllConnections(); await new Promise(resolve => guard.close(resolve)); }
report.modelRequests = report.networkRequestCount; report.finishedAt = at();
}
if (!problem && (!report.cleanup?.rootExited || report.cleanup.exit?.code !== 0)) problem = fail('所属引擎进程没有可核对的正常关闭结果。');
if (!problem && report.modelRequests) problem = fail('原程序发起了核验范围之外的模型请求,连接检查失败。');
if (problem) {
report.status = report.process && !report.cleanup?.rootExited ? 'unknown' : signal?.aborted ? 'cancelled' : 'failed';
report.error = { code: problem.code ?? (signal?.aborted ? 'ENGINE_CANCELLED' : 'ENGINE_CHECK_FAILED'), message: problem.message };
throw Object.assign(problem, { report });
}
report.status = 'verified'; return report;
}
}
@@ -0,0 +1,81 @@
import fs from 'node:fs';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { createRequire } from 'node:module';
import { engineDigest, engineError, ENGINE_LIMITS } from '../../shared/contracts/engines.mjs';
export const DEEPSEEK_VERSION = '0.2.1-rc.2';
export const DEEPSEEK_PROFILE = 'sdk-minimal';
const criticalFiles = [
'apps/cli/package.json', 'apps/cli/lib/bin.js', 'packages/boot/cmdline/lib/index.js',
'packages/bundle/sdk-app/lib/index.js', 'packages/bundle/sdk-minimal/package.json',
'packages/bundle/sdk-minimal/cordis.patch.yml', 'packages/sdk/server/package.json',
'packages/sdk/server/lib/index.js', 'packages/sdk/protocol/package.json',
'packages/sdk/protocol/lib/index.js', 'packages/sdk/client/package.json', 'pnpm-lock.yaml',
];
export function engineFileIdentity(filename, maximumBytes = 32 * 1024 * 1024) {
const absolute = fs.realpathSync.native(filename), before = fs.statSync(absolute);
if (!before.isFile() || before.size > maximumBytes) throw engineError('引擎输入不是范围内的普通文件。');
const hash = createHash('sha256'), chunk = Buffer.allocUnsafe(128 * 1024), fd = fs.openSync(absolute, 'r');
try { let count; while ((count = fs.readSync(fd, chunk, 0, chunk.length, null)) > 0) hash.update(chunk.subarray(0, count)); }
finally { fs.closeSync(fd); }
const after = fs.statSync(absolute);
if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ino !== after.ino) throw engineError('读取期间引擎输入发生变化。');
return { path: absolute, bytes: after.size, sha256: hash.digest('hex') };
}
function candidates(appDirectory) {
const roots = [];
if (process.env.AGENT_WORKBENCH_DEEPSEEK_ROOT) roots.push(process.env.AGENT_WORKBENCH_DEEPSEEK_ROOT);
let parent = path.resolve(appDirectory);
for (let level = 0; level < 7; level++) {
roots.push(path.join(parent, 'DeepSeek-Harness-Desktop', 'deepseek-harness'));
const next = path.dirname(parent); if (next === parent) break; parent = next;
}
return [...new Set(roots)];
}
export function resolveDeepSeekInstallation(appDirectory = process.cwd(), requestedRoot = undefined) {
if (requestedRoot !== undefined && (typeof requestedRoot !== 'string' || !requestedRoot.trim() || !path.isAbsolute(requestedRoot))) {
throw engineError('请输入DeepSeek Harness安装的绝对目录。', 400);
}
const supplied = requestedRoot?.trim(), candidate = supplied ?? candidates(appDirectory).find(root => fs.existsSync(path.join(root, 'apps/cli/package.json')));
const base = { engineId: 'deepseek-harness', name: 'DeepSeek Harness', profile: DEEPSEEK_PROFILE,
expectedVersion: DEEPSEEK_VERSION, root: candidate ? path.resolve(candidate) : null,
capabilities: { connectionProbe: true, projectExecution: false, prompt: false, singleSessionCancel: false,
protocolVersionNegotiation: false, cancellationUnit: 'owned-process', tokenStreaming: false }, limitations: ENGINE_LIMITS };
if (!candidate) return { ...base, status: 'unavailable', message: '请填写已经安装的DeepSeek Harness源码目录,再检测本地引擎。' };
try {
const root = fs.realpathSync.native(candidate), cli = JSON.parse(fs.readFileSync(path.join(root, 'apps/cli/package.json'), 'utf8'));
if (cli.name !== '@deepseek-ai/dsh' || cli.version !== DEEPSEEK_VERSION) return { ...base, root, status: 'unsupported',
version: typeof cli.version === 'string' ? cli.version : null, message: '当前连接契约支持DeepSeek Harness ' + DEEPSEEK_VERSION + '。' };
for (const relative of ['packages/bundle/sdk-minimal/package.json', 'packages/sdk/server/package.json', 'packages/sdk/protocol/package.json', 'packages/sdk/client/package.json']) {
const metadata = JSON.parse(fs.readFileSync(path.join(root, relative), 'utf8'));
if (metadata.version !== cli.version) return { ...base, root, status: 'unsupported', version: cli.version, message: 'CLI、SDK与profile版本不一致,请核对本地安装。' };
}
const require = createRequire(path.join(root, 'apps/cli/package.json'));
const cordis = require.resolve('@deepseek-ai/cordis');
const filenames = [...criticalFiles.map(relative => path.join(root, relative)), cordis];
const inputs = filenames.map(filename => {
const file = engineFileIdentity(filename);
if (!file.path.startsWith(root + path.sep)) throw engineError('引擎关键输入不属于这个安装目录。');
return { ...file, relative: path.relative(root, file.path).replaceAll('\\', '/') };
});
const node = { ...engineFileIdentity(process.execPath, 256 * 1024 * 1024), version: process.versions.node };
if (!/^24\./.test(node.version)) return { ...base, root, status: 'unsupported', version: cli.version, message: '当前连接契约使用Node.js 24。' };
const identitySha256 = engineDigest({ root, version: cli.version, profile: DEEPSEEK_PROFILE, inputs, node });
return { ...base, root, status: 'available', version: cli.version, entry: path.join(root, 'apps/cli/lib/bin.js'), inputs, node,
identitySha256, serverInfo: { name: 'deepseek-harness-sdk-runtime', version: '0.0.1' },
message: '已找到匹配版本,可验证原程序的连接与停止。' };
} catch (error) {
return { ...base, status: 'unavailable', message: '本地引擎关键输入不完整或无法核对:' + error.message };
}
}
export function assertDeepSeekInstallation(installation) {
if (installation.status !== 'available' || !installation.identitySha256) throw engineError(installation.message || '本地引擎尚未就绪。');
const current = resolveDeepSeekInstallation(process.cwd(), installation.root);
if (current.status !== 'available' || current.identitySha256 !== installation.identitySha256) throw engineError('引擎入口、SDK、profile或运行器已变化,请重新检测并由用户发起新检查。', 409, 'ENGINE_INPUT_CHANGED');
return current;
}
+8 -6
View File
@@ -11,9 +11,9 @@ const failure = (code, message, dispatched = false) => Object.assign(new Error(m
// 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 } = {}) {
constructor(launch, { timeoutMs = 45000, maximumFrameBytes = 8 * 1024 * 1024, cancellationMethod = 'notifications/cancelled' } = {}) {
super(); this.id = randomUUID(); this.pending = new Map(); this.sequence = 0; this.trace = [];
this.timeoutMs = timeoutMs; this.maximumFrameBytes = maximumFrameBytes; this.stderr = ''; this.buffer = '';
this.timeoutMs = timeoutMs; this.maximumFrameBytes = maximumFrameBytes; this.cancellationMethod = cancellationMethod; 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;
@@ -47,8 +47,10 @@ export class McpStdio extends EventEmitter {
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.' } });
if (message.id !== undefined) {
this.emit('server-request', message);
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;
}
@@ -82,11 +84,11 @@ export class McpStdio extends EventEmitter {
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.' });
if (this.cancellationMethod) this.notify(this.cancellationMethod, { 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.' });
if (this.cancellationMethod) this.notify(this.cancellationMethod, { 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 });
+31
View File
@@ -6,6 +6,7 @@ import { inspectProject } from '../core/project-inspector.mjs';
import { assertProposalUnsealed } from '../shared/contracts/change-sets.mjs';
import { assertWorkspacesResolved } from '../shared/contracts/workspaces.mjs';
import { verifyWorkspaceProject } from '../core/workspaces/git-workspaces.mjs';
import { publicEngineJob } from '../shared/contracts/engines.mjs';
export function createSessionPublisher(clients) {
return session => {
@@ -87,6 +88,7 @@ return async (request, response) => {
});
}
if (method === 'GET' && route === '/api/research/availability') return json(response, runtime.researchManager().availability());
if (method === 'GET' && route === '/api/engines/deepseek/availability') return json(response, runtime.engineManager().availability(url.searchParams.has('root') ? url.searchParams.get('root') : undefined));
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 });
@@ -147,6 +149,35 @@ 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 === 'engines') {
const manager = runtime.engineManager();
return json(response, { availability: manager.availability(), jobs: manager.jobs(session).map(publicEngineJob) });
}
if (method === 'POST' && action === 'engines/jobs') {
const started = runtime.engineManager().start(session, await body(request));
return json(response, { job: publicEngineJob(started.job), session: store.publicSession(session) }, 202);
}
if (method === 'POST' && action === 'engines/stop') { await runtime.engineManager().stop(id); return json(response, store.publicSession(session)); }
const engineJob = action.match(/^engines\/jobs\/([a-f0-9-]+)(?:\/(report|download))?$/);
if (method === 'GET' && engineJob) {
const manager = runtime.engineManager(), job = store.owned('engine_job', engineJob[1], id);
if (engineJob[2]) {
if (!job.reportArtifactId) throw Object.assign(new Error('这次引擎检查尚未封存原记录,请等待检查结束。'), { status: 409 });
const text = manager.originalReport(session, job), artifact = store.owned('artifact', job.reportArtifactId, id);
if (engineJob[2] === 'download') {
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-engine-' + job.id + '.json"' });
response.end(text); return;
}
const offset = cursorNumber(url.searchParams.get('offset'));
const limit = Math.min(16000, url.searchParams.has('limit') ? cursorNumber(url.searchParams.get('limit')) : 4000);
if (!limit || offset > text.length) throw Object.assign(new Error('原记录的读取位置或页长超出范围。'), { status: 400 });
return json(response, { ...artifact, content: text.slice(offset, offset + limit), offset,
totalCharacters: text.length, truncated: offset + limit < text.length });
}
if (job.reportArtifactId) manager.originalReport(session, job); else manager.inputFor(session, job);
return json(response, publicEngineJob(job));
}
if (method === 'GET' && action === 'research') {
const manager = runtime.researchManager(); return json(response, { availability: manager.availability(), targets: manager.targets(session), jobs: manager.jobs(session) });
}
+1 -1
View File
@@ -1,6 +1,6 @@
import { randomUUID, createHash } from 'node:crypto';
export const APP_VERSION = '1.8.0';
export const APP_VERSION = '1.9.0';
export function executionEnvironment() {
const windows = process.platform === 'win32';
+3 -3
View File
@@ -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 || runtime.research?.active.size) throw new Error('Wait for active tasks, checks, Git deliveries, file batches, workspaces, research 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 || runtime.engines?.active.size) throw new Error('Wait for active tasks, checks, Git deliveries, file batches, workspaces, research, engines 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, research: runtime.research };
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, engines: runtime.engines };
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.research = 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; runtime.engines = null;
store.ensureStorage(); store.claimRuntime();
store.removeAllListeners('update'); store.on('update', createSessionPublisher(clients));
server.removeAllListeners('request'); server.on('request', handler);
+4
View File
@@ -4,6 +4,10 @@ import { setTimeout as delay } from 'node:timers/promises';
import { executionEnvironment, ModelRequestError, connectionFailure, httpFailure } from './diagnostics.mjs';
import { completionBody, assertPlannedRequest } from '../shared/contracts/model-request.mjs';
export const engineToolDefinitions = [
{ type: 'function', function: { name: 'inspect_engine_checks', description: '读取当前Task已经保存的外部引擎连接核验:真实安装版本、启动完成信号、SDK会话、进程关闭、原报告工件和能力限制。不会启动引擎或发送prompt;完整原记录通过已有read_artifact读取。', parameters: { type: 'object', properties: {}, additionalProperties: false } } },
];
export const toolDefinitions = [
{ type: 'function', function: { name: 'prepare_change_set', description: '把当前Task的1到32份待审查文件提案按change_ids封存为统一审查批次。原/新字节快照和Git基线持久保存;不写盘。用户在改动面板确认后才应用;不能自动应用或重放未知批次。', parameters: { type: 'object', properties: { change_ids: { type: 'array', minItems: 1, maxItems: 32, uniqueItems: true, items: { type: 'string' } } }, required: ['change_ids'] } } },
{ type: 'function', function: { name: 'index_project', description: '为当前项目建立有文件SHA256的增量符号/导入索引。JS/TS/React来自静态AST,Python是声明候选;返回范围、摘要和完整工件,不执行项目代码。动态绑定和路径别名未核对。', parameters: { type: 'object', properties: {} } } },
+30 -12
View File
@@ -2,8 +2,9 @@ import { spawn, execFile } from 'node:child_process';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { StringDecoder } from 'node:string_decoder';
import { setImmediate as yieldExecution } from 'node:timers/promises';
import { safePath, listFiles, readLines, searchFiles, proposeFile, proposePatch } from './files.mjs';
import { projectContext, toolDefinitions, researchToolDefinitions } from './provider.mjs';
import { projectContext, toolDefinitions, researchToolDefinitions, engineToolDefinitions } from './provider.mjs';
import { now, repairToolPairs } from './store.mjs';
import { executionEnvironment, sessionContext, sessionSnapshot } from './diagnostics.mjs';
import { BudgetExceeded, checkBudget } from '../shared/contracts/execution.mjs';
@@ -19,6 +20,7 @@ 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';
import { EngineManager } from '../core/engine-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: '运行终端命令' };
@@ -26,10 +28,15 @@ labels.prepare_change_set = '准备多文件变更集';
labels.list_research_targets = '查看本任务登记工件';
labels.analyze_research_target = 'REA静态分析登记工件';
labels.read_research_evidence = '读取原REA Evidence字段';
labels.inspect_engine_checks = '查看本任务外部引擎核验';
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 (tool === 'inspect_engine_checks') {
if (Object.keys(args).length) throw new Error('引擎核验查询只读取当前任务的已保存结果。');
return;
}
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及有效字段。');
@@ -62,36 +69,40 @@ 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) || !!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; }
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) || !!this.engines?.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 || (this.engines?.active.size ?? 0) > 0; }
projectIndexer() { return this.codeIndex ??= new ProjectIndex(); }
engineManager() {
return this.engines ??= new EngineManager(this.store, { appDirectory: this.appDirectory,
redact: value => this.provider.redact(value), projectBusy: projectId => this.projectHasActivity(projectId) });
}
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) || !!this.research?.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) || !!this.engines?.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.research?.projectActive(projectId) });
|| !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.research?.projectActive(projectId) || !!this.engines?.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.research?.projectActive(projectId) });
|| !!this.checks?.projectActive(projectId) || !!this.deliveries?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) || !!this.research?.projectActive(projectId) || !!this.engines?.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) || !!this.research?.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) || !!this.engines?.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) || !!this.research?.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) || !!this.engines?.projectActive(projectId) });
}
start(id, content, resume = false, { instructionSource = null } = {}) {
const session = this.store.session(id);
@@ -148,6 +159,9 @@ export class Runtime {
const signal = run.controller.signal;
let projectionLogged = false;
try {
// Immediate providers and local tools still need to deliver UI events and
// process stop/deadline input between completed, persisted operations.
await yieldExecution(undefined, { signal });
await verifyWorkspaceProject(this.store, run.project);
for (let step = 0; step < config.maxSteps; step++) {
signal.throwIfAborted();
@@ -165,8 +179,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 tools = [...this.store.core.research_target.values()].some(target => target.sessionId === session.id && target.taskId === run.taskId)
? [...toolDefinitions, ...researchToolDefinitions] : toolDefinitions;
const tools = [...toolDefinitions,
...([...this.store.core.research_target.values()].some(target => target.sessionId === session.id && target.taskId === run.taskId) ? researchToolDefinitions : []),
...([...this.store.core.engine_job.values()].some(job => job.sessionId === session.id && job.taskId === run.taskId) ? engineToolDefinitions : [])];
const planned = this.requestPlanner().prepare(session, run.record, config, { system: context, tools, stepId: stepRecord.id });
if (planned.record.archivedGroups && !projectionLogged) {
projectionLogged = true; session.compactions++;
@@ -238,6 +253,7 @@ export class Runtime {
run.record.review = { kind: 'git_delivery', planId: deliveryReview.id, status: 'pending', preparedAt: now() };
}
this.store.save(session);
await yieldExecution(undefined, { signal });
signal.throwIfAborted();
}
this.store.finishStep(session, stepRecord);
@@ -292,6 +308,8 @@ 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 === 'inspect_engine_checks') result = { status: 'completed', engine_checks: this.engineManager().jobs(session)
.filter(job => job.taskId === run.taskId).map(job => this.engineManager().summary(session, job)), note: '已保存的引擎连接核验;完整原记录使用report_artifact_id读取,查询不会启动引擎。' };
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 });
@@ -460,11 +478,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); await this.research?.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); await this.engines?.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(); await this.research?.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(); await this.engines?.stopAll(); }
}
+9
View File
@@ -9,6 +9,7 @@ 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';
import { ENGINE_ACTIVE, publicEngineJob } from '../shared/contracts/engines.mjs';
export const now = () => new Date().toISOString();
@@ -224,6 +225,13 @@ export class Store extends EventEmitter {
if (event) { event.phase = job.status; event.finishedAt = job.finishedAt; event.output = job.summary; }
changed = true;
}
for (const job of this.core.engine_job.values()) if (job.sessionId === session.id && ENGINE_ACTIVE.has(job.status)) {
job.status = 'unknown'; job.requiresVerification = true; job.verification = null; job.finishedAt = now();
job.summary = '外部引擎连接检查中断,原进程关闭状态未知。不会根据历史PID停止进程或重放请求,请查看所属原记录。';
const event = session.events.find(value => value.id === job.eventId);
if (event) { event.phase = 'unknown'; 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);
@@ -522,6 +530,7 @@ export class Store extends EventEmitter {
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),
engineJobs: [...this.core.engine_job.values()].filter(value => value.sessionId === session.id && (value.taskId === task?.id || value.requiresVerification)).slice(-20).map(publicEngineJob),
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),
+34
View File
@@ -0,0 +1,34 @@
import { createHash } from 'node:crypto';
export const ENGINE_ACTIVE = new Set(['queued', 'starting', 'initializing', 'checking', 'stopping']);
export const ENGINE_SCOPE = 'deepseek-sdk-connection-probe';
export const ENGINE_LIMITS = Object.freeze([
'当前接入核验启动、会话目录、协议错误和关闭;工程执行接入开发中。',
'SDK没有单会话cancel或close;停止以所属独立进程为单位。',
'SDK serverInfo.version与发行包版本分别核对,没有有效协议版本协商。',
'SDK事件覆盖运行时会话树,idle事件不能直接判项目交付完成。',
]);
export const engineError = (message, status = 409, code = 'ENGINE_CONTRACT') => Object.assign(new Error(message), { status, code });
export const engineDigest = value => createHash('sha256').update(typeof value === 'string' ? value : JSON.stringify(value), 'utf8').digest('hex');
export function engineInput(job) {
return { schemaVersion: 1, jobId: job.id, sessionId: job.sessionId, projectId: job.projectId,
taskId: job.taskId, runId: job.runId, engineId: job.engineId, scope: job.scope,
installation: job.installation, sdkSessionId: job.sdkSessionId, directory: job.directory,
protocolMethods: ['initialize', 'session/working-directory/get', 'session/wait', 'session/resume', 'session/cancel', 'shutdown'],
modelRequestsAllowed: 0, externalProjectToolsAllowed: false };
}
export function engineReportContract(job) {
return { schemaVersion: 1, inputSha256: job.contractSha256, owner: { sessionId: job.sessionId,
projectId: job.projectId, taskId: job.taskId, runId: job.runId, jobId: job.id },
engineId: job.engineId, scope: job.scope, installationSha256: job.installation.identitySha256,
sdkSessionId: job.sdkSessionId, outcome: { status: job.status, error: job.error ?? null, verification: job.verification }, report: job.report };
}
export function publicEngineJob(job) {
const { report, ...value } = job;
return { ...value, reportSummary: report ? { status: report.status, modelRequests: report.modelRequests,
providerRequests: report.providerRequests, observedResponses: report.responses?.length ?? 0,
rootExited: report.cleanup?.rootExited ?? null } : null };
}
+1 -1
View File
@@ -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', 'research_target', 'research_job'];
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', 'engine_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);