| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128 |
- """
- engine.sandbox — Isolated agent execution environment.
- Level 0: In-process (dev, fastest, no isolation)
- Level 1: Subprocess (default, process-level isolation)
- """
- from __future__ import annotations
- import asyncio
- import json
- import time
- import traceback
- from dataclasses import dataclass
- from typing import Any, Dict, Optional
- @dataclass
- class ResourceLimits:
- cpu_seconds: int = 300
- memory_mb: int = 512
- max_steps: int = 100
- max_tokens: int = 100_000
- network_enabled: bool = True
- @dataclass
- class ExecutionResult:
- output: str = ""
- status: str = "completed"
- error: str = ""
- duration_ms: int = 0
- steps: int = 0
- input_tokens: int = 0
- output_tokens: int = 0
- class Sandbox:
- def __init__(self, level: int = 0, limits: ResourceLimits = None):
- self.level = level
- self.limits = limits or ResourceLimits()
- async def execute(self, config: dict, input_text: str, timeout: int = 120) -> ExecutionResult:
- if self.level == 0:
- return await self._exec_inprocess(config, input_text, timeout)
- elif self.level == 1:
- return await self._exec_subprocess(config, input_text, timeout)
- else:
- return await self._exec_inprocess(config, input_text, timeout)
- async def _exec_inprocess(self, config: dict, input_text: str, timeout: int) -> ExecutionResult:
- t0 = time.time()
- try:
- import tempfile, yaml, os
- with tempfile.NamedTemporaryFile(mode='w', suffix='.yml', delete=False, encoding='utf-8') as f:
- yaml.dump(config, f, allow_unicode=True)
- tmp = f.name
- try:
- from lambdagent.fromconfig import from_config
- from lambdagent.core import Context
- term = from_config(tmp)
- ctx = Context()
- result = term.apply(input_text, ctx)
- duration = int((time.time() - t0) * 1000)
- return ExecutionResult(
- output=str(result), status="completed", duration_ms=duration,
- steps=len(ctx.trace),
- input_tokens=sum(getattr(e, 'tokens_used', 0) for e in ctx.trace),
- )
- finally:
- os.unlink(tmp)
- except Exception as e:
- return ExecutionResult(
- status="failed", error=str(e),
- duration_ms=int((time.time() - t0) * 1000),
- )
- async def _exec_subprocess(self, config: dict, input_text: str, timeout: int) -> ExecutionResult:
- import tempfile, yaml, os
- with tempfile.NamedTemporaryFile(mode='w', suffix='.yml', delete=False, encoding='utf-8') as f:
- yaml.dump(config, f, allow_unicode=True)
- config_path = f.name
- # SEC-09: Pass input via JSON file, NOT string interpolation
- import json as _json
- with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False, encoding='utf-8') as inf:
- _json.dump({"input": input_text}, inf, ensure_ascii=False)
- input_path = inf.name
- runner_code = (
- "import sys, json, time, os\n"
- "t0 = time.time()\n"
- "try:\n"
- " with open(sys.argv[1]) as _cf: config_path = sys.argv[1]\n"
- " with open(sys.argv[2]) as _if: input_text = json.load(_if)['input']\n"
- " from lambdagent.fromconfig import from_config\n"
- " from lambdagent.core import Context\n"
- " term = from_config(config_path)\n"
- " ctx = Context()\n"
- " result = term.apply(input_text, ctx)\n"
- " duration = int((time.time() - t0) * 1000)\n"
- " print(json.dumps({'output': str(result), 'status': 'completed', 'duration_ms': duration, 'steps': len(ctx.trace)}))\n"
- "except Exception as e:\n"
- " print(json.dumps({'status': 'failed', 'error': str(e), 'duration_ms': int((time.time() - t0) * 1000)}))\n"
- )
- with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False, encoding='utf-8') as sf:
- sf.write(runner_code)
- script_path = sf.name
- try:
- proc = await asyncio.create_subprocess_exec(
- 'python', script_path, config_path, input_path,
- stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
- )
- stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)
- output = stdout.decode().strip()
- if output:
- data = json.loads(output)
- return ExecutionResult(**{k: v for k, v in data.items() if hasattr(ExecutionResult, k)})
- return ExecutionResult(status="failed", error=stderr.decode()[:500])
- except asyncio.TimeoutError:
- proc.kill()
- return ExecutionResult(status="failed", error="Execution timeout ({}s)".format(timeout))
- finally:
- for p in (config_path, script_path, input_path):
- try:
- os.unlink(p)
- except OSError:
- pass
|