feat(sandbox): add Node.js code execution support to sandbox

This commit is contained in:
Eternity
2026-01-30 12:08:34 +08:00
parent ee50b25d06
commit 36e0ed15b6
35 changed files with 820 additions and 314 deletions

View File

@@ -14,7 +14,7 @@ from app.core.workflow.nodes.code.config import CodeNodeConfig
logger = logging.getLogger(__name__)
SCRIPT_TEMPLATE = Template(dedent("""
PYTHON_SCRIPT_TEMPLATE = Template(dedent("""
$code
import json
@@ -32,6 +32,20 @@ result = "<<RESULT>>" + output_json + "<<RESULT>>"
print(result)
"""))
NODEJS_SCRIPT_TEMPLATE = Template(dedent("""
$code
// decode and prepare input object
var inputs_obj = JSON.parse(Buffer.from('$inputs_variable', 'base64').toString('utf-8'))
// execute main function
var output_obj = main(inputs_obj)
// convert output to json and print
var output_json = JSON.stringify(output_obj)
var result = `<<RESULT>>$${output_json}<<RESULT>>`
console.log(result)
"""))
class CodeNode(BaseNode):
def __init__(self, node_config: dict[str, Any], workflow_config: dict[str, Any]):
@@ -83,6 +97,7 @@ class CodeNode(BaseNode):
input_variable_dict = {}
for input_variable in self.typed_config.input_variables:
input_variable_dict[input_variable.name] = self.get_variable(input_variable.variable, state)
code = base64.b64decode(
self.typed_config.code
).decode("utf-8")
@@ -90,11 +105,18 @@ class CodeNode(BaseNode):
input_variable_dict = base64.b64encode(
json.dumps(input_variable_dict).encode("utf-8")
).decode("utf-8")
final_script = SCRIPT_TEMPLATE.substitute(
code=code,
inputs_variable=input_variable_dict,
)
if self.typed_config.language == "python3":
final_script = PYTHON_SCRIPT_TEMPLATE.substitute(
code=code,
inputs_variable=input_variable_dict,
)
elif self.typed_config.language == 'nodejs':
final_script = NODEJS_SCRIPT_TEMPLATE.substitute(
code=code,
inputs_variable=input_variable_dict,
)
else:
raise ValueError(f"Unsupported language: {self.typed_config.language}")
async with httpx.AsyncClient() as client:
response = await client.post(

View File

@@ -69,7 +69,7 @@ services:
container_name: sandbox
ports:
- "8194"
command: /code/.venv/bin/python main.py
command: /code/.venv/bin/uvicorn main:app --host 0.0.0.0 --port 8194 --log-level debug
restart: unless-stopped
networks:
- sandbox