# Copyright (c) 2026 CLSA contributors # SPDX-License-Identifier: MIT """State assembly: s_t = [z_t, b_t, e_t] plus the image and tool-state blocks. The layout is fixed and versioned so that saved tensors stay interpretable and per-modality prediction error is computable by slicing, not by convention. """ from __future__ import annotations import zlib from dataclasses import dataclass import numpy as np from clsa.envs.render import extract_image_features LAYOUT_VERSION = "1.0" TOOL_KEYS = ( "balance", "order_amount", "refunded", "n_emails_sent", "n_files", "has_report", "draft_present", "contract_present", "cart_size", "budget", "marketing_notifications", "account_active", ) TOOL_SCALE = { "balance": 1000.0, "order_amount": 100.0, "n_emails_sent": 5.0, "n_files": 5.0, "cart_size": 3.0, "budget": 1000.0, } RISK_CLASSES = ("read", "reversible", "compensable", "irreversible") @dataclass(frozen=True) class StateLayout: n_z: int n_b: int = 12 n_e: int = 9 n_img: int = 8 n_tool: int = 12 @property def blocks(self) -> dict[str, tuple[int, int]]: out, i = {}, 0 for name, n in ( ("z", self.n_z), ("b", self.n_b), ("e", self.n_e), ("image", self.n_img), ("tool", self.n_tool), ): out[name] = (i, i + n) i += n return out @property def dim(self) -> int: return self.n_z + self.n_b + self.n_e + self.n_img + self.n_tool def slice(self, name: str) -> slice: a, b = self.blocks[name] return slice(a, b) def tool_vector(tool_state: dict) -> np.ndarray: v = np.zeros(len(TOOL_KEYS), dtype=np.float32) for i, k in enumerate(TOOL_KEYS): val = tool_state.get(k, 0.0) if isinstance(val, bool): v[i] = 1.0 if val else 0.0 elif isinstance(val, (int, float)): v[i] = float(val) / TOOL_SCALE.get(k, 1.0) return v def image_vector(image_ref: str | None) -> np.ndarray: v = np.zeros(8, dtype=np.float32) if not image_ref: return v from clsa.util import DATA path = image_ref if image_ref.startswith(str(DATA.parent)) else str(DATA.parent / image_ref) try: f = extract_image_features(path) except Exception: return v v[0] = (f.get("amount") or 0) / 1000.0 v[1] = float(f.get("digit_confidence", 0.0)) v[2] = 1.0 if f.get("stamp_present") else 0.0 toggles = f.get("toggle_states") or [False, False, False] v[3:6] = [1.0 if t else 0.0 for t in toggles[:3]] v[6] = float(f.get("header_rgb", [0, 0, 0])[0]) v[7] = float(f.get("body_rgb", [0, 0, 0])[2]) return v def action_features(action: dict, risk_class: str) -> np.ndarray: """16-dim action embedding: hashed tool identity + risk + numeric args.""" v = np.zeros(16, dtype=np.float32) name = action.get("name", "") bucket = zlib.crc32(name.encode("utf-8")) % 8 v[bucket] = 1.0 if risk_class in RISK_CLASSES: v[8 + RISK_CLASSES.index(risk_class)] = 1.0 args = action.get("args", {}) or {} amount = 0.0 for key in ("amount", "price"): if key in args: try: amount = float(args[key]) except (TypeError, ValueError): amount = 0.0 v[12] = amount / 100.0 v[13] = min(1.0, len(args) / 4.0) v[14] = 1.0 if not args else 0.0 v[15] = 1.0 if name in ("finish", "ask_user") else 0.0 return v def assemble_state( z: np.ndarray, b: np.ndarray, e: np.ndarray, image: np.ndarray, tool: np.ndarray, ) -> np.ndarray: return np.concatenate( [ np.asarray(z, dtype=np.float32).ravel(), np.asarray(b, dtype=np.float32).ravel(), np.asarray(e, dtype=np.float32).ravel(), np.asarray(image, dtype=np.float32).ravel(), np.asarray(tool, dtype=np.float32).ravel(), ] )