2026-06-30 01:37:23 +08:00

68 lines
2.4 KiB
Python

from __future__ import annotations
import importlib.util
import json
import os
import pathlib
from typing import Any, Callable
HelperMap = dict[str, Callable[..., Any]]
def run(
run_id: str,
node_id: str,
output_dir: Any,
node_data: dict[str, Any],
inputs: list[dict[str, Any]],
helpers: HelperMap,
) -> list[dict[str, Any]]:
params = helpers["hyperparams"](node_data)
script_id = str(params.get("SCRIPT_ID", "") or "").strip()
if not script_id:
raise RuntimeError("受控脚本算子需要 SCRIPT_ID")
if not script_id.replace("_", "").replace("-", "").isalnum():
raise RuntimeError("SCRIPT_ID 只能包含字母、数字、下划线或短横线")
repository_value = os.getenv("DROBOTICFLOW_OPERATOR_REPOSITORY", "").strip()
if not repository_value:
raise RuntimeError("DROBOTICFLOW_OPERATOR_REPOSITORY is required for controlled scripts")
repository = pathlib.Path(repository_value).resolve()
script_path = (repository / "approved_scripts" / f"{script_id}.py").resolve()
approved_root = (repository / "approved_scripts").resolve()
if approved_root not in script_path.parents or not script_path.is_file():
raise RuntimeError(f"未找到受控脚本: {script_id}")
args = _json_param(params, "SCRIPT_ARGS_JSON", {})
input_paths = _json_param(params, "INPUT_PATHS_JSON", [])
output_contract = _json_param(params, "OUTPUT_CONTRACT_JSON", {})
spec = importlib.util.spec_from_file_location(f"droboticflow_controlled_script_{script_id}", script_path)
if spec is None or spec.loader is None:
raise RuntimeError(f"无法加载受控脚本: {script_id}")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module.run(
run_id=run_id,
node_id=node_id,
output_dir=pathlib.Path(output_dir),
node_data=node_data,
inputs=inputs,
helpers=helpers,
args=args,
input_paths=input_paths,
output_contract=output_contract,
)
def _json_param(params: dict[str, Any], key: str, default: Any) -> Any:
raw = params.get(key)
if raw in (None, ""):
return default
if isinstance(raw, (dict, list)):
return raw
try:
return json.loads(str(raw))
except json.JSONDecodeError as exc:
raise RuntimeError(f"{key} must be valid JSON") from exc