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
+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);