python_eval: Docker 샌드박스 실행(네트워크 없음·읽기전용 루트·워크스페이스만 마운트·자원 제한), 이미지 없으면 호스트 폴백
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ad589844be
commit
74481dbe29
3 files changed
+66
-7
No files matched your search
@@ -0,0 +1,10 @@
|
||||
# python_eval 격리 실행용 이미지. 호스트 파일·키·네트워크에서 분리된 코드 인터프리터.
|
||||
# 빌드: docker build -t homeclaw-pysandbox docker/pysandbox
|
||||
FROM python:3.12-slim
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends fonts-nanum libgl1 libglib2.0-0 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
RUN pip install --no-cache-dir numpy pandas matplotlib scipy openpyxl pillow \
|
||||
opencv-python-headless sympy scikit-learn statsmodels
|
||||
ENV MPLBACKEND=Agg MPLCONFIGDIR=/tmp/mpl HOME=/tmp PYTHONDONTWRITEBYTECODE=1
|
||||
WORKDIR /work
|
||||
@@ -202,7 +202,7 @@ RULES: 현재날씨/예보 → 한국은 weather_kma, 해외는 weather_openmete
|
||||
|
||||
image_ocr: `IMAGE OCR TOOL: image_read(path, lang?) → extract text from an image file via OCR. Supported formats: PNG, JPG, WEBP, BMP, TIFF. lang: "eng" (English, default), "kor" (Korean), "kor+eng" (both). Returns extracted text and confidence score. Useful for screenshots, scanned documents, and diagrams containing text.`,
|
||||
|
||||
python: `PYTHON TOOL: python_eval(code, timeout?, packages?) → execute Python code in the workspace directory. Returns stdout/stderr. timeout default 15s, max 60s. packages: comma-separated pip packages to install if missing (e.g. "numpy,pandas"). Standard library and pre-installed packages available. Use for math, data analysis, CSV/JSON processing, charting (save chart to workspace file). IMAGE EDITING: input path = exact string from [IMAGE PATH for image_edit/python_eval — use EXACTLY this string: ...] hint in the message. Save output to uploads/<name>.jpg. FONT: For Korean/CJK text in Pillow (speech bubbles, watermarks, etc.) use ImageFont.truetype("/usr/share/fonts/truetype/nanum/NanumGothicBold.ttf", size) — DejaVuSans does NOT support Korean.`,
|
||||
python: `PYTHON TOOL: python_eval(code, timeout?, packages?) → execute Python code in the workspace directory. Returns stdout/stderr. timeout default 15s, max 60s. packages: comma-separated pip packages to install if missing (e.g. "numpy,pandas"). Runs in an offline Docker sandbox (no internet unless network:true; host files outside the workspace are invisible; pip install is unavailable). Preinstalled: numpy pandas matplotlib scipy openpyxl pillow opencv sympy scikit-learn statsmodels. For Korean text in matplotlib: fm.fontManager.addfont('/usr/share/fonts/truetype/nanum/NanumGothic.ttf'); plt.rc('font', family='NanumGothic'). Use for math, data analysis, CSV/JSON processing, charting (save chart to workspace file). IMAGE EDITING: input path = exact string from [IMAGE PATH for image_edit/python_eval — use EXACTLY this string: ...] hint in the message. Save output to uploads/<name>.jpg. FONT: For Korean/CJK text in Pillow (speech bubbles, watermarks, etc.) use ImageFont.truetype("/usr/share/fonts/truetype/nanum/NanumGothicBold.ttf", size) — DejaVuSans does NOT support Korean.`,
|
||||
|
||||
sqlite: `SQLITE TOOL: sqlite_query(db_path, query, write?, max_rows?) → query a SQLite .db file in the workspace. SELECT queries allowed by default. Set write=true for INSERT/UPDATE/DELETE/CREATE/DROP. Returns formatted table. db_path is relative to workspace or absolute (must be inside workspace).`,
|
||||
};
|
||||
|
||||
+55
-6
@@ -1,4 +1,4 @@
|
||||
import { spawn } from 'child_process';
|
||||
import { spawn, spawnSync } from 'child_process';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import { getConfig } from '../config/config.js';
|
||||
@@ -32,6 +32,42 @@ const BLOCKED: RegExp[] = [
|
||||
/\bimportlib\s*\.\s*import_module\s*\(/,
|
||||
];
|
||||
|
||||
|
||||
// ── Docker 샌드박스 ──────────────────────────────────────────────────────────
|
||||
// 호스트에서 직접 돌리면 모델이 만든 코드가 kim 계정 권한으로 .smallclaw/config.json(API 키),
|
||||
// vault, ~/.ssh를 읽을 수 있다 — 위 BLOCKED 정규식은 그걸 막지 못한다(open()은 차단 대상이 아님).
|
||||
// 그래서 이미지(docker/pysandbox)가 있으면 컨테이너 안에서 실행한다: 워크스페이스만 /work에
|
||||
// 마운트, 네트워크 없음, 읽기전용 루트, 권한 전부 제거, 메모리/CPU/프로세스 수 제한.
|
||||
// 이미지가 없거나 SMALLCLAW_PY_SANDBOX=0이면 예전처럼 호스트에서 실행(폴백).
|
||||
const SANDBOX_IMAGE = process.env.SMALLCLAW_PY_IMAGE || 'homeclaw-pysandbox';
|
||||
let sandboxChecked = 0;
|
||||
let sandboxOk = false;
|
||||
function sandboxAvailable(): boolean {
|
||||
if (process.env.SMALLCLAW_PY_SANDBOX === '0') return false;
|
||||
const now = Date.now();
|
||||
if (now - sandboxChecked < 60_000) return sandboxOk; // 이미지는 나중에 빌드될 수 있으니 1분마다 재확인
|
||||
sandboxChecked = now;
|
||||
try {
|
||||
const r = spawnSync('docker', ['image', 'inspect', SANDBOX_IMAGE], { timeout: 5000, stdio: 'ignore' });
|
||||
sandboxOk = r.status === 0;
|
||||
} catch { sandboxOk = false; }
|
||||
return sandboxOk;
|
||||
}
|
||||
function sandboxArgs(workspacePath: string, code: string, name: string, network: boolean): string[] {
|
||||
const uid = typeof process.getuid === 'function' ? process.getuid() : 1000;
|
||||
const gid = typeof process.getgid === 'function' ? process.getgid() : 1000;
|
||||
return [
|
||||
'run', '--rm', '--name', name, '-i',
|
||||
'--network', network ? 'bridge' : 'none',
|
||||
'--read-only', '--tmpfs', '/tmp:rw,size=256m',
|
||||
'--cap-drop', 'ALL', '--security-opt', 'no-new-privileges',
|
||||
'--memory', '1g', '--cpus', '2', '--pids-limit', '128',
|
||||
'-u', `${uid}:${gid}`,
|
||||
'-v', `${workspacePath}:/work`, '-w', '/work',
|
||||
SANDBOX_IMAGE, 'python3', '-u', '-c', code,
|
||||
];
|
||||
}
|
||||
|
||||
export const pythonEvalTool = {
|
||||
name: 'python_eval',
|
||||
description: 'Execute Python code and return stdout/stderr. Runs in the workspace directory. Useful for math, data analysis, CSV/JSON processing, and scripting tasks. Standard library and installed packages (numpy, pandas, etc.) are available. 폴더 생성(os.makedirs)은 허용됨(삭제·이름변경만 차단). 웹에서 파일 내려받기: urllib.request/requests로 raw.githubusercontent.com 등의 직접 URL에서 받고, 받은 파일 개수를 실제로 세어 보고할 것 — 기대 개수보다 적으면 성공이 아니라 실패. GitHub 저장소 파일은 추측 경로 대신 GitHub API로 먼저 확인: https://api.github.com/repos/{owner}/{repo}/git/trees/{branch}?recursive=1. 여러 파일 받기 루틴: 한꺼번에 몰아서 하지 말고 순차(파일 하나씩 requests.get(url, timeout=15)) + try/except로 타임아웃/연결오류를 잡아 파일당 1회 재시도, 도구 timeout은 60으로 올릴 것. 그래도 남은 파일은 다음 턴(또는 다음 호출)에서 이어받을 것 — 전부 한 번에 받으려다 전체가 타임아웃으로 물러나는 패턴이 실측됨. 폴더 구조: GitHub 저장소 미러를 그대로 따오지 말 것 — 워크숍 프로젝트는 workshop/<프로젝트id>/stl/ 아래 평평하게 저장하고, 굳이 나눈다면 부품군(예: Leader/Follower) 서브폴더 하나까지만.',
|
||||
@@ -39,6 +75,7 @@ export const pythonEvalTool = {
|
||||
code: 'Python code to execute',
|
||||
timeout: 'Execution timeout in seconds (default: 15, max: 60)',
|
||||
packages: 'Comma-separated pip packages to install if missing before running (e.g. "numpy,pandas")',
|
||||
network: 'true to allow internet access inside the sandbox (default false: offline)',
|
||||
},
|
||||
jsonSchema: {
|
||||
type: 'object',
|
||||
@@ -46,6 +83,7 @@ export const pythonEvalTool = {
|
||||
code: { type: 'string', description: 'Python code to execute' },
|
||||
timeout: { type: 'number', description: 'Timeout in seconds (default: 15, max: 60)' },
|
||||
packages: { type: 'string', description: 'Comma-separated packages to pip install if missing' },
|
||||
network: { type: 'boolean', description: 'Allow internet access in the sandbox (default false)' },
|
||||
},
|
||||
required: ['code'],
|
||||
additionalProperties: false,
|
||||
@@ -89,7 +127,13 @@ export const pythonEvalTool = {
|
||||
scanDir(workspacePath, '');
|
||||
} catch {}
|
||||
|
||||
if (args?.packages) {
|
||||
const useSandbox = sandboxAvailable();
|
||||
const containerName = `pyeval-${process.pid}-${Date.now()}`;
|
||||
let sandboxNote = '';
|
||||
if (args?.packages && useSandbox) {
|
||||
sandboxNote = 'packages 인자는 샌드박스에서 무시됨(설치 불가). 기본 포함: numpy pandas matplotlib scipy openpyxl pillow opencv sympy scikit-learn statsmodels. 그 외 패키지가 꼭 필요하면 사용자에게 알릴 것.';
|
||||
}
|
||||
if (args?.packages && !useSandbox) {
|
||||
const pkgs = String(args.packages).split(',').map((p: string) => p.trim()).filter((p: string) => /^[a-zA-Z0-9_\-\.]+$/.test(p));
|
||||
for (const pkg of pkgs) {
|
||||
// Try --user first; if blocked by externally-managed-environment (Python 3.12+), retry with --break-system-packages
|
||||
@@ -118,13 +162,17 @@ export const pythonEvalTool = {
|
||||
let timedOut = false;
|
||||
let settled = false;
|
||||
|
||||
const child = spawn('python3', ['-u', '-c', code], {
|
||||
cwd: workspacePath,
|
||||
env: { ...process.env, PYTHONDONTWRITEBYTECODE: '1', PYTHONUNBUFFERED: '1' },
|
||||
});
|
||||
const child = useSandbox
|
||||
? spawn('docker', sandboxArgs(workspacePath, code, containerName, args?.network === true || args?.network === 'true'))
|
||||
: spawn('python3', ['-u', '-c', code], {
|
||||
cwd: workspacePath,
|
||||
env: { ...process.env, PYTHONDONTWRITEBYTECODE: '1', PYTHONUNBUFFERED: '1' },
|
||||
});
|
||||
|
||||
const killTimer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
// docker CLI를 죽여도 컨테이너는 남으므로 이름으로 강제 종료
|
||||
if (useSandbox) { try { spawnSync('docker', ['kill', containerName], { timeout: 5000, stdio: 'ignore' }); } catch {} }
|
||||
child.kill('SIGKILL');
|
||||
}, timeoutSec * 1000);
|
||||
|
||||
@@ -182,6 +230,7 @@ export const pythonEvalTool = {
|
||||
}).join('\n');
|
||||
parts.push(`[생성된 파일]\n${links}`);
|
||||
}
|
||||
if (sandboxNote) parts.push(`[참고] ${sandboxNote}`);
|
||||
parts.push(`[exit ${result.exitCode}]`);
|
||||
|
||||
return {
|
||||
|
||||
Reference in new issue
Block a user