feat: integrate pinned original Purge with host execution gates

This commit is contained in:
Agent Workbench Dev
2026-11-02 22:32:31 +08:00
parent 1408e7ac76
commit 9106655d46
26 changed files with 3217 additions and 38 deletions
+1 -1
View File
@@ -51,7 +51,7 @@ export function EngineRunPanel({ session, onSession, onError, onNavigate }: {
{job.error && <p className="engine-run-error">{job.error}</p>}
{job.status === 'completed' && <p className="engine-run-note">原引擎运行与调用账本已核验。工程完成仍以提案应用、当前检查和父工程交付为准。</p>}
{job.requiresVerification && <p className="engine-run-note">请返回父目标核对原输入与现场。原未知结果保留,继续会创建新的运行。</p>}
{job.installation.strategy && <div className="engine-prompt-note"><strong>Purge 提示实验 · {job.installation.strategy.source.version}</strong><p>本 Run 使用已封存工程提示,原审批与预算继续生效。</p><details><summary>查看本次实验策略</summary><dl><dt>策略 SHA256</dt><dd>{job.installation.strategy.sha256}</dd><dt>来源 SHA256</dt><dd>{job.installation.strategy.source.sourceSha256}</dd><dt>文本 SHA256</dt><dd>{job.installation.strategy.promptSha256}</dd><dt>来源目录</dt><dd>{job.installation.strategy.source.root}</dd></dl><pre>{job.installation.strategy.prompt}</pre></details></div>}
{job.installation.strategy && <div className="engine-prompt-note"><strong>Purge {job.installation.strategy.kind==='purge-original-restricted-v1'?'原版受限模式':'提示实验'} · {job.installation.strategy.source.version}</strong><p>{job.installation.strategy.kind==='purge-original-restricted-v1'?'本 Run 加载固定原版入口,自动重试和继续关闭;工作台审批与预算继续生效。':'本 Run 使用已封存工程提示,原审批与预算继续生效。'}</p><details><summary>查看本次实验策略</summary><dl><dt>策略 SHA256</dt><dd>{job.installation.strategy.sha256}</dd><dt>来源 SHA256</dt><dd>{job.installation.strategy.source.sourceSha256}</dd><dt>文本 SHA256</dt><dd>{job.installation.strategy.promptSha256}</dd><dt>来源目录</dt><dd>{job.installation.strategy.source.root}</dd>{job.installation.strategy.kind==='purge-original-restricted-v1'&&<><dt>固定运行依赖 SHA256</dt><dd>{job.installation.strategy.runtime.sha256}</dd><dt>加载范围</dt><dd>{job.installation.strategy.runtime.inputs.length} 份固定输入 / {job.installation.strategy.runtime.nativeAddons.length} 个固定原生模块</dd></>}</dl><pre>{job.installation.strategy.prompt}</pre></details></div>}
{job.review && <p className="engine-run-note">人工核对记录:<code>{job.review.evidenceSha256.slice(0, 16)}</code>。原未知输出未改写为完成。</p>}
<div className="engine-run-actions"><button className="button secondary" disabled={pending} onClick={() => void read(job, 'input')}><FileText size={14} />查看原输入</button><button className="button secondary" disabled={pending || !job.reportArtifactId} onClick={() => void read(job, 'report')}><Fingerprint size={14} />查看原报告</button><button className="text-button" disabled={!job.reportArtifactId} onClick={() => void download(job)}><Download size={14} />下载完整报告</button></div>
<details><summary>任务身份与来源</summary><dl><dt>Task</dt><dd>{job.taskId}</dd><dt>Run</dt><dd>{job.runId}</dd><dt>SDK 会话</dt><dd>{job.sdkSessionId}</dd><dt>安装目录</dt><dd>{job.installation.root}</dd><dt>输入 SHA256</dt><dd>{job.inputSha256}</dd><dt>报告 SHA256</dt><dd>{job.reportSha256 ?? '尚未封存'}</dd><dt>原事件</dt><dd>{job.nativeSummary.notifications} 项</dd></dl></details>
+2
View File
@@ -14,6 +14,8 @@
.purge-strategy-fields details { font-size:12px; color:#587087; min-width:0; }
.purge-strategy-fields summary { cursor:pointer; }
.purge-strategy-fields dl > div { margin-top:8px; }
.purge-strategy-fields .purge-source-inputs { max-height:260px; overflow:auto; padding-right:8px; }
.purge-strategy-fields select { width:100%; min-height:42px; min-width:0; border:1px solid #b8c7d5; border-radius:4px; background:white; color:#243d54; padding:8px; }
.purge-strategy-fields dd { margin:4px 0 0; }
.purge-strategy-control .purge-source-error { color:#794d21; background:#fff8ee; padding:10px; border-left:3px solid #925619; overflow-wrap:anywhere; }
.engine-run-panel .engine-prompt-note { padding:12px; background:#f5f6fa; border-left:3px solid #626594; font-size:12px; line-height:1.7; }
+20 -9
View File
@@ -4,38 +4,49 @@ import { api } from './api';
import type { PurgeSourceAvailability } from './types';
import './PurgeStrategyControl.css';
export type PurgeDraft = { enabled: boolean; root: string; prompt: string; source: PurgeSourceAvailability | null };
export const emptyPurgeDraft = (): PurgeDraft => ({ enabled: false, root: '', prompt: '', source: null });
export type PurgeDraft = { enabled: boolean; kind: 'purge-prompt-experiment' | 'purge-original-restricted-v1'; root: string; prompt: string; source: PurgeSourceAvailability | null };
export const emptyPurgeDraft = (): PurgeDraft => ({ enabled: false, kind: 'purge-prompt-experiment', root: '', prompt: '', source: null });
export const purgeStrategyInput = (value: PurgeDraft) => ({kind:value.kind,root:value.source?.root,sourceSha256:value.source?.sourceSha256,prompt:value.prompt,
...(value.kind==='purge-original-restricted-v1'?{runtimeSha256:value.source?.runtimeSha256}:{})});
export function purgeDraftReady(value: PurgeDraft) {
return !value.enabled || value.source?.status === 'available' && !!value.source.sourceSha256
&& (value.source.kind??'purge-prompt-experiment')===value.kind && (value.kind!=='purge-original-restricted-v1'||!!value.source.runtimeSha256)
&& !!value.prompt.trim() && new TextEncoder().encode(value.prompt).length <= 24000;
}
export function PurgeStrategyControl({ value, onChange, busy }: { value: PurgeDraft; onChange: (value: PurgeDraft) => void; busy: boolean }) {
export function PurgeStrategyControl({ value, onChange, busy, harnessRoot }: { value: PurgeDraft; onChange: (value: PurgeDraft) => void; busy: boolean; harnessRoot?: string | null }) {
const [detecting, setDetecting] = useState(false), [error, setError] = useState('');
const request = useRef(0), current = useRef(value); current.current = value;
const previousHarness = useRef(harnessRoot);
useEffect(() => { if(previousHarness.current===harnessRoot)return;previousHarness.current=harnessRoot;request.current++;setDetecting(false);setError('');
if(current.current.kind==='purge-original-restricted-v1')onChange({...current.current,source:null}); }, [harnessRoot, onChange]);
useEffect(() => () => { request.current++; }, []);
function enabled(next: boolean) { request.current++; setDetecting(false); setError(''); onChange({ ...value, enabled: next }); }
function editRoot(root: string) { request.current++; setDetecting(false); setError(''); onChange({ ...value, root, source: null }); }
async function detect() {
const generation = ++request.current; setDetecting(true); setError(''); onChange({ ...current.current, source: null });
try {
const source = await api<PurgeSourceAvailability>('/engines/purge/source' + (value.root.trim() ? '?root=' + encodeURIComponent(value.root.trim()) : ''));
const query=new URLSearchParams({kind:value.kind});if(value.root.trim())query.set('root',value.root.trim());if(value.kind==='purge-original-restricted-v1'&&harnessRoot)query.set('harnessRoot',harnessRoot);
const source = await api<PurgeSourceAvailability>('/engines/purge/source?'+query);
if (generation !== request.current) return;
onChange({ ...current.current, root: source.root ?? current.current.root, source, prompt: current.current.prompt || source.defaultPrompt });
} catch (failure) { if (generation === request.current) setError(failure instanceof Error ? failure.message : String(failure)); }
finally { if (generation === request.current) setDetecting(false); }
}
return <section className="purge-strategy-control" aria-label="Purge 提示实验">
<header><FlaskConical size={17} /><label><input type="checkbox" checked={value.enabled} disabled={busy} onChange={event => enabled(event.target.checked)} />启用 Purge 提示实验</label><span>{value.enabled ? '仅对本计划生效' : '默认关闭'}</span></header>
<p>追加已封存的工程提示,继续使用原任务范围、检查审批和累计预算。实际收益需同题对照验证。</p>
const original=value.kind==='purge-original-restricted-v1';
return <section className="purge-strategy-control" aria-label={original?'Purge 原版受限模式':'Purge 提示实验'}>
<header><FlaskConical size={17} /><label><input type="checkbox" checked={value.enabled} disabled={busy} onChange={event => enabled(event.target.checked)} />启用 Purge {original?'原版受限模式':'提示实验'}</label><span>{value.enabled ? '仅对本计划生效' : '默认关闭'}</span></header>
<p>{original?'运行原版 1.1.78 的固定受限配置,继续使用工作台的工具审批和累计预算。原版效果需另行实测。':'追加已封存的工程提示,继续使用原任务范围、检查审批和累计预算。实际收益需同题对照验证。'}</p>
{value.enabled && <div className="purge-strategy-fields">
<label>执行模式<select aria-label="Purge 执行模式" value={value.kind} disabled={busy} onChange={event=>{request.current++;setDetecting(false);setError('');onChange({...value,kind:event.target.value as PurgeDraft['kind'],source:null});}}>
<option value="purge-prompt-experiment">独立工程提示 · 不加载原版插件</option><option value="purge-original-restricted-v1">原版 1.1.78 · 固定受限配置</option>
</select></label>
<label>Purge 源码目录<input aria-label="Purge 源码目录" value={value.root} placeholder="留空检测已知来源,或填写绝对目录" disabled={busy} onChange={event => editRoot(event.target.value)} /></label>
<button type="button" className="button secondary" disabled={busy || detecting} onClick={() => void detect()}>{detecting ? <LoaderCircle className="spin" size={14} /> : <ShieldCheck size={14} />}检测 Purge 来源</button>
{value.source && <div className="purge-source-state" role="status"><strong>{value.source.status === 'available' ? '已核对 Purge ' + value.source.version : '来源尚不可用'}</strong><p>{value.source.message}</p>{value.source.sourceSha256 && <code>{value.source.sourceSha256}</code>}</div>}
{value.source && <div className="purge-source-state" role="status"><strong>{value.source.status === 'available' ? '已核对 Purge ' + value.source.version : '来源尚不可用'}</strong><p>{value.source.message}</p>{value.source.sourceSha256 && <code>{value.source.sourceSha256}</code>}{original&&value.source.runtimeSha256&&<p>固定运行依赖 {value.source.runtimeInputs} 份 · <code>{value.source.runtimeSha256}</code></p>}</div>}
{error && <p className="purge-source-error" role="alert">{error}</p>}
<label>增强工程提示<textarea aria-label="增强工程提示" rows={5} maxLength={8000} value={value.prompt} disabled={busy} onChange={event => onChange({ ...value, prompt: event.target.value })} /></label>
<small>{new TextEncoder().encode(value.prompt).length.toLocaleString()} / 24,000 字节 · 完整文本随计划保存,运行期间不能替换。</small>
<details><summary>实验来源与执行范围</summary><p>独立提示装配参考 YuJunZhiXue / dsh-purge(Apache-2.0)。不加载上游完整插件;实验不开启宿主修改、权限绕过或自动重试。</p>{value.source?.inputs && <dl>{value.source.inputs.map(input => <div key={input.relative}><dt>{input.relative}</dt><dd>{input.sha256}</dd></div>)}</dl>}</details>
<details><summary>实验来源与执行范围</summary><p>{original?'YuJunZhiXue / dsh-purge(Apache-2.0)原版入口,完整来源和运行副本逐份核对。自动更新、宿主修改、原版工具、自动重试和继续关闭;内部提示及钩子仍由原版装配。这是固定可信源码的 Windows x64 配置,Node 权限不等同于操作系统沙箱。':'独立提示装配参考 YuJunZhiXue / dsh-purge(Apache-2.0)。不加载上游完整插件;实验不开启宿主修改、权限绕过或自动重试。'}</p>{value.source?.inputs && <dl className="purge-source-inputs">{value.source.inputs.map(input => <div key={input.relative}><dt>{input.relative}</dt><dd>{input.sha256}</dd></div>)}</dl>}</details>
</div>}
</section>;
}
+4 -4
View File
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import { ArrowUpRight, Check, GitBranch, LoaderCircle, Play, RefreshCw, ShieldCheck, Square } from 'lucide-react';
import { api, downloadBlob } from './api';
import { Modal } from './components';
import { PurgeStrategyControl, emptyPurgeDraft, purgeDraftReady } from './PurgeStrategyControl';
import { PurgeStrategyControl, emptyPurgeDraft, purgeDraftReady, purgeStrategyInput } from './PurgeStrategyControl';
import type { CollaborationGroup, Config, Session, WorkerView, ControlledEngineAvailability } from './types';
import './WorkerPanel.css';
@@ -59,7 +59,7 @@ export function WorkerPanel({ session, config, busy, onSession, onNavigate, onRe
const result = await api<{ group: CollaborationGroup; session: Session }>('/sessions/' + session.id + '/collaborations', {
goal, children: (engineMode === 'deepseek' ? drafts.slice(0, 1) : drafts).map(child => ({ label: child.label, goal: child.goal, paths: splitPaths(child.paths) })),
...(engineMode === 'deepseek' ? { engine: { id: 'deepseek-harness', root: engineInstallation?.root, controlledSha256: engineInstallation?.controlledSha256,
...(purge.enabled ? { strategy: { kind: 'purge-prompt-experiment', root: purge.source?.root, sourceSha256: purge.source?.sourceSha256, prompt: purge.prompt } } : {}) } } : {}),
...(purge.enabled ? { strategy: purgeStrategyInput(purge) } : {}) } } : {}),
budget: { maxTokens: tokens, maxSteps: steps, maxToolCalls: toolCalls, maxDurationMs: duration * 60000 },
});
if (generation !== scope.current) return;
@@ -95,7 +95,7 @@ export function WorkerPanel({ session, config, busy, onSession, onNavigate, onRe
{(!group || creating) && <div className="worker-plan-form">
<label>执行方式<select aria-label="执行方式" value={engineMode} onChange={event => setEngineMode(event.target.value as 'workbench' | 'deepseek')}><option value="workbench">工作台 · 两个受限子任务</option><option value="deepseek">DeepSeek Harness · 一个受控工程</option></select></label>
{engineMode === 'deepseek' && <section className="worker-engine-install" aria-label="受控引擎安装"><label>Harness 安装目录<input value={engineRoot} placeholder="留空检测已知本地安装" onChange={event => { detection.current++; setEngineRoot(event.target.value); setEngineInstallation(null); setDetectingEngine(false); }} /></label><button className="button secondary" disabled={detectingEngine || !!action} onClick={() => void detectEngine()}>{detectingEngine ? <LoaderCircle size={14} className="spin" /> : <ShieldCheck size={14} />}检测受控安装</button>{engineInstallation && <div role="status"><strong>{engineReady ? '受控安装可用' : '安装尚不可用'}</strong><p>{engineInstallation.message}</p>{engineReady && <code>Harness {engineInstallation.version} · {engineInstallation.controlledSha256?.slice(0, 16)}</code>}</div>}<p className="worker-note">模型连接由工作台使用;引擎只提交范围内的提案与检查请求,应用和检查仍需审查。</p></section>}
{engineMode === 'deepseek' && <PurgeStrategyControl value={purge} onChange={value => { setPurge(value); setError(''); }} busy={!!action} />}
{engineMode === 'deepseek' && <PurgeStrategyControl value={purge} onChange={value => { setPurge(value); setError(''); }} busy={!!action} harnessRoot={engineInstallation?.root} />}
<label>父目标<textarea value={goal} onChange={event => setGoal(event.target.value)} placeholder="描述需要交付的结果与验收要求" maxLength={20000} rows={3} /></label>
<div className={'worker-lanes' + (engineMode === 'deepseek' ? ' single' : '')}>{visibleDrafts.map((child, index) => <fieldset key={index}><legend>{engineMode === 'deepseek' ? '引擎工程' : '子任务 ' + (index + 1)}</legend><label>任务名称<input value={child.label} maxLength={64} onChange={event => setDrafts(values => values.map((value, i) => i === index ? { ...value, label: event.target.value } : value))} /></label><label>独立子目标<textarea value={child.goal} maxLength={8000} rows={3} onChange={event => setDrafts(values => values.map((value, i) => i === index ? { ...value, goal: event.target.value } : value))} /></label><label>允许修改的文件或目录<textarea value={child.paths} rows={2} placeholder="例如 src/parser.mjs,每行一个相对路径" onChange={event => setDrafts(values => values.map((value, i) => i === index ? { ...value, paths: event.target.value } : value))} /></label></fieldset>)}</div>
<div className="worker-budget-form"><label>总 token 预算<input type="number" min={1000} max={config.maxRunTokens} value={tokens} onChange={event => setTokens(Number(event.target.value))} /></label><label>总请求轮次<input type="number" min={2} max={200} value={steps} onChange={event => setSteps(Number(event.target.value))} /></label><label>总工具次数<input type="number" min={2} max={512} value={toolCalls} onChange={event => setToolCalls(Number(event.target.value))} /></label><label>总时限(分钟)<input type="number" min={1} max={Math.floor(config.maxRunDurationMs / 60000)} value={duration} onChange={event => setDuration(Number(event.target.value))} /></label></div>
@@ -103,7 +103,7 @@ export function WorkerPanel({ session, config, busy, onSession, onNavigate, onRe
<div className="worker-actions"><button className="button" disabled={!canPlan || !goal.trim() || visibleDrafts.some(child => !child.goal.trim() || !splitPaths(child.paths).length) || engineMode === 'deepseek' && (!engineReady || detectingEngine || !promptReady)} onClick={() => void create()}><ShieldCheck size={15} />封存分工计划</button>{creating && <button className="button secondary" onClick={() => setCreating(false)}>返回原协作</button>}</div>
</div>}
{group && !creating && <>
{group.children[0]?.engine?.strategy && <p className="worker-engine-badge">本计划的 Purge 提示实验 · {group.children[0].engine.strategy.source.version} · {group.children[0].engine.strategy.sha256.slice(0, 16)}</p>}
{group.children[0]?.engine?.strategy && <p className="worker-engine-badge">本计划的 Purge {group.children[0].engine.strategy.kind==='purge-original-restricted-v1'?'原版受限模式':'提示实验'} · {group.children[0].engine.strategy.source.version} · {group.children[0].engine.strategy.sha256.slice(0, 16)}</p>}
{group.evaluation && <p className="worker-note">本协作属于固定工程评测。执行与采纳请使用「工程评测」;这里保留原任务导航和中断现场核对。</p>}<section className="worker-parent"><div className="worker-parent-top"><span className={'worker-status ' + (group.requiresVerification || group.status === 'conflict' ? 'attention' : '')}>{statusLabel(group.status)}</span><code>{group.source.identity.branch} · {group.source.identity.head.slice(0, 12)}</code></div><h3>{group.goal}</h3><p>{group.summary}</p><dl><div><dt>模型</dt><dd>{group.model.mode === 'demo' ? '离线演示' : group.model.model}</dd></div><div><dt>执行方式</dt><dd>{group.children[0].engine ? "DeepSeek Harness " + group.children[0].engine.version : "工作台受限子任务"}</dd></div><div><dt>总预算</dt><dd>{number(group.budget.maxTokens)} tokens / {group.budget.maxSteps} 轮 / {group.budget.maxToolCalls} 次工具</dd></div><div><dt>累计用量</dt><dd>{number(group.usage?.accountedTokens)} tokens / {group.usage?.steps ?? 0} 轮 / {group.usage?.toolCalls ?? 0} 次工具 / {group.usage?.requests ?? 0} 次模型请求</dd></div><div><dt>原修改</dt><dd>{group.source.changedPaths.length ? group.source.changedPaths.map(value => value.path).join('、') : '无未提交修改'}</dd></div></dl></section>
<div className={"worker-lanes" + (group.children.length === 1 ? " single" : "")}>{(group.workers ?? []).map((child, index) => <section className="worker-lane" key={child.id}><div className="worker-lane-title"><span>通道 {index + 1}</span><span className={'worker-status ' + (child.requiresVerification ? 'attention' : '')}>{statusLabel(child.sessionStatus === 'awaiting_approval' ? 'awaiting_approval' : child.status)}</span></div><h3>{child.label}</h3>{child.engine && <p className="worker-engine-badge">DeepSeek Harness {child.engine.version} · 固定安装 {child.engine.controlledSha256?.slice(0, 12)}</p>}<p className="worker-goal">{child.goal}</p><div className="worker-scope"><span>允许修改</span>{child.paths.map(path => <code key={path}>{path}</code>)}</div><p className="worker-meter">{number(child.usage?.accountedTokens)} / {number(child.budget.maxTokens)} tokens · {child.usage?.steps ?? 0}/{child.budget.maxSteps} 轮</p><p className="worker-summary">{child.summary ?? '先创建独立工作区,再开始子任务。'}</p>{child.result && <div className="worker-proof"><Check size={14} />{child.result.paths.length} 个原改动 · 当前检查已封存</div>}<div className="worker-actions">{child.status !== 'unprepared' && <button className="button secondary" onClick={() => void onNavigate(child.projectId, child.sessionId, child.sessionStatus === "awaiting_approval" ? "approval" : child.sessionStatus === "needs_review" ? "changes" : "task")}>{child.sessionStatus === 'awaiting_approval' ? '查看并审批检查' : child.sessionStatus === 'needs_review' ? '审查子任务改动' : '打开子任务'}<ArrowUpRight size={13} /></button>}{!group.evaluation && ['ready', 'paused', 'failed', 'awaiting_review'].includes(child.status) && !running && child.sessionStatus !== 'needs_review' && <button className="text-button" disabled={!!action || config.mode === 'demo' || group.requiresVerification} onClick={() => setConfirmation({ group, operation: 'start', workerId: child.id })}><Play size={13} />继续子任务</button>}</div></section>)}</div>
<section className="worker-review"><div className="worker-review-title"><GitBranch size={18} /><h3>父工程成果审查</h3></div>{group.collection ? <><p>{group.collection.paths.length} 个路径已核对,原记录 <code>{group.collection.sha256.slice(0, 16)}</code></p>{group.collection.conflicts.length > 0 && <ul className="worker-conflicts">{group.collection.conflicts.map((conflict, i) => <li key={i}><code>{conflict.path}</code><span>{conflict.reason}</span></li>)}</ul>}<button className="text-button" disabled={!!action} onClick={() => void showRecord(group, 'collection')}>查看原成果记录</button></> : <p>等待 {group.children.length} 个子任务完成实际修改与检查。重叠路径、来源变化或原证据失效会阻止合并。</p>}{group.merge?.changeSetId && <button className="button secondary" onClick={onReview}>打开父工程变更集审查<ArrowUpRight size={14} /></button>}</section>
+8 -1
View File
@@ -303,18 +303,25 @@ export interface EngineJob {
export interface ControlledEngineAvailability extends EngineAvailability {
controlledStatus: string; controlledSha256?: string; scope: string; bridgeSha256?: string;
controlledCapabilities?: { text: boolean; nativeSessionResume: boolean; nativeModelCredentials: boolean; cancellationUnit: string };
strategy?: PurgePromptStrategy;
strategy?: PurgePromptStrategy | PurgeOriginalStrategy;
}
export interface PurgeSourceAvailability {
status: string; root: string | null; message: string; version?: string; sourceSha256?: string;
defaultEnabled: boolean; defaultPrompt: string; supportedVersions: string[];
inputs?: { relative: string; path: string; bytes: number; sha256: string }[];
kind?: 'purge-prompt-experiment' | 'purge-original-restricted-v1'; runtimeSha256?: string; runtimeInputs?: number;
}
export interface PurgePromptStrategy {
kind: 'purge-prompt-experiment'; enabled: true; sha256: string; prompt: string; promptSha256: string;
source: { root: string; version: string; sourceSha256: string };
section: { name: string; order: number; interpolate: false; text: string; textSha256: string };
}
export interface PurgeOriginalStrategy {
kind: 'purge-original-restricted-v1'; enabled: true; sha256: string; prompt: string; promptSha256: string;
source: { root: string; version: string; sourceSha256: string };
runtime: { root: string; sha256: string; inputs: { path: string; sha256: string }[]; nativeAddons: { path: string; sha256: string }[] };
originalConfig: { autoRetry: false; autoContinue: false; hooksDenyBypass: false; postPrompt: string };
}
export interface EngineRunView {
id: string; projectId: string; sessionId: string; taskId: string; runId: string; workerId: string; collaborationId: string;
installation: ControlledEngineAvailability; sdkSessionId: string; status: string; requiresVerification: boolean; verified: boolean;
+13 -5
View File
@@ -9,7 +9,8 @@ import { isId } from '../../shared/contracts/execution.mjs';
import { readOwnedProcessTree } from '../owned-process-tree.mjs';
import { CONTROLLED_BRIDGE_PLUGIN } from './controlled-plugin.mjs';
import { assertControlledInstallation, controlledDigest, controlledPatch, controlledToolCatalogue, CONTROLLED_ENGINE_SCOPE } from './controlled-installation.mjs';
import { assertPurgeStrategy } from './purge-strategy.mjs';
import { assertPurgeStrategy, PURGE_PROMPT_KIND, ORIGINAL_PURGE_KIND } from './purge-strategy.mjs';
import { OriginalPurgeRuntime } from './original-purge-runtime.mjs';
const allowedEnvironment = /^(path|pathext|systemroot|systemdrive|windir|comspec|temp|tmp|userprofile|appdata|localappdata|programfiles(?:\(x86\))?|homedrive|homepath)$/i;
const at = () => new Date().toISOString();
@@ -51,7 +52,7 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
const pluginConfig = { owner: this.owner, sdkSessionId, tools: catalogue, catalogueSha256, nonce, marker,
llmModule: this.installation.llmModule, endpoint: 'http://127.0.0.1:' + this.guard.address().port,
maximumFrameBytes: this.maximumFrameBytes, model: config.model, maxOutputTokens: config.maxOutputTokens, contextLimit: config.contextLimit,
...(strategy ? { promptExperiment: { sha256: strategy.sha256, section: strategy.section } } : {}) };
...(strategy?.kind===PURGE_PROMPT_KIND ? { promptExperiment: { sha256: strategy.sha256, section: strategy.section } } : {}) };
fs.writeFileSync(plugin, CONTROLLED_BRIDGE_PLUGIN, { flag: 'wx' }); fs.writeFileSync(patch, JSON.stringify(controlledPatch(plugin, pluginConfig)), { flag: 'wx' });
this.report.launchInputs = { plugin: engineFileIdentity(plugin), patch: engineFileIdentity(patch), cwd: fs.realpathSync.native(cwd),
disabledPlugins: this.installation.disabledPlugins, catalogue, catalogueSha256 };
@@ -59,8 +60,12 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
for (const name of Object.keys(process.env)) if (allowedEnvironment.test(name)) env[name] = process.env[name];
Object.assign(env, { DSH_HOME: home, DSH_AGENTS_HOME: agents, DSH_TELEMETRY_DISABLED: 'true' });
signal?.throwIfAborted(); assertControlledInstallation(this.installation);
this.client = this.clientFactory({ executable: this.installation.node.path,
args: [this.installation.entry, '--profile', this.installation.profile, '--patch', patch], cwd, env },
let launch={executable:this.installation.node.path,args:[this.installation.entry,'--profile',this.installation.profile,'--patch',patch],cwd,env};
if(strategy?.kind===ORIGINAL_PURGE_KIND){
this.originalPurge=new OriginalPurgeRuntime(strategy,directory);this.report.originalPurge=this.originalPurge.report;
launch=await this.originalPurge.prepare(launch,this.installation);this.report.launchInputs.patch=engineFileIdentity(patch);
}
this.client = this.clientFactory(launch,
{ timeoutMs: this.timeoutMs, maximumFrameBytes: this.maximumFrameBytes, cancellationMethod: null });
this.report.process = { pid: this.client.pid, connectionId: this.client.id, startedAt: this.client.startedAt, ownership: 'one-process-per-engine-run' };
onState('starting', this.report.process);
@@ -95,7 +100,8 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
if (controlledDigest(ready.owner) !== controlledDigest(this.owner) || ready.sdkSessionId !== sdkSessionId
|| ready.catalogueSha256 !== catalogueSha256 || controlledDigest(ready.catalogue) !== catalogueSha256
|| JSON.stringify(ready.providers) !== JSON.stringify(['agent-workbench'])
|| (ready.promptExperimentSha256 ?? null) !== (strategy?.sha256 ?? null)) throw engineError('启动后工具、模型、实验提示或Run目录不符合封存契约。');
|| (ready.promptExperimentSha256 ?? null) !== (strategy?.kind===PURGE_PROMPT_KIND?strategy.sha256:null)) throw engineError('启动后工具、模型、实验提示或Run目录不符合封存契约。');
this.originalPurge?.verify({ready:true,pid:this.client.pid});
this.verifyLaunch(); onState('initializing', { readiness: ready });
const initialized = await this.request('initialize', { cwd, provider: 'agent-workbench', model: config.model, maxTokens: config.maxOutputTokens });
if (controlledDigest(initialized.serverInfo) !== controlledDigest(this.installation.serverInfo)) throw engineError('受控SDK返回身份不符合固定发行。');
@@ -109,6 +115,7 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
for (const input of [this.report.launchInputs.plugin, this.report.launchInputs.patch]) {
if (engineFileIdentity(input.path).sha256 !== input.sha256) throw engineError('所属叠加插件或启动输入发生变化。');
}
this.originalPurge?.verify();
}
async captureTree(publish = true) {
const info = this.report.process, tree = await this.processTreeReader(info);
@@ -211,6 +218,7 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
}
if (this.guard) { this.guard.closeAllConnections(); await new Promise(resolve => this.guard.close(resolve)); }
await Promise.allSettled([...this.pending]);
if(this.originalPurge){try{this.originalPurge.verify();}catch(error){failure??=error;}finally{await this.originalPurge.close();}}
if (!interrupted && this.report.launchInputs) { try { this.verifyLaunch(); } catch (error) { failure ??= error; } }
if (!interrupted && this.report.cleanup?.exit?.code !== 0) failure ??= engineError('所属引擎未正常退出。');
this.report.finishedAt = at(); this.report.status = this.client && (!this.report.cleanup?.rootExited || !this.report.cleanup?.treeConfirmed)
+1 -1
View File
@@ -32,7 +32,7 @@ export class EngineRunner {
if (installation.controlledStatus !== 'available' || installation.controlledSha256 !== input.controlledSha256) {
throw engineError('受控引擎与刚才检测的程序/插件身份不一致,请重新检测后制定新计划。');
}
return { ...installation, ...(input.strategy === undefined ? {} : { strategy: selectPurgeStrategy(input.strategy, this.appDirectory) }) };
return { ...installation, ...(input.strategy === undefined ? {} : { strategy: selectPurgeStrategy(input.strategy, this.appDirectory, installation) }) };
}
assertCurrent(session, run) {
const driver = this.drivers.get(run.id);
File diff suppressed because it is too large Load Diff
+205
View File
@@ -0,0 +1,205 @@
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import {createHash,randomUUID,timingSafeEqual} from 'node:crypto';
import {pathToFileURL} from 'node:url';
import {engineCanonicalDigest as digest,engineError} from '../../shared/contracts/engines.mjs';
import {engineFileIdentity} from './deepseek-installation.mjs';
import {assertOriginalPurgeStrategy} from './original-purge-source.mjs';
const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
const equal=(left,right)=>typeof left==='string'&&Buffer.byteLength(left)===Buffer.byteLength(right)&&timingSafeEqual(Buffer.from(left),Buffer.from(right));
export function originalPurgeReadRoots(directories,metadata=[]){
const inside=(base,file)=>{const relative=path.relative(base,file);return relative===''||relative!=='..'&&!relative.startsWith('..'+path.sep)&&!path.isAbsolute(relative);};
const roots=[...new Set(directories.map(root=>fs.realpathSync.native(root)))];
// Node 24's Windows permission trie can deny an allowed ancestor when both
// it and a descendant are supplied. Keep only the encompassing read grant.
const minimal=roots.filter(root=>!roots.some(other=>other!==root&&inside(other,root)));
return [...minimal,...new Set(metadata.filter(file=>!minimal.some(root=>inside(root,file))))];
}
export const ORIGINAL_PURGE_WRAPPER=String.raw`import fs from 'node:fs';
export const name='workbench-original-purge-restricted';
export const inject=['systemPrompt','tools','appReady'];
export async function apply(ctx,config){
const blockedTools=[];
const tools=new Proxy(ctx.tools,{get(target,key){if(key==='register')return definition=>{
if(!['purge_status','purge_apply','purge_revert'].includes(definition.name))throw new Error('Unexpected original tool registration.');
blockedTools.push(definition.name);return ()=>{};
};const value=Reflect.get(target,key,target);return typeof value==='function'?value.bind(target):value;}});
const facade=new Proxy(ctx,{get(target,key){if(key==='tools')return tools;if(key==='get')return name=>name==='tools'?tools:target.get(name);
const value=Reflect.get(target,key,target);return typeof value==='function'?value.bind(target):value;}});
const original=await import(config.entry);await original.apply(facade,config.originalConfig);
fs.writeFileSync(config.marker,JSON.stringify({schemaVersion:1,pid:process.pid,strategySha256:config.strategySha256,
originalEntryLoaded:true,originalApplyCalled:true,blockedTools,originalConfig:config.originalConfig,upstreamPatchInstalled:false}),{flag:'wx'});
}
`;
// The only executable inputs allowed after this preload are the frozen original
// files, pinned Harness JS/JSON and the two generated, hashed host adapters.
// Node permissions are defense in depth for this trusted-source profile, not an
// OS sandbox. Native builtins belong to the pinned Node executable. Only the
// fixed require-builtin addon may use dlopen; it is recorded separately.
export const ORIGINAL_PURGE_PRELOAD=String.raw`import fs from 'node:fs';
import path from 'node:path';
import {fileURLToPath,pathToFileURL} from 'node:url';
import {registerHooks,syncBuiltinESMExports,createRequire} from 'node:module';
import {createHash} from 'node:crypto';
const policy=JSON.parse(fs.readFileSync(process.env.AWB_ORIGINAL_PURGE_POLICY,'utf8'));
const originalRead=fs.readFileSync.bind(fs),inputs=new Map(policy.inputs.map(input=>[input.path,input])),seen=new Set();
const hash=bytes=>createHash('sha256').update(bytes).digest('hex');
const fileInput=url=>{if(!url.startsWith('file:'))throw new Error('Unsealed module protocol.');
let file;try{file=fs.realpathSync.native(fileURLToPath(url));}catch(error){process.stderr.write('AWB_MODULE_LOOKUP_REFUSED '+url+'\n'+error.stack+'\n');throw error;}const input=inputs.get(file);
if(!input||hash(originalRead(file))!==input.sha256){process.stderr.write('AWB_MODULE_REFUSED '+file+'\n');throw new Error('Unsealed or changed module: '+file);}return input;};
const originalDlopen=process.dlopen;
process.dlopen=function(module,file,...args){const input=fileInput(pathToFileURL(String(file)).href);
if(!policy.nativeAddons.some(native=>native.path===input.path&&native.sha256===input.sha256))throw Object.assign(new Error('Unsealed native addon.'),{code:'ERR_ACCESS_DENIED'});
const result=originalDlopen.call(this,module,file,...args);
fs.appendFileSync(policy.nativeModules,JSON.stringify({...input,operation:'actual-process-dlopen'})+'\n');return result;};
registerHooks({resolve(specifier,context,next){
if(context.parentURL?.startsWith(policy.originalUrl)&&specifier==='@deepseek-ai/dsh-llm')return {url:policy.llmModule,shortCircuit:true};
const result=next(specifier,context);if(!result.url.startsWith('node:'))fileInput(result.url);return result;
},load(url,context,next){
if(url.startsWith('node:'))return next(url,context);
const input=fileInput(url),result=next(url,context),source=result.source==null?null:Buffer.from(result.source);
if(source&&hash(source)!==input.sha256)throw new Error('Loaded source differs from sealed bytes.');
if(!seen.has(input.path)){
if(seen.size>=1024)throw new Error('Loaded module count exceeded.');seen.add(input.path);
fs.appendFileSync(policy.modules,JSON.stringify({...input,format:result.format??null,sourceSha256:source?hash(source):null})+'\n');
}return result;
}});
const koffiModule=createRequire(import.meta.url)(policy.koffiEntry),koffi=koffiModule.default??koffiModule,originalLibraryLoad=koffi.load.bind(koffi);
koffi.load=function(name,...args){const library=policy.platformLibraries.find(input=>name.toLowerCase()===input.name||name===input.path);
if(!library||hash(originalRead(library.path))!==library.sha256)throw new Error('Unsealed native library.');
const result=originalLibraryLoad(library.path,...args);
fs.appendFileSync(policy.nativeLibraries,JSON.stringify({...library,operation:'actual-koffi-load'})+'\n');return result;};
const delegatedStat=(file,options)=>{if(options?.bigint)return null;const item=policy.directoryMetadata[path.resolve(String(file))];
if(!item)return null;const value=Object.assign(Object.create(fs.Stats.prototype),item);
for(const key of ['atime','mtime','ctime','birthtime'])value[key]=new Date(value[key]);return value;};
let deniedCount=0;const logDenied=(name,file,error)=>{if(error?.code==='ERR_ACCESS_DENIED'&&deniedCount++<24)process.stderr.write('AWB_ACCESS_REFUSED '+name+' '+String(file)+' resource='+String(error.resource)+'\n'+error.stack+'\n');};
for(const name of ['statSync','lstatSync','readFileSync','realpathSync','readdirSync','accessSync']){const original=fs[name];
const wrapped=function(file,...args){try{return original.call(this,file,...args);}catch(error){logDenied(name,file,error);throw error;}};
Object.assign(wrapped,original);fs[name]=wrapped;}
for(const name of ['readFile','stat','lstat','realpath','readdir','access','open']){const original=fs[name];
const wrap=fn=>function(file,...args){const callback=args.at(-1);if(typeof callback==='function')args[args.length-1]=function(error,...values){logDenied(name,file,error);return callback.call(this,error,...values);};
try{return fn.call(this,file,...args);}catch(error){logDenied(name,file,error);throw error;}};
const wrapped=wrap(original);Object.assign(wrapped,original);if(original.native)wrapped.native=wrap(original.native);fs[name]=wrapped;}
const stat=fs.promises.stat;fs.promises.stat=async function(file,options){try{return await stat.call(this,file,options);}catch(error){
const value=error.code==='ERR_ACCESS_DENIED'&&delegatedStat(file,options);if(value)return value;logDenied('promises.stat',file,error);throw error;}};
for(const name of ['lstat','readFile','realpath','readdir','access','mkdir','opendir']){const original=fs.promises[name];fs.promises[name]=async function(file,...args){
try{return await original.call(this,file,...args);}catch(error){logDenied('promises.'+name,file,error);throw error;}};}
const open=fs.promises.open;fs.promises.open=async function(file,...args){let handle;try{handle=await open.call(this,file,...args);}catch(error){logDenied('promises.open',file,error);throw error;}const sync=handle.sync.bind(handle);
handle.sync=async()=>{try{return await sync();}catch(error){if(error.code!=='ERR_ACCESS_DENIED')throw error;
const stat=await handle.stat({bigint:true}),response=await fetch(policy.durabilityEndpoint,{method:'POST',signal:AbortSignal.timeout(10000),
headers:{'Content-Type':'application/json',Authorization:'Bearer '+process.env.AWB_ORIGINAL_PURGE_DURABILITY_NONCE},
body:JSON.stringify({path:String(file),dev:String(stat.dev),ino:String(stat.ino),size:String(stat.size)})});
if(!response.ok)throw new Error('Owned durability synchronization refused.');await response.json();
}};return handle;};
syncBuiltinESMExports();
`;
export class OriginalPurgeRuntime {
constructor(strategy,directory){
assertOriginalPurgeStrategy(strategy);this.strategy=strategy;this.directory=fs.realpathSync.native(directory);this.inputs=[];
this.report={schemaVersion:1,kind:strategy.kind,strategySha256:strategy.sha256,runtimeSha256:strategy.runtime.sha256,
isolation:strategy.isolation,originalConfig:strategy.originalConfig,upstreamPatchInstalled:false,
durabilityReceipts:[],durabilityRejections:[],loadedModules:[],nativeLoads:[],nativeLibraries:[],readiness:null};
}
async prepare(launch,installation){
const directory=this.directory,source=path.join(directory,'original-purge');fs.mkdirSync(source);
for(const input of this.strategy.source.inputs){
const raw=fs.readFileSync(input.path);if(sha(raw)!==input.sha256)throw engineError('复制前原版输入已变化。');
const target=path.join(source,input.relative);fs.mkdirSync(path.dirname(target),{recursive:true});fs.writeFileSync(target,raw,{flag:'wx'});
this.inputs.push({...engineFileIdentity(target),relative:input.relative});
}
this.marker=path.join(directory,'original-purge-ready.json');this.modules=path.join(directory,'original-purge-modules.jsonl');this.nativeModules=path.join(directory,'original-purge-native-modules.jsonl');
this.nativeLibraries=path.join(directory,'original-purge-native-libraries.jsonl');
const wrapper=path.join(directory,'original-purge-wrapper.mjs'),preload=path.join(directory,'original-purge-preload.mjs'),policyFile=path.join(directory,'original-purge-policy.json');
fs.writeFileSync(wrapper,ORIGINAL_PURGE_WRAPPER,{flag:'wx'});fs.writeFileSync(preload,ORIGINAL_PURGE_PRELOAD,{flag:'wx'});
const nonce=randomUUID();this.server=http.createServer((request,response)=>this.handleDurability(request,response,nonce));
await new Promise((resolve,reject)=>{this.server.once('error',reject);this.server.listen(0,'127.0.0.1',resolve);});
const directoryMetadata={};
for(let ancestor=path.dirname(directory);;ancestor=path.dirname(ancestor)){
if(fs.lstatSync(ancestor).isSymbolicLink())throw engineError('所属运行目录祖先不能是链接。');
const stat=fs.statSync(ancestor);directoryMetadata[ancestor]=stat;directoryMetadata[path.toNamespacedPath(ancestor)]=stat;
if(path.dirname(ancestor)===ancestor)break;
}
const patchFile=launch.args.at(-1),patch=JSON.parse(fs.readFileSync(patchFile));
patch.push({insert:[{id:'workbench-original-purge-restricted',name:wrapper,config:{entry:pathToFileURL(path.join(source,'lib/index.js')).href,
originalConfig:this.strategy.originalConfig,strategySha256:this.strategy.sha256,marker:this.marker}}]});fs.writeFileSync(patchFile,JSON.stringify(patch));
const executableInputs=[...this.strategy.runtime.inputs,...this.inputs,engineFileIdentity(wrapper),engineFileIdentity(path.join(directory,'bridge.mjs'))];
this.expectedModules=new Map(executableInputs.map(input=>[input.path,input]));
const policy={schemaVersion:1,inputs:executableInputs,modules:this.modules,nativeModules:this.nativeModules,nativeLibraries:this.nativeLibraries,
platformLibraries:this.strategy.runtime.platformLibraries,koffiEntry:path.join(installation.root,'node_modules/.pnpm/koffi@3.1.1/node_modules/koffi/index.js'),
nativeAddons:this.strategy.runtime.nativeAddons,directoryMetadata,
originalUrl:pathToFileURL(source+path.sep).href,llmModule:installation.llmModule,durabilityEndpoint:'http://127.0.0.1:'+this.server.address().port+'/fsync'};
fs.writeFileSync(policyFile,JSON.stringify(policy),{flag:'wx'});
this.launchInputs=[engineFileIdentity(wrapper),engineFileIdentity(preload),engineFileIdentity(policyFile),...this.inputs];
const metadataReads=[];
for(const anchor of [installation.root,launch.cwd,source])for(let ancestor=path.dirname(anchor);;ancestor=path.dirname(ancestor)){
metadataReads.push(path.join(ancestor,'node_modules','*'),path.join(ancestor,'package.json'));if(path.dirname(ancestor)===ancestor)break;
}
const readRoots=originalPurgeReadRoots([installation.root,path.dirname(installation.node.path),directory,launch.cwd],
[...metadataReads,...this.strategy.runtime.platformLibraries.map(input=>input.path)]);
launch.args=['--permission','--allow-addons',...[...new Set(readRoots)].flatMap(root=>['--allow-fs-read='+root,'--allow-fs-read='+path.toNamespacedPath(root)]),
'--allow-fs-write='+directory,'--allow-fs-write='+path.toNamespacedPath(directory),'--import',pathToFileURL(preload).href,...launch.args];
Object.assign(launch.env,{USERPROFILE:path.join(directory,'home'),APPDATA:path.join(directory,'home'),LOCALAPPDATA:path.join(directory,'home'),
NARB_DISABLE_NATIVE_CACHE:'1',AWB_ORIGINAL_PURGE_POLICY:policyFile,AWB_ORIGINAL_PURGE_DURABILITY_NONCE:nonce});
this.report.launchInputs=this.launchInputs;this.report.originalCopies=this.inputs;
this.report.permissionPolicy={readRoots,writeRoot:directory,arguments:launch.args,cwd:launch.cwd,nativeCache:false};
return launch;
}
async handleDurability(request,response,nonce){
try{
if(this.closed||request.method!=='POST'||request.url!=='/fsync'||request.headers.origin!==undefined||request.headers['content-type']!=='application/json'
||!equal(request.headers.authorization,'Bearer '+nonce))throw engineError('同步请求不属于当前运行。');
const chunks=[];let size=0;for await(const chunk of request){size+=chunk.length;if(size>4096)throw engineError('同步输入超限。');chunks.push(chunk);}
const value=JSON.parse(Buffer.concat(chunks)),file=path.resolve(value.path);
if(Object.keys(value).sort().join(',')!=='dev,ino,path,size'||!file.startsWith(this.directory+path.sep)||fs.realpathSync.native(file)!==file)throw engineError('同步路径不属于运行目录。');
for(let current=file;current!==this.directory;current=path.dirname(current))if(fs.lstatSync(current).isSymbolicLink())throw engineError('同步路径不能经过链接。');
const fd=fs.openSync(file,'r+');try{
const stat=fs.fstatSync(fd,{bigint:true});if(!stat.isFile()||stat.size>64n*1024n*1024n)throw engineError('同步文件超限。');
for(const key of ['dev','ino','size'])if(String(stat[key])!==value[key])throw engineError('同步文件身份已变化。');
fs.fsyncSync(fd);const bytes=fs.readFileSync(fd);
if(BigInt(bytes.length)!==stat.size)throw engineError('同步期间文件发生变化。');
this.report.durabilityReceipts.push({path:path.relative(this.directory,file),dev:value.dev,ino:value.ino,size:value.size,sha256:sha(bytes),operation:'actual-parent-fsync'});
}finally{fs.closeSync(fd);}
response.writeHead(200,{'Content-Type':'application/json',Connection:'close'});response.end('{"flushed":true}');
}catch(error){this.report.durabilityRejections.push({at:new Date().toISOString(),reason:error.message});
if(!response.destroyed){response.writeHead(409,{'Content-Type':'application/json',Connection:'close'});response.end('{"error":"Owned durability request refused"}');}}
}
verify({ready=false,pid=null}={}){
assertOriginalPurgeStrategy(this.strategy);
for(const input of this.launchInputs??[])if(engineFileIdentity(input.path).sha256!==input.sha256)throw engineError('所属原版运行副本或适配输入已变化。',409,'ENGINE_INPUT_CHANGED');
if(ready||this.report.readiness){
const marker=JSON.parse(fs.readFileSync(this.marker));
if(marker.schemaVersion!==1||marker.pid!==(pid??this.report.readiness?.pid)||marker.strategySha256!==this.strategy.sha256
||marker.originalEntryLoaded!==true||marker.originalApplyCalled!==true||marker.upstreamPatchInstalled!==false
||digest(marker.originalConfig)!==digest(this.strategy.originalConfig)
||digest([...marker.blockedTools].sort())!==digest(['purge_apply','purge_revert','purge_status']))throw engineError('原版入口、受限配置或外部工具门控不符合封存策略。');
this.report.readiness=marker;
}
if(fs.existsSync(this.modules)){
if(fs.statSync(this.modules).size>4*1024*1024)throw engineError('原版模块收据超限。');
const lines=fs.readFileSync(this.modules,'utf8').trimEnd().split('\n');
this.report.loadedModules=lines.filter(Boolean).map(line=>{const item=JSON.parse(line),expected=this.expectedModules.get(item.path);
if(!expected||item.sha256!==expected.sha256||item.bytes!==expected.bytes||item.sourceSha256!==null&&item.sourceSha256!==expected.sha256)throw engineError('实际加载模块与封存输入不符。');return item;});
if(this.report.loadedModules.length>1024)throw engineError('原版模块收据数量超限。');
}
if(fs.existsSync(this.nativeModules)){
if(fs.statSync(this.nativeModules).size>65536)throw engineError('原生加载收据超限。');
this.report.nativeLoads=fs.readFileSync(this.nativeModules,'utf8').trimEnd().split('\n').filter(Boolean).map(line=>{const item=JSON.parse(line);
if(!this.strategy.runtime.nativeAddons.some(expected=>expected.path===item.path&&expected.sha256===item.sha256&&expected.bytes===item.bytes)
||item.operation!=='actual-process-dlopen')throw engineError('实际原生加载不属于固定清单。');return item;});
}
if(fs.existsSync(this.nativeLibraries)){
if(fs.statSync(this.nativeLibraries).size>65536)throw engineError('原生库加载收据超限。');
this.report.nativeLibraries=fs.readFileSync(this.nativeLibraries,'utf8').trimEnd().split('\n').filter(Boolean).map(line=>{const item=JSON.parse(line);
if(!this.strategy.runtime.platformLibraries.some(expected=>expected.path===item.path&&expected.sha256===item.sha256&&expected.bytes===item.bytes)
||item.operation!=='actual-koffi-load')throw engineError('实际原生库加载不属于固定清单。');return item;});
}
if(ready&&this.report.nativeLoads.length!==this.strategy.runtime.nativeAddons.length)throw engineError('未核对固定原生模块的实际加载。');
return this.report;
}
async close(){if(this.closed)return;this.closed=true;if(this.server){this.server.closeAllConnections();await new Promise(resolve=>this.server.close(resolve));}}
}
@@ -0,0 +1,64 @@
import fs from 'node:fs';
import path from 'node:path';
import {createHash} from 'node:crypto';
import lock from './original-purge-lock.json' with {type:'json'};
import {engineCanonicalDigest as digest,engineError} from '../../shared/contracts/engines.mjs';
import {engineFileIdentity} from './deepseek-installation.mjs';
export const ORIGINAL_PURGE_KIND='purge-original-restricted-v1';
export const ORIGINAL_PURGE_LOCK_SHA256=digest(lock);
const hash=bytes=>createHash('sha256').update(bytes).digest('hex');
const changed=message=>engineError(message,409,'ENGINE_INPUT_CHANGED');
function directory(root){
if(typeof root!=='string'||!path.isAbsolute(root)||!fs.lstatSync(root).isDirectory()||fs.lstatSync(root).isSymbolicLink())throw changed('原版来源需要普通绝对目录。');
return fs.realpathSync.native(root);
}
function pinnedInputs(root,expected,{original=false}={}){
const inputs=expected.map(input=>{
const file=path.join(root,input.relative),identity=engineFileIdentity(file,8*1024*1024);
if(!identity.path.startsWith(root+path.sep)||identity.bytes!==input.bytes||identity.sha256!==input.sha256)throw changed('固定原版输入已变化:'+input.relative);
if(original){
for(let current=file;current!==root;current=path.dirname(current))if(fs.lstatSync(current).isSymbolicLink())throw changed('原版输入不能经过链接。');
}
return {...identity,relative:input.relative};
});
if(original){
const found=[];function walk(relative){const file=path.join(root,relative),stat=fs.lstatSync(file);
if(stat.isSymbolicLink())throw changed('原版 lib 不能包含链接。');
if(stat.isDirectory()){for(const name of fs.readdirSync(file))walk(path.join(relative,name));}
else if(stat.isFile())found.push(relative.replaceAll('\\','/'));else throw changed('原版 lib 包含非普通文件。');
if(found.length>128)throw changed('原版 lib 文件数量超出固定版本。');
}walk('lib');
if(digest(found.sort())!==digest(expected.filter(item=>item.relative.startsWith('lib/')).map(item=>item.relative).sort()))throw changed('原版 lib 文件集合已变化。');
}
return inputs;
}
export function originalPurgeSource(root){
root=directory(root);const inputs=pinnedInputs(root,lock.original,{original:true});
const source={name:'dsh-purge',version:lock.purgeVersion,dshTarget:lock.harnessVersion,license:'Apache-2.0',attribution:'YuJunZhiXue / dsh-purge',root,inputs,lockSha256:ORIGINAL_PURGE_LOCK_SHA256};
return {...source,sourceSha256:digest(source)};
}
export function originalPurgeRuntime(installation){
if(process.platform!=='win32'||process.arch!=='x64')throw changed('当前原版受限配置仅核验 Windows x64。');
if(installation?.controlledStatus!=='available'||installation.version!==lock.harnessVersion)throw changed('原版受限模式需要已检测的 Harness 0.2.1-rc.2。');
const root=directory(installation.root),inputs=pinnedInputs(root,lock.harness);
const platformLibraries=['kernel32.dll','advapi32.dll'].map(name=>({...engineFileIdentity(path.join(process.env.SystemRoot,'System32',name)),name}));
const runtime={root,inputs,node:installation.node,lockSha256:ORIGINAL_PURGE_LOCK_SHA256,platformLibraries,
nativeAddons:lock.nativeAddons.map(input=>({...input,path:path.join(root,input.relative)}))};
return {...runtime,sha256:digest(runtime)};
}
export function originalPurgeStrategy(source,runtime,prompt){
const postPrompt='[Agent Workbench original Purge '+source.sourceSha256+' / '+hash(Buffer.from(prompt))+']\n'+prompt+'\n[/Agent Workbench original Purge]';
const config={enabled:true,autoApplyOnStart:false,autoUpdateOnStart:false,autoRevertOnMissing:false,injectOnce:false,stripMnemon:true,verbose:false,
autoRetry:false,retryMax:0,autoContinue:false,continueMax:0,capabilityProtocol:true,hooksDenyBypass:false,postPromptOrder:5100,postPrompt};
const strategy={schemaVersion:1,kind:ORIGINAL_PURGE_KIND,enabled:true,source,runtime,prompt,promptSha256:hash(Buffer.from(prompt)),originalConfig:config,
implementation:'workbench-original-entry-restricted-v1',upstreamPluginLoaded:true,automaticRetry:false,hostModification:false,
isolation:{profile:'fixed-trusted-source-node-permissions-v1',osSandbox:false,pinnedNativeAddons:true,arbitraryNativeAddons:false,originalTools:false,credentials:false}};
return {...strategy,sha256:digest(strategy)};
}
export function assertOriginalPurgeStrategy(strategy){
const source=originalPurgeSource(strategy.source?.root),runtime=originalPurgeRuntime({controlledStatus:'available',version:lock.harnessVersion,...strategy.runtime});
const node=engineFileIdentity(strategy.runtime.node.path,256*1024*1024);
if(node.sha256!==strategy.runtime.node.sha256||node.bytes!==strategy.runtime.node.bytes||strategy.runtime.node.version!==process.versions.node
||digest(originalPurgeStrategy(source,runtime,strategy.prompt))!==digest(strategy))throw changed('原版策略、运行器或固定加载输入已变化,请保留原记录并封存新计划。');
}
+21 -2
View File
@@ -4,6 +4,8 @@ import { createHash } from 'node:crypto';
import { engineError, engineCanonicalDigest } from '../../shared/contracts/engines.mjs';
import { engineFileIdentity } from './deepseek-installation.mjs';
import { registeredSourceRoots } from './registered-sources.mjs';
import { ORIGINAL_PURGE_KIND, originalPurgeSource, originalPurgeRuntime, originalPurgeStrategy, assertOriginalPurgeStrategy } from './original-purge-source.mjs';
export { ORIGINAL_PURGE_KIND } from './original-purge-source.mjs';
export const PURGE_SOURCE_FILES = Object.freeze(['package.json', 'lib/index.js', 'lib/identity.js', 'lib/core.js',
'lib/continue-retry.js', 'lib/capability-protocol.js', 'cordis.patch.yml', 'LICENSE', 'NOTICE']);
@@ -69,7 +71,22 @@ function strategyFor(source, prompt) {
implementation: 'workbench-independent-prompt-v1', upstreamPluginLoaded: false, automaticRetry: false, hostModification: false };
return { ...strategy, sha256: engineCanonicalDigest(strategy) };
}
export function selectPurgeStrategy(input, appDirectory = process.cwd()) {
export function resolveOriginalPurgeSource(appDirectory=process.cwd(),root,installation) {
const detected=resolvePurgeSource(appDirectory,root),base={...detected,kind:ORIGINAL_PURGE_KIND,supportedVersions:['1.1.78']};
try {
const source=originalPurgeSource(detected.root),runtime=originalPurgeRuntime(installation);
return {...base,...source,status:'available',runtimeSha256:runtime.sha256,runtimeInputs:runtime.inputs.length,
message:'原版 1.1.78 完整文件与固定 Harness 依赖已核对。使用独立运行副本;自动重试、继续和原版修改工具关闭。'};
}catch(error){return {...base,status:'unavailable',sourceSha256:undefined,message:'原版受限模式尚不可用:'+error.message};}
}
export function selectPurgeStrategy(input, appDirectory = process.cwd(), installation) {
if(input?.kind===ORIGINAL_PURGE_KIND){
if(Object.keys(input).some(key=>!['kind','root','sourceSha256','runtimeSha256','prompt'].includes(key)))throw engineError('原版受限模式不接受权限或自动重试参数。',400);
promptText(input.prompt);
const source=resolveOriginalPurgeSource(appDirectory,input.root,installation);
if(source.status!=='available'||source.sourceSha256!==input.sourceSha256||source.runtimeSha256!==input.runtimeSha256)throw engineError('原版来源或运行依赖与刚才的检测不一致,请重新检测并封存新计划。');
return originalPurgeStrategy(originalPurgeSource(source.root),originalPurgeRuntime(installation),input.prompt);
}
if (!input || typeof input !== 'object' || Array.isArray(input) || Object.keys(input).some(key => !['kind', 'root', 'sourceSha256', 'prompt'].includes(key))
|| input.kind !== PURGE_PROMPT_KIND || typeof input.root !== 'string' || !/^[a-f0-9]{64}$/.test(input.sourceSha256 ?? '')) {
throw engineError('实验策略只接受已检测来源与完整工程提示。', 400);
@@ -81,6 +98,7 @@ export function selectPurgeStrategy(input, appDirectory = process.cwd()) {
}
export function assertPurgeStrategy(strategy) {
if (strategy === undefined) return;
if(strategy?.kind===ORIGINAL_PURGE_KIND){promptText(strategy.prompt);return assertOriginalPurgeStrategy(strategy);}
if (!strategy || strategy.kind !== PURGE_PROMPT_KIND || strategy.enabled !== true || !strategy.source) throw engineError('原提示实验策略无效。');
const source = resolvePurgeSource(process.cwd(), strategy.source.root);
if (source.status !== 'available' || source.sourceSha256 !== strategy.source.sourceSha256) throw engineError('Purge 来源已变化,原提示实验不能继续;请保留记录并封存新计划。', 409, 'ENGINE_INPUT_CHANGED');
@@ -93,7 +111,8 @@ export function nativeSystemTexts(input) {
}
export function assertPurgeModelInput(input, strategy) {
if (!strategy) return;
if (nativeSystemTexts(input).reduce((count, text) => count + text.split(strategy.section.text).length - 1, 0) !== 1) {
const expected=strategy.kind===ORIGINAL_PURGE_KIND?strategy.originalConfig.postPrompt:strategy.section.text;
if (nativeSystemTexts(input).reduce((count, text) => count + text.split(expected).length - 1, 0) !== 1) {
throw engineError('实际模型输入缺少唯一完整的封存提示实验段,未发送请求。');
}
}
+14 -3
View File
@@ -9,7 +9,7 @@ import { assertWorkspacesResolved } from '../shared/contracts/workspaces.mjs';
import { verifyWorkspaceProject } from '../core/workspaces/git-workspaces.mjs';
import { publicEngineJob } from '../shared/contracts/engines.mjs';
import { publicEngineRun, verifyEngineInput, originalEngineRun } from '../shared/contracts/engine-execution.mjs';
import { resolvePurgeSource } from '../core/engines/purge-strategy.mjs';
import { resolvePurgeSource,resolveOriginalPurgeSource,ORIGINAL_PURGE_KIND } from '../core/engines/purge-strategy.mjs';
import { verifyBrowserJob } from '../core/browser/browser-manager.mjs';
import { ConfigImporter } from '../core/models/config-import.mjs';
import { ProjectMemoryManager } from '../core/memory/project-memory.mjs';
@@ -24,7 +24,12 @@ import { readInstallationProgress } from '../core/desktop/installation-progress.
export function createSessionPublisher(clients) {
return session => {
const payload = (session.eventSeq ? 'id: ' + session.eventSeq + '\n' : '') + 'data: ' + JSON.stringify({ kind: 'session', seq: session.eventSeq, session }) + '\n\n';
const snapshot = JSON.stringify({ kind: 'session', seq: session.eventSeq, session });
// Large source/Run receipts stay in the session API. Repeatedly queueing
// them on SSE can disconnect a healthy reader before it receives a cursor.
const data = Buffer.byteLength(snapshot) <= 64 * 1024 ? snapshot : JSON.stringify({ kind: 'session_changed', seq: session.eventSeq,
sessionId: session.id, projectId: session.projectId, revision: session.revision });
const payload = (session.eventSeq ? 'id: ' + session.eventSeq + '\n' : '') + 'data: ' + data + '\n\n';
for (const response of clients) {
if (response.destroyed || response.writableEnded || response.writableLength > 2 * 1024 * 1024) { response.destroy(); clients.delete(response); }
else response.write(payload);
@@ -243,7 +248,13 @@ 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/engines/deepseek/controlled-availability') return json(response, runtime.engineRunner().availability(url.searchParams.has('root') ? url.searchParams.get('root') : undefined));
if (method === 'GET' && route === '/api/engines/purge/source') return json(response, resolvePurgeSource(appDirectory, url.searchParams.has('root') ? url.searchParams.get('root') : undefined));
if (method === 'GET' && route === '/api/engines/purge/source') {
const root=url.searchParams.has('root')?url.searchParams.get('root'):undefined;
if(url.searchParams.get('kind')===ORIGINAL_PURGE_KIND)return json(response,resolveOriginalPurgeSource(appDirectory,root,
runtime.engineRunner().availability(url.searchParams.has('harnessRoot')?url.searchParams.get('harnessRoot'):undefined)));
if(url.searchParams.has('kind')&&url.searchParams.get('kind')!=='purge-prompt-experiment')throw Object.assign(new Error('未知 Purge 策略。'),{status:400});
return json(response,resolvePurgeSource(appDirectory,root));
}
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 });