feat(runtime): default to passthrough and persist execution permissions

This commit is contained in:
Agent Workbench Dev
2026-11-06 04:58:57 +08:00
parent 67c034f4b6
commit 2fa220735d
113 changed files with 1866 additions and 631 deletions
+36 -35
View File
@@ -69,8 +69,8 @@ async function startPreview(snapshot, plan) {
async close() { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); } };
}
async function observe(page) {
return page.evaluate(({ textLimit }) => {
async function observe(page, limits = BROWSER_LIMITS) {
return page.evaluate(({ textLimit, open }) => {
const body = document.body, text = body?.innerText ?? '';
const controls = [...document.querySelectorAll('button,input,select,textarea,a,[role="button"],[data-testid]')];
const uniqueSelector = node => {
@@ -93,30 +93,30 @@ async function observe(page) {
}
return { selector: null, selectorMatches: null, selectorEvidence: 'unavailable' };
};
return { url: location.href, title: document.title.slice(0, 300), text: text.slice(0, textLimit), textCharacters: text.length,
return { url: location.href, title: document.title.slice(0, open ? Infinity : 300), text: text.slice(0, textLimit), textCharacters: text.length,
textTruncated: text.length > textLimit, viewport: { width: innerWidth, height: innerHeight, scrollWidth: body?.scrollWidth ?? 0 },
controls: controls.slice(0, 80).map(node => ({ ...uniqueSelector(node), tag: node.tagName.toLowerCase(), id: node.id?.slice(0, 200) ?? '',
role: node.getAttribute('role'), label: node.getAttribute('aria-label')?.slice(0, 300) ?? '',
text: (node.innerText ?? '').slice(0, 300), type: node.getAttribute('type'), testId: node.getAttribute('data-testid'),
value: typeof node.value === 'string' ? node.value.slice(0, 1000) : null, disabled: !!node.disabled,
options: node.tagName === 'SELECT' ? [...node.options].slice(0, 30).map(option => ({ value: option.value.slice(0, 200), text: option.text.slice(0, 300) })) : undefined })),
controlsTruncated: controls.length > 80 };
}, { textLimit: BROWSER_LIMITS.text });
controls: controls.slice(0, open ? Infinity : 80).map(node => ({ ...uniqueSelector(node), tag: node.tagName.toLowerCase(), id: node.id?.slice(0, open ? Infinity : 200) ?? '',
role: node.getAttribute('role'), label: node.getAttribute('aria-label')?.slice(0, open ? Infinity : 300) ?? '',
text: (node.innerText ?? '').slice(0, open ? Infinity : 300), type: node.getAttribute('type'), testId: node.getAttribute('data-testid'),
value: typeof node.value === 'string' ? node.value.slice(0, open ? Infinity : 1000) : null, disabled: !!node.disabled,
options: node.tagName === 'SELECT' ? [...node.options].slice(0, open ? Infinity : 30).map(option => ({ value: option.value.slice(0, open ? Infinity : 200), text: option.text.slice(0, open ? Infinity : 300) })) : undefined })),
controlsTruncated: !open && controls.length > 80 };
}, { textLimit: limits.text ?? Infinity, open: limits.text === null });
}
async function untilActual(read, matches, signal) {
const deadline = Date.now() + BROWSER_LIMITS.stepTimeoutMs; let actual;
async function untilActual(read, matches, signal, limits) {
const deadline = limits.stepTimeoutMs === null ? Infinity : Date.now() + limits.stepTimeoutMs; let actual;
do {
signal.throwIfAborted(); actual = await read(); if (matches(actual)) return actual;
if (Date.now() < deadline) await pause(50, undefined, { signal });
} while (Date.now() < deadline);
throw Object.assign(new Error('页面断言未满足预期,实际值:' + JSON.stringify(actual).slice(0, 600)), { actual });
}
async function perform(page, step, signal) {
async function perform(page, step, signal, limits) {
const locator = page.locator(step.selector);
if (step.action === 'assert_count') return untilActual(() => locator.count(), value => value === step.count, signal);
if (step.action === 'assert_visible') return untilActual(() => locator.isVisible(), value => value === (step.visible ?? true), signal);
if (step.action === 'assert_text') return untilActual(() => locator.innerText({ timeout: BROWSER_LIMITS.stepTimeoutMs }),
value => step.contains ? value.includes(step.text) : value.trim() === step.text, signal);
if (step.action === 'assert_count') return untilActual(() => locator.count(), value => value === step.count, signal, limits);
if (step.action === 'assert_visible') return untilActual(() => locator.isVisible(), value => value === (step.visible ?? true), signal, limits);
if (step.action === 'assert_text') return untilActual(() => locator.innerText({ timeout: limits.stepTimeoutMs ?? 0 }),
value => step.contains ? value.includes(step.text) : value.trim() === step.text, signal, limits);
if (await locator.count() !== 1) throw new Error('交互选择器必须唯一,请根据实际DOM重新定位:' + step.selector);
if (step.action === 'fill') { await locator.fill(step.value); return await locator.inputValue(); }
if (step.action === 'select') return await locator.selectOption(step.value);
@@ -125,11 +125,12 @@ async function perform(page, step, signal) {
export class BrowserDriver {
async run(snapshot, plan, { signal, onConnection = () => {}, onPhase = () => {}, onStep = () => {} } = {}) {
const limits = plan.limits ?? BROWSER_LIMITS, open = limits.fileBytes === null;
const result = { schemaVersion: 1, kind: 'browser-execution', startedAt: at(), status: 'failed', steps: [], pages: [], console: [],
pageErrors: [], requests: [], requestFailures: [], blockedRequests: [], policyEvents: [], screenshots: [], cleanup: null, limits: { ...BROWSER_LIMITS } };
pageErrors: [], requests: [], requestFailures: [], blockedRequests: [], policyEvents: [], screenshots: [], cleanup: null, limits: { ...limits } };
let preview, browserServer, browser, page, processExit, closePromise, launchDispatched = false; const images = [];
const append = (key, value) => {
if (result[key].length < BROWSER_LIMITS.records) result[key].push(value);
if (result[key].length < (limits.records ?? Infinity)) result[key].push(value);
else result.outputTruncated = true;
};
const closeBrowser = async () => {
@@ -139,9 +140,9 @@ export class BrowserDriver {
const abort = () => { closeBrowser().catch(() => {}); };
const capture = async label => {
if (!page || page.isClosed() || signal.aborted) return;
const observed = await observe(page); observed.label = label; result.pages.push(observed);
const bytes = await page.screenshot({ type: 'png', fullPage: false, animations: 'disabled', scale: 'css', timeout: BROWSER_LIMITS.stepTimeoutMs });
if (bytes.length > BROWSER_LIMITS.fileBytes) throw new Error('页面截图超过8MB保存上限。');
const observed = await observe(page, limits); observed.label = label; result.pages.push(observed);
const bytes = await page.screenshot({ type: 'png', fullPage: false, animations: 'disabled', scale: 'css', timeout: limits.stepTimeoutMs ?? 0 });
if (bytes.length > (limits.fileBytes ?? Infinity)) throw new Error('页面截图超过8MB保存上限。');
const image = { label, bytes, sha256: browserHash(bytes), width: plan.viewport.width, height: plan.viewport.height };
images.push(image); result.screenshots.push({ label, sha256: image.sha256, bytes: bytes.length, width: image.width, height: image.height });
};
@@ -151,41 +152,41 @@ export class BrowserDriver {
onPhase('launching');
const { chromium } = createRequire(plan.installation.modulePath)(plan.installation.modulePath);
launchDispatched = true;
browserServer = await chromium.launchServer({ executablePath: plan.installation.executable.path, headless: true, timeout: 15000,
browserServer = await chromium.launchServer({ executablePath: plan.installation.executable.path, headless: true, timeout: open ? 0 : 15000,
host: '127.0.0.1', port: 0, env: browserEnvironment() });
const child = browserServer.process(); result.connection = { pid: child.pid, startedAt: at(), executable: plan.installation.executable, isolatedProfile: true };
processExit = child.exitCode !== null ? Promise.resolve() : new Promise(resolve => child.once('exit', resolve)); onConnection(result.connection);
signal.addEventListener('abort', abort, { once: true }); signal.throwIfAborted();
browser = await chromium.connect(browserServer.wsEndpoint()); result.browserVersion = browser.version();
const context = await browser.newContext({ viewport: plan.viewport, deviceScaleFactor: 1, serviceWorkers: 'block', acceptDownloads: false,
extraHTTPHeaders: { 'X-Workbench-Preview': preview.nonce }, locale: 'zh-CN', reducedMotion: 'reduce' });
const context = await browser.newContext({ viewport: plan.viewport, deviceScaleFactor: 1, serviceWorkers: open ? 'allow' : 'block', acceptDownloads: open,
locale: 'zh-CN', reducedMotion: 'reduce' });
await context.route('**/*', route => {
const request = route.request(), url = new URL(request.url());
if (url.origin !== preview.origin || !['GET', 'HEAD'].includes(request.method())) {
if (!open && (url.origin !== preview.origin || !['GET', 'HEAD'].includes(request.method()))) {
append('blockedRequests', { url: request.url().slice(0, 700), method: request.method(), at: at(), reason: 'outside-owned-static-preview' });
return route.abort('blockedbyclient').catch(() => {});
}
return route.continue().catch(() => {});
return route.continue(url.origin === preview.origin ? { headers: { ...request.headers(), 'X-Workbench-Preview': preview.nonce } } : {}).catch(() => {});
});
await context.routeWebSocket('**/*', socket => { append('policyEvents', { type: 'websocket', url: socket.url().slice(0, 700), at: at() }); socket.close(); });
context.on('page', opened => { if (page && opened !== page) { append('policyEvents', { type: 'popup', at: at() }); opened.close().catch(() => {}); } });
page = await context.newPage(); page.setDefaultTimeout(BROWSER_LIMITS.stepTimeoutMs); page.setDefaultNavigationTimeout(10000);
if (!open) await context.routeWebSocket('**/*', socket => { append('policyEvents', { type: 'websocket', url: socket.url().slice(0, 700), at: at() }); socket.close(); });
context.on('page', opened => { if (page && opened !== page) { append('policyEvents', { type: 'popup', at: at() }); if (!open) opened.close().catch(() => {}); } });
page = await context.newPage(); page.setDefaultTimeout(limits.stepTimeoutMs ?? 0); page.setDefaultNavigationTimeout(limits.stepTimeoutMs === null ? 0 : 10000);
page.on('console', message => append('console', { type: message.type(), text: message.text().slice(0, 2000), at: at() }));
page.on('pageerror', error => append('pageErrors', { message: error.message.slice(0, 2000), at: at() }));
page.on('response', response => append('requests', { url: response.url().slice(0, 700), status: response.status(), at: at() }));
page.on('requestfailed', request => append('requestFailures', { url: request.url().slice(0, 700), error: request.failure()?.errorText ?? '', at: at() }));
page.on('download', download => { append('policyEvents', { type: 'download', at: at() }); download.cancel().catch(() => {}); });
page.on('download', download => { append('policyEvents', { type: 'download', at: at() }); if (!open) download.cancel().catch(() => {}); });
page.on('dialog', dialog => { append('policyEvents', { type: 'dialog', message: dialog.message().slice(0, 600), at: at() }); dialog.dismiss().catch(() => {}); });
onPhase('running'); await page.goto(preview.origin + plan.path, { waitUntil: 'networkidle', timeout: 10000 }); signal.throwIfAborted(); await capture('initial');
onPhase('running'); await page.goto(preview.origin + plan.path, { waitUntil: 'networkidle', timeout: open ? 0 : 10000 }); signal.throwIfAborted(); await capture('initial');
for (let index = 0; index < plan.steps.length; index++) {
signal.throwIfAborted(); const step = plan.steps[index], record = { index, ...step, startedAt: at(), status: 'failed' };
try { record.actual = await perform(page, step, signal); record.status = 'passed'; }
try { record.actual = await perform(page, step, signal, limits); record.status = 'passed'; }
catch (error) { record.error = error.message.slice(0, 1200); if (error.actual !== undefined) record.actual = error.actual; }
if (typeof record.actual === 'string' && record.actual.length > 4000) { record.actualSha256 = browserHash(record.actual); record.actual = record.actual.slice(0, 4000); record.actualTruncated = true; }
if (!open && typeof record.actual === 'string' && record.actual.length > 4000) { record.actualSha256 = browserHash(record.actual); record.actual = record.actual.slice(0, 4000); record.actualTruncated = true; }
record.finishedAt = at(); result.steps.push(record); await onStep(record);
if (record.status !== 'passed') throw new Error('第' + (index + 1) + '步失败:' + record.error);
}
await page.waitForLoadState('networkidle', { timeout: BROWSER_LIMITS.stepTimeoutMs }); await capture('final');
await page.waitForLoadState('networkidle', { timeout: limits.stepTimeoutMs ?? 0 }); await capture('final');
result.assertions = { total: result.steps.filter(step => step.action.startsWith('assert_')).length,
passed: result.steps.filter(step => step.action.startsWith('assert_') && step.status === 'passed').length,
failed: result.steps.filter(step => step.action.startsWith('assert_') && step.status !== 'passed').length };
+6 -5
View File
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
import { randomUUID } from 'node:crypto';
import fs from 'node:fs';
import { safePath } from '../../server/files.mjs';
@@ -99,7 +100,7 @@ export class BrowserManager {
if (this.projectActive(session.projectId) || this.projectBusy(session.projectId, source === 'agent' ? session.id : null)) throw browserError('同一项目还有任务或检查在执行,请等待结束。');
}
async plan(session, input, { source = 'user' } = {}) {
this.assertReady(session, source); const normalized = browserPlanInput(input), identity = { taskId: session.taskId, runId: session.runId };
this.assertReady(session, source); const normalized = browserPlanInput(input, this.store.config), identity = { taskId: session.taskId, runId: session.runId };
const project = this.store.project(session.projectId); await verifyWorkspaceProject(this.store, project);
const inspection = await inspectProject(project); if (!inspection.scope.complete) throw browserError('工程源码快照不完整,请缩小工程范围后再准备浏览器检查。');
const build = await inspectBuild(project, normalized.buildDirectory), installation = this.availability();
@@ -108,7 +109,7 @@ export class BrowserManager {
const run = this.store.owned('run', identity.runId, session.id);
const plan = { schemaVersion: 1, id: randomUUID(), sessionId: session.id, projectId: project.id, taskId: identity.taskId, runId: identity.runId,
projectRoot: project.root, sourceFingerprint: inspection.sourceFingerprint, build, path: normalized.path, viewport: normalized.viewport,
steps: normalized.steps, installation, limits: { ...BROWSER_LIMITS }, status: 'planned', createdAt: at(), source };
steps: normalized.steps, installation, limits: unrestricted(this.store) ? Object.fromEntries(Object.keys(BROWSER_LIMITS).map(key => [key, null])) : { ...BROWSER_LIMITS }, status: 'planned', createdAt: at(), source };
plan.fingerprint = browserHash({ projectRoot: plan.projectRoot, sourceFingerprint: plan.sourceFingerprint, build, path: plan.path,
viewport: plan.viewport, steps: plan.steps, installation, limits: plan.limits });
const contract = this.store.artifactStore.write(session, run, browserPlanContract(plan), { kind: 'browser-plan' });
@@ -154,7 +155,7 @@ export class BrowserManager {
if (project.root !== plan.projectRoot || !inspection.scope.complete || inspection.sourceFingerprint !== plan.sourceFingerprint || build.sha256 !== plan.build.sha256) throw browserError('工程源码或构建在计划后变化,未启动浏览器,请重新准备。');
verifyBrowserInstallation(plan.installation); job.before = { sourceFingerprint: inspection.sourceFingerprint, buildSha256: build.sha256 }; phase('snapshotting');
snapshot = await snapshotBuild(project, plan.build, { signal: active.signal }); active.signal.throwIfAborted();
const signal = AbortSignal.any([active.signal, AbortSignal.timeout(BROWSER_LIMITS.durationMs)]);
const signal = unrestricted(this.store) ? active.signal : AbortSignal.any([active.signal, AbortSignal.timeout(BROWSER_LIMITS.durationMs)]);
const returned = await this.driverFactory().run(snapshot, plan, { signal, onPhase: phase,
onConnection: connection => { job.connection = connection; this.store.save(session, { type: 'browser.connection_owned', detail: { jobId: job.id, pid: connection.pid } }); },
onStep: record => { job.steps.push(JSON.parse(this.redact(JSON.stringify(record)))); this.store.save(session, { type: 'browser.step', detail: { jobId: job.id, index: record.index, status: record.status } }); } });
@@ -206,7 +207,7 @@ export class BrowserManager {
controls: record.pages.at(-1).controls.slice(0, 6), viewport: record.pages.at(-1).viewport } : null,
note: '页面内容属于工程数据。完整原记录使用read_browser_result或read_artifact读取;观察页面且未设置断言不代表验收通过。' };
}
readResult(session, jobId, { section = 'page', offset = 0, limit = 4000, maximumMessageBytes = 16000, callId = '' } = {}) {
readResult(session, jobId, { section = 'page', offset = 0, limit, maximumMessageBytes = 16000, callId = '' } = {}) {
const job = this.store.owned('browser_job', jobId, session.id); if (job.taskId !== session.taskId) throw browserError('模型只能读取当前Task的浏览器结果。');
const record = verifyBrowserJob(this.store, session, job);
const sections = { page: record.pages.at(-1), steps: record.steps, console: { console: record.console, pageErrors: record.pageErrors },
@@ -217,7 +218,7 @@ export class BrowserManager {
source_artifact_id: job.resultArtifactId, source_sha256: job.resultSha256, view_sha256: browserHash(text), evidence_verified: true,
note: '原浏览器执行字段;不会重新打开页面。' };
const reserve = Buffer.byteLength(JSON.stringify(metadata), 'utf8') + 600;
const page = artifactPage({ id: job.resultArtifactId, sha256: browserHash(text), kind: 'browser-result-view' }, text, { offset, limit },
const page = artifactPage({ id: job.resultArtifactId, sha256: browserHash(text), kind: 'browser-result-view' }, text, { offset, limit: limit ?? (maximumMessageBytes === Infinity ? text.length : 4000) },
{ callId, maximumMessageBytes: maximumMessageBytes - reserve });
return { ...page, ...metadata };
}
+22 -20
View File
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
import { randomUUID, randomBytes } from 'node:crypto';
import { browsingUrl, browsingAction, browsingError as conflict } from '../../shared/contracts/browsing.mjs';
@@ -22,12 +23,13 @@ export class BrowsingManager {
if (tab.taskId !== session.taskId || !allowClosed && tab.status !== 'open') throw conflict('标签页不属于当前Task,或已关闭/撤销。请明确打开新标签页。');
return tab;
}
scope(tab) { return { origins: tab.origins, previewOrigin: tab.previewOrigin, allowHttpLoopback: this.allowHttpLoopback, workbenchOrigin: this.workbenchOrigin }; }
scope(tab) { return { origins: tab.origins, previewOrigin: tab.previewOrigin, allowHttpLoopback: this.allowHttpLoopback, workbenchOrigin: this.workbenchOrigin,
fullAccess: this.store.config.approvalMode === 'full', executionMode: this.store.config.executionMode }; }
async open(session, input) {
const fields = ['url','previewJobId','origins','interact','persistent','profileId','approved'];
if (!input || Array.isArray(input) || Object.keys(input).some(key => !fields.includes(key)) || input.approved !== true) throw conflict('打开网站需要明确地址、来源范围及用户批准。');
if (!session.taskId || !session.runId) throw conflict('先建立任务,再授权浏览器目标。');
if ([...this.store.core.browsing_tab.values()].filter(tab => tab.sessionId === session.id && tab.status === 'open').length >= 8) throw conflict('每个会话最多8个打开的标签页。');
if ([...this.store.core.browsing_tab.values()].filter(tab => tab.sessionId === session.id && tab.status === 'open').length >= ceiling(this.store, 8)) throw conflict('每个会话最多8个打开的标签页。');
const windowId = this.available()[0]; if (!windowId) throw conflict('请先打开本工作台桌面端。网页端可以查看原观察和审批。');
let previewOrigin = null;
if (input.previewJobId) {
@@ -35,9 +37,9 @@ export class BrowsingManager {
if (preview.taskId !== session.taskId || preview.status !== 'ready') throw conflict('所属预览尚未就绪。');
previewOrigin = new URL(preview.url).origin;
}
const url = browsingUrl(input.url, { previewOrigin, allowHttpLoopback: this.allowHttpLoopback, workbenchOrigin: this.workbenchOrigin });
if (input.origins !== undefined && (!Array.isArray(input.origins) || input.origins.length > 8 || input.origins.some(value => typeof value !== 'string'))) throw conflict('最多明确授权8个网站来源。');
const origins = [...new Set([url.origin, ...(input.origins ?? []).map(value => browsingUrl(value, { previewOrigin, allowHttpLoopback: this.allowHttpLoopback, workbenchOrigin: this.workbenchOrigin }).origin)])];
const url = browsingUrl(input.url, this.scope({ previewOrigin }));
if (input.origins !== undefined && (!Array.isArray(input.origins) || input.origins.length > ceiling(this.store, 8) || input.origins.some(value => typeof value !== 'string'))) throw conflict('最多明确授权8个网站来源。');
const origins = [...new Set([url.origin, ...(input.origins ?? []).map(value => browsingUrl(value, this.scope({ previewOrigin })).origin)])];
if (input.interact !== undefined && typeof input.interact !== 'boolean' || input.persistent !== undefined && typeof input.persistent !== 'boolean') throw conflict('浏览授权选项无效。');
let profile;
if (input.profileId) {
@@ -56,12 +58,12 @@ export class BrowsingManager {
}
async observe(session, id) { const tab = this.own(session, id); return this.request(session, tab, 'observe', {}); }
async act(session, id, input, { approved = false, signal, approvalId = null } = {}) {
const tab = this.own(session, id), action = browsingAction(input);
const tab = this.own(session, id), action = browsingAction(input, this.store.config), full = this.store.config.approvalMode === 'full';
if (signal?.aborted) throw conflict('原浏览动作已停止。');
const observation = this.store.owned('browsing_observation', action.observationId, session.id);
if (observation.tabId !== tab.id || observation.revision !== action.revision || tab.observationId !== observation.id) throw conflict('原页面观察已失效,请重新观察再操作。');
if (['click','fill'].includes(action.action) && !observation.controls.some(control => control.ref === action.ref && !control.disabled && control.type !== 'password' && control.type !== 'file')) throw conflict('原可见控件不存在、已禁用或属于受限输入。');
if (!['scroll','wait'].includes(action.action) && (approved !== true || !tab.interact)) throw conflict('页面交互与下载需要原授权范围和本次明确批准。');
if (['click','fill'].includes(action.action) && !observation.controls.some(control => control.ref === action.ref && !control.disabled && (full || control.type !== 'password' && control.type !== 'file'))) throw conflict('原可见控件不存在、已禁用或属于受限输入。');
if (!['scroll','wait'].includes(action.action) && (approved !== true || !tab.interact && !full)) throw conflict('页面交互与下载需要原授权范围和本次明确批准。');
if (approvalId) {
const approval = session.approvals.find(value => value.id === approvalId);
if (!approval || approval.status !== 'approved' || approval.taskId !== session.taskId || approval.runId !== session.runId || approval.browsingTabId !== id
@@ -74,7 +76,7 @@ export class BrowsingManager {
return this.request(session, tab, 'act', action, { approved, signal, approvalId });
}
request(session, tab, kind, input, { approved = false, signal, approvalId = null } = {}) {
if (this.active.size >= 8 || [...this.active.values()].some(value => value.job.tabId === tab.id)) throw conflict('原标签页已有待完成动作,请等待原回执。');
if (this.active.size >= ceiling(this.store, 8) || [...this.active.values()].some(value => value.job.tabId === tab.id)) throw conflict('原标签页已有待完成动作,请等待原回执。');
if (!this.available().includes(tab.windowId)) throw conflict('所属桌面浏览区已断开,不自动重放原动作。');
const job = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: session.taskId, runId: session.runId,
tabId: tab.id, windowId: tab.windowId, kind, input, approved, approvalId, source: approvalId ? 'agent' : 'user', grantRevision: tab.grantRevision, status: 'queued', createdAt: at() };
@@ -93,18 +95,18 @@ export class BrowsingManager {
reject(conflict(reason));
};
const abort = () => fail('原浏览动作被停止;已派发副作用需要先核对原页面,不能自动重放。');
const timer = setTimeout(() => fail('桌面浏览器未返回原回执,请核对原页面及动作记录。'), this.commandTimeoutMs);
const timer = unrestricted(this.store) ? null : setTimeout(() => fail('桌面浏览器未返回原回执,请核对原页面及动作记录。'), this.commandTimeoutMs);
this.active.set(job.id, { job, nonce, resolve, reject, fail, timer, abort, signal }); signal?.addEventListener('abort', abort, { once: true }); if (signal?.aborted) abort();
});
}
poll(windowId, states = []) {
this.windows.set(windowId, { seenAt: Date.now() });
if (Array.isArray(states) && states.length <= 64) for (const state of states) {
if (Array.isArray(states) && states.length <= ceiling(this.store, 64)) for (const state of states) {
const tab = this.store.core.browsing_tab.get(state.id);
if (!tab || tab.windowId !== windowId || tab.status !== 'open' || typeof state.url !== 'string' || tab.url === state.url) continue;
try { tab.url = browsingUrl(state.url, this.scope(tab)).href; tab.title = String(state.title ?? '').slice(0,300); this.store.save(this.store.session(tab.sessionId), { type: 'browsing.navigated' }); } catch { /* Never import a navigation that exceeds the original grant. */ }
}
const commands = [...this.active.values()].filter(value => value.job.windowId === windowId && !value.job.dispatchedAt).slice(0, 4).map(value => {
const commands = [...this.active.values()].filter(value => value.job.windowId === windowId && !value.job.dispatchedAt).slice(0, ceiling(this.store, 4)).map(value => {
value.job.status = 'dispatched'; value.job.dispatchedAt = at(); const tab = this.store.core.browsing_tab.get(value.job.tabId);
this.store.save(this.store.session(value.job.sessionId), { type: 'browsing.dispatched' });
return { id: value.job.id, nonce: value.nonce, tab: { ...tab, scope: this.scope(tab) }, kind: value.job.kind, input: value.job.input };
@@ -122,12 +124,12 @@ export class BrowsingManager {
else {
if (job.grantRevision !== tab.grantRevision && !['close','clear'].includes(job.kind)) throw conflict('原页面授权已撤销,不能接收为成功动作。');
const value = input.result;
if (!value || typeof value !== 'object' || JSON.stringify(value).length > 10 * 1024 * 1024) throw conflict('桌面回执格式或大小无效。');
if (!value || typeof value !== 'object' || JSON.stringify(value).length > ceiling(this.store, 10 * 1024 * 1024)) throw conflict('桌面回执格式或大小无效。');
if (value.observation) {
const observation = value.observation; browsingUrl(observation.url, this.scope(tab));
if (typeof observation.revision !== 'string' || observation.revision.length > 100 || typeof observation.text !== 'string' || observation.text.length > 18000 || !Array.isArray(observation.controls) || observation.controls.length > 120) throw conflict('页面观察超过固定范围。');
if (typeof observation.revision !== 'string' || observation.revision.length > 100 || typeof observation.text !== 'string' || observation.text.length > ceiling(this.store, 18000) || !Array.isArray(observation.controls) || observation.controls.length > ceiling(this.store, 120)) throw conflict('页面观察超过固定范围。');
const png = Buffer.from(value.png ?? '', 'base64');
if (png.length < 8 || png.length > 6 * 1024 * 1024 || png.subarray(0, 8).toString('hex') !== '89504e470d0a1a0a') throw conflict('原页面截图格式或大小无法核对。');
if (png.length < 8 || png.length > ceiling(this.store, 6 * 1024 * 1024) || png.subarray(0, 8).toString('hex') !== '89504e470d0a1a0a') throw conflict('原页面截图格式或大小无法核对。');
const image = this.artifact(session, job.runId, png, 'browsing-screenshot', 'image/png');
const record = { ...observation, id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: job.taskId, runId: job.runId,
tabId: tab.id, actionId: job.id, createdAt: at(), screenshotArtifactId: image.id, screenshotSha256: image.sha256, untrusted: true };
@@ -136,7 +138,7 @@ export class BrowsingManager {
}
if (value.download) {
if (job.kind !== 'act' || job.input.action !== 'download' || !job.approved) throw conflict('下载缺少原明确审批。');
const bytes = Buffer.from(value.download.bytes ?? '', 'base64'); if (bytes.length > 6 * 1024 * 1024) throw conflict('下载超过6MiB范围。');
const bytes = Buffer.from(value.download.bytes ?? '', 'base64'); if (bytes.length > ceiling(this.store, 6 * 1024 * 1024)) throw conflict('下载超过6MiB范围。');
browsingUrl(value.download.url, this.scope(tab)); if (value.download.url !== job.input.url) throw conflict('实际下载地址与原审批不符。');
const artifact = this.artifact(session, job.runId, bytes, 'browsing-download', 'application/octet-stream'); job.downloadArtifactId = artifact.id; job.downloadSha256 = artifact.sha256;
result = { artifactId: artifact.id, sha256: artifact.sha256, bytes: bytes.length, url: value.download.url };
@@ -168,10 +170,10 @@ export class BrowsingManager {
job.reconciliation = { at: at(), result: 'user_retained_original_unknown' }; this.store.save(session, { type: 'browsing.unknown_retained' });
}
snapshot(session) {
return { available: this.available().length > 0, tabs: [...this.store.core.browsing_tab.values()].filter(tab => tab.sessionId === session.id && tab.taskId === session.taskId).slice(-16),
profiles: [...this.store.core.browsing_profile.values()].filter(profile => profile.sessionId === session.id && profile.persistent).slice(-16),
observations: [...this.store.core.browsing_observation.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId).slice(-16),
actions: [...this.store.core.browsing_action.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId).slice(-24) };
return { available: this.available().length > 0, tabs: [...this.store.core.browsing_tab.values()].filter(tab => tab.sessionId === session.id && tab.taskId === session.taskId).slice(-ceiling(this.store, 16)),
profiles: [...this.store.core.browsing_profile.values()].filter(profile => profile.sessionId === session.id && profile.persistent).slice(-ceiling(this.store, 16)),
observations: [...this.store.core.browsing_observation.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId).slice(-ceiling(this.store, 16)),
actions: [...this.store.core.browsing_action.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId).slice(-ceiling(this.store, 24)) };
}
toolSnapshot(session) {
const value = this.snapshot(session);
+3 -2
View File
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
@@ -13,7 +14,7 @@ export async function inspectBuild(project, directory, { signal } = {}) {
const root = safePath(project, directory), files = []; let bytes = 0;
if (fs.lstatSync(root).isSymbolicLink() || !fs.statSync(root).isDirectory()) throw browserError('构建预览需要常规文件夹,不能使用链接。');
const walk = async (relative = '', depth = 0) => {
if (depth > 12) throw browserError('构建目录超过12层,请缩小预览范围。');
if (!unrestricted(project) && depth > 12) throw browserError('构建目录超过12层,请缩小预览范围。');
for (const entry of (await fs.promises.readdir(path.join(root, relative), { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
signal?.throwIfAborted();
const name = (relative ? relative + '/' : '') + entry.name;
@@ -22,7 +23,7 @@ export async function inspectBuild(project, directory, { signal } = {}) {
if (info.isSymbolicLink()) throw browserError('构建文件不能通过链接读取。');
if (info.isDirectory()) { await walk(name, depth + 1); continue; }
if (!info.isFile() || !PREVIEW_MIME[path.extname(name).toLowerCase()]) throw browserError('构建目录包含不支持的静态文件:' + name);
if (info.size > BROWSER_LIMITS.fileBytes || bytes + info.size > BROWSER_LIMITS.bytes || files.length >= BROWSER_LIMITS.files) throw browserError('构建预览上限为512文件、32MB,单文件8MB。');
if (!unrestricted(project) && (info.size > BROWSER_LIMITS.fileBytes || bytes + info.size > BROWSER_LIMITS.bytes || files.length >= BROWSER_LIMITS.files)) throw browserError('构建预览上限为512文件、32MB,单文件8MB。');
const content = await fs.promises.readFile(candidate);
if (content.length !== info.size) throw browserError('构建文件在读取期间变化,请重新准备预览。');
bytes += content.length; files.push({ path: name, bytes: content.length, sha256: browserHash(content) });
+3 -2
View File
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../shared/contracts/execution-policy.mjs';
import fs from 'node:fs';
import path from 'node:path';
import { runOwnedCommand } from './owned-command.mjs';
@@ -246,12 +247,12 @@ export class CheckRunner {
const isPython = check.engine === 'python';
try { invocation = isPython ? await preparePythonInvocation(check, project, { signal }) : npmInvocation(check.name, this.runtimeDirectory); }
catch (error) { return { status: signal.aborted ? 'cancelled' : error.status === 409 ? 'stale' : 'failed', exitCode: null, durationMs: Date.now() - started, tests: null, stdout: '', stderr: error.message, reason: error.message }; }
const result = await runOwnedCommand(invocation,{cwd:safePath(project),signal,onSpawn,timeoutMs:this.timeoutMs,
const result = await runOwnedCommand(invocation,{cwd:safePath(project),signal,onSpawn,timeoutMs:unrestricted(this.store)?0:this.timeoutMs,unlimitedOutput:unrestricted(this.store),
env:isPython ? pythonEnvironment() : projectEnvironment({NO_COLOR:'1',CI:'1'}),input:isPython?invocation.input:null});
let collectedEvidence=null,collectedResult=null,evidenceError=null,cleanupError=null;
const unknown=result.status==='unknown';
if(isPython && !unknown && result.exitCode!==null) {
try { const saved=readPythonEvidence(invocation,result.exitCode);collectedEvidence=saved.text;collectedResult=saved.result; }
try { const saved=readPythonEvidence(invocation,result.exitCode,this.store.config);collectedEvidence=saved.text;collectedResult=saved.result; }
catch(error){evidenceError=error.message;}
}
const tests=check.kind==='test' ? isPython?collectedResult?.tests??null:parseTestEvidence(result.stdout.slice(-240000),check.framework) : null;
+1 -1
View File
@@ -61,7 +61,7 @@ export class IndexCache {
if (envelope.schemaVersion !== 1 || hash(JSON.stringify(envelope.payload)) !== envelope.sha256) return { entries: null, reason: 'corrupt' };
const payload = envelope.payload;
if (JSON.stringify(payload.identity) !== JSON.stringify(identity)) return { entries: null, reason: 'identity-changed' };
if (!Array.isArray(payload.entries) || payload.entries.length > 1000) return { entries: null, reason: 'corrupt' };
if (!Array.isArray(payload.entries) || payload.entries.length > (this.maximumProjects === Infinity ? Infinity : 1000)) return { entries: null, reason: 'corrupt' };
return { entries: new Map(payload.entries.map(entry => [entry.path, entry])), reason: 'disk' };
} catch { this.error = '派生缓存读取失败;本次从当前源码重建。'; return { entries: null, reason: 'unavailable' }; }
}
+12 -11
View File
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
import { randomUUID } from 'node:crypto';
import { PNG } from 'pngjs';
import jpeg from 'jpeg-js';
@@ -78,23 +79,23 @@ function sentImage(decoded, orientation, maximum) {
}
return { bytes:PNG.sync.write(output),width,height };
}
export function validateImage(input) {
export function validateImage(input, config = {}) {
if (!input || Object.keys(input).some(key => !['name','mediaType','base64'].includes(key)) || typeof input.name !== 'string' || !input.name.trim() || input.name.length > 160
|| /[\\/\x00-\x1f]/.test(input.name) || !['image/png','image/jpeg'].includes(input.mediaType) || typeof input.base64 !== 'string') throw reject('请选择PNG或JPEG图片,文件名不能包含路径。');
if (input.base64.length > Math.ceil(IMAGE_LIMITS.bytes / 3) * 4) throw reject('单张图片最多2MB,请先裁剪或压缩。',413);
if (input.base64.length > Math.ceil(ceiling(config, IMAGE_LIMITS.bytes) / 3) * 4) throw reject('单张图片最多2MB,请先裁剪或压缩。',413);
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(input.base64)) throw reject('图片编码无效。');
const bytes = Buffer.from(input.base64,'base64');
if (bytes.length > IMAGE_LIMITS.bytes) throw reject('单张图片最多2MB,请先裁剪或压缩。',413);
if (bytes.length > ceiling(config, IMAGE_LIMITS.bytes)) throw reject('单张图片最多2MB,请先裁剪或压缩。',413);
if (!bytes.length || bytes.toString('base64') !== input.base64) throw reject('图片编码或大小无效。');
const size = dimensions(bytes,input.mediaType);
if (!size.width || !size.height || Math.max(size.width,size.height)>IMAGE_LIMITS.dimension || size.width*size.height>IMAGE_LIMITS.pixels) throw reject('图片尺寸过大,请裁剪后再添加。',413);
if (!size.width || !size.height || Math.max(size.width,size.height)>ceiling(config, IMAGE_LIMITS.dimension) || size.width*size.height>ceiling(config, IMAGE_LIMITS.pixels)) throw reject('图片尺寸过大,请裁剪后再添加。',413);
let decoded;
try { decoded = input.mediaType==='image/png' ? PNG.sync.read(bytes,{checkCRC:true}) : jpeg.decode(bytes,{useTArray:true,tolerantDecoding:false,maxResolutionInMP:16.8,maxMemoryUsageInMB:160}); }
try { decoded = input.mediaType==='image/png' ? PNG.sync.read(bytes,{checkCRC:true}) : jpeg.decode(bytes,{useTArray:true,tolerantDecoding:false,maxResolutionInMP:ceiling(config,16.8),maxMemoryUsageInMB:ceiling(config,160)}); }
catch { throw reject('图片无法完整解码,请重新导出PNG/JPEG。'); }
if (decoded.width!==size.width || decoded.height!==size.height) throw reject('图片实际尺寸不一致。');
let maximum = IMAGE_LIMITS.sentDimension, sent = sentImage(decoded,size.orientation,maximum);
while(sent.bytes.length>IMAGE_LIMITS.sentBytes && maximum>64) { maximum=Math.floor(maximum*0.75);sent=sentImage(decoded,size.orientation,maximum); }
if(sent.bytes.length>IMAGE_LIMITS.sentBytes)throw reject('图片发送副本超过大小限制,请先裁剪。',413);
let maximum = unrestricted(config) ? Math.max(decoded.width, decoded.height) : IMAGE_LIMITS.sentDimension, sent = sentImage(decoded,size.orientation,maximum);
while(sent.bytes.length>ceiling(config, IMAGE_LIMITS.sentBytes) && maximum>64) { maximum=Math.floor(maximum*0.75);sent=sentImage(decoded,size.orientation,maximum); }
if(sent.bytes.length>ceiling(config, IMAGE_LIMITS.sentBytes))throw reject('图片发送副本超过大小限制,请先裁剪。',413);
return { bytes, sent:sent.bytes, width:size.width,height:size.height,orientation:size.orientation,sentWidth:sent.width,sentHeight:sent.height };
}
@@ -103,8 +104,8 @@ export class InputAttachments {
list(session) { return [...this.store.core.input_attachment.values()].filter(row=>row.sessionId===session.id && ['draft','attached'].includes(row.status)).map(row=>structuredClone(row)); }
upload(session,input) {
if(this.busy(session.projectId))throw reject('请等待当前项目执行结束后再添加附件。',409);
if(this.list(session).filter(row=>row.status==='draft').length>=IMAGE_LIMITS.drafts)throw reject('待发送图片已满,请先移除不用的图片。',409);
const value=validateImage(input),identity={id:session.id,projectId:session.projectId,taskId:null,runId:null};
if(this.list(session).filter(row=>row.status==='draft').length>=ceiling(this.store, IMAGE_LIMITS.drafts))throw reject('待发送图片已满,请先移除不用的图片。',409);
const value=validateImage(input, this.store.config),identity={id:session.id,projectId:session.projectId,taskId:null,runId:null};
const original=this.store.artifactStore.write(identity,null,value.bytes,{kind:'input-image-original',mediaType:input.mediaType});
const sent=this.store.artifactStore.write(identity,null,value.sent,{kind:'input-image-sent',mediaType:'image/png'});
this.store.core.artifact.set(original.id,original);this.store.core.artifact.set(sent.id,sent);
@@ -120,7 +121,7 @@ export class InputAttachments {
row.status='withdrawn';this.store.save(session,{type:'input_attachment.withdrawn'});return this.list(session);
}
validateSelection(session,ids) {
if(!Array.isArray(ids)||ids.length>IMAGE_LIMITS.perTask||new Set(ids).size!==ids.length)throw reject('每个任务当前支持一张图片。');
if(!Array.isArray(ids)||ids.length>ceiling(this.store, IMAGE_LIMITS.perTask)||new Set(ids).size!==ids.length)throw reject('每个任务当前支持一张图片。');
return ids.map(id=>{const row=this.get(session,id);if(row.status!=='draft')throw reject('图片已发送或移除,请重新选择。',409);this.read(session,id);this.read(session,id,{original:true});return row;});
}
read(session,id,{original=false}={}) {
+16 -14
View File
@@ -15,7 +15,7 @@ const names = { FunctionDeclaration: 'function', FunctionExpression: 'function',
const parserVersion = 'babel-parser-7.29.11';
const nodeName = node => node?.type === 'Identifier' ? node.name : node?.type === 'PrivateName' ? '#' + node.id.name : node?.type === 'StringLiteral' ? node.value : null;
function javascript(source, filename, maximumNodes, maximumSymbols) {
function javascript(source, filename, maximumNodes, maximumSymbols, open = false) {
const plugins = [...(/\.(?:[mc]?ts|tsx)$/i.test(filename) ? ['typescript'] : []), ...(/\.(?:[mc]?js|jsx|tsx)$/i.test(filename) ? ['jsx'] : []), 'decorators-legacy'];
const ast = parse(source, { sourceType: 'unambiguous', plugins, createImportExpressions: true, allowReturnOutsideFunction: true, allowAwaitOutsideFunction: true });
const exported = new Set(), exportNames = new Set(), topLevel = new Set();
@@ -58,8 +58,8 @@ function javascript(source, filename, maximumNodes, maximumSymbols) {
else if (node.type === 'ImportExpression') { sourceNode = node.source; importKind = 'literal-dynamic-import'; }
else if (node.type === 'CallExpression' && node.callee?.type === 'Identifier' && node.callee.name === 'require') { sourceNode = node.arguments[0]; importKind = 'literal-require-call'; }
else if (node.type === 'TSImportEqualsDeclaration' && node.moduleReference?.type === 'TSExternalModuleReference') { sourceNode = node.moduleReference.expression; importKind = 'import-equals'; }
if (sourceNode?.type === 'StringLiteral' && imports.length < 400) imports.push({ source: sourceNode.value.slice(0, 500), line: node.loc.start.line,
kind: importKind, bindings: node.type === 'TSImportEqualsDeclaration' ? [nodeName(node.id)].filter(Boolean) : (node.specifiers ?? []).map(value => nodeName(value.local)).filter(Boolean).slice(0, 30), evidenceMethod: 'javascript-typescript-ast' });
if (sourceNode?.type === 'StringLiteral' && imports.length < (open ? Infinity : 400)) imports.push({ source: sourceNode.value.slice(0, open ? Infinity : 500), line: node.loc.start.line,
kind: importKind, bindings: node.type === 'TSImportEqualsDeclaration' ? [nodeName(node.id)].filter(Boolean) : (node.specifiers ?? []).map(value => nodeName(value.local)).filter(Boolean).slice(0, open ? Infinity : 30), evidenceMethod: 'javascript-typescript-ast' });
else if (sourceNode) { truncated = true; if (sourceNode.type !== 'StringLiteral') opaqueImports++; }
let childScope = scope;
if (name && (names[node.type] && ['function', 'class'].includes(kind) || node.type === 'VariableDeclarator' && kind === 'function' || kind === 'method')) childScope = [...scope, name];
@@ -72,7 +72,7 @@ function javascript(source, filename, maximumNodes, maximumSymbols) {
// This lexer only removes comments and string bodies so declaration candidates
// do not come from docstrings. It is deliberately not a Python compiler.
function python(source, maximumSymbols) {
function python(source, maximumSymbols, open = false) {
let triple = null, quote = null, escaped = false, truncated = false, bracketDepth = 0, lineContinuation = false;
const symbols = [], imports = [], scopes = [];
const lines = source.split('\n');
@@ -109,7 +109,7 @@ function python(source, maximumSymbols) {
if (imported) {
const sources = imported[1] ? [imported[1]] : imported[3].split(',').map(value => value.trim().split(/\s+/)[0]);
for (const source of sources) if (source) {
if (imports.length < 400) imports.push({ source: source.slice(0, 500), line: index + 1, kind: 'python-import-candidate', bindings: [], evidenceMethod: 'python-declaration-candidate' });
if (imports.length < (open ? Infinity : 400)) imports.push({ source: source.slice(0, open ? Infinity : 500), line: index + 1, kind: 'python-import-candidate', bindings: [], evidenceMethod: 'python-declaration-candidate' });
else truncated = true;
}
}
@@ -143,7 +143,9 @@ function resolveImport(from, dependency, files) {
export class ProjectIndex {
constructor({ maximumProjects = 8, maximumFileBytes = 256000, maximumSymbols = 6000, maximumSymbolsPerFile = 300, maximumAstNodes = 80000,
cacheDirectory, maximumCacheBytes = 32 * 1024 * 1024, maximumEntryBytes = 8 * 1024 * 1024, parserRevision = 'index-2-python-candidates-1' } = {}) {
cacheDirectory, maximumCacheBytes = 32 * 1024 * 1024, maximumEntryBytes = 8 * 1024 * 1024, executionMode = 'restricted', parserRevision = 'index-2-python-candidates-1' } = {}) {
this.open = executionMode === 'unrestricted';
if (this.open) maximumProjects = maximumFileBytes = maximumSymbols = maximumSymbolsPerFile = maximumAstNodes = maximumCacheBytes = maximumEntryBytes = Infinity;
this.maximumProjects = maximumProjects; this.maximumFileBytes = maximumFileBytes; this.maximumSymbols = maximumSymbols;
this.maximumSymbolsPerFile = maximumSymbolsPerFile; this.maximumAstNodes = maximumAstNodes;
this.projects = new Map(); this.pending = new Map(); this.identities = new Map(); this.latest = new Map(); this.memoryBytes = new Map(); this.generation = 0;
@@ -189,7 +191,7 @@ export class ProjectIndex {
const text = readText(project, file.path);
if (text.sha256 !== file.sha256) throw conflict('建立索引期间文件已变化,请刷新工程索引:' + file.path);
const parseStarted = performance.now(); parsedFiles++;
try { Object.assign(entry, js.test(file.path) ? javascript(text.content, file.path, this.maximumAstNodes, this.maximumSymbolsPerFile) : python(text.content, this.maximumSymbolsPerFile)); }
try { Object.assign(entry, js.test(file.path) ? javascript(text.content, file.path, this.maximumAstNodes, this.maximumSymbolsPerFile, this.open) : python(text.content, this.maximumSymbolsPerFile, this.open)); }
finally { parseMs += performance.now() - parseStarted; }
entry.status = entry.truncated ? 'partial' : 'indexed';
} catch (error) {
@@ -212,7 +214,7 @@ export class ProjectIndex {
const allSymbols = entries.flatMap(file => file.symbols.map(value => ({ ...value, path: file.path, sha256: file.sha256, language: file.language })));
const symbols = allSymbols.slice(0, this.maximumSymbols).sort((a, b) => a.path.localeCompare(b.path) || a.line - b.line || a.name.localeCompare(b.name));
const allImports = entries.flatMap(file => file.imports.map(value => resolveImport(file.path, value, available)));
const imports = allImports.slice(0, 6000);
const imports = allImports.slice(0, this.open ? Infinity : 6000);
const removedFiles = [...previous.keys()].filter(file => !next.has(file)).length;
const entryBytes = Buffer.byteLength(JSON.stringify([...next.values()])), withinCapacity = entryBytes <= Math.min(this.cache.maximumEntryBytes, this.cache.maximumBytes);
const canStore = this.cache.enabled && inspection.scope.complete && generation === this.generation && withinCapacity;
@@ -251,21 +253,21 @@ export class ProjectIndex {
sourceScope: index.sourceScope, warnings: index.warnings.slice(0, 20), notes: index.notes, ...(index.cache ? { cache: index.cache } : {}) };
}
validEntry(entry) {
const bounded = value => typeof value === 'string' && value.length <= 10000;
const bounded = value => typeof value === 'string' && value.length <= (this.open ? Infinity : 10000);
return Array.isArray(entry.symbols) && entry.symbols.length <= this.maximumSymbolsPerFile
&& entry.symbols.every(value => value && bounded(value.name) && bounded(value.qualifiedName) && bounded(value.kind) && bounded(value.signature)
&& Number.isInteger(value.column) && value.column > 0 && Number.isInteger(value.line) && value.line > 0
&& Number.isInteger(value.endLine) && value.endLine >= value.line && typeof value.exported === 'boolean' && bounded(value.evidenceMethod))
&& Array.isArray(entry.imports) && entry.imports.length <= 400
&& Array.isArray(entry.imports) && entry.imports.length <= (this.open ? Infinity : 400)
&& entry.imports.every(value => value && bounded(value.source) && bounded(value.kind) && bounded(value.evidenceMethod) && Number.isInteger(value.line) && value.line > 0
&& Array.isArray(value.bindings) && value.bindings.length <= 30 && value.bindings.every(bounded))
&& Array.isArray(value.bindings) && value.bindings.length <= (this.open ? Infinity : 30) && value.bindings.every(bounded))
&& ['metadata-only', 'indexed', 'partial', 'outside-index-budget'].includes(entry.status)
&& ['file-sha256', 'javascript-typescript-ast', 'python-declaration-candidate'].includes(entry.method)
&& typeof entry.truncated === 'boolean';
}
query(index, { query = '', kind = 'all', limit = 30 } = {}) {
if (typeof query !== 'string' || query.length > 200 || !['all', 'symbols', 'imports', 'files'].includes(kind)
|| !Number.isInteger(limit) || limit < 1 || limit > 60) throw new Error('索引查询需要200字以内文本、有效类型与1到60条结果上限。');
query(index, { query = '', kind = 'all', limit = this.open ? Infinity : 30 } = {}) {
if (typeof query !== 'string' || query.length > (this.open ? Infinity : 200) || !['all', 'symbols', 'imports', 'files'].includes(kind)
|| !(this.open && limit === Infinity) && (!Number.isSafeInteger(limit) || limit < 1 || !this.open && limit > 60)) throw new Error('索引查询需要200字以内文本、有效类型与1到60条结果上限。');
const terms = query.trim().toLocaleLowerCase().split(/\s+/).filter(Boolean);
const score = (name, filename) => {
const lower = name.toLocaleLowerCase(), all = (name + ' ' + filename).toLocaleLowerCase();
+6 -2
View File
@@ -11,7 +11,7 @@ const pooledReads = calls => calls?.length && calls.every(isPagedRead) && (calls
// This is the actual tool page, not a rewrite of a historical result. Count
// the escaped JSON tool message which will be present in the next request.
export function artifactPage(artifact, text, args, { maximumMessageBytes = 16000, callId = '' } = {}) {
const requestedOffset = args.offset ?? 0, requestedLimit = args.limit ?? 2000;
const requestedOffset = args.offset ?? 0, requestedLimit = args.limit ?? (maximumMessageBytes === Infinity ? text.length : 2000);
let offset = Math.min(requestedOffset, text.length);
if (offset > 0 && /[\uDC00-\uDFFF]/.test(text[offset]) && /[\uD800-\uDBFF]/.test(text[offset - 1])) offset--;
let maximumEnd = boundary(text, Math.min(offset + requestedLimit, text.length));
@@ -32,6 +32,7 @@ export function artifactPage(artifact, text, args, { maximumMessageBytes = 16000
}
export function readMessageBudget(plan, message) {
if (plan.budget.inputBudget === null) return Infinity;
const calls = message.tool_calls?.length ?? 1;
const assistantTokens = Math.ceil(Buffer.byteLength(JSON.stringify(message), 'utf8') / 3) + 8;
// Reserve space for the current call's framing and the next state/notice.
@@ -46,7 +47,10 @@ export function readMessageBudget(plan, message) {
// read. Mixed batches and historical plans retain the original 2560 reserve.
// This is page sizing, never dispatch authorization: the complete next wire
// request and observed-usage reservation are still checked independently.
const growth = Math.max(plan.readStateGrowthTokens ?? 0, pureReads ? 512 + Math.min(2048, Math.max(0, calls - 1) * 256) : 2560);
// Browser fields do not grow source-page coverage. Keep the larger source
// reservation for file/artifact reads without shrinking a small browser page.
const browserOnly = message.tool_calls?.length && message.tool_calls.every(call => call.function.name === 'read_browser_result');
const growth = Math.max(browserOnly ? 0 : plan.readStateGrowthTokens ?? 0, pureReads ? 512 + Math.min(2048, Math.max(0, calls - 1) * 256) : 2560);
const tokens = plan.budget.inputBudget - (plan.nextReadFixedInputTokens ?? plan.mandatoryInputTokens) - (plan.workingRetentionTokens ?? 0) - assistantTokens - calls * 8 - growth;
return Math.max(1024, Math.floor(tokens * 3 / calls));
}
+33 -23
View File
@@ -9,6 +9,7 @@ import { mcpCatalogMessage, MCP_LIMITS } from '../tools/mcp-contract.mjs';
import { modelReservation,taskConsumption,verifyModelReservation } from '../../shared/contracts/model-reservation.mjs';
import { fileContinuation } from './read-continuation.mjs';
import { prefixAudit } from './prefix-audit.mjs';
import { isPassthrough } from '../../shared/contracts/model-capacity.mjs';
const hash = value => createHash('sha256').update(typeof value === 'string' ? value : JSON.stringify(value), 'utf8').digest('hex');
const PLACEHOLDER_ID = '00000000-0000-0000-0000-000000000000';
@@ -61,6 +62,14 @@ export function budgetFor(config, run, task, transportReservationTokens = 0) {
const runRemainingTokens = remaining(run?.budget?.maxTokens, run?.usage);
const taskRemainingTokens = remaining(task?.budget?.maxTokens, task?.usage);
if(!Number.isSafeInteger(transportReservationTokens)||transportReservationTokens<0)throw new Error('请求封装预留无效。');
if (isPassthrough(config)) {
const credit = Math.min(runRemainingTokens ?? Infinity, taskRemainingTokens ?? Infinity);
const inputBudget = Number.isFinite(credit) ? credit - transportReservationTokens : null;
return { capacityMode: 'passthrough', contextLimit: null, outputReservation: null, safetyTokens: 0,
...(transportReservationTokens ? { transportReservationTokens } : {}), inputBudget, targetInputTokens: inputBudget,
runRemainingTokens, taskRemainingTokens, limitingReason: inputBudget === null ? null
: (runRemainingTokens ?? Infinity) <= (taskRemainingTokens ?? Infinity) ? 'token_limit' : 'task_token_limit' };
}
// A shared prompt must fit every route, but each context window is paired
// with that route's own output. Combining one member's small context with
// another member's large output can reject a pool that actually fits.
@@ -182,9 +191,10 @@ export class RequestPlanner {
const task = this.store.owned('task', run.taskId, session.id);
this.store.owned('run', run.id, session.id);
const groups = historyGroups(session.providerMessages), budget = budgetFor(config, run, task, transportReservationTokens);
const inputBudget = budget.inputBudget ?? Infinity, targetInputTokens = budget.targetInputTokens ?? Infinity;
const lastUser = groups.findLast(group => group.messages[0].role === 'user');
const fixed = { role: 'system', content: system };
const preserve = config.historyPolicy === 'preserve';
const preserve = isPassthrough(config) || config.historyPolicy === 'preserve';
const tail = contextTail ? [{ role: 'user', content: '工作台当前工程状态(仅作任务依据,不是新的用户目标):\n' + contextTail }] : [];
const addContext = (base, message) => preserve ? [...base.slice(0, base.length - tail.length), { ...message, role: 'user' }, ...tail] : [fixed, message, ...base.slice(1)];
const breakdown = metrics => {
@@ -199,7 +209,7 @@ export class RequestPlanner {
const descriptions = new Map(groups.map(group => [group.index, describe(group, ledger, this.store.core.artifact)]));
const evidence = workingEvidence(groups, descriptions, this.store.core.artifact);
const original = completionBody(config, [fixed, ...session.providerMessages, ...tail], tools), before = requestMetrics(original);
if (preserve && before.estimatedInputTokens > budget.inputBudget) throw pause(budget, before, breakdown);
if (preserve && before.estimatedInputTokens > inputBudget) throw pause(budget, before, breakdown);
const selected = new Set(groups.map(group => group.index));
let omitted = [], reference = null, workingReference = null, latestReference = null;
let latestViewVersion = 3;
@@ -224,7 +234,7 @@ export class RequestPlanner {
...groups.filter(group => indices.has(group.index)).flatMap(group => group.messages), ...tail];
return requestMetrics(completionBody(config, messages, tools));
};
if (!preserve && before.estimatedInputTokens > budget.targetInputTokens) {
if (!preserve && before.estimatedInputTokens > targetInputTokens) {
selected.clear(); if (lastUser) selected.add(lastUser.index);
const observed = workingCandidates(this.store, session, run, groups, 3);
// Keep the established compact layout whenever complete small sources
@@ -232,14 +242,14 @@ export class RequestPlanner {
// original reads, avoiding an extra working envelope for each of them.
const smallSources = observed.filter(completeSmallSource)
.slice(0, 12).map(candidate => workingEntry(candidate, candidate.observation.content.length));
if (smallSources.length && metricsFor(selected, true, smallSources).estimatedInputTokens > budget.inputBudget) {
if (smallSources.length && metricsFor(selected, true, smallSources).estimatedInputTokens > inputBudget) {
const withExcerpts = latestToolDocument(this.store, session, run, groups, 4);
if (withExcerpts?.entries.some(entry => typeof entry.result.content_excerpt === 'string')) {
latestViewVersion = 4; latestDocument = withExcerpts;
}
}
const mandatory = metricsFor(selected);
if (mandatory.estimatedInputTokens > budget.inputBudget) throw pause(budget, mandatory, breakdown);
if (mandatory.estimatedInputTokens > inputBudget) throw pause(budget, mandatory, breakdown);
const coveredByRaw = entry => (entry.fragments ?? [entry.source]).every(source => selected.has(source.group_index));
// A complete small read can travel with its latest result. Do not spend
// another provenance envelope to repeat those same source bytes. Longer
@@ -250,12 +260,12 @@ export class RequestPlanner {
// Admit complete small source observations before optional raw history.
// A reservation alone does not keep code in the actual sent request.
const newest = groups.at(-1);
const retentionTarget = budget.inputBudget;
const retentionTarget = inputBudget;
// Preserve the entire newly returned pure-read pair when it fits. Large
// accumulated ranges must not consume the next page's protocol slot.
if (newest?.messages[0].tool_calls?.length && newest.messages[0].tool_calls.every(call => call.function.name === 'read_file')) {
selected.add(newest.index);
if (metricsFor(selected).estimatedInputTokens > budget.inputBudget) selected.delete(newest.index);
if (metricsFor(selected).estimatedInputTokens > inputBudget) selected.delete(newest.index);
}
for (const candidate of observed.filter(completeSmallSource)) {
if (entries.length >= 12) break;
@@ -270,13 +280,13 @@ export class RequestPlanner {
if (message.role !== 'tool') return true;
try { const result = JSON.parse(message.content); return !result.kind?.startsWith('context-') && result.kind !== 'tool-result'; } catch { return true; }
});
if (newestUseful && !selected.has(newest.index) && newest.contributionTokens <= budget.inputBudget) {
if (newestUseful && !selected.has(newest.index) && newest.contributionTokens <= inputBudget) {
selected.add(newest.index);
const remaining = entries.filter(entry => !coveredByRaw(entry));
if (metricsFor(selected, true, remaining).estimatedInputTokens > budget.inputBudget) selected.delete(newest.index);
if (metricsFor(selected, true, remaining).estimatedInputTokens > inputBudget) selected.delete(newest.index);
else entries.splice(0, entries.length, ...remaining);
}
const target = Math.max(budget.targetInputTokens, metricsFor(selected).estimatedInputTokens);
const target = Math.max(targetInputTokens, metricsFor(selected).estimatedInputTokens);
const priority = [...new Set(evidence.map(value => value.group_index))].map(index => groups[index]);
const addGroup = group => {
if (selected.has(group.index) || selected.size >= 32 || group.contributionTokens > target) return;
@@ -329,11 +339,11 @@ export class RequestPlanner {
let mcpReference = null, mcpDocument = null;
if (mcpCatalog?.projectId === session.projectId && mcpCatalog.entries?.length) {
mcpDocument = { ...mcpCatalog, sessionId: session.id, taskId: run.taskId, runId: run.id, entries: [] };
for (const entry of mcpCatalog.entries.slice(0, MCP_LIMITS.allowedTools)) {
for (const entry of mcpCatalog.entries.slice(0, isPassthrough(config) ? Infinity : MCP_LIMITS.allowedTools)) {
mcpDocument.entries.push(entry);
const candidate = addContext(messages, mcpCatalogMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, mcpDocument));
if (Buffer.byteLength(JSON.stringify(mcpDocument), 'utf8') > 24000
|| requestMetrics(completionBody(config, candidate, tools)).estimatedInputTokens > Math.min(budget.inputBudget, budget.targetInputTokens)) mcpDocument.entries.pop();
if (Buffer.byteLength(JSON.stringify(mcpDocument), 'utf8') > (isPassthrough(config) ? Infinity : 24000)
|| requestMetrics(completionBody(config, candidate, tools)).estimatedInputTokens > Math.min(inputBudget, targetInputTokens)) mcpDocument.entries.pop();
}
if (mcpDocument.entries.length) {
mcpReference = this.artifact(session, run, mcpDocument, 'context-mcp-catalog');
@@ -343,11 +353,11 @@ export class RequestPlanner {
let skillReference = null, skillDocument = null;
if (skillCatalog?.projectId === session.projectId && skillCatalog.entries?.length) {
skillDocument = { ...skillCatalog, sessionId: session.id, taskId: run.taskId, runId: run.id, entries: [] };
for (const entry of skillCatalog.entries.slice(0, SKILL_LIMITS.enabled)) {
for (const entry of skillCatalog.entries.slice(0, isPassthrough(config) ? Infinity : SKILL_LIMITS.enabled)) {
skillDocument.entries.push(entry);
const candidate = addContext(messages, skillCatalogMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, skillDocument));
if (Buffer.byteLength(JSON.stringify(skillDocument), 'utf8') > SKILL_LIMITS.catalogBytes
|| requestMetrics(completionBody(config, candidate, tools)).estimatedInputTokens > Math.min(budget.inputBudget, budget.targetInputTokens)) skillDocument.entries.pop();
if (Buffer.byteLength(JSON.stringify(skillDocument), 'utf8') > (isPassthrough(config) ? Infinity : SKILL_LIMITS.catalogBytes)
|| requestMetrics(completionBody(config, candidate, tools)).estimatedInputTokens > Math.min(inputBudget, targetInputTokens)) skillDocument.entries.pop();
}
if (skillDocument.entries.length) {
skillReference = this.artifact(session, run, skillDocument, 'context-skill-catalog');
@@ -358,12 +368,12 @@ export class RequestPlanner {
let memoryReference = null, memoryDocument = null;
if (projectMemory?.projectId === session.projectId && projectMemory.entries?.length) {
memoryDocument = { ...projectMemory, sessionId: session.id, taskId: run.taskId, runId: run.id, entries: [] };
const memoryBudget = Math.min(budget.inputBudget, budget.targetInputTokens);
for (const entry of projectMemory.entries.slice(0, MEMORY_CONTEXT_LIMITS.entries)) {
const memoryBudget = Math.min(inputBudget, targetInputTokens);
for (const entry of projectMemory.entries.slice(0, isPassthrough(config) ? Infinity : MEMORY_CONTEXT_LIMITS.entries)) {
if (entry.sourceFingerprint !== projectMemory.sourceFingerprint) continue;
memoryDocument.entries.push(entry);
const candidate = addContext(messages, projectMemoryMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, memoryDocument));
if (Buffer.byteLength(JSON.stringify(memoryDocument), 'utf8') > MEMORY_CONTEXT_LIMITS.bytes
if (Buffer.byteLength(JSON.stringify(memoryDocument), 'utf8') > (isPassthrough(config) ? Infinity : MEMORY_CONTEXT_LIMITS.bytes)
|| requestMetrics(completionBody(config, candidate, tools)).estimatedInputTokens > memoryBudget) memoryDocument.entries.pop();
}
if (memoryDocument.entries.length) {
@@ -372,7 +382,7 @@ export class RequestPlanner {
}
}
const body = completionBody(config, messages, tools), metrics = requestMetrics(body);
if (metrics.estimatedInputTokens > budget.inputBudget) throw pause(budget, metrics, breakdown);
if (metrics.estimatedInputTokens > inputBudget) throw pause(budget, metrics, breakdown);
const tokenReservation=engineStepOnly?null:modelReservation(config,body,taskConsumption(this.store,task.id));
const runCredit=budget.runRemainingTokens??Infinity,taskCredit=budget.taskRemainingTokens??Infinity,credit=Math.min(runCredit,taskCredit);
if(tokenReservation&&tokenReservation.reservedTokens>credit)throw pause({...budget,limitingReason:runCredit<=taskCredit?'token_limit':'task_token_limit',
@@ -453,7 +463,7 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
|| Math.max(...requestVariants(body).map(outputReservation)) !== plan.budget.outputReservation
: requestVariants(body).some(value => outputReservation(value) !== plan.budget.outputReservation);
if (metrics.bytes !== plan.requestBytes || metrics.estimatedInputTokens !== plan.estimatedInputTokens
|| invalidOutput || metrics.estimatedInputTokens > plan.budget.inputBudget) throw new Error('请求预算与原正文不匹配。');
|| invalidOutput || plan.budget.inputBudget !== null && metrics.estimatedInputTokens > plan.budget.inputBudget) throw new Error('请求预算与原正文不匹配。');
historyGroups(requestHistory(body));
for (const variant of requestVariants(body)) historyGroups(requestHistory(variant));
const frozen = JSON.parse(store.artifactStore.read(get(plan.artifactId, 'context-plan')));
@@ -519,7 +529,7 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
if (artifact.taskId !== plan.taskId || artifact.runId !== plan.runId || document.projectId !== session.projectId
|| document.sessionId !== session.id || document.taskId !== plan.taskId || document.runId !== plan.runId
|| document.kind !== 'source-checked-project-memory' || document.entries.length !== plan.projectMemoryEntries
|| document.entries.length > MEMORY_CONTEXT_LIMITS.entries || Buffer.byteLength(JSON.stringify(document), 'utf8') > MEMORY_CONTEXT_LIMITS.bytes
|| plan.budget.capacityMode !== 'passthrough' && document.entries.length > MEMORY_CONTEXT_LIMITS.entries || plan.budget.capacityMode !== 'passthrough' && Buffer.byteLength(JSON.stringify(document), 'utf8') > MEMORY_CONTEXT_LIMITS.bytes
|| document.entries.some(entry => entry.sourceFingerprint !== document.sourceFingerprint)) throw new Error('项目记忆工件归属或范围不匹配。');
const message = projectMemoryMessage(artifact, document);
if (!carriesContext(message.content)) throw new Error('项目记忆与实际发送内容不匹配。');
@@ -533,7 +543,7 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
if (artifact.taskId !== plan.taskId || artifact.runId !== plan.runId || document.projectId !== session.projectId
|| document.sessionId !== session.id || document.taskId !== plan.taskId || document.runId !== plan.runId
|| document.kind !== 'registered-skill-catalog' || !Array.isArray(document.entries) || document.entries.length !== plan.skillCatalogEntries
|| document.entries.length > SKILL_LIMITS.enabled || Buffer.byteLength(JSON.stringify(document), 'utf8') > SKILL_LIMITS.catalogBytes
|| plan.budget.capacityMode !== 'passthrough' && document.entries.length > SKILL_LIMITS.enabled || plan.budget.capacityMode !== 'passthrough' && Buffer.byteLength(JSON.stringify(document), 'utf8') > SKILL_LIMITS.catalogBytes
|| new Set(document.entries.map(entry => entry.id)).size !== document.entries.length) throw new Error('技能目录归属或范围不匹配。');
const message = skillCatalogMessage(artifact, document);
if (!carriesContext(message.content)) throw new Error('技能目录与实际发送内容不匹配。');
+3 -1
View File
@@ -4,6 +4,7 @@ import { createHash } from 'node:crypto';
import { safePath } from '../../server/files.mjs';
import { assertLocalTree, samePath } from './file-state.mjs';
import { desktopInput, assertDesktopFrame, desktopError } from '../../shared/contracts/desktop-bridge.mjs';
import { ceiling } from '../../shared/contracts/execution-policy.mjs';
export class DesktopBridge {
constructor(controller, { dialog, shell, getWindow, onStopped = () => {} }) { Object.assign(this, { controller, dialog, shell, getWindow, onStopped }); this.pending = new Set(); }
@@ -54,7 +55,8 @@ export class DesktopBridge {
if (action === 'revealFile') {
await this.task(value); const project = await this.project(value.projectId), target = safePath(project, value.path);
assertLocalTree(target); const stat = fs.lstatSync(target);
if (!stat.isFile() || stat.nlink !== 1 || stat.size > 1024 * 1024) throw desktopError('原文件入口只接受当前工程的普通文本文件。');
const { config } = await this.controller.api('/bootstrap');
if (!stat.isFile() || stat.nlink !== 1 || stat.size > ceiling(config, 1024 * 1024)) throw desktopError('原文件入口只接受当前工程的普通文本文件。');
const bytes = fs.readFileSync(target);
if (bytes.includes(0) || createHash('sha256').update(bytes).digest('hex') !== value.sha256) throw desktopError('文件内容已变化或不是文本,请重新读取后定位。');
try { new TextDecoder('utf8', { fatal: true }).decode(bytes); } catch { throw desktopError('当前文件不是UTF-8文本,请先核对编码。'); }
+2 -2
View File
@@ -13,8 +13,8 @@ export const HOST_ENVIRONMENT = Object.freeze(['AGENT_WORKBENCH_DEEPSEEK_ROOT',
async function jsonResponse(response) {
if (!response.ok) throw hostError('本机宿主接口拒绝操作(HTTP ' + response.status + ')。', 'HOST_API_REJECTED', response.status);
const chunks = []; let length = 0;
for await (const chunk of response.body) { length += chunk.length; if (length > 4 * 1024 * 1024) throw hostError('本机宿主响应过大。'); chunks.push(chunk); }
const chunks = [];
for await (const chunk of response.body) chunks.push(chunk);
try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { throw hostError('端口未返回有效的宿主协议。'); }
}
+6 -3
View File
@@ -31,7 +31,7 @@ export async function apply(ctx, config) {
let size = 0; const chunks = [];
for await (const chunk of response.body) {
size += chunk.length;
if (size > config.maximumFrameBytes) throw new Error('Owned bridge response exceeded its bound.');
if (config.maximumFrameBytes !== null && size > config.maximumFrameBytes) throw new Error('Owned bridge response exceeded its bound.');
chunks.push(chunk);
}
const value = JSON.parse(Buffer.concat(chunks).toString('utf8'));
@@ -55,13 +55,16 @@ export async function apply(ctx, config) {
class WorkbenchAdapter extends LlmAdapter {
async resolveModel(provider, model) {
if (provider !== 'agent-workbench' || model !== config.model) throw new Error('Owned model route changed.');
return { provider, id: model, name: model, contextWindow: config.contextLimit, defaultMaxTokens: config.maxOutputTokens };
// Native SDK metadata requires a positive integer. This planning sentinel
// is never sent as an output cap: passthrough stream() omits maxTokens.
return { provider, id: model, name: model, contextWindow: config.contextLimit,
defaultMaxTokens: config.capacityMode === 'passthrough' ? Number.MAX_SAFE_INTEGER : config.maxOutputTokens };
}
async *stream(options) {
if (options.provider !== 'agent-workbench' || options.model !== config.model) throw new Error('Unowned model route.');
const result = await post('/model', { messages: options.messages, system: options.system ?? null,
tools: options.tools ?? [], toolHistory: options.toolHistory ?? null,
model: options.model, maxTokens: options.maxTokens ?? config.maxOutputTokens }, options.signal);
model: options.model, ...(config.capacityMode !== 'passthrough' ? { maxTokens: options.maxTokens ?? config.maxOutputTokens } : {}) }, options.signal);
const message = result.message;
if (result.finishReason === 'length') throw new Error('Owned model output reached its bound; incomplete tools are not executed.');
if (!message || message.role !== 'assistant' || typeof message.content !== 'string'
+12 -7
View File
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
@@ -26,6 +27,7 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
async open({ directory, cwd, owner, sdkSessionId, tools, config, strategy, signal, onModel, onTool, onState = () => {}, onNotification = () => {} }) {
for (const field of ['sessionId', 'projectId', 'taskId', 'runId', 'jobId']) if (!isId(owner?.[field])) throw engineError('受控引擎所属身份无效。', 400);
if (!isId(sdkSessionId) || typeof onModel !== 'function' || typeof onTool !== 'function') throw engineError('受控引擎回调或会话无效。', 400);
if (unrestricted(config)) { this.maximumFrameBytes = Infinity; this.timeoutMs = 0; }
signal?.throwIfAborted(); assertControlledInstallation(this.installation);
assertPurgeStrategy(strategy); this.strategy = structuredClone(strategy);
const catalogue = controlledToolCatalogue(tools), catalogueSha256 = controlledDigest(catalogue);
@@ -51,7 +53,8 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
await new Promise((resolve, reject) => { this.guard.once('error', reject); this.guard.listen(0, '127.0.0.1', resolve); });
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,
maximumFrameBytes: unrestricted(config) ? null : this.maximumFrameBytes, model: config.model, capacityMode: config.capacityMode,
maxOutputTokens: config.capacityMode === 'passthrough' ? null : config.maxOutputTokens, contextLimit: config.capacityMode === 'passthrough' ? Number.MAX_SAFE_INTEGER : config.contextLimit,
...(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),
@@ -59,6 +62,7 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
const env = {};
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' });
if (unrestricted(config)) { this.maximumFrameBytes = Infinity; this.timeoutMs = 0; }
signal?.throwIfAborted(); assertControlledInstallation(this.installation);
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){
@@ -85,7 +89,7 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
let notificationBytes = 0;
this.client.on('notification', value => {
notificationBytes += Buffer.byteLength(JSON.stringify(value));
if (notificationBytes > 16 * 1024 * 1024 || this.report.notifications.length + this.report.unownedNotifications.length >= 8192) {
if (!unrestricted(config) && (notificationBytes > 16 * 1024 * 1024 || this.report.notifications.length + this.report.unownedNotifications.length >= 8192)) {
this.client.fail(engineError('受控引擎事件超过接收范围。')); return;
}
if (!['session.event', 'session.status', 'subagent.started', 'subagent.finished'].includes(value.method)) {
@@ -103,7 +107,8 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
|| (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 });
const initialized = await this.request('initialize', { cwd, provider: 'agent-workbench', model: config.model,
...(config.capacityMode !== 'passthrough' ? { maxTokens: config.maxOutputTokens } : {}) });
if (controlledDigest(initialized.serverInfo) !== controlledDigest(this.installation.serverInfo)) throw engineError('受控SDK返回身份不符合固定发行。');
const working = await this.request('session/working-directory/get', { sessionId: sdkSessionId });
if (fs.realpathSync.native(working.cwd) !== fs.realpathSync.native(cwd)) throw engineError('原SDK工作目录不属于所封存的工作区。');
@@ -142,18 +147,18 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
if (!data || typeof data !== 'object' || Array.isArray(data)) throw engineError('桥调用正文必须是对象。', 400);
if (request.url === '/tool') {
if (Object.keys(data).some(key => !['callId', 'name', 'arguments'].includes(key))
|| typeof data.callId !== 'string' || !data.callId || data.callId.length > 160 || !this.catalogueNames.has(data.name)
|| typeof data.callId !== 'string' || !data.callId || data.callId.length > ceiling(this.config, 160) || !this.catalogueNames.has(data.name)
|| !data.arguments || typeof data.arguments !== 'object' || Array.isArray(data.arguments)) throw engineError('工具调用不符合原目录和参数契约。', 400);
if (this.callIds.has(data.callId)) throw engineError('原引擎工具调用ID已接收,不会重复执行。');
this.callIds.add(data.callId);
} else if (Object.keys(data).some(key => !['messages', 'system', 'tools', 'toolHistory', 'model', 'maxTokens'].includes(key))
|| data.model !== this.config.model || !Array.isArray(data.messages) || !Array.isArray(data.tools)
|| controlledDigest(controlledToolCatalogue(data.tools)) !== this.catalogueSha256
|| !Number.isSafeInteger(data.maxTokens) || data.maxTokens < 1 || data.maxTokens > this.config.maxOutputTokens) {
|| (this.config.capacityMode !== 'passthrough' && (!Number.isSafeInteger(data.maxTokens) || data.maxTokens < 1 || data.maxTokens > this.config.maxOutputTokens))) {
throw engineError('原引擎模型请求与封存的目录、模型或输出预算不一致。', 400);
}
const trace = { id: randomUUID(), route: request.url, requestSha256: controlledDigest(body), requestBytes: size, data: body.data, status: 'received', startedAt: at() };
if (this.report.bridgeRequests.length >= 1024) throw engineError('桥请求次数超过接收范围。');
if (this.report.bridgeRequests.length >= ceiling(this.config, 1024)) throw engineError('桥请求次数超过接收范围。');
this.report.bridgeRequests.push(trace);
const callback = request.url === '/model' ? onModel : onTool;
if (request.url === '/model') this.report.modelRequests++; else this.report.toolRequests++;
@@ -167,7 +172,7 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
async request(method, params = {}) {
this.signal?.throwIfAborted(); this.verifyLaunch();
const result = await this.client.request(method, params, { signal: this.signal,
...(method === 'session/wait' ? { timeoutMs: this.config.maxRunDurationMs ?? 600000 } : {}) });
...(method === 'session/wait' ? { timeoutMs: this.config.maxRunDurationMs === 0 ? 0 : this.config.maxRunDurationMs ?? 600000 } : {}) });
this.report.responses.push({ method, params, result, trace: structuredClone(this.client.trace.at(-1)) }); return result;
}
async prompt(content) {
+1 -1
View File
@@ -31,7 +31,7 @@ export class DeepSeekAdapter {
this.installation = installation; this.timeoutMs = timeoutMs; this.clientFactory = clientFactory;
}
async waitReady(marker, nonce, signal) {
const deadline = Date.now() + this.timeoutMs;
const deadline = this.timeoutMs === 0 ? Infinity : Date.now() + this.timeoutMs;
while (true) {
signal?.throwIfAborted();
if (fs.existsSync(marker)) {
+9 -8
View File
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
@@ -176,7 +177,7 @@ class EngineRunDriver {
try {
this.assertInput(); signal.throwIfAborted(); checkBudget(this.run.record, this.store.core.task.get(this.run.taskId));
const allCalls = [...this.store.core.engine_run.values()].filter(job => job.workerId === this.run.worker.id).reduce((total, job) => total + job.calls.length, 0);
if (allCalls >= this.run.worker.budget.maxToolCalls) throw new BudgetExceeded('worker_tool_limit', '原引擎工具次数已到所属子任务累计上限。');
if (this.run.worker.budget.maxToolCalls > 0 && allCalls >= this.run.worker.budget.maxToolCalls) throw new BudgetExceeded('worker_tool_limit', '原引擎工具次数已到所属子任务累计上限。');
const callId = this.job.id + ':' + input.callId;
if (this.pendingCalls.has(callId) || this.job.calls.some(call => call.callId === callId)) throw engineError('原引擎调用已经登记,不会再次执行。');
const record = { sourceCallId: input.callId, callId, name: input.name, argumentsSha256: controlledDigest(input.arguments),
@@ -201,14 +202,14 @@ class EngineRunDriver {
const task = this.store.core.task.get(this.run.taskId); checkBudget(this.run.record, task);
const originalMessages = nativeMessagesToChat(input), tools = input.tools.map(tool => ({ type: 'function', function: tool }));
engineHistoryGroups(originalMessages);
const config = { ...this.run.config, maxOutputTokens: input.maxTokens };
const config = { ...this.run.config, maxOutputTokens: input.maxTokens ?? this.run.config.maxOutputTokens };
const owner = { sessionId: this.session.id, projectId: this.session.projectId, taskId: this.run.taskId, runId: this.run.id };
const source=this.store.artifactStore.write(this.session,this.run.record,
JSON.parse(this.provider.redact(JSON.stringify({schemaVersion:1,owner,native:input}))),{kind:'engine-native-input'});
this.store.core.artifact.set(source.id,source);
const safety=Math.max(512,Math.ceil(Math.min(config.contextLimit,24000)*0.1));
let index=null,reference={id:null,sha256:null};
if(requestMetrics(completionBody(config,originalMessages,tools)).estimatedInputTokens>config.contextLimit-config.maxOutputTokens-safety){
if(config.capacityMode !== 'passthrough' && requestMetrics(completionBody(config,originalMessages,tools)).estimatedInputTokens>config.contextLimit-config.maxOutputTokens-safety){
index=engineContextIndex(originalMessages,engineContextEvidence(this.store,this.session,this.job,originalMessages),
{artifact_id:source.id,sha256:source.sha256,owner});
reference=this.store.artifactStore.write(this.session,this.run.record,JSON.parse(this.provider.redact(JSON.stringify(index))),{kind:'engine-history-index'});
@@ -218,12 +219,12 @@ class EngineRunDriver {
const view={schemaVersion:1,mode:projected.mode,sourceArtifactId:source.id,sourceSha256:source.sha256,
indexArtifactId:projected.indexArtifactId,indexSha256:projected.indexSha256,beforeInputTokens:projected.before.estimatedInputTokens,
inputBudget:projected.inputBudget,safetyTokens:projected.safetyTokens,retainedGroups:projected.retainedGroups,archivedGroups:projected.archivedGroups};
const maximumAttempts = config.mode === 'demo' ? 1 : config.modelRouting?.maxAttempts ?? 1;
const credit = Math.min(this.run.record.budget.maxTokens - accountedTokens(this.run.record.usage), task.budget.maxTokens - accountedTokens(task.usage));
const maximumAttempts = config.mode === 'demo' || config.capacityMode === 'passthrough' ? 1 : config.modelRouting?.maxAttempts ?? 1;
const credit = Math.min(this.run.record.budget.maxTokens > 0 ? this.run.record.budget.maxTokens - accountedTokens(this.run.record.usage) : Infinity, task.budget.maxTokens > 0 ? task.budget.maxTokens - accountedTokens(task.usage) : Infinity);
const tokenReservation=modelReservation(config,body,taskConsumption(this.store,task.id),128);
const estimate = tokenReservation.reservedTokens;
const attempts = Math.min(maximumAttempts, Math.floor(credit / estimate), this.run.worker.budget.maxSteps - task.usage.requests);
if (metrics.estimatedInputTokens>projected.inputBudget || attempts < 1) {
const attempts = Math.min(maximumAttempts, Math.floor(credit / estimate), this.run.worker.budget.maxSteps > 0 ? this.run.worker.budget.maxSteps - task.usage.requests : Infinity);
if (projected.inputBudget !== null && metrics.estimatedInputTokens>projected.inputBudget || attempts < 1) {
const overhead=requestMetrics(completionBody(config,[],[])).estimatedInputTokens;
const toolDefinitionTokens=requestMetrics(completionBody(config,[],tools)).estimatedInputTokens-overhead;
const fixedInstructionTokens=requestMetrics(completionBody(config,originalMessages.filter(x=>['system','developer','user'].includes(x.role)),[])).estimatedInputTokens-overhead;
@@ -233,7 +234,7 @@ class EngineRunDriver {
taskRemainingTokens:Math.max(0,task.budget.maxTokens-accountedTokens(task.usage)),maxAttempts:Math.max(0,attempts),sourceArtifactId:source.id,sourceSha256:source.sha256,
breakdown:{requestOverheadTokens:overhead,toolDefinitionTokens,fixedInstructionTokens,
retainedHistoryAndViewTokens:metrics.estimatedInputTokens-overhead-toolDefinitionTokens-fixedInstructionTokens},
limitingReason:metrics.estimatedInputTokens>projected.inputBudget?'context_limit':'remaining_token_budget'};
limitingReason:projected.inputBudget !== null && metrics.estimatedInputTokens>projected.inputBudget?'context_limit':'remaining_token_budget'};
const rejected=this.store.artifactStore.write(this.session,this.run.record,
JSON.parse(this.provider.redact(JSON.stringify({schemaVersion:1,owner,view,body,budget:contextBudget,dispatched:false}))),{kind:'engine-model-rejection'});
this.store.core.artifact.set(rejected.id,rejected);(this.job.inputRejections??=[]).push({artifactId:rejected.id,sha256:rejected.sha256,...contextBudget});this.save('input_rejected');
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
import fs from 'node:fs';
import path from 'node:path';
import { createHash } from 'node:crypto';
@@ -19,7 +20,7 @@ export function fileIdentity(file, maximum = 128 * 1024 * 1024) {
function declaration(project, name) {
const target = safePath(project, name, true);
try { fs.lstatSync(target); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
const identity = fileIdentity(target, 8 * 1024 * 1024), text = fs.readFileSync(target, 'utf8');
const identity = fileIdentity(target, ceiling(project, 8 * 1024 * 1024)), text = fs.readFileSync(target, 'utf8');
if (environmentHash(text) !== identity.sha256) throw environmentConflict('环境声明在读取期间变化。');
return { ...identity, text };
}
@@ -36,11 +37,12 @@ export function npmRuntime(runtimeDirectory = null) {
// Hash actual dependency bytes. A hidden lockfile alone cannot prove that the
// installed packages are still the ones a previous command checked.
export function dependencyTree(project, { maximumFiles = 40000, maximumBytes = 512 * 1024 * 1024 } = {}) {
if (unrestricted(project)) { maximumFiles = Infinity; maximumBytes = Infinity; }
const root = path.join(safePath(project), 'node_modules'), hash = createHash('sha256');
let files = 0, bytes = 0, entriesSeen = 0;
try {fs.lstatSync(root);}catch(error){if(error.code==='ENOENT')return { status:'missing',files:0,bytes:0,sha256:null };throw error;}
const visit = (directory, depth = 0) => {
if (depth > 100) throw new Error('依赖目录过深');
if (depth > ceiling(project, 100)) throw new Error('依赖目录过深');
const stat = fs.lstatSync(directory);
if (!stat.isDirectory() || stat.isSymbolicLink() || !same(fs.realpathSync.native(directory), directory)) throw new Error('依赖目录包含链接或路径替换');
const entries=fs.readdirSync(directory).sort();
@@ -92,7 +94,7 @@ export function inspectNodeEnvironment(project, { runtimeDirectory = null, treeL
const packages = [];
for (const [relative,value] of Object.entries(lock?.packages ?? {})) {
if (!relative) continue;
if (packages.length >= 5000) { issues.push('锁文件包数超过5000的支持范围。'); break; }
if (packages.length >= ceiling(project, 5000)) { issues.push('锁文件包数超过5000的支持范围。'); break; }
if (!/^node_modules\//.test(relative) || relative.includes('\\') || relative.split('/').some(part=>!part||part==='..'||part==='.'||part.includes(':')) || value?.link || !value || typeof value !== 'object') {
issues.push('锁文件含本地链接、工作区或不支持的包路径。'); continue;
}
+2 -1
View File
@@ -1,3 +1,4 @@
import { unrestricted } from '../../shared/contracts/execution-policy.mjs';
import fs from 'node:fs';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
@@ -83,7 +84,7 @@ export class EnvironmentManager {
'--fetch-retries=0','--fetch-timeout=60000','--offline='+(input.offline===true)]};
const plan={schemaVersion:1,id,sessionId:session.id,projectId:project.id,taskId:session.taskId,runId:session.runId,diagnosticId:diagnostic.id,
root:project.root,workspace:projectWorkspaceIdentity(project),sourceFingerprint:diagnostic.sourceFingerprint,nodeIdentity:node.identity,
dependencyInputs:node.dependencyInputs,registry,scripts,offline:input.offline===true,timeoutMs:this.timeoutMs,invocation,configFiles,cacheDirectory,
dependencyInputs:node.dependencyInputs,registry,scripts,offline:input.offline===true,timeoutMs:unrestricted(this.store)?0:this.timeoutMs,invocation,configFiles,cacheDirectory,
lifecycle:node.lifecycle,installScriptPackages:node.installScriptPackages,packageCount:node.packageCount,status:'planned',createdAt:at(),jobId:null};
plan.fingerprint=hash(planSeal(plan));
const artifact=this.artifact(session,plan.runId,planSeal(plan),'environment-plan');plan.contractArtifactId=artifact.id;plan.contractSha256=artifact.sha256;
+5 -3
View File
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
import { randomUUID } from 'node:crypto';
import { modelSnapshot } from '../../shared/contracts/execution.mjs';
import { workerUsage, COLLABORATION_CLOSED } from '../../shared/contracts/workers.mjs';
@@ -84,8 +85,8 @@ export class EvaluationManager {
const initial = structuredClone(this.store.config), config = this.runtime.provider.prepareConfig?.(initial,this.store) ?? initial;
if (JSON.stringify(modelSnapshot(config)) !== JSON.stringify(batch.model)) throw evaluationConflict('模型连接或池修订已变化,请重新封存评测。');
const part = key => Math.floor(batch.budget[key]/batch.samples.length);
const budget = {maxTokens:Math.min(part('maxTokens'),config.maxRunTokens),maxSteps:part('maxSteps'),maxToolCalls:part('maxToolCalls'),maxDurationMs:batch.budget.maxDurationMs};
const original = {maxTokens:500,maxSteps:1,maxToolCalls:1}, candidate = Object.fromEntries(Object.keys(original).map(key=>[key,budget[key]-original[key]]));
const budget = unrestricted(config) ? {maxTokens:0,maxSteps:0,maxToolCalls:0,maxDurationMs:0} : {maxTokens:Math.min(part('maxTokens'),config.maxRunTokens),maxSteps:part('maxSteps'),maxToolCalls:part('maxToolCalls'),maxDurationMs:batch.budget.maxDurationMs};
const original = {maxTokens:500,maxSteps:1,maxToolCalls:1}, candidate = Object.fromEntries(Object.keys(original).map(key=>[key,unrestricted(config)?0:budget[key]-original[key]]));
signal.throwIfAborted();
const group = await manager.plan(session,{goal:sample.goal+'\n验收条件:'+sample.criteria,budget,children:[
{label:'原版 · '+sample.label,goal:'只执行原固定检查,不修改工程,不请求模型。',paths:sample.paths,budget:original},
@@ -113,6 +114,7 @@ export class EvaluationManager {
});
}
remaining(batch) {
if (batch.budget.maxDurationMs === 0) return Infinity;
batch.startedAt ??= at(); batch.deadline ??= Date.parse(batch.startedAt)+batch.budget.maxDurationMs;
const remaining = batch.deadline-Date.now(); if (remaining<=0) throw evaluationConflict('本批总时限已用完,原记录保留;可封存已有结果或重新规划。'); return remaining;
}
@@ -124,7 +126,7 @@ export class EvaluationManager {
const remaining=this.remaining(batch), group=this.group(session,batch,sample), child=group.children.find(child=>child.evaluation.role==='original');
sample.baselineAttemptedAt=at();this.save(session,batch,'baseline_intent');
const owner=this.store.session(child.sessionId), runner=this.runtime.checkRunner(), plan=await runner.plan(owner,sample.checks);
const combined=AbortSignal.any([signal,AbortSignal.timeout(remaining)]), started=await runner.start(owner,plan.id,{signal:combined,source:'user'});
const combined=Number.isFinite(remaining)?AbortSignal.any([signal,AbortSignal.timeout(remaining)]):signal, started=await runner.start(owner,plan.id,{signal:combined,source:'user'});
sample.baselineJobId=started.job.id;this.save(session,batch,'baseline_started');await started.promise;
const worker=this.store.core.worker.get(child.id);worker.status=started.job.requiresVerification?'unknown':'baseline_complete';worker.finishedAt=at();worker.summary=started.job.summary;worker.requiresVerification=!!started.job.requiresVerification;
this.store.putRecord('worker',owner,worker,'evaluation.original_finished');
+27 -22
View File
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../shared/contracts/execution-policy.mjs';
import fs from 'node:fs';
import path from 'node:path';
import { assertChangeSetsResolved } from '../shared/contracts/change-sets.mjs';
@@ -42,8 +43,8 @@ function protectedIndex(stageText, flagText, paths) {
flags: flagText.split('\0').filter(line => line && !chosen.has(line.slice(2))).sort(),
}));
}
function validMessage(value) {
if (typeof value !== 'string' || !value.trim() || value.length > 1600 || value.includes('\0')
function validMessage(value, config) {
if (typeof value !== 'string' || !value.trim() || value.length > ceiling(config, 1600) || value.includes('\0')
|| /^Workbench-(?:Delivery|Task|Session):/im.test(value)) throw new Error('提交说明需要1到1600个字符,不能包含工作台保留的trailer。');
return value.replaceAll('\r\n', '\n').trim();
}
@@ -118,13 +119,13 @@ export class GitDelivery {
if (!oid(headId) || !ref.ok || !/^refs\/heads\/[^\s\0]+$/.test(reference)) throw conflict('当前交付切片需要已有提交的命名分支;请先用Git建立基线分支。');
const gitDir = fs.realpathSync.native(gitDirectory.text.trim()), indexPath = path.resolve(index.text.trim());
if (normalize(path.dirname(indexPath)) !== normalize(gitDir) || !fs.existsSync(indexPath) || fs.lstatSync(indexPath).isSymbolicLink()
|| fs.statSync(indexPath).size > 16 * 1024 * 1024) throw conflict('当前Git索引位置、类型或大小未被交付器支持。');
|| fs.statSync(indexPath).size > ceiling(this.store, 16 * 1024 * 1024)) throw conflict('当前Git索引位置、类型或大小未被交付器支持。');
for (const name of ['MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD', 'REBASE_HEAD', 'rebase-apply', 'rebase-merge', 'sequencer', 'BISECT_START']) {
if (fs.existsSync(path.join(gitDir, name))) throw conflict('Git正在合并、变基或定位问题;先完成该操作再交付。');
}
if (!allowOwnLock && fs.existsSync(indexPath + '.lock')) throw conflict('Git索引正在被其他操作锁定,请先核对该操作。');
const paths = [...new Set(inventory.text.split('\0').filter(Boolean))];
if (paths.length > 1000) throw conflict('工程超过当前1000文件快照上限,请缩小工程范围后交付。');
if (!unrestricted(this.store) && paths.length > 1000) throw conflict('工程超过当前1000文件快照上限,请缩小工程范围后交付。');
const attributes = await this.needGit(project, ['check-attr', '-z', 'filter', 'working-tree-encoding', '--stdin'], { input: paths.join('\0') + (paths.length ? '\0' : '') });
const attributeParts = attributes.text.split('\0').filter(Boolean);
for (let i = 0; i < attributeParts.length; i += 3) if (!['unspecified', 'unset'].includes(attributeParts[i + 2])) {
@@ -165,7 +166,7 @@ export class GitDelivery {
if (!selected.has(relative)) selected.set(relative, []);
selected.get(relative).push(change);
}
if (!selected.size || selected.size > 32) throw conflict('当前任务需要1到32个已应用且归属明确的文件;旧版未记录Task归属的提案需要重新审查。');
if (!selected.size || selected.size > ceiling(this.store, 32)) throw conflict('当前任务需要已应用且归属明确的文件。');
const stageEntries = entries(snapshot.stage), result = [];
for (const [relative, chain] of selected) {
const latest = chain.at(-1), bytes = fs.readFileSync(safePath(project, relative));
@@ -199,21 +200,21 @@ export class GitDelivery {
deletions: parts.filter(part => part.removed).reduce((sum, part) => sum + part.count, 0), diff: this.redact(diff) });
}
if (!result.length) throw conflict('当前任务的文件内容已在Git HEAD中,没有新的交付改动。');
if (Buffer.byteLength(result.map(file => file.diff).join('\n'), 'utf8') > 1024 * 1024) throw conflict('提交差异超过1MB预览上限,请缩小本次任务。');
if (!unrestricted(this.store) && Buffer.byteLength(result.map(file => file.diff).join('\n'), 'utf8') > 1024 * 1024) throw conflict('提交差异超过1MB预览上限,请缩小本次任务。');
return result.sort((a, b) => a.path.localeCompare(b.path));
}
async plan(session, options = {}, { source = 'user' } = {}) {
if (session.fileDrafts?.some(row => row.taskId === session.taskId && row.status === 'staging')) throw conflict('分段文件草稿尚未完成,请完成提案或显式放弃后再交付。');
assertWorkersResolved(this.store, session.projectId);
if (workerForProject(this.store, session.projectId)) throw conflict('受限子任务不能独立Git提交;请在父任务审查合并后交付。');
if (!unrestricted(this.store) && workerForProject(this.store, session.projectId)) throw conflict('受限子任务不能独立Git提交;请在父任务审查合并后交付。');
const idleOptions = { exceptSessionId: source === 'agent' ? session.id : null };
this.assertIdle(session, idleOptions); const { task, run } = this.assertTask(session);
const identity = { taskId: task.id, runId: run.id }, project = this.store.project(session.projectId);
const snapshot = await this.snapshot(project), inspection = await inspectProject(project);
const check = verifiedCheck(this.store, session, inspection);
if (!check) {
const previous = this.store.core.check_job.get(task.verification.checkJobId);
if (!check && !unrestricted(this.store)) {
const previous = this.store.core.check_job.get(task.verification?.checkJobId);
if (previous?.status === 'passed' && task.verification.status === 'passed') {
previous.stale = true; previous.staleReason = 'Git交付核对发现源码或检查日志证据失效。';
task.verification = { ...task.verification, status: 'stale', reason: previous.staleReason };
@@ -221,30 +222,33 @@ export class GitDelivery {
}
throw conflict('提交需要与当前源码一致、日志完整且测试数量明确的通过记录;请先执行工程检查。');
}
if (!check.sourceFingerprint) {
if (check && !check.sourceFingerprint) {
check.sourceFingerprint = inspection.sourceFingerprint;
task.verification = { ...task.verification, sourceFingerprint: inspection.sourceFingerprint };
}
assertBrowserResolved(this.store, session.projectId);
const browser = await currentBrowserVerification(this.store, session, inspection);
if (browser.required && browser.status !== 'passed') throw conflict('本任务已配置页面验收,请先取得当前源码与构建的实际浏览器断言通过记录。');
const taskPlan = await new TaskPlanManager(this.store).assertReady(session, { inspection });
const requirements = await new RequirementReview(this.store).assertReady(session, { inspection });
if (!unrestricted(this.store) && browser.required && browser.status !== 'passed') throw conflict('本任务已配置页面验收,请先取得当前源码与构建的实际浏览器断言通过记录。');
const taskPlan = unrestricted(this.store) ? {} : await new TaskPlanManager(this.store).assertReady(session, { inspection });
const requirements = unrestricted(this.store) ? {} : await new RequirementReview(this.store).assertReady(session, { inspection });
const files = await this.selectedFiles(session, project, snapshot);
const name = options.authorName ?? snapshot.config['user.name'] ?? 'Agent Workbench';
const email = options.authorEmail ?? snapshot.config['user.email'] ?? 'local@agent-workbench.invalid';
const author = { ...validAuthor(name, email), source: options.authorName || options.authorEmail ? 'explicit' : snapshot.config['user.name'] && snapshot.config['user.email'] ? 'git-config' : 'workbench-local' };
const message = validMessage(options.message ?? '完成:' + task.goal.replace(/\s+/g, ' ').slice(0, 90));
const message = validMessage(options.message ?? '完成:' + task.goal.replace(/\s+/g, ' ').slice(0, 90), this.store.config);
const second = await this.snapshot(project);
if (snapshot.digest !== second.digest || identity.taskId !== session.taskId || identity.runId !== session.runId) throw conflict('准备提交期间工程或任务已变化,请重新预览。');
this.assertIdle(session, idleOptions); this.assertTask(session);
await new TaskPlanManager(this.store).assertReady(session, { expectedBinding: taskPlan.binding_sha256 });
await new RequirementReview(this.store).assertReady(session, { expectedBinding: requirements.binding_sha256 });
if (!unrestricted(this.store)) {
await new TaskPlanManager(this.store).assertReady(session, { expectedBinding: taskPlan.binding_sha256 });
await new RequirementReview(this.store).assertReady(session, { expectedBinding: requirements.binding_sha256 });
}
const diffArtifact = this.store.artifactStore.write(session, run, files.map(file => file.diff).join('\n'), { kind: 'delivery-diff', mediaType: 'text/plain' });
this.store.core.artifact.set(diffArtifact.id, diffArtifact);
const plan = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: task.id, runId: run.id, status: 'planned', createdAt: at(),
message, author, files, paths: files.map(file => file.path), snapshot, preparedBy: source, fingerprint: inspection.fingerprint, sourceFingerprint: inspection.sourceFingerprint,
checkJobId: check.id, checkSummary: check.results.map(value => ({ name: value.name, command: value.command, exitCode: value.exitCode, tests: value.tests, logArtifactId: value.logArtifactId })),
executionMode: this.store.config.executionMode ?? 'restricted',
checkJobId: check?.id ?? null, checkSummary: (check?.results ?? []).map(value => ({ name: value.name, command: value.command, exitCode: value.exitCode, tests: value.tests, logArtifactId: value.logArtifactId })),
...(taskPlan.configured ? { taskPlanId: taskPlan.plan_id, taskPlanRevision: taskPlan.revision, taskPlanBindingSha256: taskPlan.binding_sha256 } : {}),
...(requirements.configured ? { requirementBindingSha256: requirements.binding_sha256 } : {}),
...(browser.required ? { browserJobId: browser.jobId, browserPlanId: browser.planId, browserBuildSha256: browser.buildSha256 } : {}),
@@ -274,8 +278,8 @@ export class GitDelivery {
return plan;
}
async start(session, planId) {
this.assertIdle(session); this.assertTask(session);
async start(session, planId, { source = 'user' } = {}) {
this.assertIdle(session, { exceptSessionId: source === 'agent' ? session.id : null }); this.assertTask(session);
const plan = this.store.owned('delivery_plan', planId, session.id);
if (plan.taskId !== session.taskId || plan.runId !== session.runId || plan.status !== 'planned') throw conflict('提交计划已使用或不属于当前Task/Run,请重新预览。');
const controller = new AbortController();
@@ -299,6 +303,7 @@ export class GitDelivery {
}
async verifyBrowserDelivery(session, plan, inspection) {
if (unrestricted(plan)) return;
await new RequirementReview(this.store).assertReady(session, { inspection, expectedBinding: plan.requirementBindingSha256 ?? null });
await new TaskPlanManager(this.store).assertReady(session, { inspection, expectedBinding: plan.taskPlanBindingSha256 ?? null });
assertBrowserResolved(this.store, session.projectId);
@@ -315,7 +320,7 @@ export class GitDelivery {
const snapshot = await this.snapshot(project), inspection = await inspectProject(project);
signal.throwIfAborted();
if (session.taskId !== plan.taskId || session.runId !== plan.runId || snapshot.digest !== plan.snapshot.digest || inspection.fingerprint !== plan.fingerprint) throw conflict('提交预览后工程、Git索引或Task/Run已变化,没有执行提交。');
if (!verifiedCheck(this.store, session, inspection)) throw conflict('提交前检查证据已失效,请重新运行工程检查。');
if (!unrestricted(plan) && !verifiedCheck(this.store, session, inspection)) throw conflict('提交前检查证据已失效,请重新运行工程检查。');
await this.verifyBrowserDelivery(session, plan, inspection);
const selected = await this.selectedFiles(session, project, snapshot);
if (JSON.stringify(selected) !== JSON.stringify(plan.files)) throw conflict('当前文件与已审核提交清单不一致。');
@@ -390,7 +395,7 @@ export class GitDelivery {
child.stderr.on('data', bytes => { errors = (errors + bytes.toString('utf8')).slice(-8000); });
const done = new Promise((resolve, reject) => { child.once('error', reject); child.once('close', code => resolve(code)); });
done.catch(() => {});
const timer = setTimeout(() => child.kill(), 15000);
const timer = unrestricted(plan) ? null : setTimeout(() => child.kill(), 15000);
const stop = () => { if (!commitSent && !child.stdin.writableEnded) child.stdin.end('abort\n'); };
signal.addEventListener('abort', stop, { once: true });
try {
@@ -401,7 +406,7 @@ export class GitDelivery {
const actualRef = (await this.needGit(project, ['symbolic-ref', '--quiet', 'HEAD'])).text.trim();
if (actualRef !== plan.snapshot.reference || digestFile(job.indexPath) !== job.indexBeforeSha256) throw conflict('Git锁定后当前分支或索引与提交计划不同,未发布提交。');
const inspection = await inspectProject(project);
if (inspection.sourceFingerprint !== plan.sourceFingerprint || !verifiedCheck(this.store, session, inspection)) throw conflict('Git锁定后源码或实际检查已经变化,未发布提交。');
if (inspection.sourceFingerprint !== plan.sourceFingerprint || !unrestricted(plan) && !verifiedCheck(this.store, session, inspection)) throw conflict('Git锁定后源码或实际检查已经变化,未发布提交。');
await this.verifyBrowserDelivery(session, plan, inspection);
await this.checkpoint(session, job, 'ref_prepared');
signal.throwIfAborted();
+2 -2
View File
@@ -13,7 +13,7 @@ export function gitArguments(root, args, hooksDirectory) {
...(hooksDirectory ? ['-c', 'core.hooksPath=' + hooksDirectory] : []), ...args];
}
export function runGit(root, args, { input, env = {}, signal, timeoutMs = 10000, hooksDirectory, maximumBytes = 2 * 1024 * 1024, onSpawn } = {}) {
export function runGit(root, args, { input, env = {}, signal, timeoutMs = 0, hooksDirectory, maximumBytes = Infinity, onSpawn } = {}) {
return new Promise((resolve, reject) => {
if (signal?.aborted) return reject(signal.reason ?? new Error('Git操作已停止。'));
const child = spawn('git', gitArguments(root, args, hooksDirectory), { env: gitEnvironment(env), windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
@@ -22,7 +22,7 @@ export function runGit(root, args, { input, env = {}, signal, timeoutMs = 10000,
const capture = list => chunk => { bytes += chunk.length; if (bytes > maximumBytes) { exceeded = true; child.kill(); } else list.push(chunk); };
child.stdout.on('data', capture(chunks)); child.stderr.on('data', capture(errors));
child.stdin.on('error', () => {});
const timer = setTimeout(() => { timedOut = true; child.kill(); }, timeoutMs);
const timer = timeoutMs > 0 ? setTimeout(() => { timedOut = true; child.kill(); }, timeoutMs) : null;
const stop = () => child.kill();
signal?.addEventListener('abort', stop, { once: true });
child.once('error', error => { clearTimeout(timer); signal?.removeEventListener('abort', stop); reject(error); });
+9 -8
View File
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
import { randomUUID, createHash } from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
@@ -128,7 +129,7 @@ export class ProjectMemoryManager {
if (memory.status === 'current' && !inspection.scope.complete) value.status = 'unverified';
presented.push(value);
}
const memories = presented.filter(value => includeExpired || value.status === 'current').slice(0, MAX_MEMORIES);
const memories = presented.filter(value => includeExpired || value.status === 'current').slice(0, ceiling(this.store, MAX_MEMORIES));
return {
projectId, sourceFingerprint: inspection.sourceFingerprint, inspectedAt: inspection.inspectedAt,
scope: inspection.scope, memories,
@@ -141,15 +142,15 @@ export class ProjectMemoryManager {
}
async create(session, input = {}) {
if ([...this.store.core.memory.values()].filter(value => value.projectId === session.projectId).length >= MAX_MEMORIES) throw memoryError('项目记忆已到500条上限。', 409);
if ([...this.store.core.memory.values()].filter(value => value.projectId === session.projectId).length >= ceiling(this.store, MAX_MEMORIES)) throw memoryError('项目记忆已到500条上限。', 409);
const project = this.store.project(session.projectId);
const inspection = await this.inspect(session.projectId);
if (!inspection.scope.complete) throw memoryError('本次工程源码扫描不完整,暂不能保存绑定工程版本的项目记忆;请先缩小工程范围或排除超预算文件。', 409);
const title = text(input.title || '未命名记忆', MAX_TITLE);
const title = text(input.title || '未命名记忆', ceiling(this.store, MAX_TITLE));
const content = String(input.content ?? '').trim();
if (!content || content.length > MAX_CONTENT) throw memoryError('项目记忆内容不能为空且不能超过16000字符。');
if (!content || content.length > ceiling(this.store, MAX_CONTENT)) throw memoryError('项目记忆内容不能为空且不能超过16000字符。');
if (title.length < 1) throw memoryError('项目记忆标题不能为空。');
const tags = Array.isArray(input.tags) ? [...new Set(input.tags.map(value => text(value, MAX_TAG)).filter(Boolean))].slice(0, MAX_TAGS) : [];
const tags = Array.isArray(input.tags) ? [...new Set(input.tags.map(value => text(value, ceiling(this.store, MAX_TAG))).filter(Boolean))].slice(0, ceiling(this.store, MAX_TAGS)) : [];
if (input.tags !== undefined && !Array.isArray(input.tags)) throw memoryError('项目记忆标签需要数组。');
let expiresAt = null;
if (input.expiresAt !== undefined && input.expiresAt !== null && input.expiresAt !== '') {
@@ -189,7 +190,7 @@ export class ProjectMemoryManager {
return false;
}
async context(session, { redact = value => value, maxEntries = MEMORY_CONTEXT_LIMITS.entries, maxBytes = MEMORY_CONTEXT_LIMITS.bytes } = {}) {
async context(session, { redact = value => value, maxEntries = ceiling(this.store, MEMORY_CONTEXT_LIMITS.entries), maxBytes = ceiling(this.store, MEMORY_CONTEXT_LIMITS.bytes) } = {}) {
// No scan or context overhead for projects without memory.
if (![...this.store.core.memory.values()].some(value => value.projectId === session.projectId && value.status === 'current')) return null;
let view;
@@ -201,8 +202,8 @@ export class ProjectMemoryManager {
throw error;
}
if (!view.scope.complete || !view.memories.length) return null;
const entryLimit = Math.max(0, Math.min(MEMORY_CONTEXT_LIMITS.entries, Math.floor(maxEntries) || 0));
const byteLimit = Math.max(0, Math.min(MEMORY_CONTEXT_LIMITS.bytes, Math.floor(maxBytes) || 0));
const entryLimit = Math.max(0, Math.min(ceiling(this.store, MEMORY_CONTEXT_LIMITS.entries), Math.floor(maxEntries) || 0));
const byteLimit = Math.max(0, Math.min(ceiling(this.store, MEMORY_CONTEXT_LIMITS.bytes), Math.floor(maxBytes) || 0));
const document = { schemaVersion: 1, kind: 'source-checked-project-memory', projectId: session.projectId,
sourceFingerprint: view.sourceFingerprint, checkedAt: view.inspectedAt, availableEntries: view.memories.length, entries: [] };
for (const memory of view.memories) {
+7 -6
View File
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
@@ -22,11 +23,11 @@ export class ConfigImporter {
read(source, filename) {
if (!path.isAbsolute(filename)) throw new Error('请选择配置文件的绝对路径。');
const stat = fs.lstatSync(filename);
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 64 * 1024 * 1024) throw new Error('配置必须为64MB以内的普通文件。');
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > ceiling(this.hub.store, 64 * 1024 * 1024)) throw new Error('配置必须为64MB以内的普通文件。');
const rows = [], notices = [];
if (source === 'workbench-json') {
const value = JSON.parse(fs.readFileSync(filename, 'utf8').replace(/^\uFEFF/, ''));
if (value.schema !== 1 || !Array.isArray(value.connections) || value.connections.length > 100) throw new Error('连接JSON需要schema:1与connections数组(最多100项)。');
if (value.schema !== 1 || !Array.isArray(value.connections) || value.connections.length > ceiling(this.hub.store, 100)) throw new Error('连接JSON需要schema:1与connections数组(最多100项)。');
for (const [index, item] of value.connections.entries()) {
if (item.protocol && !MODEL_PROTOCOLS.includes(item.protocol)) { notices.push('第' + (index + 1) + '项协议暂不支持,已跳过。'); continue; }
rows.push({ sourceId: String(item.id ?? index), name: item.name, model: item.model, protocol: item.protocol ?? 'chat-completions',
@@ -44,8 +45,8 @@ export class ConfigImporter {
try {
const columns = db.prepare('PRAGMA table_info(providers)').all().map(value => value.name);
if (!['id', 'app_type', 'name', 'settings_config'].every(value => columns.includes(value))) throw new Error('CCSwitch providers表不符合已验证格式。');
const providers = db.prepare('SELECT id,app_type,name,settings_config FROM providers ORDER BY app_type,id LIMIT 101').all();
if (providers.length > 100) throw new Error('来源超过100个provider,请缩小导入范围。');
const providers = db.prepare('SELECT id,app_type,name,settings_config FROM providers ORDER BY app_type,id' + (unrestricted(this.hub.store) ? '' : ' LIMIT 101')).all();
if (providers.length > ceiling(this.hub.store, 100)) throw new Error('来源超过100个provider,请缩小导入范围。');
for (const provider of providers) {
let config;
try { config = JSON.parse(provider.settings_config); } catch { notices.push(provider.name + '配置不是有效JSON,已跳过。'); continue; }
@@ -66,7 +67,7 @@ export class ConfigImporter {
if (!String(row.model ?? '').trim() || !String(row.name ?? '').trim()) throw new Error('缺少名称或模型');
if (row.apiKey !== undefined && typeof row.apiKey !== 'string') throw new Error('凭据不是字符串');
const native = row.nativeParameters !== undefined || row.outputTokenField !== undefined || row.parameterProfile !== undefined
? nativeParameterSettings(row.protocol, row.nativeParameters ?? {}, row.outputTokenField, row.parameterProfile) : {};
? nativeParameterSettings(row.protocol, row.nativeParameters ?? {}, row.outputTokenField, row.parameterProfile, this.hub.store.config) : {};
entries.push({ ...row, ...native, ...messagesAuthSettings(row.protocol, row.messagesAuth), name: String(row.name).slice(0, 100), model: String(row.model).slice(0, 200), baseUrl: validateProtocolEndpoint(row.protocol, modelEndpoint(row.baseUrl)),
origin: digest({ source, path: path.resolve(filename), id: row.sourceId }), apiKey: row.apiKey?.trim() ?? '' });
} catch { notices.push(String(row.name ?? '某项配置').slice(0, 100) + '缺少有效的接口或模型,已跳过。'); }
@@ -76,7 +77,7 @@ export class ConfigImporter {
preview(source, filename) {
const contents = this.read(source, filename), id = randomUUID();
for (const [key, value] of this.previews) if (Date.now() - value.created > 300000) this.previews.delete(key);
if (this.previews.size >= 8) throw new Error('预览数量过多,请先完成已有导入。');
if (this.previews.size >= ceiling(this.hub.store, 8)) throw new Error('预览数量过多,请先完成已有导入。');
this.previews.set(id, { source, path: path.resolve(filename), created: Date.now(), ...contents });
return { id, entries: contents.entries.map(({ apiKey, sourceId, origin, ...value }, index) => ({ ...value, id: String(index), hasKey: !!apiKey })), notices: contents.notices, expiresInMs: 300000 };
}
+2 -2
View File
@@ -4,7 +4,7 @@ const object = value => value && typeof value === 'object' && !Array.isArray(val
const fail = message => { throw protocolFailure('Messages 流:' + message); };
// Each block and the whole message must close before any tool becomes dispatchable.
export function messagesStream() {
export function messagesStream(config = {}) {
let message = null, active = null, deltaSeen = false, stopped = false, text = '', toolCount = 0;
const blocks = [];
return {
@@ -23,7 +23,7 @@ export function messagesStream() {
if (!object(block) || !['text', 'tool_use', 'thinking', 'redacted_thinking'].includes(block.type)) fail('未接入的内容块类型。');
if (block.type === 'text' && typeof block.text !== 'string' || block.type === 'tool_use' && (!object(block.input) || typeof block.id !== 'string' || !block.id || typeof block.name !== 'string' || !block.name)
|| block.type === 'thinking' && (typeof block.thinking !== 'string' || block.signature !== undefined && typeof block.signature !== 'string') || block.type === 'redacted_thinking' && typeof block.data !== 'string') fail('初始内容块格式无效。');
if (block.type === 'tool_use' && (++toolCount > 12 || blocks.some(item => item.block.id === block.id))) fail('工具数量超限或身份重复。');
if (block.type === 'tool_use' && (++toolCount > 12 && config.executionMode !== 'unrestricted' || blocks.some(item => item.block.id === block.id))) fail('工具数量超限或身份重复。');
// Thinking signatures normally arrive in a later signature_delta.
// Final protocol normalization still requires a complete signature.
const initial = structuredClone(block);
+8 -7
View File
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
import { randomUUID, createHash } from 'node:crypto';
import { catalogPage, catalogRoute } from '../../shared/contracts/model-catalog.mjs';
import { messagesAuthSettings, validateProtocolEndpoint } from '../../shared/contracts/model-endpoint.mjs';
@@ -72,23 +73,23 @@ export class ModelCatalog {
do {
controller.signal.throwIfAborted();
this.current({ binding });
if (Date.now() >= deadline) throw fail('获取模型目录超过60秒,请稍后重试。');
if (!unrestricted(this.hub.store) && (Date.now() >= deadline)) throw fail('获取模型目录超过60秒,请稍后重试。');
const query = cursor ? '?after_id=' + encodeURIComponent(cursor) + '&limit=100' : connection.protocol === 'anthropic-messages' ? '?limit=100' : '';
const raw = await this.hub.provider.request({ ...connection, model: '', mode: 'demo' }, route + query, undefined, controller.signal, key, undefined,
{ attempts: 1, timeoutMs: Math.min(20000, deadline - Date.now()), totalTimeoutMs: Math.min(20000, deadline - Date.now()) });
{ attempts: 1, timeoutMs: unrestricted(this.hub.store) ? 0 : Math.min(20000, deadline - Date.now()), totalTimeoutMs: unrestricted(this.hub.store) ? 0 : Math.min(20000, deadline - Date.now()) });
const encoded = this.hub.provider.redact(JSON.stringify(raw), key); bytes += Buffer.byteLength(encoded);
if (bytes > 4 * 1024 * 1024) throw fail('模型目录超过4MB上限,请使用供应商筛选接口或手动添加。');
const page = catalogPage(JSON.parse(encoded)); pages++;
if (page.entries.length > 1000) throw fail('单页模型超过1000项,请核对上游分页。');
if (!unrestricted(this.hub.store) && (page.entries.length > 1000)) throw fail('单页模型超过1000项,请核对上游分页。');
for (const item of page.entries) {
if (entries.has(item.id) && JSON.stringify(entries.get(item.id)) !== JSON.stringify(item)) throw fail('上游目录包含相同型号的冲突定义,请核对后重试。');
if (entries.size === 1000 && !entries.has(item.id)) { complete = false; warning = '已达到1000项目录上限;当前只显示已获取部分,可使用手动兼容入口。'; break; }
if (!unrestricted(this.hub.store) && (entries.size === 1000 && !entries.has(item.id))) { complete = false; warning = '已达到1000项目录上限;当前只显示已获取部分,可使用手动兼容入口。'; break; }
entries.set(item.id, item);
}
if (!page.hasMore || !complete) break;
if (cursors.has(page.cursor) || !page.entries.length) throw fail('上游分页未向前推进,已停止获取。');
cursors.add(page.cursor); cursor = page.cursor;
if (pages === 20 || entries.size === 1000) { complete = false; warning = '目录仍有后续页,已达到本次获取上限;当前只显示部分模型。'; break; }
if (!unrestricted(this.hub.store) && (pages === 20 || entries.size === 1000)) { complete = false; warning = '目录仍有后续页,已达到本次获取上限;当前只显示部分模型。'; break; }
} while (true);
controller.signal.throwIfAborted(); this.current({ binding }); this.prune();
if (this.previews.size >= 8) this.previews.delete(this.previews.keys().next().value);
@@ -103,7 +104,7 @@ export class ModelCatalog {
this.prune(); const value = this.previews.get(input.previewId);
if (!value) throw fail('模型目录预览已取消、过期或宿主已重启,请重新获取。', 409);
this.current(value);
if (!Array.isArray(input.models) || !input.models.length || input.models.length > 100 || new Set(input.models).size !== input.models.length) throw fail('请选择1–100个不重复的上游模型。');
if (!Array.isArray(input.models) || !input.models.length || !unrestricted(this.hub.store) && input.models.length > 100 || new Set(input.models).size !== input.models.length) throw fail('请选择1–100个不重复的上游模型。');
const selected = input.models.map(id => value.preview.entries.find(model => model.id === id));
if (selected.some(model => !model)) throw fail('所选模型不属于本次上游目录。');
if (selected.some(model => model.lifecycle === 'retired')) throw fail('已退役型号不能新增使用,请选择其它模型。');
@@ -111,7 +112,7 @@ export class ModelCatalog {
const declarations = capabilityDeclarations(input.declarations, { text: 'unknown', tools: 'unknown', streaming: 'unknown', vision: 'unknown', audio: 'unknown' });
if (!['keep', 'manual', 'auto'].includes(input.routing ?? 'keep')) throw fail('请选择保留当前选择、手动指定或自动适配。');
if (input.routing === 'manual' && !input.models.includes(input.defaultModel)) throw fail('请在勾选的模型中指定默认型号。');
if (input.routing === 'auto' && input.models.length > 32) throw fail('单个自动模型池最多32个成员;可减少本次选择或分别建立模型池。');
if (!unrestricted(this.hub.store) && (input.routing === 'auto' && input.models.length > 32)) throw fail('单个自动模型池最多32个成员;可减少本次选择或分别建立模型池。');
if (input.persistKey === true && !value.explicitKey) throw fail('本机加密保存需要本次新填写的 Key;已有凭据沿用原保存状态。');
const hub = this.hub;
const result = hub.editRegistry(() => {
+18 -17
View File
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
import { randomUUID, createHash } from 'node:crypto';
import { setTimeout as delay } from 'node:timers/promises';
import { ModelRequestError } from '../../server/diagnostics.mjs';
@@ -84,7 +85,7 @@ export class ModelHub {
throw cause;
} finally { this.editingRegistry = false; }
}
saveAttempts() { this.attempts = this.attempts.slice(-1000); this.store.storage.transaction(() => this.store.storage.setMeta('modelAttempts', this.attempts)); }
saveAttempts() { if (!unrestricted(this.store)) this.attempts = this.attempts.slice(-1000); this.store.storage.transaction(() => this.store.storage.setMeta('modelAttempts', this.attempts)); }
connections() {
return [{ id: legacyId, name: '原模型连接', brand: '兼容服务', protocol: 'chat-completions', baseUrl: this.store.config.baseUrl,
model: this.store.config.model, enabled: true, requiresKey: false, revision: this.store.config.configRevision ?? 1,
@@ -203,15 +204,15 @@ export class ModelHub {
if (!this.editingRegistry) return this.editRegistry(() => this.upsert(input));
if (input.id === legacyId) throw error('原连接请通过模型连接设置修改。');
const previous = input.id ? this.connection(input.id) : null;
if (this.state.connections.length >= 100 && !previous) throw error('最多保存100个模型连接。');
if (!unrestricted(this.store) && this.state.connections.length >= 100 && !previous) throw error('最多保存100个模型连接。');
if (previous && input.revision !== previous.revision) throw error('模型连接已修改,请刷新后重试。', 409);
const protocol = modelProtocol(input.protocol ?? previous?.protocol ?? 'chat-completions');
const native = Object.hasOwn(input, 'nativeParameters') || Object.hasOwn(input, 'outputTokenField') || Object.hasOwn(input, 'parameterProfile') || previous?.nativeParameters || previous?.parameterProfile
? nativeParameterSettings(protocol, input.nativeParameters ?? previous?.nativeParameters ?? {}, input.outputTokenField ?? previous?.outputTokenField, input.parameterProfile ?? previous?.parameterProfile) : null;
? nativeParameterSettings(protocol, input.nativeParameters ?? previous?.nativeParameters ?? {}, input.outputTokenField ?? previous?.outputTokenField, input.parameterProfile ?? previous?.parameterProfile, this.store.config) : null;
const declarations = capabilityDeclarations(input.capabilityDeclarations, previous?.capabilityDeclarations);
if (input.streaming !== undefined && typeof input.streaming !== 'boolean') throw error('流式选项必须为开启或关闭。');
const streaming = input.streaming ?? previous?.streaming ?? false;
if (streaming && declarations.streaming !== 'supported') throw error('请先声明服务支持流式输出,再开启流式请求。');
if (!unrestricted(this.store) && streaming && declarations.streaming !== 'supported') throw error('请先声明服务支持流式输出,再开启流式请求。');
const name = label(input.name), model = label(input.model, 200);
if (!name || !model) throw error('请填写连接名称和实际模型名称。');
const connection = { id: previous?.id ?? randomUUID(), name, brand: label(input.brand || '自定义', 40), protocol, model,
@@ -219,7 +220,7 @@ export class ModelHub {
...messagesAuthSettings(protocol, input.messagesAuth ?? previous?.messagesAuth),
baseUrl: validateProtocolEndpoint(protocol, modelEndpoint(input.baseUrl)), enabled: input.enabled !== false, requiresKey: input.requiresKey !== false,
...capacitySettings(input, previous ?? undefined),
concurrency: bounded(input.concurrency, 1, 1, 8), revision: (previous?.revision ?? 0) + 1,
concurrency: unrestricted(this.store) ? (input.concurrency ?? 0) : bounded(input.concurrency, 1, 1, 8), revision: (previous?.revision ?? 0) + 1,
source: previous?.source ?? 'manual', ...(previous?.importOrigin ? { importOrigin: previous.importOrigin, importRevision: previous.importRevision } : {}),
createdAt: previous?.createdAt ?? stamp(), updatedAt: stamp() };
if (previous?.credentialSource && !Object.hasOwn(input, 'apiKey')) {
@@ -227,7 +228,7 @@ export class ModelHub {
connection.credentialSource = previous.credentialSource;
}
if (previous?.upstreamModel && previous.model === connection.model && credentialScope(previous) === credentialScope(connection)) connection.upstreamModel = previous.upstreamModel;
assertModelParameterSupport(connection, connection.nativeParameters ?? {});
if (!unrestricted(this.store)) assertModelParameterSupport(connection, connection.nativeParameters ?? {});
if (Object.hasOwn(input, 'apiKey')) {
if (typeof input.apiKey !== 'string' || input.apiKey.length > 16000) throw error('模型凭据格式无效。');
}
@@ -244,7 +245,7 @@ export class ModelHub {
setNativeParameters(input) {
const connection = this.connection(input.id);
if (connection.revision !== input.revision) throw error('连接已变化,请刷新后核对原生参数。', 409);
const settings = nativeParameterSettings(connection.protocol, input.nativeParameters, input.outputTokenField, input.parameterProfile ?? connection.parameterProfile);
const settings = nativeParameterSettings(connection.protocol, input.nativeParameters, input.outputTokenField, input.parameterProfile ?? connection.parameterProfile, this.store.config);
if (connection.id === legacyId) this.save(settings);
else this.upsert({ ...connection, ...settings });
return { center: this.view(), config: { ...this.store.config, hasKey: this.provider.hasKey() } };
@@ -257,8 +258,8 @@ export class ModelHub {
const previous = input.id ? this.state.pools.find(value => value.id === input.id) : null;
if (input.id && !previous) throw error('模型池不存在。', 404);
if (previous && input.revision !== previous.revision) throw error('模型池已修改,请刷新后重试。', 409);
if (!previous && this.state.pools.length >= 32) throw error('最多保存32个模型池。');
if (!label(input.name) || !Array.isArray(input.members) || !input.members.length || input.members.length > 32) throw error('模型池需要名称和1–32个成员。');
if (!unrestricted(this.store) && !previous && this.state.pools.length >= 32) throw error('最多保存32个模型池。');
if (!label(input.name) || !Array.isArray(input.members) || !input.members.length || !unrestricted(this.store) && input.members.length > 32) throw error('模型池需要名称和1–32个成员。');
const seen = new Set();
const members = input.members.map(value => {
this.connection(value.connectionId);
@@ -288,7 +289,7 @@ export class ModelHub {
const members = (pool?.members ?? [{ connectionId: selection.id, weight: 1 }]).map(value => ({ ...this.connection(value.connectionId), capabilityEvidence: this.state.capabilityResults?.[value.connectionId], weight: value.weight,
credentialRevision: this.credential(this.connection(value.connectionId))?.revision ?? 0,
...(this.connection(value.connectionId).credentialSource ? { credentialSourceRevision: this.credentialOwner(this.connection(value.connectionId))?.revision ?? null } : {}) }));
if (!members.some(value => this.status(value).status === 'configured' || this.status(value).status === 'cooling')) throw error('没有可用模型连接,请核对启用状态、临时凭据和故障。');
if (!members.some(value => unrestricted(this.store) && value.enabled || this.status(value).status === 'configured' || this.status(value).status === 'cooling')) throw error('没有可用模型连接,请核对启用状态、临时凭据和故障。');
return { ...config, ...messagesAuthSettings(members[0].protocol, members[0].messagesAuth), baseUrl: members[0].baseUrl, model: members[0].model, protocol: modelProtocol(members[0].protocol), streaming: members[0].streaming === true,
nativeParameters: members[0].nativeParameters ?? {}, outputTokenField: members[0].outputTokenField, parameterProfile: members[0].parameterProfile,
modelConnectionId: members[0].id, modelCredentialRevision: members[0].credentialRevision,
@@ -301,18 +302,18 @@ export class ModelHub {
if (!current?.enabled || current.revision !== member.revision || (this.credential(current)?.revision ?? 0) !== member.credentialRevision) return false;
if (current.credentialSource && (!this.credentialOwner(current) || member.credentialSourceRevision !== undefined && this.credentialOwner(current).revision !== member.credentialSourceRevision)) return false;
const health = this.health.get(this.identity(member));
return (!member.requiresKey || !!this.credential(member)?.key) && !health?.blocked && !(health?.cooldownUntil > Date.now());
return unrestricted(this.store) || (!member.requiresKey || !!this.credential(member)?.key) && !health?.blocked && !(health?.cooldownUntil > Date.now());
}
async acquire(routing, runId, excluded, signal, deadline, requirements = []) {
if (this.waiting >= 100) throw error('模型请求队列已满,请稍后继续任务。');
if (!unrestricted(this.store) && this.waiting >= 100) throw error('模型请求队列已满,请稍后继续任务。');
this.waiting++;
try {
while (true) {
signal?.throwIfAborted();
const eligible = routing.members.filter(value => capabilityRejections(value, requirements, value.credentialRevision).length === 0);
const eligible = routing.members.filter(value => unrestricted(this.store) || capabilityRejections(value, requirements, value.credentialRevision).length === 0);
if (!eligible.length) throw Object.assign(error('模型池没有满足本次任务能力的成员;请核对工具调用和流式能力声明。'), { rejections: routing.members.flatMap(value => capabilityRejections(value, requirements, value.credentialRevision)) });
const healthy = eligible.filter(value => this.available(value) && !excluded.has(value.id));
const ready = healthy.filter(value => (this.leases.get(value.id) ?? 0) < value.concurrency);
const ready = healthy.filter(value => unrestricted(this.store) || (value.concurrency === 0 || (this.leases.get(value.id) ?? 0) < value.concurrency));
if (ready.length) {
const remembered = routing.sticky && this.sticky.get(runId);
let selected = ready.find(value => value.id === remembered);
@@ -337,11 +338,11 @@ export class ModelHub {
finally { operation?.finish(); }
}
async completeOwned(config, body, signal, onProgress, plan, execute,beforeDispatch) {
const routing = config.modelRouting, excluded = new Set(), deadline = Date.now() + Math.min(routing.queueTimeoutMs, 60000);
const routing = config.modelRouting, excluded = new Set(), deadline = unrestricted(config) ? Infinity : Date.now() + Math.min(routing.queueTimeoutMs, 60000);
const requestId = plan?.id ?? randomUUID(), runId = plan?.runId ?? requestId;
const requirements = config.capabilityProbe ? [] : ['text', ...(requestVariants(body).some(value => value.tools?.length) ? ['tools'] : []),
...(requestImages(body).length ? ['vision'] : [])];
const rejections = config.capabilityProbe ? [] : routing.members.flatMap(value => capabilityRejections(value, [...requirements, ...(value.streaming ? ['streaming'] : [])], value.credentialRevision));
const rejections = config.capabilityProbe || unrestricted(config) ? [] : routing.members.flatMap(value => capabilityRejections(value, [...requirements, ...(value.streaming ? ['streaming'] : [])], value.credentialRevision));
const eligibleRouting = { ...routing, members: routing.members.filter(value => !rejections.some(item => item.connectionId === value.id)) };
if (!eligibleRouting.members.length) {
const attempt = { id: randomUUID(), requestId, taskId: plan?.taskId ?? null, runId, sessionId: plan?.sessionId ?? null, projectId: plan?.projectId ?? null,
@@ -438,7 +439,7 @@ export class ModelHub {
}
lastError = cause; excluded.add(member.id); this.sticky.delete(runId);
signal?.throwIfAborted();
if ((!diagnostic?.retryable && !diagnostic?.failoverAllowed) || count === routing.maxAttempts) throw cause;
if (config.capacityMode === 'passthrough' || (!diagnostic?.retryable && !diagnostic?.failoverAllowed) || count === routing.maxAttempts) throw cause;
onProgress?.({ phase: 'retrying', attempt: count, maxAttempts: routing.maxAttempts, connectionId: member.id, modelAttemptId: attempt.id,
diagnostic, waitMs: 0, switching: true });
} finally { attempt.finishedAt = stamp(); lease.release(); this.saveAttempts(); }
+6 -6
View File
@@ -15,7 +15,7 @@ export async function readModelStream(response, config, signal, onProgress, tool
let upstreamFailure = null;
let reasoning = '', hasReasoning = false;
const calls = new Map(), responseCalls = new Map();
const messages = config.protocol === 'anthropic-messages' ? messagesStream() : null;
const messages = config.protocol === 'anthropic-messages' ? messagesStream(config) : null;
let eventName = '';
const progress = force => {
if (!force && Date.now() - lastProgress < 100) {
@@ -33,7 +33,7 @@ export async function readModelStream(response, config, signal, onProgress, tool
const processData = raw => {
if (terminal || done || messages?.stopped) throw protocolFailure('模型流在终结后仍包含数据,未采用响应。');
frames++;
if (frames > 100000) throw protocolFailure('模型事件流超过事件数量上限。');
if (config.executionMode !== 'unrestricted' && frames > 100000) throw protocolFailure('模型事件流超过事件数量上限。');
if (raw === '[DONE]') { if (config.protocol !== 'chat-completions' && config.protocol) throw protocolFailure('所选协议缺少正式终结事件。'); done = true; return; }
let event;
try { event = JSON.parse(raw); } catch { throw protocolFailure('模型事件流包含无效JSON。'); }
@@ -43,7 +43,7 @@ export async function readModelStream(response, config, signal, onProgress, tool
if (event.usage && !messages) usage = event.usage;
const failUpstream = () => {
usage = event.response?.usage ?? usage;
const { details } = upstreamCapture({ raw: Buffer.from(raw, 'utf8'), event, scope: 'sse-event', status: response.status, headers: response.headers }, redact);
const { details } = upstreamCapture({ raw: Buffer.from(raw, 'utf8'), event, scope: 'sse-event', ...(config.capacityMode === 'passthrough' ? { maximum: Infinity } : {}), status: response.status, headers: response.headers }, redact);
details.responseId ??= responseId;
upstreamFailure = httpFailure(response.status, (details.message ?? details.reason ?? '上游事件 ' + event.type).slice(0, 600), { upstream: details });
if (event.type === 'response.incomplete') {
@@ -110,7 +110,7 @@ export async function readModelStream(response, config, signal, onProgress, tool
if (choice.finish_reason) { if (finish && finish !== choice.finish_reason) throw protocolFailure('Chat流终结原因发生变化。'); finish = choice.finish_reason; }
}
}
if (calls.size > 12 || responseCalls.size > 12) throw protocolFailure('模型流工具数量超出上限。');
if (config.executionMode !== 'unrestricted' && (calls.size > 12 || responseCalls.size > 12)) throw protocolFailure('模型流工具数量超出上限。');
progress(false);
};
const line = value => {
@@ -127,7 +127,7 @@ export async function readModelStream(response, config, signal, onProgress, tool
if (chunk.done) break;
onBytes?.(chunk.value.length);
bytes += chunk.value.length; hash.update(chunk.value);
if (bytes > 4 * 1024 * 1024) throw protocolFailure('模型事件流超过4MB读取上限。');
if (config.capacityMode !== 'passthrough' && bytes > 4 * 1024 * 1024) throw protocolFailure('模型事件流超过4MB读取上限。');
chunks.push(Buffer.from(chunk.value));
buffer += decoder.decode(chunk.value, { stream: true });
// CRLF, LF and CR line endings, including a CR split across chunks.
@@ -159,7 +159,7 @@ export async function readModelStream(response, config, signal, onProgress, tool
if (!done || !['stop', 'tool_calls'].includes(finish)) throw protocolFailure('Chat流未完整终结或达到输出上限,未执行工具。', 'stream_interrupted');
value = { choices: [{ message: { role: 'assistant', content: text, ...(hasReasoning ? { reasoning_content: reasoning } : {}), ...(calls.size ? { tool_calls: [...calls.entries()].sort((a, b) => a[0] - b[0]).map(([, item]) => item) } : {}) }, finish_reason: finish }], usage };
}
validateModelResponse(config.protocol !== 'chat-completions' && config.protocol ? normalizeProtocolResponse(config, value) : value, tools);
validateModelResponse(config.protocol !== 'chat-completions' && config.protocol ? normalizeProtocolResponse(config, value) : value, tools, config);
validated = true; progress(true);
return { value, evidence: { bytes, frames, sha256: hash.copy().digest('hex'), terminal: true, protocol: config.protocol ?? 'chat-completions' } };
} finally {
+3 -2
View File
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
import { ModelRequestError } from '../../server/diagnostics.mjs';
export const protocolFailure = (message, kind = 'protocol', extra = null) => new ModelRequestError({ kind, source: 'model_connection', origin: 'local', stage: 'model_request',
title: '模型响应未通过完整性核对', message, retryable: false, occurredAt: new Date().toISOString(), ...(extra ? extra : {}) });
@@ -46,12 +47,12 @@ function acceptsEmptyObject(tools, name) {
['type', 'properties', 'required', 'additionalProperties', 'description', 'title', '$schema'].includes(key));
}
export function validateModelResponse(value, tools) {
export function validateModelResponse(value, tools, config = {}) {
const choice = value.choices?.[0], message = choice?.message;
if (choice?.finish_reason === 'length') throw outputTruncatedFailure();
if (!message || choice.finish_reason === 'content_filter') throw protocolFailure('模型响应缺少完整message或因内容过滤未完整结束,未执行工具。');
const calls = message.tool_calls;
if (calls !== undefined && (!Array.isArray(calls) || calls.length > 12)) throw protocolFailure('模型工具调用数量或格式无效。');
if (calls !== undefined && (!Array.isArray(calls) || !unrestricted(config) && calls.length > 12)) throw protocolFailure('模型工具调用数量或格式无效。');
const ids = new Set();
for (const call of calls ?? []) {
if (!call.id || typeof call.id !== 'string' || ids.has(call.id) || call.type !== 'function' || typeof call.function?.name !== 'string' || !call.function.name || typeof call.function.arguments !== 'string') throw protocolFailure('模型工具身份或参数无效。');
+4 -4
View File
@@ -2,7 +2,7 @@ export const DEFAULT_MODEL_TIMEOUT_MS = 300000;
export const DEFAULT_STREAM_IDLE_TIMEOUT_MS = 120000;
export function modelWaitSettings(config = {}) {
const bounded = (value, fallback, minimum, maximum) => Number.isSafeInteger(value) && value >= minimum && value <= maximum ? value : fallback;
const bounded = (value, fallback, minimum, maximum) => Number.isSafeInteger(value) && (value === 0 || value >= minimum && value <= maximum) ? value : fallback;
return { modelResponseTimeoutMs: bounded(config.modelResponseTimeoutMs, DEFAULT_MODEL_TIMEOUT_MS, 15000, 900000),
modelStreamIdleTimeoutMs: bounded(config.modelStreamIdleTimeoutMs, DEFAULT_STREAM_IDLE_TIMEOUT_MS, 5000, 300000) };
}
@@ -11,7 +11,7 @@ export function validateModelWaitSettings(input, previous = {}) {
const next = modelWaitSettings(previous);
for (const [key, minimum, maximum] of [['modelResponseTimeoutMs', 15000, 900000], ['modelStreamIdleTimeoutMs', 5000, 300000]]) {
if (!Object.hasOwn(input, key)) continue;
if (!Number.isSafeInteger(input[key]) || input[key] < minimum || input[key] > maximum) throw Object.assign(new Error('模型等待时限必须为范围内的整数毫秒。'), { status: 400 });
if (!Number.isSafeInteger(input[key]) || input[key] !== 0 && (input[key] < minimum || input[key] > maximum)) throw Object.assign(new Error('模型等待时限必须为范围内的整数毫秒。'), { status: 400 });
next[key] = input[key];
}
return next;
@@ -29,8 +29,8 @@ export function requestDeadline({ signal, timeoutMs, idleTimeoutMs }) {
controller.abort(new DOMException('Model response deadline exceeded', 'TimeoutError'));
};
let bytes = 0;
absoluteTimer = setTimeout(() => abort('total'), Math.max(1, timeoutMs));
absoluteTimer.unref?.();
if (timeoutMs > 0) absoluteTimer = setTimeout(() => abort('total'), Math.max(1, timeoutMs));
absoluteTimer?.unref?.();
const armIdle = () => {
clearTimeout(idleTimer);
if (idleTimeoutMs > 0 && !controller.signal.aborted && !signal?.aborted) {
+9 -4
View File
@@ -1,19 +1,24 @@
import { openDefaults, approvalModes } from '../../shared/contracts/execution-policy.mjs';
import { CAPACITY_RANGES, capacityMode } from '../../shared/contracts/model-capacity.mjs';
const ranges = {
...CAPACITY_RANGES, maxSteps: [1, 30],
maxRunDurationMs: [1000, 3600000], maxRunTokens: [1000, 2000000], maxTaskTokens: [1000, 10000000],
...CAPACITY_RANGES, maxSteps: [0, Number.MAX_SAFE_INTEGER],
maxRunDurationMs: [0, Number.MAX_SAFE_INTEGER], maxRunTokens: [0, Number.MAX_SAFE_INTEGER], maxTaskTokens: [0, Number.MAX_SAFE_INTEGER],
modelResponseTimeoutMs: [0, Number.MAX_SAFE_INTEGER], modelStreamIdleTimeoutMs: [0, Number.MAX_SAFE_INTEGER],
};
// Budget-only edits cannot change the selected route, endpoint or credential.
export function validateRuntimeBudgets(input) {
if (!input || typeof input !== 'object' || Array.isArray(input) || !Object.keys(input).length
|| Object.keys(input).some(key => !['capacityMode', 'historyPolicy'].includes(key) && !Object.hasOwn(ranges, key))) throw new Error('只接受运行预算字段;模型连接请在模型选择中切换。');
|| Object.keys(input).some(key => !['approvalMode', 'executionMode', 'capacityMode', 'historyPolicy'].includes(key) && !Object.hasOwn(ranges, key))) throw new Error('只接受运行设置字段;模型连接请在模型选择中切换。');
for (const [key, value] of Object.entries(input)) {
if (key === 'approvalMode') { if (!approvalModes.includes(value)) throw new Error('请选择请求批准、帮我批准或完全访问权限。'); continue; }
if (key === 'executionMode') { if (!['unrestricted', 'restricted'].includes(value)) throw new Error('执行方式无效。'); continue; }
if (key === 'capacityMode') { capacityMode(value); continue; }
if (key === 'historyPolicy') { if (!['preserve', 'compact'].includes(value)) throw new Error('请选择完整传递或允许整理历史。'); continue; }
const [min, max] = ranges[key];
if (!Number.isSafeInteger(value) || value < min || value > max) throw new Error(key + ' 需填写范围内的整数。');
}
return { ...input, ...(!Object.hasOwn(input, 'capacityMode') && ['contextLimit', 'maxOutputTokens'].some(key => Object.hasOwn(input, key)) ? { capacityMode: 'manual' } : {}) };
if (input.executionMode === 'unrestricted') return { ...input, ...openDefaults };
return { ...input, ...(input.capacityMode === 'passthrough' ? { historyPolicy: 'preserve' } : {}), ...(!Object.hasOwn(input, 'capacityMode') && ['contextLimit', 'maxOutputTokens'].some(key => Object.hasOwn(input, key)) ? { capacityMode: 'manual' } : {}) };
}
+2 -2
View File
@@ -1,7 +1,7 @@
import { Agent,EnvHttpProxyAgent,fetch } from 'undici';
export class ModelTransport {
constructor({environment=process.env,lookup,connectTimeoutMs=10000}={}){
constructor({environment=process.env,lookup,connectTimeoutMs=0}={}){
const setting=(lower,upper)=>environment[lower]??environment[upper]??'';
this.proxy={httpProxy:setting('http_proxy','HTTP_PROXY'),httpsProxy:setting('https_proxy','HTTPS_PROXY'),noProxy:setting('no_proxy','NO_PROXY')};
this.connect={autoSelectFamily:true,autoSelectFamilyAttemptTimeout:250,timeout:connectTimeoutMs,...(lookup?{lookup}:{})};
@@ -10,7 +10,7 @@ export class ModelTransport {
}
fetch(url,options){
this.dispatcher??=this.profile.httpProxyConfigured||this.profile.httpsProxyConfigured
?new EnvHttpProxyAgent({...this.proxy,connect:this.connect,proxyTls:this.connect,requestTls:this.connect}):new Agent({connect:this.connect});
?new EnvHttpProxyAgent({...this.proxy,connect:this.connect,proxyTls:this.connect,requestTls:this.connect,headersTimeout:0,bodyTimeout:0}):new Agent({connect:this.connect,headersTimeout:0,bodyTimeout:0});
return fetch(url,{...options,dispatcher:this.dispatcher});
}
async close(){const dispatcher=this.dispatcher;this.dispatcher=null;await dispatcher?.close();}
+8 -8
View File
@@ -20,7 +20,7 @@ export function retryAfterMilliseconds(value, now = Date.now()) {
// Captures are bounded independently of the generated-response limit. An
// interrupted or truncated prefix never claims to be the complete response.
export async function readErrorResponse(response, signal) {
export async function readErrorResponse(response, signal, maximum = ERROR_CAPTURE_LIMIT) {
if (!response.body) return { raw: Buffer.alloc(0), receivedBytes: 0, truncated: false };
const reader = response.body.getReader(), parts = [];
let receivedBytes = 0, capturedBytes = 0, truncated = false, interrupted = false;
@@ -30,9 +30,9 @@ export async function readErrorResponse(response, signal) {
const { done, value } = await reader.read();
if (done) break;
receivedBytes += value.length;
const keep = Math.min(value.length, ERROR_CAPTURE_LIMIT - capturedBytes);
const keep = Math.min(value.length, maximum - capturedBytes);
if (keep) { parts.push(Buffer.from(value.subarray(0, keep))); capturedBytes += keep; }
if (receivedBytes > ERROR_CAPTURE_LIMIT) { truncated = true; break; }
if (receivedBytes > maximum) { truncated = true; break; }
}
} catch (cause) {
interrupted = true;
@@ -44,8 +44,8 @@ export async function readErrorResponse(response, signal) {
}
export function upstreamCapture({ raw, receivedBytes = raw.length, truncated = false, interrupted = false, status,
headers, event, scope = 'http-body' }, redact = String) {
const bounded = raw.subarray(0, ERROR_CAPTURE_LIMIT), decoded = bounded.toString('utf8');
headers, event, scope = 'http-body', maximum = ERROR_CAPTURE_LIMIT }, redact = String) {
const bounded = raw.subarray(0, Number.isFinite(maximum) ? maximum : raw.length), decoded = bounded.toString('utf8');
const text = sanitizeModelText(decoded, redact), changed = text !== decoded;
const capture = changed ? Buffer.from(text, 'utf8') : Buffer.from(bounded);
let parsed = event;
@@ -70,7 +70,7 @@ export function upstreamCapture({ raw, receivedBytes = raw.length, truncated = f
schema: 1, scope, httpStatus: status,
code: field('code', fields?.code, 160), type: field('type', fields?.type ?? (parsed?.type === 'error' ? null : parsed?.type), 160),
message: field('message', fields?.message ?? (typeof original === 'string' ? original : null), 4096),
param: field('param', fields?.param), reason: field('reason', parsed?.response?.incomplete_details?.reason ?? parsed?.incomplete_details?.reason),
param: field('param', fields?.param), reason: field('reason', parsed?.response?.incomplete_details?.reason ?? parsed?.incomplete_details?.reason ?? parsed?.choices?.[0]?.finish_reason ?? parsed?.stop_reason),
requestId: diagnosticHeaders['x-request-id'] ?? diagnosticHeaders['request-id'] ?? diagnosticHeaders.requestid
?? diagnosticHeaders['anthropic-request-id'] ?? diagnosticHeaders['x-amzn-requestid']
?? field('requestId', parsed?.request_id ?? fields?.request_id ?? parsed?.requestId),
@@ -80,8 +80,8 @@ export function upstreamCapture({ raw, receivedBytes = raw.length, truncated = f
...(retryAfter && retryAfterMs === null ? { retryAfterInvalid: true } : {}),
rawPreview: text.slice(0, PREVIEW_LIMIT), previewTruncated: text.length > PREVIEW_LIMIT,
capture: { scope, receivedBytes, capturedBytes: bounded.length, storedBytes: Buffer.byteLength(text.slice(0, PREVIEW_LIMIT), 'utf8'), retention: 'preview-only',
complete: !truncated && !interrupted && raw.length <= ERROR_CAPTURE_LIMIT,
truncated: truncated || raw.length > ERROR_CAPTURE_LIMIT, interrupted, capturedRange: [0, bounded.length],
complete: !truncated && !interrupted && raw.length <= maximum,
truncated: truncated || raw.length > maximum, interrupted, capturedRange: [0, bounded.length],
redacted: changed, sha256: createHash('sha256').update(capture).digest('hex') },
...(shortenedFields.length ? { shortenedFields } : {}),
};
+5 -5
View File
@@ -5,7 +5,7 @@ import { readOwnedProcessTree } from './owned-process-tree.mjs';
// Both checks and dependency preparation use this direct, shell-free process
// owner. Callers choose fixed invocations and interpret their own evidence.
export async function runOwnedCommand(invocation, { cwd, env, signal, onSpawn = null, input = null, timeoutMs = 180000, onOutput = null } = {}) {
export async function runOwnedCommand(invocation, { cwd, env, signal, onSpawn = null, input = null, timeoutMs = 180000, unlimitedOutput = false, onOutput = null } = {}) {
const started = Date.now(), at = () => new Date().toISOString();
if (signal.aborted) return { status: 'cancelled', exitCode: null, durationMs: 0, stdout: '', stderr: '', process: null };
return new Promise(resolve => {
@@ -16,10 +16,10 @@ export async function runOwnedCommand(invocation, { cwd, env, signal, onSpawn =
const processInfo = { pid: child.pid ?? null, hostPid: process.pid, executable: invocation.executable,
argsSha256: createHash('sha256').update(JSON.stringify(invocation.args)).digest('hex'), cwd, startedAt: at() };
const append = (name, text) => { const value = streams[name]; value.characters += text.length;
value.head = (value.head + text).slice(0, 240000); value.tail = (value.tail + text).slice(-240000);
value.head = unlimitedOutput ? value.head + text : (value.head + text).slice(0, 240000); value.tail = unlimitedOutput ? '' : (value.tail + text).slice(-240000);
if (onOutput && !settled) { try { onOutput(name, text); } catch (error) { ownershipError = error; terminate(); } }
};
const captured = name => { const value = streams[name]; return value.characters <= 240000 ? value.head
const captured = name => { const value = streams[name]; return unlimitedOutput || value.characters <= 240000 ? value.head
: value.characters <= 480000 ? value.head + value.tail.slice(value.head.length - value.characters)
: value.head + '\n[中间日志超出保存上限,保留开头和结尾]\n' + value.tail; };
const captureTree = async (publish = true) => {
@@ -47,7 +47,7 @@ export async function runOwnedCommand(invocation, { cwd, env, signal, onSpawn =
resolve({ status: unknown ? 'unknown' : signal.aborted ? 'cancelled' : timedOut || error || ownershipError || code !== 0 ? 'failed' : 'passed',
exitCode: code, durationMs: Date.now() - started, stdout: captured('stdout'),
stderr: captured('stderr') + (error ? '\n' + error.message : '') + (ownershipError ? '\n' + ownershipError.message : ''),
timedOut, truncated: streams.stdout.characters > 480000 || streams.stderr.characters > 480000,
timedOut, truncated: !unlimitedOutput && (streams.stdout.characters > 480000 || streams.stderr.characters > 480000),
...(onSpawn ? { process: { ...processInfo, rootExited: rootClosed, treeTermination: terminating ? unknown ? 'unknown' : 'confirmed' : 'not_requested' } } : {}),
reason: unknown ? '进程结束未得到确认,需要核对实际副作用。' : timedOut ? '命令超过时间上限,已请求终止所属进程树。' : error?.message ?? ownershipError?.message ?? null });
};
@@ -64,7 +64,7 @@ export async function runOwnedCommand(invocation, { cwd, env, signal, onSpawn =
}
killTimer = setTimeout(() => { void finish(null, null, true); }, 5000);
};
const timeout = setTimeout(() => { timedOut = true; terminate(); }, timeoutMs);
const timeout = timeoutMs > 0 ? setTimeout(() => { timedOut = true; terminate(); }, timeoutMs) : null;
signal.addEventListener('abort', terminate, { once: true });
for (const name of ['stdout', 'stderr']) {
child[name].on('data', bytes => append(name, streams[name].decoder.write(bytes)));
+2 -1
View File
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
@@ -62,7 +63,7 @@ export class LocalFilePreviews {
if (!mediaType) throw fail('此文件类型不用于网页预览。', 403);
await verifyWorkspaceProject(this.store, project);
const file = safePath(project, resource), stat = fs.statSync(file);
if (!stat.isFile() || stat.size > 20 * 1024 * 1024) throw fail('资源不存在或超过 20 MB 预览上限。', 413);
if (!stat.isFile() || stat.size > ceiling(this.store, 20 * 1024 * 1024)) throw fail('资源不存在或超过 20 MB 预览上限。', 413);
const bytes = fs.readFileSync(file);
entry.lastRead = Date.now();
response.writeHead(200, { 'Content-Type': mediaType, 'Content-Length': bytes.length });
+2 -1
View File
@@ -1,3 +1,4 @@
import { unrestricted } from '../../shared/contracts/execution-policy.mjs';
import fs from 'node:fs';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
@@ -58,7 +59,7 @@ export class PreviewManager {
const plan = { schemaVersion: 1, id: randomUUID(), sessionId: session.id, projectId: project.id, taskId: session.taskId, runId: session.runId,
root: project.root, workspace: projectWorkspaceIdentity(project), nodeIdentity: node.identity, sourceFingerprint: inspection.sourceFingerprint,
cli, script: manifest.scripts.dev, invocation: { executable: node.runtime.node.path, args: [cli.path, '--host', '127.0.0.1', '--port', String(port), '--strictPort', '--clearScreen', 'false'] },
port, url: 'http://127.0.0.1:' + port + '/', timeoutMs: 8 * 60 * 60 * 1000, status: 'planned', createdAt: at() };
port, url: 'http://127.0.0.1:' + port + '/', timeoutMs: unrestricted(this.store) ? 0 : 8 * 60 * 60 * 1000, status: 'planned', createdAt: at() };
plan.fingerprint = hash(seal(plan)); const artifact = this.artifact(session, plan.runId, seal(plan), 'preview-plan');
plan.artifactId = artifact.id; plan.artifactSha256 = artifact.sha256;
return this.store.putRecord('preview_plan', session, plan, 'preview.planned');
+21 -19
View File
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../shared/contracts/execution-policy.mjs';
import fs from 'node:fs';
import path from 'node:path';
import { createHash } from 'node:crypto';
@@ -19,33 +20,34 @@ function gitMarker(root) {
const languages = { '.js': 'JavaScript', '.mjs': 'JavaScript', '.cjs': 'JavaScript', '.ts': 'TypeScript', '.tsx': 'TypeScript', '.mts': 'TypeScript', '.cts': 'TypeScript', '.jsx': 'JavaScript', '.py': 'Python', '.go': 'Go', '.rs': 'Rust', '.cs': 'C#', '.vue': 'Vue', '.html': 'HTML', '.css': 'CSS' };
const recognizedScripts = /^(test(?::[a-z0-9_-]+)?|typecheck|check|lint|build)$/i;
async function gitCommand(root, args) {
async function gitCommand(project, args) {
const root = safePath(project);
try {
const result = await runGit(root, args, { timeoutMs: 5000, maximumBytes: 512000 });
const result = await runGit(root, args, { timeoutMs: unrestricted(project) ? 0 : 5000, maximumBytes: ceiling(project, 512000) });
return { ok: result.ok, output: result.text, error: result.ok ? null : result.code };
} catch (error) { return { ok: false, output: '', error: error.code ?? 'git-unavailable' }; }
}
export async function gitBaseline(project) {
const root = safePath(project);
const probe = await gitCommand(root, ['rev-parse', '--is-inside-work-tree']);
const probe = await gitCommand(project, ['rev-parse', '--is-inside-work-tree']);
if (!probe.ok || probe.output.trim() !== 'true') return { available: false, head: null, branch: null, dirty: false, status: '', complete: true, paths: null };
const top = await gitCommand(root, ['rev-parse', '--show-toplevel']);
const top = await gitCommand(project, ['rev-parse', '--show-toplevel']);
const normalize = value => process.platform === 'win32' ? path.resolve(value).toLowerCase() : path.resolve(value);
if (!top.ok || normalize(top.output.trim()) !== normalize(root)) return { available: false, parentRepository: true,
note: '上级目录的Git仓库不作为当前项目独立基线。', head: null, branch: null, dirty: false, status: '', complete: true, paths: null };
// Even status may run a repository's clean/process filter. Read only the
// configuration key names, then disable those commands for this inspection.
const filterConfig = await gitCommand(root, ['config', '--null', '--name-only', '--get-regexp', '^filter\\..*\\.(clean|process|required)$']);
const filterConfig = await gitCommand(project, ['config', '--null', '--name-only', '--get-regexp', '^filter\\..*\\.(clean|process|required)$']);
const filtersKnown = filterConfig.ok || filterConfig.error === 1;
const drivers = [...new Set(filterConfig.output.split('\0').filter(key => /^filter\..+\.(clean|process|required)$/i.test(key)).map(key => key.replace(/\.(clean|process|required)$/i, '')))];
const filterOverrides = drivers.flatMap(key => ['-c', key + '.clean=', '-c', key + '.process=', '-c', key + '.required=false']);
const [status, head, branch, files] = await Promise.all([
filtersKnown ? gitCommand(root, [...filterOverrides, 'status', '--porcelain=v1', '-z', '--untracked-files=all', '--ignore-submodules=all', '--', '.'])
filtersKnown ? gitCommand(project, [...filterOverrides, 'status', '--porcelain=v1', '-z', '--untracked-files=all', '--ignore-submodules=all', '--', '.'])
: Promise.resolve({ ok: false, output: '', error: 'filter-config-unavailable' }),
gitCommand(root, ['rev-parse', '--verify', 'HEAD']),
gitCommand(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']),
gitCommand(root, ['ls-files', '-z', '--cached', '--others', '--exclude-standard', '--', '.']),
gitCommand(project, ['rev-parse', '--verify', 'HEAD']),
gitCommand(project, ['symbolic-ref', '--quiet', '--short', 'HEAD']),
gitCommand(project, ['ls-files', '-z', '--cached', '--others', '--exclude-standard', '--', '.']),
]);
return { available: true, head: head.ok ? head.output.trim() : null, branch: branch.ok ? branch.output.trim() : null,
dirty: !!status.output, status: status.output.replaceAll('\0', '\n').slice(0, 8000),
@@ -57,7 +59,7 @@ export async function gitBaseline(project) {
function declaration(project, relative, maximum = 64000) {
const file = safePath(project, relative, true);
if (!fs.existsSync(file)) return null;
if (!fs.statSync(file).isFile() || fs.statSync(file).size > maximum) throw new Error(relative + ' 超过工程声明的读取上限。');
if (!fs.statSync(file).isFile() || fs.statSync(file).size > ceiling(project, maximum)) throw new Error(relative + ' 超过工程声明的读取上限。');
return readText(project, relative);
}
@@ -71,11 +73,11 @@ function framework(script) {
export async function inspectProject(project, { includeFiles = false, strictSnapshot = false } = {}) {
const root = safePath(project), rootAccess = strictSnapshot ? accessIdentity(fs.lstatSync(root)) : null,
marker = strictSnapshot ? gitMarker(root) : null, git = await gitBaseline(project);
const inventory = git.paths ? null : listFiles(project, '', 8, 1500);
const inventory = git.paths ? null : listFiles(project, '', ceiling(project, 8), ceiling(project, 1500), { inventoryOnly: true });
const candidates = (git.paths ?? inventory.files.filter(file => file.kind === 'file').map(file => file.path)).slice().sort();
const fingerprints = [], names = [], excluded = [], detected = new Set(), sourceFiles = [];
let bytes = 0, complete = git.complete && !inventory?.truncated && candidates.length <= 1000;
for (const relative of candidates.slice(0, 1000)) {
let bytes = 0, complete = git.complete && !inventory?.truncated && candidates.length <= ceiling(project, 1000);
for (const relative of candidates.slice(0, ceiling(project, 1000))) {
if (excludedFromInventory(relative)) { excluded.push(relative); continue; }
try {
if (strictSnapshot) {
@@ -91,7 +93,7 @@ export async function inspectProject(project, { includeFiles = false, strictSnap
if (!info.isFile() || info.isSymbolicLink()) { excluded.push(relative); continue; }
names.push(relative);
const language = languages[path.extname(relative).toLowerCase()]; if (language) detected.add(language);
if (info.size > 1024 * 1024 || bytes + info.size > 16 * 1024 * 1024) { complete = false; fingerprints.push([relative, info.size, 'outside-read-budget']); continue; }
if (!unrestricted(project) && (info.size > 1024 * 1024 || bytes + info.size > 16 * 1024 * 1024)) { complete = false; fingerprints.push([relative, info.size, 'outside-read-budget']); continue; }
const contents = fs.readFileSync(file), sha256 = hash(contents); bytes += contents.length; fingerprints.push([relative, sha256]);
sourceFiles.push({ path: relative, sha256, bytes: contents.length, language: language ?? null,
...(strictSnapshot ? { access: accessIdentity(info) } : {}) });
@@ -136,8 +138,8 @@ export async function inspectProject(project, { includeFiles = false, strictSnap
git: visibleGit, fingerprint, sourceFingerprint, inspectedAt: new Date().toISOString(),
...(includeFiles ? { files: sourceFiles } : {}),
...(strictSnapshot ? { snapshot: { rootAccess, gitMarker: marker, candidates } } : {}),
scope: { complete, scannedFiles: fingerprints.length, bytes, excludedFiles: excluded.length, maximumFiles: 1000, maximumBytes: 16 * 1024 * 1024,
note: '有界快照;Git工程遵循ignore并包含未跟踪源码,跳过依赖、链接和常见凭据路径。' } };
scope: { complete, scannedFiles: fingerprints.length, bytes, excludedFiles: excluded.length, maximumFiles: unrestricted(project) ? null : 1000, maximumBytes: unrestricted(project) ? null : 16 * 1024 * 1024,
note: unrestricted(project) ? '完整源码快照;无本地数量或体积上限,遵循源码范围和Git ignore。' : '有界快照;Git工程遵循ignore并包含未跟踪源码,跳过依赖、链接和常见凭据路径。' } };
}
// Close the index snapshot without reparsing manifests or repeating unrelated
@@ -148,13 +150,13 @@ export async function verifyIndexSnapshot(project, inspection) {
let candidates;
if (inspection.git.available) {
const [files, head, branch] = await Promise.all([
gitCommand(root, ['ls-files', '-z', '--cached', '--others', '--exclude-standard', '--', '.']),
gitCommand(root, ['rev-parse', '--verify', 'HEAD']), gitCommand(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']),
gitCommand(project, ['ls-files', '-z', '--cached', '--others', '--exclude-standard', '--', '.']),
gitCommand(project, ['rev-parse', '--verify', 'HEAD']), gitCommand(project, ['symbolic-ref', '--quiet', '--short', 'HEAD']),
]);
if (!files.ok || (head.ok ? head.output.trim() : null) !== inspection.git.head || (branch.ok ? branch.output.trim() : null) !== inspection.git.branch) throw changedSnapshot();
candidates = [...new Set(files.output.split('\0').filter(Boolean))].sort();
} else {
const inventory = listFiles(project, '', 8, 1500);
const inventory = listFiles(project, '', ceiling(project, 8), ceiling(project, 1500), { inventoryOnly: true });
candidates = inventory.files.filter(file => file.kind === 'file').map(file => file.path).sort();
if (inspection.scope.complete && inventory.truncated) throw changedSnapshot();
}
+3 -2
View File
@@ -5,6 +5,7 @@ import { createHash, randomUUID } from 'node:crypto';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { projectEnvironment } from './process-environment.mjs';
import { ceiling } from '../shared/contracts/execution-policy.mjs';
const executeFile = promisify(execFile);
const digest = bytes => createHash('sha256').update(bytes).digest('hex');
@@ -105,9 +106,9 @@ export async function preparePythonInvocation(check, project, { signal } = {}) {
} };
}
export function readPythonEvidence(invocation, exitCode) {
export function readPythonEvidence(invocation, exitCode, config = {}) {
if (!fs.existsSync(invocation.resultPath)) throw new Error('Python进程未返回结构化结果,日志文字不能代替测试统计。');
if (fs.statSync(invocation.resultPath).size > 2 * 1024 * 1024) throw new Error('Python结构化结果超过读取上限。');
if (fs.statSync(invocation.resultPath).size > ceiling(config, 2 * 1024 * 1024)) throw new Error('Python结构化结果超过读取上限。');
const text = fs.readFileSync(invocation.resultPath, 'utf8'), result = JSON.parse(text);
validatePythonEvidence(result, invocation, exitCode);
return { result, text };
+19 -18
View File
@@ -6,6 +6,7 @@ import { RESEARCH_ACTIVE, researchError, researchFileIdentity, researchTargetCon
import { artifactPage } from './context/read-budget.mjs';
import { createResearchOutputDirectory } from './tools/research-output.mjs';
import { assertMcpResolved } from './tools/mcp-contract.mjs';
import { unrestricted, ceiling } from '../shared/contracts/execution-policy.mjs';
const at = () => new Date().toISOString();
const sha = text => createHash('sha256').update(text, 'utf8').digest('hex');
@@ -33,11 +34,11 @@ export class ResearchManager {
}
release(id, active) { this.active.delete(id); if (this.projects.get(active.projectId) === id) this.projects.delete(active.projectId); }
async register(session, input) {
if (!input || typeof input.path !== 'string' || input.label !== undefined && (typeof input.label !== 'string' || input.label.length > 160)
|| input.goal !== undefined && (typeof input.goal !== 'string' || !input.goal.trim() || input.goal.length > 20000)) throw researchError('请输入工件路径,名称最多160字,研究目标最多20000字。', 400);
if (!input || typeof input.path !== 'string' || input.label !== undefined && (typeof input.label !== 'string' || input.label.length > ceiling(this.store, 160))
|| input.goal !== undefined && (typeof input.goal !== 'string' || !input.goal.trim() || input.goal.length > ceiling(this.store, 20000))) throw researchError('请输入有效工件路径、名称与研究目标。', 400);
const id = randomUUID(), active = this.reserve(session, id), identity = { taskId: session.taskId, runId: session.runId };
active.promise = (async () => {
const file = await researchFileIdentity(input.path, { signal: active.signal }); active.signal.throwIfAborted();
const file = await researchFileIdentity(input.path, { signal: active.signal, config: this.store.config }); active.signal.throwIfAborted();
if (session.taskId !== identity.taskId || session.runId !== identity.runId) throw researchError('登记期间任务已经切换,请重新登记。');
let task = this.store.core.task.get(session.taskId);
if (!task || ['completed', 'idle'].includes(task.status)) {
@@ -59,8 +60,8 @@ export class ResearchManager {
})().finally(() => this.release(id, active));
return active.promise;
}
targets(session) { return [...this.store.core.research_target.values()].filter(target => target.sessionId === session.id && target.taskId === session.taskId).slice(-32); }
jobs(session) { return [...this.store.core.research_job.values()].filter(job => job.sessionId === session.id).slice(-30); }
targets(session) { return [...this.store.core.research_target.values()].filter(target => target.sessionId === session.id && target.taskId === session.taskId).slice(-ceiling(this.store, 32)); }
jobs(session) { return [...this.store.core.research_job.values()].filter(job => job.sessionId === session.id).slice(-ceiling(this.store, 30)); }
targetFor(session, id) {
const target = this.store.owned('research_target', id, session.id);
if (target.taskId !== session.taskId) throw researchError('工件属于此前Task,请在当前任务重新登记。');
@@ -94,7 +95,7 @@ export class ResearchManager {
const event = session.events.find(value => value.id === job.eventId);
const phase = (status, summary) => { job.status = status; job.summary = summary; event.phase = status; event.output = summary; this.store.save(session, { type: 'research.' + status, detail: { jobId: job.id } }); };
try {
job.before = await researchFileIdentity(target.path, { signal: active.signal }); active.signal.throwIfAborted();
job.before = await researchFileIdentity(target.path, { signal: active.signal, config: this.store.config }); active.signal.throwIfAborted();
if (job.before.sha256 !== target.sha256 || job.before.bytes !== target.bytes) throw researchError('工件在登记后变化,请按新版本重新登记。');
const reusable = !options.refresh && [...this.store.core.research_job.values()].findLast(value => value.id !== job.id && value.sessionId === session.id
&& value.taskId === job.taskId && value.targetId === target.id && value.operationId === job.operationId && value.status === 'completed' && value.evidenceBinding?.verified);
@@ -105,7 +106,7 @@ export class ResearchManager {
} else {
const output = createResearchOutputDirectory(this.store.directory, job.id);
const scratch = output.path; job.outputDirectory = scratch; job.outputScope = output.scope;
adapter = this.adapterFactory(job.installation, { cwd: scratch, timeoutMs: this.timeoutMs,
adapter = this.adapterFactory(job.installation, { cwd: scratch, timeoutMs: unrestricted(this.store) ? 0 : this.timeoutMs, config: this.store.config,
onClient: client => { active.client = client; job.connection = { id: client.id, pid: client.pid ?? null, startedAt: client.startedAt }; this.store.save(session, { type: 'research.connection_owned', detail: { jobId: job.id } }); } });
phase('connecting', '正在核对REA握手和实际工具契约。');
const contract = await adapter.connect(active.signal);
@@ -119,7 +120,7 @@ export class ResearchManager {
job.bundle = sealResearchDocument(this.store, session, run, bundleText, 'research-evidence-bundle');
job.evidence = sealResearchDocument(this.store, session, run, JSON.stringify(evidence), 'research-evidence');
job.evidenceBinding = bindReaEvidence({ structuredContent: evidence }, target, job.operation); job.evidenceId = evidence.evidence_id;
job.after = await researchFileIdentity(target.path, { signal: active.signal }); active.signal.throwIfAborted();
job.after = await researchFileIdentity(target.path, { signal: active.signal, config: this.store.config }); active.signal.throwIfAborted();
if (job.after.sha256 !== target.sha256 || job.after.bytes !== target.bytes) throw researchError('分析期间工件变化,原响应保留但不作为登记版本的已核验结果。');
job.summary = '原完整Evidence与登记工件、分析前后SHA256均已核对。静态候选和未知范围见原限制。';
}
@@ -158,17 +159,17 @@ export class ResearchManager {
|| !bundle.records?.some(record => JSON.stringify(record) === JSON.stringify(evidence))) throw researchError('原完整Evidence不在封存的Bundle中。');
readResearchDocument(this.store, session, job.raw); return evidence;
}
readEvidence(session, jobId, { pointer = '/normalized_result', offset = 0, limit = 4000, maximumMessageBytes = 30000, callId = '' } = {}) {
const job = this.store.owned('research_job', jobId, session.id), evidence = this.verifiedEvidence(session, job), value = researchPointer(evidence, pointer);
readEvidence(session, jobId, { pointer = '/normalized_result', offset = 0, limit, maximumMessageBytes = ceiling(this.store, 30000), callId = '' } = {}) {
const job = this.store.owned('research_job', jobId, session.id), evidence = this.verifiedEvidence(session, job), value = researchPointer(evidence, pointer, this.store.config);
const text = JSON.stringify(value, null, 2), viewSha256 = sha(text);
const metadata = { research_job_id: job.id, evidence_id: job.evidenceId, target_sha256: job.targetSha256,
pointer, view_sha256: viewSha256, source_artifact_id: job.evidence.id, source_document_sha256: job.evidence.documentSha256,
available_fields: value && typeof value === 'object' ? Object.keys(value).slice(0, 32) : [],
available_fields: value && typeof value === 'object' ? Object.keys(value).slice(0, ceiling(this.store, 32)) : [],
navigation: 'Use read_research_evidence with the same research_job_id and pointer, then next_offset.', scope: job.scope };
const frameBytes = object => Buffer.byteLength(JSON.stringify({ role: 'tool', tool_call_id: callId, content: JSON.stringify(object) }), 'utf8');
const reserve = frameBytes(metadata) + 128;
if (maximumMessageBytes - reserve < 1024) throw researchError('当前完整请求没有足够的Evidence页预算,请使用已返回摘要或缩小请求范围。');
const page = artifactPage({ id: job.evidence.id, sha256: viewSha256, kind: 'research-evidence-view' }, text, { offset, limit }, { maximumMessageBytes: maximumMessageBytes - reserve, callId });
if (maximumMessageBytes - reserve < 1) throw researchError('当前完整请求没有足够的Evidence页预算,请使用已返回摘要或缩小请求范围。');
const page = artifactPage({ id: job.evidence.id, sha256: viewSha256, kind: 'research-evidence-view' }, text, { offset, limit: limit ?? (unrestricted(this.store) ? text.length : 4000) }, { maximumMessageBytes: maximumMessageBytes - reserve, callId });
delete page.artifact_id;
const result = { ...page, ...metadata, maximum_message_bytes: maximumMessageBytes };
if (frameBytes(result) > maximumMessageBytes) throw researchError('Evidence页超过当前完整协议预算,未返回超限页面。');
@@ -176,16 +177,16 @@ export class ResearchManager {
}
result(job) {
const summary = job.evidenceBinding?.summary ?? null, statistics = job.evidenceBinding?.statistics ?? null;
const summaryFits = Buffer.byteLength(JSON.stringify(summary), 'utf8') <= 2400;
const summaryFits = Buffer.byteLength(JSON.stringify(summary), 'utf8') <= ceiling(this.store, 2400);
return { status: job.status === 'completed' ? 'completed' : 'failed', research_status: job.status, research_job_id: job.id,
target_id: job.targetId, target_sha256: job.targetSha256, evidence_id: job.evidenceId ?? null, evidence_verified: !!job.evidenceBinding?.verified,
evidence_artifact_id: job.evidence?.id ?? null, bundle_artifact_id: job.bundle?.id ?? null, raw_artifact_id: job.raw?.id ?? null,
reused_from_job_id: job.reusedFromJobId ?? null, summary: summaryFits ? summary : null, summary_complete: summaryFits,
summary_excerpt: summaryFits ? null : JSON.stringify(summary).slice(0, 2400),
statistics: Buffer.byteLength(JSON.stringify(statistics), 'utf8') <= 1200 ? statistics : null,
limitations: (job.evidenceBinding?.limitations ?? []).slice(0, 12).map(value => value.slice(0, 280)),
limitations_complete: (job.evidenceBinding?.limitations ?? []).length <= 12 && (job.evidenceBinding?.limitations ?? []).every(value => value.length <= 280),
message: job.summary.slice(0, 1500), requires_review: job.requiresVerification, scope: job.scope };
statistics: Buffer.byteLength(JSON.stringify(statistics), 'utf8') <= ceiling(this.store, 1200) ? statistics : null,
limitations: (job.evidenceBinding?.limitations ?? []).slice(0, ceiling(this.store, 12)).map(value => value.slice(0, ceiling(this.store, 280))),
limitations_complete: (job.evidenceBinding?.limitations ?? []).length <= ceiling(this.store, 12) && (job.evidenceBinding?.limitations ?? []).every(value => value.length <= ceiling(this.store, 280)),
message: job.summary.slice(0, ceiling(this.store, 1500)), requires_review: job.requiresVerification, scope: job.scope };
}
originalDocument(session, job, kind = 'bundle') {
if (!['bundle', 'raw'].includes(kind) || !job[kind]) throw researchError('这个操作尚未保存所选原文。', 404);
+16 -15
View File
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
import fs from 'node:fs';
import path from 'node:path';
import { createHash, randomUUID } from 'node:crypto';
@@ -16,17 +17,17 @@ const text = (value, maximum, name) => {
return value.trim();
};
export function readSkillSource(filename) {
export function readSkillSource(filename, config = {}) {
if (typeof filename !== 'string' || !path.isAbsolute(filename) || path.basename(filename).toLowerCase() !== 'skill.md') throw fail('请选择本地SKILL.md的绝对路径。');
const stat = fs.lstatSync(filename);
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > SKILL_LIMITS.fileBytes) throw fail('技能来源需要不超过64KB的常规SKILL.md文件。');
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > ceiling(config, SKILL_LIMITS.fileBytes)) throw fail('技能来源需要不超过64KB的常规SKILL.md文件。');
const resolved = fs.realpathSync.native(filename), handle = fs.openSync(filename, 'r');
try {
const opened = fs.fstatSync(handle);
if (!opened.isFile() || opened.size > SKILL_LIMITS.fileBytes || opened.dev !== stat.dev || opened.ino !== stat.ino) throw fail('技能来源在读取前已变化。', 409);
const bytes = Buffer.alloc(SKILL_LIMITS.fileBytes + 1), length = fs.readSync(handle, bytes, 0, bytes.length, 0), data = bytes.subarray(0, length);
if (!opened.isFile() || opened.size > ceiling(config, SKILL_LIMITS.fileBytes) || opened.dev !== stat.dev || opened.ino !== stat.ino) throw fail('技能来源在读取前已变化。', 409);
const bytes = Buffer.alloc((unrestricted(config) ? opened.size : SKILL_LIMITS.fileBytes) + 1), length = fs.readSync(handle, bytes, 0, bytes.length, 0), data = bytes.subarray(0, length);
const after = fs.fstatSync(handle);
if (length > SKILL_LIMITS.fileBytes || length !== opened.size || after.size !== opened.size || after.mtimeMs !== opened.mtimeMs
if (length > ceiling(config, SKILL_LIMITS.fileBytes) || length !== opened.size || after.size !== opened.size || after.mtimeMs !== opened.mtimeMs
|| after.ctimeMs !== opened.ctimeMs || fs.realpathSync.native(filename) !== resolved) throw fail('技能来源在读取期间变化或超出64KB。', 409);
const content = data.toString('utf8');
if (!Buffer.from(content, 'utf8').equals(data) || content.includes('\0') || !content.trim()) throw fail('技能来源需要非空UTF-8文本。');
@@ -49,11 +50,11 @@ export const skillToolDefinitions = [{ type: 'function', function: { name: 'read
offset: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 16000 },
} } } }];
export function skillReadInput(input) {
export function skillReadInput(input, config = {}) {
exact(input, ['skill_id', 'revision', 'source_sha256', 'offset', 'limit']);
if (typeof input.skill_id !== 'string' || !/^[a-f0-9-]{36}$/i.test(input.skill_id) || !Number.isSafeInteger(input.revision) || input.revision < 1
|| typeof input.source_sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(input.source_sha256)) throw fail('技能读取需要本次目录的ID、修订和来源SHA256。');
for (const field of ['offset', 'limit']) if (input[field] !== undefined && (!Number.isSafeInteger(input[field]) || input[field] < (field === 'offset' ? 0 : 1) || field === 'limit' && input[field] > 16000)) throw fail('技能分页范围无效。');
for (const field of ['offset', 'limit']) if (input[field] !== undefined && (!Number.isSafeInteger(input[field]) || input[field] < (field === 'offset' ? 0 : 1) || field === 'limit' && input[field] > ceiling(config, 16000))) throw fail('技能分页范围无效。');
}
export class SkillRegistry {
@@ -86,7 +87,7 @@ export class SkillRegistry {
const version = this.current(registration);
let status = 'current', reason = '';
try {
const { source } = readSkillSource(version.source.path);
const { source } = readSkillSource(version.source.path, this.store.config);
if (source.sha256 !== version.source.sha256 || source.path !== version.source.path) { status = 'changed'; reason = '来源文件已变化,请审查并登记新修订。'; }
} catch (error) { status = 'unavailable'; reason = this.redact(error.message); }
return { id: registration.id, projectId: registration.projectId, configurationRevision: registration.configurationRevision, name: registration.name, description: registration.description,
@@ -109,8 +110,8 @@ export class SkillRegistry {
register(projectId, input) {
this.assertIdle(projectId); exact(input, ['path', 'name', 'description', 'version']);
const name = text(input.name, 100, '技能名称'), description = text(input.description, 500, '用途'), version = text(input.version, 80, '版本');
const loaded = readSkillSource(input.path), state = this.state(), existing = state.registrations.filter(value => value.projectId === projectId);
if (existing.length >= SKILL_LIMITS.registrations) throw fail('每项目最多登记32个技能。');
const loaded = readSkillSource(input.path, this.store.config), state = this.state(), existing = state.registrations.filter(value => value.projectId === projectId);
if (existing.length >= ceiling(this.store, SKILL_LIMITS.registrations)) throw fail('每项目最多登记32个技能。');
const normalize = value => process.platform === 'win32' ? value.toLowerCase() : value;
if (existing.some(value => normalize(value.versions.at(-1).source.path) === normalize(loaded.source.path))) throw fail('该来源已登记,请刷新原技能修订。', 409);
const safe = JSON.parse(this.redact(JSON.stringify({ name, description, version, source: loaded.source })));
@@ -128,7 +129,7 @@ export class SkillRegistry {
if (input.configurationRevision !== value.configurationRevision) throw fail('技能启停配置已变化,请刷新后操作。', 409);
this.current(value);
if (input.enabled && this.inspect(value).status !== 'current') throw fail('技能来源已变化或不可用,请登记新修订后启用。', 409);
if (input.enabled && state.registrations.filter(item => item.projectId === projectId && item.enabled && item.id !== value.id).length >= SKILL_LIMITS.enabled) throw fail('每项目最多同时启用8个技能。');
if (input.enabled && state.registrations.filter(item => item.projectId === projectId && item.enabled && item.id !== value.id).length >= ceiling(this.store, SKILL_LIMITS.enabled)) throw fail('每项目最多同时启用8个技能。');
value.enabled = input.enabled; value.configurationRevision++; value.updatedAt = at(); this.save(state); return this.inspect(value);
}
refresh(projectId, input) {
@@ -136,8 +137,8 @@ export class SkillRegistry {
const state = this.state(), value = this.find(state, projectId, input.id, input.revision), prior = this.current(value);
if (input.configurationRevision !== value.configurationRevision) throw fail('技能启停配置已变化,请刷新后操作。', 409);
if (!Number.isSafeInteger(input.revision)) throw fail('登记新修订需要当前revision。');
if (value.versions.length >= SKILL_LIMITS.revisions) throw fail('技能已达到20个修订上限,请缩小注册范围。');
const version = text(input.version, 80, '版本'), loaded = readSkillSource(prior.source.path), content = this.redact(loaded.content);
if (value.versions.length >= ceiling(this.store, SKILL_LIMITS.revisions)) throw fail('技能已达到20个修订上限,请缩小注册范围。');
const version = text(input.version, 80, '版本'), loaded = readSkillSource(prior.source.path, this.store.config), content = this.redact(loaded.content);
if (loaded.source.sha256 === prior.source.sha256 && version === prior.version) throw fail('来源和版本未变化,无须新增修订。', 409);
value.revision++; value.configurationRevision++; value.enabled = false; value.updatedAt = at();
value.versions.push({ revision: value.revision, version: this.redact(version), source: loaded.source, snapshotSha256: sha(content), content, createdAt: value.updatedAt });
@@ -152,11 +153,11 @@ export class SkillRegistry {
version: this.redact(current.version), sourceSha256: current.source.sha256, snapshotSha256: current.snapshotSha256,
status: current.status, reason: current.reason };
});
if (entries.length > SKILL_LIMITS.enabled) throw fail('已启用技能超出目录范围,请核对注册数据。', 409);
if (entries.length > ceiling(this.store, SKILL_LIMITS.enabled)) throw fail('已启用技能超出目录范围,请核对注册数据。', 409);
return { schemaVersion: 1, kind: 'registered-skill-catalog', projectId, registryRevision: state.revision, entries };
}
read(session, run, input, { maximumMessageBytes = 16000, callId = '' } = {}) {
skillReadInput(input);
skillReadInput(input, this.store.config);
const plan = this.store.owned('context_plan', run.currentContextPlanId, session.id);
if (plan.taskId !== run.taskId || plan.runId !== run.id || session.runId !== run.id || session.taskId !== run.taskId || !plan.skillCatalogArtifactId) throw fail('当前运行没有已发送的技能目录。', 409);
const artifact = this.store.owned('artifact', plan.skillCatalogArtifactId, session.id);
+1 -1
View File
@@ -9,7 +9,7 @@ export class ArtifactStore {
}
write(session, run, value, { kind = 'tool-result', mediaType = 'application/json' } = {}) {
const bytes = Buffer.isBuffer(value) ? Buffer.from(value) : Buffer.from(typeof value === 'string' ? value : JSON.stringify(value), 'utf8');
if (bytes.length > 8 * 1024 * 1024) throw new Error('单项执行工件超过8MB,请缩小输出范围。');
if (!this.unrestricted?.() && bytes.length > 8 * 1024 * 1024 && !['model-request', 'model-http-response', 'model-stream-response'].includes(kind)) throw new Error('单项执行工件超过8MB,请缩小输出范围。');
const sha256 = createHash('sha256').update(bytes).digest('hex');
const relative = sha256.slice(0, 2) + '/' + sha256 + '.blob';
const file = path.join(this.root, relative);
+4 -3
View File
@@ -5,14 +5,15 @@ import { isId } from '../../shared/contracts/execution.mjs';
import { DEFAULT_MODEL_CAPACITY } from '../../shared/contracts/model-capacity.mjs';
export const DEFAULT_CONFIG = {
mode: 'demo', baseUrl: 'http://127.0.0.1:11434/v1', model: '', ...DEFAULT_MODEL_CAPACITY, capacityMode: 'model', historyPolicy: 'preserve', maxSteps: 12,
maxRunDurationMs: 600000, maxRunTokens: 200000, maxTaskTokens: 1000000, configRevision: 1,
modelResponseTimeoutMs: 300000, modelStreamIdleTimeoutMs: 120000,
mode: 'demo', baseUrl: 'http://127.0.0.1:11434/v1', model: '', ...DEFAULT_MODEL_CAPACITY, approvalMode: 'ask', capacityMode: 'passthrough', historyPolicy: 'preserve', executionMode: 'unrestricted', maxSteps: 0,
maxRunDurationMs: 0, maxRunTokens: 0, maxTaskTokens: 0, configRevision: 1,
modelResponseTimeoutMs: 0, modelStreamIdleTimeoutMs: 0,
};
export function cleanConfig(value = {}) {
const result = { ...DEFAULT_CONFIG };
for (const key of Object.keys(result)) if (Object.hasOwn(value, key)) result[key] = value[key];
if (!Object.hasOwn(value, 'executionMode') && ['contextLimit', 'maxOutputTokens', 'maxSteps', 'maxRunTokens'].some(key => Object.hasOwn(value, key))) result.executionMode = 'restricted';
// Old settings stay manual. Every saved Run keeps its original snapshot.
if (!Object.hasOwn(value, 'capacityMode') && (Object.hasOwn(value, 'contextLimit') || Object.hasOwn(value, 'maxOutputTokens'))) result.capacityMode = 'manual';
if (!Object.hasOwn(value, 'historyPolicy') && (Object.hasOwn(value, 'contextLimit') || Object.hasOwn(value, 'maxOutputTokens'))) result.historyPolicy = 'compact';
+1 -1
View File
@@ -79,7 +79,7 @@ export class FileResults {
return receipts;
}
record(session, input, { source = 'agent' } = {}) {
const args = fileResultInput(input, { source }), task = this.store.owned('task', session.taskId, session.id), run = this.store.owned('run', session.runId, session.id);
const args = fileResultInput(input, { source, config: this.store.config }), task = this.store.owned('task', session.taskId, session.id), run = this.store.owned('run', session.runId, session.id);
if (!['agent', 'user'].includes(source) || run.taskId !== task.id || run.purpose === 'diagnostic' && source !== 'user') throw planError('诊断运行不能登记或替代原任务成果。');
const project = this.store.project(session.projectId), prepared = [];
for (const file of args.files) {
+3 -2
View File
@@ -1,3 +1,4 @@
import { ceiling } from '../../shared/contracts/execution-policy.mjs';
import { randomUUID } from 'node:crypto';
import { TaskPlanManager } from './task-plan-manager.mjs';
import { inspectProject } from '../project-inspector.mjs';
@@ -109,7 +110,7 @@ export class RequirementReview {
const { task, run } = this.planner.task(session), previous = this.current(session), revision = previous?.revision ?? 0;
if (previous) this.verifyRecord(session, previous, 'task-requirements', ledgerContract);
if (input.expected_revision !== revision) throw planError('要求修订已变化,请刷新后保存。', 'stale');
if (revision >= 24 || !Array.isArray(input.requirements) || !input.requirements.length || input.requirements.length > 24)
if (revision >= ceiling(this.store, 24) || !Array.isArray(input.requirements) || !input.requirements.length || input.requirements.length > ceiling(this.store, 24))
throw planError('每个Task最多24项要求与24次修订。', 'input', 400);
const sources = requirementSources(task), items = input.requirements.map(value => itemInput(value, sources));
const explicitReview = input.source_set_sha256 !== undefined || input.reviewed_source_ids !== undefined || input.draft_id !== undefined;
@@ -132,7 +133,7 @@ export class RequirementReview {
}
if (new Set(items.map(row => row.key)).size !== items.length || previous?.items.some(row => !items.some(item => item.key === row.key)))
throw planError('要求ID需唯一;原要求不能删除,可修订并保留原记录。', 'input', 400);
if (JSON.stringify(items).length > 24000) throw planError('要求范围过大,请缩小Task。', 'input', 400);
if (JSON.stringify(items).length > ceiling(this.store, 24000)) throw planError('要求范围过大,请缩小Task。', 'input', 400);
for (const item of items) {
if (item.method === 'not_requested' && taskContract(task).checks !== 'skip') throw planError('当前用户约定没有跳过检查,不能标为按约定未执行。');
const old = previous?.items.find(row => row.key === item.key);
+4 -3
View File
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
import fs from 'node:fs';
import { randomUUID } from 'node:crypto';
import { safePath } from '../../server/files.mjs';
@@ -49,7 +50,7 @@ export class TaskPlanManager {
const { artifact, text } = this.artifact(session, plan.contractArtifactId, 'task-plan', plan.taskId, plan.runId);
if (artifact.sha256 !== plan.contractSha256 || text !== JSON.stringify(taskPlanContract(plan))
|| plan.requirementsSha256 !== planHash(plan.requirements)) throw planError('任务计划与封存的目标、步骤或依赖不一致。');
taskPlanInput({ expected_revision: plan.revision, steps: plan.steps });
taskPlanInput({ expected_revision: plan.revision, steps: plan.steps }, this.store.config);
return plan;
}
assertUnchanged(session, plan, taskId, runId, requirementsSha256) {
@@ -58,7 +59,7 @@ export class TaskPlanManager {
}
plan(session, options, { source = 'user' } = {}) { return this.mutate(session, source, () => this.planAction(session, options)); }
async planAction(session, options) {
const input = taskPlanInput(JSON.parse(this.redact(JSON.stringify(options)))), { task, run } = this.task(session);
const input = taskPlanInput(JSON.parse(this.redact(JSON.stringify(options))), this.store.config), { task, run } = this.task(session);
const requirements = taskRequirements(task), requirementsSha256 = planHash(requirements), previous = this.current(session);
if (previous) this.planFor(session, previous.id);
const revision = previous?.revision ?? 0;
@@ -66,7 +67,7 @@ export class TaskPlanManager {
&& [revision, revision - 1].includes(input.expected_revision)) return previous;
if (task.status === 'completed') throw planError('已完成任务保留原计划,请为新增工作发送新任务。');
if (input.expected_revision !== revision) throw planError('计划视图已过期,请按当前revision保存。', 'stale');
if (revision >= TASK_PLAN_LIMITS.revisions) throw planError('任务计划已到修订上限,请缩小任务后继续。');
if (revision >= ceiling(this.store, TASK_PLAN_LIMITS.revisions)) throw planError('任务计划已到修订上限,请缩小任务后继续。');
if (previous && (input.steps.length < previous.steps.length || previous.steps.some((step, index) => !same(step, input.steps[index])))) throw planError('已有步骤和通过条件不能删改;请保留原步骤并追加。');
await verifyWorkspaceProject(this.store, this.store.project(session.projectId));
for (const step of input.steps) for (const file of step.paths ?? []) safePath(this.store.project(session.projectId), file, true);
+32 -18
View File
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
import fs from 'node:fs';
import { randomUUID } from 'node:crypto';
import { createTask, createRun, modelSnapshot, accountedTokens, BudgetExceeded } from '../../shared/contracts/execution.mjs';
@@ -23,7 +24,7 @@ const at = () => new Date().toISOString();
const sourceIdentity = source => Object.fromEntries(['root', 'head', 'reference', 'branch', 'gitDir', 'commonDir', 'indexSha256',
'statusSha256', 'sourceFingerprint', 'treeSha256', 'configuration', 'filterDrivers'].map(key => [key, source[key]]));
const configView = config => Object.fromEntries(['mode', 'baseUrl', 'model', 'contextLimit', 'maxOutputTokens', 'configRevision',
'maxSteps', 'maxRunDurationMs', 'maxRunTokens', 'maxTaskTokens', ...(config.protocol ? ['protocol', 'streaming'] : []), ...(config.modelRouting ? ['modelRouting'] : [])].map(key => [key, structuredClone(config[key])]));
'executionMode', 'approvalMode', 'capacityMode', 'historyPolicy', 'maxSteps', 'maxRunDurationMs', 'maxRunTokens', 'maxTaskTokens', ...(config.protocol ? ['protocol', 'streaming'] : []), ...(config.modelRouting ? ['modelRouting'] : [])].map(key => [key, structuredClone(config[key])]));
const alive = pid => { if (!pid) return false; try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; } };
export class WorkerManager {
@@ -93,7 +94,7 @@ export class WorkerManager {
this.preparingGroupId = temporaryId;
const source = await this.workspaces.snapshot(project);
controller.signal.throwIfAborted();
if (source.changedPathCount > 32) throw workerConflict('来源已有修改超过32个路径,请先缩小范围;不会遗漏原修改后合并。');
if (source.changedPathCount > ceiling(config, 32)) throw workerConflict('来源已有修改超过32个路径,请先缩小范围;不会遗漏原修改后合并。');
for (const child of definition.children) for (const relative of child.paths) safePath(project, relative, true);
const run = this.store.beginRun(session, definition.goal, false, config, { forceNewTask: true });
session.status = 'paused'; this.store.finishRun(session, run, 'worker_control');
@@ -209,6 +210,7 @@ export class WorkerManager {
}
const initial = structuredClone(this.store.config), current = this.runtime.provider.prepareConfig ? this.runtime.provider.prepareConfig(initial, this.store) : initial;
if (JSON.stringify(modelSnapshot(current)) !== JSON.stringify(group.model)) throw workerConflict('模型连接或池快照已变化;不能在原协作中悄悄替换模型。');
if (unrestricted(group.config)) return { ...group.config, maxSteps: 0, maxRunDurationMs: 0, maxRunTokens: 0, maxTaskTokens: 0 };
const usage = workerUsage(this.store, worker), remaining = group.deadline - Date.now();
if (remaining <= 0) throw new BudgetExceeded('time_limit', '父协作总时限已用完,原任务与成果保留。');
if (usage.accountedTokens >= worker.budget.maxTokens || usage.steps >= worker.budget.maxSteps || usage.toolCalls >= worker.budget.maxToolCalls
@@ -267,7 +269,7 @@ export class WorkerManager {
const output = await this.output(session, worker);
const artifact = this.store.artifactStore.write(session, this.store.owned('run', worker.currentRunId, session.id), output, { kind: 'worker-result' });
this.store.core.artifact.set(artifact.id, artifact);
worker.result = { artifactId: artifact.id, sha256: artifact.sha256, fingerprint: workerHash(output), checkJobId: output.check.id, paths: output.files.map(file => file.path) };
worker.result = { artifactId: artifact.id, sha256: artifact.sha256, fingerprint: workerHash(output), checkJobId: output.check?.id ?? null, paths: output.files.map(file => file.path) };
worker.status = 'completed'; worker.summary = '实际改动与原检查证据已封存,等待父任务归集。';
} else worker.summary = unknown.length ? '执行结果或原进程待核对,不会重放。' : session.failure?.message ?? '原子任务已保存,等待审查或继续。';
} catch (error) {
@@ -298,7 +300,7 @@ export class WorkerManager {
workerForSession(this.store, session);
if (worker.evaluation?.role === 'original') throw workerConflict('原版检查不生成候选成果。');
await verifyEvaluationSources(this.store, session);
const baseline = this.baseline(session, worker), project = this.store.project(worker.projectId);
const baseline = this.baseline(session, worker), project = this.store.project(worker.projectId), config = this.store.core.collaboration.get(worker.collaborationId).config;
await verifyWorkspaceProject(this.store, project);
if (this.uncertain(worker).length) throw workerConflict('子任务仍有结果未知的工具、检查或文件批次');
assertEngineWorkerResult(this.store, session, worker);
@@ -309,9 +311,9 @@ export class WorkerManager {
if (git.head !== worker.baseCommit || git.indexSha256 !== baseline.git.indexSha256 || git.reference !== baseline.git.reference
|| git.gitDir !== baseline.git.gitDir || git.commonDir !== baseline.git.commonDir
|| JSON.stringify(git.configuration) !== JSON.stringify(baseline.git.configuration)) throw workerConflict('子任务HEAD、索引或Git配置已变化,独立提交或暂存不能作为原成果');
if (git.changedPathCount > 32 || git.changedPaths.some(file => !after.has(workerPathKey(file.path)))) throw workerConflict('实际Git修改包含删除、链接、排除文件或超出32文件范围,不能遗漏后合并');
if (git.changedPathCount > ceiling(config, 32) || git.changedPaths.some(file => !after.has(workerPathKey(file.path)))) throw workerConflict('实际Git修改包含删除、链接、排除文件或超出文件范围,不能遗漏后合并');
const paths = [...new Set([...before.keys(), ...after.keys()])].filter(key => before.get(key)?.sha256 !== after.get(key)?.sha256);
if (!paths.length || paths.length > 32) throw workerConflict('可交付成果需要1到32个实际文本改动');
if (!paths.length || paths.length > ceiling(config, 32)) throw workerConflict('可交付成果需要实际文本改动;手动限制最多32个文件');
let bytes = 0;
const files = paths.map(key => {
const original = before.get(key), actual = after.get(key), relative = actual?.path ?? original.path;
@@ -335,14 +337,14 @@ export class WorkerManager {
const text = readText(project, relative), last = chain.at(-1), first = chain[0];
if (text.sha256 !== last.sha256) throw workerConflict('成果读取期间原文件发生变化:' + relative);
const raw = fs.readFileSync(safePath(project, relative)); bytes += raw.length + Buffer.byteLength(first.baseContent, 'utf8');
if (raw.length > 512000 || bytes > 4 * 1024 * 1024) throw workerConflict('成果超过单文件512KB或原文/建议合计4MB范围');
if (raw.length > ceiling(config, 512000) || bytes > ceiling(config, 4 * 1024 * 1024)) throw workerConflict('成果超过单文件512KB或原文/建议合计4MB范围');
return { path: relative, beforeSha256: original?.sha256 ?? null, sha256: actual.sha256, bytes: raw.length,
before: original ? Buffer.from(first.baseContent, 'utf8').toString('base64') : null, after: raw.toString('base64'), changeIds: chain.map(change => change.id) };
}).sort((a, b) => a.path.localeCompare(b.path));
const check = verifiedCheck(this.store, session, inspection);
if (!check) throw workerConflict('缺少与当前源码一致、日志完整且测试数量明确的通过记录');
const plan = this.runtime.checkRunner().planFor(session, check.planId);
for (const result of check.results) if (result.kind === 'test' && result.engine !== 'python') {
if (!check && !unrestricted(config)) throw workerConflict('缺少与当前源码一致、日志完整且测试数量明确的通过记录');
const plan = check && this.runtime.checkRunner().planFor(session, check.planId);
for (const result of check?.results ?? []) if (result.kind === 'test' && result.engine !== 'python') {
const spec = plan.checks.find(value => value.name === result.name);
const evidence = parseTestEvidence(this.store.artifactStore.read(this.store.owned('artifact', result.logArtifactId, session.id)), spec?.framework);
if (JSON.stringify(evidence) !== JSON.stringify(result.tests)) throw workerConflict('检查数量与原日志不一致');
@@ -354,11 +356,11 @@ export class WorkerManager {
return { schemaVersion: 1, workerId: worker.id, collaborationId: worker.collaborationId, workerFingerprint: worker.fingerprint,
projectId: worker.projectId, sessionId: worker.sessionId, taskId: worker.taskId, baseCommit: worker.baseCommit,
sourceFingerprint: inspection.sourceFingerprint, files, inventoryFingerprint: workerHash(current),
check: { id: check.id, planId: check.planId, runId: check.runId, sourceFingerprint: check.sourceFingerprint, results: check.results.map(result => ({
check: check ? { id: check.id, planId: check.planId, runId: check.runId, sourceFingerprint: check.sourceFingerprint, results: check.results.map(result => ({
id: result.id, name: result.name, tests: result.tests, exitCode: result.exitCode, logArtifactId: result.logArtifactId,
logSha256: this.store.owned('artifact', result.logArtifactId, session.id).sha256,
...(result.metricsArtifactId ? { metricsArtifactId: result.metricsArtifactId, metricsSha256: result.metricsSha256 } : {}),
})) }, usage: workerUsage(this.store, worker), runIds: worker.runIds };
})) } : null, usage: workerUsage(this.store, worker), runIds: worker.runIds };
}
async verifiedResult(group, child) {
const worker = this.store.core.worker.get(child.id), session = this.store.session(child.sessionId);
@@ -407,12 +409,12 @@ export class WorkerManager {
sha256: workerHash(Buffer.from(content, 'utf8')), childSha256: file.sha256, content });
} catch (error) { conflicts.push({ path: file.path, workerIds: [file.workerId], reason: this.runtime.provider.redact(error.message ?? String(error)) }); }
}
if (all.length > 32 || targets.reduce((sum, file) => sum + Buffer.byteLength(file.content, 'utf8'), 0) > 2 * 1024 * 1024) conflicts.push({ path: '(整批)', workerIds: group.children.map(child => child.id), reason: '合并超过32文件或2MB建议内容,请缩小交付范围。' });
if (all.length > ceiling(group.config, 32) || targets.reduce((sum, file) => sum + Buffer.byteLength(file.content, 'utf8'), 0) > ceiling(group.config, 2 * 1024 * 1024)) conflicts.push({ path: '(整批)', workerIds: group.children.map(child => child.id), reason: '合并超过32文件或2MB建议内容,请缩小交付范围。' });
await this.sourceFor(group);
return { schemaVersion: 1, collaborationId: group.id, groupFingerprint: group.fingerprint, projectId: group.projectId,
sessionId: session.id, taskId: group.taskId, runId: group.runId, source: group.source.identity,
workers: proofs.map(proof => ({ workerId: proof.worker.id, artifactId: proof.artifact.id, sha256: proof.artifact.sha256, fingerprint: proof.worker.fingerprint,
checkJobId: proof.output.check.id, paths: proof.output.files.map(file => file.path) })),
checkJobId: proof.output.check?.id ?? null, paths: proof.output.files.map(file => file.path) })),
paths: all.map(file => file.path).sort(), conflicts, targets: targets.sort((a, b) => a.path.localeCompare(b.path)) };
}
collect(session, id, fingerprint, { evaluation = false } = {}) {
@@ -466,12 +468,24 @@ export class WorkerManager {
await this.faultInjector?.('merge_proposal', group, file);
}
await this.verifyCollection(session, group); signal.throwIfAborted();
const manager = new ChangeSetManager(this.store, { projectBusy: (projectId, exceptId) => this.runtime.projectHasActivity(projectId, exceptId, { excludeGroupId: group.id, excludeEvaluationId: group.evaluation?.batchId }) });
const manager = new ChangeSetManager(this.store, { beforeApply: (owner, batch) => this.verifyMerge(owner, batch),
projectBusy: (projectId, exceptId) => this.runtime.projectHasActivity(projectId, exceptId, { excludeGroupId: group.id, excludeEvaluationId: group.evaluation?.batchId }) });
const set = await manager.prepare(session, group.merge.changeIds, { collaborationBinding: { id: group.id, fingerprint: group.fingerprint,
collectionArtifactId: group.collection.artifactId, collectionSha256: group.collection.sha256 } });
group.merge.changeSetId = set.id; group.merge.fingerprint = set.fingerprint; group.merge.status = 'prepared';
group.status = 'merge_prepared'; group.summary = '父Task独立提案与原字节变更集已封存,等待明确审查应用;父工程尚未修改。';
session.status = 'needs_review';
group.status = unrestricted(group.config) ? 'merge_preparing' : 'merge_prepared';
group.summary = unrestricted(group.config) ? '子任务成果已封存,正在自动写入父工程。' : '父Task独立提案与原字节变更集已封存,等待明确审查应用;父工程尚未修改。';
session.status = unrestricted(group.config) ? 'running' : 'needs_review';
if (unrestricted(group.config)) {
const operation = await manager.start(session, set.id, set.fingerprint, { source: 'agent' });
const cancel = () => { manager.stop(session.id).catch(() => {}); };
signal.addEventListener('abort', cancel, { once: true });
if (signal.aborted) cancel();
try { await operation.promise; } finally { signal.removeEventListener('abort', cancel); }
if (set.status !== 'completed') throw workerConflict(set.summary);
group.status = 'merge_prepared'; group.merge.status = 'applied'; group.summary = '子任务成果已自动写入父工程,原字节与差异已保存。';
this.store.save(session);
}
} catch (error) {
group.status = group.merge ? 'unknown' : 'stale'; group.requiresVerification = !!group.merge;
group.summary = this.runtime.provider.redact(error.message ?? String(error));
@@ -514,7 +528,7 @@ export class WorkerManager {
const linked = this.groups(session).find(group => group.merge?.changeSetId === set.id);
if (!set.collaborationBinding && !linked) return;
const group = this.own(session, set.collaborationBinding?.id ?? linked.id, set.collaborationBinding?.fingerprint ?? linked.fingerprint);
if (group.status !== 'merge_prepared' || group.requiresVerification || group.merge?.changeSetId !== set.id || group.merge.fingerprint !== set.fingerprint
if (!(group.status === 'merge_prepared' || unrestricted(group.config) && group.status === 'merge_preparing' && this.active.has(group.id)) || group.requiresVerification || group.merge?.changeSetId !== set.id || group.merge.fingerprint !== set.fingerprint
|| set.collaborationBinding?.collectionArtifactId !== group.collection?.artifactId || set.collaborationBinding?.collectionSha256 !== group.collection?.sha256
|| JSON.stringify(set.files.map(file => file.changeId)) !== JSON.stringify(group.merge.changeIds)) throw workerConflict('父变更集与原协作/归集记录不一致,不能应用。');
if (group.evaluation) this.runtime.evaluationManager().adoptionFor(session, group);
+3 -2
View File
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
import { createHash } from 'node:crypto';
export const MCP_PROTOCOL = '2025-03-26';
@@ -38,9 +39,9 @@ export function checkMcpSchema(schema) {
visit(schema); return true;
}
export function validateMcpArguments(schema, args) {
export function validateMcpArguments(schema, args, config = {}) {
checkMcpSchema(schema);
if (!plain(args) || Buffer.byteLength(JSON.stringify(args)) > MCP_LIMITS.argumentBytes) throw mcpError('外部工具参数需要最多16000字节的JSON对象。', 400);
if (!plain(args) || Buffer.byteLength(JSON.stringify(args)) > ceiling(config, MCP_LIMITS.argumentBytes)) throw mcpError('外部工具参数需要最多16000字节的JSON对象。', 400);
let visited = 0;
const validate = (spec, value, location, depth = 0) => {
if (++visited > 2048 || depth > 16) throw mcpError('外部工具参数嵌套或条数超出范围。', 400);
+9 -8
View File
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
@@ -69,7 +70,7 @@ export class McpRegistry {
if (this.redact(JSON.stringify(launch)) !== JSON.stringify(launch)) throw mcpError('程序路径包含模型凭据,请换用不含凭据的路径。', 400);
const timeoutMs = input.timeoutMs ?? 15000;
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 500 || timeoutMs > 45000) throw mcpError('MCP请求超时范围为500到45000毫秒。', 400);
const state = this.state(); if (state.registrations.filter(value => value.projectId === projectId).length >= MCP_LIMITS.registrations) throw mcpError('每项目最多16个MCP注册。', 400);
const state = this.state(); if (state.registrations.filter(value => value.projectId === projectId).length >= ceiling(this.store, MCP_LIMITS.registrations)) throw mcpError('每项目最多16个MCP注册。', 400);
if (state.registrations.some(value => value.projectId === projectId && mcpHash(value.launch) === mcpHash(launch))) throw mcpError('相同MCP程序已登记。');
const registration = { id: randomUUID(), projectId, name: this.redact(input.name.trim()), launch, timeoutMs,
configurationRevision: 1, enabled: false, allowedTools: [], contract: null, createdAt: at(), updatedAt: at() };
@@ -79,7 +80,7 @@ export class McpRegistry {
this.idle(projectId); fields(input, ['id', 'configurationRevision', 'enabled', 'allowedTools']);
const state = this.state(), value = this.find(projectId, input.id, input.configurationRevision, state);
if (!Number.isSafeInteger(input.configurationRevision) || typeof input.enabled !== 'boolean' || !Array.isArray(input.allowedTools)
|| input.allowedTools.length > MCP_LIMITS.allowedTools || new Set(input.allowedTools).size !== input.allowedTools.length) throw mcpError('启停配置需要当前修订与最多12项工具。', 400);
|| input.allowedTools.length > ceiling(this.store, MCP_LIMITS.allowedTools) || new Set(input.allowedTools).size !== input.allowedTools.length) throw mcpError('启停配置需要当前修订与最多12项工具。', 400);
if (input.enabled || input.allowedTools.length) {
this.verifyLaunch(value); const contract = this.contract(value);
for (const name of input.allowedTools) { const tool = contract.tools.find(tool => tool.name === name); if (!tool || tool.unsupported) throw mcpError('所选工具缺少当前可验证的参数契约。', 400); checkMcpSchema(tool.inputSchema); }
@@ -95,14 +96,14 @@ export class McpRegistry {
configurationRevision: value.configurationRevision, contractSha256: value.contract.sha256,
tool: tool.name, description: this.redact(tool.description ?? '').slice(0, 1000), inputSchema: tool.inputSchema });
}
return JSON.parse(this.redact(JSON.stringify({ schemaVersion: 1, kind: 'registered-mcp-catalog', projectId, entries: entries.slice(0, MCP_LIMITS.allowedTools) })));
return JSON.parse(this.redact(JSON.stringify({ schemaVersion: 1, kind: 'registered-mcp-catalog', projectId, entries: entries.slice(0, ceiling(this.store, MCP_LIMITS.allowedTools)) })));
}
prepareCall(session, run, input) {
mcpCallInput(input); const value = this.find(session.projectId, input.registration_id, input.configuration_revision);
if (this.redact(JSON.stringify(input.arguments)) !== JSON.stringify(input.arguments)) throw mcpError('外部工具参数包含模型凭据,请移除后再请求。', 400);
if (!value.enabled || value.contract?.sha256 !== input.contract_sha256 || !value.allowedTools.includes(input.tool)) throw mcpError('MCP工具未启用或原契约已变化。');
this.verifyLaunch(value); const contract = this.contract(value), tool = contract.tools.find(tool => tool.name === input.tool);
if (!tool || tool.unsupported) throw mcpError('MCP工具参数契约不受支持。'); validateMcpArguments(tool.inputSchema, input.arguments);
if (!tool || tool.unsupported) throw mcpError('MCP工具参数契约不受支持。'); validateMcpArguments(tool.inputSchema, input.arguments, this.store.config);
if (session.taskId !== run.taskId || session.runId !== run.id) throw mcpError('MCP调用的Task/Run已变化。');
const plan = this.store.owned('context_plan', run.currentContextPlanId, session.id), artifact = this.store.owned('artifact', plan.mcpCatalogArtifactId, session.id);
if (artifact.kind !== 'context-mcp-catalog' || artifact.sha256 !== plan.mcpCatalogSha256 || artifact.taskId !== run.taskId || artifact.runId !== run.id) throw mcpError('本次发送的MCP目录身份不匹配。');
@@ -167,7 +168,7 @@ export class McpRegistry {
const directory = path.join(base, job.id); fs.mkdirSync(directory); job.directory = directory;
job.status = 'connecting'; job.processStarted = true; this.store.putRecord('mcp_job', session, job, 'mcp.starting');
const client = active.client = new McpStdio({ executable: registration.launch.executable.path, args: registration.launch.args, cwd: directory, env: envProfile() },
{ timeoutMs: registration.timeoutMs, maximumFrameBytes: MCP_LIMITS.resultBytes });
{ timeoutMs: unrestricted(this.store) ? 0 : registration.timeoutMs, maximumFrameBytes: ceiling(this.store, MCP_LIMITS.resultBytes) });
job.pid = client.pid ?? null; job.connectionId = client.id; this.store.putRecord('mcp_job', session, job, 'mcp.connected');
initialize = await client.request('initialize', { protocolVersion: MCP_PROTOCOL, capabilities: {}, clientInfo: { name: 'agent-workbench', version: '1.12-development' } }, { signal });
if (initialize.protocolVersion !== MCP_PROTOCOL || typeof initialize.serverInfo?.name !== 'string' || typeof initialize.serverInfo?.version !== 'string' || !initialize.capabilities?.tools) throw mcpError('MCP实际握手不符合固定协议和工具契约。');
@@ -175,8 +176,8 @@ export class McpRegistry {
tools = []; const cursors = new Set(); let cursor, pages = 0;
do {
const page = await client.request('tools/list', cursor ? { cursor } : {}, { signal });
if (++pages > MCP_LIMITS.pages || !Array.isArray(page.tools)) throw mcpError('MCP工具发现分页无效。');
tools.push(...page.tools); if (tools.length > MCP_LIMITS.tools || Buffer.byteLength(JSON.stringify(tools)) > MCP_LIMITS.catalogBytes) throw mcpError('MCP工具目录超出当前接入预算。');
if (++pages > ceiling(this.store, MCP_LIMITS.pages) || !Array.isArray(page.tools)) throw mcpError('MCP工具发现分页无效。');
tools.push(...page.tools); if (tools.length > ceiling(this.store, MCP_LIMITS.tools) || Buffer.byteLength(JSON.stringify(tools)) > ceiling(this.store, MCP_LIMITS.catalogBytes)) throw mcpError('MCP工具目录超出当前接入预算。');
cursor = page.nextCursor;
if (cursor !== undefined && (typeof cursor !== 'string' || cursor.length > 1000 || cursors.has(cursor))) throw mcpError('MCP工具发现分页没有推进。');
if (cursor) cursors.add(cursor);
@@ -189,7 +190,7 @@ export class McpRegistry {
if (job.input.call) {
const previous = this.contract(registration);
if (mcpHash({ protocolVersion: MCP_PROTOCOL, serverInfo: initialize.serverInfo, tools }) !== mcpHash({ protocolVersion: previous.protocolVersion, serverInfo: previous.serverInfo, tools: previous.tools })) throw mcpError('MCP实际版本或工具schema已变化,工具调用没有发送。');
const call = job.input.call; validateMcpArguments(tools.find(tool => tool.name === call.tool).inputSchema, call.arguments);
const call = job.input.call; validateMcpArguments(tools.find(tool => tool.name === call.tool).inputSchema, call.arguments, this.store.config);
signal.throwIfAborted(); job.status = 'calling'; job.dispatched = true;
this.store.putRecord('mcp_job', session, job, 'mcp.calling');
result = await client.request('tools/call', { name: call.tool, arguments: call.arguments }, { signal });
+2 -2
View File
@@ -87,10 +87,10 @@ export class McpStdio extends EventEmitter {
if (this.cancellationMethod) this.notify(this.cancellationMethod, { requestId: id, reason: 'Owned Workbench operation stopped.' });
this.settle(id, failure('MCP_CANCELLED', '分析已请求停止,尚未返回的结果不算完成。', true));
};
const timer = setTimeout(() => {
const timer = timeoutMs > 0 ? setTimeout(() => {
if (this.cancellationMethod) this.notify(this.cancellationMethod, { requestId: id, reason: 'Owned Workbench request deadline.' });
this.settle(id, failure('MCP_TIMEOUT', 'MCP请求到达等待上限,没有自动重试。', true));
}, timeoutMs);
}, timeoutMs) : null;
this.pending.set(id, { resolve, reject, timer, abort, signal, record }); signal?.addEventListener('abort', abort, { once: true });
this.write({ jsonrpc: '2.0', id, method, params }, error => { if (error) this.settle(id, failure('MCP_WRITE_FAILED', error.message, true)); });
});
+9 -8
View File
@@ -2,6 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { createHash, randomUUID } from 'node:crypto';
import { McpStdio } from './mcp-stdio.mjs';
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
export const REA_VERSION = '6.8.0';
export const REA_PROTOCOL = '2025-03-26';
@@ -43,8 +44,8 @@ export function resolveReaInstallation(appDirectory = process.cwd(), { packageRo
}
export class ReaAdapter {
constructor(installation, { cwd, onClient = () => {}, timeoutMs = 45000 } = {}) {
this.installation = installation; this.cwd = cwd; this.onClient = onClient; this.timeoutMs = timeoutMs;
constructor(installation, { cwd, onClient = () => {}, timeoutMs = 45000, config = {} } = {}) {
this.installation = installation; this.cwd = cwd; this.onClient = onClient; this.timeoutMs = timeoutMs; this.config = config;
}
async connect(signal) {
if (this.installation.status !== 'available') throw new Error(this.installation.message ?? 'REA尚未就绪。');
@@ -54,7 +55,7 @@ export class ReaAdapter {
const allowed = /^(path|pathext|systemroot|systemdrive|windir|comspec|temp|tmp|userprofile|appdata|localappdata|programfiles(?:\(x86\))?|homedrive|homepath)$/i;
const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => allowed.test(name)));
Object.assign(env, { REA_MCP_INPUT_SCHEMA_PROFILE: 'compact', REA_MCP_OUTPUT_SCHEMA_PROFILE: 'off' });
this.client = new McpStdio({ executable: this.installation.node.path, args: [this.installation.entry.path, 'mcp'], cwd: this.cwd, env }, { timeoutMs: this.timeoutMs });
this.client = new McpStdio({ executable: this.installation.node.path, args: [this.installation.entry.path, 'mcp'], cwd: this.cwd, env }, { timeoutMs: this.timeoutMs, maximumFrameBytes: ceiling(this.config, 4 * 1024 * 1024) });
this.onClient(this.client);
const initialize = await this.client.request('initialize', { protocolVersion: REA_PROTOCOL, capabilities: {},
clientInfo: { name: 'agent-workbench-research-adapter', version: '1.8.0' } }, { signal });
@@ -63,8 +64,8 @@ export class ReaAdapter {
const pages = [], tools = [], cursors = new Set(); let cursor;
do {
const page = await this.client.request('tools/list', cursor ? { cursor } : {}, { signal }); pages.push(page);
if (!Array.isArray(page.tools) || pages.length > 10) throw new Error('REA工具发现返回了无效分页。');
tools.push(...page.tools); if (tools.length > 500) throw new Error('REA工具发现超过当前接入范围。');
if (!Array.isArray(page.tools) || pages.length > ceiling(this.config, 10)) throw new Error('REA工具发现返回了无效分页。');
tools.push(...page.tools); if (tools.length > ceiling(this.config, 500)) throw new Error('REA工具发现超过当前接入范围。');
cursor = page.nextCursor; if (cursor && cursors.has(cursor)) throw new Error('REA工具发现分页没有推进。'); if (cursor) cursors.add(cursor);
} while (cursor);
if (new Set(tools.map(tool => tool.name)).size !== tools.length) throw new Error('REA工具身份重复,不能按名称猜测契约。');
@@ -79,7 +80,7 @@ export class ReaAdapter {
if (!spec || !spec.extensions.includes(path.extname(target.path).toLowerCase())) throw new Error('分析方式不适用于这个登记工件。');
const tool = this.tools.find(tool => tool.name === spec.name); if (!tool) throw new Error('当前REA没有提供所选工具。');
if (!this.tools.some(value => value.name === 'export_evidence_bundle')) throw new Error('REA没有提供完整Evidence导出,尚未调用分析工具。');
const args = operation === 'javascript' ? { input_path: target.path, format: 'asar', integrity_policy: 'fail',
const args = unrestricted(this.config) ? (operation === 'javascript' ? { input_path: target.path, format: 'asar', integrity_policy: 'fail', detail: 'full' } : { path: target.path }) : operation === 'javascript' ? { input_path: target.path, format: 'asar', integrity_policy: 'fail',
detail: 'summary', max_heap_mb: 256, max_semantic_nodes: 10000, max_semantic_nodes_per_file: 2000, analysis_timeout_ms: 30000 }
: { path: target.path, max_file_bytes: 512 * 1024 * 1024, ...(operation === 'pe-imports' ? { max_dlls: 256, max_functions: 10000 } : { max_entries: 10000 }) };
const request = { name: tool.name, arguments: args }, result = await this.client.request('tools/call', request, { signal });
@@ -92,11 +93,11 @@ export class ReaAdapter {
received.exportRequest = exportRequest; received.exportResult = exportResult;
if (exportResult.isError) return received;
const stat = fs.lstatSync(destination);
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 64 * 1024 * 1024) throw new Error('REA导出超过64MiB接收范围或不是常规文件。');
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > ceiling(this.config, 64 * 1024 * 1024)) throw new Error('REA导出超过接收额度或不是常规文件。');
const bytes = fs.readFileSync(destination), text = bytes.toString('utf8');
if (!Buffer.from(text, 'utf8').equals(bytes)) throw new Error('REA导出不是有效UTF-8,原导出留在所属任务目录。');
const bundle = JSON.parse(text);
if (!Array.isArray(bundle.records) || bundle.records.length > 500 || new Set(bundle.records.map(record => record.evidence_id)).size !== bundle.records.length) throw new Error('REA导出记录身份无效。');
if (!Array.isArray(bundle.records) || bundle.records.length > ceiling(this.config, 500) || new Set(bundle.records.map(record => record.evidence_id)).size !== bundle.records.length) throw new Error('REA导出记录身份无效。');
const evidence = bundle.records.find(record => record.evidence_id === originalId && record.operation === spec.name);
if (!evidence) throw new Error('REA导出缺少原分析Evidence,不能用摘要替代。');
return { ...received, bundleText: text, evidence };
+6 -5
View File
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
import fs from 'node:fs';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
@@ -56,7 +57,7 @@ function observe(project, file) {
const { target } = targetFor(project, file.path);
let stat;
try { stat = fs.lstatSync(target); } catch (error) { if (error.code !== 'ENOENT') throw error; }
if (stat && (!stat.isFile() || stat.size > 4 * 1024 * 1024)) throw new Error('目标已不是有界普通文件。');
if (stat && (!stat.isFile() || stat.size > ceiling(project, 4 * 1024 * 1024))) throw new Error('目标文件类型或当前文件额度不符。');
const exists = !!stat, actualSha256 = exists ? hash(fs.readFileSync(target)) : null;
const state = exists === file.baseExists && actualSha256 === file.baseSha256 ? 'before'
: exists && actualSha256 === file.sha256 ? 'after' : 'external';
@@ -148,7 +149,7 @@ export class ChangeSetManager {
&& this.inspect(session, set).every(value => value.state === 'before');
}
async prepare(session, changeIds, { source = 'user', collaborationBinding = null } = {}) {
if (!Array.isArray(changeIds) || !changeIds.length || changeIds.length > 32 || new Set(changeIds).size !== changeIds.length) throw conflict('变更集需要1到32个不同的提案ID。');
if (!Array.isArray(changeIds) || !changeIds.length || !unrestricted(this.store) && changeIds.length > 32 || new Set(changeIds).size !== changeIds.length) throw conflict('变更集需要1到32个不同的提案ID。');
this.requireIdle(session, { source });
const task = this.store.owned('task', session.taskId, session.id), run = this.store.owned('run', session.runId, session.id);
const existing = [...this.store.core.change_set.values()].find(value => value.projectId === session.projectId && value.status === 'prepared');
@@ -181,7 +182,7 @@ export class ChangeSetManager {
const before = change.baseExists ? fs.readFileSync(target) : null, after = Buffer.from(change.content, 'utf8');
if (hash(after) !== change.sha256 || before && hash(before) !== change.baseSha256) throw conflict('提案内容或原文件已经变化:' + portable);
budget += (before?.length ?? 0) + after.length;
if (budget > 4 * 1024 * 1024) throw conflict('变更集原文与建议内容合计超过4MB。');
if (budget > ceiling(this.store, 4 * 1024 * 1024)) throw conflict('变更集原文与建议内容合计超过4MB。');
return { change, portable, before, after, mode: before ? fs.statSync(target).mode & 0o777 : 0o644 };
});
for (const { change, portable, before, after, mode } of snapshots) {
@@ -204,10 +205,10 @@ export class ChangeSetManager {
this.projects.set(session.projectId, set.id); this.active.set(set.id, operation); return operation;
}
release(set) { this.projects.delete(set.projectId); this.active.delete(set.id); }
async start(session, id, fingerprint) {
async start(session, id, fingerprint, { source = 'user' } = {}) {
const set = this.own(session, id, fingerprint, { current: true });
if (typeof fingerprint !== 'string' || set.status !== 'prepared' || set.attemptedAt) throw conflict('这个批次已执行或尚未提交原审查指纹,不能重复应用。');
this.requireIdle(session, { exceptId: set.id });
this.requireIdle(session, { exceptId: set.id, source });
const operation = this.claim(session, set);
try {
await verifyWorkspaceProject(this.store, this.store.project(session.projectId));
+3 -2
View File
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
import fs from 'node:fs';
import { randomUUID } from 'node:crypto';
import { safePath, readText, hash, proposeFile } from '../../server/files.mjs';
@@ -28,7 +29,7 @@ export function proposeFileChunk(store, session, args) {
if (args.draft_id && (!draft || draft.status !== 'staging' || draft.taskId !== session.taskId || draft.projectId !== session.projectId || draft.path !== args.path)) fail('草稿不属于当前Task/路径或已结束,请核对原回执。');
if (!draft) {
if (args.offset !== 0 || args.expected_sha256 !== undefined && args.expected_sha256 !== emptySha) fail('新草稿必须从offset 0开始。');
if (pendingFileDrafts(session).some(row => row.path === args.path) || pendingFileDrafts(session).length >= 16) fail('该路径已有未完成草稿或当前Task已达16份草稿,请继续原草稿或显式放弃。');
if (pendingFileDrafts(session).some(row => row.path === args.path) || !unrestricted(store) && pendingFileDrafts(session).length >= 16) fail('该路径已有未完成草稿或当前Task已达16份草稿,请继续原草稿或显式放弃。');
if (Object.hasOwn(args, 'base_sha256') && args.base_sha256 !== base) fail('原文件SHA已变化,请重新核对。');
draft = { id: randomUUID(), projectId: session.projectId, taskId: session.taskId, path: args.path, status: 'staging', baseSha256: base,
sha256: emptySha, characters: 0, bytes: 0, chunks: [], createdAt: new Date().toISOString() };
@@ -41,7 +42,7 @@ export function proposeFileChunk(store, session, args) {
}).join('');
if (hash(Buffer.from(previous)) !== draft.sha256 || previous.length !== draft.characters || Buffer.byteLength(previous) !== draft.bytes) fail('原草稿校验失败,未采用任何片段。');
const content = previous + args.content, bytes = Buffer.byteLength(content);
if (bytes > 512000 || draft.chunks.length >= 256) fail('完整文本超过512KB或256段;请按工程模块拆分文件。');
if (!unrestricted(store) && (bytes > 512000 || draft.chunks.length >= 256)) fail('完整文本超过512KB或256段;请按工程模块拆分文件。');
const artifact = store.artifactStore.write(session, run, args.content, { kind: 'file-proposal-fragment', mediaType: 'text/plain' });
store.core.artifact.set(artifact.id, artifact);
const next = { ...draft, sha256: hash(Buffer.from(content)), characters: content.length, bytes, chunks: [...draft.chunks, { id: artifact.id, sha256: artifact.sha256 }] };
+62
View File
@@ -0,0 +1,62 @@
import fs from 'node:fs';
import path from 'node:path';
import { runGit } from '../git-process.mjs';
import { excludedFromInventory, safePath } from '../../server/files.mjs';
const operations = new WeakMap();
const identity = { GIT_AUTHOR_NAME: 'Agent Workbench', GIT_AUTHOR_EMAIL: 'local@agent-workbench.invalid',
GIT_COMMITTER_NAME: 'Agent Workbench', GIT_COMMITTER_EMAIL: 'local@agent-workbench.invalid' };
// Establish a local recovery point before the first automatic write. Existing
// repositories, staged changes and remote configuration are never replaced.
export async function ensureGitBaseline(store, session, { signal } = {}) {
const project = store.project(session.projectId), root = safePath(project);
let projectOperations = operations.get(store);
if (!projectOperations) operations.set(store, projectOperations = new Map());
const key = root + ':' + session.taskId;
if (projectOperations.has(key)) return projectOperations.get(key);
const promise = (async () => {
const git = async (args, options = {}) => {
const result = await runGit(root, args, { signal, ...options });
if (!result.ok) throw new Error(result.error.trim() || '本地Git基线未创建。');
return result.text.trim();
};
try {
const existing = await runGit(root, ['rev-parse', '--show-toplevel'], { signal });
const normalize = value => process.platform === 'win32' ? path.resolve(value).toLowerCase() : path.resolve(value);
const created = !existing.ok || normalize(existing.text.trim()) !== normalize(root);
if (created) { await git(['init']); await git(['config', '--local', 'core.autocrlf', 'false']); }
const head = await runGit(root, ['rev-parse', '--verify', 'HEAD'], { signal });
if (head.ok) return { status: 'existing', commit: head.text.trim(), root: existing.text.trim(), created: false };
let tree, files = [];
if (created) {
const candidates = await runGit(root, ['ls-files', '--others', '--exclude-standard', '-z'], { signal });
if (!candidates.ok) throw new Error(candidates.error);
files = candidates.text.split('\0').filter(file => file && !excludedFromInventory(file)
&& !/(?:^|\/)(?:\.npmrc|\.pypirc|\.netrc)$|\.(?:pem|key|p12|pfx)$/i.test(file))
.filter(file => { const entry = fs.lstatSync(path.join(root, file)); return entry.isFile() && !entry.isSymbolicLink() && entry.nlink === 1; });
if (files.length) await git(['-c', 'core.autocrlf=false', 'add', '--pathspec-from-file=-', '--pathspec-file-nul'], { input: files.join('\0') + '\0' });
tree = await git(['write-tree']);
} else {
// An existing unborn repo may contain the user's staged files. An empty
// parent preserves that index and its staged diff exactly.
tree = await git(['hash-object', '-w', '-t', 'tree', '--stdin'], { input: '' });
}
const commit = await git(['commit-tree', tree], { input: 'Workbench: local baseline before automatic edits\n', env: identity });
await git(['update-ref', 'HEAD', commit, '0'.repeat(commit.length)]);
const record = { status: 'created', created, commit, root, files: files.length,
scope: created ? 'nonignored-source-files' : 'empty-parent-preserving-user-index', createdAt: new Date().toISOString() };
session.gitBaseline = record;
store.event(session, { kind: 'change', label: '本地Git基线已保存', phase: 'completed', output: JSON.stringify(record) });
return record;
} catch (cause) {
signal?.throwIfAborted();
const record = { status: 'unavailable', message: cause.message, root, createdAt: new Date().toISOString() };
session.gitBaseline = record;
store.event(session, { kind: 'change', label: 'Git基线未完成,文件仍保留原字节备份', phase: 'failed', output: cause.message });
return record;
}
})();
projectOperations.set(key, promise);
return promise;
}
+14 -13
View File
@@ -1,3 +1,4 @@
import { unrestricted, ceiling } from '../../shared/contracts/execution-policy.mjs';
import fs from 'node:fs';
import path from 'node:path';
import { createHash, randomUUID } from 'node:crypto';
@@ -49,10 +50,10 @@ function sourceChanges(text) {
return changes;
}
function configurationHash(file, optional = false) {
function configurationHash(file, optional = false, config = {}) {
if (optional && !fs.existsSync(file)) return null;
const stat = fs.lstatSync(file);
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > 256 * 1024) throw conflict('Git配置不是有界普通文件,请先核对。');
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > ceiling(config, 256 * 1024)) throw conflict('Git配置类型或当前文件额度不符,请先核对。');
return hash(fs.readFileSync(file));
}
@@ -66,9 +67,9 @@ function checkoutFile(project, relative) {
return fs.lstatSync(target);
}
function committedTree(text) {
function committedTree(text, config = {}) {
const entries = text.split('\0').filter(Boolean), files = [], names = new Map(); let bytes = 0;
if (entries.length > 1000) throw conflict('已提交版本超过当前1000文件工作区上限。');
if (!unrestricted(config) && entries.length > 1000) throw conflict('已提交版本超过当前1000文件工作区上限。');
for (const entry of entries) {
const match = entry.match(/^(100644|100755) blob ([a-f0-9]+)\s+(\d+)\t(.+)$/s);
if (!match || !oid(match[2])) throw conflict('已提交版本包含链接、子模块或未支持的Git文件类型。');
@@ -81,7 +82,7 @@ function committedTree(text) {
names.set(normalized, name);
}
if (excludedFromInventory(relative)) throw conflict('已提交版本包含凭据、依赖或内部目录,请先整理可交付的源码版本。');
if (!Number.isSafeInteger(count) || count > 1024 * 1024 || bytes + count > 16 * 1024 * 1024) throw conflict('已提交内容超过单文件1MB或总计16MB工作区上限。');
if (!Number.isSafeInteger(count) || !unrestricted(config) && (count > 1024 * 1024 || bytes + count > 16 * 1024 * 1024)) throw conflict('已提交内容超过单文件1MB或总计16MB工作区上限。');
files.push({ mode, blob, bytes: count, path: relative }); bytes += count;
}
return { files, bytes };
@@ -155,7 +156,7 @@ export class WorkspaceManager {
this.target(record, { checkExisting: false }); return record;
}
git(root, args, options = {}) {
return runGit(root, ['-c', 'core.longpaths=true', ...args], { timeoutMs: 30000, maximumBytes: 4 * 1024 * 1024, hooksDirectory: this.hooksDirectory,
return runGit(root, ['-c', 'core.longpaths=true', ...args], { timeoutMs: unrestricted(this.store) ? 0 : 30000, maximumBytes: ceiling(this.store, 4 * 1024 * 1024), hooksDirectory: this.hooksDirectory,
...options, env: { GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: this.emptyConfig, ...(options.env ?? {}) } });
}
async need(root, args, options) {
@@ -194,11 +195,11 @@ export class WorkspaceManager {
ordinaryDirectory(gitDir); ordinaryDirectory(commonDir);
if (!same(path.dirname(indexPath), gitDir)) throw conflict('来源Git索引位置无法核对。');
const indexStat = fs.lstatSync(indexPath);
if (!indexStat.isFile() || indexStat.isSymbolicLink() || indexStat.nlink !== 1 || indexStat.size > 16 * 1024 * 1024 || fs.existsSync(indexPath + '.lock')) throw conflict('来源Git索引类型、大小或外部锁需要先核对。');
if (!indexStat.isFile() || indexStat.isSymbolicLink() || indexStat.nlink !== 1 || indexStat.size > ceiling(this.store, 16 * 1024 * 1024) || fs.existsSync(indexPath + '.lock')) throw conflict('来源Git索引类型、大小或外部锁需要先核对。');
for (const name of ['MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD', 'REBASE_HEAD', 'rebase-apply', 'rebase-merge', 'sequencer', 'BISECT_START']) if (fs.existsSync(path.join(gitDir, name))) throw conflict('来源Git正在合并、变基或定位问题,请先完成该操作。');
const tree = committedTree(inventory.text);
const configuration = { common: configurationHash(path.join(commonDir, 'config')),
worktree: configurationHash(path.join(gitDir, 'config.worktree'), true) };
const tree = committedTree(inventory.text, this.store.config);
const configuration = { common: configurationHash(path.join(commonDir, 'config'), false, this.store.config),
worktree: configurationHash(path.join(gitDir, 'config.worktree'), true, this.store.config) };
const inspection = await inspectProject(project);
if (!inspection.scope.complete) throw conflict('来源工程超出当前完整快照范围,请先缩小工程再创建隔离工作区。');
const changes = sourceChanges(status.text);
@@ -336,14 +337,14 @@ export class WorkspaceManager {
}
if (tagged.some(entry => !entry.startsWith('H ') || !byPath.has(entry.slice(2)))) throw conflict('工作区索引存在跳过检查或假定未变化标记。');
const indexFile = path.join(gitDir, 'index'), indexStat = fs.lstatSync(indexFile);
if (!indexStat.isFile() || indexStat.isSymbolicLink() || indexStat.nlink !== 1 || indexStat.size > 16 * 1024 * 1024
if (!indexStat.isFile() || indexStat.isSymbolicLink() || indexStat.nlink !== 1 || indexStat.size > ceiling(this.store, 16 * 1024 * 1024)
|| fs.existsSync(indexFile + '.lock')) throw conflict('工作区索引或外部锁需要先核对。');
let actualBytes = 0;
const candidate = { root: record.root, workspace: { gitDir, commonGitDir: commonDir, branch: record.branch } };
for (const file of expected) {
const stat = checkoutFile(candidate, file.path);
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > 2 * 1024 * 1024
|| (actualBytes += stat.size) > 32 * 1024 * 1024) throw conflict('实际检出文件不是有界普通源码文件。');
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > ceiling(this.store, 2 * 1024 * 1024)
|| (actualBytes += stat.size) > ceiling(this.store, 32 * 1024 * 1024)) throw conflict('实际检出文件类型或当前文件额度不符。');
}
// Git's C-quoted stdin paths are data, never shell command text. Hashing
// honors built-in EOL conversion while every configured filter is off.