import { spawn } from 'child_process';
interface ExecuteCodeArgs {
code: string;
language: string;
timeout: number;
libraries: string[];
sse?: (data: any) => void;
}
export async function executeCode({ code, language, timeout, libraries, sse }: ExecuteCodeArgs): Promise<any> {
if (language !== 'python') {
return { isError: true, content: [{ type: 'text', text: 'Only Python is supported.' }] };
}
return new Promise((resolve) => {
console.log('Executing code in Docker container...');
// Execute Python code directly in the container
const dockerArgs = [
'run', '--rm', '-i',
'my-llm-sandbox',
'python', '-c', code
];
const proc = spawn('docker', dockerArgs);
let output = '';
let errorOutput = '';
proc.stdout.on('data', (data: Buffer) => {
const dataStr = data.toString();
output += dataStr;
console.log('[STDOUT]', dataStr);
if (sse) sse({ type: 'stdout', data: dataStr });
});
proc.stderr.on('data', (data: Buffer) => {
const dataStr = data.toString();
errorOutput += dataStr;
console.error('[STDERR]', dataStr);
if (sse) sse({ type: 'stderr', data: dataStr });
});
proc.on('close', (code: number) => {
console.log(`Process closed with code ${code}`);
resolve({
content: [
{ type: 'text', text: output },
...(errorOutput ? [{ type: 'text', text: `Errors: ${errorOutput}` }] : [])
],
exitCode: code
});
});
proc.on('error', (error: Error) => {
console.error('Process error:', error);
resolve({
isError: true,
content: [
{ type: 'text', text: `Error: ${error.message}` }
]
});
});
});
}