@rasteaks/grandma2-toolkit 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,237 @@
1
+ """Audited operations shared by the CLI and MCP; scene writes never imply visual acceptance."""
2
+
3
+ from contextlib import contextmanager, ExitStack
4
+ from datetime import datetime, timezone
5
+ import gzip
6
+ import hashlib
7
+ import json
8
+ import math
9
+ from pathlib import Path
10
+ import re
11
+ import threading
12
+ import time
13
+ import uuid
14
+ import xml.etree.ElementTree as ET
15
+
16
+ from .config import Config
17
+ from .transport import MA2Client, MA2Error, validate_command
18
+
19
+ POOL = r"(?:Page|Executor|Sequence|Effect|Preset|Camera|Group|View|ViewButton|Layout|Fixture|Channel|Root|UserProfile|MAtricks|Macro)"
20
+ ADDRESS = r"[0-9]+(?:\.[0-9]+)*"
21
+ OBJECT = re.compile(rf"{POOL}(?: {ADDRESS}(?: Thru {ADDRESS})?)?", re.I)
22
+ # List supports child enumeration, Cue ranges and a screen qualifier. Export takes
23
+ # an object followed by a filename, so its argument grammar stays separate.
24
+ LIST_RANGE = rf"{ADDRESS}(?:\.\*| Thru(?: {ADDRESS})?)?"
25
+ LIST_OBJECT = re.compile(
26
+ rf"(?:(?:{POOL}|Screen|Layer|FixtureType)(?: {LIST_RANGE})?"
27
+ rf"|Sequence [0-9]+ Cue(?: {LIST_RANGE})?"
28
+ rf"|ViewButton {LIST_RANGE} /screen=[0-9]+"
29
+ r"|LiveSetup\.(?:FixtureTypes|Layers)|NetworkInfo)", re.I)
30
+ EXPORT_DIRS = {"effect": "effects", "matricks": "matricks", "macro": "macros"}
31
+ NS = {"m": "http://schemas.malighting.de/grandma2/xml/MA"}
32
+
33
+
34
+ def object_path(value: str) -> str:
35
+ """A narrow object grammar prevents query/export arguments becoming command chains."""
36
+ if not OBJECT.fullmatch(value):
37
+ raise ValueError("Use an object path such as 'Executor 3.1 Thru 3.8' or 'Root 10.6.3.76'")
38
+ return value
39
+
40
+
41
+ def xml_fingerprint(data: bytes) -> str:
42
+ """Ignore export timestamps and indentation; keep every object attribute and child."""
43
+ root = ET.fromstring(data)
44
+ for info in root.findall("m:Info", NS):
45
+ root.remove(info)
46
+ for elem in root.iter():
47
+ if elem.text is not None and not elem.text.strip():
48
+ elem.text = None
49
+ elem.tail = None
50
+ return hashlib.sha256(ET.tostring(root)).hexdigest()
51
+
52
+
53
+ class Toolkit:
54
+ """Serialize in-process commands; use a fresh verified connection for every operation."""
55
+
56
+ def __init__(self, config: Config | None = None, client_factory=MA2Client):
57
+ self.config = config or Config.from_env()
58
+ self.client_factory = client_factory
59
+ self.lock = threading.RLock()
60
+
61
+ def _redact(self, value):
62
+ text = json.dumps(value, ensure_ascii=False, default=str)
63
+ if self.config.password:
64
+ text = text.replace(self.config.password, "[redacted]")
65
+ return json.loads(text)
66
+
67
+ @contextmanager
68
+ def operation(self, action: str, target: str, details=None):
69
+ """Audit both failure and success, including partially executed batches."""
70
+ with self.lock:
71
+ folder = self.config.output_dir / (datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ_") + uuid.uuid4().hex[:10])
72
+ folder.mkdir(parents=True, exist_ok=False)
73
+ record = {"action": action, "target": target, "details": details, "commands": [], "ok": False}
74
+ try:
75
+ yield folder, record
76
+ record["ok"] = True
77
+ except Exception as exc:
78
+ record["error"] = self._redact(str(exc))
79
+ raise
80
+ finally:
81
+ (folder / "audit.json").write_text(json.dumps(self._redact(record), ensure_ascii=False, indent=2), encoding="utf-8")
82
+
83
+ def _send(self, client, record, command, allow_missing=False):
84
+ item = {"command": command, "outcome": "unknown"}
85
+ record["commands"].append(item)
86
+ reply = client.command(command, allow_missing=allow_missing)
87
+ item.update(reply=reply, outcome="acknowledged")
88
+ return reply
89
+
90
+ def _guard(self, client, expected_show: str):
91
+ if not self.config.allow_write:
92
+ raise PermissionError("Writes disabled; configure MA2_ALLOW_WRITE=1 for authorized operations")
93
+ if not expected_show or client.value("SHOWFILE") != expected_show:
94
+ raise MA2Error("Active Show does not match expected_show; no mutation sent")
95
+
96
+ def status(self, target="onpc"):
97
+ with self.operation("status", target) as (folder, record):
98
+ with self.client_factory(self.config, target) as client:
99
+ result = {"target": target, "host": self.config.host, "port": client.port,
100
+ "runtime": client.runtime, "show": client.value("SHOWFILE"),
101
+ "network_status": client.value("STATUS")}
102
+ record["result"] = result
103
+ return {**result, "audit_dir": str(folder)}
104
+
105
+ def connections(self):
106
+ """Keep both sockets open together and compare shows without changing either session."""
107
+ with self.operation("connections", "both") as (folder, record), ExitStack() as stack:
108
+ endpoints = {}
109
+ for target in ("onpc", "ma3d"):
110
+ try:
111
+ client = stack.enter_context(self.client_factory(self.config, target))
112
+ endpoints[target] = {"connected": True, "port": client.port, "runtime": client.runtime,
113
+ "show": client.value("SHOWFILE"), "network_status": client.value("STATUS")}
114
+ except (MA2Error, OSError, ValueError) as exc:
115
+ endpoints[target] = {"connected": False, "error": self._redact(str(exc))}
116
+ matched = all(e["connected"] for e in endpoints.values()) and endpoints["onpc"]["show"] == endpoints["ma3d"]["show"]
117
+ result = {"endpoints": endpoints, "same_show_name": matched,
118
+ "note": "Matching names alone do not prove both applications joined the same session."}
119
+ record["result"] = result
120
+ return {**result, "audit_dir": str(folder)}
121
+
122
+ def list_objects(self, object: str, target="onpc"):
123
+ if not LIST_OBJECT.fullmatch(object):
124
+ raise ValueError("Use a List object such as 'Root 10.4.*' or 'Sequence 121 Cue 1 Thru 5'")
125
+ command = "List " + object
126
+ with self.operation("list", target, object) as (folder, record), self.client_factory(self.config, target) as client:
127
+ return {"reply": self._send(client, record, command, True), "audit_dir": str(folder)}
128
+
129
+ def execute(self, commands: list[str], expected_show: str, target="onpc"):
130
+ """Explicit general-purpose write channel. A batch is sequential, not transactional."""
131
+ if not 1 <= len(commands) <= 100:
132
+ raise ValueError("Send between 1 and 100 commands")
133
+ for cmd in commands:
134
+ validate_command(cmd)
135
+ if re.search(r"\b(?:Login|Logout)\b", cmd, re.I):
136
+ raise ValueError("Authentication commands are not accepted; use environment configuration")
137
+ with self.operation("execute", target, commands) as (folder, record), self.client_factory(self.config, target) as client:
138
+ replies = []
139
+ for cmd in commands:
140
+ # Another client can change the Show between commands; recheck each time.
141
+ self._guard(client, expected_show)
142
+ replies.append(self._send(client, record, cmd))
143
+ return {"replies": replies, "audit_dir": str(folder), "visual_acceptance": False}
144
+
145
+ def _local_runtime(self, client) -> Path:
146
+ # Native export/save files exist on the endpoint machine, not on a remote caller.
147
+ if self.config.host not in ("127.0.0.1", "localhost", "::1"):
148
+ raise ValueError("File export/backup requires a local endpoint; remote raw commands remain available")
149
+ runtime = Path(client.runtime)
150
+ if not runtime.is_absolute() or not runtime.is_dir():
151
+ raise ValueError("Verified runtime directory is not locally accessible")
152
+ return runtime
153
+
154
+ def export_object(self, object: str, target="onpc"):
155
+ object_path(object)
156
+ with self.operation("export", target, object) as (folder, record), self.client_factory(self.config, target) as client:
157
+ runtime = self._local_runtime(client)
158
+ name = "g2tk_" + uuid.uuid4().hex
159
+ directory = EXPORT_DIRS.get(object.split()[0].lower(), "importexport")
160
+ source = runtime / directory / (name + ".xml")
161
+ self._send(client, record, f"Export {object} {name}")
162
+ deadline = time.monotonic() + self.config.timeout
163
+ while time.monotonic() < deadline:
164
+ try:
165
+ data = source.read_bytes()
166
+ digest = xml_fingerprint(data)
167
+ break
168
+ except (OSError, ET.ParseError):
169
+ time.sleep(.1)
170
+ else:
171
+ raise MA2Error(f"Export did not finish; check native {directory} folder")
172
+ output = folder / "object.xml"
173
+ output.write_bytes(data)
174
+ result = {"file": str(output), "native_file": str(source), "fingerprint": digest, "audit_dir": str(folder)}
175
+ record["result"] = result
176
+ return result
177
+
178
+ def backup_show(self, expected_show: str):
179
+ """Save onPC and copy only the new, stable, complete gzip; never reuse a previous save."""
180
+ if not re.fullmatch(r"[\w .-]+", expected_show) or expected_show in (".", ".."):
181
+ raise ValueError("Show name cannot contain path or console syntax characters")
182
+ with self.operation("backup", "onpc", expected_show) as (folder, record), self.client_factory(self.config, "onpc") as client:
183
+ self._guard(client, expected_show)
184
+ source = self._local_runtime(client) / "shows" / (expected_show + ".show.gz")
185
+ before = source.stat().st_mtime_ns if source.exists() else None
186
+ self._send(client, record, "SaveShow /noconfirm")
187
+ deadline = time.monotonic() + max(30, self.config.timeout)
188
+ while time.monotonic() < deadline:
189
+ try:
190
+ stamp = (source.stat().st_mtime_ns, source.stat().st_size)
191
+ if stamp[0] != before:
192
+ data = source.read_bytes()
193
+ gzip.decompress(data)
194
+ time.sleep(.5)
195
+ if stamp == (source.stat().st_mtime_ns, source.stat().st_size):
196
+ break
197
+ except (OSError, EOFError):
198
+ pass
199
+ time.sleep(.1)
200
+ else:
201
+ raise MA2Error("New SaveShow file not confirmed; no backup copied")
202
+ output = folder / source.name
203
+ output.write_bytes(data)
204
+ digest = hashlib.sha256(data).hexdigest()
205
+ result = {"file": str(output), "sha256": digest, "audit_dir": str(folder)}
206
+ record["result"] = result
207
+ return result
208
+
209
+ def set_transform(self, object: str, expected_show: str, values: dict[str, float], target="ma3d"):
210
+ """Set a verified Camera or scene body address, never fixture Pan/Tilt programmer values."""
211
+ if not re.fullmatch(r"(?:Camera \d+|Root \d+(?:\.\d+){2,})", object, re.I):
212
+ raise ValueError("Transform requires one Camera or explicit scene Root address")
213
+ allowed = {"x": "X", "y": "Y", "z": "Z", "rx": "Rot.X", "ry": "Rot.Y", "rz": "Rot.Z", "fov": "FOV"}
214
+ if not values or not set(values) <= allowed.keys():
215
+ raise ValueError("Transform accepts x/y/z/rx/ry/rz/fov")
216
+ if any(not math.isfinite(v) for v in values.values()):
217
+ raise ValueError("Transform values must be finite")
218
+ if "fov" in values and (not object.lower().startswith("camera ") or not 0 < values["fov"] < math.pi):
219
+ raise ValueError("Camera FOV must be radians between 0 and pi")
220
+ command = "Assign " + object + " " + " ".join(f"/{allowed[k]}={v:g}" for k, v in values.items())
221
+ with self.operation("transform", target, {"object": object, "values": values}) as (folder, record), self.client_factory(self.config, target) as client:
222
+ self._guard(client, expected_show)
223
+ before = self._send(client, record, "List " + object)
224
+ self._send(client, record, command)
225
+ after = self._send(client, record, "List " + object)
226
+ return {"before": before, "after": after, "audit_dir": str(folder),
227
+ "note": "Compare requested fields with readback. Raw List text is not an automatic numeric or visual pass.",
228
+ "visual_acceptance": False}
229
+
230
+ def capture_ma3d(self, window_title: str | None = None):
231
+ """Capture only a uniquely identified visible MA3D window; never control it."""
232
+ from .capture import capture_window
233
+ with self.operation("capture", "ma3d") as (folder, record):
234
+ result = capture_window(folder / "ma3d.png", window_title)
235
+ record["result"] = result
236
+ return {**result, "audit_dir": str(folder), "visual_acceptance": False,
237
+ "note": "Inspect this image and confirm camera/lighting state; a screenshot alone does not pass acceptance."}
@@ -0,0 +1,176 @@
1
+ """Bounded Telnet exchanges with runtime identity checks and completion markers."""
2
+
3
+ import re
4
+ import select
5
+ import socket
6
+ import time
7
+ import uuid
8
+
9
+ from .config import Config
10
+
11
+ # Feedback can follow the active destination prompt on the same line.
12
+ FEEDBACK_PREFIX = r"^[ \t]*(?:(?:\[[^\]\n]+\]|EditSetup(?:/[^>\n]+)?)[ \t]*>[ \t]*)?"
13
+
14
+
15
+ class MA2Error(RuntimeError):
16
+ """An operation failed or its result is unknown; mutations must not be retried blindly."""
17
+
18
+
19
+ class TelnetDecoder:
20
+ """Strip fragmented IAC negotiation; refuse options instead of treating them as text."""
21
+
22
+ def __init__(self):
23
+ self.state = "data"
24
+ self.verb = 0
25
+
26
+ def feed(self, data: bytes) -> tuple[bytes, bytes]:
27
+ out, replies = bytearray(), bytearray()
28
+ for b in data:
29
+ if self.state == "data":
30
+ if b == 255:
31
+ self.state = "iac"
32
+ else:
33
+ out.append(b)
34
+ elif self.state == "iac":
35
+ if b == 255:
36
+ out.append(b)
37
+ self.state = "data"
38
+ elif b in (251, 252, 253, 254):
39
+ self.verb, self.state = b, "option"
40
+ elif b == 250:
41
+ self.state = "sub"
42
+ else:
43
+ self.state = "data"
44
+ elif self.state == "option":
45
+ if self.verb in (251, 253):
46
+ replies.extend((255, 254 if self.verb == 251 else 252, b))
47
+ self.state = "data"
48
+ elif self.state == "sub":
49
+ if b == 255:
50
+ self.state = "sub_iac"
51
+ elif self.state == "sub_iac":
52
+ self.state = "data" if b == 240 else "sub"
53
+ return bytes(out), bytes(replies)
54
+
55
+
56
+ def clean(data: bytes) -> str:
57
+ """Decode after collecting bytes so UTF-8 split across TCP packets remains intact."""
58
+ return re.sub(r"\x1b\[[0-9;?]*[A-Za-z]", "", data.decode("utf-8", errors="replace")).replace("\r", "")
59
+
60
+
61
+ def validate_command(command: str) -> None:
62
+ """MA2 3.3 has a short line buffer; larger batches must use separate commands."""
63
+ if not command.strip() or any(ord(c) < 32 for c in command):
64
+ raise ValueError("A command must be one nonempty line without control characters")
65
+ if len(command.encode("utf-8")) > 480:
66
+ raise ValueError("Command exceeds conservative MA2 limit of 480 UTF-8 bytes")
67
+
68
+
69
+ class MA2Client:
70
+ """One operation owns one connection; only connection discovery may try another port."""
71
+
72
+ def __init__(self, config: Config, target: str = "onpc"):
73
+ if target not in ("onpc", "ma3d"):
74
+ raise ValueError("Target must be onpc or ma3d")
75
+ self.config = config
76
+ self.target = target
77
+ self.socket = None
78
+ self.port = None
79
+ self.runtime = ""
80
+ self.decoder = TelnetDecoder()
81
+
82
+ def __enter__(self):
83
+ self.config.validate()
84
+ failures = []
85
+ for port in self.config.ports:
86
+ try:
87
+ self.decoder = TelnetDecoder()
88
+ self.socket = socket.create_connection((self.config.host, port), timeout=2)
89
+ self.socket.settimeout(self.config.timeout)
90
+ self._banner()
91
+ # Login responses are never returned or logged, even on failure.
92
+ reply = self._exchange(f'Login "{self.config.user}" "{self.config.password}"')
93
+ if f"Logged in as User '{self.config.user}'".lower() not in reply.lower():
94
+ raise MA2Error("Login was not acknowledged")
95
+ self.runtime = self.value("PATH")
96
+ normalized = self.runtime.replace("\\", "/").lower()
97
+ identity = "onpc" if "/grandma/gma2_" in normalized else "ma3d" if "ma3d" in normalized else "unknown"
98
+ if identity != self.target:
99
+ raise MA2Error("Endpoint runtime does not match the requested target")
100
+ self.port = port
101
+ return self
102
+ except (OSError, MA2Error) as exc:
103
+ # Report only error classes; echoed Login lines can contain secrets.
104
+ failures.append(f"{port}:{type(exc).__name__}")
105
+ self.close()
106
+ raise MA2Error(f"No authenticated {self.target} endpoint: " + ", ".join(failures))
107
+
108
+ def __exit__(self, *_):
109
+ self.close()
110
+
111
+ def close(self):
112
+ """Close a failed or completed session without replaying any command."""
113
+ if self.socket is not None:
114
+ self.socket.close()
115
+ self.socket = None
116
+
117
+ def _recv(self) -> bytes:
118
+ data = self.socket.recv(65536)
119
+ if not data:
120
+ raise MA2Error("Console disconnected; command outcome may be unknown")
121
+ text, negotiation = self.decoder.feed(data)
122
+ if negotiation:
123
+ self.socket.sendall(negotiation)
124
+ return text
125
+
126
+ def _banner(self):
127
+ deadline = time.monotonic() + .4
128
+ while time.monotonic() < deadline:
129
+ if select.select([self.socket], [], [], .1)[0]:
130
+ self._recv()
131
+
132
+ def _exchange(self, command: str) -> str:
133
+ validate_command(command)
134
+ marker = "G2TK_DONE_" + uuid.uuid4().hex
135
+ barrier = f'Lua "gma.feedback(\'{marker}\')"'
136
+ self.socket.sendall((command + "\r\n" + barrier + "\r\n").encode("utf-8"))
137
+ deadline = time.monotonic() + self.config.timeout
138
+ data = bytearray()
139
+ # Match actual feedback, never the marker inside an echoed Lua command.
140
+ done = re.compile(FEEDBACK_PREFIX + marker + r"[ \t]*$", re.M)
141
+ while time.monotonic() < deadline:
142
+ if select.select([self.socket], [], [], min(.2, max(0, deadline-time.monotonic())))[0]:
143
+ data.extend(self._recv())
144
+ if len(data) > 8 * 1024 * 1024:
145
+ raise MA2Error("Response exceeds 8 MiB; query a smaller range")
146
+ result = clean(data)
147
+ match = done.search(result)
148
+ if match:
149
+ result = result[:match.start()]
150
+ # Strip our barrier echo while retaining the command's original reply.
151
+ result = "\n".join(line for line in result.splitlines() if marker not in line)
152
+ if "Executing :" not in result:
153
+ raise MA2Error("Command acknowledgement missing; outcome unknown")
154
+ return result.strip()
155
+ raise MA2Error("Completion marker timed out; outcome unknown; do not replay writes")
156
+
157
+ def command(self, command: str, allow_missing: bool = False) -> str:
158
+ reply = self._exchange(command)
159
+ # Inspect diagnostics, not echoed commands or names containing 'ERROR'.
160
+ diagnostics = re.sub(r"(?m)^.*Executing :.*$", "", reply)
161
+ if re.search(r"(?im)(?:^|>)\s*(?:Error\s*#|UNKNOWN COMMAND|INVALID COMMAND|ILLEGAL|ACCESS DENIED|NOT POSSIBLE|CANNOT IMPORT|OBJECT DOES NOT EXIST)", diagnostics):
162
+ raise MA2Error("Console rejected command: " + reply)
163
+ if not allow_missing and "NO OBJECTS FOUND" in diagnostics.upper():
164
+ raise MA2Error("Console object not found: " + reply)
165
+ return reply
166
+
167
+ def value(self, name: str) -> str:
168
+ """Only expose fixed read-only Lua expressions; user-supplied Lua uses the write gate."""
169
+ if name not in ("PATH", "SHOWFILE", "VERSION", "HOSTNAME", "STATUS"):
170
+ raise ValueError("Unsupported status field")
171
+ expr = "gma.network.getstatus()" if name == "STATUS" else f"gma.show.getvar('{name}')"
172
+ reply = self.command(f'Lua "gma.feedback(\'G2TK_VALUE=\'..tostring({expr}))"')
173
+ found = re.search(FEEDBACK_PREFIX + r"G2TK_VALUE=([^\n]*)", reply, re.M)
174
+ if not found:
175
+ raise MA2Error("Status feedback missing")
176
+ return found.group(1).strip()