File size: 8,417 Bytes
ae96451
 
563e902
ae96451
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
563e902
ae96451
 
 
 
 
563e902
 
 
 
 
 
 
 
 
 
 
 
ae96451
 
 
563e902
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b4c023
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
563e902
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import logging
import json
import os
import pybullet as pb
from llm_panda import config

logger = logging.getLogger(__name__)

class ExecutionMonitor:
    def __init__(self, scene, controller, agent):
        self.scene = scene
        self.controller = controller
        self.agent = agent
        
    def verify_step(self, step, held_before, expected_location, carried_object, pending_target_pos):
        func = step.get("function")
        args = step.get("args", {})
        
        if func != "pick_up" and self.controller.is_stuck():
            return False, f"IK joint stuck during '{func}'"
            
        if func == "pick_up":
            name = args.get("object_id")
            oid = self.scene.name_to_id(name)
            if oid is None:
                return False, f"unknown object '{name}'"
            if carried_object != oid:
                # Rule-based validation from gripper
                return False, f"pick_up('{name}') did not secure the object (gripper missed)"
            pos, _ = pb.getBasePositionAndOrientation(oid)
            if pos[2] < config.TABLE_TOP_Z + 0.05:
                return False, f"'{name}' was not lifted (z={pos[2]:.3f})"
            return True, ""
            
        if func == "move_to":
            if carried_object is None:
                return False, "move_to ended with nothing held"
            target = pending_target_pos
            if target is not None:
                tcp = self.controller.tcp_position()
                d = ((tcp[0] - target[0]) ** 2 + (tcp[1] - target[1]) ** 2) ** 0.5
                if d > 0.12:
                    return False, f"arm stopped {d:.3f} m short of the target XY (likely stuck)"
            return True, ""
            
        if func == "place_down":
            if held_before is None:
                return True, ""
            if carried_object is not None:
                return False, "gripper still holding after place_down"
            pos, _ = pb.getBasePositionAndOrientation(held_before)
            if pos[2] < config.TABLE_TOP_Z - 0.10:
                return False, f"placed object fell off the surface (z={pos[2]:.3f})"
            loc = self.scene.classify_location(pos)
            expected_surface = "table" if expected_location == "buffer" else expected_location
            if expected_surface and loc != expected_surface:
                return False, f"object landed at '{loc}', expected '{expected_surface}'"
            return True, ""
            
        return True, ""
        
    def verify_goal(self, nl_command, scene_state_text, resolved_goal=None):
        """
        Uses LLM (if available) or Rule-based to check if the goal is met.
        Since we might not want to incur an extra API call if not strictly necessary,
        we can delegate to the agent's check_goal method.
        """
        enabled = os.environ.get(
            "STRUCTURED_GOAL_CHECK_ENABLED", "true"
        ).lower() not in {"0", "false", "no", "off"}
        if enabled and resolved_goal is not None:
            result = self._verify_predicates(
                resolved_goal,
                scene_state_text,
                scene=self.scene,
            )
            if result is not None:
                return result
            nl_command = resolved_goal.canonical_instruction
        if hasattr(self.agent, "check_goal"):
            return self.agent.check_goal(nl_command, scene_state_text)
        return True, "Assumed Goal Reached (Agent lacks check_goal method)"

    @staticmethod
    def _verify_predicates(resolved_goal, scene_state_text, scene=None):
        """Evaluate common robot goals without another probabilistic LLM call."""
        try:
            state = (
                json.loads(scene_state_text)
                if isinstance(scene_state_text, str)
                else scene_state_text
            )
        except (TypeError, ValueError, json.JSONDecodeError):
            return None
        if not isinstance(state, dict):
            return None

        objects = {
            obj.get("name"): obj
            for obj in state.get("objects", [])
            if isinstance(obj, dict) and obj.get("name")
        }
        failures = []
        passed = []
        for predicate in resolved_goal.predicates:
            if predicate.type == "carried_object_is":
                actual = state.get("carried_object")
                ok = actual == predicate.object_id
                detail = (
                    f"carried_object={actual!r}, expected {predicate.object_id!r}"
                )
            elif predicate.type == "location_is":
                obj = objects.get(predicate.object_id, {})
                actual = obj.get("location")
                expected = (
                    "table"
                    if predicate.location_id == "buffer"
                    else predicate.location_id
                )
                ok = actual == expected
                detail = (
                    f"{predicate.object_id}.location={actual!r}, expected "
                    f"{expected!r}"
                )
            elif predicate.type == "position_near":
                obj = objects.get(predicate.object_id, {})
                actual_position = obj.get("position")
                target_position = predicate.target_position
                tolerance = predicate.tolerance or 0.04
                same_surface = (
                    not predicate.location_id
                    or obj.get("location") == predicate.location_id
                )
                if (
                    isinstance(actual_position, (list, tuple))
                    and len(actual_position) >= 2
                    and target_position
                    and len(target_position) >= 2
                ):
                    distance = (
                        (actual_position[0] - target_position[0]) ** 2
                        + (actual_position[1] - target_position[1]) ** 2
                    ) ** 0.5
                    ok = distance <= tolerance and same_surface
                else:
                    distance = None
                    ok = False
                detail = (
                    f"{predicate.object_id}.position={actual_position!r}, "
                    f"expected near {target_position!r} "
                    f"(tolerance={tolerance:.3f}, distance={distance!r})"
                )
            elif predicate.type == "relation_is":
                obj = objects.get(predicate.object_id, {})
                relations = obj.get("relations", {}) or {}
                if predicate.relation == "next_to":
                    actual = (obj.get("distances", {}) or {}).get(
                        predicate.relative_to
                    )
                    same_surface = (
                        obj.get("location")
                        == objects.get(predicate.relative_to, {}).get("location")
                    )
                    ok = (
                        isinstance(actual, (int, float))
                        and actual <= max(0.20, config.RELATION_TARGET_GAP * 1.5)
                        and same_surface
                    )
                else:
                    actual = relations.get(predicate.relation)
                    if isinstance(actual, list):
                        ok = predicate.relative_to in actual
                    else:
                        ok = actual == predicate.relative_to
                    if (
                        not ok
                        and predicate.relation == "on_top_of"
                        and scene is not None
                        and hasattr(scene, "is_on_top")
                    ):
                        ok = scene.is_on_top(
                            predicate.object_id,
                            predicate.relative_to,
                        )
                        if ok:
                            actual = "verified_from_live_aabb"
                detail = (
                    f"{predicate.object_id}.{predicate.relation}={actual!r}, "
                    f"expected {predicate.relative_to!r}"
                )
            else:
                return None

            (passed if ok else failures).append(detail)

        if failures:
            return False, "Structured goal failed: " + "; ".join(failures)
        return True, "Structured goal satisfied: " + "; ".join(passed)