123 lines
5.6 KiB
JavaScript
123 lines
5.6 KiB
JavaScript
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';
|
||
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);
|
||
|
||
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();
|
||
if (timeout !== undefined && (!Number.isFinite(timeout) || timeout <= 0)) {
|
||
throw Error('项目终端的时限必须是正数');
|
||
}
|
||
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 {
|
||
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),
|
||
});
|
||
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 (deadline.signal.aborted) throw Error(`项目终端已达到本次工具调用的时限(${seconds} 秒)`);
|
||
throw error;
|
||
} finally {
|
||
clearTimeout(timer);
|
||
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 });
|
||
}
|
||
}
|
||
},
|
||
};
|
||
}
|