mjguard 0.1.0__py3-none-any.whl

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.
mjguard/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Guarded MCP control for MuJoCo-modelled robot arms: every motion is checked in the model before it runs."""
2
+
3
+ __version__ = "0.1.0"
mjguard/cli.py ADDED
@@ -0,0 +1,96 @@
1
+ """`mjguard serve CONFIG` runs the MCP server; `mjguard check CONFIG` validates a config and prints the envelope."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import contextlib
7
+ import ipaddress
8
+ import json
9
+ import logging
10
+ import sys
11
+ from collections.abc import Sequence
12
+ from pathlib import Path
13
+ from typing import cast
14
+
15
+ from . import __version__
16
+
17
+
18
+ def _is_loopback(host: str) -> bool:
19
+ if host == "localhost":
20
+ return True
21
+ try:
22
+ return ipaddress.ip_address(host).is_loopback
23
+ except ValueError:
24
+ return False
25
+
26
+
27
+ def main(argv: Sequence[str] | None = None) -> int:
28
+ from .config import presets
29
+
30
+ parser = argparse.ArgumentParser(prog="mjguard", description="Guarded MCP control for MuJoCo-modelled arms.")
31
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
32
+ sub = parser.add_subparsers(dest="command", required=True)
33
+ help_config = f"robot config TOML, or a built-in preset: {', '.join(presets())}"
34
+
35
+ check = sub.add_parser("check", help="load a config, check the rest pose and print the envelope")
36
+ check.add_argument("config", help=help_config)
37
+
38
+ serve = sub.add_parser("serve", help="run the MCP server on a simulated arm")
39
+ serve.add_argument("config", help=help_config)
40
+ serve.add_argument("--trace", type=Path, help="append every call to this JSONL file")
41
+ serve.add_argument("--http", action="store_true", help="serve streamable HTTP instead of stdio")
42
+ serve.add_argument("--host", default="127.0.0.1")
43
+ serve.add_argument("--port", type=int, default=8000)
44
+ serve.add_argument("--allow-remote", action="store_true", help="allow a non-loopback --host (no authentication)")
45
+ serve.add_argument("--realtime", action="store_true", help="run the simulation in real time")
46
+ serve.add_argument("--log-level", default="WARNING", choices=["DEBUG", "INFO", "WARNING", "ERROR"])
47
+ args = parser.parse_args(argv)
48
+
49
+ from .config import ConfigError, load
50
+
51
+ try:
52
+ # Resolving a Menagerie preset may clone it on first use, and the downloader prints to stdout. In stdio mode
53
+ # stdout is the protocol, so all of that goes to stderr.
54
+ with contextlib.redirect_stdout(sys.stderr):
55
+ config = load(args.config)
56
+ if args.command == "check":
57
+ from .guard import Guard
58
+
59
+ guard = Guard(config)
60
+ refusal, clearance = guard.check_configuration(guard.model.home, guard.model.home_gripper)
61
+ report = {
62
+ "ok": refusal is None,
63
+ "rest_pose": "passes" if refusal is None else refusal.to_dict(),
64
+ "rest_clearance_mm": round(clearance, 1),
65
+ "moving_collision_geoms": len(guard.model.moving_geoms),
66
+ "physics": bool(config.actuators),
67
+ "limits": guard.describe(),
68
+ }
69
+ print(json.dumps(report, indent=2, ensure_ascii=False))
70
+ return 0 if refusal is None else 1
71
+ except ConfigError as exc:
72
+ print(f"mjguard: config error: {exc}", file=sys.stderr)
73
+ return 2
74
+
75
+ if not 0 < args.port < 65536:
76
+ parser.error("--port must be between 1 and 65535")
77
+ if args.http and not _is_loopback(args.host) and not args.allow_remote:
78
+ parser.error(f"--host {args.host} is not loopback and the endpoint has no authentication; add --allow-remote")
79
+ logging.basicConfig(
80
+ level=args.log_level, stream=sys.stderr, format="%(asctime)s %(levelname)s %(name)s: %(message)s"
81
+ )
82
+
83
+ from .executor import Executor, SimTransport, Trace
84
+ from .server import LogLevel, create_server
85
+
86
+ executor = Executor(config, SimTransport(config, realtime=args.realtime), Trace(args.trace))
87
+ server = create_server(executor, args.host, args.port, cast(LogLevel, args.log_level))
88
+ try:
89
+ server.run(transport="streamable-http" if args.http else "stdio")
90
+ except KeyboardInterrupt:
91
+ executor.stop()
92
+ return 0
93
+
94
+
95
+ if __name__ == "__main__":
96
+ raise SystemExit(main())
mjguard/config.py ADDED
@@ -0,0 +1,173 @@
1
+ """Robot configuration: which MJCF, which joints, where the tool is, and the safety limits.
2
+
3
+ A config is a small TOML file. Paths are relative to the file. `mjcf` may also be `menagerie:<name>`, which resolves
4
+ to a MuJoCo Menagerie scene through the optional `robot_descriptions` package.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ import tomllib
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+
16
+ class ConfigError(ValueError):
17
+ """The robot config is missing a field or names something the model does not have."""
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Limits:
22
+ """The safety envelope. Frozen at startup; the MCP surface has no way to change it."""
23
+
24
+ min_clearance_mm: float = 20.0
25
+ """Hard limit: the measured arm is halted if a moving collision geom or the tool point gets closer to the floor."""
26
+ planning_margin_mm: float = 10.0
27
+ """Plans keep this much extra clearance above the hard limit, so servo sag and tracking error stay inside it."""
28
+ joint_margin_deg: float = 2.0
29
+ """Planning keeps this far inside each joint's range."""
30
+ max_step_deg: float = 3.0
31
+ """Waypoint spacing: no joint moves more than this between two checked waypoints."""
32
+ max_joint_speed_dps: float = 60.0
33
+ workspace_mm: dict[str, tuple[float, float]] = field(default_factory=dict[str, tuple[float, float]])
34
+ """Optional box for the tool point, e.g. {"x": (-400, 600)}. Missing axes are unbounded."""
35
+ position_tolerance_mm: float = 1.0
36
+ angle_tolerance_deg: float = 1.5
37
+
38
+ @property
39
+ def planning_clearance_mm(self) -> float:
40
+ return self.min_clearance_mm + self.planning_margin_mm
41
+
42
+ def __post_init__(self) -> None:
43
+ for name in ("min_clearance_mm", "max_step_deg", "max_joint_speed_dps", "position_tolerance_mm"):
44
+ value = getattr(self, name)
45
+ if not (math.isfinite(value) and value > 0):
46
+ raise ConfigError(f"limits.{name} must be a positive number, got {value!r}")
47
+ if not (math.isfinite(self.planning_margin_mm) and self.planning_margin_mm >= 0):
48
+ raise ConfigError("limits.planning_margin_mm must be >= 0")
49
+ if not (math.isfinite(self.joint_margin_deg) and self.joint_margin_deg >= 0):
50
+ raise ConfigError("limits.joint_margin_deg must be >= 0")
51
+ for axis, bounds in self.workspace_mm.items():
52
+ if axis not in ("x", "y", "z") or len(bounds) != 2 or not bounds[0] < bounds[1]:
53
+ raise ConfigError(f"limits.workspace_mm.{axis} must be [low, high] with low < high")
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class Gripper:
58
+ joints: tuple[str, ...]
59
+ closed: tuple[float, ...]
60
+ open: tuple[float, ...]
61
+ actuator: str | None = None
62
+ ctrl_closed: float | None = None
63
+ ctrl_open: float | None = None
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class RobotConfig:
68
+ name: str
69
+ mjcf: Path
70
+ joints: tuple[str, ...]
71
+ floor_geom: str
72
+ tcp_site: str | None = None
73
+ tcp_body: str | None = None
74
+ tcp_offset_m: tuple[float, float, float] = (0.0, 0.0, 0.0)
75
+ tool_axis: str = "z"
76
+ """Axis of the tool frame that points out of the tool; `move_to(tool_down=True)` points it at the floor."""
77
+ keyframe: str | None = None
78
+ actuators: tuple[str, ...] = ()
79
+ """Position actuators for the arm joints, in the same order. Empty: the simulator moves joints kinematically."""
80
+ gripper: Gripper | None = None
81
+ limits: Limits = field(default_factory=Limits)
82
+
83
+ def __post_init__(self) -> None:
84
+ if not self.joints:
85
+ raise ConfigError("arm.joints must list at least one joint")
86
+ if (self.tcp_site is None) == (self.tcp_body is None):
87
+ raise ConfigError("set exactly one of arm.tcp_site or arm.tcp_body")
88
+ if self.tool_axis not in ("x", "y", "z", "-x", "-y", "-z"):
89
+ raise ConfigError("arm.tool_axis must be one of x, y, z, -x, -y, -z")
90
+ if self.actuators and len(self.actuators) != len(self.joints):
91
+ raise ConfigError("arm.actuators must have one entry per joint, or be empty")
92
+
93
+
94
+ def _menagerie(name: str) -> Path:
95
+ try:
96
+ import importlib
97
+
98
+ module = importlib.import_module(f"robot_descriptions.{name}_mj_description")
99
+ except ImportError as exc:
100
+ raise ConfigError(f"menagerie:{name} is not a known MuJoCo Menagerie robot: {exc}") from exc
101
+ mjcf = Path(module.MJCF_PATH)
102
+ scene = mjcf.parent / "scene.xml"
103
+ return scene if scene.exists() else mjcf
104
+
105
+
106
+ def resolve_mjcf(value: str, base: Path) -> Path:
107
+ if value.startswith("menagerie:"):
108
+ return _menagerie(value.removeprefix("menagerie:"))
109
+ path = (base / value).resolve()
110
+ if not path.exists():
111
+ raise ConfigError(f"model.mjcf: {path} does not exist")
112
+ return path
113
+
114
+
115
+ def _require(table: dict[str, Any], key: str, where: str) -> Any:
116
+ if key not in table:
117
+ raise ConfigError(f"{where}.{key} is required")
118
+ return table[key]
119
+
120
+
121
+ def from_dict(data: dict[str, Any], base: Path) -> RobotConfig:
122
+ model = data.get("model", {})
123
+ arm = data.get("arm", {})
124
+ raw_limits = dict(data.get("limits", {}))
125
+ if "workspace_mm" in raw_limits:
126
+ raw_limits["workspace_mm"] = {k: (float(v[0]), float(v[1])) for k, v in raw_limits["workspace_mm"].items()}
127
+ try:
128
+ limits = Limits(**raw_limits)
129
+ except TypeError as exc:
130
+ raise ConfigError(f"[limits]: {exc}") from exc
131
+ gripper = None
132
+ if "gripper" in data:
133
+ g = data["gripper"]
134
+ gripper = Gripper(
135
+ joints=tuple(_require(g, "joints", "gripper")),
136
+ closed=tuple(float(v) for v in _require(g, "closed", "gripper")),
137
+ open=tuple(float(v) for v in _require(g, "open", "gripper")),
138
+ actuator=g.get("actuator"),
139
+ ctrl_closed=g.get("ctrl_closed"),
140
+ ctrl_open=g.get("ctrl_open"),
141
+ )
142
+ if not (len(gripper.joints) == len(gripper.closed) == len(gripper.open)):
143
+ raise ConfigError("gripper.joints, gripper.closed and gripper.open must have the same length")
144
+ return RobotConfig(
145
+ name=str(data.get("name", "robot")),
146
+ mjcf=resolve_mjcf(str(_require(model, "mjcf", "model")), base),
147
+ floor_geom=str(_require(model, "floor_geom", "model")),
148
+ keyframe=model.get("keyframe"),
149
+ joints=tuple(_require(arm, "joints", "arm")),
150
+ tcp_site=arm.get("tcp_site"),
151
+ tcp_body=arm.get("tcp_body"),
152
+ tcp_offset_m=tuple(float(v) for v in arm.get("tcp_offset_m", (0.0, 0.0, 0.0))), # type: ignore[arg-type]
153
+ tool_axis=str(arm.get("tool_axis", "z")),
154
+ actuators=tuple(arm.get("actuators", ())),
155
+ gripper=gripper,
156
+ limits=limits,
157
+ )
158
+
159
+
160
+ def load(path: str | Path) -> RobotConfig:
161
+ path = Path(path)
162
+ if not path.exists():
163
+ preset = Path(__file__).parent / "presets" / f"{path.name.removesuffix('.toml')}.toml"
164
+ if preset.exists():
165
+ path = preset
166
+ else:
167
+ raise ConfigError(f"{path} does not exist and is not a built-in preset ({', '.join(presets())})")
168
+ with path.open("rb") as f:
169
+ return from_dict(tomllib.load(f), path.parent)
170
+
171
+
172
+ def presets() -> list[str]:
173
+ return sorted(p.stem for p in (Path(__file__).parent / "presets").glob("*.toml"))
mjguard/executor.py ADDED
@@ -0,0 +1,336 @@
1
+ """The only path from a request to a transport: plan, check every waypoint, run, and monitor what actually ran."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ import math
8
+ import threading
9
+ import time
10
+ from collections import deque
11
+ from collections.abc import Callable, Sequence
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+ from typing import Any, Protocol
15
+
16
+ import mujoco as _mujoco
17
+ import numpy as np
18
+
19
+ from .config import RobotConfig
20
+ from .guard import Guard, Plan, Refusal
21
+ from .model import ArmModel, Vec
22
+
23
+ # MuJoCo's compiled bindings ship no type stubs; keep the untyped surface behind one explicit name.
24
+ mj: Any = _mujoco
25
+
26
+ log = logging.getLogger("mjguard")
27
+ Result = dict[str, Any]
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class FollowResult:
32
+ stopped: bool
33
+ waypoints_done: int
34
+
35
+
36
+ class Transport(Protocol):
37
+ """Something that can report joint positions and follow checked waypoints: a simulator or a real arm."""
38
+
39
+ name: str
40
+
41
+ def read(self) -> tuple[Vec, Vec]:
42
+ """Measured (arm joints, gripper joints)."""
43
+ ...
44
+
45
+ def follow(
46
+ self,
47
+ waypoints: Sequence[Vec],
48
+ gripper: Vec | None,
49
+ period_s: float,
50
+ should_stop: Callable[[], bool],
51
+ on_waypoint: Callable[[Vec, Vec], None],
52
+ ) -> FollowResult: ...
53
+
54
+
55
+ class SimTransport:
56
+ """MuJoCo simulation of the arm. With actuators configured it runs physics; otherwise it sets joints directly."""
57
+
58
+ def __init__(self, config: RobotConfig, realtime: bool = False) -> None:
59
+ self.name = "mujoco"
60
+ self.model = ArmModel(config)
61
+ self.m, self.d = self.model.m, self.model.d
62
+ self.realtime = realtime
63
+ self.physics = bool(config.actuators)
64
+ self.gripper_cfg = config.gripper
65
+ self._lock = threading.Lock()
66
+ self.d.qpos[:] = self.model.qpos0
67
+ if self.physics:
68
+ for a, q in zip(self.model.actuator_ids, self.model.home, strict=True):
69
+ self.d.ctrl[a] = q
70
+ mj.mj_forward(self.m, self.d)
71
+
72
+ def read(self) -> tuple[Vec, Vec]:
73
+ with self._lock:
74
+ return self.d.qpos[self.model.qadr].copy(), self.d.qpos[self.model.gripper_qadr].copy()
75
+
76
+ def _gripper_ctrl(self, gripper: Vec) -> None:
77
+ g = self.gripper_cfg
78
+ if g is None or self.model.gripper_actuator < 0 or g.ctrl_closed is None or g.ctrl_open is None:
79
+ self.d.qpos[self.model.gripper_qadr] = gripper
80
+ return
81
+ closed, opened = np.array(g.closed), np.array(g.open)
82
+ span = opened - closed
83
+ frac = float(np.mean(np.divide(gripper - closed, span, out=np.zeros_like(span), where=span != 0)))
84
+ self.d.ctrl[self.model.gripper_actuator] = g.ctrl_closed + frac * (g.ctrl_open - g.ctrl_closed)
85
+
86
+ def follow(
87
+ self,
88
+ waypoints: Sequence[Vec],
89
+ gripper: Vec | None,
90
+ period_s: float,
91
+ should_stop: Callable[[], bool],
92
+ on_waypoint: Callable[[Vec, Vec], None],
93
+ ) -> FollowResult:
94
+ steps = max(1, round(period_s / self.m.opt.timestep))
95
+ start_g = self.read()[1]
96
+ for i, q in enumerate(waypoints):
97
+ if should_stop():
98
+ return FollowResult(True, i)
99
+ t0 = time.monotonic()
100
+ g = None if gripper is None else start_g + (gripper - start_g) * ((i + 1) / len(waypoints))
101
+ with self._lock:
102
+ if self.physics:
103
+ for a, v in zip(self.model.actuator_ids, q, strict=True):
104
+ self.d.ctrl[a] = v
105
+ if g is not None:
106
+ self._gripper_ctrl(g)
107
+ for _ in range(steps):
108
+ mj.mj_step(self.m, self.d)
109
+ else:
110
+ self.d.qpos[self.model.qadr] = q
111
+ if g is not None:
112
+ self.d.qpos[self.model.gripper_qadr] = g
113
+ self.d.qvel[:] = 0
114
+ mj.mj_forward(self.m, self.d)
115
+ measured = self.d.qpos[self.model.qadr].copy(), self.d.qpos[self.model.gripper_qadr].copy()
116
+ on_waypoint(*measured)
117
+ if self.realtime:
118
+ time.sleep(max(0.0, period_s - (time.monotonic() - t0)))
119
+ if self.physics: # let the servos settle on the last waypoint
120
+ with self._lock:
121
+ for _ in range(round(0.3 / self.m.opt.timestep)):
122
+ mj.mj_step(self.m, self.d)
123
+ return FollowResult(False, len(waypoints))
124
+
125
+
126
+ class Trace:
127
+ """Last `keep` calls in memory; optionally appended to a JSONL file."""
128
+
129
+ def __init__(self, path: Path | None = None, keep: int = 200) -> None:
130
+ self.path = path
131
+ self.events: deque[Result] = deque(maxlen=keep)
132
+ self._lock = threading.Lock()
133
+
134
+ def record(self, tool: str, arguments: Result, result: Result) -> None:
135
+ event = {"t": round(time.time(), 3), "tool": tool, "arguments": arguments, "result": result}
136
+ with self._lock:
137
+ self.events.append(event)
138
+ if self.path is not None:
139
+ with self.path.open("a", encoding="utf-8") as f:
140
+ f.write(json.dumps(event, ensure_ascii=False, default=str) + "\n")
141
+
142
+ def latest(self, n: int = 50) -> list[Result]:
143
+ with self._lock:
144
+ return list(self.events)[-n:]
145
+
146
+
147
+ def _deg(v: float) -> float:
148
+ return round(math.degrees(v), 1)
149
+
150
+
151
+ class Executor:
152
+ def __init__(self, config: RobotConfig, transport: Transport, trace: Trace | None = None) -> None:
153
+ self.config = config
154
+ self.transport = transport
155
+ self.guard = Guard(config)
156
+ self.trace = trace or Trace()
157
+ self._monitor = ArmModel(config) # only used inside the motion lock
158
+ self._view = ArmModel(config)
159
+ self._view_lock = threading.Lock()
160
+ self._motion = threading.Lock()
161
+ self._stop = threading.Event()
162
+
163
+ # ------------------------------------------------------------------ reading
164
+ def _state(self, q: Vec, g: Vec) -> Result:
165
+ with self._view_lock:
166
+ pos, axis = self._view.tool(q)
167
+ clearance = self._view.clearance_mm(q, g)
168
+ floor = self._view.floor_z
169
+ state: Result = {
170
+ "backend": self.transport.name,
171
+ "moving": self._motion.locked(),
172
+ "tool": {
173
+ "x_mm": round(float(pos[0]) * 1000, 1),
174
+ "y_mm": round(float(pos[1]) * 1000, 1),
175
+ "z_mm": round((float(pos[2]) - floor) * 1000, 1),
176
+ "axis": [round(float(v), 3) for v in axis],
177
+ },
178
+ "joints": {
179
+ name: (_deg(float(q[i])) if self._view.hinge[i] else round(float(q[i]) * 1000, 1))
180
+ for i, name in enumerate(self.config.joints)
181
+ },
182
+ "min_clearance_mm": round(clearance, 1),
183
+ }
184
+ if self.config.gripper is not None:
185
+ closed, opened = np.array(self.config.gripper.closed), np.array(self.config.gripper.open)
186
+ span = opened - closed
187
+ frac = np.divide(g - closed, span, out=np.zeros_like(span), where=span != 0)
188
+ state["gripper_opening"] = round(float(np.clip(np.mean(frac), 0, 1)), 3)
189
+ return state
190
+
191
+ def get_state(self) -> Result:
192
+ return {"ok": True, "state": self._state(*self.transport.read())}
193
+
194
+ def get_limits(self) -> Result:
195
+ return {"ok": True, "limits": self.guard.describe()}
196
+
197
+ # ------------------------------------------------------------------ acting
198
+ def stop(self) -> Result:
199
+ was_moving = self._motion.locked()
200
+ self._stop.set()
201
+ result: Result = {
202
+ "ok": True,
203
+ "was_moving": was_moving,
204
+ "note": "software stop; on real hardware a physical e-stop is the only power cut",
205
+ }
206
+ self.trace.record("stop", {}, result)
207
+ return result
208
+
209
+ def _run(
210
+ self,
211
+ tool: str,
212
+ arguments: Result,
213
+ speed: float,
214
+ planner: Callable[[Vec, Vec], tuple[Plan | Refusal, Vec | None]],
215
+ ) -> Result:
216
+ if not self._motion.acquire(blocking=False):
217
+ result: Result = {"ok": False, "refusal": Refusal("BUSY", "another motion is running").to_dict()}
218
+ self.trace.record(tool, arguments, result)
219
+ return result
220
+ try:
221
+ self._stop.clear()
222
+ q, g = self.transport.read()
223
+ plan, gripper_goal = planner(q, g)
224
+ if isinstance(plan, Refusal):
225
+ result = {"ok": False, "refusal": plan.to_dict(), "state": self._state(q, g)}
226
+ else:
227
+ result = self._execute(plan, gripper_goal, speed)
228
+ except Exception as exc:
229
+ log.exception("%s failed", tool)
230
+ refusal = Refusal("INTERNAL_ERROR", f"{tool} failed inside the server: {type(exc).__name__}: {exc}")
231
+ result = {"ok": False, "refusal": refusal.to_dict()}
232
+ finally:
233
+ self._motion.release()
234
+ self.trace.record(tool, arguments, result)
235
+ return result
236
+
237
+ def _execute(self, plan: Plan, gripper: Vec | None, speed: float) -> Result:
238
+ lim = self.config.limits
239
+ speed = float(np.clip(speed, 0.05, 1.0))
240
+ period = lim.max_step_deg / (lim.max_joint_speed_dps * speed)
241
+ lowest = [math.inf]
242
+ breach: list[str] = []
243
+
244
+ def monitor(q: Vec, g: Vec) -> None:
245
+ clearance = self._monitor.clearance_mm(q, g)
246
+ lowest[0] = min(lowest[0], clearance)
247
+ if clearance < lim.min_clearance_mm:
248
+ breach.append(f"measured clearance {clearance:.1f} mm, hard limit {lim.min_clearance_mm:g} mm")
249
+ elif contacts := self._monitor.contacts(q, g):
250
+ breach.append(f"measured contact {contacts[0].a} / {contacts[0].b}")
251
+
252
+ followed = self.transport.follow(
253
+ plan.waypoints, gripper, period, lambda: self._stop.is_set() or bool(breach), monitor
254
+ )
255
+ final = self.transport.read()
256
+ if not breach:
257
+ monitor(*final) # after the servos settle: what the arm holds now must be inside the envelope too
258
+ with self._view_lock:
259
+ planned_tool = self._view.tool(plan.waypoints[-1])[0]
260
+ measured_tool = self._view.tool(final[0])[0]
261
+ tracking_mm = round(float(np.linalg.norm(planned_tool - measured_tool)) * 1000, 1)
262
+ if breach:
263
+ refusal: Refusal | None = Refusal("ENVELOPE_BREACH", f"halted: {breach[0]}")
264
+ elif followed.stopped:
265
+ refusal = Refusal("STOPPED", "motion was stopped before it finished")
266
+ else:
267
+ refusal = None
268
+ return {
269
+ "ok": refusal is None,
270
+ "plan": {
271
+ "waypoints": len(plan.waypoints),
272
+ "duration_s": round(len(plan.waypoints) * period, 2),
273
+ "planned_min_clearance_mm": round(plan.min_clearance_mm, 1),
274
+ },
275
+ "executed": {
276
+ "waypoints": followed.waypoints_done,
277
+ "min_clearance_mm": round(lowest[0], 1),
278
+ "tool_tracking_error_mm": tracking_mm,
279
+ },
280
+ "state": self._state(*final),
281
+ **({"refusal": refusal.to_dict()} if refusal is not None else {}),
282
+ }
283
+
284
+ def move_to(self, x_mm: float, y_mm: float, z_mm: float, tool_down: bool = True, speed: float = 0.5) -> Result:
285
+ floor = self.guard.model.floor_z
286
+ target = np.array([x_mm / 1000, y_mm / 1000, floor + z_mm / 1000])
287
+ direction = np.array([0.0, 0.0, -1.0]) if tool_down else None
288
+ args = {"x_mm": x_mm, "y_mm": y_mm, "z_mm": z_mm, "tool_down": tool_down, "speed": speed}
289
+ return self._run(
290
+ "move_to",
291
+ args,
292
+ speed,
293
+ lambda q, g: (self.guard.plan_pose_with_fallback(q, target, direction, g), None),
294
+ )
295
+
296
+ def move_joints(self, joints: dict[str, float], speed: float = 0.5) -> Result:
297
+ args = {"joints": joints, "speed": speed}
298
+ unknown = sorted(set(joints) - set(self.config.joints))
299
+ if unknown:
300
+ refusal = Refusal("BAD_TARGET", f"unknown joints {unknown}; known: {list(self.config.joints)}")
301
+ result: Result = {"ok": False, "refusal": refusal.to_dict()}
302
+ self.trace.record("move_joints", args, result)
303
+ return result
304
+
305
+ def planner(q: Vec, g: Vec) -> tuple[Plan | Refusal, Vec | None]:
306
+ goal = q.copy()
307
+ for i, name in enumerate(self.config.joints):
308
+ if name in joints:
309
+ v = joints[name]
310
+ goal[i] = math.radians(v) if self.guard.model.hinge[i] else v / 1000
311
+ return self.guard.check_path(q, goal, g), None
312
+
313
+ return self._run("move_joints", args, speed, planner)
314
+
315
+ def gripper(self, opening: float, speed: float = 0.5) -> Result:
316
+ args = {"opening": opening, "speed": speed}
317
+ cfg = self.config.gripper
318
+
319
+ def planner(q: Vec, g: Vec) -> tuple[Plan | Refusal, Vec | None]:
320
+ if cfg is None:
321
+ return Refusal("BAD_TARGET", "this robot has no gripper configured"), None
322
+ if not (math.isfinite(opening) and 0.0 <= opening <= 1.0):
323
+ return Refusal("BAD_TARGET", "opening must be between 0 (closed) and 1 (open)"), None
324
+ goal = np.array(cfg.closed) + (np.array(cfg.open) - np.array(cfg.closed)) * opening
325
+ steps = max(2, int(np.ceil(np.max(np.abs(goal - g)) / 0.01)))
326
+ for i in range(1, steps + 1):
327
+ refusal, _ = self.guard.check_configuration(q, g + (goal - g) * (i / steps))
328
+ if refusal is not None:
329
+ return refusal, None
330
+ return Plan([q.copy() for _ in range(steps)], self.guard.model.clearance_mm(q, goal)), goal
331
+
332
+ return self._run("gripper", args, speed, planner)
333
+
334
+ def rest(self, speed: float = 0.5) -> Result:
335
+ home = self.guard.model.home
336
+ return self._run("rest", {"speed": speed}, speed, lambda q, g: (self.guard.check_path(q, home, g), None))