rsnarsna
feat(alli-backend): Wave-1 standardization, standalone sys.env node & vault crypto, and DEC-014 security hardening
8628c98 Download lambdas/codegen/emitters_core.py from Rsnarsna/auto: direct link, hf CLI and curl.
- Browser
- Download file 15 kB
-
https://huggingface.co/spaces/Rsnarsna/auto/resolve/main/lambdas/codegen/emitters_core.py
- Command line
-
hf download hf://spaces/Rsnarsna/auto/lambdas/codegen/emitters_core.py
-
curl -L -o emitters_core.py https://huggingface.co/spaces/Rsnarsna/auto/resolve/main/lambdas/codegen/emitters_core.py
15 kB
| """ | |
| ALLI Codegen Subpackage: Core, Essentials, Math, Operator & I/O Node Emitters. | |
| """ | |
| from typing import Optional, Tuple | |
| from language_core.codegen_contracts import format_literal, sanitize_identifier | |
| from language_core.input_transforms import parse_safe_literal_or_json | |
| from lambdas.codegen.context import NodeCodegenCtx | |
| from lambdas.codegen.wave1_core_emitters import ( | |
| SAFE_BINARY_OPS, SAFE_COMPARE_OPS, SAFE_HTTP_METHODS, SAFE_LOGICAL_OPS, | |
| SAFE_ROUNDING_MODES, emit_safe_constant_node, emit_safe_type_cast, | |
| emit_safe_variable_node, validate_safe_op, | |
| ) | |
| def emit_category_node(nctx: NodeCodegenCtx) -> Tuple[bool, Optional[str]]: | |
| raw_type, node_id, safe_id, params, cg = nctx.raw_type, nctx.node_id, nctx.safe_id, nctx.params, nctx.cg | |
| lines, ovm = cg.code_body_lines, cg.output_var_map | |
| if raw_type == "cat_essentials": | |
| nv = f"essentials_{safe_id}" | |
| in_val = nctx.resolve_input("in", nctx.resolve_input("message", format_literal(params.get("message", "Hello, World!")))) | |
| lines.extend([f" {nv} = {in_val}", f" print({nv})"]) | |
| ovm.update({f"{node_id}:out": nv, f"{node_id}:result": nv, node_id: nv}) | |
| return True, nv | |
| if raw_type == "cat_variables": | |
| vn = sanitize_identifier(str(params.get("var_name") or "my_var"), "my_var") | |
| lines.append(f" {vn} = {nctx.resolve_input('in', format_literal(params.get('value', 10)))}") | |
| for k in ("out", "out_val", "val", "value", "result"): | |
| ovm[f"{node_id}:{k}"] = vn | |
| ovm[node_id] = vn | |
| return True, vn | |
| if raw_type == "cat_data_types": | |
| nv = f"collection_{safe_id}" | |
| lines.append(f" {nv} = {str(params.get('default_value') or '[1, 2, 3]')}") | |
| ovm.update({f"{node_id}:out": nv, f"{node_id}:collection": nv, f"{node_id}:result": nv, node_id: nv}) | |
| return True, nv | |
| if raw_type == "cat_operators": | |
| nv = f"calc_{safe_id}" | |
| va = nctx.resolve_input("a", format_literal(params.get("a", 5))) | |
| vb = nctx.resolve_input("b", format_literal(params.get("b", 3))) | |
| lines.append(f" {nv} = {va} {str(params.get('operator', '+'))} {vb}") | |
| ovm.update({f"{node_id}:out": nv, f"{node_id}:result": nv, node_id: nv}) | |
| return True, nv | |
| if raw_type == "cat_math": | |
| cg.discovered_modules.add("math") | |
| nv = f"math_{safe_id}" | |
| vx = nctx.resolve_input("x", format_literal(params.get("x", 49.0))) | |
| lines.append(f" {nv} = math.{params.get('func', 'sqrt')}({vx})") | |
| ovm.update({f"{node_id}:out": nv, f"{node_id}:result": nv, node_id: nv}) | |
| return True, nv | |
| if raw_type == "cat_control_flow": | |
| nv = f"branch_{safe_id}" | |
| lines.append(f" {nv} = bool({nctx.resolve_input('condition', format_literal(params.get('condition', True)))})") | |
| ovm.update({f"{node_id}:out": nv, f"{node_id}:then": nv, f"{node_id}:else": f"(not {nv})", f"{node_id}:result": nv, node_id: nv}) | |
| return True, nv | |
| if raw_type == "cat_functions": | |
| fn = sanitize_identifier(str(params.get("func_name") or "make_toy"), "make_toy") | |
| nv = f"res_{fn}_{safe_id}" | |
| lines.extend([f" def {fn}(args):", " return args", f" {nv} = {fn}({nctx.resolve_input('args', '\"toy_part\"')})"]) | |
| ovm.update({f"{node_id}:out": nv, f"{node_id}:result": nv, node_id: nv}) | |
| return True, nv | |
| if raw_type == "cat_strings_collections": | |
| nv = f"text_{safe_id}" | |
| txt = nctx.resolve_input("text", format_literal(params.get("text", "Hello World"))) | |
| op = params.get("operation", "upper") | |
| lines.append(f" {nv} = len({txt})" if op == "len" else f" {nv} = str({txt}).{op}()") | |
| ovm.update({f"{node_id}:out": nv, f"{node_id}:result": nv, node_id: nv}) | |
| return True, nv | |
| if raw_type == "cat_oop": | |
| cn = sanitize_identifier(str(params.get("class_name") or "House"), "House").capitalize() | |
| nv = f"house_{safe_id}" | |
| lines.extend([f" class {cn}:", " def __init__(self):", " self.doors = 2", " self.windows = 4", f" {nv} = {cn}()"]) | |
| ovm.update({f"{node_id}:out": nv, f"{node_id}:instance": nv, f"{node_id}:result": nv, node_id: nv}) | |
| return True, nv | |
| if raw_type == "cat_files": | |
| nv = f"file_data_{safe_id}" | |
| lines.append(f" {nv} = f'Content of {{{format_literal(params.get('file_path', 'data.txt'))}}}'") | |
| ovm.update({f"{node_id}:out": nv, f"{node_id}:content": nv, f"{node_id}:result": nv, node_id: nv}) | |
| return True, nv | |
| if raw_type == "cat_modules": | |
| mod = str(params.get("module_name") or "math") | |
| cg.discovered_modules.add(mod) | |
| nv = f"tool_{safe_id}" | |
| lines.append(f" {nv} = {mod}") | |
| ovm.update({f"{node_id}:out": nv, f"{node_id}:module": nv, f"{node_id}:result": nv, node_id: nv}) | |
| return True, nv | |
| return False, None | |
| def emit_essentials_node(nctx: NodeCodegenCtx) -> Tuple[bool, Optional[str]]: | |
| raw_type, node_id, safe_id, params, cg = nctx.raw_type, nctx.node_id, nctx.safe_id, nctx.params, nctx.cg | |
| lines, ovm = cg.code_body_lines, cg.output_var_map | |
| if raw_type in ("workflow.start", "start"): | |
| nv = f"start_{safe_id}" | |
| lines.append(f" {nv} = True") | |
| ovm.update({f"{node_id}:trigger": nv, node_id: nv}) | |
| return True, nv | |
| if raw_type in ("trigger.schedule", "schedule"): | |
| cg.discovered_modules.add("datetime") | |
| nv, ts = f"trigger_{safe_id}", f"ts_{safe_id}" | |
| lines.extend([f" {ts} = datetime.datetime.now(datetime.timezone.utc).isoformat()", f" {nv} = True"]) | |
| ovm.update({f"{node_id}:trigger": nv, f"{node_id}:timestamp": ts, node_id: nv}) | |
| return True, nv | |
| if raw_type in ("trigger.webhook", "webhook"): | |
| nv, pv, hv = f"trigger_{safe_id}", f"payload_{safe_id}", f"headers_{safe_id}" | |
| lines.extend([f" {pv} = {{}}", f" {hv} = {{}}", f" {nv} = True"]) | |
| ovm.update({f"{node_id}:trigger": nv, f"{node_id}:payload": pv, f"{node_id}:headers": hv, node_id: nv}) | |
| return True, nv | |
| if raw_type in ("api.http_request", "http_request", "http"): | |
| cg.discovered_modules.add("requests") | |
| cg.discovered_requirements.add("requests") | |
| method = validate_safe_op(str(params.get("method", "GET")).upper(), SAFE_HTTP_METHODS, "GET", nctx, "http_method") | |
| url_expr = nctx.resolve_input("url", format_literal(params.get("url", "https://api.example.com/data"))) | |
| payload_expr = nctx.resolve_input("payload", "None") | |
| raw_hdr_p = params.get("headers") | |
| hdr_fallback = "None" | |
| if raw_hdr_p is not None and raw_hdr_p != "": | |
| ok_hp, parsed_hp = parse_safe_literal_or_json(raw_hdr_p) if isinstance(raw_hdr_p, str) else (isinstance(raw_hdr_p, dict), raw_hdr_p) | |
| hdr_fallback = repr(parsed_hp) if ok_hp and isinstance(parsed_hp, dict) else format_literal(raw_hdr_p) | |
| headers_expr = nctx.resolve_input("headers", hdr_fallback) | |
| if headers_expr != "None" and not headers_expr.strip().startswith("{"): | |
| cg.discovered_modules.add("ast") | |
| headers_expr = f"(ast.literal_eval({headers_expr}) if isinstance({headers_expr}, str) else {headers_expr})" | |
| try: | |
| timeout_val = max(1, min(int(params.get("timeout", 5)), 60)) | |
| except (ValueError, TypeError): | |
| timeout_val = 5 | |
| nv, sv, hr = f"resp_{safe_id}", f"status_{safe_id}", f"resp_headers_{safe_id}" | |
| lines.extend([ | |
| f" {nv} = requests.request('{method}', {url_expr}, json={payload_expr}, headers={headers_expr}, timeout={timeout_val})", | |
| f" {sv} = {nv}.status_code", | |
| f" {hr} = dict({nv}.headers)", | |
| ]) | |
| ovm.update({f"{node_id}:response": nv, f"{node_id}:text": f"{nv}.text", f"{node_id}:data": f"{nv}.json()", f"{node_id}:result": f"{nv}.json()", f"{node_id}:out": f"{nv}.json()", f"{node_id}:status_code": sv, f"{node_id}:headers": hr, f"{node_id}:then": "True", node_id: nv}) | |
| return True, nv | |
| return False, None | |
| def emit_values_math_io_node(nctx: NodeCodegenCtx) -> Tuple[bool, Optional[str]]: | |
| raw_type, node_id, safe_id, params, cg = nctx.raw_type, nctx.node_id, nctx.safe_id, nctx.params, nctx.cg | |
| lines, ovm = cg.code_body_lines, cg.output_var_map | |
| if raw_type == "alli.primitive.datetime": | |
| from lambdas.codegen.emitters_libraries import emit_python_library_preset_node | |
| return emit_python_library_preset_node(nctx) | |
| if raw_type in ("constant.int", "constant.float", "constant.str", "constant.bool", "core.constant", "input", "primitive.input") or raw_type.startswith(("constant.", "primitive.constant")) or raw_type in ("alli.primitive.constant", "alli.primitive.constant.list"): | |
| return emit_safe_constant_node(nctx) | |
| if raw_type in ("core.variable", "variable") or "variable" in raw_type: | |
| return emit_safe_variable_node(nctx) | |
| if raw_type in ("math.sqrt", "sqrt") or "sqrt" in raw_type: | |
| cg.discovered_modules.add("math") | |
| x_expr = nctx.resolve_input("x", nctx.resolve_input("val", nctx.resolve_input("in", params.get("x", 49.0)))) | |
| nv = f"sqrt_{safe_id}" | |
| rounding = validate_safe_op(params.get("rounding", "none"), SAFE_ROUNDING_MODES, "none", nctx, "rounding") | |
| if rounding == "round": | |
| lines.append(f" {nv} = round(math.sqrt({x_expr}), {int(params.get('precision', 2))})") | |
| elif rounding in ("floor", "ceil"): | |
| lines.append(f" {nv} = math.{rounding}(math.sqrt({x_expr}))") | |
| else: | |
| lines.append(f" {nv} = math.sqrt({x_expr})") | |
| return True, nv | |
| if raw_type in ("core.binary_op", "binary_op") or "binary" in raw_type or raw_type.startswith(("math.add", "math.sub", "math.multiply", "math.divide", "math.pow")): | |
| a_expr = nctx.resolve_input("a", nctx.resolve_input("x", params.get("a", params.get("x", 0)))) | |
| b_expr = nctx.resolve_input("b", nctx.resolve_input("y", params.get("b", params.get("y", 0)))) | |
| nv = f"res_{safe_id}" | |
| if "pow" in raw_type or raw_type.startswith("math.pow"): | |
| cg.discovered_modules.add("math") | |
| lines.append(f" {nv} = math.pow({a_expr}, {b_expr})") | |
| else: | |
| raw_op = "+" if "add" in raw_type else ("-" if "sub" in raw_type else ("*" if "multiply" in raw_type else ("/" if "divide" in raw_type else params.get("operator", "+")))) | |
| op = validate_safe_op(raw_op, SAFE_BINARY_OPS, "+", nctx, "binary") | |
| if op in ("/", "//", "%") and b_expr in ("0", "0.0"): | |
| cg.diagnostics.append({"code": "MATH-E001", "severity": "error", "message": f"Division by zero detected in node '{nctx.label}' ({node_id})", "node_id": node_id}) | |
| lines.append(f" {nv} = {a_expr} {op} {b_expr}") | |
| return True, nv | |
| if raw_type in ("core.compare", "compare") or "compare" in raw_type: | |
| nv = f"cmp_{safe_id}" | |
| op = validate_safe_op(params.get("operator", "=="), SAFE_COMPARE_OPS, "==", nctx, "compare") | |
| lines.append(f" {nv} = ({nctx.resolve_input('a', params.get('a', 0))} {op} {nctx.resolve_input('b', params.get('b', 0))})") | |
| return True, nv | |
| if raw_type in ("core.logical_op", "logical_op") or "logical" in raw_type: | |
| op = validate_safe_op(str(params.get("operator", "and")).lower(), SAFE_LOGICAL_OPS, "and", nctx, "logical") | |
| nv = f"logic_{safe_id}" | |
| a_expr = nctx.resolve_input("a", params.get("a", True)) | |
| lines.append(f" {nv} = (not {a_expr})" if op == "not" else f" {nv} = ({a_expr} {op} {nctx.resolve_input('b', params.get('b', True))})") | |
| return True, nv | |
| if raw_type in ("core.type_cast", "type_cast", "custom.type_cast") or "type_cast" in raw_type: | |
| return emit_safe_type_cast(nctx) | |
| if raw_type in ("io.print", "print") or "terminal" in raw_type or "output" in raw_type or "display" in raw_type: | |
| val_expr = nctx.resolve_input(["value", "val", "in", "x"], params.get("value", "")) | |
| prefix = params.get("prefix", "") | |
| if prefix and not str(prefix).endswith(" "): | |
| prefix = f"{prefix} " | |
| if prefix: | |
| p_str = str(prefix) | |
| lines.append( | |
| f" print({format_literal(p_str)} + str({val_expr}))" | |
| if any(ch in p_str for ch in '{}"\'\\\r\n\0') | |
| else f' print(f"{p_str}{{{val_expr}}}")' | |
| ) | |
| else: | |
| lines.append(f" print({val_expr})") | |
| ovm.update({f"{node_id}:out": val_expr, f"{node_id}:then": "True", node_id: val_expr}) | |
| return True, val_expr | |
| if raw_type in ("io.input", "input"): | |
| cg.discovered_modules.add("sys") | |
| default_val = params.get("default_value") if params.get("default_value") is not None else params.get("literal_value") | |
| prompt = params.get("prompt", "") | |
| user_var = params.get("var_name") or params.get("alias") | |
| if user_var: nv = sanitize_identifier(user_var, "user_input") | |
| elif nctx.clean_lbl and not nctx.clean_lbl[0].isdigit() and len(nctx.clean_lbl) <= 24: nv = nctx.clean_lbl if cg.step_counter == 1 else f"{nctx.clean_lbl}_{cg.step_counter}" | |
| else: nv = "user_input" if cg.step_counter == 1 else f"user_input_{cg.step_counter}" | |
| itype = str(params.get("input_type") or "").lower() | |
| if default_val is not None and not prompt: | |
| dtype = itype or ("float" if isinstance(default_val, float) else "any") | |
| lines.append(f" {nv} = {format_literal(default_val, dtype)}") | |
| else: | |
| fb_lit = format_literal(default_val if default_val is not None else "", itype if (default_val is not None and itype in ("int", "float", "bool")) else "str") | |
| prompt_lit = format_literal(str(prompt)) | |
| lines.extend([f" try:", f" {nv} = input({prompt_lit}) if sys.stdin.isatty() else {fb_lit}", f" except (EOFError, OSError):", f" {nv} = {fb_lit}"]) | |
| if itype in ("int", "float"): | |
| lines.append(f" {nv} = {itype}({nv})") | |
| ovm.update({f"{node_id}:value": nv, f"{node_id}:out": nv, f"{node_id}:output": nv, f"{node_id}:then": "True", node_id: nv}) | |
| return True, nv | |
| if raw_type in ("math.abs", "math.round", "math.floor", "math.ceil", "math.min", "math.max"): | |
| fn, nv = raw_type.split(".", 1)[1], f"{raw_type.split('.', 1)[1]}_{safe_id}" | |
| x_e = nctx.resolve_input("x", params.get("x", 0.0)) | |
| if fn in ("floor", "ceil"): cg.discovered_modules.add("math"); lines.append(f" {nv} = math.{fn}({x_e})") | |
| elif fn == "abs": lines.append(f" {nv} = abs({x_e})") | |
| elif fn == "round": lines.append(f" {nv} = round({x_e}, {int(params.get('precision', 0))})") | |
| else: lines.append(f" {nv} = {fn}({nctx.resolve_input('a', params.get('a', 0.0))}, {nctx.resolve_input('b', params.get('b', 0.0))})") | |
| return True, nv | |
| return False, None | |