feat: connect controlled engines to owned Tasks, approvals and budget ledger
This commit is contained in:
@@ -74,6 +74,8 @@ test('bridge authentication, current Run, process, SDK session and browser-origi
|
||||
assert.equal((await b.post('/tool', data, overrides)).status, 403);
|
||||
}
|
||||
assert.equal(calls, 0); assert.equal(b.driver.report.toolRequests, 0);
|
||||
b.driver.client.exited = true;
|
||||
assert.equal((await b.post('/tool', data)).status, 403); assert.equal(calls, 0);
|
||||
});
|
||||
|
||||
test('bridge duplicates, unknown tools, malformed arguments and source changes are refused before a second side effect', async t => {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fixture, until } from './helpers.mjs';
|
||||
import { workerHttp } from './fixtures/workers-http.mjs';
|
||||
import { ControlledWorkerFixture } from './fixtures/controlled-worker.mjs';
|
||||
import { createEngineFixture } from '../scripts/engine-fixtures.mjs';
|
||||
import { EngineRunner } from '../src/core/engines/engine-runner.mjs';
|
||||
import { resolveControlledInstallation, CONTROLLED_CRITICAL_FILES } from '../src/core/engines/controlled-installation.mjs';
|
||||
|
||||
test('controlled engine HTTP freezes one child, pages original owned input/report, rejects foreign reads and prevents changed-source reuse', async t => {
|
||||
const f = fixture(t), host = await workerHttp(f), root = createEngineFixture(path.join(f.root, 'harness'));
|
||||
for (const file of CONTROLLED_CRITICAL_FILES) { fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true }); fs.writeFileSync(path.join(root, file), 'export const fixture = true;\n'); }
|
||||
host.runtime.controlledEngines = new EngineRunner(f.store, host.provider, { directoryRoot: path.join(f.root, 'engines'), sessionFactory: () => new ControlledWorkerFixture() });
|
||||
const installation = await host.api('/engines/deepseek/controlled-availability?root=' + encodeURIComponent(root));
|
||||
assert.equal(installation.controlledStatus, 'available');
|
||||
const input = { goal: 'HTTP controlled engine', engine: { id: 'deepseek-harness', root, controlledSha256: installation.controlledSha256 },
|
||||
children: [{ label: 'engine-1', goal: 'Repair and check one child', paths: ['src/a.mjs'] }] };
|
||||
const route = '/sessions/' + f.session.id, group = (await host.api(route + '/collaborations', input)).group;
|
||||
assert.equal(group.children.length, 1); const action = operation => host.api(route + '/collaborations/' + group.id + '/' + operation, { fingerprint: group.fingerprint });
|
||||
await action('prepare'); await until(() => f.store.core.collaboration.get(group.id).status === 'ready', 20000);
|
||||
await action('start'); await until(() => f.store.core.collaboration.get(group.id).status === 'awaiting_review', 20000);
|
||||
const childRoute = '/sessions/' + group.children[0].sessionId, view = await host.api(childRoute + '/engine-runs'), job = view[0];
|
||||
assert.equal(job.status, 'completed'); assert.equal(job.nativeSummary.treeConfirmed, true); assert.equal(job.modelRequests, 2); assert.equal(job.toolRequests, 1);
|
||||
const original = f.store.artifactStore.read(f.store.core.artifact.get(job.reportArtifactId));
|
||||
const first = await host.api(childRoute + '/engine-runs/' + job.id + '/report?offset=0&limit=200');
|
||||
assert.equal(first.content, original.slice(0, 200)); assert.equal(first.sha256, job.reportSha256); assert.equal(first.truncated, true);
|
||||
const second = await host.api(childRoute + '/engine-runs/' + job.id + '/report?offset=200&limit=200'); assert.equal(second.content, original.slice(200, 400));
|
||||
const raw = await fetch(host.url + '/api' + childRoute + '/engine-runs/' + job.id + '/download', { headers: { 'X-Workbench-Token': host.token } });
|
||||
assert.equal(await raw.text(), original); assert.match(raw.headers.get('content-disposition'), /attachment/);
|
||||
assert.equal((await host.api(childRoute + '/engine-runs/' + job.id + '/input?limit=200')).sha256, job.inputSha256);
|
||||
assert.equal((await host.raw(childRoute + '/engine-runs/' + job.id + '/report?offset=999999')).status, 400);
|
||||
assert.equal((await host.raw(childRoute + '/engine-runs', undefined, 'foreign')).status, 403);
|
||||
assert.ok((await host.raw(route + '/engine-runs/' + job.id + '/report')).status >= 400);
|
||||
assert.equal((await host.raw(childRoute + '/engines/jobs', { root })).status, 409);
|
||||
assert.equal((await host.api(childRoute + '/execution')).engineRuns[0].id, job.id);
|
||||
const artifact = f.store.core.artifact.get(job.reportArtifactId); fs.appendFileSync(path.join(f.store.artifactStore.root, artifact.relative), 'damage');
|
||||
assert.ok((await host.raw(childRoute + '/engine-runs/' + job.id + '/report')).status >= 400);
|
||||
const before = f.store.core.task.size; fs.appendFileSync(resolveControlledInstallation(f.root, root).controlledInputs[0].path, '// changed\n');
|
||||
const another = f.store.createSession(f.project.id);
|
||||
assert.equal((await host.raw('/sessions/' + another.id + '/collaborations', input)).status, 409);
|
||||
assert.equal(f.store.core.task.size, before); assert.equal(host.requests.length, 2);
|
||||
});
|
||||
@@ -0,0 +1,195 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { fixture, call, until, assertToolPairs } from './helpers.mjs';
|
||||
import { controlledWorker, ControlledWorkerFixture } from './fixtures/controlled-worker.mjs';
|
||||
import { applyWorkerProposals, approveWorkerChecks, ownerBytes } from './fixtures/workers-project.mjs';
|
||||
import { ControlledDeepSeekSession } from '../src/core/engines/controlled-session.mjs';
|
||||
import { Store } from '../src/server/store.mjs';
|
||||
import { nativeMessagesToChat, originalEngineRun, verifyEngineModelInput } from '../src/shared/contracts/engine-execution.mjs';
|
||||
|
||||
const usage = { total_tokens: 168, prompt_tokens: 123, completion_tokens: 45 };
|
||||
async function prepare(f, context) {
|
||||
const group = await context.manager.plan(f.session, context.definition);
|
||||
await (await context.manager.prepare(f.session, group.id, group.fingerprint)).promise;
|
||||
assert.equal(group.status, 'ready', group.summary); return group;
|
||||
}
|
||||
const jobs = (f, group) => [...f.store.core.engine_run.values()].filter(job => job.collaborationId === group.id);
|
||||
|
||||
test('native text and call IDs preserve original result pairing while unsupported content fails closed', () => {
|
||||
const input = { system: 'fixed', messages: [{ role: 'assistant', content: [{ type: 'reasoning', text: 'private' }, { type: 'tool-call', id: 'native', name: 'read_file', arguments: '{"path":"README.md"}' }] },
|
||||
{ role: 'tool', toolCallId: 'native', content: [{ type: 'text', text: 'result' }] }] };
|
||||
const mapped = nativeMessagesToChat(input); assert.equal(mapped[1].content, ''); assert.equal(mapped[1].tool_calls[0].id, 'native'); assert.equal(mapped[2].tool_call_id, 'native');
|
||||
assert.throws(() => nativeMessagesToChat({ messages: [{ role: 'user', content: [{ type: 'image', url: 'invalid' }] }] }), /尚未验证/);
|
||||
assert.throws(() => nativeMessagesToChat({ messages: [{ role: 'tool', content: [] }] }), /toolCallId/);
|
||||
});
|
||||
|
||||
test('one engine child freezes real installation identity before creating tasks and rejects a changed source', async t => {
|
||||
const f = fixture(t), context = controlledWorker(f);
|
||||
const group = await context.manager.plan(f.session, context.definition); assert.equal(group.children.length, 1);
|
||||
assert.equal(group.children[0].engine.controlledSha256, context.installation.controlledSha256);
|
||||
fs.appendFileSync(context.installation.controlledInputs[0].path, '// changed\n');
|
||||
assert.throws(() => context.runtime.engineRunner().selected(context.definition.engine), /不一致/);
|
||||
await (await context.manager.prepare(f.session, group.id, group.fingerprint)).promise;
|
||||
const worker = f.store.core.worker.get(group.children[0].id); group.deadline = Date.now() + 60000;
|
||||
assert.throws(() => context.manager.configFor(group, worker), /已变化/);
|
||||
assert.equal(context.requests.length, 0);
|
||||
});
|
||||
|
||||
test('owned native tools return saved results, use real approvals/checks and account each actual request once across new engine Runs', async t => {
|
||||
const f = fixture(t), context = controlledWorker(f), original = ownerBytes(f), group = await prepare(f, context);
|
||||
await (await context.manager.start(f.session, group.id, group.fingerprint)).promise;
|
||||
assert.equal(group.status, 'awaiting_review', group.summary); assert.equal(jobs(f, group)[0].status, 'completed');
|
||||
await applyWorkerProposals(f, context.runtime, group);
|
||||
await approveWorkerChecks(f, context.runtime, group, context.manager.start(f.session, group.id, group.fingerprint));
|
||||
assert.equal(group.status, 'ready_to_collect', group.summary); assert.deepEqual(ownerBytes(f), original);
|
||||
const child = group.children[0], session = f.store.session(child.sessionId), worker = f.store.core.worker.get(child.id);
|
||||
assert.equal(worker.status, 'completed', worker.summary); assert.equal(session.approvals.filter(value => value.status === 'approved').length, 1);
|
||||
const all = jobs(f, group), requestCount = all.reduce((sum, job) => sum + job.requests.length, 0);
|
||||
assert.equal(all.length, 2); assert.equal(f.store.core.task.get(worker.taskId).usage.requests, requestCount);
|
||||
assert.equal(f.store.core.task.get(worker.taskId).usage.totalTokens, requestCount * 168);
|
||||
assert.ok(all.every(job => job.status === 'completed' && job.requests.every(request => request.accountedAttempts === 1)));
|
||||
for (const job of all) {
|
||||
originalEngineRun(f.store, session, job);
|
||||
for (const request of job.requests) verifyEngineModelInput(f.store, session, job, request);
|
||||
for (const entry of job.calls) {
|
||||
assert.equal(entry.callId, job.id + ':' + entry.sourceCallId);
|
||||
assert.equal(f.store.core.tool.get(entry.invocationId).callId, entry.callId); assert.ok(entry.outputArtifactId);
|
||||
}
|
||||
}
|
||||
assertToolPairs(session.providerMessages);
|
||||
assert.ok(context.requests.some(request => request.messages.some(message => message.role === 'tool'
|
||||
&& JSON.parse(message.content).status === 'completed' && JSON.parse(message.content).check_status === 'passed')));
|
||||
assert.equal([...f.store.core.context_plan.values()].filter(plan => plan.taskId === worker.taskId).some(plan => plan.workerDispatchedAt), false);
|
||||
assert.equal(context.runtime.controlledEngines.drivers.size, 0);
|
||||
const finalReport = f.store.core.artifact.get(all.at(-1).reportArtifactId);
|
||||
fs.appendFileSync(path.join(f.store.artifactStore.root, finalReport.relative), 'damaged');
|
||||
await assert.rejects(context.manager.output(session, worker), /校验失败/);
|
||||
});
|
||||
|
||||
test('forged native scope cannot change a parent file and a final completion claim cannot replace worker proof', async t => {
|
||||
const f = fixture(t), context = controlledWorker(f, { respond: ({ messages }) => messages.some(message => message.role === 'tool')
|
||||
? { message: { role: 'assistant', content: 'claimed complete' }, usage }
|
||||
: { message: { role: 'assistant', content: '', tool_calls: [call('outside', 'propose_file', { path: 'README.md', content: 'forged', reason: 'forged' })] }, usage } });
|
||||
const original = ownerBytes(f), group = await prepare(f, context);
|
||||
await (await context.manager.start(f.session, group.id, group.fingerprint)).promise;
|
||||
const session = f.store.session(group.children[0].sessionId); assert.deepEqual(ownerBytes(f), original);
|
||||
assert.equal(session.changes.length, 0); assert.equal(group.status, 'paused'); assert.equal(f.store.core.run.get(session.runId).stopReason, 'worker_incomplete');
|
||||
assert.equal(context.native[0].received[0].result.status, 'error'); assert.match(context.native[0].received[0].result.message, /范围/);
|
||||
});
|
||||
|
||||
test('duplicate native IDs are rejected without replaying a saved tool', async t => {
|
||||
const f = fixture(t), context = controlledWorker(f, { respond: () => ({ message: { role: 'assistant', content: '', tool_calls: [call('same', 'read_file', { path: 'README.md' })] }, usage }) });
|
||||
const group = await prepare(f, context); await (await context.manager.start(f.session, group.id, group.fingerprint)).promise;
|
||||
const job = jobs(f, group)[0]; assert.equal(job.calls.length, 1); assert.equal(f.store.core.tool.size, 1); assert.equal(job.status, 'failed');
|
||||
assert.equal(context.requests.length, 2); assert.match(job.error, /已经登记/);
|
||||
});
|
||||
|
||||
test('native input exceeding the context budget is retained and sends no model request', async t => {
|
||||
class Oversized extends ControlledWorkerFixture {
|
||||
async wait() { const { onModel, tools, config, signal } = this.options; return onModel({ model: config.model, maxTokens: config.maxOutputTokens,
|
||||
tools: tools.map(value => value.function), messages: [{ role: 'user', content: [{ type: 'text', text: 'x'.repeat(2000000) }] }] }, { id: randomUUID() }, signal); }
|
||||
}
|
||||
const f = fixture(t), context = controlledWorker(f, { sessionFactory: () => new Oversized() }), group = await prepare(f, context);
|
||||
await (await context.manager.start(f.session, group.id, group.fingerprint)).promise;
|
||||
assert.equal(context.requests.length, 0); assert.equal(jobs(f, group)[0].requests.length, 0);
|
||||
assert.equal(f.store.core.task.get(group.children[0].taskId).usage.requests, 0); assert.match(jobs(f, group)[0].error, /预算/);
|
||||
});
|
||||
|
||||
test('stop retains a late reported model usage once and executes no tool from that output', async t => {
|
||||
let release; const waiting = new Promise(resolve => { release = resolve; });
|
||||
const f = fixture(t), context = controlledWorker(f, { respond: async () => { await waiting; return { message: { role: 'assistant', content: '', tool_calls: [call('late', 'propose_file', { path: 'src/a.mjs', content: 'late', reason: 'late' })] }, usage }; } });
|
||||
const group = await prepare(f, context), started = context.manager.start(f.session, group.id, group.fingerprint);
|
||||
await until(() => context.requests.length === 1); const stopping = context.runtime.stop(f.session.id); release();
|
||||
await stopping; await started.promise;
|
||||
const task = f.store.core.task.get(group.children[0].taskId), session = f.store.session(group.children[0].sessionId);
|
||||
assert.equal(task.usage.requests, 1); assert.equal(task.usage.totalTokens, 168); assert.equal(session.changes.length, 0);
|
||||
assert.equal(jobs(f, group)[0].calls.length, 0); assert.equal(jobs(f, group)[0].status, 'cancelled');
|
||||
assert.ok(jobs(f, group)[0].requests[0].responseArtifactId); assert.equal(context.runtime.controlledEngines.drivers.size, 0);
|
||||
});
|
||||
|
||||
test('a source change after the original model intent stops before native tools execute', async t => {
|
||||
const f = fixture(t); let context;
|
||||
context = controlledWorker(f, { respond: () => { fs.appendFileSync(context.installation.controlledInputs[0].path, '// runtime changed\n');
|
||||
return { message: { role: 'assistant', content: '', tool_calls: [call('changed', 'propose_file', { path: 'src/a.mjs', content: 'bad', reason: 'bad' })] }, usage }; } });
|
||||
const group = await prepare(f, context); await (await context.manager.start(f.session, group.id, group.fingerprint)).promise;
|
||||
assert.equal(f.store.session(group.children[0].sessionId).changes.length, 0); assert.equal(jobs(f, group)[0].calls.length, 0);
|
||||
assert.equal(jobs(f, group)[0].requiresVerification, false); assert.match(jobs(f, group)[0].error, /已变化/);
|
||||
});
|
||||
test('an engine source change while approval is pending invalidates the old permission before any check starts', async t => {
|
||||
const f = fixture(t), context = controlledWorker(f, { respond: ({ messages }) => {
|
||||
const result = messages.filter(message => message.role === 'tool').at(-1);
|
||||
return { message: { role: 'assistant', content: '', tool_calls: [result ? call('check', 'run_checks', { plan_id: JSON.parse(result.content).id }) : call('plan', 'plan_checks', { names: ['test', 'build'] })] }, usage };
|
||||
} }), group = await prepare(f, context), started = context.manager.start(f.session, group.id, group.fingerprint);
|
||||
const session = f.store.session(group.children[0].sessionId);
|
||||
await until(() => session.approvals.some(approval => approval.status === 'pending'), 15000);
|
||||
fs.appendFileSync(context.installation.controlledInputs[0].path, '// changed while awaiting approval\n');
|
||||
context.runtime.decide(session.id, session.approvals.find(approval => approval.status === 'pending').id, true);
|
||||
await started.promise; assert.equal(f.store.core.check_job.size, 0); assert.equal(jobs(f, group)[0].status, 'failed');
|
||||
assert.equal(context.requests.length, 2); assert.match(jobs(f, group)[0].error, /已变化/);
|
||||
});
|
||||
|
||||
test('missing or noncompleted turn end cannot be adopted even with an owned receipt and assistant text', async () => {
|
||||
for (const kind of [null, 'failed', 'cancelled']) {
|
||||
const native = new ControlledDeepSeekSession({}); native.request = async () => ({}); native.report = { receipt: { messageId: 'owned' }, notifications: [
|
||||
{ method: 'session.event', params: { event: { type: 'agent/inbox/spliced', data: { inserted: [{ id: 'owned' }] } } } },
|
||||
{ method: 'session.event', params: { event: { type: 'assistant/message', data: { message: { content: [{ type: 'text', text: 'claim' }] } } } } },
|
||||
...(kind ? [{ method: 'session.event', params: { event: { type: 'turn/end', data: { reason: { kind } } } } }] : [])] };
|
||||
await assert.rejects(native.wait(), /正常结束/);
|
||||
}
|
||||
});
|
||||
|
||||
test('closed root with an original live descendant remains unknown and retains its process tree', async () => {
|
||||
const native = new ControlledDeepSeekSession({}, { processTreeReader: async () => ({ supported: true, processes: [{ pid: 91, createdAt: '2026-10-31T00:00:00Z' }] }) });
|
||||
native.report = { process: { pid: 90, startedAt: new Date().toISOString() }, notifications: [] };
|
||||
native.client = { exited: true, close: async () => ({ rootExited: true, exit: { code: 0 } }), trace: [], stderr: '' };
|
||||
const result = await native.close({ force: true }); assert.equal(result.status, 'unknown'); assert.equal(result.cleanup.treeConfirmed, false);
|
||||
assert.equal(result.process.descendants[0].pid, 91);
|
||||
});
|
||||
|
||||
async function pendingRecovery(f, context) {
|
||||
const group = await prepare(f, context); await (await context.manager.start(f.session, group.id, group.fingerprint)).promise;
|
||||
const job = jobs(f, group)[0], session = f.store.session(job.sessionId), old = job.requests[0];
|
||||
const input = verifyEngineModelInput(f.store, session, job, old);
|
||||
const request = { id: randomUUID(), bridgeTraceId: randomUUID(), sourceSha256: old.sourceSha256, requestSha256: old.requestSha256,
|
||||
requestBytes: old.requestBytes, estimatedInputTokens: old.estimatedInputTokens, reservedPerAttempt: old.reservedPerAttempt,
|
||||
maxAttempts: 2, accountedAttempts: 0, observedAttempts: 1, status: 'dispatched', startedAt: new Date().toISOString(), dispatchedAt: new Date().toISOString() };
|
||||
const artifact = f.store.artifactStore.write(session, f.store.core.run.get(job.runId), { schemaVersion: 1, owner: input.owner,
|
||||
native: input.native, body: input.body, plan: { ...request, ...input.owner } }, { kind: 'engine-model-input' });
|
||||
f.store.core.artifact.set(artifact.id, artifact); request.inputArtifactId = artifact.id; request.inputSha256 = artifact.sha256;
|
||||
job.requests.push(request); job.status = 'running'; job.finishedAt = null; job.native = null; job.reportArtifactId = null; job.reportSha256 = null;
|
||||
job.originalOutcome = null; job.process = { pid: 2147483000, startedAt: new Date().toISOString(), rootCreatedAt: '2026-10-31T00:00:00.000Z', descendants: [] };
|
||||
group.status = 'running'; f.store.save(f.session);
|
||||
const worker = f.store.core.worker.get(group.children[0].id); worker.status = 'running'; worker.ownerPid = null;
|
||||
session.status = 'running'; const run = f.store.core.run.get(job.runId); run.status = 'running'; run.finishedAt = null;
|
||||
f.store.save(session); return { job, request, worker, group, before: structuredClone(f.store.core.task.get(worker.taskId).usage) };
|
||||
}
|
||||
|
||||
test('host recovery reserves original pending attempts exactly once and explicit review preserves unknown outcomes', async t => {
|
||||
const f = fixture(t), context = controlledWorker(f), pending = await pendingRecovery(f, context); f.store.close();
|
||||
const reopened = new Store(f.data), task = reopened.core.task.get(pending.worker.taskId);
|
||||
assert.equal(task.usage.requests, pending.before.requests + 2); assert.equal(task.usage.unknownRequests, pending.before.unknownRequests + 2);
|
||||
assert.equal(task.usage.estimatedUnknownTokens, pending.before.estimatedUnknownTokens + 2 * pending.request.reservedPerAttempt);
|
||||
const firstUsage = structuredClone(task.usage); reopened.close();
|
||||
const second = new Store(f.data); f.onCleanup(() => second.close()); assert.deepEqual(second.core.task.get(task.id).usage, firstUsage);
|
||||
const { Runtime } = await import('../src/server/runtime.mjs'); const runtime = new Runtime(second, context.provider); f.onCleanup(() => runtime.stopAll());
|
||||
const manager = runtime.workerManager(), parent = second.session(f.session.id), group = second.core.collaboration.get(pending.group.id);
|
||||
assert.equal(group.status, 'unknown'); assert.throws(() => manager.start(parent, group.id, group.fingerprint), /核对/);
|
||||
await (await manager.reconcile(parent, group.id, group.fingerprint)).promise;
|
||||
assert.ok(group.evidence, group.summary); const original = structuredClone(second.core.engine_run.get(pending.job.id));
|
||||
await manager.acknowledge(parent, group.id, group.fingerprint, group.evidence.sha256);
|
||||
const reviewed = second.core.engine_run.get(pending.job.id); assert.equal(reviewed.status, 'resolved_external'); assert.equal(reviewed.verified, false);
|
||||
assert.deepEqual(reviewed.originalOutcome, original.originalOutcome); assert.deepEqual(reviewed.requests, original.requests);
|
||||
assert.equal(context.requests.length, 2); assert.equal(reviewed.review.result, 'unknown-preserved');
|
||||
});
|
||||
|
||||
test('corrupted model reservation cannot reduce recovered budget or permit a new engine request', async t => {
|
||||
const f = fixture(t), context = controlledWorker(f), pending = await pendingRecovery(f, context);
|
||||
pending.request.reservedPerAttempt = 1; f.store.save(f.store.session(pending.worker.sessionId)); f.store.close();
|
||||
const reopened = new Store(f.data); f.onCleanup(() => reopened.close()); const job = reopened.core.engine_run.get(pending.job.id);
|
||||
assert.equal(job.requiresVerification, true); assert.match(job.requests.at(-1).verificationError, /预算|不一致/);
|
||||
assert.equal(reopened.executionSnapshot(reopened.session(pending.worker.sessionId)).accountedTaskTokens, pending.worker.budget.maxTokens);
|
||||
assert.equal(job.requests.at(-1).recoveryConservativeCharge, true); assert.equal(context.requests.length, 2);
|
||||
});
|
||||
Vendored
+55
@@ -0,0 +1,55 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { createEngineFixture } from '../../scripts/engine-fixtures.mjs';
|
||||
import { CONTROLLED_CRITICAL_FILES, resolveControlledInstallation, controlledDigest } from '../../src/core/engines/controlled-installation.mjs';
|
||||
import { EngineRunner } from '../../src/core/engines/engine-runner.mjs';
|
||||
import { prepareWorkerFixture } from './workers-project.mjs';
|
||||
|
||||
// A protocol fixture, not the native Harness. Native acceptance is independent.
|
||||
export class ControlledWorkerFixture {
|
||||
constructor() { this.report = { notifications: [], bridgeRequests: [] }; this.received = []; }
|
||||
async open(options) {
|
||||
this.options = options; this.report.owner = options.owner; this.report.sdkSessionId = options.sdkSessionId;
|
||||
options.onState('ready', {}); return this.report;
|
||||
}
|
||||
async prompt(content) { this.content = content; this.report.receipt = { messageId: randomUUID() }; return this.report.receipt; }
|
||||
async wait() {
|
||||
const { onModel, onTool, tools, config, signal } = this.options;
|
||||
const messages = [{ role: 'user', content: [{ type: 'text', text: this.content }] }];
|
||||
for (let step = 0; step < 100; step++) {
|
||||
signal.throwIfAborted();
|
||||
const input = { messages: structuredClone(messages), system: 'Protocol fixture for the owned task.',
|
||||
tools: tools.map(value => value.function ?? value), toolHistory: null, model: config.model, maxTokens: config.maxOutputTokens };
|
||||
const result = await onModel(input, { id: randomUUID() }, signal);
|
||||
signal.throwIfAborted();
|
||||
const message = result.message, content = [{ type: 'text', text: message.content }];
|
||||
for (const call of message.tool_calls ?? []) content.push({ type: 'tool-call', id: call.id, name: call.function.name, arguments: call.function.arguments });
|
||||
messages.push({ role: 'assistant', content });
|
||||
if (!message.tool_calls?.length) return message.content;
|
||||
for (const call of message.tool_calls) {
|
||||
const input = { callId: call.id, name: call.function.name, arguments: JSON.parse(call.function.arguments) };
|
||||
const result = await onTool(input, { id: randomUUID() }, signal);
|
||||
this.received.push({ input, result, resultSha256: controlledDigest(result) });
|
||||
messages.push({ role: 'tool', toolCallId: call.id, content: [{ type: 'text', text: JSON.stringify(result) }] });
|
||||
}
|
||||
}
|
||||
throw new Error('Fixture exceeded its step bound.');
|
||||
}
|
||||
async close({ force } = {}) {
|
||||
return Object.assign(this.report, { status: force ? 'cancelled' : 'closed', cleanup: { rootExited: true, treeConfirmed: true, remainingProcesses: [] } });
|
||||
}
|
||||
}
|
||||
export function controlledWorker(f, { respond = null, sessionFactory = () => new ControlledWorkerFixture() } = {}) {
|
||||
const context = prepareWorkerFixture(f, { respond });
|
||||
const root = createEngineFixture(path.join(f.root, 'controlled-harness'));
|
||||
for (const file of CONTROLLED_CRITICAL_FILES) {
|
||||
fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true }); fs.writeFileSync(path.join(root, file), 'export const fixture = true;\n');
|
||||
}
|
||||
const installation = resolveControlledInstallation(f.root, root), native = [];
|
||||
context.runtime.controlledEngines = new EngineRunner(f.store, context.provider, { directoryRoot: path.join(f.root, 'owned-engines'),
|
||||
sessionFactory: () => { const value = sessionFactory(); native.push(value); return value; } });
|
||||
const definition = { goal: '交付受控引擎的独立工程成果', engine: { id: 'deepseek-harness', root, controlledSha256: installation.controlledSha256 },
|
||||
budget: { maxSteps: 30 }, children: [{ label: 'engine-1', goal: '实现独立文件并通过当前检查', paths: ['src/a.mjs'] }] };
|
||||
return { ...context, installation, root, native, definition };
|
||||
}
|
||||
Reference in New Issue
Block a user