feat: verify owned DeepSeek engine connections and responsive task execution
This commit is contained in:
@@ -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))); }
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import http from 'node:http';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { McpStdio } from '../tools/mcp-stdio.mjs';
|
||||
import { engineDigest, engineError, ENGINE_SCOPE } from '../../shared/contracts/engines.mjs';
|
||||
import { assertDeepSeekInstallation, engineFileIdentity } from './deepseek-installation.mjs';
|
||||
|
||||
export const DEEPSEEK_READY_PLUGIN = `import fs from 'node:fs';
|
||||
export const name = 'agent-workbench-sdk-ready';
|
||||
export const inject = ['appReady'];
|
||||
export function apply(ctx, config) {
|
||||
const ready = ctx.get('appReady');
|
||||
if (!ready || typeof ready.onReady !== 'function') throw new Error('The fixed SDK launcher has no appReady service.');
|
||||
const stop = ready.onReady(() => {
|
||||
const value = { schemaVersion: 1, nonce: config.nonce, pid: process.pid, signal: 'appReady', readyAt: new Date().toISOString() };
|
||||
const temporary = config.marker + '.writing';
|
||||
fs.writeFileSync(temporary, JSON.stringify(value), { flag: 'wx' });
|
||||
fs.renameSync(temporary, config.marker);
|
||||
});
|
||||
ctx.effect(() => stop, 'workbench.sdk-ready');
|
||||
}
|
||||
`;
|
||||
|
||||
const allowedEnvironment = /^(path|pathext|systemroot|systemdrive|windir|comspec|temp|tmp|userprofile|appdata|localappdata|programfiles(?:\(x86\))?|homedrive|homepath)$/i;
|
||||
const at = () => new Date().toISOString();
|
||||
const fail = (message, code = 'ENGINE_PROTOCOL') => engineError(message, 409, code);
|
||||
|
||||
export class DeepSeekAdapter {
|
||||
constructor(installation, { timeoutMs = 15000, clientFactory = (launch, options) => new McpStdio(launch, options) } = {}) {
|
||||
this.installation = installation; this.timeoutMs = timeoutMs; this.clientFactory = clientFactory;
|
||||
}
|
||||
async waitReady(marker, nonce, signal) {
|
||||
const deadline = Date.now() + this.timeoutMs;
|
||||
while (true) {
|
||||
signal?.throwIfAborted();
|
||||
if (fs.existsSync(marker)) {
|
||||
const readiness = JSON.parse(fs.readFileSync(marker, 'utf8'));
|
||||
if (readiness.schemaVersion !== 1 || readiness.nonce !== nonce || readiness.pid !== this.client.pid
|
||||
|| readiness.signal !== 'appReady' || !Number.isFinite(Date.parse(readiness.readyAt))) throw fail('启动完成信号与所属进程不一致。');
|
||||
return { ...readiness, artifact: engineFileIdentity(marker) };
|
||||
}
|
||||
if (this.client.exited || this.client.protocolError) throw fail('原程序在启动完成前关闭或返回无效协议。');
|
||||
if (Date.now() >= deadline) throw fail('原程序未在等待范围内报告启动完成,尚未发送initialize。', 'ENGINE_START_TIMEOUT');
|
||||
await new Promise(resolve => setTimeout(resolve, 15));
|
||||
}
|
||||
}
|
||||
async probe({ directory, sdkSessionId, signal, onState = () => {} }) {
|
||||
const report = { schemaVersion: 1, scope: ENGINE_SCOPE, sdkSessionId, startedAt: at(), finishedAt: null,
|
||||
responses: [], notifications: [], unownedNotifications: [], rejectedServerRequests: [], networkRequests: [], networkRequestCount: 0,
|
||||
modelRequests: 0, providerRequests: 0, process: null, cleanup: null, readiness: null };
|
||||
let guard, problem = null;
|
||||
const cwd = path.join(directory, 'project'), home = path.join(directory, 'home'), agents = path.join(directory, 'agents');
|
||||
try {
|
||||
signal?.throwIfAborted(); report.before = assertDeepSeekInstallation(this.installation);
|
||||
fs.mkdirSync(directory, { recursive: false });
|
||||
for (const folder of [cwd, home, agents]) fs.mkdirSync(folder);
|
||||
const readme = path.join(cwd, 'README.md'), bytes = Buffer.from('# Agent Workbench owned engine connection probe\n');
|
||||
fs.writeFileSync(readme, bytes, { flag: 'wx' });
|
||||
report.workspace = { root: cwd, before: engineFileIdentity(readme) };
|
||||
const nonce = randomUUID(), marker = path.join(directory, 'ready.json'), plugin = path.join(directory, 'ready.mjs'), patch = path.join(directory, 'ready.patch.json');
|
||||
fs.writeFileSync(plugin, DEEPSEEK_READY_PLUGIN, { flag: 'wx' });
|
||||
fs.writeFileSync(patch, JSON.stringify([{ insert: [{ id: 'agent-workbench-sdk-ready', name: plugin, config: { marker, nonce } }] }]), { flag: 'wx' });
|
||||
report.launchInputs = { plugin: engineFileIdentity(plugin), patch: engineFileIdentity(patch), profile: this.installation.profile };
|
||||
guard = http.createServer((request, response) => {
|
||||
report.networkRequestCount++;
|
||||
if (report.networkRequests.length < 128) report.networkRequests.push({ method: request.method, path: request.url.slice(0, 2000), receivedAt: at() });
|
||||
response.writeHead(409, { Connection: 'close' }); response.end('This owned connection probe accepts no model requests.');
|
||||
});
|
||||
await new Promise((resolve, reject) => { guard.once('error', reject); guard.listen(0, '127.0.0.1', resolve); });
|
||||
const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => allowedEnvironment.test(name)));
|
||||
Object.assign(env, { DSH_HOME: home, DSH_AGENTS_HOME: agents, DSH_TELEMETRY_DISABLED: 'true',
|
||||
DEEPSEEK_API_KEY: 'agent-workbench-owned-protocol-fixture', DEEPSEEK_BASE_URL: 'http://127.0.0.1:' + guard.address().port });
|
||||
signal?.throwIfAborted(); assertDeepSeekInstallation(this.installation);
|
||||
this.client = this.clientFactory({ executable: this.installation.node.path,
|
||||
args: [this.installation.entry, '--profile', this.installation.profile, '--patch', patch], cwd, env },
|
||||
{ timeoutMs: this.timeoutMs, maximumFrameBytes: 4 * 1024 * 1024, cancellationMethod: null });
|
||||
report.process = { pid: this.client.pid, connectionId: this.client.id, startedAt: this.client.startedAt, ownership: 'one-process-per-engine-check' };
|
||||
onState('starting', { pid: this.client.pid, connectionId: this.client.id });
|
||||
let notificationBytes = 0;
|
||||
this.client.on('server-request', value => {
|
||||
if (report.rejectedServerRequests.length >= 32) { this.client.fail(fail('引擎反向请求超过连接核验范围。')); return; }
|
||||
report.rejectedServerRequests.push({ id: value.id, method: value.method, parametersSha256: engineDigest(value.params ?? {}) });
|
||||
});
|
||||
this.client.on('notification', value => {
|
||||
notificationBytes += Buffer.byteLength(JSON.stringify(value), 'utf8');
|
||||
if (notificationBytes > 1024 * 1024 || report.notifications.length + report.unownedNotifications.length >= 128) {
|
||||
this.client.fail(fail('引擎事件超过连接核验的接收范围。')); return;
|
||||
}
|
||||
const owned = value.params?.sessionId === sdkSessionId;
|
||||
(owned ? report.notifications : report.unownedNotifications).push(value);
|
||||
});
|
||||
report.readiness = await this.waitReady(marker, nonce, signal);
|
||||
if (engineFileIdentity(plugin).sha256 !== report.launchInputs.plugin.sha256 || engineFileIdentity(patch).sha256 !== report.launchInputs.patch.sha256) throw fail('启动期间所属就绪插件或profile叠加输入发生变化。');
|
||||
onState('initializing', { readiness: report.readiness });
|
||||
const request = async (method, params = {}, expectError = false) => {
|
||||
let result, error;
|
||||
try { result = await this.client.request(method, params, { signal }); }
|
||||
catch (failure) {
|
||||
if (!expectError || failure.code !== 'MCP_REMOTE_ERROR') throw failure;
|
||||
try { error = JSON.parse(failure.message); } catch { throw fail('原程序错误返回不是可核对的协议错误。'); }
|
||||
}
|
||||
const trace = this.client.trace.at(-1);
|
||||
const observation = { method, id: trace.id, parameters: params, parametersSha256: trace.parametersSha256,
|
||||
...(error ? { error } : { result }), startedAt: trace.startedAt, finishedAt: trace.finishedAt };
|
||||
report.responses.push(observation);
|
||||
if (expectError && (!error || typeof error.code !== 'number' || typeof error.message !== 'string')) throw fail('原程序没有按协议拒绝这个未存在的会话操作。');
|
||||
return error ?? result;
|
||||
};
|
||||
const initialized = await request('initialize', { cwd, provider: 'deepseek-official', model: 'deepseek-flash', reasoningEffort: 'off', maxTokens: 256 });
|
||||
if (initialized?.serverInfo?.name !== this.installation.serverInfo.name || initialized?.serverInfo?.version !== this.installation.serverInfo.version) throw fail('SDK返回身份不符合固定发行契约。');
|
||||
onState('checking', { serverInfo: initialized.serverInfo });
|
||||
const workingDirectory = await request('session/working-directory/get', { sessionId: sdkSessionId });
|
||||
if (typeof workingDirectory?.cwd !== 'string' || fs.realpathSync.native(workingDirectory.cwd) !== fs.realpathSync.native(cwd)) throw fail('SDK会话目录与所属探针目录不一致。');
|
||||
const missing = randomUUID();
|
||||
for (const method of ['session/wait', 'session/resume', 'session/cancel']) {
|
||||
const error = await request(method, { sessionId: missing }, true);
|
||||
if (method === 'session/cancel' && !error.message.includes('unknown DeepSeek Harness SDK runtime method: session/cancel')) throw fail('SDK取消能力与已锁定协议不一致。');
|
||||
if (method !== 'session/cancel' && !error.message.includes(missing)) throw fail('SDK错误没有保留所核对的会话身份。');
|
||||
}
|
||||
const shutdown = await request('shutdown');
|
||||
if (!shutdown || typeof shutdown !== 'object' || Array.isArray(shutdown) || Object.keys(shutdown).length) throw fail('SDK关闭响应不符合固定契约。');
|
||||
report.workspace.after = engineFileIdentity(readme);
|
||||
report.workspace.unchanged = fs.readFileSync(readme).equals(bytes) && fs.readdirSync(cwd).length === 1;
|
||||
if (!report.workspace.unchanged) throw fail('原程序修改了连接探针输入,不能记为核验通过。');
|
||||
report.after = assertDeepSeekInstallation(this.installation);
|
||||
} catch (error) { problem = error; }
|
||||
finally {
|
||||
if (this.client) {
|
||||
try { report.cleanup = await this.client.close({ force: !!problem || signal?.aborted === true }); }
|
||||
catch (error) { problem ??= error; }
|
||||
report.trace = this.client.trace; report.stderr = this.client.stderr;
|
||||
}
|
||||
if (guard) { guard.closeAllConnections(); await new Promise(resolve => guard.close(resolve)); }
|
||||
report.modelRequests = report.networkRequestCount; report.finishedAt = at();
|
||||
}
|
||||
if (!problem && (!report.cleanup?.rootExited || report.cleanup.exit?.code !== 0)) problem = fail('所属引擎进程没有可核对的正常关闭结果。');
|
||||
if (!problem && report.modelRequests) problem = fail('原程序发起了核验范围之外的模型请求,连接检查失败。');
|
||||
if (problem) {
|
||||
report.status = report.process && !report.cleanup?.rootExited ? 'unknown' : signal?.aborted ? 'cancelled' : 'failed';
|
||||
report.error = { code: problem.code ?? (signal?.aborted ? 'ENGINE_CANCELLED' : 'ENGINE_CHECK_FAILED'), message: problem.message };
|
||||
throw Object.assign(problem, { report });
|
||||
}
|
||||
report.status = 'verified'; return report;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { createRequire } from 'node:module';
|
||||
import { engineDigest, engineError, ENGINE_LIMITS } from '../../shared/contracts/engines.mjs';
|
||||
|
||||
export const DEEPSEEK_VERSION = '0.2.1-rc.2';
|
||||
export const DEEPSEEK_PROFILE = 'sdk-minimal';
|
||||
const criticalFiles = [
|
||||
'apps/cli/package.json', 'apps/cli/lib/bin.js', 'packages/boot/cmdline/lib/index.js',
|
||||
'packages/bundle/sdk-app/lib/index.js', 'packages/bundle/sdk-minimal/package.json',
|
||||
'packages/bundle/sdk-minimal/cordis.patch.yml', 'packages/sdk/server/package.json',
|
||||
'packages/sdk/server/lib/index.js', 'packages/sdk/protocol/package.json',
|
||||
'packages/sdk/protocol/lib/index.js', 'packages/sdk/client/package.json', 'pnpm-lock.yaml',
|
||||
];
|
||||
|
||||
export function engineFileIdentity(filename, maximumBytes = 32 * 1024 * 1024) {
|
||||
const absolute = fs.realpathSync.native(filename), before = fs.statSync(absolute);
|
||||
if (!before.isFile() || before.size > maximumBytes) throw engineError('引擎输入不是范围内的普通文件。');
|
||||
const hash = createHash('sha256'), chunk = Buffer.allocUnsafe(128 * 1024), fd = fs.openSync(absolute, 'r');
|
||||
try { let count; while ((count = fs.readSync(fd, chunk, 0, chunk.length, null)) > 0) hash.update(chunk.subarray(0, count)); }
|
||||
finally { fs.closeSync(fd); }
|
||||
const after = fs.statSync(absolute);
|
||||
if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ino !== after.ino) throw engineError('读取期间引擎输入发生变化。');
|
||||
return { path: absolute, bytes: after.size, sha256: hash.digest('hex') };
|
||||
}
|
||||
|
||||
function candidates(appDirectory) {
|
||||
const roots = [];
|
||||
if (process.env.AGENT_WORKBENCH_DEEPSEEK_ROOT) roots.push(process.env.AGENT_WORKBENCH_DEEPSEEK_ROOT);
|
||||
let parent = path.resolve(appDirectory);
|
||||
for (let level = 0; level < 7; level++) {
|
||||
roots.push(path.join(parent, 'DeepSeek-Harness-Desktop', 'deepseek-harness'));
|
||||
const next = path.dirname(parent); if (next === parent) break; parent = next;
|
||||
}
|
||||
return [...new Set(roots)];
|
||||
}
|
||||
|
||||
export function resolveDeepSeekInstallation(appDirectory = process.cwd(), requestedRoot = undefined) {
|
||||
if (requestedRoot !== undefined && (typeof requestedRoot !== 'string' || !requestedRoot.trim() || !path.isAbsolute(requestedRoot))) {
|
||||
throw engineError('请输入DeepSeek Harness安装的绝对目录。', 400);
|
||||
}
|
||||
const supplied = requestedRoot?.trim(), candidate = supplied ?? candidates(appDirectory).find(root => fs.existsSync(path.join(root, 'apps/cli/package.json')));
|
||||
const base = { engineId: 'deepseek-harness', name: 'DeepSeek Harness', profile: DEEPSEEK_PROFILE,
|
||||
expectedVersion: DEEPSEEK_VERSION, root: candidate ? path.resolve(candidate) : null,
|
||||
capabilities: { connectionProbe: true, projectExecution: false, prompt: false, singleSessionCancel: false,
|
||||
protocolVersionNegotiation: false, cancellationUnit: 'owned-process', tokenStreaming: false }, limitations: ENGINE_LIMITS };
|
||||
if (!candidate) return { ...base, status: 'unavailable', message: '请填写已经安装的DeepSeek Harness源码目录,再检测本地引擎。' };
|
||||
try {
|
||||
const root = fs.realpathSync.native(candidate), cli = JSON.parse(fs.readFileSync(path.join(root, 'apps/cli/package.json'), 'utf8'));
|
||||
if (cli.name !== '@deepseek-ai/dsh' || cli.version !== DEEPSEEK_VERSION) return { ...base, root, status: 'unsupported',
|
||||
version: typeof cli.version === 'string' ? cli.version : null, message: '当前连接契约支持DeepSeek Harness ' + DEEPSEEK_VERSION + '。' };
|
||||
for (const relative of ['packages/bundle/sdk-minimal/package.json', 'packages/sdk/server/package.json', 'packages/sdk/protocol/package.json', 'packages/sdk/client/package.json']) {
|
||||
const metadata = JSON.parse(fs.readFileSync(path.join(root, relative), 'utf8'));
|
||||
if (metadata.version !== cli.version) return { ...base, root, status: 'unsupported', version: cli.version, message: 'CLI、SDK与profile版本不一致,请核对本地安装。' };
|
||||
}
|
||||
const require = createRequire(path.join(root, 'apps/cli/package.json'));
|
||||
const cordis = require.resolve('@deepseek-ai/cordis');
|
||||
const filenames = [...criticalFiles.map(relative => path.join(root, relative)), cordis];
|
||||
const inputs = filenames.map(filename => {
|
||||
const file = engineFileIdentity(filename);
|
||||
if (!file.path.startsWith(root + path.sep)) throw engineError('引擎关键输入不属于这个安装目录。');
|
||||
return { ...file, relative: path.relative(root, file.path).replaceAll('\\', '/') };
|
||||
});
|
||||
const node = { ...engineFileIdentity(process.execPath, 256 * 1024 * 1024), version: process.versions.node };
|
||||
if (!/^24\./.test(node.version)) return { ...base, root, status: 'unsupported', version: cli.version, message: '当前连接契约使用Node.js 24。' };
|
||||
const identitySha256 = engineDigest({ root, version: cli.version, profile: DEEPSEEK_PROFILE, inputs, node });
|
||||
return { ...base, root, status: 'available', version: cli.version, entry: path.join(root, 'apps/cli/lib/bin.js'), inputs, node,
|
||||
identitySha256, serverInfo: { name: 'deepseek-harness-sdk-runtime', version: '0.0.1' },
|
||||
message: '已找到匹配版本,可验证原程序的连接与停止。' };
|
||||
} catch (error) {
|
||||
return { ...base, status: 'unavailable', message: '本地引擎关键输入不完整或无法核对:' + error.message };
|
||||
}
|
||||
}
|
||||
|
||||
export function assertDeepSeekInstallation(installation) {
|
||||
if (installation.status !== 'available' || !installation.identitySha256) throw engineError(installation.message || '本地引擎尚未就绪。');
|
||||
const current = resolveDeepSeekInstallation(process.cwd(), installation.root);
|
||||
if (current.status !== 'available' || current.identitySha256 !== installation.identitySha256) throw engineError('引擎入口、SDK、profile或运行器已变化,请重新检测并由用户发起新检查。', 409, 'ENGINE_INPUT_CHANGED');
|
||||
return current;
|
||||
}
|
||||
@@ -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 });
|
||||
|
||||
Reference in New Issue
Block a user