sandbox.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. """
  2. engine.sandbox — Isolated agent execution environment.
  3. Level 0: In-process (dev, fastest, no isolation)
  4. Level 1: Subprocess (default, process-level isolation)
  5. """
  6. from __future__ import annotations
  7. import asyncio
  8. import json
  9. import time
  10. import traceback
  11. from dataclasses import dataclass
  12. from typing import Any, Dict, Optional
  13. @dataclass
  14. class ResourceLimits:
  15. cpu_seconds: int = 300
  16. memory_mb: int = 512
  17. max_steps: int = 100
  18. max_tokens: int = 100_000
  19. network_enabled: bool = True
  20. @dataclass
  21. class ExecutionResult:
  22. output: str = ""
  23. status: str = "completed"
  24. error: str = ""
  25. duration_ms: int = 0
  26. steps: int = 0
  27. input_tokens: int = 0
  28. output_tokens: int = 0
  29. class Sandbox:
  30. def __init__(self, level: int = 0, limits: ResourceLimits = None):
  31. self.level = level
  32. self.limits = limits or ResourceLimits()
  33. async def execute(self, config: dict, input_text: str, timeout: int = 120) -> ExecutionResult:
  34. if self.level == 0:
  35. return await self._exec_inprocess(config, input_text, timeout)
  36. elif self.level == 1:
  37. return await self._exec_subprocess(config, input_text, timeout)
  38. else:
  39. return await self._exec_inprocess(config, input_text, timeout)
  40. async def _exec_inprocess(self, config: dict, input_text: str, timeout: int) -> ExecutionResult:
  41. t0 = time.time()
  42. try:
  43. import tempfile, yaml, os
  44. with tempfile.NamedTemporaryFile(mode='w', suffix='.yml', delete=False, encoding='utf-8') as f:
  45. yaml.dump(config, f, allow_unicode=True)
  46. tmp = f.name
  47. try:
  48. from lambdagent.fromconfig import from_config
  49. from lambdagent.core import Context
  50. term = from_config(tmp)
  51. ctx = Context()
  52. result = term.apply(input_text, ctx)
  53. duration = int((time.time() - t0) * 1000)
  54. return ExecutionResult(
  55. output=str(result), status="completed", duration_ms=duration,
  56. steps=len(ctx.trace),
  57. input_tokens=sum(getattr(e, 'tokens_used', 0) for e in ctx.trace),
  58. )
  59. finally:
  60. os.unlink(tmp)
  61. except Exception as e:
  62. return ExecutionResult(
  63. status="failed", error=str(e),
  64. duration_ms=int((time.time() - t0) * 1000),
  65. )
  66. async def _exec_subprocess(self, config: dict, input_text: str, timeout: int) -> ExecutionResult:
  67. import tempfile, yaml, os
  68. with tempfile.NamedTemporaryFile(mode='w', suffix='.yml', delete=False, encoding='utf-8') as f:
  69. yaml.dump(config, f, allow_unicode=True)
  70. config_path = f.name
  71. # SEC-09: Pass input via JSON file, NOT string interpolation
  72. import json as _json
  73. with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False, encoding='utf-8') as inf:
  74. _json.dump({"input": input_text}, inf, ensure_ascii=False)
  75. input_path = inf.name
  76. runner_code = (
  77. "import sys, json, time, os\n"
  78. "t0 = time.time()\n"
  79. "try:\n"
  80. " with open(sys.argv[1]) as _cf: config_path = sys.argv[1]\n"
  81. " with open(sys.argv[2]) as _if: input_text = json.load(_if)['input']\n"
  82. " from lambdagent.fromconfig import from_config\n"
  83. " from lambdagent.core import Context\n"
  84. " term = from_config(config_path)\n"
  85. " ctx = Context()\n"
  86. " result = term.apply(input_text, ctx)\n"
  87. " duration = int((time.time() - t0) * 1000)\n"
  88. " print(json.dumps({'output': str(result), 'status': 'completed', 'duration_ms': duration, 'steps': len(ctx.trace)}))\n"
  89. "except Exception as e:\n"
  90. " print(json.dumps({'status': 'failed', 'error': str(e), 'duration_ms': int((time.time() - t0) * 1000)}))\n"
  91. )
  92. with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False, encoding='utf-8') as sf:
  93. sf.write(runner_code)
  94. script_path = sf.name
  95. try:
  96. proc = await asyncio.create_subprocess_exec(
  97. 'python', script_path, config_path, input_path,
  98. stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
  99. )
  100. stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)
  101. output = stdout.decode().strip()
  102. if output:
  103. data = json.loads(output)
  104. return ExecutionResult(**{k: v for k, v in data.items() if hasattr(ExecutionResult, k)})
  105. return ExecutionResult(status="failed", error=stderr.decode()[:500])
  106. except asyncio.TimeoutError:
  107. proc.kill()
  108. return ExecutionResult(status="failed", error="Execution timeout ({}s)".format(timeout))
  109. finally:
  110. for p in (config_path, script_path, input_path):
  111. try:
  112. os.unlink(p)
  113. except OSError:
  114. pass