"""Cooperative cancellation primitives for interruptible robot execution.""" from __future__ import annotations import threading class ExecutionInterrupted(RuntimeError): """Raised at a safe checkpoint after a newer command supersedes a task.""" class CancellationToken: """Thread-safe, dependency-free cancellation token.""" def __init__(self): self._event = threading.Event() self.reason = "" def request(self, reason: str = "superseded") -> None: self.reason = reason self._event.set() @property def requested(self) -> bool: return self._event.is_set() def checkpoint(self) -> None: if self.requested: raise ExecutionInterrupted(self.reason or "interrupted")