147 lines
11 KiB
JavaScript
147 lines
11 KiB
JavaScript
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;
|
|
}
|
|
}
|