# ----------------------------------------------------------------------------
# Copyright (c) 2021-2026 DexForce Technology Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------
"""Core semantic objects and planning contract for atomic skills."""
from __future__ import annotations
from embodichain.lab.sim.motion._budget import _planning_call
from abc import ABC, abstractmethod
from collections.abc import Mapping, Callable
from copy import deepcopy
from dataclasses import dataclass, field, replace
from functools import cached_property
import math
from typing import Any, ClassVar, Generic, TYPE_CHECKING, Protocol
import torch
from embodichain.compute.trajectory import differentiate_positions
from .affordance import Affordance
from .bindings import EndpointBinding, JointPositionTarget
from .continuation import PlanContinuationResult
from .effects import StateDelta
from .goals import collect_scene_dependencies
from .invocation import (
SkillInvocation,
SkillOptions,
GoalT,
OptionsT,
ResolvedSkillRequest,
)
from .plans import (
SkillPlan,
EffectVerificationRequirement,
PlannerDiagnostics,
PlanQualification,
PlanningFailure,
TimedTrajectory,
TrajectorySegment,
normalize_success_mask,
)
from .policies import (
DynamicCollisionMode,
MotionPolicy,
PlanningRecovery,
RecoveryPolicy,
)
from .requirements import GRASP_CAPABILITY, SkillBindingContract
from .runtime_commands import (
_sequence_from_fresh_frames,
_frame_from_fresh_commands,
EndpointCommand,
JointPositionPayload,
RuntimeCommandFrame,
TimedCommandSequence,
)
from .tracking import (
FeedbackTerminalAcceptance,
TimedTrackingSequence,
TrackingFrame,
TrackingSetpoint,
)
if TYPE_CHECKING:
from embodichain.lab.sim.objects import Robot
from embodichain.lab.sim.motion.motion_generator import MotionGenerator
from .reward_profiles import SkillRewardProfile
from .runtime import SkillPlanningServices
from .state import PlanningContext
from .nominal import NominalMotionSource
from .nominal import InstantiatedSkillMotion
def resolve_runtime_device(device: torch.device | str) -> torch.device:
"""Resolve an indexless CUDA device to the active concrete GPU index.
Args:
device: PyTorch device or device string.
Returns:
Concrete runtime device.
"""
resolved = torch.device(device)
if resolved.type == "cuda" and resolved.index is None:
return torch.device(f"cuda:{torch.cuda.current_device()}")
return resolved
[docs]
@dataclass(frozen=True, slots=True, eq=False)
class ObjectSemantics:
"""Shallow-frozen semantic information about an interaction object.
.. attention::
Top-level fields cannot be rebound after construction. Nested
affordance and metadata objects may remain mutable but never establish
object identity.
"""
affordance: Affordance
"""Affordance data describing supported interactions."""
geometry: dict[str, Any]
"""Non-affordance metadata used to resolve geometry-derived affordance data."""
entity_id: str
"""Stable scene identifier used by snapshot grounding and object identity."""
properties: dict[str, Any] = field(default_factory=dict)
"""Physical properties such as mass and friction."""
label: str = "none"
"""Semantic object category."""
def __post_init__(self) -> None:
if not isinstance(self.affordance, Affordance):
raise TypeError("affordance must be an Affordance instance.")
if not isinstance(self.geometry, dict):
raise TypeError("geometry must be a dict.")
if not isinstance(self.properties, dict):
raise TypeError("properties must be a dict.")
if not isinstance(self.label, str) or not self.label:
raise ValueError("label must be a non-empty string.")
if not isinstance(self.entity_id, str) or not self.entity_id.strip():
raise ValueError("entity_id must be a non-empty string.")
self.affordance.resolve_from_object_geometry(self.geometry)
self.affordance.object_label = self.label
def _same_object_identity(
left: ObjectSemantics,
right: ObjectSemantics,
) -> bool:
"""Return whether two semantic snapshots identify the same object."""
return left is right or left.entity_id == right.entity_id
[docs]
@dataclass(frozen=True, slots=True)
class SkillDescriptor:
"""Machine-readable metadata for one registered atomic skill."""
skill_id: str
goal_type: type[Any] | tuple[type[Any], ...]
options_type: type[SkillOptions]
agent_visible: bool = True
open_loop: bool = False
"""Whether completion reports motion execution without physical-effect proof."""
binding_contract: SkillBindingContract | None = None
"""Explicit generic resource contract used by Task Program lowering."""
planning_recovery_type: (
type[PlanningRecovery] | tuple[type[PlanningRecovery], ...] | None
) = None
"""Exact supported declaration type(s); None rejects nonempty declarations."""
supports_segment_motion_recovery: bool = field(default=False, init=False)
"""Derived from the actual Atomic override; not a caller-supplied claim."""
def __post_init__(self) -> None:
if not isinstance(self.skill_id, str) or not self.skill_id:
raise ValueError("SkillDescriptor.skill_id must be non-empty.")
goal_types = (
self.goal_type if isinstance(self.goal_type, tuple) else (self.goal_type,)
)
if not goal_types or not all(isinstance(item, type) for item in goal_types):
raise TypeError("SkillDescriptor.goal_type must contain concrete types.")
if not isinstance(self.options_type, type) or not issubclass(
self.options_type, SkillOptions
):
raise TypeError(
"SkillDescriptor.options_type must be an SkillOptions subclass."
)
if not isinstance(self.open_loop, bool):
raise TypeError("SkillDescriptor.open_loop must be a bool.")
recovery_types = (
self.planning_recovery_type
if isinstance(self.planning_recovery_type, tuple)
else (
()
if self.planning_recovery_type is None
else (self.planning_recovery_type,)
)
)
if self.planning_recovery_type is not None and (
not recovery_types
or len(set(recovery_types)) != len(recovery_types)
or any(
not isinstance(value, type) or not issubclass(value, PlanningRecovery)
for value in recovery_types
)
):
raise TypeError(
"planning_recovery_type requires distinct PlanningRecovery types or None."
)
if self.binding_contract is not None:
if not isinstance(self.binding_contract, SkillBindingContract):
raise TypeError(
"SkillDescriptor.binding_contract must be a "
"SkillBindingContract or None."
)
[docs]
def validate_motion_policy(self, policy: MotionPolicy) -> None:
"""Reject unsupported segment recovery before grounding/provider work.
Args:
policy: Explicit motion policy selected for this exact skill.
Raises:
TypeError: The policy has an unsupported type.
ValueError: Segment recovery has no implementation for this skill.
"""
if not isinstance(policy, MotionPolicy):
raise TypeError("policy must be a MotionPolicy.")
if (
policy.segment_sample_count_retries or policy.segment_continuous_ik_recovery
) and not self.supports_segment_motion_recovery:
raise ValueError(
f"Skill {self.skill_id!r} does not support Cartesian segment recovery."
)
[docs]
def validate_planning_recovery(self, policy: RecoveryPolicy) -> None:
"""Reject incompatible declarations before grounding or planning.
Args:
policy: Selected immutable recovery policy.
Raises:
TypeError: The policy or concrete declaration type is unsupported.
ValueError: The declaration belongs to another skill.
"""
if not isinstance(policy, RecoveryPolicy):
raise TypeError("policy must be a RecoveryPolicy.")
policy.validate_skill(self.skill_id)
declaration = policy.planning_recovery
if declaration is not None and type(declaration) not in (
self.planning_recovery_type
if isinstance(self.planning_recovery_type, tuple)
else (self.planning_recovery_type,)
):
raise TypeError(
f"Skill {self.skill_id!r} does not support planning recovery {type(declaration).__name__}."
)
[docs]
class CompletePlanBuilder(Protocol):
"""Engine-owned candidate construction and selected-plan finalization."""
def __call__(
self,
request: ResolvedSkillRequest,
*,
planner: (
Callable[[ResolvedSkillRequest, PlanningContext], SkillPlan] | None
) = None,
apply_transform: bool = True,
action_qualifier: (
Callable[
[ResolvedSkillRequest, PlanningContext, SkillPlan],
PlanQualification | None,
]
| None
) = None,
) -> SkillPlan:
"""Build with sampling retries and final generic qualification.
``planner`` retains request preparation and command authorization.
Explicit candidate search may defer the caller's transform until
:meth:`finalize_selected`; default calls preserve the original pipeline.
A declared mask-only velocity gate waits until the complete action hook
returns; it does not change masks seen by internal candidate searches.
``action_qualifier`` replaces only this build's post-transform action
qualification. Structural checks and generic final velocity checks remain
mandatory; omitted callbacks use the action's normal qualifier.
"""
...
[docs]
def plan_preview(
self, request: ResolvedSkillRequest, context: PlanningContext
) -> SkillPlan:
"""Build an exact suffix under a private same-observation context.
The original caller transform stays local to this complete planning call.
The engine validates rows, observed robot, world/scene and request owner;
no command, state commit or second compiler is created by a preview.
"""
...
[docs]
def finalize_selected(
self, request: ResolvedSkillRequest, plan: SkillPlan
) -> SkillPlan:
"""Transform the selected candidate and qualify it without replanning.
Call once after selecting a candidate built with ``apply_transform=False``.
Structural, velocity and action final-plan qualification remain enforced.
"""
...
[docs]
class AtomicSkill(Generic[GoalT, OptionsT], ABC):
"""Side-effect-free planner for one semantically meaningful robot skill.
Actions own only typed default runtime options. An
:class:`~embodichain.lab.sim.atomic_skills.engine.AtomicSkillEngine` binds
its shared planning services before an action is invoked.
"""
skill_id: ClassVar[str]
"""Stable registry identifier for this skill."""
GoalType: ClassVar[type[Any] | tuple[type[Any], ...]]
"""Concrete goal dataclass or dataclasses accepted by this skill."""
OptionsType: ClassVar[type[SkillOptions]] = SkillOptions
"""Concrete per-invocation runtime options accepted by this skill."""
PlanningRecoveryType: ClassVar[
type[PlanningRecovery] | tuple[type[PlanningRecovery], ...] | None
] = None
"""Exact opt-in planning declarations supported by this skill."""
agent_visible: ClassVar[bool] = True
"""Whether an Action Agent should expose this skill by default."""
open_loop: ClassVar[bool] = False
"""Whether the skill intentionally declares no verified physical effect."""
binding_contract: ClassVar[SkillBindingContract | None] = None
"""Explicit robot-independent requirements for semantic discovery.
Concrete action classes must declare this attribute in their own class
body to opt into the semantic catalog. Inheriting another action's contract
does not silently expose a new skill identifier.
"""
def __init_subclass__(cls, **kwargs: Any) -> None:
"""Reject skill classes that bypass framework-owned scene binding."""
super().__init_subclass__(**kwargs)
if "plan" in cls.__dict__:
raise TypeError(
"AtomicSkill subclasses must implement _plan(); the public "
"plan() method is framework-owned."
)
[docs]
def __init__(
self,
default_options: OptionsT | None = None,
) -> None:
selected_options = (
self.OptionsType() if default_options is None else default_options
)
if not isinstance(selected_options, self.OptionsType):
raise TypeError(
f"{type(self).__name__} expects default_options of type "
f"{self.OptionsType.__name__}, got "
f"{type(selected_options).__name__}."
)
self._default_options: OptionsT = deepcopy(selected_options)
self._planning_services: SkillPlanningServices | None = None
@property
def default_options(self) -> OptionsT:
"""Return an owned copy of the action's default runtime options."""
return deepcopy(self._default_options)
@property
def is_bound(self) -> bool:
"""Whether an engine has supplied this action's planning resources."""
return self._planning_services is not None
@property
def planning_services(self) -> SkillPlanningServices:
"""Return the engine-owned services borrowed by this action.
Raises:
RuntimeError: If the action has not been registered or planned by
an
:class:`~embodichain.lab.sim.atomic_skills.engine.AtomicSkillEngine`.
"""
if self._planning_services is None:
raise RuntimeError(
f"Atomic Skill {self.skill_id!r} is not bound to an "
"AtomicSkillEngine. Register it with engine.register()."
)
return self._planning_services
@property
def motion_generator(self) -> MotionGenerator:
"""Return the engine-owned motion generator borrowed by this action."""
return self.planning_services.motion_generator
@property
def robot(self) -> Robot:
"""Return the robot associated with the owning engine."""
return self.planning_services.robot
@property
def device(self) -> torch.device:
"""Return the concrete runtime device associated with the engine."""
return self.planning_services.device
@cached_property
def num_envs(self) -> int:
"""Number of environments owned by the bound robot."""
selection = self.planning_services.env_ids
return (
int(
self.robot.get_qpos(
**(
{"env_ids": self.planning_services.env_ids}
if self.planning_services.env_ids is not None
else {}
)
).shape[0]
)
if selection is None
else len(selection)
)
@cached_property
def robot_dof(self) -> int:
"""Number of full-robot degrees of freedom."""
return int(self.robot.dof)
def _bind(self, services: SkillPlanningServices) -> None:
"""Bind engine-owned planning services exactly once."""
if self._planning_services is services:
return
if self._planning_services is not None:
raise ValueError(
f"Atomic Skill {self.skill_id!r} is already bound to another "
"AtomicSkillEngine."
)
self._planning_services = services
[docs]
@classmethod
def reward_profiles(cls) -> dict[str, SkillRewardProfile]:
"""Return execution-independent reward recipes without binding a planner."""
from .reward_profiles import skill_reward_profiles
return skill_reward_profiles(cls.skill_id)
[docs]
@classmethod
def descriptor(cls) -> SkillDescriptor:
"""Return stable metadata used by registries and Action Agent adapters."""
descriptor = SkillDescriptor(
skill_id=cls.skill_id,
goal_type=cls.GoalType,
options_type=cls.OptionsType,
agent_visible=cls.agent_visible,
open_loop=cls.open_loop,
binding_contract=cls.__dict__.get("binding_contract"),
planning_recovery_type=cls.PlanningRecoveryType,
)
object.__setattr__(
descriptor,
"supports_segment_motion_recovery",
cls._validate_segment_motion_recovery
is not AtomicSkill._validate_segment_motion_recovery,
)
return descriptor
[docs]
def resolve_request(
self,
invocation: SkillInvocation[GoalT, OptionsT],
) -> ResolvedSkillRequest[GoalT, OptionsT]:
"""Validate and snapshot an invocation through engine-owned resources.
Args:
invocation: Caller-owned invocation to resolve.
Returns:
Immutable request reused by planning and recovery replans.
Raises:
ValueError: If the stable skill identifier does not match.
TypeError: If the goal or options type is incompatible.
KeyError: If a required binding role is missing.
"""
if invocation.skill_id != self.skill_id:
raise ValueError(
f"Invocation skill_id {invocation.skill_id!r} does not match "
f"{self.skill_id!r}."
)
descriptor = self.descriptor()
descriptor.validate_planning_recovery(invocation.recovery_policy)
descriptor.validate_motion_policy(invocation.motion_policy)
if not isinstance(invocation.goal, self.GoalType):
expected = (
" | ".join(item.__name__ for item in self.GoalType)
if isinstance(self.GoalType, tuple)
else self.GoalType.__name__
)
raise TypeError(
f"Skill {self.skill_id!r} expects goal {expected}, got "
f"{type(invocation.goal).__name__}."
)
contract = type(self).__dict__.get("binding_contract")
if contract is None:
raise ValueError(
f"Skill {self.skill_id!r} has no explicit SkillBindingContract."
)
self.planning_services.validate_binding(invocation.binding, contract)
options = (
self._default_options
if invocation.skill_options is None
else invocation.skill_options
)
if not isinstance(options, self.OptionsType):
raise TypeError(
f"Skill {self.skill_id!r} expects options "
f"{self.OptionsType.__name__}, got {type(options).__name__}."
)
return ResolvedSkillRequest(
skill_id=invocation.skill_id,
goal=invocation.goal,
binding=self.planning_services.apply_command_overrides(
invocation.binding,
invocation.control_overrides,
),
motion_policy=invocation.motion_policy,
tracking_policy=invocation.tracking_policy,
recovery_policy=invocation.recovery_policy,
phase_effect_gates=invocation.phase_effect_gates,
skill_options=options,
invocation_id=invocation.invocation_id,
revision=invocation.revision,
)
[docs]
def require_goal(
self,
request: ResolvedSkillRequest[GoalT, OptionsT],
) -> GoalT:
"""Validate a resolved request and return its concrete goal."""
if request.skill_id != self.skill_id:
raise ValueError(
f"Request skill_id {request.skill_id!r} does not match "
f"{self.skill_id!r}."
)
descriptor = self.descriptor()
descriptor.validate_planning_recovery(request.recovery_policy)
descriptor.validate_motion_policy(request.motion_policy)
if not isinstance(request.goal, self.GoalType):
raise TypeError(
f"Skill {self.skill_id!r} received incompatible goal "
f"{type(request.goal).__name__}."
)
if not isinstance(request.skill_options, self.OptionsType):
raise TypeError(
f"Skill {self.skill_id!r} received incompatible options "
f"{type(request.skill_options).__name__}."
)
contract = type(self).__dict__.get("binding_contract")
if contract is None:
raise ValueError(
f"Skill {self.skill_id!r} has no explicit SkillBindingContract."
)
self.planning_services.validate_binding(request.binding, contract)
return request.goal
[docs]
@_planning_call("check")
def plan_complete_request(
self,
request: ResolvedSkillRequest[GoalT, OptionsT],
context: PlanningContext,
*,
build: CompletePlanBuilder,
external_nominal: bool = False,
) -> SkillPlan:
"""Delegate one complete request, optionally specialized by a typed skill.
Args:
request: Already-resolved immutable invocation and selected policies.
context: Actual planning observation; no execution is permitted.
build: Engine-owned builder retaining generic retry/transform/final
qualification boundaries. A skill may select only its declared
bounded alternatives; it cannot modify the builder or registry.
external_nominal: Whether the caller supplied an external nominal
motion source. Unsupported explicit recovery combinations reject.
Returns:
One complete action plan. The default delegates exactly once and
performs no reads, snapshots, retries or state changes.
"""
return build(request)
[docs]
@_planning_call("check")
def plan(
self,
request: ResolvedSkillRequest[GoalT, OptionsT],
context: PlanningContext,
*,
nominal_source: NominalMotionSource | None = None,
planner: (
Callable[[ResolvedSkillRequest, PlanningContext], SkillPlan] | None
) = None,
) -> SkillPlan:
"""Bind the current collision scene and invoke the skill planner.
Args:
request: Immutable, typed, and embodiment-resolved action request.
context: Latest observed robot, task, and scene state.
Returns:
Scene-bound action plan with expected, uncommitted effects.
"""
self.require_goal(request)
if planner is not None and (
not callable(planner) or nominal_source is not None
):
raise ValueError(
"An action-owned candidate planner cannot replace external nominal motion."
)
segment_recovery = bool(
request.motion_policy.segment_sample_count_retries
or request.motion_policy.segment_continuous_ik_recovery
)
if segment_recovery:
if nominal_source is not None:
raise ValueError(
"Segment motion recovery cannot alter external nominal motion."
)
self._validate_segment_motion_recovery(request, context)
prepared = self._prepare_request(request, context)
plan = (
(self._plan if planner is None else planner)(prepared, context)
if nominal_source is None
else self._plan_from_nominal(prepared, context, nominal_source)
)
if not isinstance(plan, SkillPlan):
raise TypeError("AtomicSkill._plan() must return an SkillPlan.")
return replace(
plan,
commands=self._authorize_command_targets(prepared, plan.commands),
)
def _validate_segment_motion_recovery(self, request, context) -> None:
"""Reject unsupported non-default segment policy before scene/provider work."""
raise ValueError(
f"Skill {self.skill_id!r} does not support Cartesian segment recovery."
)
def _qualify_final_plan(
self,
request: ResolvedSkillRequest[GoalT, OptionsT],
context: PlanningContext,
plan: SkillPlan,
) -> PlanQualification | None:
"""Inspect emitted samples after plan transforms without replanning.
The engine supplies an owned plan snapshot and accepts only a mask and
diagnostics. Implementations may reject rows, never return a replacement
plan, change the request/context, execute commands or commit effects.
The default has no additional qualification requirement.
"""
return None
def _plan_from_nominal(
self,
request: ResolvedSkillRequest[GoalT, OptionsT],
context: PlanningContext,
nominal_source: NominalMotionSource,
) -> SkillPlan:
"""Reject external motion unless the concrete skill opts in."""
raise ValueError(
f"Skill {self.skill_id!r} does not support external nominal motion."
)
def _validate_nominal_motion(
self,
request: ResolvedSkillRequest[GoalT, OptionsT],
context: PlanningContext,
source: NominalMotionSource,
*,
segments: tuple[str, ...] | None,
) -> InstantiatedSkillMotion:
"""Validate a single-slot external reference before skill assembly."""
from .nominal import InstantiatedSkillMotion
if context.batch_size != 1:
raise ValueError("external nominal motion currently requires B=1")
if (
request.recovery_policy.max_replans
or request.recovery_policy.max_skill_retries
):
raise ValueError(
"external nominal motion requires zero replans and action retries"
)
source_generator = getattr(source, "motion_generator", None)
if (
source_generator is not None
and source_generator is not self.motion_generator
):
raise ValueError(
"external source must use the engine-owned motion generator"
)
motion = source.instantiate(request, context)
if not isinstance(motion, InstantiatedSkillMotion):
raise TypeError("nominal source must return a InstantiatedSkillMotion")
timed = motion.trajectory
if segments is not None and tuple(motion.segment_lengths) != segments:
raise ValueError(f"external motion requires ordered segments {segments}")
if tuple(self.robot.joint_names) != motion.joint_names:
raise ValueError("external motion joint layout does not match the robot")
if (
timed.batch_size != 1
or timed.robot_dof != context.robot.robot_dof
or not torch.equal(timed.env_ids, context.env_ids)
):
raise ValueError(
"external motion must match the active environment and robot"
)
if not torch.allclose(
motion.initial_qpos, context.robot.qpos, atol=1e-4, rtol=0
):
raise ValueError(
"external motion start does not match the observed robot state"
)
hand = request.binding.endpoint("primary", "grasp").require_target(
JointPositionTarget
)
arm = request.binding.endpoint("primary", "motion").require_target(
JointPositionTarget
)
hand_ids = set(hand.joint_ids)
owned = hand_ids | set(arm.joint_ids)
mimic_ids = tuple(getattr(self.robot, "mimic_ids", ()))
if mimic_ids:
parents = tuple(self.robot.mimic_parents)
multipliers = tuple(self.robot.mimic_multipliers)
offsets = tuple(self.robot.mimic_offsets)
if not (len(mimic_ids) == len(parents) == len(multipliers) == len(offsets)):
raise ValueError("robot mimic metadata is inconsistent")
pending = list(zip(mimic_ids, parents, multipliers, offsets))
while pending:
previous = len(pending)
for item in tuple(pending):
child, parent, multiplier, offset = item
if parent not in owned:
continue
if (
type(child) is not int
or type(parent) is not int
or not 0 <= child < timed.robot_dof
or not 0 <= parent < timed.robot_dof
):
raise ValueError("robot mimic metadata indexes invalid joints")
expected = timed.positions[:, :, parent] * multiplier + offset
if not torch.allclose(
timed.positions[:, :, child], expected, atol=1e-5, rtol=0
):
raise ValueError(
"external motion violates robot mimic constraints: "
f"{self.robot.joint_names[child]} <- {self.robot.joint_names[parent]} "
f"multiplier={multiplier} offset={offset} "
f"max_error={float((timed.positions[:,:,child]-expected).abs().max()):.6g}"
)
owned.add(child)
pending.remove(item)
if len(pending) == previous:
break
unowned = [index for index in range(timed.robot_dof) if index not in owned]
if unowned and not torch.allclose(
timed.positions[:, :, unowned],
context.robot.qpos[:, None, unowned].expand(-1, timed.waypoint_count, -1),
atol=1e-6,
rtol=0,
):
raise ValueError("external motion cannot command unowned joints")
other_ids = [
index
for index in range(timed.robot_dof)
if index not in hand_ids | set(mimic_ids)
]
if not torch.allclose(
timed.positions[:, 0, other_ids],
context.robot.qpos[:, other_ids],
atol=1e-4,
rtol=0,
):
raise ValueError(
"external motion begins with a discontinuous non-gripper target"
)
if timed.waypoint_count < 2 or not torch.allclose(
timed.dt[:, 0], torch.zeros_like(timed.dt[:, 0]), atol=1e-7, rtol=0
):
raise ValueError(
"external motion requires at least two samples and zero initial dt"
)
if not torch.allclose(
timed.dt[:, 1:],
torch.full_like(timed.dt[:, 1:], context.require_control_dt()),
atol=1e-6,
rtol=0,
):
raise ValueError("external motion must use the environment control grid")
arm_ids = list(arm.joint_ids)
limits = self.robot.get_qpos_limits(name=arm.control_part)
speeds = self.robot.get_qvel_limits(name=arm.control_part)
if self.planning_services.env_ids is not None:
if isinstance(limits, torch.Tensor) and limits.ndim == 3:
limits = limits.index_select(0, context.env_ids.to(limits.device))
if isinstance(speeds, torch.Tensor) and speeds.ndim == 2:
speeds = speeds.index_select(0, context.env_ids.to(speeds.device))
if (
not isinstance(limits, torch.Tensor)
or limits.shape != (1, len(arm_ids), 2)
or bool(torch.isnan(limits).any())
or not bool((limits[:, :, 0] <= limits[:, :, 1]).all())
):
raise ValueError("external motion requires ordered robot joint limits")
if (
not isinstance(speeds, torch.Tensor)
or speeds.shape != (1, len(arm_ids))
or bool(torch.isnan(speeds).any())
or not bool((speeds > 0).all())
):
raise ValueError("external motion requires positive robot speed limits")
arm_path = timed.positions[:, :, arm_ids]
if bool(
(
(arm_path < limits[:, None, :, 0] - 1e-5)
| (arm_path > limits[:, None, :, 1] + 1e-5)
).any()
):
raise ValueError("external motion exceeds robot joint limits")
velocity = (arm_path[:, 1:] - arm_path[:, :-1]) / timed.dt[:, 1:, None]
if request.motion_policy.velocity_limit is not None:
speeds = torch.minimum(
speeds, torch.full_like(speeds, request.motion_policy.velocity_limit)
)
if bool((velocity.abs() > speeds[:, None] + 1e-5).any()):
raise ValueError("external motion exceeds robot speed limits")
if (
request.motion_policy.acceleration_limit is not None
and velocity.shape[1] > 1
):
acceleration = (velocity[:, 1:] - velocity[:, :-1]) / timed.dt[:, 2:, None]
if bool(
(
acceleration.abs() > request.motion_policy.acceleration_limit + 1e-5
).any()
):
magnitude = acceleration.abs()
flat_index = int(magnitude.reshape(-1).argmax())
sample_index = flat_index // len(arm_ids) + 2
joint_index = arm_ids[flat_index % len(arm_ids)]
start = 0
phase = "unknown"
for phase_name, length in motion.segment_lengths.items():
if start <= sample_index < start + length:
phase = phase_name
break
start += length
raise ValueError(
"external motion exceeds the configured acceleration limit: "
f"sample={sample_index}, phase={phase}, joint={self.robot.joint_names[joint_index]}, "
f"acceleration={float(magnitude.reshape(-1)[flat_index]):.6g}, "
f"limit={request.motion_policy.acceleration_limit:.6g}"
)
return motion
def _validate_nominal_anchor(
self,
trajectory: TimedTrajectory,
*,
index: int,
endpoint: JointPositionTarget,
target: torch.Tensor,
) -> None:
"""Verify an external reference against a skill-owned TCP target."""
if not 0 <= index < trajectory.waypoint_count:
raise ValueError("external motion anchor index is out of range")
qpos = trajectory.positions[:, index, list(endpoint.joint_ids)]
actual = self.robot.compute_fk(
qpos=qpos,
name=endpoint.control_part,
to_matrix=True,
**(
{"env_ids": self.planning_services.env_ids}
if self.planning_services.env_ids is not None
else {}
),
)
if (
not isinstance(actual, torch.Tensor)
or actual.shape != target.shape
or not bool(torch.isfinite(actual).all())
):
raise ValueError("external motion anchor FK is unavailable")
position_error = torch.linalg.vector_norm(
actual[:, :3, 3] - target[:, :3, 3], dim=-1
)
relative = actual[:, :3, :3].transpose(-1, -2) @ target[:, :3, :3]
cosine = ((relative.diagonal(dim1=-2, dim2=-1).sum(-1) - 1) / 2).clamp(-1, 1)
rotation_error = torch.acos(cosine)
if bool(((position_error > 0.002) | (rotation_error > math.radians(2))).any()):
raise ValueError(
"external motion does not reach its required TCP anchor: "
f"position_error_m={float(position_error.max()):.6g}, "
f"rotation_error_deg={math.degrees(float(rotation_error.max())):.6g}"
)
def _prepare_request(
self,
request: ResolvedSkillRequest[GoalT, OptionsT],
context: PlanningContext,
) -> ResolvedSkillRequest[GoalT, OptionsT]:
"""Bind snapshot obstacle poses without mutating the resolved request."""
if not self._uses_collision_world(request, context):
return request
poses = context.scene.collision_obstacle_poses(
batch_size=context.batch_size,
device=context.robot.qpos.device,
dtype=context.robot.qpos.dtype,
)
policy = replace(
request.motion_policy,
plan_opts=self.motion_generator.bind_collision_world(
request.motion_policy.plan_opts,
obstacle_poses=poses,
),
)
return replace(request, motion_policy=policy)
def _uses_collision_world(
self,
request: ResolvedSkillRequest[GoalT, OptionsT],
context: PlanningContext,
) -> bool:
"""Return whether this planning attempt consumes collision revisions."""
mode = request.motion_policy.dynamic_collision_mode
if mode is DynamicCollisionMode.OFF:
return False
uses_motion_generator = request.motion_policy.strategy == "motion_gen"
has_collision_entities = bool(context.scene.collision_entity_ids)
supports_updates = (
getattr(
self.motion_generator,
"supports_dynamic_collision_world",
False,
)
is True
)
available = (
uses_motion_generator and has_collision_entities and supports_updates
)
if mode is DynamicCollisionMode.REQUIRED and not available:
missing: list[str] = []
if not uses_motion_generator:
missing.append("strategy='motion_gen'")
if not has_collision_entities:
missing.append("scene collision entities")
if not supports_updates:
missing.append("a planner with dynamic collision-world support")
raise ValueError(
"dynamic_collision_mode='required' cannot be satisfied; missing "
+ ", ".join(missing)
+ "."
)
return available
def _scene_dependencies(
self,
request: ResolvedSkillRequest[GoalT, OptionsT],
) -> tuple[str, ...]:
"""Return scene entities whose poses materially affect this plan."""
return collect_scene_dependencies(request.goal)
[docs]
def build_plan(
self,
request: ResolvedSkillRequest[GoalT, OptionsT],
context: PlanningContext,
*,
success: bool | torch.Tensor,
trajectory: TimedTrajectory,
expected_effects: StateDelta | None = None,
effect_candidates: StateDelta | None = None,
effect_verification: EffectVerificationRequirement | None = None,
replannable: bool = True,
preserve_velocity_samples: bool = False,
diagnostics: PlannerDiagnostics | None = None,
segment_lengths: Mapping[str, int] | None = None,
scene_dependency_monitor_until: Mapping[str, int] | None = None,
scene_dependency_end_segment: str | None = None,
) -> SkillPlan:
"""Build a validated action plan for a primitive implementation.
Args:
request: Resolved invocation snapshot being planned.
context: Planning input used for the plan.
success: Per-environment planning success or scalar planner result.
trajectory: Full-robot trajectory with explicit timing.
expected_effects: Symbolic effects to verify after execution.
effect_candidates: Planned attachment baselines used by phase gates
and in-flight held-object guards without committing task state.
effect_verification: Optional explicit physical-effect boundary.
Use this when verification is required without a symbolic task-
state delta.
preserve_velocity_samples: Keep explicitly authored arrival velocities across
consecutive timed segments. Derived velocity targets retain their usual
boundary and stationary treatment.
replannable: Whether the execution runtime may replan this action.
diagnostics: Optional retained planner diagnostics.
segment_lengths: Optional ordered mapping from semantic segment
names to waypoint counts. Zero-length entries are omitted.
scene_dependency_monitor_until: Optional per-entity exclusive
waypoint-index upper bound for scene-motion invalidation. An
entity is monitored while the current waypoint index is smaller
than its bound. ``0`` disables monitoring immediately; omitted
dependencies remain monitored for the full action. Once the bound
is reached, all pose changes for that entity are ignored.
scene_dependency_end_segment: Optional last segment during which
scene motion may invalidate and replan the action for every
dependency.
Returns:
Side-effect-free action plan.
"""
success_mask = normalize_success_mask(
success,
num_envs=context.batch_size,
device=self.device,
name="Planning success",
)
if not isinstance(trajectory, TimedTrajectory):
raise TypeError(
"trajectory must be a TimedTrajectory with explicit dt; atomic "
"actions may not return untimed position tensors."
)
timed = trajectory
if timed.batch_size != context.batch_size:
raise ValueError("Trajectory and planning context batch sizes must match.")
if timed.robot_dof != context.robot.robot_dof:
raise ValueError("Trajectory robot_dof must match the planning context.")
planner = (
None
if self._planning_services is None
else self._planning_services.motion_generator.planner
)
preserve_failed_positions = (
getattr(planner, "preserve_failed_plan_positions", False) is True
)
if not preserve_failed_positions:
timed = timed.hold_rows(success_mask, context.robot.qpos)
from ._expansion_phases import FREE_PHASES
already_bridged = diagnostics is not None and bool(
diagnostics.metadata.get("reference_bridge")
)
bridge_supported = (
next(iter(segment_lengths or {}), None)
in FREE_PHASES.get(request.skill_id, ())
and request.motion_policy.acceleration_limit is not None
# Position-only transports may expose zero feedforward velocity
# during motion. Do not apply this rest handoff to action recovery.
and request.recovery_policy.max_replans == 0
and request.recovery_policy.max_skill_retries == 0
and request.revision == 0
and bool(success_mask.any())
and not (
diagnostics is not None and diagnostics.backend == "external_nominal"
)
)
if (
request.tracking_policy.boundary_reference_bridge
and not already_bridged
and context.robot.command_qvel is not None
):
motion_ids = tuple(
dict.fromkeys(
i
for e in request.binding.endpoints
if e.endpoint_id == "motion"
for i in e.joint_ids
)
)
if motion_ids and bool(
(
context.robot.command_qvel[success_mask][:, list(motion_ids)].abs()
> 1e-6
).any()
):
bridge_supported = False
if (
request.tracking_policy.boundary_reference_bridge
and not bridge_supported
and not already_bridged
):
previous = diagnostics or PlannerDiagnostics(backend="reference_takeover")
diagnostics = replace(
previous,
metadata={
**previous.metadata,
"reference_bridge_unavailable": "unsupported_phase_source_or_boundary_conditions",
},
)
if (
request.tracking_policy.boundary_reference_bridge
and bridge_supported
and not (
diagnostics is not None and diagnostics.metadata.get("reference_bridge")
)
):
from ._reference_bridge import _reference_prefix
from ._expansion_phases import FREE_PHASES
lengths = dict(segment_lengths or {})
first = next(iter(lengths), None)
if first not in FREE_PHASES.get(request.skill_id, ()):
raise ValueError(
"Reference takeover requires an explicitly free first phase"
)
reference = context.robot.command_qpos
reference_velocity = context.robot.command_qvel
if reference is None or reference_velocity is None:
raise ValueError(
"Reference takeover requires measured controller target snapshots"
)
ids = tuple(
dict.fromkeys(
i
for e in request.binding.endpoints
if e.endpoint_id == "motion"
for i in e.joint_ids
)
)
if not ids or bool(
(reference_velocity[success_mask][:, list(ids)].abs() > 1e-6).any()
):
raise ValueError(
"Reference takeover requires stationary motion targets"
)
dt = context.require_control_dt()
limits = (
self.robot.get_qvel_limits(env_ids=context.env_ids)[success_mask]
.amin(dim=0)
.to(timed.positions)
)
if request.motion_policy.velocity_limit is not None:
limits = limits.clamp(max=request.motion_policy.velocity_limit)
acceleration = request.motion_policy.acceleration_limit
if acceleration is None:
raise ValueError(
"Reference takeover requires an explicit acceleration bound"
)
reference = torch.where(
success_mask[:, None], reference, timed.positions[:, 0]
)
prefix = _reference_prefix(
reference, timed.positions[:, 0], ids, dt, limits, acceleration
)
count = prefix.shape[1]
if count:
positions = torch.cat((prefix, timed.positions), dim=1)
times = torch.cat(
(
timed.dt.new_full((timed.batch_size, count), dt),
timed.dt.clone(),
),
dim=1,
)
times[:, 0] = 0
times[:, count] = dt
window = positions[:, : count + min(3, timed.waypoint_count), list(ids)]
window_dt = times[:, : window.shape[1]]
speed = torch.diff(window, dim=1) / window_dt[:, 1:, None]
accel = torch.diff(speed, dim=1) / window_dt[:, 2:, None]
joint_limits = self.robot.get_qpos_limits(
joint_ids=list(ids), env_ids=context.env_ids
).to(window)
if (
joint_limits.shape != (timed.batch_size, len(ids), 2)
or bool(torch.isnan(joint_limits).any())
or bool((joint_limits[..., 0] > joint_limits[..., 1]).any())
):
raise ValueError(
"Reference takeover requires valid ordered joint limits"
)
if bool(
(
(window < joint_limits[:, None, :, 0] - 1e-6)
| (window > joint_limits[:, None, :, 1] + 1e-6)
)[success_mask].any()
):
raise ValueError("Reference takeover exceeds joint limits")
if bool(
(
speed[success_mask].abs() > limits[list(ids)][None, None] + 1e-5
).any()
) or bool((accel[success_mask].abs() > acceleration + 1e-5).any()):
raise ValueError(
"Reference takeover seam exceeds velocity/acceleration bounds"
)
original_velocity = timed.velocities
if original_velocity is None:
original_velocity = differentiate_positions(
timed.positions, timed.dt
)
original_velocity = original_velocity.clone()
original_velocity[:, 0] = 0
original_velocity[:, -1] = 0
bridge_points = torch.cat((prefix, timed.positions[:, :1]), dim=1)
bridge_dt = times[:, : count + 1]
bridge_velocity = differentiate_positions(bridge_points, bridge_dt)
velocity = torch.cat(
(bridge_velocity[:, :-1], original_velocity), dim=1
)
timed = TimedTrajectory.from_positions(
positions, env_ids=timed.env_ids, dt=times, velocities=velocity
)
segment_lengths = dict(lengths)
segment_lengths[first] += count
if scene_dependency_monitor_until is not None:
scene_dependency_monitor_until = {
key: (value + count if value else 0)
for key, value in scene_dependency_monitor_until.items()
}
previous = diagnostics or PlannerDiagnostics(
backend="reference_takeover"
)
diagnostics = replace(
previous,
metadata={
**previous.metadata,
"reference_bridge": {
"prefix_samples": count,
"control_dt": dt,
"joint_ids": ids,
},
"source_collision_evidence": previous.metadata.get(
"collision_evidence", "unverified"
),
"collision_evidence": "unverified",
"collision_scope": "not_checked",
},
)
else:
previous = diagnostics or PlannerDiagnostics(
backend="reference_takeover"
)
diagnostics = replace(
previous,
metadata={
**previous.metadata,
"reference_bridge": {
"prefix_samples": 0,
"control_dt": dt,
"joint_ids": ids,
},
},
)
# Composite skills may rebuild positions/timing after MotionGenerator.
# Derive references only after that final composition, before lowering.
velocities = timed.velocities
if request.motion_policy.velocity_targets == "zero":
velocities = torch.zeros_like(timed.positions)
elif velocities is None:
velocities = differentiate_positions(timed.positions, timed.dt)
else:
velocities = velocities.clone()
if timed.waypoint_count and not (
preserve_velocity_samples and timed.velocities is not None
):
# Commands are held until the next arrival. A stationary interval
# and the final settling window must never retain a moving target.
stationary = timed.positions[:, 1:] == timed.positions[:, :-1]
velocities[:, :-1] = velocities[:, :-1].masked_fill(stationary, 0.0)
velocities[:, 1:] = velocities[:, 1:].masked_fill(stationary, 0.0)
velocities[:, 0] = 0.0
velocities[:, -1] = 0.0
if diagnostics is not None and diagnostics.metadata.get("reference_bridge"):
join = int(diagnostics.metadata["reference_bridge"]["prefix_samples"])
velocities[:, join] = 0.0
ids = list(diagnostics.metadata["reference_bridge"]["joint_ids"])
window_velocity = velocities[:, : join + 3, ids]
window_acceleration = (
torch.diff(window_velocity, dim=1)
/ timed.dt[:, 1 : window_velocity.shape[1], None]
)
cap = self.robot.get_qvel_limits(
joint_ids=ids, env_ids=context.env_ids
).to(window_velocity)
if request.motion_policy.velocity_limit is not None:
cap = cap.clamp(max=request.motion_policy.velocity_limit)
if not bool(torch.isfinite(cap[success_mask]).all()) or bool(
(cap[success_mask] <= 0).any()
):
raise ValueError(
"Reference takeover requires finite positive velocity bounds"
)
if bool(
(
window_velocity[success_mask].abs()
> cap[success_mask, None] + 1e-5
).any()
) or bool(
(
window_acceleration[success_mask].abs()
> request.motion_policy.acceleration_limit + 1e-5
).any()
):
raise ValueError(
"Reference takeover command derivatives exceed motion bounds"
)
timed = replace(timed, velocities=velocities)
commands = self._joint_command_sequence(
request,
timed,
active_mask=success_mask,
)
return self.build_command_plan(
request,
context,
success=success_mask,
commands=commands,
expected_effects=expected_effects,
effect_candidates=effect_candidates,
effect_verification=effect_verification,
replannable=replannable,
diagnostics=diagnostics,
segment_lengths=segment_lengths,
scene_dependency_monitor_until=scene_dependency_monitor_until,
scene_dependency_end_segment=scene_dependency_end_segment,
joint_trajectory=timed,
)
[docs]
def build_command_plan(
self,
request: ResolvedSkillRequest[GoalT, OptionsT],
context: PlanningContext,
*,
success: bool | torch.Tensor,
commands: TimedCommandSequence,
expected_effects: StateDelta | None = None,
effect_candidates: StateDelta | None = None,
effect_verification: EffectVerificationRequirement | None = None,
replannable: bool = True,
diagnostics: PlannerDiagnostics | None = None,
segment_lengths: Mapping[str, int] | None = None,
scene_dependency_monitor_until: Mapping[str, int] | None = None,
scene_dependency_end_segment: str | None = None,
joint_trajectory: TimedTrajectory | None = None,
) -> SkillPlan:
"""Build a plan from transport-neutral runtime command frames.
Tracking targets are projected from the command payloads through the
typed channels declared by each bound endpoint. Semantic effects remain
externally verified through the execution session.
Args:
request: Resolved invocation snapshot being planned.
context: Planning input used for the plan.
success: Per-environment planning success or scalar planner result.
commands: Transport-neutral command sequence for the action.
expected_effects: Symbolic effects to verify after execution.
effect_candidates: Planned attachment baselines used by phase gates
and in-flight held-object guards without committing task state.
effect_verification: Optional explicit physical-effect boundary.
replannable: Whether the execution runtime may replan this action.
diagnostics: Optional retained planner diagnostics.
segment_lengths: Optional ordered mapping from semantic segment names
to command-frame counts. Zero-length entries are omitted.
scene_dependency_monitor_until: Optional per-entity exclusive
command-frame-index upper bound for scene-motion invalidation. An
entity is monitored while the current frame index is smaller than
its bound. ``0`` disables monitoring immediately; omitted
dependencies remain monitored for the full action. Once the bound
is reached, all pose changes for that entity are ignored.
scene_dependency_end_segment: Optional last segment during which
scene motion may invalidate and replan the action for every
dependency.
joint_trajectory: Optional joint trajectory retained for offline
compilation and inspection.
Returns:
Side-effect-free action plan.
"""
if not isinstance(commands, TimedCommandSequence):
raise TypeError("commands must be a TimedCommandSequence.")
if commands.batch_size != context.batch_size:
raise ValueError(
"Command sequence and planning context batch sizes must match."
)
if not torch.equal(commands.env_ids, context.env_ids):
raise ValueError("Command sequence env_ids must match the context.")
success_mask = normalize_success_mask(
success,
num_envs=context.batch_size,
device=self.device,
name="Planning success",
)
commands = self._authorize_command_targets(
request,
commands,
active_mask=success_mask,
)
tracking = self._tracking_sequence(request, commands)
segments = self._build_segments(
segment_lengths,
frame_count=commands.frame_count,
)
if diagnostics is None:
diagnostics = PlannerDiagnostics(
backend=self.planning_services.planner_name
)
if (~success_mask).any() and diagnostics.failure is None:
diagnostics = PlannerDiagnostics(
backend=diagnostics.backend,
messages=diagnostics.messages,
metadata=diagnostics.metadata,
failure=PlanningFailure("planning_failed", retryable=True),
)
return SkillPlan(
skill_id=self.skill_id,
plan_success=success_mask,
commands=commands,
recovery_policy=request.recovery_policy,
tracking_policy=request.tracking_policy,
planned_scene_version=context.scene.version,
planned_collision_world_revision=(
context.scene.collision_world_revisions(context.batch_size)
),
diagnostics=diagnostics,
tracking=tracking,
joint_trajectory=joint_trajectory,
segments=segments,
scene_dependencies=self._scene_dependencies(request),
scene_dependency_monitor_until=(
{}
if scene_dependency_monitor_until is None
else scene_dependency_monitor_until
),
scene_dependency_end_segment=scene_dependency_end_segment,
collision_world_sensitive=self._uses_collision_world(request, context),
replannable=replannable,
expected_effects=expected_effects or StateDelta(),
effect_candidates=effect_candidates or StateDelta(),
effect_verification=effect_verification,
invocation_id=request.invocation_id,
invocation_revision=request.revision,
)
def _tracking_sequence(
self,
request: ResolvedSkillRequest[GoalT, OptionsT],
commands: TimedCommandSequence,
) -> TimedTrackingSequence | None:
"""Project command payloads through binding-owned tracking channels."""
policy = request.tracking_policy
metrics = list(() if policy.in_flight is None else policy.in_flight.metrics)
if isinstance(policy.terminal, FeedbackTerminalAcceptance):
metrics.extend(policy.terminal.metrics)
if not metrics:
return None
runtime = self.planning_services.tracking_runtime
for metric in metrics:
runtime.evaluators.resolve(metric)
metrics_by_channel = {metric.channel_id: metric for metric in metrics}
endpoints_by_destination: dict[
tuple[str, str],
tuple[EndpointBinding, ...],
] = {}
for endpoint in request.binding.endpoints:
endpoints_by_destination.setdefault(endpoint.destination_key, ())
endpoints_by_destination[endpoint.destination_key] += (endpoint,)
tracking_frames: list[TrackingFrame] = []
for frame_index, frame in enumerate(commands.frames):
setpoints: list[TrackingSetpoint] = []
for command in frame.commands:
endpoints = endpoints_by_destination[command.destination_key]
for endpoint in endpoints:
# Contact intentionally prevents grasping endpoints from
# reaching their unobstructed close setpoint. Attachment
# and release are accepted by typed effect evidence; joint
# tracking remains authoritative for motion endpoints.
if GRASP_CAPABILITY in endpoint.capabilities:
continue
for channel_id in metrics_by_channel:
channel = endpoint.tracking_channels.get(channel_id)
if channel is None:
continue
runtime.providers.resolve(channel.source)
runtime.projectors.resolve(channel.projector)
setpoints.append(
TrackingSetpoint(
endpoint_key=endpoint.key,
binding=channel,
desired=runtime.project(command, channel),
)
)
covered_channels = {setpoint.binding.channel_id for setpoint in setpoints}
missing_channels = sorted(
set(metrics_by_channel).difference(covered_channels)
)
if missing_channels:
raise ValueError(
f"Command frame {frame_index} cannot project configured "
f"tracking channels {missing_channels}; bound endpoints must "
"declare a typed feedback source and projector."
)
tracking_frames.append(TrackingFrame(tuple(setpoints)))
return TimedTrackingSequence(
env_ids=commands.env_ids,
frames=tuple(tracking_frames),
)
@staticmethod
def _authorize_command_targets(
request: ResolvedSkillRequest[GoalT, OptionsT],
commands: TimedCommandSequence,
*,
active_mask: torch.Tensor | None = None,
) -> TimedCommandSequence:
"""Bind every emitted command to an endpoint authorized by the request.
Actions may choose a subset of their bound endpoints for any frame, but
they cannot synthesize a destination outside the resolved resource
binding. The returned sequence replaces caller-provided target metadata
with the engine-owned binding snapshot, so transports never receive
altered joint claims or other target fields. When ``active_mask`` is
provided, authorization and failed-row masking share the same rebuild.
"""
authorized: dict[tuple[str, str], list[EndpointBinding]] = {}
for endpoint in request.binding.endpoints:
authorized.setdefault(endpoint.destination_key, []).append(endpoint)
unknown = sorted(
{
command.destination_key
for frame in commands.frames
for command in frame.commands
if command.destination_key not in authorized
}
)
if unknown:
raise ValueError(
"Runtime commands reference destinations not authorized by the "
f"action binding: {unknown}."
)
frames: list[RuntimeCommandFrame] = []
for frame in commands.frames:
endpoint_commands: list[EndpointCommand] = []
joint_owners: dict[int, tuple[str, str]] = {}
token_owners: dict[str, tuple[str, str]] = {}
for command in frame.commands:
bound_endpoints = authorized[command.destination_key]
target = bound_endpoints[0].target
if any(
type(endpoint.target) is not type(target)
for endpoint in bound_endpoints[1:]
):
raise ValueError(
f"Action binding destination {command.destination_key} has "
"incompatible target declarations."
)
if type(command.target) is not type(target):
raise TypeError(
f"Runtime command destination {command.destination_key} uses "
f"target type {type(command.target).__name__}, but its bound "
f"endpoint uses {type(target).__name__}."
)
if isinstance(target, JointPositionTarget) and command.target != target:
raise ValueError(
f"Runtime command destination {command.destination_key} "
"does not preserve its bound joint-position target."
)
joint_ids = {
joint_id
for endpoint in bound_endpoints
for joint_id in endpoint.joint_ids
}
claim_tokens = {
token
for endpoint in bound_endpoints
for token in endpoint.claim_tokens
}
overlapping_joints = sorted(joint_ids & joint_owners.keys())
overlapping_tokens = sorted(claim_tokens & token_owners.keys())
if overlapping_joints or overlapping_tokens:
conflicting_destinations = sorted(
{joint_owners[joint_id] for joint_id in overlapping_joints}
| {token_owners[token] for token in overlapping_tokens}
)
raise ValueError(
f"Runtime command destination {command.destination_key} "
f"conflicts with {conflicting_destinations} on bound joint "
f"IDs {overlapping_joints} or claim tokens "
f"{overlapping_tokens}."
)
for joint_id in joint_ids:
joint_owners[joint_id] = command.destination_key
for token in claim_tokens:
token_owners[token] = command.destination_key
endpoint_commands.append(
EndpointCommand(target=target, payload=command.payload)
)
frames.append(
_frame_from_fresh_commands(
endpoint_commands,
active_mask=(
frame.active_mask
if active_mask is None
else frame.active_mask & active_mask
),
env_ids=frame.env_ids,
hold_duration=frame.hold_duration,
)
)
return _sequence_from_fresh_frames(frames, commands.env_ids)
def _joint_command_sequence(
self,
request: ResolvedSkillRequest[GoalT, OptionsT],
trajectory: TimedTrajectory,
*,
active_mask: torch.Tensor,
) -> TimedCommandSequence:
"""Lower one full-robot planner trajectory to endpoint commands."""
targets = tuple(
(
endpoint,
endpoint.require_target(JointPositionTarget),
)
for endpoint in request.binding.endpoints
)
if not targets:
raise ValueError(
"Joint trajectory plans require at least one bound "
"JointPositionTarget endpoint."
)
frames: list[RuntimeCommandFrame] = []
for waypoint_index in range(trajectory.waypoint_count):
endpoint_commands: list[EndpointCommand] = []
for _, target in targets:
joint_ids = list(target.joint_ids)
velocities = (
None
if trajectory.velocities is None
else trajectory.velocities[:, waypoint_index, joint_ids]
)
endpoint_commands.append(
EndpointCommand(
target=target,
payload=JointPositionPayload(
positions=trajectory.positions[
:, waypoint_index, joint_ids
],
velocities=velocities,
),
)
)
next_waypoint_index = min(
waypoint_index + 1,
trajectory.waypoint_count - 1,
)
# ``dt[:, i]`` is the arrival interval for waypoint ``i``. After
# dispatching it, wait for the next arrival interval; the terminal
# frame reuses its own interval as the action's settling window.
frames.append(
_frame_from_fresh_commands(
endpoint_commands,
active_mask=active_mask,
env_ids=trajectory.env_ids,
hold_duration=trajectory.dt[:, next_waypoint_index],
)
)
return _sequence_from_fresh_frames(frames, trajectory.env_ids)
@staticmethod
def _build_segments(
segment_lengths: Mapping[str, int] | None,
*,
frame_count: int,
) -> tuple[TrajectorySegment, ...]:
"""Validate optional named ranges for one command sequence."""
if segment_lengths is None:
return ()
segments: list[TrajectorySegment] = []
offset = 0
for name, length in segment_lengths.items():
if not isinstance(name, str) or not name:
raise ValueError("Trajectory segment names must be non-empty.")
if isinstance(length, bool) or not isinstance(length, int):
raise TypeError("Trajectory segment lengths must be integers.")
if length < 0:
raise ValueError("Trajectory segment lengths must be non-negative.")
if length == 0:
continue
segments.append(
TrajectorySegment(name=name, start=offset, stop=offset + length)
)
offset += length
if offset != frame_count:
raise ValueError(
"Trajectory segment lengths must sum to the command frame count "
f"({frame_count}), got {offset}."
)
return tuple(segments)
[docs]
def failed_plan(
self,
request: ResolvedSkillRequest[GoalT, OptionsT],
context: PlanningContext,
*,
message: str | None = None,
failure_code: str = "planning_failed",
retryable: bool = True,
) -> SkillPlan:
"""Build a failed empty plan without changing task state.
Args:
request: Resolved invocation that failed to plan.
context: Planning input used for the attempt.
message: Optional diagnostic message.
failure_code: Stable machine-readable planning failure code.
retryable: Whether execution may spend action-retry budget on the
failed rows.
Returns:
Failed action plan with an empty trajectory.
"""
success = torch.zeros(context.batch_size, dtype=torch.bool, device=self.device)
diagnostics = PlannerDiagnostics(
backend=self.planning_services.planner_name,
messages=(() if message is None else (message,)),
failure=PlanningFailure(failure_code, retryable=retryable),
)
if request.binding.endpoints and all(
isinstance(endpoint.target, JointPositionTarget)
for endpoint in request.binding.endpoints
):
return self.build_plan(
request,
context,
success=success,
trajectory=TimedTrajectory.empty(
batch_size=context.batch_size,
robot_dof=context.robot.robot_dof,
device=self.device,
env_ids=context.env_ids,
),
replannable=True,
diagnostics=diagnostics,
)
return self.build_command_plan(
request,
context,
success=success,
commands=TimedCommandSequence(frames=(), env_ids=context.env_ids),
replannable=True,
diagnostics=diagnostics,
)
[docs]
def continue_plan(
self,
request: ResolvedSkillRequest,
context: PlanningContext,
plan: SkillPlan,
active_mask: torch.Tensor,
) -> PlanContinuationResult:
"""Plan a later chunk without beginning another logical skill.
Args:
request: The unchanged resolved invocation.
context: Fresh observations with authoritative row identity and timing.
plan: Completed chunk and its owned continuation cursor.
active_mask: Eligible rows that executed the completed chunk.
Returns:
Physical row acceptance and an optional later plan.
"""
raise ValueError(f"Skill {self.skill_id!r} does not support continuation.")
[docs]
def on_plan_installed(
self, request: ResolvedSkillRequest, context: PlanningContext, plan: SkillPlan
) -> None:
"""Publish bookkeeping only after an execution plan was accepted.
Args:
request: The installed plan's resolved invocation.
context: Observations used for this plan.
plan: Validated plan after destination and lifecycle acceptance.
"""
@abstractmethod
def _plan(
self,
request: ResolvedSkillRequest[GoalT, OptionsT],
context: PlanningContext,
) -> SkillPlan:
"""Plan one invocation without stepping simulation or committing state.
Args:
request: Immutable, typed, and embodiment-resolved action request.
context: Latest observed robot, task, and scene state.
Returns:
Scene-bound action plan with expected, uncommitted effects.
"""
__all__ = [
"AtomicSkill",
"CompletePlanBuilder",
"ObjectSemantics",
"SkillDescriptor",
"resolve_runtime_device",
]