181 lines
8.7 KiB
JavaScript
181 lines
8.7 KiB
JavaScript
import {openXiaoyiSkills} from '../src/xiaoyi-release.mjs';
|
|
import {xiaoyiFixture} from './xiaoyi-fixture.mjs';
|
|
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 { 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 fetch = xiaoyiFixture('lighting','r1',skill.path,
|
|
Object.fromEntries([skill,finish,...assets].map(file=>[file.path,file.text])));
|
|
const host = {store,productionSkills:await openXiaoyiSkills(store,'lighting',undefined,undefined,fetch)};
|
|
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/);
|
|
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.ok(events.some(e => e.type === 'enterprise_skill_resource_read' && e.revision === 'lighting@r1'));
|
|
assert.ok(events.some(e => e.type === 'project_shell_started' &&
|
|
e.commandSha256 === createHash('sha256').update(command).digest('hex') &&
|
|
e.sources.some(source => source.revision === 'lighting@r1' && /^[a-f0-9]{64}$/.test(source.sha256))));
|
|
|
|
host.productionSkills = await openXiaoyiSkills(store,'lighting',undefined,undefined,()=>assert.fail('release was already locked'));
|
|
await bashTool(tools).execute('reopened', {command});
|
|
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);
|
|
});
|