本地项目{session ?
:
等待新任务}
diff --git a/src/client/EnginePanel.css b/src/client/EnginePanel.css
new file mode 100644
index 00000000..6929b614
--- /dev/null
+++ b/src/client/EnginePanel.css
@@ -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; } }
diff --git a/src/client/EnginePanel.tsx b/src/client/EnginePanel.tsx
new file mode 100644
index 00000000..d0fd065c
--- /dev/null
+++ b/src/client/EnginePanel.tsx
@@ -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
= { 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(null);
+ const [checking, setChecking] = useState(false), [pending, setPending] = useState(false);
+ const [retry, setRetry] = useState(null), [preview, setPreview] = useState(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('/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('/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('/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
+
+
+
+ 当前可用能力
原程序连接与独立进程停止
同任务保存原记录与来源
+
工程执行接入中本次检查不发送模型任务。完成连接核验后,继续接入工程工具与交付流程。
+
连接与执行范围
每次检查启动一个独立进程。停止只作用于这个检查;SDK 会话目录、协议版本与完整错误保存在原记录。当前版本没有开放外部引擎修改工程。
+ 本任务连接记录 {jobs.length}
+ {running && }
+ {!jobs.length && 先验证这个安装能否连接检查完成后,可以查看实际启动、协议返回和进程结束记录;检查不会调用已配置的模型。
}
+ {jobs.map(job => { const verified = job.status === 'completed' && job.verification?.verified === true;
+ return
+ DeepSeek Harness {job.installation.version}{date(job.startedAt)}
+
{active.includes(job.status) && }{states[job.status] ?? job.status}
+ {job.summary}
+
+
安装身份{job.installation.identitySha256?.slice(0, 12) ?? '等待核对'}
+
启动完成{job.readiness ? 'PID ' + job.readiness.pid : '尚无信号'}
+
协议返回{job.serverInfo?.version ?? '尚无返回'}
+
进程结束{job.reportSummary?.rootExited ? '已核对' : job.finishedAt ? '待核对' : '检查中'}
+
+
+
+ {!active.includes(job.status) && }
+ 任务与安装来源
- 项目
- {project.name}
- Task
- {job.taskId}
- Run
- {job.runId}
+ - SDK 会话
- {job.sdkSessionId}
- 安装目录
- {job.installation.root}
- 安装 SHA256
- {job.installation.identitySha256}
+ - 原记录 SHA256
- {job.reportSha256 ?? '尚未封存'}
- 模型请求
- {job.reportSummary?.modelRequests ?? '尚未核对'}
+ ;
+ })}
+
+ {retry &&
setRetry(null)}>
+ {retry.installation.root}
将重新核对当前安装、启动完成、SDK 返回和进程关闭。本次不会发送模型任务。
+ }
+ {preview &&
{ viewRequest.current++; setPreview(null); setViewBusy(false); }}>
+ 原记录 SHA256{preview.page.sha256}
+ {preview.page.content}
+ {preview.page.offset.toLocaleString()}–{(preview.page.offset + preview.page.content.length).toLocaleString()} / {preview.page.totalCharacters.toLocaleString()} 字符
+
+
+
+ }
+
;
+}
diff --git a/src/client/api.ts b/src/client/api.ts
index 7b8c3f54..e3d79013 100644
--- a/src/client/api.ts
+++ b/src/client/api.ts
@@ -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');
+}
diff --git a/src/client/types.ts b/src/client/types.ts
index 1d12ba06..86dfb9ef 100644
--- a/src/client/types.ts
+++ b/src/client/types.ts
@@ -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 {
diff --git a/src/core/engine-manager.mjs b/src/core/engine-manager.mjs
new file mode 100644
index 00000000..a27bf2a4
--- /dev/null
+++ b/src/core/engine-manager.mjs
@@ -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))); }
+}
diff --git a/src/core/engines/deepseek-adapter.mjs b/src/core/engines/deepseek-adapter.mjs
new file mode 100644
index 00000000..07e1bed3
--- /dev/null
+++ b/src/core/engines/deepseek-adapter.mjs
@@ -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;
+ }
+}
diff --git a/src/core/engines/deepseek-installation.mjs b/src/core/engines/deepseek-installation.mjs
new file mode 100644
index 00000000..0df83469
--- /dev/null
+++ b/src/core/engines/deepseek-installation.mjs
@@ -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;
+}
diff --git a/src/core/tools/mcp-stdio.mjs b/src/core/tools/mcp-stdio.mjs
index ff51b7c3..be231b91 100644
--- a/src/core/tools/mcp-stdio.mjs
+++ b/src/core/tools/mcp-stdio.mjs
@@ -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 });
diff --git a/src/server/app.mjs b/src/server/app.mjs
index b228b88f..2cea91a6 100644
--- a/src/server/app.mjs
+++ b/src/server/app.mjs
@@ -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) });
}
diff --git a/src/server/diagnostics.mjs b/src/server/diagnostics.mjs
index 69bc5167..444ff62c 100644
--- a/src/server/diagnostics.mjs
+++ b/src/server/diagnostics.mjs
@@ -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';
diff --git a/src/server/hot-upgrade.mjs b/src/server/hot-upgrade.mjs
index e772f328..c6dc694f 100644
--- a/src/server/hot-upgrade.mjs
+++ b/src/server/hot-upgrade.mjs
@@ -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);
diff --git a/src/server/provider.mjs b/src/server/provider.mjs
index 82099a58..62b64595 100644
--- a/src/server/provider.mjs
+++ b/src/server/provider.mjs
@@ -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: {} } } },
diff --git a/src/server/runtime.mjs b/src/server/runtime.mjs
index 9dde5c79..8b7c3873 100644
--- a/src/server/runtime.mjs
+++ b/src/server/runtime.mjs
@@ -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(); }
}
diff --git a/src/server/store.mjs b/src/server/store.mjs
index 17513406..5acda170 100644
--- a/src/server/store.mjs
+++ b/src/server/store.mjs
@@ -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),
diff --git a/src/shared/contracts/engines.mjs b/src/shared/contracts/engines.mjs
new file mode 100644
index 00000000..a7850961
--- /dev/null
+++ b/src/shared/contracts/engines.mjs
@@ -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 };
+}
diff --git a/src/shared/contracts/execution.mjs b/src/shared/contracts/execution.mjs
index a5df7bfd..8a6f9cf7 100644
--- a/src/shared/contracts/execution.mjs
+++ b/src/shared/contracts/execution.mjs
@@ -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);
diff --git a/task_plan.md b/task_plan.md
index caeddb9d..6bcb36c4 100644
--- a/task_plan.md
+++ b/task_plan.md
@@ -1,5 +1,17 @@
# Agent Workbench:核心代理能力研究与产品计划
+## 当前执行:1.9 引擎接入与实际流程(2026-10-30)
+
+用户要求继续全量推进,接续既有1.8.0与未提交引擎实现。正式服务与真实模型连接保持;当前开发使用独立宿主、数据目录和本地Git小步提交。
+
+1. [complete] 未提交DeepSeek引擎契约、实际0.2.1-rc.2 SDK、22项专项与原协议记录已经完成;接续审核并在独立发行中验证。
+2. [complete] 引擎面板10组桌面/390px验收通过,含原记录下载、归属、停止和实际重启;保留前两轮失败原记录。
+3. [pending] 审查实际SDK的受控执行入口,按真实工具与权限契约推进工程执行;连接通过和工程交付分别判定,不以idle通知判断完成。
+4. [in_progress] 接续PID30912的1.9.0完整源码回归;首轮全量界面在离线演示等待审批时超时,保存原DOM/数据库/报告,先查实际任务与负载。完成后提交实现、生成不可变发行、独立源码/便携验收和保留原Provider升级。
+5. [pending] 继续真实工程样本、桌面宿主与手机伴随端切片;每个实际成果独立验证和提交,计划不记为已实现。
+
+恢复核对:Agent-Workbench为独立Git仓库;正式1.8.0已有244项独立源码、98组界面和真实四模块工程交付证据,不重复既有任务。新增核心/适配/API草稿未提交,前一轮尚无产品引擎UI或实际SDK适配验收。Node实测24.22.1。首次父目录Git错误与大输出截断已改为明确工作目录和限定读取。
+
## 用户授权与目标
- 本项目专注编程代理能力研究与工作台开发,其他项目不纳入本项目计划和版本管理。
- 本对话已获确认:研究 Claude Code,形成机制报告并提炼自己的本地代理设计。
diff --git a/tests/engine-api.test.mjs b/tests/engine-api.test.mjs
new file mode 100644
index 00000000..5e40ac4e
--- /dev/null
+++ b/tests/engine-api.test.mjs
@@ -0,0 +1,60 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import path from 'node:path';
+import { createHash } from 'node:crypto';
+import { fixture, launchWorkbench, until } from './helpers.mjs';
+import { createEngineFixture } from '../scripts/engine-fixtures.mjs';
+
+test('engine HTTP checks bind the detected installation and current task, page original bytes and preserve them across host restart', async t => {
+ const f = fixture(t), root = createEngineFixture(path.join(f.root, 'sdk 源码 #'));
+ f.store.close(); let host = await launchWorkbench(t, f.data, { AGENT_WORKBENCH_DEEPSEEK_ROOT: root });
+ const route = '/sessions/' + f.session.id, installation = await host.api('/engines/deepseek/availability');
+ assert.equal(installation.status, 'available'); assert.equal(installation.capabilities.projectExecution, false);
+ await assert.rejects(host.api(route + '/engines/jobs', { root, identitySha256: '0'.repeat(64) }), /检测结果不一致/);
+ assert.equal((await host.api(route)).execution.engineJobs.length, 0);
+ const started = await host.api(route + '/engines/jobs', { root, identitySha256: installation.identitySha256 });
+ const jobRoute = route + '/engines/jobs/' + started.job.id;
+ await until(async () => (await host.api(route)).execution.engineJobs.at(-1).reportArtifactId, 15000);
+ const job = await host.api(jobRoute), session = await host.api(route);
+ assert.equal(job.status, 'completed'); assert.equal(job.report, undefined); assert.equal(job.reportSummary.modelRequests, 0);
+ assert.equal(job.taskId, session.execution.task.id); assert.equal(job.runId, session.execution.run.id);
+ assert.equal((await host.api(route + '/engines')).jobs[0].id, job.id);
+ const response = await fetch(host.url + '/api' + jobRoute + '/download', { headers: { 'X-Workbench-Token': host.bootstrap.token } });
+ assert.equal(response.status, 200); assert.match(response.headers.get('content-disposition'), /attachment/);
+ const text = await response.text(), original = JSON.parse(text);
+ assert.equal(createHash('sha256').update(text).digest('hex'), job.reportSha256); assert.equal(original.owner.sessionId, f.session.id);
+ assert.equal(original.report.responses.length, 6); assert.equal(original.report.cleanup.rootExited, true);
+ let content = '', offset = 0, page;
+ do {
+ page = await host.api(jobRoute + '/report?offset=' + offset + '&limit=1700'); assert.equal(page.sha256, job.reportSha256);
+ content += page.content; offset += page.content.length;
+ } while (page.truncated);
+ assert.equal(content, text); await assert.rejects(host.api(jobRoute + '/report?limit=0'), /读取位置或页长/);
+ const other = await host.api('/sessions', { projectId: f.project.id });
+ await assert.rejects(host.api('/sessions/' + other.id + '/engines/jobs/' + job.id + '/report'), /不属于/);
+ const wire = path.join(root, 'wire.jsonl'), before = fs.readFileSync(wire);
+ await host.close(); host = await launchWorkbench(t, f.data, { AGENT_WORKBENCH_DEEPSEEK_ROOT: root });
+ const reopened = await host.api(jobRoute); assert.equal(reopened.status, 'completed'); assert.equal(reopened.reportSha256, job.reportSha256);
+ assert.equal((await host.api(jobRoute + '/report?limit=1700')).content, text.slice(0, 1700));
+ assert.deepEqual(fs.readFileSync(wire), before); assert.equal((await host.api(route)).execution.task.usage.requests, 0);
+});
+
+test('HTTP stop seals a pending SDK call, rejects automatic replay and keeps failures attached to the original session', async t => {
+ const f = fixture(t), root = createEngineFixture(path.join(f.root, 'sdk'), { mode: 'hang-init' }); f.store.close();
+ const host = await launchWorkbench(t, f.data, { AGENT_WORKBENCH_DEEPSEEK_ROOT: root }), route = '/sessions/' + f.session.id;
+ const started = await host.api(route + '/engines/jobs', { root });
+ await until(async () => (await host.api(route)).execution.engineJobs.at(-1).status === 'initializing', 15000);
+ const other = await host.api('/sessions', { projectId: f.project.id });
+ await assert.rejects(host.api('/sessions/' + other.id + '/messages', { content: 'owned request' }), /在执行/);
+ await host.api(route + '/engines/stop', {});
+ const job = await host.api(route + '/engines/jobs/' + started.job.id);
+ assert.equal(job.status, 'cancelled'); assert.equal(job.reportSummary.rootExited, true); assert.equal(job.taskId, started.job.taskId);
+ await assert.rejects(host.api(route + '/engines/jobs', { root }), /重新验证/);
+ const text = fs.readFileSync(path.join(root, 'wire.jsonl'), 'utf8'); assert.equal(text.includes('notifications/cancelled'), false);
+ fs.writeFileSync(path.join(root, 'fixture-options.json'), '{}');
+ const retry = await host.api(route + '/engines/jobs', { root, retry: true });
+ await until(async () => (await host.api(route)).execution.engineJobs.at(-1).reportArtifactId, 15000);
+ assert.equal((await host.api(route + '/engines/jobs/' + retry.job.id)).status, 'completed');
+ assert.notEqual(retry.job.id, job.id); assert.equal((await host.api(route)).execution.engineJobs.length, 2);
+});
diff --git a/tests/engine.test.mjs b/tests/engine.test.mjs
new file mode 100644
index 00000000..c1b70c1d
--- /dev/null
+++ b/tests/engine.test.mjs
@@ -0,0 +1,181 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+import { EngineManager } from '../src/core/engine-manager.mjs';
+import { DeepSeekAdapter } from '../src/core/engines/deepseek-adapter.mjs';
+import { resolveDeepSeekInstallation } from '../src/core/engines/deepseek-installation.mjs';
+import { Store } from '../src/server/store.mjs';
+import { Runtime, validateToolArgs } from '../src/server/runtime.mjs';
+import { Provider } from '../src/server/provider.mjs';
+import { createEngineFixture } from '../scripts/engine-fixtures.mjs';
+import { fixture, until } from './helpers.mjs';
+
+function setup(t, options = {}) {
+ const f = fixture(t), root = createEngineFixture(path.join(f.root, 'harness 源码 #'), options);
+ const manager = new EngineManager(f.store, { adapterFactory: installation => new DeepSeekAdapter(installation, { timeoutMs: 3000 }) });
+ f.onCleanup(async () => {
+ await manager.stopAll();
+ for (const job of manager.jobs(f.session)) {
+ const directory = path.resolve(job.directory), base = path.resolve(os.tmpdir(), 'AgentWorkbench-Engines');
+ assert.equal(path.dirname(directory), base); assert.equal(path.basename(directory), job.id);
+ fs.rmSync(directory, { recursive: true, force: true, maxRetries: 3 });
+ }
+ });
+ const audit = () => fs.existsSync(path.join(root, 'wire.jsonl')) ? fs.readFileSync(path.join(root, 'wire.jsonl'), 'utf8').trim().split('\n').map(line => JSON.parse(line)) : [];
+ return { ...f, root, manager, audit };
+}
+
+test('engine detection seals the actual CLI, SDK, profile and Node and rejects mixed versions without launch', t => {
+ const f = setup(t), current = resolveDeepSeekInstallation(process.cwd(), f.root);
+ assert.equal(current.status, 'available'); assert.equal(current.version, '0.2.1-rc.2'); assert.equal(current.inputs.length, 13);
+ const pkg = path.join(f.root, 'packages/sdk/server/package.json');
+ fs.writeFileSync(pkg, JSON.stringify({ version: 'another-version' }));
+ assert.equal(f.manager.availability(f.root).status, 'unsupported'); assert.throws(() => f.manager.start(f.session, { root: f.root }), /版本不一致/);
+ assert.equal(f.audit().length, 0); assert.equal(f.store.core.engine_job.size, 0);
+ fs.writeFileSync(pkg, JSON.stringify({ version: '0.2.1-rc.2' }));
+ const detected = f.manager.availability(f.root); fs.appendFileSync(path.join(f.root, 'apps/cli/lib/bin.js'), '\n// changed after detection\n');
+ assert.throws(() => f.manager.start(f.session, { root: f.root, identitySha256: detected.identitySha256 }), /检测结果不一致/);
+ assert.equal(f.audit().length, 0); assert.equal(f.store.core.engine_job.size, 0);
+});
+
+test('owned engine probe waits for real ready identity, verifies six native responses and saves immutable task evidence', async t => {
+ const f = setup(t, { readyDelayMs: 150 });
+ const originalBytes = fs.readFileSync(path.join(f.projectRoot, 'README.md'));
+ const started = f.manager.start(f.session, { root: f.root });
+ assert.throws(() => f.manager.start(f.session, { root: f.root }), /在执行/);
+ const job = await started.promise;
+ assert.equal(job.status, 'completed'); assert.equal(job.verification.verified, true); assert.equal(job.report.responses.length, 6);
+ assert.equal(job.report.modelRequests, 0); assert.equal(job.report.cleanup.rootExited, true); assert.equal(job.report.cleanup.exit.code, 0);
+ assert.equal(job.report.readiness.pid, job.pid); assert.equal(job.sdkSessionId, job.report.sdkSessionId);
+ assert.equal(f.store.executionSnapshot(f.session).engineJobs[0].report, undefined);
+ assert.equal(f.store.executionSnapshot(f.session).engineJobs[0].reportSummary.observedResponses, 6);
+ const original = JSON.parse(f.manager.originalReport(f.session, job));
+ assert.equal(original.owner.taskId, f.session.taskId); assert.equal(original.inputSha256, job.contractSha256);
+ assert.ok(original.report.responses[2].error.message.includes(original.report.responses[2].parameters.sessionId));
+ assert.deepEqual(fs.readFileSync(path.join(f.projectRoot, 'README.md')), originalBytes);
+ assert.equal(f.store.core.task.get(f.session.taskId).usage.requests, 0); assert.equal(f.session.status, 'paused');
+ assert.equal(f.audit().filter(value => value.type === 'wire' && value.value.method === 'session/prompt').length, 0);
+});
+
+test('an invalid startup nonce is rejected before initialize and preserves the process close and partial report', async t => {
+ const f = setup(t, { mode: 'bad-ready' }), job = await f.manager.start(f.session, { root: f.root }).promise;
+ assert.equal(job.status, 'failed'); assert.match(job.summary, /启动完成信号/); assert.equal(job.report.trace.length, 0);
+ assert.equal(job.report.cleanup.rootExited, true); assert.equal(f.audit().filter(value => value.type === 'wire').length, 0);
+ assert.equal(f.manager.summary(f.session, job).evidence_verified, false);
+});
+
+test('SDK identity and session directory mismatches retain raw responses and never become verified', async t => {
+ for (const mode of ['wrong-version', 'wrong-cwd', 'malformed']) {
+ const f = setup(t, { mode }), job = await f.manager.start(f.session, { root: f.root }).promise;
+ assert.equal(job.status, 'failed', mode); assert.equal(job.verification, null); assert.ok(job.reportArtifactId);
+ assert.equal(job.report.cleanup.rootExited, true); assert.equal(f.manager.summary(f.session, job).evidence_verified, false);
+ if (mode !== 'malformed') assert.ok(job.report.responses.length);
+ }
+});
+
+test('cancel during a pending initialize closes only the owned process without sending an unsupported MCP cancellation', async t => {
+ const f = setup(t, { mode: 'hang-init' }), started = f.manager.start(f.session, { root: f.root });
+ await until(() => started.job.status === 'initializing' && f.audit().some(value => value.value?.method === 'initialize'));
+ await f.manager.stop(f.session.id);
+ const job = await started.promise;
+ assert.equal(job.status, 'cancelled'); assert.equal(job.report.cleanup.rootExited, true);
+ assert.equal(job.report.cleanup.pid, job.pid); assert.equal(job.requiresVerification, false);
+ assert.equal(f.audit().filter(value => value.value?.method === 'notifications/cancelled').length, 0);
+ assert.throws(() => f.manager.start(f.session, { root: f.root }), /重新验证/);
+});
+
+test('cancel before readiness sends no protocol request and a user retry creates a different process and record', async t => {
+ const f = setup(t, { mode: 'no-ready' }), started = f.manager.start(f.session, { root: f.root });
+ await until(() => started.job.pid && f.audit().length);
+ await f.manager.stop(f.session.id); assert.equal((await started.promise).status, 'cancelled');
+ assert.equal(f.audit().filter(value => value.type === 'wire').length, 0);
+ fs.writeFileSync(path.join(f.root, 'fixture-options.json'), '{}');
+ const retry = await f.manager.start(f.session, { root: f.root, retry: true }).promise;
+ assert.equal(retry.status, 'completed'); assert.notEqual(retry.id, started.job.id); assert.notEqual(retry.pid, started.job.pid);
+});
+
+test('source or scratch changes and unexpected model traffic fail after preserving the actual observed result', async t => {
+ for (const mode of ['change-input', 'change-workspace', 'model-request']) {
+ const f = setup(t, { mode }), job = await f.manager.start(f.session, { root: f.root }).promise;
+ assert.equal(job.status, 'failed', mode); assert.equal(job.report.cleanup.rootExited, true); assert.equal(job.verification, null);
+ if (mode === 'model-request') { assert.equal(job.report.modelRequests, 1); assert.equal(job.report.providerRequests, 0); }
+ assert.equal(f.session.changes.length, 0);
+ }
+});
+
+test('unowned idle notifications stay quarantined and server requests receive a rejection without granting operations', async t => {
+ const f = setup(t, { mode: 'unowned-event' }), job = await f.manager.start(f.session, { root: f.root }).promise;
+ assert.equal(job.status, 'completed'); assert.equal(job.report.notifications.length, 0); assert.equal(job.report.unownedNotifications.length, 1);
+ assert.equal(f.store.core.task.get(f.session.taskId).status, 'paused');
+ const reverse = setup(t, { mode: 'reverse-request' }), response = await reverse.manager.start(reverse.session, { root: reverse.root }).promise;
+ assert.equal(response.status, 'completed'); assert.equal(response.report.rejectedServerRequests.length, 1);
+ assert.ok(reverse.audit().some(value => value.value?.id === 'reverse-control' && value.value?.error?.code === -32601));
+ assert.equal(reverse.session.approvals.length, 0); assert.equal(reverse.session.changes.length, 0);
+});
+
+test('engine probe environment excludes parent secrets and NODE_OPTIONS while preserving operating system paths', async t => {
+ const f = setup(t), previousSecret = process.env.OWNED_ENGINE_TEST_SECRET, previousOptions = process.env.NODE_OPTIONS;
+ process.env.OWNED_ENGINE_TEST_SECRET = 'owned-non-credential-test'; process.env.NODE_OPTIONS = '--no-warnings';
+ try {
+ const job = await f.manager.start(f.session, { root: f.root }).promise; assert.equal(job.status, 'completed');
+ const launch = f.audit()[0]; assert.equal(launch.secretInherited, false); assert.equal(launch.nodeOptionsInherited, false);
+ } finally {
+ if (previousSecret === undefined) delete process.env.OWNED_ENGINE_TEST_SECRET; else process.env.OWNED_ENGINE_TEST_SECRET = previousSecret;
+ if (previousOptions === undefined) delete process.env.NODE_OPTIONS; else process.env.NODE_OPTIONS = previousOptions;
+ }
+});
+
+test('foreign sessions and altered reports or task bindings cannot reuse verified engine evidence', async t => {
+ const f = setup(t), job = await f.manager.start(f.session, { root: f.root }).promise, other = f.store.createSession(f.project.id);
+ assert.throws(() => f.manager.originalReport(other, job), /不属于/);
+ const original = job.sdkSessionId; job.sdkSessionId = other.id;
+ assert.equal(f.manager.summary(f.session, job).evidence_verified, false); assert.throws(() => f.manager.originalReport(f.session, job), /不一致/); job.sdkSessionId = original;
+ const artifact = f.store.core.artifact.get(job.reportArtifactId), filename = path.join(f.store.artifactStore.root, artifact.relative);
+ fs.appendFileSync(filename, 'tampered'); assert.equal(f.manager.summary(f.session, job).evidence_verified, false);
+ assert.throws(() => f.manager.originalReport(f.session, job), /校验失败/);
+});
+
+test('restart never replays an active engine check or stops a historical PID, and keeps prior task state', async t => {
+ const f = setup(t), job = await f.manager.start(f.session, { root: f.root }).promise;
+ const calls = f.audit().length; job.status = 'starting'; job.pid = process.pid; job.verification = null;
+ f.store.putRecord('engine_job', f.session, job, 'fixture.crash_window'); f.store.close();
+ const reopened = new Store(f.data); f.onCleanup(() => reopened.close());
+ const saved = reopened.core.engine_job.get(job.id);
+ assert.equal(saved.status, 'unknown'); assert.equal(saved.requiresVerification, true); assert.equal(saved.pid, process.pid);
+ assert.equal(f.audit().length, calls); assert.equal(reopened.session(f.session.id).taskId, f.session.taskId);
+});
+
+test('model argument validation and runtime activity do not grant external engine prompt or project execution', t => {
+ const f = setup(t), runtime = new Runtime(f.store, new Provider());
+ assert.doesNotThrow(() => validateToolArgs('inspect_engine_checks', {}));
+ assert.throws(() => validateToolArgs('inspect_engine_checks', { root: f.root }), /当前任务/);
+ assert.throws(() => validateToolArgs('engine_prompt', {}), /没有工具/);
+ assert.throws(() => f.manager.start(f.session, { root: f.root, prompt: 'not accepted' }), /只接受/);
+ runtime.engines = { active: new Map([[f.session.id, {}]]), isActive: id => id === f.session.id, projectActive: id => id === f.project.id };
+ assert.equal(runtime.hasActivity(), true); assert.equal(runtime.isActive(f.session.id), true); assert.equal(runtime.projectHasActivity(f.project.id), true);
+ assert.throws(() => runtime.start(f.session.id, 'fixture request'), /在执行/);
+});
+
+test('a follow-up question receives the actual failed engine check from its original Task and keeps its report unchanged', async t => {
+ const f = setup(t, { mode: 'bad-ready' }), job = await f.manager.start(f.session, { root: f.root }).promise;
+ assert.equal(job.status, 'failed'); const originalReport = f.manager.originalReport(f.session, job), taskId = job.taskId;
+ const provider = new Provider(); let requests = 0;
+ provider.complete = async (_config, messages, _project, _signal, _progress, _plan, tools) => {
+ requests++;
+ assert.ok(tools.some(tool => tool.function.name === 'inspect_engine_checks'));
+ if (requests === 1) return { message: { role: 'assistant', content: '', tool_calls: [
+ { id: 'owned-engine-question', type: 'function', function: { name: 'inspect_engine_checks', arguments: '{}' } },
+ ] }, usage: null };
+ const result = JSON.parse(messages.filter(message => message.role === 'tool').at(-1).content), check = result.engine_checks[0];
+ assert.equal(check.engine_job_id, job.id); assert.equal(check.task_id, taskId); assert.equal(check.engine_status, 'failed');
+ assert.match(check.message, /启动完成信号/); assert.equal(check.report_sha256, job.reportSha256);
+ return { message: { role: 'assistant', content: '当前任务的引擎启动完成信号与所属进程不一致,检查未通过;原进程已经关闭,原记录仍保留。' }, usage: null };
+ };
+ const runtime = new Runtime(f.store, provider); runtime.engines = f.manager;
+ f.onCleanup(() => runtime.stopAll());
+ runtime.start(f.session.id, '刚才的引擎连接检查为什么报错?'); await runtime.active.get(f.session.id).promise;
+ assert.equal(f.session.taskId, taskId); assert.equal(f.session.status, 'completed'); assert.equal(requests, 2);
+ assert.equal(f.manager.originalReport(f.session, job), originalReport); assert.match(f.session.messages.at(-1).content, /当前任务/);
+});
diff --git a/tests/runtime.test.mjs b/tests/runtime.test.mjs
index cbbecbf1..edac9990 100644
--- a/tests/runtime.test.mjs
+++ b/tests/runtime.test.mjs
@@ -19,6 +19,49 @@ function commandProvider(command) {
return provider;
}
+test('a stop from the event loop interrupts immediate model replies before later tools', async t => {
+ const f = fixture(t), provider = new Provider();
+ let replies = 0, stopped;
+ const runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll());
+ provider.complete = async () => {
+ replies++;
+ if (replies === 1) setImmediate(() => { stopped = runtime.stop(f.session.id); });
+ return { message: { role: 'assistant', content: 'Controlled immediate reply.',
+ ...(replies <= 6 ? { tool_calls: [call('immediate-' + replies, 'list_files', { path: '', depth: 1 })] } : {}) }, usage: null };
+ };
+ runtime.start(f.session.id, 'Inspect this owned fixture; allow an incoming stop to take effect.');
+ await runtime.active.get(f.session.id).promise;
+ await new Promise(resolve => setImmediate(resolve)); await stopped;
+ assert.equal(f.session.status, 'paused', 'The event loop must process the stop before the task finishes.');
+ assert.equal(replies, 1, 'A completed tool must be persisted before stop prevents the next model reply.');
+ const tools = [...f.store.core.tool.values()].filter(value => value.sessionId === f.session.id);
+ assert.equal(tools.length, 1); assert.equal(tools[0].state, 'completed');
+ assert.equal(f.store.core.run.get(f.session.runId).stopReason, 'cancelled');
+ assertToolPairs(f.session.providerMessages);
+});
+
+test('a stop after the first tool preserves a complete interrupted multi-call protocol group', async t => {
+ const f = fixture(t), provider = new Provider(), runtime = new Runtime(f.store, provider);
+ f.onCleanup(() => runtime.stopAll());
+ let scheduled = false, stopped;
+ f.store.on('update', () => {
+ if (!scheduled && f.session.events.some(value => value.toolCallId === 'fair-batch-0' && value.phase === 'completed')) {
+ scheduled = true; setImmediate(() => { stopped = runtime.stop(f.session.id); });
+ }
+ });
+ provider.complete = async () => ({ message: { role: 'assistant', content: 'Controlled immediate multi-tool reply.',
+ tool_calls: Array.from({ length: 6 }, (_, index) => call('fair-batch-' + index, 'list_files', { path: '', depth: 1 })) }, usage: null });
+ runtime.start(f.session.id, 'Inspect this fixture and accept a stop before later batched calls.');
+ await runtime.active.get(f.session.id).promise;
+ await new Promise(resolve => setImmediate(resolve)); await stopped;
+ assert.equal(f.session.status, 'paused');
+ const tools = [...f.store.core.tool.values()].filter(value => value.sessionId === f.session.id);
+ assert.equal(tools.length, 6); assert.equal(tools[0].state, 'completed');
+ assert.ok(tools.slice(1).every(value => value.state === 'interrupted' && !value.requiresVerification));
+ assertToolPairs(f.session.providerMessages);
+ assert.equal(f.session.providerMessages.filter(value => value.role === 'tool').length, 6);
+});
+
test('the compatible HTTP loop preserves call IDs, validates errors and waits before executing commands', async t => {
const f = fixture(t);
const command = 'node -e "require(\'node:fs\').writeFileSync(\'approved.txt\',\'ok\'); console.log(\'fixture-command\')"';