Merge commit '217cfdc3' into codex/xiaoyi-whole-detail-fidelity

This commit is contained in:
WuYongJie 2026-11-26 17:36:49 +08:00
commit f4648cbfc3
10 changed files with 431 additions and 62 deletions

View File

@ -14,7 +14,9 @@
## 工具与画布
只开放规则读取、事实记忆、历史检索、沙箱工具开发/运行、画布读取及现有图层编辑。禁用 SDK 默认终端、文件操作、外部扩展、目录扫描和任意网络工具。
Pi 使用项目文件工具和受限 Bash 执行辅助任务。Bash 在本机 Linux 容器内启动,提供 Python 3.13 和 Pillow 12.3.0,关闭网络,只允许写入本项目的 `/workspace` 和容器临时目录。选定版本声明的 Skill、引用和辅助文件保留相对路径,只读呈现在 `/skills`。例如 `python /skills/Skills/lighting/scripts/crop.py input.png output.png`。发布脚本由资源组或模板的 `skill_sources` 声明文件 ID、版本和路径,支持 `.py`、`.sh` 以及随脚本发布的 `.json`、`.csv`。
终端默认时限 60 秒,最长 120 秒,标准输出与标准错误合计最多返回 48 KiB。用户取消或达到时限时,终止整个容器及其子进程。脚本可以在工作目录生成裁切等过程产物,画布写入仍通过原生命令。
自建工具使用 `quickjs-emscripten@0.32.0`:8MB内存、256KB栈、约200ms中断限时、仅JSON输入输出。至少3项测试通过才保存不可变版本;运行时复核版本哈希。无宿主文件、网络、Key或Node API。计算结果不直接写画布,仍须通过原生编辑命令。
@ -46,6 +48,23 @@ npm ci --ignore-scripts
npm test
```
### 本机 Skill 脚本环境
Windows 使用 Docker Desktop Linux 引擎。首次准备镜像需要本机已有的 `bash:5.2`、`python:3.13-alpine` 镜像,以及 Pillow 12.3.0 的 CPython 3.13 Linux musl x64 wheel。下面仅下载约 7 MB 的 Pillow wheel,构建使用本机镜像,脚本运行时禁止拉取镜像。从 `apps/detail-agent-pi` 运行:
```powershell
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true
docker --context desktop-linux image inspect --format '{{.Id}}' bash:5.2 python:3.13-alpine
$skillBuild = (New-Item -ItemType Directory -Path (Join-Path $env:TEMP ('xiaoyi-skill-' + [guid]::NewGuid()))).FullName
Copy-Item -LiteralPath 'skill-runtime/Dockerfile','skill-runtime/.dockerignore' -Destination $skillBuild
python -m pip download --only-binary=:all: --no-deps --platform musllinux_1_2_x86_64 --implementation cp --python-version 3.13 --abi cp313 --dest $skillBuild Pillow==12.3.0
docker --context desktop-linux build --builder desktop-linux --pull=false --network=none -t gongxiangp2-skill-runtime:python3.13-pillow12.3.0 $skillBuild
npm run test:skill-runtime
```
有离线 wheel 时可以直接复制到构建目录,跳过下载。客户端运行时只依赖 Docker 和已构建的本机工具镜像。
原生客户端构建与使用见 `../detail-photocraft/JIANSUN.md`。完整本地包包含原生程序、`agent/node.exe`、`agent/src`、`agent/vendor` 与锁定依赖,不包含账号配置、Key、用户工程或请求日志:
```powershell

View File

