""" Shared declarative node specification loader for domain node modules. Loads validated NodeDefinition contracts from alli_backend/specs/nodes/*.json. """ import ast import json from functools import lru_cache from pathlib import Path from typing import Any, Dict, List, Tuple from language_core.node_definition import NodeDefinition NODE_SPECS_DIR = Path(__file__).resolve().parent.parent.parent / "specs" / "nodes" def parse_safe_literal_or_json(raw: Any) -> Tuple[bool, Any]: """Safely parses a stringified JSON or Python literal without eval().""" if not isinstance(raw, str): return False, raw s = raw.strip() if not s: return False, raw try: return True, json.loads(s) except Exception: pass try: return True, ast.literal_eval(s) except Exception: return False, raw @lru_cache(maxsize=16) def load_node_specs(domain_name: str) -> List[Dict[str, Any]]: """Load raw node definition dicts for a domain spec JSON file.""" spec_path = NODE_SPECS_DIR / f"{domain_name}.json" with open(spec_path, "r", encoding="utf-8") as f: return json.load(f) def _coerce_port_literals(mapping: Dict[str, Any], port_types: Dict[str, str]) -> None: """Restore JSON-serialized lists back to Python tuples/sets where port type specifies.""" for key, val in list(mapping.items()): ptype = str(port_types.get(key, "")).lower() if isinstance(val, list): if ptype == "tuple": mapping[key] = tuple(val) elif ptype == "set": mapping[key] = set(val) def register_domain_nodes(registry: Any, domain_name: str, executors: Dict[str, Any]) -> None: """Register all nodes for a domain from JSON spec paired with Python executors.""" for raw_spec in load_node_specs(domain_name): schema = NodeDefinition.model_validate(raw_spec) in_types = {p.id: p.type for p in schema.inputs} out_types = {p.id: p.type for p in schema.outputs} if schema.docs: for ex in schema.docs.examples: _coerce_port_literals(ex.inputs, in_types) _coerce_port_literals(ex.expected_output, out_types) if schema.verification: _coerce_port_literals(schema.verification.test_inputs, in_types) _coerce_port_literals(schema.verification.expected_outputs, out_types) registry.register(schema, executor=executors.get(schema.type))