import test from 'node:test'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; import http from 'node:http'; import { randomUUID } from 'node:crypto'; import { fixture } from './helpers.mjs'; import { createEngineFixture } from '../scripts/engine-fixtures.mjs'; import { CONTROLLED_CRITICAL_FILES, resolveControlledInstallation, assertControlledInstallation, controlledToolCatalogue, controlledDigest, controlledPatch } from '../src/core/engines/controlled-installation.mjs'; import { CONTROLLED_DISABLED_PLUGINS } from '../src/core/engines/controlled-plugin.mjs'; import { ControlledDeepSeekSession } from '../src/core/engines/controlled-session.mjs'; const tools = [{ name: 'read_file', description: 'Read the owned project file.', parameters: { type: 'object', properties: { path: { type: 'string' } }, required: ['path'] } }]; function installation(t) { const f = fixture(t), 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'); } return { ...f, root, installation: resolveControlledInstallation(f.root, root) }; } test('controlled installation pins the native kernel and bridge independently of the existing connection-probe identity', t => { const f = installation(t), original = f.installation; assert.equal(original.controlledStatus, 'available'); assert.equal(original.controlledInputs.length, CONTROLLED_CRITICAL_FILES.length); assert.equal(original.controlledCapabilities.nativeModelCredentials, false); assert.equal(original.controlledCapabilities.singleSessionCancel, false); fs.appendFileSync(path.join(f.root, CONTROLLED_CRITICAL_FILES[0]), '// changed runtime\n'); const current = resolveControlledInstallation(f.root, f.root); assert.equal(current.identitySha256, original.identitySha256); assert.notEqual(current.controlledSha256, original.controlledSha256); assert.throws(() => assertControlledInstallation(original), /工具内核或叠加插件已变化/); }); test('controlled profiles disable every native project/terminal provider and native model/retry route using the actual include patch contract', () => { const patch = controlledPatch('owned-plugin.mjs', { fixture: true }); assert.deepEqual(patch.slice(0, -1), CONTROLLED_DISABLED_PLUGINS.map(id => ({ id, disabled: true }))); assert.deepEqual(patch.at(-1).insert[0], { id: 'agent-workbench-controlled-bridge', name: 'owned-plugin.mjs', config: { fixture: true } }); assert.ok(CONTROLLED_DISABLED_PLUGINS.includes('persistent-pwsh')); assert.ok(CONTROLLED_DISABLED_PLUGINS.includes('tool-fs')); }); test('owned tool catalogues seal full schemas canonically and reject duplicate or malformed declarations', () => { assert.equal(controlledDigest(controlledToolCatalogue(tools)), controlledDigest(controlledToolCatalogue([{ function: tools[0] }]))); assert.throws(() => controlledToolCatalogue([...tools, tools[0]]), /重复/); assert.throws(() => controlledToolCatalogue([{ ...tools[0], parameters: { type: 'array' } }]), /格式无效/); }); async function bridge(t, { onTool = async () => ({ observed: true }), onModel = async () => ({ observed: true }), maximumFrameBytes = 4096 } = {}) { const f = installation(t), driver = new ControlledDeepSeekSession(f.installation, { maximumFrameBytes }); const owner = Object.fromEntries(['sessionId', 'projectId', 'taskId', 'runId', 'jobId'].map(key => [key, randomUUID()])); driver.owner = owner; driver.sdkSessionId = randomUUID(); driver.client = { pid: 11717 }; driver.catalogueNames = new Set(['read_file']); driver.callIds = new Set(); driver.catalogueSha256 = controlledDigest(tools); driver.config = { model: 'fixture-model', maxOutputTokens: 512 }; driver.verifyLaunch = () => {}; driver.report = { bridgeRequests: [], modelRequests: 0, toolRequests: 0 }; const controller = new AbortController(), authentication = 'Bearer owned-test-token'; const server = http.createServer((request, response) => { driver.handleBridge(request, response, { authentication, onTool, onModel, signal: controller.signal }).catch(error => { response.writeHead(error.status ?? 409, { 'Content-Type': 'application/json' }); response.end(JSON.stringify({ error: error.message })); }); }); await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); f.onCleanup(() => new Promise(resolve => { controller.abort(); server.closeAllConnections(); server.close(resolve); })); const post = (route, data, overrides = {}) => fetch('http://127.0.0.1:' + server.address().port + route, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: authentication, ...overrides.headers }, body: JSON.stringify({ owner, sessionId: driver.sdkSessionId, pid: driver.client.pid, data, ...overrides.body }), }); return { driver, post, owner, controller }; } test('bridge authentication, current Run, process, SDK session and browser-origin checks reject before dispatch', async t => { let calls = 0; const b = await bridge(t, { onTool: async () => { calls++; return {}; } }); const data = { callId: 'owned-call', name: 'read_file', arguments: { path: 'README.md' } }; for (const overrides of [{ headers: { Authorization: 'Bearer foreign' } }, { headers: { Origin: 'http://example.invalid' } }, { body: { owner: { ...b.owner, runId: randomUUID() } } }, { body: { sessionId: randomUUID() } }, { body: { pid: 31313 } }]) { 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 => { let calls = 0; const b = await bridge(t, { onTool: async () => { calls++; return { read: true }; } }); const data = { callId: 'call-1', name: 'read_file', arguments: { path: 'README.md' } }; assert.equal((await b.post('/tool', data)).status, 200); assert.equal((await b.post('/tool', data)).status, 409); assert.equal((await b.post('/tool', { ...data, callId: 'call-2', name: 'pwsh' })).status, 400); assert.equal((await b.post('/tool', { ...data, callId: 'call-3', arguments: [] })).status, 400); b.driver.verifyLaunch = () => { throw Object.assign(new Error('source changed'), { status: 409 }); }; assert.equal((await b.post('/tool', { ...data, callId: 'call-4' })).status, 409); assert.equal(calls, 1); assert.equal(b.driver.report.bridgeRequests.length, 1); }); test('bridge model requests bind the exact catalogue, route and output bound and preserve raw request/result identity', async t => { let calls = 0; const b = await bridge(t, { onModel: async () => { calls++; return { message: { role: 'assistant', content: 'owned' } }; } }); const data = { messages: [], system: null, tools, toolHistory: null, model: 'fixture-model', maxTokens: 256 }; assert.equal((await b.post('/model', { ...data, maxTokens: 513 })).status, 400); assert.equal((await b.post('/model', { ...data, model: 'other' })).status, 400); assert.equal((await b.post('/model', { ...data, tools: [{ ...tools[0], description: 'changed' }] })).status, 400); const response = await b.post('/model', data); assert.equal(response.status, 200); assert.equal(calls, 1); assert.equal(b.driver.report.modelRequests, 1); const trace = b.driver.report.bridgeRequests[0]; assert.equal(trace.status, 'completed'); assert.equal(trace.resultSha256, controlledDigest(await response.json())); assert.deepEqual(trace.data, data); }); test('stopped and oversized bridge requests never reach a local model or tool callback', async t => { let calls = 0; const b = await bridge(t, { maximumFrameBytes: 512, onTool: async () => { calls++; return {}; } }); const data = { callId: 'large', name: 'read_file', arguments: { path: 'x'.repeat(1000) } }; assert.equal((await b.post('/tool', data)).status, 413); b.controller.abort(); assert.equal((await b.post('/tool', { ...data, arguments: {} })).status, 403); assert.equal(calls, 0); });