gongxiangp2/apps/detail-agent-pi/test/project-shell.integration.mjs

225 lines
11 KiB
JavaScript

import assert from 'node:assert/strict';
import { execFile } from 'node:child_process';
import { createHash } from 'node:crypto';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { test } from 'node:test';
import { promisify } from 'node:util';
import { EnterpriseContext } from '../src/enterprise-context.mjs';
import { openEnterpriseSkills } from '../src/enterprise-skill-resources.mjs';
import { projectTools } from '../src/project-tools.mjs';
async function fixture(t) {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'xiaoyi-skill, 项目-'));
t.after(() => fs.rm(dir, { recursive: true, force: true }));
const events = [];
const store = { dir, root: dir, appendEvent: async event => { events.push(event); } };
return { store, events };
}
function bashTool(tools) {
return tools.find(tool => tool.name === 'bash');
}
async function assertRemoved(events) {
const finished = events.findLast(event => event.type === 'project_shell_finished');
assert.match(finished?.container ?? '', /^[a-f0-9]{64}$/);
const endpoint = process.platform === 'win32'
? 'npipe:////./pipe/dockerDesktopLinuxEngine' : 'unix:///var/run/docker.sock';
await assert.rejects(promisify(execFile)('docker', [
'--host', endpoint, 'container', 'inspect', finished.container,
]), /No such/);
return finished;
}
const script = `from pathlib import Path
import csv
import json
from PIL import Image
config = json.loads(Path(__file__).with_name("crop.json").read_text())
with Path(__file__).with_name("colors.csv").open(newline="") as file:
rows = list(csv.DictReader(file))
Image.new("RGB", (8, 6), rows[0]["color"]).save("input.png")
with Image.open("input.png") as source:
source.crop(config["box"]).save("output.png")
with Image.open("output.png") as result:
print(json.dumps({"size": result.size, "pixel": result.getpixel((0, 0)), "pillow": Image.__version__}))
try:
Path(__file__).write_text("changed")
except OSError as error:
assert error.errno == 30, error
else:
raise AssertionError("published script was writable")
`;
test('Pi runs the locked Skill script with Pillow and its published JSON/CSV', {timeout: 60000}, async t => {
const { store, events } = await fixture(t);
const skill = {
fileId: 'skill', revision: 'r1', name: 'SKILL.md', path: 'Skills/lighting/SKILL.md',
text: '---\nname: lighting\ndescription: Tests the pinned lighting workflow.\n---\n' +
'Use [finish](references/finish.md) and [crop](scripts/crop.py).\n',
};
const finish = {
fileId: 'finish', revision: 'r2', name: 'finish.md', path: 'Skills/lighting/references/finish.md',
text: 'Finish starts here.\n' + 'x'.repeat(24000) + '\nRule at the end.',
};
const assets = [
{ fileId: 'crop', revision: 'r7', name: 'crop.py', text: script },
{ fileId: 'config', revision: 'r3', name: 'crop.json', text: '{"box":[1,1,5,4]}' },
{ fileId: 'colors', revision: 'r5', name: 'colors.csv', text: 'color\nred\n' },
].map(file => ({ ...file, path: 'Skills/lighting/scripts/' + file.name }));
const downloaded = [];
let publishedCropRevision = 'r7';
const context = new EnterpriseContext(store, {
async call(name) {
if (name === 'list_libraries') return {result: {navigation: [{name: 'Skills', path: 'Skills'}]}};
assert.equal(name, 'get_resource_set');
return {result: {
revision: 'release-1', resourceSet: {brand: 'Brand', category: 'lighting'},
components: [{id: 'visual_guides', status: 'available', assets: [
{role: 'guide', required: true, status: 'available', file: skill},
...[finish, ...assets].map(file => ({
id: file.fileId, role: 'asset', status: 'available',
file: file.fileId === 'crop' ? {...file, revision: publishedCropRevision} : file,
})),
]}],
}};
},
async readDocument(fileId, revision) {
const file = [skill, finish].find(file => file.fileId === fileId);
assert.equal(revision, file.revision);
return {result: {text: file.text, pages: file === finish ? 2 : 1}};
},
async download({fileId, revision}, {signal}) {
signal.throwIfAborted();
const file = assets.find(file => file.fileId === fileId);
assert.equal(revision, file.revision);
downloaded.push([fileId, revision]);
const localPath = path.join(store.root, file.name);
await fs.writeFile(localPath, file.text);
return {result: {localPath, sha256: createHash('sha256').update(file.text).digest('hex')}};
},
});
const selection = {
task: 'production', brandName: 'Brand', categoryName: 'lighting',
resourceSetId: 'release', runDeadline: 1000, outputId: 'detail',
};
const open = scope => openEnterpriseSkills(store, scope,
pins => context.load(scope, {pins, read: fn => fn()}),
(target, options) => context.loadReference(target, {...options, read: fn => fn()}));
const host = {store, productionSkills: await open(selection)};
const { cwd, tools, read } = await projectTools(host);
const skillFile = host.productionSkills.resource.skills[0].filePath;
const readResult = await read('main').execute('read-ref', {
path: path.join(path.dirname(skillFile), 'references', 'finish.md'),
});
assert.match(readResult.content[0].text, /Rule at the end/);
assert.deepEqual(downloaded, []);
publishedCropRevision = 'r8';
const second = {...selection, outputId: 'main'};
host.productionSkills = await open(second);
const command = 'python /skills/Skills/lighting/scripts/crop.py';
const result = await bashTool(tools).execute('pillow', {command});
assert.deepEqual(JSON.parse(result.content[0].text), {size: [4, 3], pixel: [255, 0, 0], pillow: '12.3.0'});
assert.ok((await fs.readFile(path.join(cwd, 'output.png'))).subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex')));
assert.deepEqual(downloaded, [['crop', 'r7'], ['config', 'r3'], ['colors', 'r5']]);
assert.ok(events.some(e => e.type === 'enterprise_skill_resource_read' && e.revision === 'r2'));
assert.ok(events.some(e => e.type === 'project_shell_started' &&
e.commandSha256 === createHash('sha256').update(command).digest('hex') &&
e.sources.some(source => source.revision === 'r7' && /^[a-f0-9]{64}$/.test(source.sha256))));
host.productionSkills = await openEnterpriseSkills(store, second, () => assert.fail('release was already locked'));
await bashTool(tools).execute('reopened', {command});
assert.equal(downloaded.length, 3);
assert.equal((await assertRemoved(events)).exitCode, 0);
assert.ok(!(await fs.readdir(store.dir)).some(name => name.startsWith('skill-shell-')));
});
test('project shell reaches only the workspace and has no network', {timeout: 30000}, async t => {
const { store } = await fixture(t);
const { cwd, tools } = await projectTools({store});
await fs.mkdir(path.join(store.dir, 'private'));
await fs.writeFile(path.join(store.dir, 'private', 'sentinel'), 'protected');
await fs.symlink(path.join(store.dir, 'private'), path.join(cwd, 'linked'),
process.platform === 'win32' ? 'junction' : 'dir');
const result = await bashTool(tools).execute('boundary', {command: `python - <<'PY'
from pathlib import Path
assert not Path("/workspace/../private/sentinel").exists()
assert not Path("/workspace/linked/sentinel").exists()
assert not Path("/var/run/docker.sock").exists()
assert {p.name for p in Path("/sys/class/net").iterdir()} == {"lo"}
try:
Path("/workspace/../outside.txt").write_text("outside")
except OSError as error:
assert error.errno == 30, error
else:
raise AssertionError("container root is writable")
Path("allowed.txt").write_text("inside")
print("bounded")
PY`});
assert.equal(result.content[0].text.trim(), 'bounded');
assert.equal(await fs.readFile(path.join(cwd, 'allowed.txt'), 'utf8'), 'inside');
assert.equal(await fs.readFile(path.join(store.dir, 'private', 'sentinel'), 'utf8'), 'protected');
await assert.rejects(fs.access(path.join(store.dir, 'outside.txt')), {code: 'ENOENT'});
});
test('AbortSignal stops a running Python script and its detached child', {timeout: 40000}, async t => {
const { store, events } = await fixture(t);
const { cwd, tools } = await projectTools({store});
const abort = new AbortController();
let abortedAt;
const running = bashTool(tools).execute('abort', {command: `python - <<'PY'
from pathlib import Path
import subprocess
import sys
import time
subprocess.Popen([sys.executable, "-c", 'import time; from pathlib import Path; Path("child-ready").touch(); time.sleep(15); Path("child-survived").touch()'], start_new_session=True)
while not Path("child-ready").exists():
time.sleep(.01)
print("child started", flush=True)
time.sleep(30)
PY`}, abort.signal, update => {
if (!abortedAt && update.content.some(block => block.text?.includes('child started'))) {
abortedAt = performance.now();
abort.abort();
}
});
await assert.rejects(running, {name: 'AbortError'});
const elapsed = performance.now() - abortedAt;
assert.ok(abortedAt && elapsed < 5000);
t.diagnostic(`AbortSignal 到容器清理完成约 ${Math.round(elapsed)} ms`);
await fs.access(path.join(cwd, 'child-ready'));
await assert.rejects(fs.access(path.join(cwd, 'child-survived')), {code: 'ENOENT'});
assert.equal((await assertRemoved(events)).cancelled, true);
});
test('AbortSignal received during container creation prevents script dispatch', {timeout: 30000}, async t => {
const { store, events } = await fixture(t);
const abort = new AbortController();
store.appendEvent = async event => {
events.push(event);
if (event.type === 'project_shell_started') abort.abort();
};
const { cwd, tools } = await projectTools({store});
await assert.rejects(bashTool(tools).execute('abort-before-start', {
command: 'touch ran',
}, abort.signal), {name: 'AbortError'});
await assert.rejects(fs.access(path.join(cwd, 'ran')), {code: 'ENOENT'});
assert.equal((await assertRemoved(events)).cancelled, true);
});
test('project shell reports its timeout and bounds stdout plus stderr', {timeout: 40000}, async t => {
const { store, events } = await fixture(t);
const { tools } = await projectTools({store});
const bash = bashTool(tools);
const result = await bash.execute('output', {command: "python -c 'import sys; print(\"x\" * 256000); sys.stderr.write(\"y\" * 256000)'"});
assert.match(result.content[0].text, /后续输出已截断/);
assert.ok(Buffer.byteLength(result.content[0].text) < 50 * 1024);
assert.equal((await assertRemoved(events)).outputTruncated, true);
await assert.rejects(bash.execute('timeout', {command: "python -c 'import time; time.sleep(30)'", timeout: 3}), /时限/);
assert.equal((await assertRemoved(events)).timedOut, true);
});