@ -5,6 +5,7 @@
"type": "module",
"scripts": {
"test": "node --test test/*.test.mjs",
"test:skill-runtime": "node --test test/project-shell.integration.mjs",
"verify:live": "node scripts/acceptance.mjs"
},
"engines": {

View File

@ -0,0 +1,2 @@
*
!pillow-12.3.0-*.whl

View File

@ -0,0 +1,7 @@
FROM bash:5.2 AS bash
FROM python:3.13-alpine
COPY --from=bash /usr/local/bin/bash /usr/local/bin/bash
COPY pillow-12.3.0-*.whl /tmp/wheels/
RUN python -m pip install --no-index --no-deps --no-cache-dir --find-links=/tmp/wheels Pillow==12.3.0 \
&& bash --version \
&& python -c 'from PIL import Image; print(Image.__version__)'

View File

@ -961,7 +961,7 @@ export class DetailPiAgent {
this.productionSkills=await openEnterpriseSkills(this.store,selection,
pins=>this.loadWholeDetailKnowledge(selection,this.productionSignal,false,pins),
(target,lock)=>this.enterpriseContext.loadReference(target,{
...lock,read:this.productionKnowledgeRead(selection.task),
...lock,read:this.productionKnowledgeRead('production',lock.signal),
}));
this.session.setActiveToolsByName([...new Set([...this.session.getActiveToolNames(),'read'])]);
}

View File

@ -1,9 +1,11 @@
import fs from 'node:fs/promises';
import path from 'node:path';
import { EnterpriseKnowledge } from './enterprise-knowledge.mjs';
import { atomic } from './store.mjs';
import path from 'node:path';
const tasks = {chat:'详情页项目创作流程、模板字段应用与品牌规范',copy:'卖点文案生成、修改与字段约束',image:'图片提示词、候选修改与视觉品牌规范',plan:'成熟模板内容策划与字段适配',canvas:'成熟模板字段回填、保留排版与局部修改'};
const skillRoot = file => file?.match(/^(.*\/Skills\/[^/]+)\//)?.[1];
const isSkillRuntimeFile = file => /\.(py|sh|json|csv)$/i.test(file);
export function links(document) {
return [...document.text.matchAll(/\[([^\]]+)\]\(([^)\n]+\.md)(?:#[^)]*)?\)/g)]
@ -100,7 +102,8 @@ export class EnterpriseContext {
const component=set.components.find(c=>c.id==='visual_guides');
if(!component)return null;
if(component.status!=='available')throw Error('所选模板发布的制作规则尚有缺项');
const sources=component.assets.filter(asset=>asset.role==='guide'&&asset.required).map(asset=>{
const sources=component.assets.filter(asset=>(asset.role==='guide'&&asset.required) ||
(asset.status==='available'&&isSkillRuntimeFile(asset.file?.path))).map(asset=>{
if(asset.status!=='available')throw Error('无法读取已发布的规则:'+asset.file?.name);
const {fileId,revision,path}=asset.file;
return {fileId,revision,path,kind:asset.file.name==='SKILL.md'?'skill':asset.id};
@ -112,11 +115,15 @@ export class EnterpriseContext {
}
async loadGuides(identity,sources,resourceRevision,{signal,read,pins}) {
const skills=[],rules=[];
const skills=[],rules=[],scriptSources=[];
for (const {fileId,revision,path:source,kind} of sources) {
if(!fileId||!revision||!source||!kind)throw Error('模板制作规则缺少文件身份、版本或用途');
const target=kind==='skill'?skills:rules;
const pinned=pins?.get(source);
if (isSkillRuntimeFile(source)) {
scriptSources.push({fileId:pinned?.fileId??fileId,revision:pinned?.revision??revision,path:source});
continue;
}
const target=kind==='skill'?skills:rules;
if (pinned) {
target.push({...pinned,kind});
} else {
@ -125,10 +132,16 @@ export class EnterpriseContext {
}
}
if(!skills.length)throw Error('所选模板未声明制作 Skill 正文');
return {...identity,skills,rules,resourceRevision,execution:'按项目发布的 Skill 和引用执行。'};
return {...identity,skills,rules,resourceRevision,scriptSources,execution:'按项目发布的 Skill 和引用执行。'};
}
async loadReference(target, {directory, source, signal, read}) {
if (isSkillRuntimeFile(target)) {
if (!source?.fileId || !source.revision || source.path!==target) throw Error('脚本资源须绑定到已发布的文件版本');
const {result}=await read(()=>this.client.download({fileId:source.fileId,revision:source.revision},{signal}));
const bytes = await fs.readFile(result.localPath, {signal});
return {...source,sha256:result.sha256,kind:'skill-runtime',bytes:bytes.toString('base64')};
}
directory??=(await read(()=>this.client.call('list_libraries',{},{signal}))).result.navigation
?.find(item=>item.name==='Skills')?.path;
if (!directory || !target.startsWith(directory+'/')) throw Error('技能引用超出授权技能目录');

View File

@ -18,6 +18,9 @@ export async function openEnterpriseSkills(store, selection, load, loadReference
const pins = new Map();
for (const entry of entries.filter(name => name.endsWith('.json'))) {
const prior = JSON.parse(await fs.readFile(path.join(selections, entry), 'utf8'));
for (const source of prior.scriptSources ?? []) {
if (!pins.has(source.path)) pins.set(source.path, source);
}
for (const source of [...prior.skills, ...prior.rules]) pins.set(source.path, source);
}
return pins;
@ -34,12 +37,15 @@ export async function openEnterpriseSkills(store, selection, load, loadReference
const references = new Map();
const inFlight = new Map();
const filePath = relative => path.join(directory, 'files', ...relative.split('/'));
const validPath = relative => relative !== '..' && !relative.startsWith('../') &&
!path.posix.isAbsolute(relative) && !/[:\\]/u.test(relative);
const validPath = relative => typeof relative === 'string' && relative && relative !== '.' &&
relative !== '..' && !relative.startsWith('../') && !path.posix.isAbsolute(relative) &&
!/[:\\\0]/u.test(relative) && path.posix.normalize(relative) === relative;
async function materialize(item) {
const {fileId, revision, text, kind, path: relative} = item;
if (!validPath(relative) || path.posix.normalize(relative) !== relative || typeof text !== 'string') {
const {fileId, revision, text, kind, sha256, path: relative} = item;
const bytes = kind === 'skill-runtime' && typeof item.bytes === 'string'
? Buffer.from(item.bytes, 'base64') : typeof text === 'string' ? Buffer.from(text) : null;
if (!validPath(relative) || !bytes) {
throw Error('企业 Skill 资源缺少可读取的正文或路径:' + relative);
}
const target = filePath(relative);
@ -50,13 +56,13 @@ export async function openEnterpriseSkills(store, selection, load, loadReference
if (prior) return;
await fs.mkdir(path.dirname(target), {recursive:true});
try {
await fs.writeFile(target, text, {encoding:'utf8', flag:'wx'});
await fs.writeFile(target, bytes, {flag:'wx'});
} catch (error) {
if (error.code !== 'EEXIST' || await fs.readFile(target, 'utf8') !== text) throw error;
if (error.code !== 'EEXIST' || !(await fs.readFile(target)).equals(bytes)) throw error;
}
documents.set(target, {fileId, revision, kind, path:relative});
documents.set(target, {fileId, revision, kind, path:relative, ...(sha256 ? {sha256} : {})});
if (kind === 'skill') skillPaths.push(target);
for (const link of links(item).filter(({target}) => validPath(target))) {
for (const link of (typeof text === 'string' ? links(item) : []).filter(({target}) => validPath(target))) {
if (!references.has(filePath(link.target))) {
references.set(filePath(link.target), {target:link.target, from:relative});
}
@ -64,14 +70,31 @@ export async function openEnterpriseSkills(store, selection, load, loadReference
}
for (const item of [...knowledge.skills, ...knowledge.rules]) await materialize(item);
const scriptSources = new Map();
for (const source of knowledge.scriptSources ?? []) {
if (!validPath(source.path)) throw Error('已发布的脚本资源路径无效:' + source.path);
const file = filePath(source.path);
const prior = scriptSources.get(file);
if (prior && (prior.fileId !== source.fileId || prior.revision !== source.revision)) {
throw Error('同一脚本路径声明了多个版本:' + source.path);
}
scriptSources.set(file, source);
}
let saving = Promise.resolve();
async function resolveReference({target, from}) {
async function resolveReference({target, from}, script, signal) {
try {
const pins = await readPins();
const source = knowledge.referenceSources?.find(item => item.path === target);
const source = script ?? knowledge.referenceSources?.find(item => item.path === target);
const pinned = pins.get(target);
const item = pinned ? {...pinned,kind:'native-reference'} :
await loadReference(target, {source,directory:knowledge.skillDirectory});
const hasContent = script ? pinned?.kind === 'skill-runtime' : typeof pinned?.text === 'string';
const item = hasContent ? {...pinned,kind:script ? 'skill-runtime' : 'native-reference'} :
await loadReference(target, {source,directory:knowledge.skillDirectory,signal});
if (item.path !== target) throw Error('返回的资源路径与锁定路径不一致');
if (script && (item.fileId !== script.fileId || item.revision !== script.revision)) {
throw Error('返回的脚本与锁定版本不一致');
}
signal?.throwIfAborted();
const save = saving.then(async () => {
if (knowledge.rules.some(rule => rule.path === target)) return;
const rules = [...knowledge.rules, item];
@ -82,20 +105,30 @@ export async function openEnterpriseSkills(store, selection, load, loadReference
await save;
await materialize(item);
} catch (error) {
signal?.throwIfAborted();
throw Error('无法读取「' + from + '」引用的「' + target + '」:' + error.message, {cause:error});
}
}
async function resolveFile(file) {
async function resolveFile(file, signal) {
if (documents.has(file)) return true;
const reference = references.get(file);
const script = scriptSources.get(file);
const reference = script ? {target:script.path,from:'发布资源'} : references.get(file);
if (!reference || !loadReference) return false;
if (!inFlight.has(file)) {
inFlight.set(file, resolveReference(reference).finally(() => inFlight.delete(file)));
inFlight.set(file, resolveReference(reference, script, signal).finally(() => inFlight.delete(file)));
}
await inFlight.get(file);
return true;
}
async function shellFiles(signal) {
for (const file of scriptSources.keys()) {
signal.throwIfAborted();
if (!await resolveFile(file, signal)) throw Error('无法读取已发布的脚本资源:' + scriptSources.get(file).path);
}
return [...documents].map(([file, source]) => ({file, source}));
}
const resource = loadSkills({cwd:store.dir, agentDir:store.dir, skillPaths, includeDefaults:false});
const loadedPaths = new Set(resource.skills.map(skill => skill.filePath));
const missing = skillPaths.filter(file => !loadedPaths.has(file));
@ -106,5 +139,5 @@ export async function openEnterpriseSkills(store, selection, load, loadReference
await store.appendEvent({type:'enterprise_skill_resources_bound', outputId:selection.outputId,
...((knowledge.resourceRevision) ? {resourceRevision:knowledge.resourceRevision} : null),
sources:[...documents.values()]});
return {knowledge, resource, documents, resolveFile};
return {knowledge, resource, documents, resolveFile, shellFiles};
}

View File

@ -1,58 +1,121 @@
import { execFile, spawn } from 'node:child_process';
import { createHash } from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
import { promisify } from 'node:util';
const docker = promisify(execFile);
const endpoint = process.platform === 'win32'
? 'npipe:////./pipe/dockerDesktopLinuxEngine'
: 'unix:///var/run/docker.sock';
const image = 'docker.io/library/bash:5.2';
export const projectShellImage = 'gongxiangp2-skill-runtime:python3.13-pillow12.3.0';
const dockerArgs = ['--host', endpoint];
const dockerOptions = { windowsHide: true };
const outputLimit = 48 * 1024;
const run = args => docker('docker', [...dockerArgs, ...args], dockerOptions);
export function projectShell(root, store) {
function bind(source, target, readonly = false) {
const sourceField = 'source=' + source;
const field = /[",\r\n]/u.test(sourceField) ? '"' + sourceField.replaceAll('"', '""') + '"' : sourceField;
return ['--mount', `type=bind,${field},target=${target}${readonly ? ',readonly' : ''}`];
}
export function projectShell(root, store, skillFiles = () => []) {
return {
async exec(command, _cwd, { onData, signal, timeout }) {
signal?.throwIfAborted();
const run = (args) => docker('docker', ['--host', endpoint, ...args], dockerOptions);
let container;
try {
const {stdout} = await run([
'create', '--pull=never', '--network=none', '--read-only', '--cap-drop=ALL',
'--security-opt=no-new-privileges', '--tmpfs', '/tmp',
'--mount', `type=bind,source=${root},target=/workspace`,
'--workdir', '/workspace', '--entrypoint', '/usr/local/bin/bash', image, '-lc', command,
]);
container = stdout.trim();
} catch (error) {
await store.appendEvent({type: 'project_shell_blocked', reason: 'local-sandbox-unavailable'});
const detail = error.stderr?.trim();
throw Error(`项目终端需要运行中的本地 Docker 及 ${image} 镜像${detail ? '。'+detail : ''}`);
if (timeout !== undefined && (!Number.isFinite(timeout) || timeout <= 0)) {
throw Error('项目终端的时限必须是正数');
}
let cleanup;
const remove = () => cleanup ??= run(['rm', '--force', container]);
let timer;
let timedOut = false;
const stop = () => { void remove().catch(() => {}); };
const seconds = Math.min(timeout ?? 60, 120);
const deadline = new AbortController();
const operation = signal ? AbortSignal.any([signal, deadline.signal]) : deadline.signal;
const timer = setTimeout(() => deadline.abort(), seconds * 1000);
let container, stagedSkills, cleanup, outputTruncated = false, exitCode;
const remove = () => cleanup ??= run(['container', 'rm', '--force', container]).catch(error => {
// Successful runs have already been removed by Docker's --rm.
if (!error.stderr?.includes('No such container')) throw error;
});
try {
signal?.throwIfAborted();
await store.appendEvent({type: 'project_shell_started', sandbox: image});
signal?.throwIfAborted();
const exitCode = await new Promise((resolve, reject) => {
const child = spawn('docker', ['--host', endpoint, 'start', '-a', container], dockerOptions);
child.stdout.on('data', onData);
child.stderr.on('data', onData);
child.once('error', reject);
child.once('close', resolve);
signal?.addEventListener('abort', stop, {once: true});
if (timeout > 0) timer = setTimeout(() => { timedOut = true; stop(); }, timeout * 1000);
const files = await skillFiles(operation);
if (files.length) {
stagedSkills = await fs.mkdtemp(path.join(store.dir, 'skill-shell-'));
for (const { file, source } of files) {
operation.throwIfAborted();
const target = path.join(stagedSkills, ...source.path.split('/'));
await fs.mkdir(path.dirname(target), { recursive: true });
await fs.copyFile(file, target);
}
}
operation.throwIfAborted();
try {
const { stdout } = await run([
'container', 'create', '--rm', '--pull=never', '--network=none', '--read-only',
'--cap-drop=ALL', '--security-opt=no-new-privileges', '--init', '--pids-limit=64',
'--cpus=1', '--memory=768m', '--memory-swap=768m', '--log-driver=none',
'--tmpfs', '/tmp:rw,noexec,nosuid,nodev,size=64m',
'--label', 'org.jiansun.role=xiaoyi-skill-runtime',
...bind(root, '/workspace'),
...(stagedSkills ? bind(stagedSkills, '/skills', true) : []),
'--env', 'PYTHONDONTWRITEBYTECODE=1', '--env', 'PYTHONUNBUFFERED=1',
'--workdir', '/workspace', '--entrypoint', '/bin/busybox',
projectShellImage, 'timeout', '-s', 'KILL', String(Math.ceil(seconds)),
'/usr/local/bin/bash', '-c', command,
]);
container = stdout.trim();
} catch (error) {
operation.throwIfAborted();
await store.appendEvent({ type: 'project_shell_blocked', reason: 'local-sandbox-unavailable' });
const detail = error.stderr?.trim();
throw Error(`项目终端需要运行中的本地 Docker 及 ${projectShellImage} 镜像${detail ? '。' + detail : ''}`);
}
await store.appendEvent({
type: 'project_shell_started', sandbox: projectShellImage, container,
commandSha256: createHash('sha256').update(command).digest('hex'),
sources: files.map(({ source }) => source),
});
await store.appendEvent({type: 'project_shell_finished', exitCode, cancelled: signal?.aborted === true, timedOut});
operation.throwIfAborted();
let remaining = outputLimit;
const data = chunk => {
if (remaining > 0) onData(chunk.subarray(0, remaining));
if (chunk.length > remaining && !outputTruncated) {
outputTruncated = true;
onData(Buffer.from('\n[项目终端输出超过 48 KiB,后续输出已截断]\n'));
}
remaining = Math.max(0, remaining - chunk.length);
};
const child = spawn('docker', [...dockerArgs, 'container', 'start', '--attach', container], dockerOptions);
const stop = () => { void remove().catch(() => child.kill()); };
operation.addEventListener('abort', stop, { once: true });
try {
exitCode = await new Promise((resolve, reject) => {
child.stdout.on('data', data);
child.stderr.on('data', data);
child.once('error', reject);
child.once('close', code => resolve(code ?? 1));
});
operation.throwIfAborted();
return { exitCode };
} finally {
operation.removeEventListener('abort', stop);
}
} catch (error) {
signal?.throwIfAborted();
if (timedOut) throw Error('项目终端已达到本次工具调用的时限');
return {exitCode};
if (deadline.signal.aborted) throw Error(`项目终端已达到本次工具调用的时限(${seconds} 秒)`);
throw error;
} finally {
clearTimeout(timer);
signal?.removeEventListener('abort', stop);
await remove();
try {
if (container) {
await remove();
await store.appendEvent({
type: 'project_shell_finished', container, exitCode,
cancelled: signal?.aborted === true, timedOut: deadline.signal.aborted, outputTruncated,
});
}
} finally {
if (stagedSkills) await fs.rm(stagedSkills, { recursive: true });
}
}
},
};

View File

@ -4,9 +4,11 @@ import {createReadTool,createWriteTool,createEditTool,createLsTool,createFindToo
import {projectShell} from './project-shell.mjs';
export async function projectTools(host) {
const cwd = path.join(host.store.dir,'workspace');
const projectRoot = await fs.realpath(host.store.dir);
const cwd = path.join(projectRoot,'workspace');
await fs.mkdir(cwd,{recursive:true});
const root = await fs.realpath(cwd);
if (path.relative(cwd,root)) throw Error('项目工作目录必须位于本项目内');
const inside = (parent,file) => {
const relative=path.relative(parent,file);
if (relative==='..' || relative.startsWith('..'+path.sep) || path.isAbsolute(relative)) {
@ -44,6 +46,11 @@ export async function projectTools(host) {
}});
const writeFile=async (file,content)=>fs.writeFile(await checked(file),content);
const stat=async file=>fs.stat(await checked(file));
const bash=createBashTool(cwd,{
operations:projectShell(root,host.store,signal=>host.productionSkills?.shellFiles(signal)??[]),
exposeSessionEnvironment:false,
});
bash.description='在隔离的 /workspace 中执行 Bash(含 Python、Pillow)。已发布的 Skill 脚本和资料按原相对路径只读挂载在 /skills。可在工作区创建任务脚本与产物。默认时限 60 秒,最长 120 秒,输出上限 48 KiB。';
return {cwd,read,tools:[
read('main'),
createWriteTool(cwd,{operations:{writeFile,mkdir:async dir=>{await fs.mkdir(await checked(dir),{recursive:true});}}}),
@ -61,6 +68,6 @@ export async function projectTools(host) {
return matches;
}}}),
createGrepTool(cwd,{operations:{isDirectory:async file=>(await stat(file)).isDirectory()}}),
createBashTool(cwd,{operations:projectShell(root,host.store),exposeSessionEnvironment:false}),
bash,
]};
}

View File

@ -0,0 +1,224 @@
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);
});