diff --git a/surfaces/blender/brokkr_bridge/blender_manifest.toml b/surfaces/blender/brokkr_bridge/blender_manifest.toml new file mode 100644 index 0000000..ec5feed --- /dev/null +++ b/surfaces/blender/brokkr_bridge/blender_manifest.toml @@ -0,0 +1,15 @@ +schema_version = "1.0.0" +id = "brokkr_bridge" +version = "0.2.0" +name = "Brokkr Bridge" +tagline = "Brokkr command intents, receipts and snapshots over CultMesh" +maintainer = "GameCult " +type = "add-on" +blender_version_min = "5.3.0" +platforms = ["windows-x64"] +license = ["SPDX:GPL-3.0-or-later"] +# CultLib's cultnet-py and cultcache-py import msgpack; Blender's Python does not ship it. The wheel is +# the installed msgpack 1.2.2 CPython 3.13 Windows build (Blender 5.3 runs Python 3.13). The C extension +# matters: CultLib at baf4ecf7 fails on msgpack's pure-Python fallback (object_pairs_hook gets a generator). +# Linux and macOS wheels are not bundled yet. +wheels = ["./wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl"] diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 2528bbc..3ed2dcf 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -59,6 +59,9 @@ NO_SCENE_CHANGE_ACTIONS = ("exportGltf", "renderStill") # Anything that writes scene state or changes her mode is refused; renderStill does neither. EDIT_MODE_SAFE_ACTIONS = ("renderStill",) REQUESTED_BY_SHAPE = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$") +# A commandId becomes part of a receipt key, so it is a short string of key-safe characters ('.' is left +# out: it separates the '.denied' suffix). +COMMAND_ID_SHAPE = re.compile(r"^[A-Za-z0-9_-]{1,128}$") NOTE_LIMIT = 200 EVALUATED_POSITION_CAP = 256 @@ -154,11 +157,18 @@ class BrokkrBlenderTarget: commands = snapshot.get(COMMAND_INTENT_SCHEMA, {}) receipts: list[dict[str, Any]] = [] self._receipted.update( - r.get("commandId", "") for r in snapshot.get(COMMAND_RECEIPT_SCHEMA, {}).values()) + r["commandId"] for r in snapshot.get(COMMAND_RECEIPT_SCHEMA, {}).values() + if isinstance(r.get("commandId"), str)) for command_key, command in sorted(commands.items()): - reused = command.get("commandId") in self._receipted + command_id = command.get("commandId") + valid = _valid_command_id(command_id) + reused = valid and command_id in self._receipted receipt = self.run_intent(context, command) + if not valid: + # No safe key exists for this id: the denial is receipted under a fresh key and names the + # queue key, so the intent leaves the queue and its sender can still find the refusal. + receipt["message"] += f" (queue key {command_key})" # Receipts are write-once: a reused id's denial goes under '.denied', never over the # original. The sender learns of it by reading that key (and the drain's returned list). self.publish_receipt(cache_path, cultlib_py_src, receipt, debug_mirror_root, @@ -521,8 +531,8 @@ class BrokkrBlenderTarget: requested_by = command.get("requestedBy") action = command.get("action", "") denial = "" - if not isinstance(command_id, str) or not command_id: - denial = "Intent has no commandId." + if not _valid_command_id(command_id): + denial = "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'." elif command_id in self._receipted: denial = f"commandId {command_id!r} was already receipted; ids are single-use." elif not isinstance(requested_by, str) or not REQUESTED_BY_SHAPE.match(requested_by): @@ -533,7 +543,7 @@ class BrokkrBlenderTarget: denial = (f"Object {self._edit_mode_object()!r} is in Edit Mode: object-level intents are refused " "until she leaves it; nothing was changed.") if denial: - if isinstance(command_id, str) and command_id: + if _valid_command_id(command_id): self._receipted.add(command_id) return self._receipt(command, "denied", denial, "") @@ -1094,7 +1104,7 @@ class BrokkrBlenderTarget: def _receipt(self, command: dict[str, Any], status: str, message: str, object_name: str) -> dict[str, Any]: return { "schema": COMMAND_RECEIPT_SCHEMA, - "commandId": command.get("commandId") or uuid.uuid4().hex, + "commandId": command["commandId"] if _valid_command_id(command.get("commandId")) else uuid.uuid4().hex, "action": command.get("action", ""), "status": status, "message": message, @@ -1222,9 +1232,15 @@ def _load_cultmesh(cultlib_py_src: str) -> tuple[Any, Any]: import cultmesh_py # type: ignore import cultcache_py # type: ignore except ModuleNotFoundError as exc: + own = {name.replace("-", "_") for name in CULTLIB_PY_PACKAGES} + if exc.name in own: + raise RuntimeError( + "Brokkr Blender target requires CultLib's Python packages. Set CultLib Python Source " + "to the CultLib packages directory or install cultcache-py, cultnet-py and cultmesh-py into Blender's Python." + ) from exc raise RuntimeError( - "Brokkr Blender target requires CultLib's Python packages. Set CultLib Python Source " - "to the CultLib packages directory or install cultcache-py, cultnet-py and cultmesh-py into Blender's Python." + f"A CultLib Python package needs the module {exc.name!r}, which Blender's Python does not have. " + "Install the add-on as an extension (it bundles msgpack) or install that module into Blender's Python." ) from exc if not hasattr(cultcache_py, "convert"): raise RuntimeError( @@ -1255,6 +1271,10 @@ def _to_list(value: Any) -> list[float]: return [float(item) for item in value] +def _valid_command_id(value: Any) -> bool: + return isinstance(value, str) and COMMAND_ID_SHAPE.match(value) is not None + + def _vector(value: Any, size: int, fallback: Any) -> tuple[float, ...]: if value is None: return tuple(float(item) for item in fallback) diff --git a/surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl b/surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl new file mode 100644 index 0000000..83a8682 Binary files /dev/null and b/surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl differ diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 3b3a93d..29b1242 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -28,6 +28,27 @@ py -3 -c "import sys; sys.path.insert(0, r'/surfaces/blender/brokkr_brid The command prints the record count and leaves the source unwritten. Records a new daemon already appended (MessagePack) are carried into the new file. +### msgpack for a stock Blender + +CultLib's `cultnet-py` and `cultcache-py` import `msgpack`, and Blender's Python does +not ship it. Install Brokkr as an extension so Blender installs it for you: +`surfaces/blender/brokkr_bridge/blender_manifest.toml` lists the bundled wheel +`wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl`, which Blender unpacks into the extension's own +site-packages when the extension is enabled. Build and install it: + +```text +blender --command extension build --source-dir surfaces/blender/brokkr_bridge --output-dir +blender --command extension install-file --repo user_default --enable /brokkr_bridge-0.2.0.zip +``` + +The bundled wheel is msgpack 1.2.2 for CPython 3.13 on Windows x64 (Blender 5.3's Python), +repacked from the installed package with its Apache-2.0 licence; the extension is therefore +declared `windows-x64`, Blender 5.3 or newer. The C extension matters: CultLib at `baf4ecf7` +fails on msgpack's pure-Python fallback. Linux and macOS wheels are not bundled yet: there, +or in a plain add-on directory install, put `msgpack` into Blender's Python yourself. A +CultLib package missing a module is reported by that module's name, not as a missing +CultLib package. + The default node cache is: ```text diff --git a/surfaces/blender/tests/live/agent_turn_queue.py b/surfaces/blender/tests/live/agent_turn_queue.py index e44669a..18fc00a 100644 --- a/surfaces/blender/tests/live/agent_turn_queue.py +++ b/surfaces/blender/tests/live/agent_turn_queue.py @@ -3,13 +3,17 @@ are drained by the add-on's own 1 s timer as one undo step each, with write-once BROKKR_USER_SCRIPTS= (also BLENDER_USER_SCRIPTS) BROKKR_SCRATCH= - BROKKR_PYLIBS= + BROKKR_ADDON_MODULE= + BROKKR_CULTLIB= + BROKKR_PYLIBS= blender --factory-startup --python agent_turn_queue.py -- Intents are put into the node database as brokkr-ctl does (no debug-mirror files). Writes .result.json, then quits Blender. Undo is read only here, by this driver. """ +import importlib import json import os import sys @@ -23,19 +27,28 @@ if os.environ.get("BROKKR_PYLIBS"): SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() SCRATCH.mkdir(parents=True, exist_ok=True) OUT = sys.argv[sys.argv.index("--") + 1] -R = {"blender": bpy.app.version_string, "checks": [], "receipts": {}} +R = {"blender": bpy.app.version_string, "module": os.environ.get("BROKKR_ADDON_MODULE", "brokkr_bridge"), + "pylibs": bool(os.environ.get("BROKKR_PYLIBS")), "checks": [], "receipts": {}} -bpy.ops.preferences.addon_enable(module="brokkr_bridge") -import brokkr_bridge as addon # noqa: E402 -from brokkr_bridge import blender_target as bt # noqa: E402 +MODULE = os.environ.get("BROKKR_ADDON_MODULE", "brokkr_bridge") +bpy.ops.preferences.addon_enable(module=MODULE) +addon = importlib.import_module(MODULE) +bt = importlib.import_module(MODULE + ".blender_target") -prefs = bpy.context.preferences.addons["brokkr_bridge"].preferences +try: + import msgpack + R["msgpack"] = msgpack.__file__ +except ImportError: + R["msgpack"] = None +prefs = bpy.context.preferences.addons[MODULE].preferences CACHE = str(SCRATCH / "queue.ccmp") prefs.cultmesh_cache_path = CACHE prefs.debug_mirror_root = "" # the debug-mirror door is not used here prefs.output_dir = str(SCRATCH / "out") prefs.import_dir = "" prefs.auto_drain_commands = True +if os.environ.get("BROKKR_CULTLIB"): + prefs.cultlib_py_src = os.environ["BROKKR_CULTLIB"] (SCRATCH / "out").mkdir(exist_ok=True) adapter = addon.target() @@ -73,6 +86,11 @@ def receipt(key): return n.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}).get(f"blender/receipts/{key}") +def all_receipts(): + n, _ = node() + return n.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}) + + def pending(): n, _ = node() return n.database.snapshot().get(bt.COMMAND_INTENT_SCHEMA, {}) @@ -190,11 +208,33 @@ def q5_exit(): check("queue: add-on drain reports no error", adapter.last_auto_drain_error == "", adapter.last_auto_drain_error) +def q6(): + queue("bad-list", action="createObject", objectType="MESH", name="QBadList", requestedBy="nibu/hands") + queue("bad-int", action="createObject", objectType="MESH", name="QBadInt", requestedBy="nibu/hands") + n, docs = node() + for key in ("bad-list", "bad-int"): # overwrite the id with a non-string, as a hand-written put could + doc = dict(n.database.snapshot()[bt.COMMAND_INTENT_SCHEMA][f"blender/commands/{key}"]) + doc["commandId"] = ["x"] if key == "bad-list" else 7 + n.database.put(docs["command_intent"], f"blender/commands/{key}", doc) + queue("zzzzzzzz-good", action="createObject", objectType="MESH", name="QAfterBad", requestedBy="nibu/hands") + + +def q6_check(): + denials = [r for k, r in all_receipts().items() if "queue key blender/commands/bad-" in r.get("message", "")] + R["receipts"]["q6"] = denials + check("queue: a list id and an int id are denied under fresh keys, removed from the queue, drain not wedged", + len(denials) == 2 and all(r["status"] == "denied" and isinstance(r["commandId"], str) for r in denials) + and not pending() and "QBadList" not in names() and "QBadInt" not in names() + and receipt("zzzzzzzz-good")["status"] == "accepted" and "QAfterBad" in names() + and adapter.last_auto_drain_error == "", [adapter.last_auto_drain_error, list(pending())]) + + steps = [ once(q1), until(drained("aaaaaaaa-0001")), once(q1_check), once(q2), until(lambda: receipt("aaaaaaaa-0001.denied")), once(q2_check), once(q3), until(drained("aaaaaaaa-0003")), once(q3_check), once(q4), until(drained("aaaaaaaa-0004", "aaaaaaaa-0005")), once(q4_undo_two), + once(q6), until(drained("zzzzzzzz-good")), once(q6_check), once(q5_edit), until(drained("aaaaaaaa-0006", "aaaaaaaa-0007", "aaaaaaaa-0008")), once(q5_check), once(q5_exit), ] i = 0 diff --git a/surfaces/blender/tests/live/agent_turn_queue.result.json b/surfaces/blender/tests/live/agent_turn_queue.result.json index a040d56..cbd7ce5 100644 --- a/surfaces/blender/tests/live/agent_turn_queue.result.json +++ b/surfaces/blender/tests/live/agent_turn_queue.result.json @@ -1,5 +1,7 @@ { "blender": "5.3.0", + "module": "bl_ext.user_default.brokkr_bridge", + "pylibs": false, "checks": [ { "name": "queue: createObject drained by the add-on timer, accepted, labelled, attributed", @@ -10,7 +12,7 @@ "message": "Blender object created.", "note": "queue test", "objectName": "QCube", - "observedAt": "2026-11-27T18:07:31.682454+00:00", + "observedAt": "2026-11-27T18:33:33.859109+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "accepted", @@ -31,7 +33,7 @@ "message": "Blender object created.", "note": "queue test", "objectName": "QCube", - "observedAt": "2026-11-27T18:07:31.682454+00:00", + "observedAt": "2026-11-27T18:33:33.859109+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "accepted", @@ -47,7 +49,7 @@ "message": "commandId 'aaaaaaaa-0001' was already receipted; ids are single-use.", "note": "", "objectName": "", - "observedAt": "2026-11-27T18:07:33.680885+00:00", + "observedAt": "2026-11-27T18:33:35.854629+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "denied", @@ -63,7 +65,7 @@ "message": "Intent has no requestedBy of the form '/'.", "note": "", "objectName": "", - "observedAt": "2026-11-27T18:07:35.693748+00:00", + "observedAt": "2026-11-27T18:33:37.862020+00:00", "requestedBy": "", "schema": "brokkr.blender.command_receipt.v0", "status": "denied", @@ -89,6 +91,14 @@ ] ] }, + { + "name": "queue: a list id and an int id are denied under fresh keys, removed from the queue, drain not wedged", + "ok": true, + "detail": [ + "", + [] + ] + }, { "name": "queue: in Edit Mode setWorld, exportGltf and an object write are all denied, her mode kept", "ok": true, @@ -111,7 +121,7 @@ "message": "Blender object created.", "note": "queue test", "objectName": "QCube", - "observedAt": "2026-11-27T18:07:31.682454+00:00", + "observedAt": "2026-11-27T18:33:33.859109+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "accepted", @@ -123,7 +133,7 @@ "message": "Blender object created.", "note": "queue test", "objectName": "QCube", - "observedAt": "2026-11-27T18:07:31.682454+00:00", + "observedAt": "2026-11-27T18:33:33.859109+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "accepted", @@ -135,7 +145,7 @@ "message": "commandId 'aaaaaaaa-0001' was already receipted; ids are single-use.", "note": "", "objectName": "", - "observedAt": "2026-11-27T18:07:33.680885+00:00", + "observedAt": "2026-11-27T18:33:35.854629+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "denied", @@ -147,12 +157,38 @@ "message": "Intent has no requestedBy of the form '/'.", "note": "", "objectName": "", - "observedAt": "2026-11-27T18:07:35.693748+00:00", + "observedAt": "2026-11-27T18:33:37.862020+00:00", "requestedBy": "", "schema": "brokkr.blender.command_receipt.v0", "status": "denied", "undoLabel": "" }, + "q6": [ + { + "action": "createObject", + "commandId": "8cdf6298074845bfa652d7136ec176f0", + "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-int)", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T18:33:41.872393+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "denied", + "undoLabel": "" + }, + { + "action": "createObject", + "commandId": "cfdfef85da3a4c0398901d7ffef109af", + "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-list)", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T18:33:41.884756+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "denied", + "undoLabel": "" + } + ], "q5": [ { "action": "setWorld", @@ -160,7 +196,7 @@ "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", "note": "", "objectName": "", - "observedAt": "2026-11-27T18:07:39.773004+00:00", + "observedAt": "2026-11-27T18:33:43.881906+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "denied", @@ -172,7 +208,7 @@ "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", "note": "", "objectName": "", - "observedAt": "2026-11-27T18:07:39.867526+00:00", + "observedAt": "2026-11-27T18:33:43.894611+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "denied", @@ -184,7 +220,7 @@ "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", "note": "", "objectName": "", - "observedAt": "2026-11-27T18:07:39.950112+00:00", + "observedAt": "2026-11-27T18:33:43.916685+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "denied", @@ -192,5 +228,6 @@ } ] }, + "msgpack": "F:\\aeth-wt\\brokkr-live-2.res\\extensions\\.local\\lib\\python3.13\\site-packages\\msgpack\\__init__.py", "ok": true } \ No newline at end of file diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index 4874644..69e83fc 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -2,6 +2,8 @@ from __future__ import annotations import re +import sys +import tempfile import unittest import unittest.mock from pathlib import Path @@ -146,6 +148,36 @@ class AgentTurnTests(unittest.TestCase): self.assertEqual(again["status"], "denied") self.assertEqual(len(self.bpy.created), 1) + # fix batch s2 + def test_no_scene_change_set_is_exactly_export_and_render(self): + self.assertEqual(bt.NO_SCENE_CHANGE_ACTIONS, ("exportGltf", "renderStill")) + receipt = self.run_action(action="setWorld", color=[0.1, 0.2, 0.3]) + self.assertEqual(receipt["status"], "accepted") + self.assertEqual(len(self.bpy.undo.pushes), 1) + + def test_malformed_command_ids_are_denied_without_raising(self): + for bad in (["x"], 7, 1.5, {"a": 1}, "", "a/b", "x.denied", "has space", "a" * 200, None, True): + receipt = self.run_action(action="createObject", objectType="EMPTY", commandId=bad) + self.assertEqual(receipt["status"], "denied", repr(bad)) + self.assertIsInstance(receipt["commandId"], str) + self.assertRegex(receipt["commandId"], bt.COMMAND_ID_SHAPE.pattern, repr(bad)) + self.assertEqual(self.bpy.created, []) + self.assertEqual(self.bpy.undo.pushes, []) + + def test_load_cultmesh_names_the_missing_module(self): + root = Path(tempfile.mkdtemp()) + self.addCleanup(lambda: __import__("shutil").rmtree(root, ignore_errors=True)) + src = root / "cultmesh-py" / "src" / "cultmesh_py" + src.mkdir(parents=True) + (src / "__init__.py").write_text("import brokkr_no_such_dependency_xyz") + saved = {k: sys.modules.pop(k) for k in ("cultmesh_py", "cultcache_py") if k in sys.modules} + saved_path = list(sys.path) + self.addCleanup(lambda: (sys.modules.update(saved), sys.path[:] == saved_path or sys.path.__setitem__(slice(None), saved_path))) + with self.assertRaises(RuntimeError) as caught: + bt._load_cultmesh(str(root)) + self.assertIn("brokkr_no_such_dependency_xyz", str(caught.exception)) + self.assertNotIn("requires CultLib's Python packages", str(caught.exception)) + class FakeNode: """The node database drain_commands reads: intents, receipts, and what it puts and deletes.""" @@ -177,6 +209,21 @@ class DrainTests(unittest.TestCase): def intent(self, cid, **fields): return {"commandId": cid, "requestedBy": "nibu/hands", "action": "createObject", "objectType": "EMPTY", **fields} + def test_malformed_ids_in_the_queue_never_wedge_the_drain(self): + node = FakeNode({ + "blender/commands/a-list": self.intent(["x"]), + "blender/commands/b-int": self.intent(7), + "blender/commands/c-good": self.intent("good-1"), + }) + receipts = self.drain(node) # must not raise + self.assertEqual(sorted(node.deleted), sorted(node.docs[bt.COMMAND_INTENT_SCHEMA])) + self.assertEqual([r["status"] for r in receipts], ["denied", "denied", "accepted"]) + keys = [k for k, _ in node.puts] + self.assertTrue(all(isinstance(k, str) and "[" not in k for k in keys), keys) + self.assertIn("blender/receipts/good-1", keys) + bad = [v for k, v in node.puts if k != "blender/receipts/good-1"] + self.assertTrue(all("blender/commands/" in v["message"] for v in bad), [v["message"] for v in bad]) + def test_drain_seeds_receipted_from_persisted_receipts(self): old = {"blender/receipts/old-1": {"commandId": "old-1", "status": "accepted"}} node = FakeNode({"blender/commands/old-1": self.intent("old-1")}, old)