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 { assertMcpResolved } from './tools/mcp-contract.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 = {}) { assertMcpResolved(this.store, session.projectId); 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))); } }