67 lines
1.8 KiB
Python
67 lines
1.8 KiB
Python
import os
|
|||
|
|
import subprocess
|
||
|
|
|
||
|
|
from google.genai import types
|
||
|
|
|
||
|
|
|
||
|
|
def run_python_file(
|
||
|
|
working_directory: str, file_path: str, args: list[str] | None = None
|
||
|
|
) -> str:
|
||
|
|
try:
|
||
|
|
wdp = os.path.abspath(working_directory)
|
||
|
|
target = os.path.normpath(os.path.join(wdp, file_path))
|
||
|
|
valid_target_dir = os.path.commonpath([wdp, target]) == wdp
|
||
|
|
|
||
|
|
if not valid_target_dir:
|
||
|
|
return f'Error: Cannot execute "{file_path}" as it is outside the permitted working directory'
|
||
|
|
|
||
|
|
if not os.path.isfile(target):
|
||
|
|
return f'Error: "{file_path}" does not exist or is not a regular file'
|
||
|
|
|
||
|
|
if not target.endswith(".py"):
|
||
|
|
return f'Error: "{file_path}" is not a Python file'
|
||
|
|
|
||
|
|
command = ["python", target]
|
||
|
|
|
||
|
|
if args != None:
|
||
|
|
command.extend(args)
|
||
|
|
|
||
|
|
result = subprocess.run(
|
||
|
|
command,
|
||
|
|
cwd=working_directory,
|
||
|
|
text=True,
|
||
|
|
timeout=30_000,
|
||
|
|
capture_output=True,
|
||
|
|
)
|
||
|
|
|
||
|
|
if result.returncode != 0:
|
||
|
|
return f"Process exited with code {result.returncode}"
|
||
|
|
|
||
|
|
if len(result.stdout) == 0 and len(result.stderr) == 0:
|
||
|
|
return "No output produced"
|
||
|
|
|
||
|
|
return f"STDOUT: {result.stdout}\nSTDERR: {result.stderr}"
|
||
|
|
except Exception as e:
|
||
|
|
return f"Error: {e}"
|
||
|
|
|
||
|
|
|
||
|
|
schema_run_python_file = types.FunctionDeclaration(
|
||
|
|
name="run_python_file",
|
||
|
|
description="",
|
||
|
|
parameters=types.Schema(
|
||
|
|
type=types.Type.OBJECT,
|
||
|
|
properties={
|
||
|
|
"file_path": types.Schema(
|
||
|
|
type=types.Type.STRING,
|
||
|
|
description="",
|
||
|
|
),
|
||
|
|
"args": types.Schema(
|
||
|
|
type=types.Type.ARRAY,
|
||
|
|
items=types.Schema(type=types.Type.STRING),
|
||
|
|
description="",
|
||
|
|
),
|
||
|
|
},
|
||
|
|
required=["file_path"],
|
||
|
|
),
|
||
|
|
)
|