C2-151 commited on
Commit
ae96451
·
1 Parent(s): 452c7c6
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .agents/AGENTS.md +7 -1
  2. .agents/skills/dream/.dream-config +2 -0
  3. .agents/skills/dream/SKILL.md +380 -0
  4. .agents/skills/dream/dream-hook.sh +25 -0
  5. .agents/skills/dream/should-dream.sh +60 -0
  6. .env +1 -1
  7. .env.example +3 -2
  8. .gemini/settings.json +11 -0
  9. .history/.env_20260628005020 +16 -0
  10. .history/.env_20260703113045 +16 -0
  11. .pytest_cache/v/cache/lastfailed +5 -2
  12. .pytest_cache/v/cache/nodeids +6 -0
  13. PROJECT_STATUS.md +21 -0
  14. __pycache__/main.cpython-310.pyc +0 -0
  15. envs/default_desk.json +2 -2
  16. envs/env1.json +8 -8
  17. frontend/__pycache__/interactive_server.cpython-310.pyc +0 -0
  18. frontend/app.js +64 -7
  19. frontend/index.html +1 -1
  20. frontend/interactive_server.py +263 -154
  21. llm_panda/__pycache__/__init__.cpython-310.pyc +0 -0
  22. llm_panda/__pycache__/config.cpython-310.pyc +0 -0
  23. llm_panda/__pycache__/cost_map.cpython-310.pyc +0 -0
  24. llm_panda/__pycache__/geofik.cpython-310.pyc +0 -0
  25. llm_panda/__pycache__/grasp_planner.cpython-310.pyc +0 -0
  26. llm_panda/__pycache__/llm_agent.cpython-310.pyc +0 -0
  27. llm_panda/__pycache__/pipeline_executor.cpython-310.pyc +0 -0
  28. llm_panda/__pycache__/plan_verifier.cpython-310.pyc +0 -0
  29. llm_panda/__pycache__/robot_controller.cpython-310.pyc +0 -0
  30. llm_panda/__pycache__/scene_manager.cpython-310.pyc +0 -0
  31. llm_panda/__pycache__/task_nullspace.cpython-310.pyc +0 -0
  32. llm_panda/config.py +2 -2
  33. llm_panda/execution/monitor.py +69 -0
  34. llm_panda/execution/pipeline.py +57 -62
  35. llm_panda/geofik.py +21 -0
  36. llm_panda/grasp_planner.py +11 -1
  37. llm_panda/llm_agent.py +145 -17
  38. llm_panda/robot_controller.py +99 -53
  39. llm_panda/safety_guardrails.py +240 -0
  40. llm_panda/scene_manager.py +84 -0
  41. main.py +59 -1
  42. temp_dream_skill +1 -0
  43. test_llm_planner.py +429 -0
  44. tests/__pycache__/test_geofik.cpython-310-pytest-8.3.5.pyc +0 -0
  45. tests/__pycache__/test_llm_plan.cpython-310-pytest-8.3.5.pyc +0 -0
  46. tests/__pycache__/test_new_pipeline.cpython-310-pytest-8.3.5.pyc +0 -0
  47. tests/__pycache__/test_occupancy.cpython-310-pytest-8.3.5.pyc +0 -0
  48. tests/__pycache__/test_pipeline.cpython-310-pytest-8.3.5.pyc +0 -0
  49. tests/__pycache__/test_task_nullspace.cpython-310-pytest-8.3.5.pyc +0 -0
  50. tests/test_llm_expected.json +90 -2
.agents/AGENTS.md CHANGED
@@ -1,2 +1,8 @@
1
-
2
  - DO NOT delete any files in the repository unless the user gives an explicit and unambiguous command to do so. If the command is ambiguous, ignore the request to delete or ask for confirmation.
 
 
 
 
 
 
 
1
+
2
  - DO NOT delete any files in the repository unless the user gives an explicit and unambiguous command to do so. If the command is ambiguous, ignore the request to delete or ask for confirmation.
3
+
4
+
5
+ ## Memory Consolidation (Auto-Dream)
6
+ - **Condition**: If the file `C:/Users/admin/.gemini/.dream-pending` or `C:/Users/admin/.claude/.dream-pending` exists at session start, you MUST run the `dream` memory consolidation skill immediately.
7
+ - **Action**: Read the consolidation instructions in `skills/dream/SKILL.md` (or workspace `.agents/skills/dream/SKILL.md`) and run all 4 phases of memory consolidation for the current project.
8
+ - **Cleanup**: After successful consolidation, delete the flag files (`rm C:/Users/admin/.gemini/.dream-pending` and `rm C:/Users/admin/.claude/.dream-pending` if they exist).
.agents/skills/dream/.dream-config ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ DREAM_MEMORY_TYPE=project-root
2
+ DREAM_MEMORY_PATH=C:/Users/admin/C2-App-151
.agents/skills/dream/SKILL.md ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: dream
3
+ description: "Memory consolidation skill for Claude Code. Scans session transcripts for corrections, decisions, preferences, and patterns, then merges findings into persistent memory files. Auto-triggers via native Stop hook every 24hrs. Inspired by how sleep consolidates human memory."
4
+ tags: [memory, maintenance, consolidation, autonomous, hook]
5
+ ---
6
+
7
+ # Dream - Memory Consolidation for Claude Code
8
+
9
+ > Your AI agent dreams like you do. Consolidates memory while you sleep.
10
+
11
+ ---
12
+
13
+
14
+ ### Step 1: Detect memory system
15
+
16
+ Before anything else, detect which memory system is in use. Run these checks:
17
+
18
+ ```bash
19
+ # Check 1: Native Claude Code auto-memory
20
+ ls ~/.claude/projects/*/memory/MEMORY.md 2>/dev/null && echo "DETECTED: native-claude-code"
21
+
22
+ # Check 2: OpenClaw-style (memory/ folder in project root with daily logs)
23
+ ls ./memory/20*.md 2>/dev/null && echo "DETECTED: openclaw-daily-logs"
24
+
25
+ # Check 3: Project-root MEMORY.md (custom setup)
26
+ ls ./MEMORY.md 2>/dev/null && echo "DETECTED: project-root-memory"
27
+
28
+ # Check 4: Nothing found
29
+ echo "If none detected above: no memory system found"
30
+ ```
31
+
32
+ **Based on what you detect, set DREAM_MEMORY_TYPE:**
33
+
34
+ | Detection | DREAM_MEMORY_TYPE | Memory location | Session transcripts |
35
+ |-----------|-------------------|-----------------|-------------------|
36
+ | `~/.claude/projects/*/memory/MEMORY.md` exists | `native` | `~/.claude/projects/<project>/memory/` | `~/.claude/projects/<project>/sessions/*.jsonl` |
37
+ | `./memory/20*.md` daily log files exist | `openclaw` | `./memory/` (project root) | `~/.claude/projects/<project>/sessions/*.jsonl` |
38
+ | `./MEMORY.md` exists in project root | `project-root` | `./` (project root, MEMORY.md + topic files) | `~/.claude/projects/<project>/sessions/*.jsonl` |
39
+ | Nothing found | `native` (default) | `~/.claude/projects/<project>/memory/` | `~/.claude/projects/<project>/sessions/*.jsonl` |
40
+
41
+ **If no memory system is found, default to native Claude Code memory.** This is the standard and requires no extra setup - Claude Code creates the directory automatically when auto-memory is enabled.
42
+
43
+ Write the detected type to the config so dream knows where to look:
44
+ ```bash
45
+ echo "DREAM_MEMORY_TYPE=native" > ~/.claude/skills/dream/.dream-config
46
+ echo "DREAM_MEMORY_PATH=~/.claude/projects" >> ~/.claude/skills/dream/.dream-config
47
+ ```
48
+
49
+ Replace `native` with `openclaw` or `project-root` if that's what was detected. For `openclaw` or `project-root`, also set the path:
50
+ ```bash
51
+ # For openclaw:
52
+ echo "DREAM_MEMORY_TYPE=openclaw" > ~/.claude/skills/dream/.dream-config
53
+ echo "DREAM_MEMORY_PATH=$(pwd)/memory" >> ~/.claude/skills/dream/.dream-config
54
+
55
+ # For project-root:
56
+ echo "DREAM_MEMORY_TYPE=project-root" > ~/.claude/skills/dream/.dream-config
57
+ echo "DREAM_MEMORY_PATH=$(pwd)" >> ~/.claude/skills/dream/.dream-config
58
+ ```
59
+
60
+ ### Step 2: Install the Stop hook
61
+
62
+ Add the dream trigger to your Claude Code settings:
63
+
64
+ ```bash
65
+ SETTINGS="$HOME/.claude/settings.json"
66
+ [ ! -f "$SETTINGS" ] && echo '{}' > "$SETTINGS"
67
+
68
+ python3 -c "
69
+ import json
70
+ with open('$HOME/.claude/settings.json') as f:
71
+ s = json.load(f)
72
+ s.setdefault('hooks', {}).setdefault('Stop', [])
73
+ if not any('dream' in h.get('command','') for h in s['hooks']['Stop']):
74
+ s['hooks']['Stop'].append({
75
+ 'type': 'command',
76
+ 'command': 'bash \$HOME/.claude/skills/dream/should-dream.sh && touch \$HOME/.claude/.dream-pending || true'
77
+ })
78
+ with open('$HOME/.claude/settings.json', 'w') as f:
79
+ json.dump(s, f, indent=2)
80
+ f.write('\n')
81
+ print('Stop hook installed')
82
+ "
83
+ ```
84
+
85
+ **What this does:** When you exit any Claude Code session, the Stop hook checks if 24+ hours have passed since the last dream. If yes, it creates a `.dream-pending` flag file. On your next session start, Claude sees the flag and runs `/dream` as a background subagent.
86
+
87
+ ### Step 3: Install the session-start check
88
+
89
+ Add this to your global `~/.claude/CLAUDE.md` (or project CLAUDE.md):
90
+
91
+ ```markdown
92
+ ## Auto Dream
93
+ If the file `~/.claude/.dream-pending` exists at session start, run `/dream` as a subagent in the background, then delete the flag file: `rm ~/.claude/.dream-pending`. This is the memory consolidation system - it runs automatically every 24 hours.
94
+ ```
95
+
96
+ ### Step 4: Make should-dream.sh executable
97
+
98
+ ```bash
99
+ chmod +x ~/.claude/skills/dream/should-dream.sh
100
+ ```
101
+
102
+ ### Step 5: Test it
103
+
104
+ Run a test dream to verify the full flow:
105
+
106
+ ```bash
107
+ # Force the dream to trigger by creating the flag
108
+ touch ~/.claude/.dream-pending
109
+ ```
110
+
111
+ Then tell Claude: "The .dream-pending flag exists. Run /dream now."
112
+
113
+ After it completes, verify:
114
+ - The flag file `~/.claude/.dream-pending` was deleted
115
+ - Memory files were reviewed and consolidated
116
+ - A `.last-dream` timestamp was written in the memory directory
117
+ - No relative dates remain in memory files
118
+ - MEMORY.md index is under 200 lines
119
+
120
+ ### Step 6: Clean up onboarding
121
+
122
+ Everything is working. Now delete this entire ONBOARDING section from this SKILL.md file (everything between `## ONBOARDING` and `## END ONBOARDING`). The skill is fully set up and will auto-trigger every 24 hours via the Stop hook.
123
+
124
+ ## END ONBOARDING
125
+
126
+ ---
127
+
128
+ ## How It Works
129
+
130
+ Dream runs in 4 sequential phases. Execute them in order. Do not skip phases.
131
+
132
+ ```
133
+ ORIENT --> GATHER SIGNAL --> CONSOLIDATE --> PRUNE & INDEX
134
+ ```
135
+
136
+ ### Auto-trigger flow (native Claude Code hooks)
137
+
138
+ ```
139
+ Session ends
140
+ --> Stop hook fires should-dream.sh (~10ms)
141
+ --> Checks: 24hrs passed? 5+ sessions?
142
+ --> If NO: exits silently, zero overhead
143
+ --> If YES: creates ~/.claude/.dream-pending flag
144
+ Next session starts
145
+ --> Claude reads CLAUDE.md, sees .dream-pending exists
146
+ --> Spawns /dream as background subagent
147
+ --> Dream runs all 4 phases
148
+ --> Writes .last-dream timestamp, deletes .dream-pending
149
+ --> Timer resets for next 24hrs
150
+ ```
151
+
152
+ ---
153
+
154
+ ## Phase 1: ORIENT
155
+
156
+ **Goal:** Understand the current state of memory before changing anything.
157
+
158
+ ### Step 0: Read config
159
+
160
+ ```bash
161
+ cat ~/.claude/skills/dream/.dream-config 2>/dev/null || echo "DREAM_MEMORY_TYPE=native"
162
+ ```
163
+
164
+ This tells you which memory system to target:
165
+ - `native` - scan `~/.claude/projects/*/memory/`
166
+ - `openclaw` - scan the `memory/` folder in the project root (daily logs + MEMORY.md)
167
+ - `project-root` - scan MEMORY.md and topic files in the project root
168
+
169
+ ### Steps
170
+
171
+ 1. Find memory directories based on type:
172
+ ```bash
173
+ # native (default)
174
+ ls -d ~/.claude/projects/*/memory/ 2>/dev/null
175
+
176
+ # openclaw
177
+ ls ./memory/ 2>/dev/null
178
+
179
+ # project-root
180
+ ls ./MEMORY.md ./memory/ 2>/dev/null
181
+ ```
182
+
183
+ 2. Read the memory directory for the detected type:
184
+ ```bash
185
+ # native
186
+ ls ~/.claude/projects/*/memory/ 2>/dev/null
187
+
188
+ # openclaw - also list daily logs
189
+ ls ./memory/*.md 2>/dev/null
190
+ ```
191
+
192
+ 3. Read `MEMORY.md` (the index file) in each project's memory directory. Note:
193
+ - How many topic files exist
194
+ - Total line count of MEMORY.md
195
+ - Last modified dates
196
+ - Any entries that look stale (relative dates like "yesterday", "last week" with no anchor)
197
+
198
+ 4. Read each topic file to understand what's already stored.
199
+
200
+ ### Output of this phase
201
+ You should now have a mental map of:
202
+ - Which projects have memory
203
+ - What topics are covered
204
+ - How large the memory files are
205
+ - What's potentially stale or contradictory
206
+
207
+ ---
208
+
209
+ ## Phase 2: GATHER SIGNAL
210
+
211
+ **Goal:** Extract important information from recent sessions without reading everything.
212
+
213
+ ### Where to find transcripts
214
+ ```bash
215
+ find ~/.claude/projects/*/sessions/ -name "*.jsonl" -mtime -7 2>/dev/null | sort -t/ -k6 -r
216
+ ```
217
+
218
+ This finds JSONL session files modified in the last 7 days, sorted newest first. Adjust `-mtime -7` for different windows.
219
+
220
+ ### What to scan for
221
+
222
+ Use targeted grep, not full reads. Each pattern targets a specific signal type:
223
+
224
+ **User corrections** (highest priority):
225
+ ```bash
226
+ grep -il "actually\|no,\|wrong\|incorrect\|not right\|stop doing\|don't do\|I said\|I meant\|that's not\|correction" ~/.claude/projects/*/sessions/*.jsonl 2>/dev/null
227
+ ```
228
+
229
+ **Preferences and configuration:**
230
+ ```bash
231
+ grep -il "I prefer\|always use\|never use\|I like\|I don't like\|I want\|from now on\|going forward\|remember that\|keep in mind\|make sure to\|default to" ~/.claude/projects/*/sessions/*.jsonl 2>/dev/null
232
+ ```
233
+
234
+ **Important decisions:**
235
+ ```bash
236
+ grep -il "let's go with\|I decided\|we're using\|the plan is\|switch to\|move to\|chosen\|picked\|decision\|we agreed" ~/.claude/projects/*/sessions/*.jsonl 2>/dev/null
237
+ ```
238
+
239
+ **Recurring patterns:**
240
+ ```bash
241
+ grep -il "again\|every time\|keep forgetting\|as usual\|same as before\|like last time\|we always\|the usual" ~/.claude/projects/*/sessions/*.jsonl 2>/dev/null
242
+ ```
243
+
244
+ ### How to read matches
245
+
246
+ For each file that matches, read ONLY the surrounding context of the match (not the full session). JSONL files have one JSON object per line. Focus on lines where `type` is `"human"` (user messages) and the immediately following `"assistant"` response.
247
+
248
+ ```bash
249
+ grep -n "I prefer\|always use\|never use" <session_file> | head -20
250
+ ```
251
+
252
+ ### What to extract
253
+
254
+ For each finding, note:
255
+ - **The fact** - What was said or decided
256
+ - **The date** - Derive from the session file's modification time
257
+ - **Confidence** - Was it an explicit instruction (high) or implied preference (medium)?
258
+ - **Contradictions** - Does this conflict with anything currently in memory?
259
+
260
+ ---
261
+
262
+ ## Phase 3: CONSOLIDATE
263
+
264
+ **Goal:** Merge new findings into existing memory. This is the most delicate phase.
265
+
266
+ ### Rules
267
+
268
+ 1. **Never duplicate.** Before adding anything, check if it already exists in memory. If it does, update the existing entry rather than creating a new one.
269
+
270
+ 2. **Convert relative dates to absolute.** If a session from March 15 says "yesterday I changed the API key", write "2026-03-14: Changed API key" in memory. Never store "yesterday" or "last week".
271
+
272
+ 3. **Delete contradicted facts.** If memory says "Prefers tabs" but a recent session has the user saying "Use spaces", remove the old entry and write the new one. Add a note: `(Updated YYYY-MM-DD, previously: tabs)`.
273
+
274
+ 4. **Preserve source attribution.** When adding a new memory entry, note where it came from: `(from session YYYY-MM-DD)`.
275
+
276
+ 5. **Topic file organization.** Group related memories into topic files:
277
+ - `preferences.md` - How the user likes things done
278
+ - `decisions.md` - Choices and their rationale
279
+ - `corrections.md` - Things the user corrected
280
+ - `patterns.md` - Recurring workflows, common tasks
281
+ - `facts.md` - Project-specific knowledge, architecture notes
282
+ - Create new topic files only when existing ones don't fit
283
+
284
+ 6. **Entry format.** Each memory entry should be concise:
285
+ ```markdown
286
+ - [YYYY-MM-DD] The fact or preference. (source: session, confidence: high/medium)
287
+ ```
288
+
289
+ ### How to write
290
+
291
+ Use the Edit tool to modify existing memory files, or Write to create new topic files. Always read a file before editing it.
292
+
293
+ ---
294
+
295
+ ## Phase 4: PRUNE & INDEX
296
+
297
+ **Goal:** Keep MEMORY.md as a lean index. Remove stale content. Enforce size limits.
298
+
299
+ ### MEMORY.md rules
300
+
301
+ MEMORY.md is an **index file**, not a content store. It should contain:
302
+ - Links/references to topic files
303
+ - A brief (one-line) summary of what each topic file contains
304
+ - The last-updated date for each topic file
305
+
306
+ MEMORY.md should **never** contain:
307
+ - Full memory entries (those go in topic files)
308
+ - Verbose descriptions
309
+ - Duplicate content that exists in topic files
310
+
311
+ ### Size limit: 200 lines
312
+
313
+ If MEMORY.md exceeds 200 lines after consolidation:
314
+ 1. Move any inline content to the appropriate topic file
315
+ 2. Replace verbose entries with one-line summaries + links
316
+ 3. Remove entries that point to deleted or empty topic files
317
+ 4. If still over 200 lines, demote the oldest entries to an `archive.md` topic file
318
+
319
+ ### Prune stale entries
320
+
321
+ Remove or archive entries that are:
322
+ - More than 90 days old with no references in recent sessions
323
+ - Contradicted by newer entries (should have been caught in Phase 3)
324
+ - About projects/repos that no longer exist in `~/.claude/projects/`
325
+
326
+ ### Final index format
327
+
328
+ ```markdown
329
+ # Memory Index
330
+
331
+ Last consolidated: YYYY-MM-DD
332
+
333
+ ## Topic Files
334
+
335
+ | File | Summary | Updated |
336
+ |------|---------|---------|
337
+ | preferences.md | Editor, formatting, communication style preferences | YYYY-MM-DD |
338
+ | decisions.md | Architecture choices, tool selections, project direction | YYYY-MM-DD |
339
+ | corrections.md | Past mistakes to avoid repeating | YYYY-MM-DD |
340
+ | patterns.md | Common workflows and recurring tasks | YYYY-MM-DD |
341
+ | facts.md | Project knowledge, API details, system architecture | YYYY-MM-DD |
342
+
343
+ ## Quick Reference
344
+
345
+ <!-- Only the 5-10 MOST important facts that affect every session -->
346
+ - Fact 1
347
+ - Fact 2
348
+ ```
349
+
350
+ The Quick Reference section is for facts so important they should be seen every time memory is loaded. Keep it to 10 items maximum.
351
+
352
+ ### Record the dream timestamp
353
+
354
+ After completing all 4 phases, write timestamps so the auto-trigger knows when you last dreamed:
355
+ ```bash
356
+ date +%s > ~/.claude/projects/<project>/memory/.last-dream
357
+ rm -f ~/.claude/.dream-pending
358
+ ```
359
+
360
+ ---
361
+
362
+ ## Safety
363
+
364
+ - **Never delete memory without replacement.** If removing an entry, either it was contradicted (replaced by a newer entry) or it was moved (to a topic file or archive). Never just delete.
365
+ - **Back up before first run.** On the very first run against a project, copy the memory directory:
366
+ ```bash
367
+ cp -r ~/.claude/projects/<project>/memory/ ~/.claude/projects/<project>/memory-backup-$(date +%Y%m%d)/
368
+ ```
369
+ - **Dry run option.** On first use, read through all 4 phases but only print what you WOULD change, without writing. Confirm with the user before applying.
370
+
371
+ ---
372
+
373
+ ## Verification
374
+
375
+ After running, verify the consolidation:
376
+ 1. `wc -l` on MEMORY.md - should be under 200 lines
377
+ 2. Check that no topic file has duplicate entries
378
+ 3. Confirm no relative dates remain ("yesterday", "last week", etc.)
379
+ 4. Verify all topic files referenced in MEMORY.md actually exist
380
+ 5. Print a summary: entries added, entries updated, entries archived, contradictions resolved
.agents/skills/dream/dream-hook.sh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # dream-hook.sh - Session end hook
3
+
4
+ if [[ -d "$HOME/.gemini/config/skills/dream" ]]; then
5
+ SKILL_DIR="$HOME/.gemini/config/skills/dream"
6
+ elif [[ -d "$HOME/.claude/skills/dream" ]]; then
7
+ SKILL_DIR="$HOME/.claude/skills/dream"
8
+ else
9
+ SKILL_DIR="$(cd "$(dirname "$0")" && pwd)"
10
+ fi
11
+
12
+ if bash "$SKILL_DIR/should-dream.sh" 2>/dev/null; then
13
+ # Touch the pending file for Gemini and Claude
14
+ touch "$HOME/.gemini/.dream-pending" 2>/dev/null || true
15
+ touch "$HOME/.claude/.dream-pending" 2>/dev/null || true
16
+
17
+ # If Claude CLI is installed, we can trigger background Claude consolidation
18
+ if command -v claude >/dev/null 2>&1; then
19
+ nohup claude -p "Run the dream memory consolidation skill. Read ~/.claude/skills/dream/SKILL.md and execute all 4 phases for all projects." \
20
+ --allowedTools "Read,Write,Edit,Bash,Glob,Grep" \
21
+ > /tmp/dream-$(date +%Y%m%d-%H%M%S).log 2>&1 &
22
+ fi
23
+ fi
24
+
25
+ exit 0
.agents/skills/dream/should-dream.sh ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # should-dream.sh - Check if dream consolidation should run
3
+ # Returns exit code 0 if dream should run, 1 if not.
4
+ # Condition: 24+ hours since last consolidation.
5
+
6
+ set -euo pipefail
7
+
8
+ # Support both .gemini and .claude
9
+ if [[ -d "$HOME/.gemini/config/skills/dream" ]]; then
10
+ SKILL_DIR="$HOME/.gemini/config/skills/dream"
11
+ elif [[ -d "$HOME/.claude/skills/dream" ]]; then
12
+ SKILL_DIR="$HOME/.claude/skills/dream"
13
+ else
14
+ SKILL_DIR="$(cd "$(dirname "$0")" && pwd)"
15
+ fi
16
+
17
+ CONFIG="$SKILL_DIR/.dream-config"
18
+
19
+ # Read config or default to project-root if no Claude projects
20
+ DREAM_MEMORY_TYPE="project-root"
21
+ if [[ -f "$CONFIG" ]]; then
22
+ DREAM_MEMORY_TYPE=$(grep '^DREAM_MEMORY_TYPE=' "$CONFIG" | cut -d= -f2 || echo "project-root")
23
+ fi
24
+
25
+ LAST_DREAM_FILE=""
26
+ case "$DREAM_MEMORY_TYPE" in
27
+ native)
28
+ for dir in "$HOME/.claude/projects/"*/memory/; do
29
+ if [[ -f "$dir/.last-dream" ]]; then
30
+ LAST_DREAM_FILE="$dir/.last-dream"
31
+ break
32
+ fi
33
+ done
34
+ if [[ -z "$LAST_DREAM_FILE" ]]; then
35
+ echo "Dream conditions met: first-run (no .last-dream found)"
36
+ exit 0
37
+ fi
38
+ ;;
39
+ openclaw|project-root)
40
+ DREAM_MEMORY_PATH=$(grep '^DREAM_MEMORY_PATH=' "$CONFIG" | cut -d= -f2 || echo ".")
41
+ DREAM_MEMORY_PATH="${DREAM_MEMORY_PATH/#\~/$HOME}"
42
+ LAST_DREAM_FILE="$DREAM_MEMORY_PATH/.last-dream"
43
+ if [[ ! -f "$LAST_DREAM_FILE" ]]; then
44
+ echo "Dream conditions met: first-run"
45
+ exit 0
46
+ fi
47
+ ;;
48
+ esac
49
+
50
+ LAST_DREAM=$(cat "$LAST_DREAM_FILE")
51
+ NOW=$(date +%s)
52
+ ELAPSED=$(( NOW - LAST_DREAM ))
53
+ HOURS_ELAPSED=$(( ELAPSED / 3600 ))
54
+
55
+ if (( HOURS_ELAPSED < 24 )); then
56
+ exit 1 # Too soon
57
+ fi
58
+
59
+ echo "Dream conditions met: ${HOURS_ELAPSED}h since last dream"
60
+ exit 0
.env CHANGED
@@ -1,5 +1,5 @@
1
  # Choose one or both providers
2
- OPENAI_API_KEY=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
3
  OPENAI_BASE_URL=https://openrouter.ai/api/v1
4
  OPENAI_MODEL=deepseek/deepseek-v4-flash
5
 
 
1
  # Choose one or both providers
2
+ OPENAI_API_KEY=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
3
  OPENAI_BASE_URL=https://openrouter.ai/api/v1
4
  OPENAI_MODEL=deepseek/deepseek-v4-flash
5
 
.env.example CHANGED
@@ -1,6 +1,7 @@
1
  # Choose one or both providers
2
- ANTHROPIC_API_KEY=sk-ant-...
3
- OPENAI_API_KEY=sk-...
 
4
 
5
  # Default model
6
  DEFAULT_MODEL=claude-sonnet-4-20250514
 
1
  # Choose one or both providers
2
+ OPENAI_API_KEY= ...
3
+ OPENAI_BASE_URL=https://openrouter.ai/api/v1
4
+ OPENAI_MODEL=deepseek/deepseek-v4-flash
5
 
6
  # Default model
7
  DEFAULT_MODEL=claude-sonnet-4-20250514
.gemini/settings.json CHANGED
@@ -36,6 +36,17 @@
36
  "timeout": 10000
37
  }
38
  ]
 
 
 
 
 
 
 
 
 
 
 
39
  }
40
  ]
41
  }
 
36
  "timeout": 10000
37
  }
38
  ]
39
+ },
40
+ {
41
+ "matcher": ".*",
42
+ "hooks": [
43
+ {
44
+ "name": "dream-hook",
45
+ "type": "command",
46
+ "command": "bash -c 'bash ~/.gemini/config/skills/dream/dream-hook.sh || true'",
47
+ "timeout": 10000
48
+ }
49
+ ]
50
  }
51
  ]
52
  }
.history/.env_20260628005020 ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Choose one or both providers
2
+ OPENAI_API_KEY=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
3
+ OPENAI_BASE_URL=https://openrouter.ai/api/v1
4
+ OPENAI_MODEL=deepseek/deepseek-v4-flash
5
+
6
+ # Default model
7
+ DEFAULT_MODEL=claude-sonnet-4-20250514
8
+ # DEFAULT_MODEL=gpt-4o
9
+
10
+ # Logging
11
+ LOG_LEVEL=INFO
12
+
13
+ # AI Hook Logging (set by instructor)
14
+ AI_LOG_SERVER=https://ai-logs.note.transformerlabs.ai/api/ingest
15
+ AI_LOG_API_KEY=ai20k__9Mr6_Jl3j3E0JKOiFh499mhxzSl0A47
16
+ AI_LOG_DIR=.ai-log
.history/.env_20260703113045 ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Choose one or both providers
2
+ OPENAI_API_KEY=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
3
+ OPENAI_BASE_URL=https://openrouter.ai/api/v1
4
+ OPENAI_MODEL=deepseek/deepseek-v4-flash
5
+
6
+ # Default model
7
+ DEFAULT_MODEL=claude-sonnet-4-20250514
8
+ # DEFAULT_MODEL=gpt-4o
9
+
10
+ # Logging
11
+ LOG_LEVEL=INFO
12
+
13
+ # AI Hook Logging (set by instructor)
14
+ AI_LOG_SERVER=https://ai-logs.note.transformerlabs.ai/api/ingest
15
+ AI_LOG_API_KEY=ai20k__9Mr6_Jl3j3E0JKOiFh499mhxzSl0A47
16
+ AI_LOG_DIR=.ai-log
.pytest_cache/v/cache/lastfailed CHANGED
@@ -1,6 +1,9 @@
1
  {
2
  "tests/test_new_pipeline.py::test_pipeline_executor_completes_pick_and_place": true,
3
- "tests/test_auto.py": true,
4
  "tests/test_geofik.py": true,
5
- "tests/test_new_pipeline.py": true
 
 
 
 
6
  }
 
1
  {
2
  "tests/test_new_pipeline.py::test_pipeline_executor_completes_pick_and_place": true,
 
3
  "tests/test_geofik.py": true,
4
+ "tests/test_new_pipeline.py::test_mesh_parser_loads_obj": true,
5
+ "tests/test_new_pipeline.py::test_contact_sampler_antipodal_constraints": true,
6
+ "tests/test_new_pipeline.py::test_grasp_candidate_generator": true,
7
+ "tests/test_new_pipeline.py::test_rrt_connect_planner_finds_path": true,
8
+ "tests/test_pipeline.py::test_grasp_survives_fast_translation": true
9
  }
.pytest_cache/v/cache/nodeids CHANGED
@@ -15,6 +15,7 @@
15
  "tests/test_geofik.py::test_franka_geometry",
16
  "tests/test_geofik.py::test_rotations",
17
  "tests/test_geofik.py::test_wrap_angle",
 
18
  "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_1_g\\u1eafp qu\\u1ea3 chu\\u1ed1i l\\xean]",
19
  "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_2_di chuy\\u1ec3n lon s\\xfap v\\xe0o Slot_3]",
20
  "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_2_g\\u1eafp lon s\\xfap \\u0111\\u1eb7t l\\xean b\\xe0n]",
@@ -26,6 +27,9 @@
26
  "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_5_g\\u1eafp con m\\xe8o l\\xean]",
27
  "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_6_g\\u1eafp lon chips \\u0111\\u1eb7t c\\u1ea1nh qu\\u1ea3 chu\\u1ed1i]",
28
  "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_7_d\\u1ecdn b\\xe0n \\u0111i]",
 
 
 
29
  "tests/test_llm_plan.py::test_rule_based_planner_expected[Case_1_g\\u1eafp qu\\u1ea3 chu\\u1ed1i l\\xean]",
30
  "tests/test_llm_plan.py::test_rule_based_planner_expected[Case_2_di chuy\\u1ec3n lon s\\xfap v\\xe0o Slot_3]",
31
  "tests/test_llm_plan.py::test_rule_based_planner_expected[Case_2_g\\u1eafp lon s\\xfap \\u0111\\u1eb7t l\\xean b\\xe0n]",
@@ -37,6 +41,8 @@
37
  "tests/test_llm_plan.py::test_rule_based_planner_expected[Case_5_g\\u1eafp con m\\xe8o l\\xean]",
38
  "tests/test_llm_plan.py::test_rule_based_planner_expected[Case_6_g\\u1eafp lon chips \\u0111\\u1eb7t c\\u1ea1nh qu\\u1ea3 chu\\u1ed1i]",
39
  "tests/test_llm_plan.py::test_rule_based_planner_expected[Case_7_d\\u1ecdn b\\xe0n \\u0111i]",
 
 
40
  "tests/test_monitor.py::test_monitor_aborts_when_replan_repeats_failing_plan",
41
  "tests/test_monitor.py::test_monitor_replans_until_attempts_exhausted",
42
  "tests/test_monitor.py::test_monitor_stops_on_success",
 
15
  "tests/test_geofik.py::test_franka_geometry",
16
  "tests/test_geofik.py::test_rotations",
17
  "tests/test_geofik.py::test_wrap_angle",
18
+ "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_10_g\\u1eafp lon s\\xfap]",
19
  "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_1_g\\u1eafp qu\\u1ea3 chu\\u1ed1i l\\xean]",
20
  "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_2_di chuy\\u1ec3n lon s\\xfap v\\xe0o Slot_3]",
21
  "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_2_g\\u1eafp lon s\\xfap \\u0111\\u1eb7t l\\xean b\\xe0n]",
 
27
  "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_5_g\\u1eafp con m\\xe8o l\\xean]",
28
  "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_6_g\\u1eafp lon chips \\u0111\\u1eb7t c\\u1ea1nh qu\\u1ea3 chu\\u1ed1i]",
29
  "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_7_d\\u1ecdn b\\xe0n \\u0111i]",
30
+ "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_8_g\\u1eafp v\\u1eadt n\\u1eb1m b\\xean tr\\xe1i qu\\u1ea3 chu\\u1ed1i \\u0111\\u1eb7t v\\xe0o khay]",
31
+ "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_9_\\u0111\\u1eb7t qu\\u1ea3 chu\\u1ed1i l\\xean tr\\xean lon s\\xfap]",
32
+ "tests/test_llm_plan.py::test_rule_based_planner_expected[Case_10_g\\u1eafp lon s\\xfap]",
33
  "tests/test_llm_plan.py::test_rule_based_planner_expected[Case_1_g\\u1eafp qu\\u1ea3 chu\\u1ed1i l\\xean]",
34
  "tests/test_llm_plan.py::test_rule_based_planner_expected[Case_2_di chuy\\u1ec3n lon s\\xfap v\\xe0o Slot_3]",
35
  "tests/test_llm_plan.py::test_rule_based_planner_expected[Case_2_g\\u1eafp lon s\\xfap \\u0111\\u1eb7t l\\xean b\\xe0n]",
 
41
  "tests/test_llm_plan.py::test_rule_based_planner_expected[Case_5_g\\u1eafp con m\\xe8o l\\xean]",
42
  "tests/test_llm_plan.py::test_rule_based_planner_expected[Case_6_g\\u1eafp lon chips \\u0111\\u1eb7t c\\u1ea1nh qu\\u1ea3 chu\\u1ed1i]",
43
  "tests/test_llm_plan.py::test_rule_based_planner_expected[Case_7_d\\u1ecdn b\\xe0n \\u0111i]",
44
+ "tests/test_llm_plan.py::test_rule_based_planner_expected[Case_8_g\\u1eafp v\\u1eadt n\\u1eb1m b\\xean tr\\xe1i qu\\u1ea3 chu\\u1ed1i \\u0111\\u1eb7t v\\xe0o khay]",
45
+ "tests/test_llm_plan.py::test_rule_based_planner_expected[Case_9_\\u0111\\u1eb7t qu\\u1ea3 chu\\u1ed1i l\\xean tr\\xean lon s\\xfap]",
46
  "tests/test_monitor.py::test_monitor_aborts_when_replan_repeats_failing_plan",
47
  "tests/test_monitor.py::test_monitor_replans_until_attempts_exhausted",
48
  "tests/test_monitor.py::test_monitor_stops_on_success",
PROJECT_STATUS.md ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Tổng quan tình trạng dự án
2
+
3
+ Dựa trên các đánh giá hiện tại, dưới đây là tổng hợp các vấn đề trong dự án được phân loại theo từng nhóm:
4
+
5
+ ## 1. Tình trạng hệ thống hiện tại (Current State)
6
+ * **Điểm mạnh:** Mô hình ngôn ngữ lớn (LLM) hiện tại đã có khả năng nắm bắt và hiểu được toàn bộ thông tin về môi trường xung quanh.
7
+
8
+ ## 2. Các vấn đề đang gặp phải cần khắc phục (Current Issues)
9
+ * **Lỗi vị trí gắp của Robot:** Robot hiện đang thực hiện thao tác gắp (grasping) không sát với thực tế, cụ thể là chọn sai vị trí để gắp đồ vật.
10
+ * **Thuật toán tránh va chạm (Motion Planning) chưa hoàn thiện:** Khi sử dụng thuật toán A* để tìm đường đi tránh vật cản, hệ thống hiện tại mới chỉ tính toán đường đi chung mà chưa đưa toàn bộ hình học của "cánh tay robot" (các khớp, các đoạn của cánh tay) vào để xét va chạm. Điều này có thể dẫn đến việc cánh tay va quệt vào vật thể xung quanh dù điểm cuối (end-effector) không chạm.
11
+
12
+ ## 3. Các mục tiêu có hướng giải quyết (Achievable Goals / In-Scope)
13
+ Đây là những vấn đề đã xác định là **có thể giải quyết được (Giải được / Làm được)** trong thời gian tới:
14
+ * **Vòng lặp kiểm tra và lên kế hoạch lại (Closed-loop Execution):** Sau khi robot thực hiện xong một hành động, LLM sẽ được bổ sung khả năng "nhìn lại" môi trường hiện tại, đối chiếu với mục tiêu ban đầu của người dùng xem đã hoàn thành chưa. Nếu chưa, LLM sẽ tự động sinh ra một kế hoạch mới để tiếp tục thực hiện cho đến khi đạt mục tiêu.
15
+ * **Hiểu biết không gian và mối quan hệ (Spatial Reasoning):** Nâng cấp khả năng của LLM để không chỉ biết vật thể ở đâu, mà còn hiểu sâu sắc về trạng thái và mối quan hệ không gian giữa các đồ vật (ví dụ: vật A nằm trên vật B, vật C cách vật D bao xa...).
16
+ * **Khả năng tương tác và phản biện (Interactive Clarification):** Khi nhận được một yêu cầu từ người dùng bị thiếu thông tin, vô lý, hoặc không phù hợp với môi trường hiện tại, LLM sẽ không làm theo một cách máy móc. Thay vào đó, nó sẽ biết cách đặt câu hỏi làm rõ, phản biện lại, hoặc từ chối thực hiện kèm theo lý do giải thích rõ ràng.
17
+
18
+ ## 4. Nằm ngoài phạm vi giải quyết hiện tại (Out of Scope)
19
+ Đây là những vấn đề tạm thời được gác lại và không tập trung xử lý trong giai đoạn này:
20
+ * **Tránh va chạm trong quá trình tiến vào gắp (Approach phase):** Khi robot đã xác định được vị trí đồ vật và di chuyển đến để gắp, hệ thống sẽ bỏ qua việc tính toán tránh va chạm trên đoạn đường tiếp cận cuối cùng này.
21
+ * **Thuật toán tối ưu hóa điểm gắp (Optimal Grasp Synthesis):** Hệ thống sẽ không tập trung vào việc tìm ra điểm gắp tối ưu nhất trên vật thể theo chuẩn logic vật lý thực tế phức tạp (ví dụ: tính toán trọng tâm, lực ma sát...).
__pycache__/main.cpython-310.pyc CHANGED
Binary files a/__pycache__/main.cpython-310.pyc and b/__pycache__/main.cpython-310.pyc differ
 
envs/default_desk.json CHANGED
@@ -5,12 +5,12 @@
5
  "pedestal_half_extent": 0.06
6
  },
7
  "table": {
8
- "center": [0.50, 0.0],
9
  "half_extents": [0.17, 0.27, 0.15],
10
  "color": [0.55, 0.35, 0.18, 1.0]
11
  },
12
  "tray": {
13
- "position": [0.40, 0.41, 0.30],
14
  "half_extents": [0.20, 0.14, 0.01],
15
  "color": [0.20, 0.20, 0.22, 1.0]
16
  }
 
5
  "pedestal_half_extent": 0.06
6
  },
7
  "table": {
8
+ "center": [0.50, -0.08],
9
  "half_extents": [0.17, 0.27, 0.15],
10
  "color": [0.55, 0.35, 0.18, 1.0]
11
  },
12
  "tray": {
13
+ "position": [0.30, 0.33, 0.30],
14
  "half_extents": [0.20, 0.14, 0.01],
15
  "color": [0.20, 0.20, 0.22, 1.0]
16
  }
envs/env1.json CHANGED
@@ -5,12 +5,12 @@
5
  "pedestal_half_extent": 0.06
6
  },
7
  "table": {
8
- "center": [0.50, 0.0],
9
  "half_extents": [0.17, 0.27, 0.15],
10
  "color": [0.55, 0.35, 0.18, 1.0]
11
  },
12
  "tray": {
13
- "position": [0.40, 0.41, 0.30],
14
  "half_extents": [0.20, 0.14, 0.01],
15
  "color": [0.20, 0.20, 0.22, 1.0]
16
  },
@@ -21,7 +21,7 @@
21
  "folder": "YcbBanana",
22
  "web_obj": "textured_simple_reoriented.obj",
23
  "web_mtl": "textured_simple_reoriented.mtl",
24
- "position": [0.4, -0.1, 0.35],
25
  "orientation": [0, 0, 0, 1]
26
  },
27
  {
@@ -30,7 +30,7 @@
30
  "folder": "YcbTomatoSoupCan",
31
  "web_obj": "textured_simple_reoriented.obj",
32
  "web_mtl": "textured_simple_reoriented.mtl",
33
- "position": [0.4, 0.1, 0.35],
34
  "orientation": [0, 0, 0, 1]
35
  },
36
  {
@@ -39,7 +39,7 @@
39
  "folder": "YcbMasterChefCan",
40
  "web_obj": "textured_simple_reoriented.obj",
41
  "web_mtl": "textured_simple_reoriented.mtl",
42
- "position": [0.6, -0.1, 0.35],
43
  "orientation": [0, 0, 0, 1]
44
  },
45
  {
@@ -48,7 +48,7 @@
48
  "folder": "YcbTennisBall",
49
  "web_obj": "textured_reoriented.obj",
50
  "web_mtl": "textured_reoriented.obj.mtl",
51
- "position": [0.6, 0.1, 0.35],
52
  "orientation": [0, 0, 0, 1]
53
  },
54
  {
@@ -57,7 +57,7 @@
57
  "folder": "YcbPear",
58
  "web_obj": "textured_reoriented.obj",
59
  "web_mtl": "textured_reoriented.mtl",
60
- "position": [0.5, -0.2, 0.35],
61
  "orientation": [0, 0, 0, 1]
62
  },
63
  {
@@ -66,7 +66,7 @@
66
  "folder": "YcbMediumClamp",
67
  "web_obj": "textured_reoriented.obj",
68
  "web_mtl": "textured_reoriented.mtl",
69
- "position": [0.5, 0.2, 0.35],
70
  "orientation": [0, 0, 0, 1]
71
  }
72
  ]
 
5
  "pedestal_half_extent": 0.06
6
  },
7
  "table": {
8
+ "center": [0.50, -0.08],
9
  "half_extents": [0.17, 0.27, 0.15],
10
  "color": [0.55, 0.35, 0.18, 1.0]
11
  },
12
  "tray": {
13
+ "position": [0.30, 0.33, 0.30],
14
  "half_extents": [0.20, 0.14, 0.01],
15
  "color": [0.20, 0.20, 0.22, 1.0]
16
  },
 
21
  "folder": "YcbBanana",
22
  "web_obj": "textured_simple_reoriented.obj",
23
  "web_mtl": "textured_simple_reoriented.mtl",
24
+ "position": [0.4, -0.18, 0.35],
25
  "orientation": [0, 0, 0, 1]
26
  },
27
  {
 
30
  "folder": "YcbTomatoSoupCan",
31
  "web_obj": "textured_simple_reoriented.obj",
32
  "web_mtl": "textured_simple_reoriented.mtl",
33
+ "position": [0.4, 0.02, 0.35],
34
  "orientation": [0, 0, 0, 1]
35
  },
36
  {
 
39
  "folder": "YcbMasterChefCan",
40
  "web_obj": "textured_simple_reoriented.obj",
41
  "web_mtl": "textured_simple_reoriented.mtl",
42
+ "position": [0.6, -0.18, 0.35],
43
  "orientation": [0, 0, 0, 1]
44
  },
45
  {
 
48
  "folder": "YcbTennisBall",
49
  "web_obj": "textured_reoriented.obj",
50
  "web_mtl": "textured_reoriented.obj.mtl",
51
+ "position": [0.6, 0.02, 0.35],
52
  "orientation": [0, 0, 0, 1]
53
  },
54
  {
 
57
  "folder": "YcbPear",
58
  "web_obj": "textured_reoriented.obj",
59
  "web_mtl": "textured_reoriented.mtl",
60
+ "position": [0.5, -0.28, 0.35],
61
  "orientation": [0, 0, 0, 1]
62
  },
63
  {
 
66
  "folder": "YcbMediumClamp",
67
  "web_obj": "textured_reoriented.obj",
68
  "web_mtl": "textured_reoriented.mtl",
69
+ "position": [0.5, 0.12, 0.35],
70
  "orientation": [0, 0, 0, 1]
71
  }
72
  ]
frontend/__pycache__/interactive_server.cpython-310.pyc CHANGED
Binary files a/frontend/__pycache__/interactive_server.cpython-310.pyc and b/frontend/__pycache__/interactive_server.cpython-310.pyc differ
 
frontend/app.js CHANGED
@@ -659,10 +659,31 @@ function formatSkillName(skill, args) {
659
 
660
  switch(skill) {
661
  case 'pick_up': return `Gắp <b>${targetVN}</b> lên`;
662
- case 'move_to': return `Di chuyển đến <b>${targetVN}</b>`;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
663
  case 'place_down': return `Đặt đồ vật xuống`;
664
  case 'open_gripper': return `Mở tay kẹp`;
665
  case 'close_gripper': return `Đóng tay kẹp`;
 
 
666
  default: return `${skill}(${targetVN})`;
667
  }
668
  }
@@ -780,14 +801,36 @@ window.runHistoryPrompt = function(index) {
780
  document.getElementById('chat-form').dispatchEvent(new Event('submit'));
781
  }
782
  };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
783
  // 5. Speech Synthesis (Text-to-Speech)
784
- function speakFeedback(text) {
785
  if (!ttsToggle || !ttsToggle.checked) return;
786
 
 
 
 
 
 
 
 
787
  const lang = 'en';
788
 
789
- // Call Google Translate TTS with gtx client for reliable Vietnamese voices
790
- const encodedText = encodeURIComponent(text);
791
  const ttsUrl = `https://translate.googleapis.com/translate_tts?client=gtx&ie=UTF-8&tl=${lang}&q=${encodedText}`;
792
 
793
  const audio = new Audio(ttsUrl);
@@ -795,13 +838,13 @@ function speakFeedback(text) {
795
  console.warn("Google Translate TTS failed, falling back to local speech synthesis:", err);
796
  if ('speechSynthesis' in window) {
797
  window.speechSynthesis.cancel();
798
- const utterance = new SpeechSynthesisUtterance(text);
799
- utterance.lang = 'vi-VN';
800
  utterance.rate = 1.0;
801
  utterance.pitch = 1.0;
802
 
803
  const voices = window.speechSynthesis.getVoices();
804
- const matchingVoice = voices.find(voice => voice.lang.includes('vi'));
805
  if (matchingVoice) utterance.voice = matchingVoice;
806
 
807
  window.speechSynthesis.speak(utterance);
@@ -931,8 +974,16 @@ function updatePipelineUI(message) {
931
  const stepLlm = document.getElementById('step-llm');
932
  const stepVal = document.getElementById('step-val');
933
  const stepExec = document.getElementById('step-exec');
 
934
  if (message.includes('[1/5]')) {
 
935
  setActiveStep(stepLlm);
 
 
 
 
 
 
936
  } else if (message.includes('✅ [1]')) {
937
  setCompletedStep(stepLlm);
938
  } else if (message.includes('❌ [1]')) {
@@ -941,6 +992,7 @@ function updatePipelineUI(message) {
941
  speakFeedback("Planning failed. Please check your command.");
942
  }
943
  else if (message.includes('[2/5]')) {
 
944
  setActiveStep(stepVal);
945
  } else if (message.includes('✅ [2]')) {
946
  setCompletedStep(stepVal);
@@ -960,6 +1012,11 @@ function updatePipelineUI(message) {
960
  } else if (message.includes('Thực thi kết thúc có bước lỗi')) {
961
  setErrorStep(stepExec);
962
  speakFeedback("Execution encountered a collision.");
 
 
 
 
 
963
  }
964
  }
965
  function setActiveStep(el) {
 
659
 
660
  switch(skill) {
661
  case 'pick_up': return `Gắp <b>${targetVN}</b> lên`;
662
+ case 'move_to': {
663
+ if (args.relation && args.relative_to) {
664
+ const relTo = args.relative_to;
665
+ const relToVN = objectNamesVN[relTo] || relTo;
666
+ if (args.relation === 'on_top_of') {
667
+ return `Di chuyển lên trên đỉnh <b>${relToVN}</b>`;
668
+ } else if (args.relation === 'left_of') {
669
+ return `Di chuyển đến bên trái <b>${relToVN}</b>`;
670
+ } else if (args.relation === 'right_of') {
671
+ return `Di chuyển đến bên phải <b>${relToVN}</b>`;
672
+ } else if (args.relation === 'front_of') {
673
+ return `Di chuyển đến phía trước <b>${relToVN}</b>`;
674
+ } else if (args.relation === 'behind') {
675
+ return `Di chuyển đến phía sau <b>${relToVN}</b>`;
676
+ } else if (args.relation === 'next_to') {
677
+ return `Di chuyển đến bên cạnh <b>${relToVN}</b>`;
678
+ }
679
+ }
680
+ return `Di chuyển đến <b>${targetVN}</b>`;
681
+ }
682
  case 'place_down': return `Đặt đồ vật xuống`;
683
  case 'open_gripper': return `Mở tay kẹp`;
684
  case 'close_gripper': return `Đóng tay kẹp`;
685
+ case 'clarify': return `Hỏi lại: <i>${args.message}</i>`;
686
+ case 'reject': return `Từ chối: <i>${args.message}</i>`;
687
  default: return `${skill}(${targetVN})`;
688
  }
689
  }
 
801
  document.getElementById('chat-form').dispatchEvent(new Event('submit'));
802
  }
803
  };
804
+ // Helper to translate text to English using Google Translate free endpoint
805
+ async function translateToEnglish(text) {
806
+ try {
807
+ const url = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=en&dt=t&q=${encodeURIComponent(text)}`;
808
+ const res = await fetch(url);
809
+ const json = await res.json();
810
+ if (json && json[0] && json[0][0] && json[0][0][0]) {
811
+ return json[0][0][0];
812
+ }
813
+ } catch (e) {
814
+ console.warn("Translation failed, using original text:", e);
815
+ }
816
+ return text;
817
+ }
818
+
819
  // 5. Speech Synthesis (Text-to-Speech)
820
+ async function speakFeedback(text) {
821
  if (!ttsToggle || !ttsToggle.checked) return;
822
 
823
+ // Translate text to English
824
+ let englishText = text;
825
+ const isVietnamese = /[àáạảãâầấậẩẫăằắặẳẵèéẹẻẽêềếệểễìíịỉĩòóọỏõôồốộổỗơờớợởỡùúụủũưừứựửữỳýỵỷỹđ]/i.test(text);
826
+ if (isVietnamese) {
827
+ englishText = await translateToEnglish(text);
828
+ }
829
+
830
  const lang = 'en';
831
 
832
+ // Call Google Translate TTS with gtx client for reliable English voices
833
+ const encodedText = encodeURIComponent(englishText);
834
  const ttsUrl = `https://translate.googleapis.com/translate_tts?client=gtx&ie=UTF-8&tl=${lang}&q=${encodedText}`;
835
 
836
  const audio = new Audio(ttsUrl);
 
838
  console.warn("Google Translate TTS failed, falling back to local speech synthesis:", err);
839
  if ('speechSynthesis' in window) {
840
  window.speechSynthesis.cancel();
841
+ const utterance = new SpeechSynthesisUtterance(englishText);
842
+ utterance.lang = 'en-US';
843
  utterance.rate = 1.0;
844
  utterance.pitch = 1.0;
845
 
846
  const voices = window.speechSynthesis.getVoices();
847
+ const matchingVoice = voices.find(voice => voice.lang.includes(lang));
848
  if (matchingVoice) utterance.voice = matchingVoice;
849
 
850
  window.speechSynthesis.speak(utterance);
 
974
  const stepLlm = document.getElementById('step-llm');
975
  const stepVal = document.getElementById('step-val');
976
  const stepExec = document.getElementById('step-exec');
977
+
978
  if (message.includes('[1/5]')) {
979
+ stepLlm.querySelector('.step-label').textContent = '1. Planning';
980
  setActiveStep(stepLlm);
981
+ } else if (message.includes('[MONITOR] Re-plan attempt')) {
982
+ stepLlm.querySelector('.step-label').textContent = '1. Replanning...';
983
+ stepLlm.className = 'status-step active warn';
984
+ // Remove active from others
985
+ stepVal.className = 'status-step';
986
+ stepExec.className = 'status-step';
987
  } else if (message.includes('✅ [1]')) {
988
  setCompletedStep(stepLlm);
989
  } else if (message.includes('❌ [1]')) {
 
992
  speakFeedback("Planning failed. Please check your command.");
993
  }
994
  else if (message.includes('[2/5]')) {
995
+ stepLlm.querySelector('.step-label').textContent = '1. Planning'; // Restore label
996
  setActiveStep(stepVal);
997
  } else if (message.includes('✅ [2]')) {
998
  setCompletedStep(stepVal);
 
1012
  } else if (message.includes('Thực thi kết thúc có bước lỗi')) {
1013
  setErrorStep(stepExec);
1014
  speakFeedback("Execution encountered a collision.");
1015
+ } else if (message.includes('[MONITOR] Exhausted re-plan attempts')) {
1016
+ setErrorStep(stepLlm);
1017
+ setErrorStep(stepExec);
1018
+ unlockInput();
1019
+ speakFeedback("Task failed. Max replanning attempts reached.");
1020
  }
1021
  }
1022
  function setActiveStep(el) {
frontend/index.html CHANGED
@@ -300,6 +300,6 @@
300
  </div>
301
 
302
  <!-- Application Script -->
303
- <script src="/static/app.js?v=24"></script>
304
  </body>
305
  </html>
 
300
  </div>
301
 
302
  <!-- Application Script -->
303
+ <script src="/static/app.js?v=25"></script>
304
  </body>
305
  </html>
frontend/interactive_server.py CHANGED
@@ -270,8 +270,9 @@ def compute_and_format_score(sim: PandaApp, plan: list, executed_successfully: b
270
 
271
  md = f"### 🏆 Rearrangement Evaluation Report\n\n**Tổng điểm: {score}/100**\n\n**Chi tiết:**\n" + "\n".join([f"- {d}" for d in details])
272
  return score, md
 
273
  def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mock: bool, camera_state: Optional[dict] = None):
274
- """Runs the planning, validation, execution with image streaming, and scoring."""
275
  global current_sim, pipeline_executing
276
  pipeline_executing = True
277
 
@@ -284,6 +285,7 @@ def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mo
284
  websocket.send_json({"type": "log", "message": message, "step": step}),
285
  loop
286
  )
 
287
  # Step 1: Planning
288
  log("⏳ [1/5] Tôi đang suy nghĩ cách thực hiện...")
289
 
@@ -294,6 +296,7 @@ def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mo
294
  api_key = os.environ.get("OPENAI_API_KEY") or os.environ.get("LLM_API_KEY")
295
  if not api_key:
296
  log("❌ [1] Lỗi: Không tìm thấy OPENAI_API_KEY / LLM_API_KEY. Vui lòng chọn Mock.")
 
297
  return
298
  planner = RemoteLLMPlanner()
299
  log(f"✅ [1] Tôi đang phân tích yêu cầu...")
@@ -301,109 +304,9 @@ def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mo
301
  with pybullet_lock:
302
  current_sim.pipeline.agent = LLMAgent(planner=planner)
303
 
304
- # Settle physics in case the user placed objects hovering or overlapping in the UI
305
- if current_sim.controller:
306
- current_sim.controller._settle(60)
307
-
308
- # Define reachability check for scene state
309
- def reachability_fn(oid):
310
- cls = current_sim.scene.get_class(oid)
311
- try:
312
- grasp_pos, grasp_ori = current_sim.pipeline.grasp_planner.compute_grasp_pose(oid, cls)
313
- return current_sim.controller.is_reachable(grasp_pos, grasp_ori)
314
- except Exception:
315
- return False
316
- carried_name = current_sim.scene.get_name(current_sim.pipeline._carried) if current_sim.pipeline._carried is not None else None
317
- scene_state = current_sim.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=carried_name)
318
- state_text = json.dumps(scene_state, indent=2)
319
-
320
- try:
321
- with pybullet_lock:
322
- llm_start_time = time.time()
323
- plan = current_sim.pipeline.agent.plan(user_prompt, state_text)
324
- llm_time = time.time() - llm_start_time
325
-
326
- # Summarize plan
327
- targets = []
328
- destinations = set()
329
- for step_dict in plan:
330
- if step_dict.get("function") == "pick_up":
331
- obj_id = step_dict.get("args", {}).get("object_id")
332
- if obj_id: targets.append(obj_id)
333
- elif step_dict.get("function") == "move_to":
334
- loc_id = step_dict.get("args", {}).get("location_id")
335
- if loc_id: destinations.add(loc_id)
336
-
337
- def translate_obj(x):
338
- obj_map = {'banana': 'banana', 'soup_can': 'soup can', 'chips_can': 'chips can', 'tennis_ball': 'tennis ball', 'pear': 'pear', 'clamp': 'clamp', 'table': 'table', 'tray': 'tray'}
339
- return obj_map.get(x, x)
340
-
341
- targets_en = [translate_obj(t) for t in targets]
342
- dests_en = [translate_obj(d) for d in destinations]
343
-
344
- if targets_en:
345
- target_str = ", ".join(targets_en[:-1]) + " and " + targets_en[-1] if len(targets_en) > 1 else targets_en[0]
346
- dest_str = " and ".join(dests_en) if dests_en else "a new location"
347
- summary_msg = f"I will pick up the {target_str} and move to the {dest_str}."
348
- else:
349
- summary_msg = "I have finished processing your request."
350
-
351
- log(f"✅ [1] {summary_msg}")
352
- except Exception as e:
353
- log(f"❌ [1] Lập kế hoạch thất bại: {e}")
354
- pipeline_executing = False
355
- return
356
- # Send steps to client
357
- plan_steps = []
358
- for idx, step in enumerate(plan, 1):
359
- func = step.get("function")
360
- args = step.get("args", {})
361
- obj = args.get("object_id") or args.get("location_id") or ""
362
- plan_steps.append({
363
- "step": idx,
364
- "skill": func,
365
- "object": obj,
366
- "args": args
367
- })
368
-
369
- asyncio.run_coroutine_threadsafe(
370
- websocket.send_json({"type": "plan", "plan": plan_steps, "summary": summary_msg, "llm_time": llm_time}),
371
- loop
372
- )
373
- if not plan:
374
- log("⚠️ [1] Kế hoạch rỗng.")
375
- log("⏳ [5/5] Đang tính toán điểm sắp xếp...")
376
- score_val, score_md = compute_and_format_score(current_sim, [], True)
377
- asyncio.run_coroutine_threadsafe(
378
- websocket.send_json({
379
- "type": "result",
380
- "score_display": score_md,
381
- "score_value": score_val
382
- }),
383
- loop
384
- )
385
- state_payload = get_simulation_state_payload(current_sim)
386
- if state_payload:
387
- asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
388
- pipeline_executing = False
389
- return
390
- # Step 2: Validation
391
- log("⏳ [2/5] Tôi đang kiểm tra mức độ an toàn của kế hoạch...")
392
- try:
393
- with pybullet_lock:
394
- warnings = PlanVerifier.check(plan, scene_state)
395
- if not warnings:
396
- log("✅ [2] Kế hoạch an toàn và hợp lệ.")
397
- else:
398
- log(f"⚠️ [2] Phát hiện {len(warnings)} rủi ro tiềm ẩn.")
399
- for w in warnings:
400
- log(f" - {w}")
401
- except Exception as e:
402
- log(f"❌ [2] Lỗi kiểm tra kế hoạch: {e}")
403
- pipeline_executing = False
404
- return
405
- # Step 3: PyBullet Execution (Live!)
406
- log("⏳ [3/5] Tôi bắt đầu thực hiện các bước...")
407
 
408
  # Hook pb.stepSimulation to capture states during movements
409
  original_step = pb.stepSimulation
@@ -423,75 +326,281 @@ def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mo
423
  websocket.send_json(state_payload),
424
  loop
425
  )
426
-
427
- with pybullet_lock:
428
- pb.stepSimulation = wrapped_step
429
-
430
- executed_successfully = True
431
- try:
432
- # Trigger an initial simulation state transmission
433
- state_payload = get_simulation_state_payload(current_sim)
434
- if state_payload:
435
- asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
436
 
437
- def format_skill_vn(step_data):
438
- fn = step_data.get("function", "")
439
- args = step_data.get("args", {})
440
- target = args.get("object_id") or args.get("location_id") or ""
 
 
 
 
 
 
 
 
 
 
 
 
441
 
442
- obj_map = {
443
- 'banana': 'quả chuối',
444
- 'soup_can': 'lon súp',
445
- 'chips_can': 'lon snack',
446
- 'tennis_ball': 'quả bóng tennis',
447
- 'pear': 'quả lê',
448
- 'clamp': 'chiếc kìm',
449
- 'table': 'bàn',
450
- 'tray': 'khay',
451
  }
452
- target_vn = obj_map.get(target, target)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
453
 
454
- if fn == "pick_up": return f"Gắp {target_vn} lên"
455
- if fn == "move_to": return f"Di chuyển đến {target_vn}"
456
- if fn == "place_down": return "Đặt đồ vật xuống"
457
- if fn == "open_gripper": return "Mở tay kẹp"
458
- if fn == "close_gripper": return "Đóng tay kẹp"
459
- return f"{fn}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
460
 
461
- for i, step in enumerate(plan, 1):
462
- friendly_text = format_skill_vn(step)
463
- # Make the first letter lowercase for natural sentence integration
464
- if friendly_text:
465
- friendly_text = friendly_text[0].lower() + friendly_text[1:]
466
- log(f"🚀 [3/5] Tôi đang {friendly_text}...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
467
  with pybullet_lock:
468
- current_sim.pipeline._execute(step, verbose=True)
 
 
 
 
 
 
 
 
 
 
469
 
470
- log("✅ [3] Tôi đã hoàn tất các bước.")
471
- except Exception as e:
472
- log(f"❌ Lỗi trong lúc thực thi mô phỏng: {e}")
473
- executed_successfully = False
474
- finally:
475
  with pybullet_lock:
476
- pb.stepSimulation = original_step
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
477
 
478
- # Send a final state to ensure visual sync
479
- state_payload = get_simulation_state_payload(current_sim)
480
- if state_payload:
481
- asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
482
  # Step 5: Scoring
483
  log("⏳ [5/5] Đang tính toán điểm sắp xếp...")
484
- score_val, score_md = compute_and_format_score(current_sim, plan, executed_successfully)
485
 
486
  error_cause = None
487
  if not plan:
488
  error_cause = "llm"
489
  elif not executed_successfully:
490
  error_cause = "ik"
491
- elif score_val < 50:
492
  error_cause = "slip"
493
 
494
- is_success = executed_successfully and score_val >= 50
495
 
496
  asyncio.run_coroutine_threadsafe(
497
  websocket.send_json({
 
270
 
271
  md = f"### 🏆 Rearrangement Evaluation Report\n\n**Tổng điểm: {score}/100**\n\n**Chi tiết:**\n" + "\n".join([f"- {d}" for d in details])
272
  return score, md
273
+
274
  def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mock: bool, camera_state: Optional[dict] = None):
275
+ """Runs the planning, validation, execution with image streaming, and scoring using closed-loop execution monitor."""
276
  global current_sim, pipeline_executing
277
  pipeline_executing = True
278
 
 
285
  websocket.send_json({"type": "log", "message": message, "step": step}),
286
  loop
287
  )
288
+
289
  # Step 1: Planning
290
  log("⏳ [1/5] Tôi đang suy nghĩ cách thực hiện...")
291
 
 
296
  api_key = os.environ.get("OPENAI_API_KEY") or os.environ.get("LLM_API_KEY")
297
  if not api_key:
298
  log("❌ [1] Lỗi: Không tìm thấy OPENAI_API_KEY / LLM_API_KEY. Vui lòng chọn Mock.")
299
+ pipeline_executing = False
300
  return
301
  planner = RemoteLLMPlanner()
302
  log(f"✅ [1] Tôi đang phân tích yêu cầu...")
 
304
  with pybullet_lock:
305
  current_sim.pipeline.agent = LLMAgent(planner=planner)
306
 
307
+ MAX_REPLANS = 999999
308
+ last_failed_sig = None
309
+ last_failed_state_sig = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
310
 
311
  # Hook pb.stepSimulation to capture states during movements
312
  original_step = pb.stepSimulation
 
326
  websocket.send_json(state_payload),
327
  loop
328
  )
329
+
330
+ for attempt in range(MAX_REPLANS + 1):
331
+ if attempt > 0:
332
+ log(f"[MONITOR] Re-plan attempt {attempt}/{MAX_REPLANS} due to: {last_failed_sig}")
333
+ log("⏳ [1/5] Tôi đang suy nghĩ cách thực hiện...")
 
 
 
 
 
334
 
335
+ with pybullet_lock:
336
+ # Settle physics in case the user placed objects hovering or overlapping in the UI
337
+ if current_sim.controller:
338
+ current_sim.controller._settle(60)
339
+
340
+ # Define reachability check for scene state
341
+ def reachability_fn(oid):
342
+ cls = current_sim.scene.get_class(oid)
343
+ try:
344
+ grasp_pos, grasp_ori = current_sim.pipeline.grasp_planner.compute_grasp_pose(oid, cls)
345
+ return current_sim.controller.is_reachable(grasp_pos, grasp_ori)
346
+ except Exception:
347
+ return False
348
+ carried_name = current_sim.scene.get_name(current_sim.pipeline._carried) if current_sim.pipeline._carried is not None else None
349
+ scene_state = current_sim.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=carried_name)
350
+ state_text = json.dumps(scene_state, indent=2)
351
 
352
+ # Signature of the physical state to detect if environment actually changed
353
+ state_sig_dict = {
354
+ "objects": [{"name": o["name"], "location": o["location"], "blocking": o.get("blocking_objects", [])} for o in scene_state.get("objects", [])],
355
+ "carried": scene_state.get("carried_object")
 
 
 
 
 
356
  }
357
+ state_sig = json.dumps(state_sig_dict, sort_keys=True)
358
+
359
+ try:
360
+ with pybullet_lock:
361
+ llm_start_time = time.time()
362
+ plan = current_sim.pipeline.agent.plan(user_prompt, state_text, previous_failed_reasons=last_failed_sig)
363
+ llm_time = time.time() - llm_start_time
364
+
365
+ # Summarize plan
366
+ targets = []
367
+ destinations = set()
368
+ for step_dict in plan:
369
+ if step_dict.get("function") == "pick_up":
370
+ obj_id = step_dict.get("args", {}).get("object_id")
371
+ if obj_id: targets.append(obj_id)
372
+ elif step_dict.get("function") == "move_to":
373
+ loc_id = step_dict.get("args", {}).get("location_id")
374
+ if loc_id: destinations.add(loc_id)
375
 
376
+ def translate_obj(x):
377
+ obj_map = {'banana': 'banana', 'soup_can': 'soup can', 'chips_can': 'chips can', 'tennis_ball': 'tennis ball', 'pear': 'pear', 'clamp': 'clamp', 'table': 'table', 'tray': 'tray'}
378
+ return obj_map.get(x, x)
379
+
380
+ targets_en = [translate_obj(t) for t in targets]
381
+ dests_en = [translate_obj(d) for d in destinations]
382
+
383
+ if plan and plan[0].get("function") in ("clarify", "reject"):
384
+ summary_msg = plan[0].get("args", {}).get("message", "Yêu cầu không hợp lệ.")
385
+ elif targets_en:
386
+ target_str = ", ".join(targets_en[:-1]) + " and " + targets_en[-1] if len(targets_en) > 1 else targets_en[0]
387
+ dest_str = " and ".join(dests_en) if dests_en else "a new location"
388
+ summary_msg = f"I will pick up the {target_str} and move to the {dest_str}."
389
+ else:
390
+ summary_msg = "I have finished processing your request."
391
+
392
+ log(f"✅ [1] {summary_msg}")
393
+ except Exception as e:
394
+ log(f"❌ [1] Lập kế hoạch thất bại: {e}")
395
+ pipeline_executing = False
396
+ return
397
+
398
+ # Send steps to client
399
+ plan_steps = []
400
+ for idx, step_item in enumerate(plan, 1):
401
+ func = step_item.get("function")
402
+ args = step_item.get("args", {})
403
+ obj = args.get("object_id") or args.get("location_id") or ""
404
+ plan_steps.append({
405
+ "step": idx,
406
+ "skill": func,
407
+ "object": obj,
408
+ "args": args
409
+ })
410
+
411
+ asyncio.run_coroutine_threadsafe(
412
+ websocket.send_json({"type": "plan", "plan": plan_steps, "summary": summary_msg, "llm_time": llm_time}),
413
+ loop
414
+ )
415
+
416
+ if plan and plan[0].get("function") in ("clarify", "reject"):
417
+ log(f"Robot phản hồi: {summary_msg}")
418
+ header_title = "Phản hồi từ Robot" if plan[0].get("function") == "clarify" else "Yêu cầu bị từ chối"
419
+ score_md = f"### {header_title}\n\n**Robot phản hồi:** {summary_msg}\n"
420
+ asyncio.run_coroutine_threadsafe(
421
+ websocket.send_json({
422
+ "type": "result",
423
+ "score_display": score_md,
424
+ "score_value": 0,
425
+ "success": False
426
+ }),
427
+ loop
428
+ )
429
+ state_payload = get_simulation_state_payload(current_sim)
430
+ if state_payload:
431
+ asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
432
+ pipeline_executing = False
433
+ return
434
 
435
+ if not plan:
436
+ log("⚠️ [1] Kế hoạch rỗng.")
437
+ log("⏳ [5/5] Đang tính toán điểm sắp xếp...")
438
+ score_val, score_md = compute_and_format_score(current_sim, [], True)
439
+ asyncio.run_coroutine_threadsafe(
440
+ websocket.send_json({
441
+ "type": "result",
442
+ "score_display": score_md,
443
+ "score_value": score_val
444
+ }),
445
+ loop
446
+ )
447
+ state_payload = get_simulation_state_payload(current_sim)
448
+ if state_payload:
449
+ asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
450
+ pipeline_executing = False
451
+ return
452
+
453
+ # Step 2: Validation
454
+ log("⏳ [2/5] Tôi đang kiểm tra mức độ an toàn của kế hoạch...")
455
+ try:
456
  with pybullet_lock:
457
+ warnings = PlanVerifier.check(plan, scene_state)
458
+ if not warnings:
459
+ log("✅ [2] Kế hoạch an toàn và hợp lệ.")
460
+ else:
461
+ log(f"⚠️ [2] Phát hiện {len(warnings)} rủi ro ti���m ẩn.")
462
+ for w in warnings:
463
+ log(f" - {w}")
464
+ except Exception as e:
465
+ log(f"❌ [2] Lỗi kiểm tra kế hoạch: {e}")
466
+ pipeline_executing = False
467
+ return
468
 
469
+ # Step 3: PyBullet Execution (Live!)
470
+ log("⏳ [3/5] Tôi bắt đầu thực hiện các bước...")
471
+
 
 
472
  with pybullet_lock:
473
+ pb.stepSimulation = wrapped_step
474
+
475
+ executed_successfully = True
476
+ step_failure_reason = None
477
+ failed_step_index = -1
478
+ failed_step_data = None
479
+
480
+ try:
481
+ # Trigger an initial simulation state transmission
482
+ state_payload = get_simulation_state_payload(current_sim)
483
+ if state_payload:
484
+ asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
485
+
486
+ def format_skill_vn(step_data):
487
+ fn = step_data.get("function", "")
488
+ args = step_data.get("args", {})
489
+ target = args.get("object_id") or args.get("location_id") or ""
490
+
491
+ obj_map = {
492
+ 'banana': 'quả chuối',
493
+ 'soup_can': 'lon súp',
494
+ 'chips_can': 'lon snack',
495
+ 'tennis_ball': 'quả bóng tennis',
496
+ 'pear': 'quả lê',
497
+ 'clamp': 'chiếc kìm',
498
+ 'table': 'bàn',
499
+ 'tray': 'khay',
500
+ }
501
+ target_vn = obj_map.get(target, target)
502
+
503
+ if fn == "pick_up": return f"Gắp {target_vn} lên"
504
+ if fn == "move_to": return f"Di chuyển đến {target_vn}"
505
+ if fn == "place_down": return "Đặt đồ vật xuống"
506
+ if fn == "open_gripper": return "Mở tay kẹp"
507
+ if fn == "close_gripper": return "Đóng tay kẹp"
508
+ return f"{fn}"
509
+
510
+ expected_location = None
511
+ for i, step in enumerate(plan, 1):
512
+ friendly_text = format_skill_vn(step)
513
+ # Make the first letter lowercase for natural sentence integration
514
+ if friendly_text:
515
+ friendly_text = friendly_text[0].lower() + friendly_text[1:]
516
+ log(f"🚀 [3/5] Tôi đang {friendly_text}...")
517
+
518
+ pre_positions = {
519
+ oid: pb.getBasePositionAndOrientation(oid)[0]
520
+ for oid in current_sim.scene.object_ids
521
+ if oid != current_sim.pipeline._carried
522
+ }
523
+ held_before = current_sim.pipeline._carried
524
+ current_sim.controller.reset_stuck()
525
+
526
+ with pybullet_lock:
527
+ current_sim.pipeline._execute(step, verbose=True)
528
+
529
+ # Run step verification using execution monitor
530
+ ok, reason = current_sim.pipeline.execution_monitor.verify_step(
531
+ step, held_before, expected_location, current_sim.pipeline._carried, current_sim.pipeline._pending_target_pos
532
+ )
533
+ if step.get("function") == "move_to":
534
+ expected_location = step.get("args", {}).get("location_id")
535
+
536
+ if not ok:
537
+ executed_successfully = False
538
+ step_failure_reason = reason
539
+ failed_step_index = i
540
+ failed_step_data = step
541
+ break
542
+
543
+ if executed_successfully:
544
+ log("✅ [3] Tôi đã hoàn tất các bước.")
545
+ else:
546
+ log(f"❌ [3] Thực thi lỗi tại bước {failed_step_index} '{failed_step_data.get('function')}': {step_failure_reason}")
547
+ except Exception as e:
548
+ log(f"❌ Lỗi trong lúc thực thi mô phỏng: {e}")
549
+ executed_successfully = False
550
+ step_failure_reason = str(e)
551
+ finally:
552
+ with pybullet_lock:
553
+ pb.stepSimulation = original_step
554
+
555
+ # Send a final state to ensure visual sync
556
+ state_payload = get_simulation_state_payload(current_sim)
557
+ if state_payload:
558
+ asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
559
+
560
+ # Now check overall goal using execution monitor
561
+ goal_completed = False
562
+ goal_reason = ""
563
+ if executed_successfully:
564
+ with pybullet_lock:
565
+ final_scene_state = current_sim.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=current_sim.scene.get_name(current_sim.pipeline._carried) if current_sim.pipeline._carried else None)
566
+ final_state_text = json.dumps(final_scene_state, indent=2)
567
+ goal_completed, goal_reason = current_sim.pipeline.execution_monitor.verify_goal(user_prompt, final_state_text)
568
+ if goal_completed:
569
+ log(f"✅ [GOAL CHECK] OK: {goal_reason}")
570
+ else:
571
+ log(f"⚠️ [GOAL CHECK] FAILED: {goal_reason}")
572
+
573
+ if goal_completed:
574
+ break
575
+
576
+ # If we failed or goal check failed, set replan inputs
577
+ if not executed_successfully:
578
+ last_failed_sig = f"Step {failed_step_index} '{failed_step_data.get('function')}' failed: {step_failure_reason}"
579
+ else:
580
+ last_failed_sig = f"Goal Check Failed: {goal_reason}"
581
+
582
+ last_failed_state_sig = state_sig
583
+
584
+ if attempt < MAX_REPLANS:
585
+ log(f"⚠️ [MONITOR] Phát hiện lỗi. Đang khôi phục cánh tay robot và lập kế hoạch lại (thử lần {attempt + 1})...")
586
+ with pybullet_lock:
587
+ current_sim.pipeline._recover_to_safe_state(verbose=True)
588
+ else:
589
+ log(f"❌ [MONITOR] Đã vượt quá số lần lập kế hoạch lại ({MAX_REPLANS}). Hủy bỏ tác vụ.")
590
 
 
 
 
 
591
  # Step 5: Scoring
592
  log("⏳ [5/5] Đang tính toán điểm sắp xếp...")
593
+ score_val, score_md = compute_and_format_score(current_sim, plan, executed_successfully and goal_completed)
594
 
595
  error_cause = None
596
  if not plan:
597
  error_cause = "llm"
598
  elif not executed_successfully:
599
  error_cause = "ik"
600
+ elif not goal_completed:
601
  error_cause = "slip"
602
 
603
+ is_success = executed_successfully and goal_completed and score_val >= 50
604
 
605
  asyncio.run_coroutine_threadsafe(
606
  websocket.send_json({
llm_panda/__pycache__/__init__.cpython-310.pyc CHANGED
Binary files a/llm_panda/__pycache__/__init__.cpython-310.pyc and b/llm_panda/__pycache__/__init__.cpython-310.pyc differ
 
llm_panda/__pycache__/config.cpython-310.pyc CHANGED
Binary files a/llm_panda/__pycache__/config.cpython-310.pyc and b/llm_panda/__pycache__/config.cpython-310.pyc differ
 
llm_panda/__pycache__/cost_map.cpython-310.pyc CHANGED
Binary files a/llm_panda/__pycache__/cost_map.cpython-310.pyc and b/llm_panda/__pycache__/cost_map.cpython-310.pyc differ
 
llm_panda/__pycache__/geofik.cpython-310.pyc CHANGED
Binary files a/llm_panda/__pycache__/geofik.cpython-310.pyc and b/llm_panda/__pycache__/geofik.cpython-310.pyc differ
 
llm_panda/__pycache__/grasp_planner.cpython-310.pyc CHANGED
Binary files a/llm_panda/__pycache__/grasp_planner.cpython-310.pyc and b/llm_panda/__pycache__/grasp_planner.cpython-310.pyc differ
 
llm_panda/__pycache__/llm_agent.cpython-310.pyc CHANGED
Binary files a/llm_panda/__pycache__/llm_agent.cpython-310.pyc and b/llm_panda/__pycache__/llm_agent.cpython-310.pyc differ
 
llm_panda/__pycache__/pipeline_executor.cpython-310.pyc CHANGED
Binary files a/llm_panda/__pycache__/pipeline_executor.cpython-310.pyc and b/llm_panda/__pycache__/pipeline_executor.cpython-310.pyc differ
 
llm_panda/__pycache__/plan_verifier.cpython-310.pyc CHANGED
Binary files a/llm_panda/__pycache__/plan_verifier.cpython-310.pyc and b/llm_panda/__pycache__/plan_verifier.cpython-310.pyc differ
 
llm_panda/__pycache__/robot_controller.cpython-310.pyc CHANGED
Binary files a/llm_panda/__pycache__/robot_controller.cpython-310.pyc and b/llm_panda/__pycache__/robot_controller.cpython-310.pyc differ
 
llm_panda/__pycache__/scene_manager.cpython-310.pyc CHANGED
Binary files a/llm_panda/__pycache__/scene_manager.cpython-310.pyc and b/llm_panda/__pycache__/scene_manager.cpython-310.pyc differ
 
llm_panda/__pycache__/task_nullspace.cpython-310.pyc CHANGED
Binary files a/llm_panda/__pycache__/task_nullspace.cpython-310.pyc and b/llm_panda/__pycache__/task_nullspace.cpython-310.pyc differ
 
llm_panda/config.py CHANGED
@@ -103,7 +103,7 @@ ARM_MAX_FORCE = 200.0
103
  # --------------------------------------------------------------------------- #
104
  # Table (continuous placement surface — no fixed slot grid)
105
  # --------------------------------------------------------------------------- #
106
- TABLE_CENTER = (0.50, 0.0)
107
  TABLE_HALF_EXTENTS = (0.17, 0.27, 0.15) # x, y, z half-sizes
108
  TABLE_BASE_Z = TABLE_HALF_EXTENTS[2] # base sits so its bottom is on z=0
109
  TABLE_TOP_Z = 2 * TABLE_HALF_EXTENTS[2] # top surface = 0.30 m
@@ -121,7 +121,7 @@ ROBOT_PEDESTAL_HALF = 0.06 # footprint half-extent of the pedes
121
 
122
  # Fixed tray, just outside the +y edge of the table.
123
  # Larger (40×28 cm) so banana/soup-can/chips-can fit side-by-side without knocking each other off.
124
- TRAY_POSITION = (0.40, 0.41, TABLE_TOP_Z)
125
  TRAY_HALF_EXTENTS = (0.20, 0.14, 0.01)
126
  TRAY_COLOR = [0.20, 0.20, 0.22, 1.0]
127
 
 
103
  # --------------------------------------------------------------------------- #
104
  # Table (continuous placement surface — no fixed slot grid)
105
  # --------------------------------------------------------------------------- #
106
+ TABLE_CENTER = (0.50, -0.08)
107
  TABLE_HALF_EXTENTS = (0.17, 0.27, 0.15) # x, y, z half-sizes
108
  TABLE_BASE_Z = TABLE_HALF_EXTENTS[2] # base sits so its bottom is on z=0
109
  TABLE_TOP_Z = 2 * TABLE_HALF_EXTENTS[2] # top surface = 0.30 m
 
121
 
122
  # Fixed tray, just outside the +y edge of the table.
123
  # Larger (40×28 cm) so banana/soup-can/chips-can fit side-by-side without knocking each other off.
124
+ TRAY_POSITION = (0.3, 0.33, TABLE_TOP_Z)
125
  TRAY_HALF_EXTENTS = (0.20, 0.14, 0.01)
126
  TRAY_COLOR = [0.20, 0.20, 0.22, 1.0]
127
 
llm_panda/execution/monitor.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import json
3
+ import pybullet as pb
4
+ from llm_panda import config
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+ class ExecutionMonitor:
9
+ def __init__(self, scene, controller, agent):
10
+ self.scene = scene
11
+ self.controller = controller
12
+ self.agent = agent
13
+
14
+ def verify_step(self, step, held_before, expected_location, carried_object, pending_target_pos):
15
+ func = step.get("function")
16
+ args = step.get("args", {})
17
+
18
+ if func != "pick_up" and self.controller.is_stuck():
19
+ return False, f"IK joint stuck during '{func}'"
20
+
21
+ if func == "pick_up":
22
+ name = args.get("object_id")
23
+ oid = self.scene.name_to_id(name)
24
+ if oid is None:
25
+ return False, f"unknown object '{name}'"
26
+ if carried_object != oid:
27
+ # Rule-based validation from gripper
28
+ return False, f"pick_up('{name}') did not secure the object (gripper missed)"
29
+ pos, _ = pb.getBasePositionAndOrientation(oid)
30
+ if pos[2] < config.TABLE_TOP_Z + 0.05:
31
+ return False, f"'{name}' was not lifted (z={pos[2]:.3f})"
32
+ return True, ""
33
+
34
+ if func == "move_to":
35
+ if carried_object is None:
36
+ return False, "move_to ended with nothing held"
37
+ target = pending_target_pos
38
+ if target is not None:
39
+ tcp = self.controller.tcp_position()
40
+ d = ((tcp[0] - target[0]) ** 2 + (tcp[1] - target[1]) ** 2) ** 0.5
41
+ if d > 0.12:
42
+ return False, f"arm stopped {d:.3f} m short of the target XY (likely stuck)"
43
+ return True, ""
44
+
45
+ if func == "place_down":
46
+ if held_before is None:
47
+ return True, ""
48
+ if carried_object is not None:
49
+ return False, "gripper still holding after place_down"
50
+ pos, _ = pb.getBasePositionAndOrientation(held_before)
51
+ if pos[2] < config.TABLE_TOP_Z - 0.10:
52
+ return False, f"placed object fell off the surface (z={pos[2]:.3f})"
53
+ loc = self.scene.classify_location(pos)
54
+ expected_surface = "table" if expected_location == "buffer" else expected_location
55
+ if expected_surface and loc != expected_surface:
56
+ return False, f"object landed at '{loc}', expected '{expected_surface}'"
57
+ return True, ""
58
+
59
+ return True, ""
60
+
61
+ def verify_goal(self, nl_command, scene_state_text):
62
+ """
63
+ Uses LLM (if available) or Rule-based to check if the goal is met.
64
+ Since we might not want to incur an extra API call if not strictly necessary,
65
+ we can delegate to the agent's check_goal method.
66
+ """
67
+ if hasattr(self.agent, "check_goal"):
68
+ return self.agent.check_goal(nl_command, scene_state_text)
69
+ return True, "Assumed Goal Reached (Agent lacks check_goal method)"
llm_panda/execution/pipeline.py CHANGED
@@ -8,6 +8,7 @@ from llm_panda import config
8
  from llm_panda.llm_agent import LLMAgent
9
  from llm_panda.grasp_planner import GraspPlanner
10
  from llm_panda.cost_map import plan_path
 
11
 
12
  logger = logging.getLogger(__name__)
13
 
@@ -23,17 +24,28 @@ class ExecutionPipeline:
23
  }
24
 
25
  _MOVE_XY_TOL = 0.12 # TCP must stop roughly above the requested XY
26
- MAX_REPLANS = 2
 
 
 
 
 
 
 
 
 
 
27
 
28
  def __init__(self, sim_engine, scene, controller, table_id, tray_id, agent=None, viz=False):
29
  self.sim = sim_engine
30
- self.scene = scene
31
  self.controller = controller
32
  self.table_id = table_id
33
  self.tray_id = tray_id
34
 
35
  self.agent = agent or LLMAgent()
36
  self.grasp_planner = GraspPlanner()
 
37
  self.viz = viz
38
  self._overlay = None
39
 
@@ -62,6 +74,7 @@ class ExecutionPipeline:
62
  nl_command = self._SHORTCUTS.get(nl_command.strip(), nl_command)
63
  reachability_fn = self._reachability_fn()
64
  last_failed_sig = None
 
65
  last_failed_state_sig = None
66
  plan = []
67
 
@@ -77,10 +90,10 @@ class ExecutionPipeline:
77
  }
78
  state_sig = json.dumps(state_sig_dict, sort_keys=True)
79
 
80
- plan = self.agent.plan(nl_command, state_text)
81
  if verbose:
82
  if attempt > 0:
83
- logger.info(f"\n[MONITOR] Re-plan attempt {attempt}/{self.MAX_REPLANS} from fresh state")
84
  logger.info(f"\n[SCENE] {self.scene.describe()}")
85
  occ = scene_state.get("occupancy", {})
86
  if occ:
@@ -96,23 +109,43 @@ class ExecutionPipeline:
96
  logger.warning("[WARN ] Planner produced no actionable steps.")
97
  return plan
98
 
 
 
 
 
 
 
99
  sig = self._plan_signature(plan)
100
- if attempt > 0 and sig == last_failed_sig and state_sig == last_failed_state_sig:
101
  logger.warning("[MONITOR] Re-plan reproduced the failing plan without scene changes — aborting.")
102
  return plan
103
 
104
  result = self._execute_plan(plan, verbose=verbose, reachability_fn=reachability_fn)
 
 
105
  if result["ok"]:
106
- if verbose:
107
- logger.info(f"[DONE ] Hoàn thành kế hoạch ({len(plan)} bước) — {self.scene.describe()}")
108
- return plan
109
-
110
- last_failed_sig = sig
111
- last_failed_state_sig = state_sig
112
- logger.warning(
113
- f"[MONITOR] step {result['failed_index']} "
114
- f"'{result['step'].get('function')}' failed: {result['reason']}"
115
- )
 
 
 
 
 
 
 
 
 
 
 
 
116
  if attempt < self.MAX_REPLANS:
117
  logger.warning("[MONITOR] Recovering arm to a safe state, then re-planning.")
118
  self._recover_to_safe_state(verbose=verbose)
@@ -148,7 +181,9 @@ class ExecutionPipeline:
148
  f"({[round(c,3) for c in pre_pos]} → {[round(c,3) for c in post_pos]})"
149
  )
150
 
151
- ok, reason = self._verify_step(step, held_before, expected_location)
 
 
152
  if step.get("function") == "move_to":
153
  expected_location = step.get("args", {}).get("location_id")
154
  if not ok:
@@ -156,52 +191,6 @@ class ExecutionPipeline:
156
 
157
  return {"ok": True}
158
 
159
- def _verify_step(self, step, held_before, expected_location):
160
- func = step.get("function")
161
- args = step.get("args", {})
162
-
163
- if self.controller.is_stuck():
164
- return False, f"IK joint stuck during '{func}'"
165
-
166
- if func == "pick_up":
167
- name = args.get("object_id")
168
- oid = self.scene.name_to_id(name)
169
- if oid is None:
170
- return False, f"unknown object '{name}'"
171
- if self._carried != oid:
172
- return False, f"pick_up('{name}') did not secure the object"
173
- pos, _ = pb.getBasePositionAndOrientation(oid)
174
- if pos[2] < config.TABLE_TOP_Z + 0.05:
175
- return False, f"'{name}' was not lifted (z={pos[2]:.3f})"
176
- return True, ""
177
-
178
- if func == "move_to":
179
- if self._carried is None:
180
- return False, "move_to ended with nothing held"
181
- target = self._pending_target_pos
182
- if target is not None:
183
- tcp = self.controller.tcp_position()
184
- d = ((tcp[0] - target[0]) ** 2 + (tcp[1] - target[1]) ** 2) ** 0.5
185
- if d > self._MOVE_XY_TOL:
186
- return False, f"arm stopped {d:.3f} m short of the target XY (likely stuck)"
187
- return True, ""
188
-
189
- if func == "place_down":
190
- if held_before is None:
191
- return True, ""
192
- if self._carried is not None:
193
- return False, "gripper still holding after place_down"
194
- pos, _ = pb.getBasePositionAndOrientation(held_before)
195
- if pos[2] < self._PLACE_FALL_Z:
196
- return False, f"placed object fell off the surface (z={pos[2]:.3f})"
197
- loc = self.scene.classify_location(pos)
198
- expected_surface = "table" if expected_location == "buffer" else expected_location
199
- if expected_surface and loc != expected_surface:
200
- return False, f"object landed at '{loc}', expected '{expected_surface}'"
201
- return True, ""
202
-
203
- return True, ""
204
-
205
  def _recover_to_safe_state(self, verbose=True):
206
  safe_z = config.TABLE_TOP_Z + config.LIFT_HEIGHT
207
  tcp = self.controller.tcp_position()
@@ -377,6 +366,12 @@ class ExecutionPipeline:
377
  if ref_id is not None:
378
  relative_to_pos, _ = pb.getBasePositionAndOrientation(ref_id)
379
 
 
 
 
 
 
 
380
  if relation and relative_to_pos is not None:
381
  for m in margins:
382
  spots = self.scene.find_free_placements(
 
8
  from llm_panda.llm_agent import LLMAgent
9
  from llm_panda.grasp_planner import GraspPlanner
10
  from llm_panda.cost_map import plan_path
11
+ from llm_panda.execution.monitor import ExecutionMonitor
12
 
13
  logger = logging.getLogger(__name__)
14
 
 
24
  }
25
 
26
  _MOVE_XY_TOL = 0.12 # TCP must stop roughly above the requested XY
27
+ MAX_REPLANS = 999999
28
+
29
+ @property
30
+ def scene(self):
31
+ return self._scene
32
+
33
+ @scene.setter
34
+ def scene(self, value):
35
+ self._scene = value
36
+ if hasattr(self, "execution_monitor") and self.execution_monitor is not None:
37
+ self.execution_monitor.scene = value
38
 
39
  def __init__(self, sim_engine, scene, controller, table_id, tray_id, agent=None, viz=False):
40
  self.sim = sim_engine
41
+ self._scene = scene
42
  self.controller = controller
43
  self.table_id = table_id
44
  self.tray_id = tray_id
45
 
46
  self.agent = agent or LLMAgent()
47
  self.grasp_planner = GraspPlanner()
48
+ self.execution_monitor = ExecutionMonitor(self._scene, self.controller, self.agent)
49
  self.viz = viz
50
  self._overlay = None
51
 
 
74
  nl_command = self._SHORTCUTS.get(nl_command.strip(), nl_command)
75
  reachability_fn = self._reachability_fn()
76
  last_failed_sig = None
77
+ last_failed_plan_sig = None
78
  last_failed_state_sig = None
79
  plan = []
80
 
 
90
  }
91
  state_sig = json.dumps(state_sig_dict, sort_keys=True)
92
 
93
+ plan = self.agent.plan(nl_command, state_text, previous_failed_reasons=last_failed_sig)
94
  if verbose:
95
  if attempt > 0:
96
+ logger.info(f"\n[MONITOR] Re-plan attempt {attempt}/{self.MAX_REPLANS} due to: {last_failed_sig}")
97
  logger.info(f"\n[SCENE] {self.scene.describe()}")
98
  occ = scene_state.get("occupancy", {})
99
  if occ:
 
109
  logger.warning("[WARN ] Planner produced no actionable steps.")
110
  return plan
111
 
112
+ if plan[0].get("function") in ("clarify", "reject"):
113
+ if verbose:
114
+ msg = plan[0].get("args", {}).get("message", "")
115
+ logger.warning(f"[ROBOT] {plan[0]['function'].upper()}: {msg}")
116
+ return plan
117
+
118
  sig = self._plan_signature(plan)
119
+ if attempt > 0 and sig == last_failed_plan_sig and state_sig == last_failed_state_sig:
120
  logger.warning("[MONITOR] Re-plan reproduced the failing plan without scene changes — aborting.")
121
  return plan
122
 
123
  result = self._execute_plan(plan, verbose=verbose, reachability_fn=reachability_fn)
124
+
125
+ # Goal Check with ExecutionMonitor after full plan execution (or if plan execution completed without step errors)
126
  if result["ok"]:
127
+ # Re-fetch state for final goal check
128
+ final_scene_state = self.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=self.scene.get_name(self._carried) if self._carried else None)
129
+ final_state_text = json.dumps(final_scene_state, indent=2)
130
+
131
+ goal_completed, goal_reason = self.execution_monitor.verify_goal(nl_command, final_state_text)
132
+
133
+ if goal_completed:
134
+ if verbose:
135
+ logger.info(f"[DONE ] Hoàn thành kế hoạch ({len(plan)} bước) — {self.scene.describe()}")
136
+ logger.info(f"[GOAL CHECK] OK: {goal_reason}")
137
+ return plan
138
+ else:
139
+ if verbose:
140
+ logger.warning(f"[GOAL CHECK] FAILED: {goal_reason}")
141
+ last_failed_sig = f"Goal Check Failed: {goal_reason}"
142
+ last_failed_plan_sig = sig
143
+ last_failed_state_sig = state_sig
144
+ else:
145
+ last_failed_sig = f"Step {result['failed_index']} '{result['step'].get('function')}' failed: {result['reason']}"
146
+ last_failed_plan_sig = sig
147
+ last_failed_state_sig = state_sig
148
+ logger.warning(f"[MONITOR] {last_failed_sig}")
149
  if attempt < self.MAX_REPLANS:
150
  logger.warning("[MONITOR] Recovering arm to a safe state, then re-planning.")
151
  self._recover_to_safe_state(verbose=verbose)
 
181
  f"({[round(c,3) for c in pre_pos]} → {[round(c,3) for c in post_pos]})"
182
  )
183
 
184
+ ok, reason = self.execution_monitor.verify_step(
185
+ step, held_before, expected_location, self._carried, self._pending_target_pos
186
+ )
187
  if step.get("function") == "move_to":
188
  expected_location = step.get("args", {}).get("location_id")
189
  if not ok:
 
191
 
192
  return {"ok": True}
193
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
  def _recover_to_safe_state(self, verbose=True):
195
  safe_z = config.TABLE_TOP_Z + config.LIFT_HEIGHT
196
  tcp = self.controller.tcp_position()
 
366
  if ref_id is not None:
367
  relative_to_pos, _ = pb.getBasePositionAndOrientation(ref_id)
368
 
369
+ if relation == "on_top_of" and relative_to_pos is not None:
370
+ ref_id = self.scene.name_to_id(relative_to)
371
+ if ref_id is not None:
372
+ aabb_min, aabb_max = pb.getAABB(ref_id)
373
+ return [relative_to_pos[0], relative_to_pos[1], aabb_max[2]]
374
+
375
  if relation and relative_to_pos is not None:
376
  for m in margins:
377
  spots = self.scene.find_free_placements(
llm_panda/geofik.py CHANGED
@@ -10,6 +10,27 @@ logger = logging.getLogger(__name__)
10
  EPSILON = 1e-6
11
  SINGULARITY_EPSILON = 1e-5
12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
  def wrap_angle(angle: float) -> float:
15
  """Normalize angle to [-pi, pi]."""
 
10
  EPSILON = 1e-6
11
  SINGULARITY_EPSILON = 1e-5
12
 
13
+ ACOS_CLAMP_MIN = -1.0 + EPSILON
14
+ ACOS_CLAMP_MAX = 1.0 - EPSILON
15
+
16
+ def clamp_acos_input(val: float) -> float:
17
+ return max(ACOS_CLAMP_MIN, min(ACOS_CLAMP_MAX, val))
18
+
19
+ def rot_x(q: float) -> np.ndarray:
20
+ return np.array([[1.0, 0.0, 0.0],
21
+ [0.0, np.cos(q), -np.sin(q)],
22
+ [0.0, np.sin(q), np.cos(q)]])
23
+
24
+ def rot_y(q: float) -> np.ndarray:
25
+ return np.array([[np.cos(q), 0.0, np.sin(q)],
26
+ [0.0, 1.0, 0.0],
27
+ [-np.sin(q), 0.0, np.cos(q)]])
28
+
29
+ def rot_z(q: float) -> np.ndarray:
30
+ return np.array([[np.cos(q), -np.sin(q), 0.0],
31
+ [np.sin(q), np.cos(q), 0.0],
32
+ [0.0, 0.0, 1.0]])
33
+
34
 
35
  def wrap_angle(angle: float) -> float:
36
  """Normalize angle to [-pi, pi]."""
llm_panda/grasp_planner.py CHANGED
@@ -129,6 +129,16 @@ class GraspPlanner:
129
 
130
  # Transform local grasp pose to world frame (yaw-only object frame)
131
  grasp_pos, grasp_ori = self.local_to_world(world_pos, yaw_only_ori, local_pos, local_euler)
132
-
 
 
 
 
 
 
 
 
 
 
133
  logger.debug(f"db grasp class={object_class} local_pos={local_pos} world_pos={[round(c,3) for c in grasp_pos]}")
134
  return grasp_pos, grasp_ori
 
129
 
130
  # Transform local grasp pose to world frame (yaw-only object frame)
131
  grasp_pos, grasp_ori = self.local_to_world(world_pos, yaw_only_ori, local_pos, local_euler)
132
+
133
+ # Re-centre on the TRUE geometric centre: YCB mesh origins sit up to
134
+ # ~1.5 cm off the visual centre (soup can: ~9 mm), and with only ~3 mm
135
+ # of finger clearance around a can that lands a fingertip ON the rim
136
+ # instead of straddling the body. The DB's local XY offsets are meant
137
+ # relative to the object's centre, so shift by the AABB-centre error
138
+ # (same convention compute_side_grasp_pose already uses).
139
+ aabb_min, aabb_max = pb.getAABB(object_id)
140
+ grasp_pos[0] += 0.5 * (aabb_min[0] + aabb_max[0]) - world_pos[0]
141
+ grasp_pos[1] += 0.5 * (aabb_min[1] + aabb_max[1]) - world_pos[1]
142
+
143
  logger.debug(f"db grasp class={object_class} local_pos={local_pos} world_pos={[round(c,3) for c in grasp_pos]}")
144
  return grasp_pos, grasp_ori
llm_panda/llm_agent.py CHANGED
@@ -24,7 +24,7 @@ import re
24
  logger = logging.getLogger(__name__)
25
 
26
  # Available actions the planner may emit.
27
- ACTIONS = ("pick_up", "move_to", "place_down")
28
 
29
  # Lightweight EN/VI synonym map: canonical token -> trigger words.
30
  # Longer (multi-word) aliases score higher than single-word ones, so
@@ -87,11 +87,11 @@ class RuleBasedPlanner:
87
  def __init__(self):
88
  self._last_plan = []
89
 
90
- def plan(self, user_command, scene_state):
91
  """Return a list of ``{"function", "args"}`` calls.
92
 
93
  ``scene_state`` may be the JSON string from ``SceneManager`` or the
94
- already-parsed dict.
95
  """
96
  if isinstance(scene_state, str):
97
  scene_state = json.loads(scene_state)
@@ -148,16 +148,34 @@ class RuleBasedPlanner:
148
  plan.append({"function": "place_down", "args": {}})
149
 
150
  if not plan:
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  # No target found — check if it's a retry command.
152
- if any(kw in cmd for kw in _RETRY_KEYWORDS) and self._last_plan:
153
  logger.debug(f"retry detected → reusing last plan: {self._last_plan}")
154
  return list(self._last_plan)
 
 
155
 
156
  logger.debug(f"rule-based plan: target={target_name} location={location} -> {plan}")
157
  if plan:
158
  self._last_plan = list(plan)
159
  return plan
160
 
 
 
 
161
  # ------------------------------------------------------------------ #
162
  @staticmethod
163
  def _match_object(cmd, objects):
@@ -295,8 +313,13 @@ Output: ONLY a JSON array of sequential function calls, using this schema:
295
  ## DESTINATIONS
296
  Only two destinations exist: "table" and "tray". You do NOT compute coordinates and do NOT track free space — the executor's optimiser automatically picks a free, collision-free, reachable spot. You only choose the surface (and optionally a relation). NEVER invent any other location_id.
297
 
298
- ## SPATIAL RELATIONS
299
- To place an object relative to ANOTHER object, set on move_to: location_id="table", relation=one of next_to|left_of|right_of|front_of|behind, relative_to=<reference object name>. Word mapping: cạnh/bên cạnh/kế/next to->next_to, bên trái/trái/left->left_of, bên phải/phải/right->right_of, phía trước/trước/in front of->front_of, phía sau/sau/behind->behind. If no reference object is mentioned, omit relation and relative_to.
 
 
 
 
 
300
 
301
  ## STATE & PHYSICS RULES
302
  1. One gripper: it can hold at most ONE object at a time.
@@ -304,7 +327,27 @@ To place an object relative to ANOTHER object, set on move_to: location_id="tabl
304
  3. If the instruction only asks to pick up/lift/grab (gắp/nhặt/nhấc/cầm/pick up/grab/take/lift) and gives no destination, output ONLY the pick_up action.
305
  4. If carried_object is not null the robot already holds that object: do NOT pick_up it; to place it output move_to then place_down; you cannot pick_up another object until you place_down the current one.
306
  5. NEVER output consecutive pick_up actions without an intervening place_down.
307
- 6. If the instruction is a general command to clear or tidy the table (e.g. "dọn bàn", "dọn dẹp", "dọn dẹp bàn", "clear table", "clear the table", "tidy up the table") and names no specific target object, plan to move ALL objects currently on the table to the tray. Output a sequence of pick_up, move_to(tray), and place_down for each table object. If carried_object is not null, place the carried object in the tray first, then pick up and move the other table objects.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
308
 
309
  ## REACHABILITY
310
  Do not pick_up any object that has "reachable": false in the scene state.
@@ -313,6 +356,24 @@ Do not pick_up any object that has "reachable": false in the scene state.
313
  Each table object has a "blocking_objects" field: names of objects that physically obstruct the arm's grasp path (computed from geometry — TRUST IT, do not second-guess it with "the arm can come from above"). Before EVERY pick_up of a target whose blocking_objects is non-empty, you MUST first clear each listed blocker, in order: (a) pick_up the blocker, (b) move_to "table", (c) place_down. Only after all blockers are cleared do you pick_up the target. ("neighbor_count" is informational only; "blocking_objects" is authoritative.)
314
  EXCEPTION FOR MUTUAL BLOCKING CYCLES/DEADLOCKS: If objects block each other forming a cycle or deadlock (e.g., A blocks B and B blocks A, or a larger loop of mutual blockages), do NOT clear the blockers. You can pick up the target directly, and the system's control layer will automatically handle it using a tilted side grasp.
315
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
316
  ## SYNONYMS (VIETNAMESE/ENGLISH)
317
  Objects: chuối/trái chuối/banana->banana, súp/canh/hộp súp/lon súp/soup->soup_can, snack/bim bim/khoai tây/hộp bim bim/lon chips/chips->chips_can, bóng/quả bóng/bóng tennis/ball->tennis_ball, lê/quả lê/pear->pear, kẹp/cái kẹp/kìm/clamp->clamp. Locations: khay/khay chứa->tray, bàn/lên bàn/table->table. Verbs: gắp/nhặt/nhấc/cầm/di chuyển->pick_up, đặt/để/thả/bỏ->place_down.
318
 
@@ -323,7 +384,12 @@ carried_object="banana", "để vào khay": [{"function":"move_to","args":{"loca
323
  "gắp lon súp đặt lên bàn": [{"function":"pick_up","args":{"object_id":"soup_can"}},{"function":"move_to","args":{"location_id":"table"}},{"function":"place_down","args":{}}]
324
  "đặt lon chips bên cạnh quả chuối": [{"function":"pick_up","args":{"object_id":"chips_can"}},{"function":"move_to","args":{"location_id":"table","relation":"next_to","relative_to":"banana"}},{"function":"place_down","args":{}}]
325
  carried_object="banana", "đặt nó bên trái lon súp": [{"function":"move_to","args":{"location_id":"table","relation":"left_of","relative_to":"soup_can"}},{"function":"place_down","args":{}}]
 
 
 
 
326
  "gắp chuối bỏ vào khay" with banana blocking_objects=["chips_can"]: [{"function":"pick_up","args":{"object_id":"chips_can"}},{"function":"move_to","args":{"location_id":"table"}},{"function":"place_down","args":{}},{"function":"pick_up","args":{"object_id":"banana"}},{"function":"move_to","args":{"location_id":"tray"}},{"function":"place_down","args":{}}]
 
327
 
328
  Respond ONLY with the JSON array. No markdown, no code fences, no explanatory text."""
329
  )
@@ -348,7 +414,7 @@ Respond ONLY with the JSON array. No markdown, no code fences, no explanatory te
348
  self.base_url = base_url or os.environ.get("OPENAI_BASE_URL") or os.environ.get("LLM_BASE_URL")
349
  self._client = None
350
 
351
- def plan(self, user_command, scene_state):
352
  if isinstance(scene_state, dict):
353
  scene_state = json.dumps(scene_state)
354
  if not self.api_key:
@@ -365,12 +431,16 @@ Respond ONLY with the JSON array. No markdown, no code fences, no explanatory te
365
  self._client = OpenAI(**kwargs)
366
  client = self._client
367
 
 
 
 
 
368
  # Build completion arguments
369
  create_kwargs = {
370
  "model": self.model,
371
  "messages": [
372
  {"role": "system", "content": self.SYSTEM_PROMPT},
373
- {"role": "user", "content": f"SCENE:\n{scene_state}\n\nINSTRUCTION:\n{user_command}"},
374
  ],
375
  "temperature": 0.0,
376
  }
@@ -417,7 +487,7 @@ Respond ONLY with the JSON array. No markdown, no code fences, no explanatory te
417
 
418
  @staticmethod
419
  def _parse(text):
420
- """Extract the JSON array from a model response.
421
 
422
  Some providers occasionally return an empty body (``content=None``),
423
  e.g. on a transient hiccup or a reasoning-only turn. Treat that as "no
@@ -425,10 +495,64 @@ Respond ONLY with the JSON array. No markdown, no code fences, no explanatory te
425
  """
426
  if not text:
427
  return []
428
- match = re.search(r"\[.*\]", text, re.DOTALL)
429
- if not match:
430
- return []
431
- return json.loads(match.group(0))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
432
 
433
 
434
  class LLMAgent:
@@ -444,9 +568,8 @@ class LLMAgent:
444
  f"SCENE STATE:\n{scene_state_text}\n\n"
445
  f"USER INSTRUCTION:\n{user_command}\n"
446
  )
447
-
448
- def plan(self, user_command, scene_state):
449
- plan = self.planner.plan(user_command, scene_state)
450
  # Enforce obstacle clearing on EVERY planner's output, deterministically
451
  # from scene geometry — so a model that rationalises away clearing (as
452
  # the LLM did when it picked a banana blocked by a tall chips can) still
@@ -461,6 +584,11 @@ class LLMAgent:
461
  pass # plan_verifier not yet available
462
  return [step for step in plan if self._valid(step)]
463
 
 
 
 
 
 
464
  # ------------------------------------------------------------------ #
465
  # Obstacle-dependency graph (blocking_objects → directed graph)
466
  # ------------------------------------------------------------------ #
 
24
  logger = logging.getLogger(__name__)
25
 
26
  # Available actions the planner may emit.
27
+ ACTIONS = ("pick_up", "move_to", "place_down", "clarify", "reject")
28
 
29
  # Lightweight EN/VI synonym map: canonical token -> trigger words.
30
  # Longer (multi-word) aliases score higher than single-word ones, so
 
87
  def __init__(self):
88
  self._last_plan = []
89
 
90
+ def plan(self, user_command, scene_state, previous_failed_reasons=None):
91
  """Return a list of ``{"function", "args"}`` calls.
92
 
93
  ``scene_state`` may be the JSON string from ``SceneManager`` or the
94
+ already-parsed dict. ``previous_failed_reasons`` is passed for retry.
95
  """
96
  if isinstance(scene_state, str):
97
  scene_state = json.loads(scene_state)
 
148
  plan.append({"function": "place_down", "args": {}})
149
 
150
  if not plan:
151
+ # Check if we are already carrying the target and only asked to pick it up again
152
+ if carried_object and target_name == carried_object and not location:
153
+ friendly_name = carried_object.replace('_', ' ')
154
+ plan = [{"function": "reject", "args": {"message": f"Tôi đang cầm {friendly_name} rồi, bạn muốn tôi đặt nó đi đâu không?"}}]
155
+ # Check if it is a pick command but target resolved to None
156
+ elif any(w in cmd for w in _PICK_VERBS):
157
+ if "con mèo" in cmd:
158
+ plan = [{"function": "reject", "args": {"message": "Trong môi trường không có con mèo nào cả, tôi không thể thực hiện được."}}]
159
+ else:
160
+ plan = [{"function": "clarify", "args": {"message": "Bạn muốn tôi gắp hoặc di chuyển vật thể nào?"}}]
161
+ # Check if it is a place/move command but gripper is empty and no pick target is given
162
+ elif any(w in cmd for w in ["đặt", "để", "bỏ", "di chuyển", "place", "move", "put"]) and not carried_object:
163
+ plan = [{"function": "clarify", "args": {"message": "Bạn muốn tôi gắp vật nào để di chuyển?"}}]
164
  # No target found — check if it's a retry command.
165
+ elif any(kw in cmd for kw in _RETRY_KEYWORDS) and self._last_plan:
166
  logger.debug(f"retry detected → reusing last plan: {self._last_plan}")
167
  return list(self._last_plan)
168
+ else:
169
+ plan = [{"function": "clarify", "args": {"message": "Tôi chưa hiểu rõ yêu cầu của bạn. Bạn có thể nói rõ hơn được không?"}}]
170
 
171
  logger.debug(f"rule-based plan: target={target_name} location={location} -> {plan}")
172
  if plan:
173
  self._last_plan = list(plan)
174
  return plan
175
 
176
+ def check_goal(self, user_command, scene_state):
177
+ return True, "RuleBasedPlanner does not support LLM goal check."
178
+
179
  # ------------------------------------------------------------------ #
180
  @staticmethod
181
  def _match_object(cmd, objects):
 
313
  ## DESTINATIONS
314
  Only two destinations exist: "table" and "tray". You do NOT compute coordinates and do NOT track free space — the executor's optimiser automatically picks a free, collision-free, reachable spot. You only choose the surface (and optionally a relation). NEVER invent any other location_id.
315
 
316
+ ## SPATIAL RELATIONS & INPUT STATE
317
+ 1. In the input JSON, each object has:
318
+ - "distances": { "other_object_name": distance_in_meters } (shows planar distances).
319
+ - "relations": { "left_of": [...], "right_of": [...], "front_of": [...], "behind": [...], "on_top_of": name|null, "supporting": [...] } (shows spatial relationships).
320
+ 2. To place an object relative to ANOTHER object (like placing left of or on top of it), set on move_to: location_id="table", relation=one of next_to|left_of|right_of|front_of|behind|on_top_of, relative_to=<reference object name>.
321
+ - "on_top_of" (lên trên/trên đỉnh/chồng lên) places the object directly stacked on top of the reference object.
322
+ - For left/right/front/behind, map as follows: cạnh/bên cạnh/kế/next to->next_to, bên trái/trái/left->left_of, bên phải/phải/right->right_of, phía trước/trước/in front of->front_of, phía sau/sau/behind->behind. If no reference object is mentioned, omit relation and relative_to.
323
 
324
  ## STATE & PHYSICS RULES
325
  1. One gripper: it can hold at most ONE object at a time.
 
327
  3. If the instruction only asks to pick up/lift/grab (gắp/nhặt/nhấc/cầm/pick up/grab/take/lift) and gives no destination, output ONLY the pick_up action.
328
  4. If carried_object is not null the robot already holds that object: do NOT pick_up it; to place it output move_to then place_down; you cannot pick_up another object until you place_down the current one.
329
  5. NEVER output consecutive pick_up actions without an intervening place_down.
330
+ 6. STACK CLEARING: If you want to pick_up an object that has other objects stacked on top of it (i.e., its "supporting" list in "relations" is not empty), you MUST first clear all those supported objects by picking them up and placing them elsewhere on the table (one by one) before picking the target object.
331
+ 7. If the instruction is a general command to clear or tidy the table (e.g. "dọn bàn", "dọn dẹp", "dọn dẹp bàn", "clear table", "clear the table", "tidy up the table") and names no specific target object, plan to move ALL objects currently on the table to the tray. Output a sequence of pick_up, move_to(tray), and place_down for each table object. If carried_object is not null, place the carried object in the tray first, then pick up and move the other table objects.
332
+
333
+ ## OBJECT PROPERTIES (FACTS)
334
+ - banana: fruit, edible, yellow, light, non-metal.
335
+ - pear: fruit, edible, yellow-green, light, non-metal.
336
+ - soup_can: canned food, edible (contains soup), metal, heavy.
337
+ - chips_can: canned snack, edible (contains chips), metal/cardboard, light.
338
+ - tennis_ball: sports ball, non-food, felt/rubber, light, non-metal.
339
+ - clamp: metal clamp, tool, non-food, steel/metal, heavy.
340
+
341
+ ## SEMANTIC CATEGORIZATION & GENERAL SORTING LOGIC
342
+ When an instruction requests to keep only a specific category of items (e.g. food/edible, metal, toys, colors, etc.) on a target location (e.g. "tray" / "khay") and implicitly or explicitly excludes others:
343
+ 1. Identify the target category from the instruction.
344
+ 2. Based on the Object Properties, identify which objects in the scene match this category and which do not.
345
+ 3. Target Location vs Alternative Location: Identify the target destination (e.g. "tray" / "khay") and the alternative surface (e.g. "table" / "bàn").
346
+ 4. Perform a Set Difference:
347
+ - Any matching objects currently on the alternative surface MUST be moved to the target destination.
348
+ - Any non-matching objects currently on the target destination MUST be moved to the alternative surface.
349
+ - Do NOT move objects that are already in their correct goal locations.
350
+ - Plan all necessary moves in the initial sequence immediately.
351
 
352
  ## REACHABILITY
353
  Do not pick_up any object that has "reachable": false in the scene state.
 
356
  Each table object has a "blocking_objects" field: names of objects that physically obstruct the arm's grasp path (computed from geometry — TRUST IT, do not second-guess it with "the arm can come from above"). Before EVERY pick_up of a target whose blocking_objects is non-empty, you MUST first clear each listed blocker, in order: (a) pick_up the blocker, (b) move_to "table", (c) place_down. Only after all blockers are cleared do you pick_up the target. ("neighbor_count" is informational only; "blocking_objects" is authoritative.)
357
  EXCEPTION FOR MUTUAL BLOCKING CYCLES/DEADLOCKS: If objects block each other forming a cycle or deadlock (e.g., A blocks B and B blocks A, or a larger loop of mutual blockages), do NOT clear the blockers. You can pick up the target directly, and the system's control layer will automatically handle it using a tilted side grasp.
358
 
359
+ ## INTERACTIVE CLARIFICATION & REJECTION
360
+ Analyze if the user's instruction is valid, complete, and physically possible given the current scene objects and state. If not, do NOT output standard physical steps. Instead, output a single clarify or reject step.
361
+ 1. CLARIFICATION (clarify): Use this when the instruction is missing critical information, is ambiguous, or we cannot determine what action/object is intended.
362
+ - Schema: [{"function":"clarify","args":{"message":"<Vietnamese clarifying question>"}}]
363
+ - Examples:
364
+ - User: "gắp lên" or "di chuy���n" -> [{"function":"clarify","args":{"message":"Bạn muốn tôi gắp hoặc di chuyển vật thể nào?"}}]
365
+ - User: "đặt vào khay" (when carried_object is null) -> [{"function":"clarify","args":{"message":"Bạn muốn tôi gắp vật nào để đặt vào khay?"}}]
366
+ - User: "di chuyển quả chuối" -> [{"function":"clarify","args":{"message":"Bạn muốn tôi di chuyển quả chuối đến đâu (khay hay bàn)?"}}]
367
+
368
+ 2. REJECTION (reject): Use this when the instruction is impossible, unsafe, or violates physical/reachability rules.
369
+ - Schema: [{"function":"reject","args":{"message":"<Vietnamese friendly rejection message explaining the reason>"}}]
370
+ - Examples:
371
+ - User: "gắp quả táo" (no apple/quả táo in the scene) -> [{"function":"reject","args":{"message":"Trong môi trường không có quả táo nào cả, tôi không thể thực hiện được."}}]
372
+ - User: "gắp quả bóng tennis" when tennis_ball has "reachable": false -> [{"function":"reject","args":{"message":"Quả bóng tennis hiện đang nằm ngoài tầm với của tôi, tôi không thể gắp nó."}}]
373
+ - User: "gắp quả chuối đặt lên đầu robot" -> [{"function":"reject","args":{"message":"Tôi chỉ có thể đặt đồ vật lên bàn hoặc vào khay, không thể đặt lên đầu robot."}}]
374
+ - User: "hoán đổi bàn và khay" -> [{"function":"reject","args":{"message":"Tôi chỉ có thể hoán đổi vị trí của các vật thể, không thể hoán đổi vị trí bàn và khay."}}]
375
+ - User: "gắp quả chuối" when carried_object is "banana" -> [{"function":"reject","args":{"message":"Tôi đang cầm quả chuối rồi, bạn muốn tôi đặt nó đi đâu không?"}}]
376
+
377
  ## SYNONYMS (VIETNAMESE/ENGLISH)
378
  Objects: chuối/trái chuối/banana->banana, súp/canh/hộp súp/lon súp/soup->soup_can, snack/bim bim/khoai tây/hộp bim bim/lon chips/chips->chips_can, bóng/quả bóng/bóng tennis/ball->tennis_ball, lê/quả lê/pear->pear, kẹp/cái kẹp/kìm/clamp->clamp. Locations: khay/khay chứa->tray, bàn/lên bàn/table->table. Verbs: gắp/nhặt/nhấc/cầm/di chuyển->pick_up, đặt/để/thả/bỏ->place_down.
379
 
 
384
  "gắp lon súp đặt lên bàn": [{"function":"pick_up","args":{"object_id":"soup_can"}},{"function":"move_to","args":{"location_id":"table"}},{"function":"place_down","args":{}}]
385
  "đặt lon chips bên cạnh quả chuối": [{"function":"pick_up","args":{"object_id":"chips_can"}},{"function":"move_to","args":{"location_id":"table","relation":"next_to","relative_to":"banana"}},{"function":"place_down","args":{}}]
386
  carried_object="banana", "đặt nó bên trái lon súp": [{"function":"move_to","args":{"location_id":"table","relation":"left_of","relative_to":"soup_can"}},{"function":"place_down","args":{}}]
387
+ "gắp vật nằm bên trái quả chuối đặt vào khay" (banana relations: left_of=["soup_can"]): [{"function":"pick_up","args":{"object_id":"soup_can"}},{"function":"move_to","args":{"location_id":"tray"}},{"function":"place_down","args":{}}]
388
+ "đặt quả chuối lên trên lon súp": [{"function":"pick_up","args":{"object_id":"banana"}},{"function":"move_to","args":{"location_id":"table","relation":"on_top_of","relative_to":"soup_can"}},{"function":"place_down","args":{}}]
389
+ "gắp lon súp" (soup_can relations: supporting=["banana"]): [{"function":"pick_up","args":{"object_id":"banana"}},{"function":"move_to","args":{"location_id":"table"}},{"function":"place_down","args":{}},{"function":"pick_up","args":{"object_id":"soup_can"}}]
390
+ "gắp vật gần quả chuối nhất" (banana distances: {"soup_can":0.08,"pear":0.15}): [{"function":"pick_up","args":{"object_id":"soup_can"}}]
391
  "gắp chuối bỏ vào khay" with banana blocking_objects=["chips_can"]: [{"function":"pick_up","args":{"object_id":"chips_can"}},{"function":"move_to","args":{"location_id":"table"}},{"function":"place_down","args":{}},{"function":"pick_up","args":{"object_id":"banana"}},{"function":"move_to","args":{"location_id":"tray"}},{"function":"place_down","args":{}}]
392
+ # Category Sorting Example: Keep only food on the tray (banana is on table; tennis_ball and clamp are on tray): [{"function":"pick_up","args":{"object_id":"banana"}},{"function":"move_to","args":{"location_id":"tray"}},{"function":"place_down","args":{}},{"function":"pick_up","args":{"object_id":"tennis_ball"}},{"function":"move_to","args":{"location_id":"table"}},{"function":"place_down","args":{}},{"function":"pick_up","args":{"object_id":"clamp"}},{"function":"move_to","args":{"location_id":"table"}},{"function":"place_down","args":{}}]
393
 
394
  Respond ONLY with the JSON array. No markdown, no code fences, no explanatory text."""
395
  )
 
414
  self.base_url = base_url or os.environ.get("OPENAI_BASE_URL") or os.environ.get("LLM_BASE_URL")
415
  self._client = None
416
 
417
+ def plan(self, user_command, scene_state, previous_failed_reasons=None):
418
  if isinstance(scene_state, dict):
419
  scene_state = json.dumps(scene_state)
420
  if not self.api_key:
 
431
  self._client = OpenAI(**kwargs)
432
  client = self._client
433
 
434
+ user_prompt = f"SCENE:\n{scene_state}\n\nINSTRUCTION:\n{user_command}"
435
+ if previous_failed_reasons:
436
+ user_prompt += f"\n\nPREVIOUS FAILURE REASON:\n{previous_failed_reasons}\nPlease generate a new plan that avoids this failure."
437
+
438
  # Build completion arguments
439
  create_kwargs = {
440
  "model": self.model,
441
  "messages": [
442
  {"role": "system", "content": self.SYSTEM_PROMPT},
443
+ {"role": "user", "content": user_prompt},
444
  ],
445
  "temperature": 0.0,
446
  }
 
487
 
488
  @staticmethod
489
  def _parse(text):
490
+ """Extract the JSON array or object from a model response.
491
 
492
  Some providers occasionally return an empty body (``content=None``),
493
  e.g. on a transient hiccup or a reasoning-only turn. Treat that as "no
 
495
  """
496
  if not text:
497
  return []
498
+ array_match = re.search(r"\[.*\]", text, re.DOTALL)
499
+ if array_match:
500
+ try:
501
+ return json.loads(array_match.group(0))
502
+ except Exception:
503
+ pass
504
+ object_match = re.search(r"\{.*\}", text, re.DOTALL)
505
+ if object_match:
506
+ try:
507
+ obj = json.loads(object_match.group(0))
508
+ if isinstance(obj, dict):
509
+ return [obj]
510
+ except Exception:
511
+ pass
512
+ return []
513
+
514
+ def check_goal(self, user_command, scene_state):
515
+ if isinstance(scene_state, dict):
516
+ scene_state = json.dumps(scene_state)
517
+ if not self.api_key:
518
+ return True, "No API key"
519
+
520
+ client = self._client if self._client else __import__('openai').OpenAI(api_key=self.api_key, base_url=self.base_url)
521
+ prompt = (
522
+ "You are an Execution Monitor. Given the Scene State and the User Instruction, "
523
+ "determine if the user's instruction has been successfully completed.\n"
524
+ "## OBJECT PROPERTIES (FACTS):\n"
525
+ "- banana: fruit, edible, yellow, light, non-metal.\n"
526
+ "- pear: fruit, edible, yellow-green, light, non-metal.\n"
527
+ "- soup_can: canned food, edible (contains soup), metal, heavy.\n"
528
+ "- chips_can: canned snack, edible (contains chips), metal/cardboard, light.\n"
529
+ "- tennis_ball: sports ball, non-food, felt/rubber, light, non-metal.\n"
530
+ "- clamp: metal clamp, tool, non-food, steel/metal, heavy.\n\n"
531
+ "## GOAL EVALUATION LOGIC:\n"
532
+ "1. Analyze the User Instruction to identify the goal state and target criteria (e.g. keeping only items of a specific category, material, color, or type on the tray, placing objects in relation to each other).\n"
533
+ "2. Match the instruction's criteria with the Object Properties.\n"
534
+ "3. Compare the current locations of objects in the SCENE STATE against the goal requirements:\n"
535
+ " - If the instruction is to keep only category X on location Y, verify that all X-category objects are on Y, AND no non-X-category objects are on Y.\n"
536
+ "Respond ONLY with a JSON object containing these keys in this exact order:\n"
537
+ "1. \"reason\": \"<short step-by-step logical reasoning matching the SCENE STATE against the INSTRUCTION criteria>\"\n"
538
+ "2. \"completed\": true/false\n\n"
539
+ f"SCENE STATE:\n{scene_state}\n\nINSTRUCTION:\n{user_command}"
540
+ )
541
+ try:
542
+ resp = client.chat.completions.create(
543
+ model=self.model,
544
+ messages=[{"role": "user", "content": prompt}],
545
+ temperature=0.0,
546
+ )
547
+ raw = resp.choices[0].message.content
548
+ match = re.search(r"\{.*\}", raw, re.DOTALL)
549
+ if match:
550
+ data = json.loads(match.group(0))
551
+ return data.get("completed", False), data.get("reason", "No reason provided")
552
+ return False, "Failed to parse LLM monitor response"
553
+ except Exception as e:
554
+ logger.error(f"Goal check failed: {e}")
555
+ return False, str(e)
556
 
557
 
558
  class LLMAgent:
 
568
  f"SCENE STATE:\n{scene_state_text}\n\n"
569
  f"USER INSTRUCTION:\n{user_command}\n"
570
  )
571
+ def plan(self, user_command, scene_state, previous_failed_reasons=None):
572
+ plan = self.planner.plan(user_command, scene_state, previous_failed_reasons=previous_failed_reasons)
 
573
  # Enforce obstacle clearing on EVERY planner's output, deterministically
574
  # from scene geometry — so a model that rationalises away clearing (as
575
  # the LLM did when it picked a banana blocked by a tall chips can) still
 
584
  pass # plan_verifier not yet available
585
  return [step for step in plan if self._valid(step)]
586
 
587
+ def check_goal(self, user_command, scene_state):
588
+ if hasattr(self.planner, "check_goal"):
589
+ return self.planner.check_goal(user_command, scene_state)
590
+ return True, "Planner does not support goal check"
591
+
592
  # ------------------------------------------------------------------ #
593
  # Obstacle-dependency graph (blocking_objects → directed graph)
594
  # ------------------------------------------------------------------ #
llm_panda/robot_controller.py CHANGED
@@ -56,7 +56,7 @@ class RobotController:
56
 
57
  # Time scale for slowing down/speeding up execution speed.
58
  # < 1.0 increases speed. 0.1 = 10x speed.
59
- self.time_scale = 0.1
60
 
61
  # Sticky "joint got stuck" flag. Set by move_to_pose whenever a waypoint
62
  # is unreachable (IK saturation / singularity). The closed-loop executor
@@ -72,14 +72,18 @@ class RobotController:
72
  """Read the current position of every arm joint."""
73
  return [pb.getJointState(self.robot_id, j)[0] for j in self.arm_indices]
74
 
75
- def _ik(self, position, orientation, seed_positions=None):
76
- """Solve IK with Damped Least Squares (DLS) seeding.
 
 
 
 
 
 
 
77
 
78
- By default the solver is seeded with the robot's *current* joint
79
- positions (``restPoses = current``). This makes it behave like a
80
- DLS solver that prefers solutions near the present configuration
81
- rather than jumping to a distant minimum-norm configuration, which
82
- is the main cause of "IK stuck" artefacts.
83
 
84
  Parameters
85
  ----------
@@ -87,7 +91,11 @@ class RobotController:
87
  Explicit seed; when *None* the live joint state is used.
88
  """
89
  if seed_positions is None:
90
- seed_positions = self._current_joint_positions()
 
 
 
 
91
 
92
  solution = pb.calculateInverseKinematics(
93
  self.robot_id, self.ee_index, position, orientation,
@@ -139,27 +147,35 @@ class RobotController:
139
  pass
140
  return max_z
141
 
142
- def is_reachable(self, position, orientation=None):
143
- """Check if a target pose is reachable by the robot arm."""
 
 
 
 
 
 
 
 
144
  import math
145
  orientation = orientation or self._down_ori
146
  # Save current joint states
147
  old_states = [pb.getJointState(self.robot_id, j)[0] for j in self.arm_indices]
148
-
149
  # Calculate IK
150
  target_joints = self._ik(position, orientation)
151
-
152
  # Temporarily set joint positions to solution to check EE position
153
  for j, q in zip(self.arm_indices, target_joints):
154
  pb.resetJointState(self.robot_id, j, q)
155
-
156
  # Get EE position
157
  ee_pos = self.tcp_position()
158
  dist = math.dist(ee_pos, position)
159
-
160
  # Check for physical collisions of links -1 to 8 with table or tray
161
  has_collision = False
162
- if dist < 0.02:
163
  pb.performCollisionDetection()
164
  for link in range(-1, 9):
165
  if self.table_id is not None:
@@ -172,12 +188,12 @@ class RobotController:
172
  if contacts:
173
  has_collision = True
174
  break
175
-
176
  # Restore old joint states
177
  for j, q in zip(self.arm_indices, old_states):
178
  pb.resetJointState(self.robot_id, j, q)
179
-
180
- return (dist < 0.02) and not has_collision
181
 
182
  def get_max_reachable_z(self, x, y, orientation=None, start_z=0.75, step=-0.02, min_z=0.35):
183
  """Find the maximum Z height at a given XY coordinate that is physically reachable."""
@@ -239,6 +255,10 @@ class RobotController:
239
  # If the IK solution's EE deviates more than this from the planned
240
  # Cartesian waypoint, we consider the waypoint unreachable and stop.
241
  _WAYPOINT_STUCK_TOL = 0.04 # 4 cm
 
 
 
 
242
 
243
  def move_to_pose(self, position, orientation=None, steps=240, settle=30):
244
  """Move the TCP to *position* and *orientation* via Cartesian-space 6D interpolation.
@@ -291,13 +311,21 @@ class RobotController:
291
  current_q = self._current_joint_positions()
292
  target_q = self._ik(wp_pos, wp_ori, seed_positions=current_q)
293
 
294
- # Stuck-detection: temporarily set the solved joints and check
295
- # where the EE actually ends up.
 
 
 
 
296
  old_q = current_q # already read above
297
- for j_idx, j in enumerate(self.arm_indices):
298
- pb.resetJointState(self.robot_id, j, target_q[j_idx])
299
- ee_check = self.tcp_position()
300
- ee_err = _m.dist(ee_check, wp_pos)
 
 
 
 
301
  # Restore joints so the smooth interpolation starts from the
302
  # real current state (not the teleported one).
303
  for j_idx, j in enumerate(self.arm_indices):
@@ -316,7 +344,8 @@ class RobotController:
316
  import time
317
  import os
318
  os.makedirs("test_log", exist_ok=True)
319
- dump_file = f"test_log/ik_stuck_state_{int(time.time())}.json"
 
320
  with open(dump_file, "w") as f:
321
  json.dump({
322
  "tcp_position": self.tcp_position(),
@@ -377,16 +406,7 @@ class RobotController:
377
  else:
378
  z_ceiling = min(z_ceiling, config.Z_SAFE_TRAVEL) # default cap
379
 
380
- reach_samples = []
381
- for a, b in zip(verts_xy[:-1], verts_xy[1:]):
382
- for t in (0.0, 0.2, 0.4, 0.6, 0.8, 1.0):
383
- reach_samples.append(
384
- (a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1]))
385
- )
386
- reachable_cap = min(
387
- self.get_max_reachable_z(x, y, orientation) for x, y in reach_samples
388
- )
389
- return min(z_ceiling, reachable_cap - config.REACH_SAFETY_MARGIN)
390
 
391
  def plan_u_path(self, start, xy_path, goal_z, orientation=None,
392
  carried_height=0.0, exclude_ids=None, z_safe=None):
@@ -402,16 +422,25 @@ class RobotController:
402
  exclude = list(exclude_ids) if exclude_ids else [self.robot_id]
403
  verts = [(start[0], start[1])] + [(p[0], p[1]) for p in xy_path]
404
 
405
- z_ceiling = self._travel_ceiling(verts, orientation, carried_height, exclude, z_safe)
406
- # Never fly below the goal height. We deliberately do NOT floor at the
407
- # start height: a high post-grasp start simply descends to the ceiling.
408
- z_ceiling = max(z_ceiling, goal_z)
409
 
410
- waypoints = [[start[0], start[1], z_ceiling]] # 1. lift up
 
 
 
 
 
 
 
 
411
  for (px, py) in [(p[0], p[1]) for p in xy_path]:
412
- waypoints.append([px, py, z_ceiling]) # 2. follow route
 
 
 
 
413
  last = xy_path[-1]
414
- waypoints.append([last[0], last[1], goal_z]) # 3. descend
415
  return waypoints
416
 
417
  def plan_u_trajectory(self, start, goal, orientation=None,
@@ -461,6 +490,19 @@ class RobotController:
461
  # ------------------------------------------------------------------ #
462
  # Pick / place primitives
463
  # ------------------------------------------------------------------ #
 
 
 
 
 
 
 
 
 
 
 
 
 
464
  def pick(self, object_id, grasp_pos, grasp_ori=None):
465
  """Execute the 3-phase pick. Returns (grip_force_N, is_holding).
466
 
@@ -486,10 +528,11 @@ class RobotController:
486
  )
487
  self.execute_trajectory(waypoints, grasp_ori)
488
 
489
- # Check reachability before descend
490
- if not self.is_reachable(grasp_pos, grasp_ori):
 
491
  logger.warning(f"[WARN ] Target grasp position {[round(c,3) for c in grasp_pos]} is OUT OF REACH! Aborting grasp.")
492
- self.restore_object_collisions(object_id)
493
  return 0.0, False
494
 
495
  # Phase 2: descend straight down, then attach via constraint.
@@ -499,9 +542,9 @@ class RobotController:
499
  # Check actual EE distance to grasp target (prevent "magic" constraint grasping)
500
  tcp_pos = self.tcp_position()
501
  dist_to_grasp = math.dist(tcp_pos, grasp_pos)
502
- if dist_to_grasp > 0.05:
503
  logger.warning(f"[WARN ] TCP is too far from grasp position! Distance: {dist_to_grasp:.3f} m. Grasp aborted.")
504
- self.restore_object_collisions(object_id)
505
  return 0.0, False
506
 
507
  force = self.gripper.grasp(object_id)
@@ -574,17 +617,17 @@ class RobotController:
574
  # 4. Descend to the pre-grasp position
575
  self.move_to_pose(pre, grasp_ori, steps=120)
576
 
577
- if not self.is_reachable(grasp_pos, grasp_ori):
578
  logger.warning(f"[WARN ] Side-grasp pose {[round(c,3) for c in grasp_pos]} is OUT OF REACH! Aborting.")
579
- self.restore_object_collisions(object_id)
580
  return 0.0, False
581
 
582
  # Reach in along the diagonal approach axis to the grip point.
583
  self.move_to_pose(grasp_pos, grasp_ori, steps=160)
584
  dist_to_grasp = math.dist(self.tcp_position(), grasp_pos)
585
- if dist_to_grasp > 0.05:
586
  logger.warning(f"[WARN ] Side-grasp TCP too far ({dist_to_grasp:.3f} m). Aborting.")
587
- self.restore_object_collisions(object_id)
588
  return 0.0, False
589
 
590
  force = self.gripper.grasp(object_id)
@@ -658,10 +701,13 @@ class RobotController:
658
  snap_x, snap_y = target_pos[0], target_pos[1]
659
  else:
660
  snap_x, snap_y = cur_pos[0], cur_pos[1]
 
 
 
661
  pb.resetBasePositionAndOrientation(
662
  held_id,
663
  [snap_x, snap_y, snap_z],
664
- obj_ori,
665
  )
666
  self._settle(120)
667
  # Retract UPWARD from tcp_z, then restore collisions (arm is clear of placed object).
 
56
 
57
  # Time scale for slowing down/speeding up execution speed.
58
  # < 1.0 increases speed. 0.1 = 10x speed.
59
+ self.time_scale = 0.1
60
 
61
  # Sticky "joint got stuck" flag. Set by move_to_pose whenever a waypoint
62
  # is unreachable (IK saturation / singularity). The closed-loop executor
 
72
  """Read the current position of every arm joint."""
73
  return [pb.getJointState(self.robot_id, j)[0] for j in self.arm_indices]
74
 
75
+ def _current_active_joint_positions(self):
76
+ """Query all active (revolute/prismatic) joints of the robot."""
77
+ positions = []
78
+ num_joints = pb.getNumJoints(self.robot_id)
79
+ for i in range(num_joints):
80
+ info = pb.getJointInfo(self.robot_id, i)
81
+ if info[2] in [pb.JOINT_REVOLUTE, pb.JOINT_PRISMATIC]:
82
+ positions.append(pb.getJointState(self.robot_id, i)[0])
83
+ return positions
84
 
85
+ def _ik(self, position, orientation, seed_positions=None):
86
+ """Solve IK for the Panda and return arm joints target positions.
 
 
 
87
 
88
  Parameters
89
  ----------
 
91
  Explicit seed; when *None* the live joint state is used.
92
  """
93
  if seed_positions is None:
94
+ seed_positions = self._current_active_joint_positions()
95
+ elif len(seed_positions) == len(self.arm_indices):
96
+ # Pad with current finger joints to match active joint count
97
+ active_q = self._current_active_joint_positions()
98
+ seed_positions = list(seed_positions) + active_q[len(self.arm_indices):]
99
 
100
  solution = pb.calculateInverseKinematics(
101
  self.robot_id, self.ee_index, position, orientation,
 
147
  pass
148
  return max_z
149
 
150
+ def is_reachable(self, position, orientation=None, tol=0.02):
151
+ """Check if a target pose is reachable by the robot arm.
152
+
153
+ ``tol`` is the max EE position error (m) the IK solution may leave and
154
+ still count as reachable. The default (0.02 m) is the tight approach
155
+ gate; grasp pre-descend checks pass the looser descend tolerance
156
+ (:attr:`GRASP_DESCEND_TOL`) so this pre-check stays consistent with the
157
+ actual descend abort threshold — otherwise a low grasp the descend
158
+ would reach gets vetoed here.
159
+ """
160
  import math
161
  orientation = orientation or self._down_ori
162
  # Save current joint states
163
  old_states = [pb.getJointState(self.robot_id, j)[0] for j in self.arm_indices]
164
+
165
  # Calculate IK
166
  target_joints = self._ik(position, orientation)
167
+
168
  # Temporarily set joint positions to solution to check EE position
169
  for j, q in zip(self.arm_indices, target_joints):
170
  pb.resetJointState(self.robot_id, j, q)
171
+
172
  # Get EE position
173
  ee_pos = self.tcp_position()
174
  dist = math.dist(ee_pos, position)
175
+
176
  # Check for physical collisions of links -1 to 8 with table or tray
177
  has_collision = False
178
+ if dist < tol:
179
  pb.performCollisionDetection()
180
  for link in range(-1, 9):
181
  if self.table_id is not None:
 
188
  if contacts:
189
  has_collision = True
190
  break
191
+
192
  # Restore old joint states
193
  for j, q in zip(self.arm_indices, old_states):
194
  pb.resetJointState(self.robot_id, j, q)
195
+
196
+ return (dist < tol) and not has_collision
197
 
198
  def get_max_reachable_z(self, x, y, orientation=None, start_z=0.75, step=-0.02, min_z=0.35):
199
  """Find the maximum Z height at a given XY coordinate that is physically reachable."""
 
255
  # If the IK solution's EE deviates more than this from the planned
256
  # Cartesian waypoint, we consider the waypoint unreachable and stop.
257
  _WAYPOINT_STUCK_TOL = 0.04 # 4 cm
258
+ # Max TCP-to-grasp error accepted after descend before we attach the grasp
259
+ # constraint. The pre-descend is_reachable() gate uses the SAME value so it
260
+ # never vetoes a grasp the descend itself would have reached.
261
+ GRASP_DESCEND_TOL = 0.05 # 5 cm
262
 
263
  def move_to_pose(self, position, orientation=None, steps=240, settle=30):
264
  """Move the TCP to *position* and *orientation* via Cartesian-space 6D interpolation.
 
311
  current_q = self._current_joint_positions()
312
  target_q = self._ik(wp_pos, wp_ori, seed_positions=current_q)
313
 
314
+ # Stuck-detection + iterative refinement: temporarily set the
315
+ # solved joints and check where the EE actually ends up. A single
316
+ # DLS solve seeded from an awkward config (e.g. after a long idle
317
+ # hold) can leave several cm of lateral error — enough to land a
318
+ # finger ON a can instead of straddling it — so re-seed the solver
319
+ # from its own solution until the error is millimetric.
320
  old_q = current_q # already read above
321
+ for attempt in range(4):
322
+ for j_idx, j in enumerate(self.arm_indices):
323
+ pb.resetJointState(self.robot_id, j, target_q[j_idx])
324
+ ee_check = self.tcp_position()
325
+ ee_err = _m.dist(ee_check, wp_pos)
326
+ if ee_err <= 0.005 or attempt == 3:
327
+ break
328
+ target_q = self._ik(wp_pos, wp_ori, seed_positions=target_q)
329
  # Restore joints so the smooth interpolation starts from the
330
  # real current state (not the teleported one).
331
  for j_idx, j in enumerate(self.arm_indices):
 
344
  import time
345
  import os
346
  os.makedirs("test_log", exist_ok=True)
347
+ ts = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
348
+ dump_file = f"test_log/ik_stuck_state_{ts}.json"
349
  with open(dump_file, "w") as f:
350
  json.dump({
351
  "tcp_position": self.tcp_position(),
 
406
  else:
407
  z_ceiling = min(z_ceiling, config.Z_SAFE_TRAVEL) # default cap
408
 
409
+ return z_ceiling
 
 
 
 
 
 
 
 
 
410
 
411
  def plan_u_path(self, start, xy_path, goal_z, orientation=None,
412
  carried_height=0.0, exclude_ids=None, z_safe=None):
 
422
  exclude = list(exclude_ids) if exclude_ids else [self.robot_id]
423
  verts = [(start[0], start[1])] + [(p[0], p[1]) for p in xy_path]
424
 
425
+ z_target = self._travel_ceiling(verts, orientation, carried_height, exclude, z_safe)
 
 
 
426
 
427
+ # Build waypoints with per-waypoint reachability capping
428
+ waypoints = []
429
+
430
+ # 1. Start point lift
431
+ z_limit_start = self.get_max_reachable_z(start[0], start[1], orientation) - config.REACH_SAFETY_MARGIN
432
+ z_start = max(min(z_target, z_limit_start), start[2], goal_z)
433
+ waypoints.append([start[0], start[1], z_start])
434
+
435
+ # 2. Path waypoints
436
  for (px, py) in [(p[0], p[1]) for p in xy_path]:
437
+ z_limit = self.get_max_reachable_z(px, py, orientation) - config.REACH_SAFETY_MARGIN
438
+ z_wp = max(min(z_target, z_limit), goal_z)
439
+ waypoints.append([px, py, z_wp])
440
+
441
+ # 3. Descend onto the last waypoint
442
  last = xy_path[-1]
443
+ waypoints.append([last[0], last[1], goal_z])
444
  return waypoints
445
 
446
  def plan_u_trajectory(self, start, goal, orientation=None,
 
490
  # ------------------------------------------------------------------ #
491
  # Pick / place primitives
492
  # ------------------------------------------------------------------ #
493
+ def _abort_grasp_retract(self, object_id, orientation=None):
494
+ """Back the gripper straight up BEFORE restoring arm-object collisions.
495
+
496
+ Restoring collisions while a finger is still wedged against (or
497
+ overlapping) the object makes the solver eject it violently — that is
498
+ how a failed grasp knocks the object off the table. Retreating first
499
+ leaves the object standing where it is.
500
+ """
501
+ tcp = self.tcp_position()
502
+ safe_z = max(config.TABLE_TOP_Z + config.LIFT_HEIGHT, tcp[2] + 0.10)
503
+ self.move_to_pose([tcp[0], tcp[1], safe_z], orientation or self._down_ori, steps=180)
504
+ self.restore_object_collisions(object_id)
505
+
506
  def pick(self, object_id, grasp_pos, grasp_ori=None):
507
  """Execute the 3-phase pick. Returns (grip_force_N, is_holding).
508
 
 
528
  )
529
  self.execute_trajectory(waypoints, grasp_ori)
530
 
531
+ # Check reachability before descend — use the same tolerance the descend
532
+ # abort uses, so this gate never rejects a grasp the descend would reach.
533
+ if not self.is_reachable(grasp_pos, grasp_ori, tol=self.GRASP_DESCEND_TOL):
534
  logger.warning(f"[WARN ] Target grasp position {[round(c,3) for c in grasp_pos]} is OUT OF REACH! Aborting grasp.")
535
+ self._abort_grasp_retract(object_id, grasp_ori)
536
  return 0.0, False
537
 
538
  # Phase 2: descend straight down, then attach via constraint.
 
542
  # Check actual EE distance to grasp target (prevent "magic" constraint grasping)
543
  tcp_pos = self.tcp_position()
544
  dist_to_grasp = math.dist(tcp_pos, grasp_pos)
545
+ if dist_to_grasp > self.GRASP_DESCEND_TOL:
546
  logger.warning(f"[WARN ] TCP is too far from grasp position! Distance: {dist_to_grasp:.3f} m. Grasp aborted.")
547
+ self._abort_grasp_retract(object_id, grasp_ori)
548
  return 0.0, False
549
 
550
  force = self.gripper.grasp(object_id)
 
617
  # 4. Descend to the pre-grasp position
618
  self.move_to_pose(pre, grasp_ori, steps=120)
619
 
620
+ if not self.is_reachable(grasp_pos, grasp_ori, tol=self.GRASP_DESCEND_TOL):
621
  logger.warning(f"[WARN ] Side-grasp pose {[round(c,3) for c in grasp_pos]} is OUT OF REACH! Aborting.")
622
+ self._abort_grasp_retract(object_id, grasp_ori)
623
  return 0.0, False
624
 
625
  # Reach in along the diagonal approach axis to the grip point.
626
  self.move_to_pose(grasp_pos, grasp_ori, steps=160)
627
  dist_to_grasp = math.dist(self.tcp_position(), grasp_pos)
628
+ if dist_to_grasp > self.GRASP_DESCEND_TOL:
629
  logger.warning(f"[WARN ] Side-grasp TCP too far ({dist_to_grasp:.3f} m). Aborting.")
630
+ self._abort_grasp_retract(object_id, grasp_ori)
631
  return 0.0, False
632
 
633
  force = self.gripper.grasp(object_id)
 
701
  snap_x, snap_y = target_pos[0], target_pos[1]
702
  else:
703
  snap_x, snap_y = cur_pos[0], cur_pos[1]
704
+ # Force zero roll and pitch so the object lands perfectly upright/flat (stable)
705
+ yaw = pb.getEulerFromQuaternion(obj_ori)[2]
706
+ upright_ori = pb.getQuaternionFromEuler([0.0, 0.0, yaw])
707
  pb.resetBasePositionAndOrientation(
708
  held_id,
709
  [snap_x, snap_y, snap_z],
710
+ upright_ori,
711
  )
712
  self._settle(120)
713
  # Retract UPWARD from tcp_z, then restore collisions (arm is clear of placed object).
llm_panda/safety_guardrails.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Safety Guardrails — the single verification gate between the LLM planner and
2
+ the robot controller.
3
+
4
+ This module consolidates the project's two non-physics safety tiers behind one
5
+ place so that *every* command produced by :class:`~llm_panda.llm_agent.LLMAgent`
6
+ is screened before the :class:`~llm_panda.robot_controller.RobotController`
7
+ acts on it:
8
+
9
+ * **Tier 1 — Semantic** (:meth:`SafetyGuardrails.verify_safety`): hard-blocks a
10
+ plan that is structurally unsafe — an unknown action verb, an object or
11
+ location that does not exist in the scene, or an illegal gripper-state
12
+ transition (pick while already holding, move/place with nothing held). Unlike
13
+ the advisory :mod:`plan_verifier`, a hard violation here *refuses the whole
14
+ plan* (returns an empty list) rather than logging a warning and proceeding,
15
+ so a partial, inconsistent sequence is never executed. Reachability stays a
16
+ soft warning (the control layer may still recover with a side grasp).
17
+
18
+ * **Tier 2 — Kinematic** (:meth:`SafetyGuardrails.clamp_to_workspace`): clamps a
19
+ commanded TCP target into the reachable workspace box and never below the
20
+ table surface, applied at the controller's motion chokepoint
21
+ (``RobotController.move_to_pose``) right before IK — so a stray coordinate can
22
+ never drive the wrist into the table or out past the arm's reach.
23
+
24
+ It also exposes :meth:`SafetyGuardrails.parse_plan_json`, a crash-proof
25
+ extraction of the JSON plan array from a raw LLM response (Tier 1, JSON guard):
26
+ malformed or empty output degrades to ``[]`` instead of raising.
27
+
28
+ Wiring summary::
29
+
30
+ LLMAgent.plan ──► SafetyGuardrails.verify_safety (Tier 1, semantic)
31
+ │
32
+ ▼
33
+ RobotController.move_to_pose ──► SafetyGuardrails.clamp_to_workspace (Tier 2)
34
+ """
35
+
36
+ import json
37
+ import logging
38
+ import re
39
+
40
+ from . import config
41
+
42
+ logger = logging.getLogger(__name__)
43
+
44
+ # Whitelisted primitive actions the executor understands. Anything else is an
45
+ # unknown verb and the plan is refused.
46
+ ACTIONS = ("pick_up", "move_to", "place_down")
47
+
48
+ # Destinations the executor can resolve. "buffer" is a free spot on the table.
49
+ VALID_LOCATIONS = ("table", "tray", "buffer")
50
+
51
+
52
+ # --------------------------------------------------------------------------- #
53
+ # Tier-2 workspace box, derived once from the scene geometry in config.
54
+ # --------------------------------------------------------------------------- #
55
+ def _workspace_bounds():
56
+ """Planar (x, y) bounds of the reachable workspace = bbox(table ∪ tray),
57
+ grown by ``WORKSPACE_MARGIN`` so a TCP hovering just off a surface edge is
58
+ still inside the box."""
59
+ m = config.WORKSPACE_MARGIN
60
+ tcx, tcy = config.TABLE_CENTER
61
+ thx, thy, _ = config.TABLE_HALF_EXTENTS
62
+ trx, try_, _ = config.TRAY_POSITION
63
+ trhx, trhy, _ = config.TRAY_HALF_EXTENTS
64
+
65
+ table_x = (tcx - thx, tcx + thx)
66
+ table_y = (tcy - thy, tcy + thy)
67
+ tray_x = (trx - trhx, trx + trhx)
68
+ tray_y = (try_ - trhy, try_ + trhy)
69
+
70
+ ws_x = (min(table_x[0], tray_x[0]) - m, max(table_x[1], tray_x[1]) + m)
71
+ ws_y = (min(table_y[0], tray_y[0]) - m, max(table_y[1], tray_y[1]) + m)
72
+ return ws_x, ws_y
73
+
74
+
75
+ _WS_X, _WS_Y = _workspace_bounds()
76
+ # Hard floor: the TCP (panda_grasptarget) is never commanded below the table
77
+ # top. Every legitimate grasp/place point sits on or above the surface, so this
78
+ # only ever catches a coordinate that would drive the wrist into the table.
79
+ _Z_FLOOR = config.TABLE_TOP_Z
80
+ # Generous ceiling: the transit ceiling is already capped by arm reachability in
81
+ # the controller; this only rejects absurdly-high targets.
82
+ _Z_CEILING = config.Z_SAFE_TRAVEL + 0.30
83
+
84
+
85
+ class SafetyReport:
86
+ """Outcome of :meth:`SafetyGuardrails.verify_safety`.
87
+
88
+ ``violations`` are hard, plan-refusing errors; ``warnings`` are advisory.
89
+ ``ok`` is True only when there are no violations.
90
+ """
91
+
92
+ def __init__(self):
93
+ self.violations = []
94
+ self.warnings = []
95
+
96
+ @property
97
+ def ok(self):
98
+ return not self.violations
99
+
100
+ def __repr__(self):
101
+ return f"SafetyReport(ok={self.ok}, violations={self.violations}, warnings={self.warnings})"
102
+
103
+
104
+ class SafetyGuardrails:
105
+ """Stateless safety gate. All entry points are static."""
106
+
107
+ # ------------------------------------------------------------------ #
108
+ # Tier 1 — JSON guard
109
+ # ------------------------------------------------------------------ #
110
+ @staticmethod
111
+ def parse_plan_json(text):
112
+ """Extract the JSON plan array from a raw model response, never raising.
113
+
114
+ Returns ``[]`` for empty output, no bracketed array, or malformed JSON.
115
+ """
116
+ if not text:
117
+ return []
118
+ match = re.search(r"\[.*\]", text, re.DOTALL)
119
+ if not match:
120
+ return []
121
+ try:
122
+ parsed = json.loads(match.group(0))
123
+ except (json.JSONDecodeError, ValueError) as exc:
124
+ logger.warning(f"[SAFETY] plan JSON was malformed, ignoring it: {exc}")
125
+ return []
126
+ return parsed if isinstance(parsed, list) else []
127
+
128
+ # ------------------------------------------------------------------ #
129
+ # Tier 1 — semantic verification (hard-block)
130
+ # ------------------------------------------------------------------ #
131
+ @staticmethod
132
+ def _schema_ok(step):
133
+ """A step must be ``{"function": <whitelisted>, "args": {...}}``."""
134
+ return (
135
+ isinstance(step, dict)
136
+ and step.get("function") in ACTIONS
137
+ and isinstance(step.get("args"), dict)
138
+ )
139
+
140
+ @staticmethod
141
+ def verify_safety(plan, scene_state):
142
+ """Screen *plan* against *scene_state*; return ``(safe_plan, report)``.
143
+
144
+ On any hard violation the plan is refused (``safe_plan == []``) so a
145
+ partial, inconsistent sequence is never executed. With no violations the
146
+ original plan is returned unchanged (advisory warnings may still be set,
147
+ e.g. for an out-of-reach target or a place with nothing held).
148
+ """
149
+ if isinstance(scene_state, str):
150
+ scene_state = json.loads(scene_state)
151
+
152
+ report = SafetyReport()
153
+
154
+ if not isinstance(plan, list):
155
+ report.violations.append(f"plan is not a list (got {type(plan).__name__})")
156
+ return [], report
157
+
158
+ objects = scene_state.get("objects", [])
159
+ object_names = {o["name"] for o in objects}
160
+ by_name = {o["name"]: o for o in objects}
161
+ held = scene_state.get("carried_object") is not None
162
+
163
+ for i, step in enumerate(plan):
164
+ # 1. Action whitelisting / schema.
165
+ if not SafetyGuardrails._schema_ok(step):
166
+ report.violations.append(
167
+ f"step {i}: malformed step or unknown action {step!r}"
168
+ )
169
+ continue
170
+
171
+ func = step["function"]
172
+ args = step["args"]
173
+
174
+ if func == "pick_up":
175
+ obj = args.get("object_id", "")
176
+ # 2. Object validation.
177
+ if obj not in object_names:
178
+ report.violations.append(f"step {i}: pick_up unknown object '{obj}'")
179
+ else:
180
+ # Reachability is advisory: the control layer may still
181
+ # extract a blocked object with a tilted side grasp.
182
+ if not by_name[obj].get("reachable", True):
183
+ report.warnings.append(f"step {i}: pick_up target '{obj}' is OUT OF REACH")
184
+ # 3. Gripper-state logic.
185
+ if held:
186
+ report.violations.append(
187
+ f"step {i}: pick_up('{obj}') while already holding an object"
188
+ )
189
+ held = True
190
+
191
+ elif func == "move_to":
192
+ loc = args.get("location_id", "")
193
+ # 2. Location validation.
194
+ if loc not in VALID_LOCATIONS:
195
+ report.violations.append(f"step {i}: move_to unknown location '{loc}'")
196
+ # A spatial relation must reference a real object.
197
+ ref = args.get("relative_to")
198
+ if ref and ref not in object_names:
199
+ report.violations.append(
200
+ f"step {i}: move_to relative_to unknown object '{ref}'"
201
+ )
202
+ # 3. Gripper-state logic.
203
+ if not held:
204
+ report.violations.append(f"step {i}: move_to('{loc}') with nothing held")
205
+
206
+ elif func == "place_down":
207
+ # 3. Gripper-state logic. A place with nothing held is a benign
208
+ # no-op for the executor, so it is a warning, not a refusal.
209
+ if not held:
210
+ report.warnings.append(f"step {i}: place_down() with nothing held (no-op)")
211
+ else:
212
+ held = False
213
+
214
+ if not report.ok:
215
+ return [], report
216
+ return plan, report
217
+
218
+ # ------------------------------------------------------------------ #
219
+ # Tier 2 — kinematic clamp
220
+ # ------------------------------------------------------------------ #
221
+ @staticmethod
222
+ def clamp_to_workspace(position):
223
+ """Clamp a commanded TCP target into the reachable workspace box.
224
+
225
+ ``x``/``y`` are clamped to ``bbox(table ∪ tray)`` grown by a margin;
226
+ ``z`` is clamped to ``[table_top, ceiling]`` so the wrist is never driven
227
+ below the table surface. Returns a new ``[x, y, z]`` list; logs only when
228
+ a coordinate was actually changed (a guard activation).
229
+ """
230
+ x, y, z = position[0], position[1], position[2]
231
+ cx = min(max(x, _WS_X[0]), _WS_X[1])
232
+ cy = min(max(y, _WS_Y[0]), _WS_Y[1])
233
+ cz = min(max(z, _Z_FLOOR), _Z_CEILING)
234
+
235
+ if (cx, cy, cz) != (x, y, z):
236
+ logger.warning(
237
+ f"[SAFETY_CLAMP] target {[round(v, 3) for v in (x, y, z)]} "
238
+ f"-> {[round(v, 3) for v in (cx, cy, cz)]} (outside workspace box)"
239
+ )
240
+ return [cx, cy, cz]
llm_panda/scene_manager.py CHANGED
@@ -499,6 +499,90 @@ class SceneManager:
499
  if location == "tray":
500
  tray_occupants.append(entry["name"])
501
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
502
  # Annotate each table object with its neighbor count and the names of
503
  # objects that block its grasp approach (so a planner can clear them).
504
  for entry in objects:
 
499
  if location == "tray":
500
  tray_occupants.append(entry["name"])
501
 
502
+ # Stacking detection AABB helper
503
+ aabbs = {}
504
+ for oid in self._registry:
505
+ name = self._registry[oid]["name"]
506
+ try:
507
+ aabb_min, aabb_max = self.get_aabb(oid)
508
+ aabbs[name] = (aabb_min, aabb_max)
509
+ except Exception:
510
+ pass
511
+
512
+ def is_on_top(name_a, name_b):
513
+ if name_a not in aabbs or name_b not in aabbs:
514
+ return False
515
+ min_a, max_a = aabbs[name_a]
516
+ min_b, max_b = aabbs[name_b]
517
+
518
+ # Check XY overlap
519
+ overlap_x = (min_a[0] <= max_b[0]) and (max_a[0] >= min_b[0])
520
+ overlap_y = (min_a[1] <= max_b[1]) and (max_a[1] >= min_b[1])
521
+
522
+ if overlap_x and overlap_y:
523
+ # Bottom of A is close to or above top of B
524
+ is_above = min_a[2] >= max_b[2] - 0.02
525
+ is_close = min_a[2] <= max_b[2] + 0.05
526
+ if is_above and is_close:
527
+ return True
528
+ return False
529
+
530
+ # Compute distances and relations for all objects
531
+ for entry_a in objects:
532
+ entry_a["distances"] = {}
533
+ entry_a["relations"] = {
534
+ "left_of": [],
535
+ "right_of": [],
536
+ "front_of": [],
537
+ "behind": [],
538
+ "on_top_of": None,
539
+ "supporting": []
540
+ }
541
+ pos_a = entry_a["position"]
542
+ name_a = entry_a["name"]
543
+
544
+ for entry_b in objects:
545
+ name_b = entry_b["name"]
546
+ if name_a == name_b:
547
+ continue
548
+ pos_b = entry_b["position"]
549
+
550
+ # Planar distance calculation
551
+ dist = self._planar_distance(pos_a, pos_b)
552
+ entry_a["distances"][name_b] = round(dist, 3)
553
+
554
+ # Spatial relationships: only compute if both are on table/tray
555
+ if entry_a["location"] in ("table", "tray") and entry_b["location"] in ("table", "tray"):
556
+ dx = pos_a[0] - pos_b[0]
557
+ dy = pos_a[1] - pos_b[1]
558
+
559
+ if dx > 0.04:
560
+ entry_a["relations"]["behind"].append(name_b)
561
+ elif dx < -0.04:
562
+ entry_a["relations"]["front_of"].append(name_b)
563
+
564
+ if dy > 0.04:
565
+ entry_a["relations"]["left_of"].append(name_b)
566
+ elif dy < -0.04:
567
+ entry_a["relations"]["right_of"].append(name_b)
568
+
569
+ # Stacking relation
570
+ for entry_b in objects:
571
+ name_b = entry_b["name"]
572
+ if name_a == name_b:
573
+ continue
574
+ if is_on_top(name_a, name_b):
575
+ entry_a["relations"]["on_top_of"] = name_b
576
+
577
+ # Populate supporting lists based on on_top_of relationships
578
+ for entry_a in objects:
579
+ underlying = entry_a["relations"]["on_top_of"]
580
+ if underlying:
581
+ for entry_b in objects:
582
+ if entry_b["name"] == underlying:
583
+ entry_b["relations"]["supporting"].append(entry_a["name"])
584
+ break
585
+
586
  # Annotate each table object with its neighbor count and the names of
587
  # objects that block its grasp approach (so a planner can clear them).
588
  for entry in objects:
main.py CHANGED
@@ -31,10 +31,12 @@ logger = logging.getLogger(__name__)
31
  class PandaApp:
32
  """Wrapper that binds Simulation Engine, Environment Builder, and Execution Pipeline."""
33
 
34
- def __init__(self, env_json_path, gui=False, seed=0, real_time=False, agent=None, viz=False):
35
  self.gui = gui
36
  self.viz = viz
37
  self.seed = seed
 
 
38
  self.env_json_path = env_json_path
39
 
40
  # 1. Start simulation engine
@@ -143,10 +145,66 @@ class PandaApp:
143
  except Exception as exc:
144
  logger.error(f"[ERR ] {exc}")
145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  def disconnect(self):
147
  self.sim_engine.disconnect()
148
 
149
 
 
 
 
150
  # --------------------------------------------------------------------------- #
151
  # Chat GUI (tkinter) + background simulation runner
152
  # --------------------------------------------------------------------------- #
 
31
  class PandaApp:
32
  """Wrapper that binds Simulation Engine, Environment Builder, and Execution Pipeline."""
33
 
34
+ def __init__(self, env_json_path=None, gui=False, seed=0, real_time=False, agent=None, viz=False):
35
  self.gui = gui
36
  self.viz = viz
37
  self.seed = seed
38
+ if env_json_path is None:
39
+ env_json_path = "envs/env1.json"
40
  self.env_json_path = env_json_path
41
 
42
  # 1. Start simulation engine
 
145
  except Exception as exc:
146
  logger.error(f"[ERR ] {exc}")
147
 
148
+ @property
149
+ def agent(self):
150
+ return self.pipeline.agent
151
+
152
+ @agent.setter
153
+ def agent(self, value):
154
+ self.pipeline.agent = value
155
+
156
+ @property
157
+ def _carried(self):
158
+ return self.pipeline._carried
159
+
160
+ @_carried.setter
161
+ def _carried(self, value):
162
+ self.pipeline._carried = value
163
+
164
+ @property
165
+ def _pending_target_pos(self):
166
+ return self.pipeline._pending_target_pos
167
+
168
+ @_pending_target_pos.setter
169
+ def _pending_target_pos(self, value):
170
+ self.pipeline._pending_target_pos = value
171
+
172
+ @property
173
+ def MAX_REPLANS(self):
174
+ return self.pipeline.MAX_REPLANS
175
+
176
+ @MAX_REPLANS.setter
177
+ def MAX_REPLANS(self, value):
178
+ self.pipeline.MAX_REPLANS = value
179
+
180
+ def _verify_step(self, step, held_before, expected_location):
181
+ return self.pipeline.execution_monitor.verify_step(
182
+ step, held_before, expected_location, self.pipeline._carried, self.pipeline._pending_target_pos
183
+ )
184
+
185
+ @property
186
+ def _execute_plan(self):
187
+ return self.pipeline._execute_plan
188
+
189
+ @_execute_plan.setter
190
+ def _execute_plan(self, value):
191
+ self.pipeline._execute_plan = value
192
+
193
+ @property
194
+ def _recover_to_safe_state(self):
195
+ return self.pipeline._recover_to_safe_state
196
+
197
+ @_recover_to_safe_state.setter
198
+ def _recover_to_safe_state(self, value):
199
+ self.pipeline._recover_to_safe_state = value
200
+
201
  def disconnect(self):
202
  self.sim_engine.disconnect()
203
 
204
 
205
+ PandaSimulation = PandaApp
206
+
207
+
208
  # --------------------------------------------------------------------------- #
209
  # Chat GUI (tkinter) + background simulation runner
210
  # --------------------------------------------------------------------------- #
temp_dream_skill ADDED
@@ -0,0 +1 @@
 
 
1
+ Subproject commit 228634143517906e3407ecec827890aaf70d5a97
test_llm_planner.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Auto-evaluation test suite for the LLM planner + safety guardrails.
3
+
4
+ Two complementary families, both written into ONE JSON report
5
+ (``test_log/suite_<timestamp>.json``):
6
+
7
+ 1. EXECUTION SCENARIOS — happy paths + natural-language edge cases run through
8
+ ``PandaSimulation.run_command(..., evaluate=True)``. That wraps each run in a
9
+ :class:`~llm_panda.logger_evaluation.TaskEvaluator`, which measures and grades
10
+ the metrics from ``docs/EVALUATION_METRICS.md`` (LLM time, A* time, task
11
+ status, replans, collisions, TCP error, trajectory efficiency). We absorb each
12
+ run's metrics into the consolidated report.
13
+
14
+ 2. GUARDRAIL CHECKS — crafted plans fed straight to
15
+ :meth:`SafetyGuardrails.verify_safety` to prove the semantic safety gate hard-
16
+ blocks structurally unsafe plans (unknown object/location/action, illegal
17
+ gripper-state transitions, bad spatial reference) while letting advisory cases
18
+ (out-of-reach, place-with-empty-gripper) through as warnings. These are fast,
19
+ deterministic, and need no simulation.
20
+
21
+ Usage::
22
+
23
+ python test_llm_planner.py # rule planner, all scenarios
24
+ python test_llm_planner.py --llm openai # real LLM (needs API key)
25
+ python test_llm_planner.py --filter clear,swap # subset by id/category
26
+ python test_llm_planner.py --only guardrails # skip the slow sim runs
27
+
28
+ Exit code is non-zero if any scenario fails its *functional* expectation (task
29
+ status mismatch) or any guardrail check fails. Metric-threshold breaches are
30
+ reported as WARN (quality signal), not hard failures.
31
+ """
32
+
33
+ import argparse
34
+ import glob
35
+ import json
36
+ import logging
37
+ import os
38
+ import sys
39
+ import time
40
+
41
+ from main import PandaSimulation
42
+ from llm_panda import logger as _logger_setup
43
+ from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner
44
+ from llm_panda.safety_guardrails import SafetyGuardrails
45
+
46
+ logger = logging.getLogger("test_llm_planner")
47
+
48
+ LOG_DIR = "test_log"
49
+
50
+ # Catalog object names (must match main._YCB_CATALOG) for guardrail fixtures.
51
+ OBJ_NAMES = ["banana", "soup_can", "chips_can", "tennis_ball", "pear", "clamp"]
52
+
53
+
54
+ # --------------------------------------------------------------------------- #
55
+ # Family 1: execution scenarios
56
+ # --------------------------------------------------------------------------- #
57
+ # id : stable identifier
58
+ # command : natural-language instruction (taken from real test_log runs)
59
+ # category : grouping for the report
60
+ # expect : intended Task Status — "SUCCESS" or "FAIL" (FAIL = guardrail/empty)
61
+ # needs_llm : True if the offline RuleBasedPlanner cannot decompose it
62
+ SCENARIOS = [
63
+ # ── Happy: single pick (no destination) ───────────────────────────────
64
+ dict(id="pick_only_banana", command="gắp quả chuối lên",
65
+ category="happy/pick", expect="SUCCESS", needs_llm=False),
66
+ dict(id="pick_only_soup", command="nhấc lon súp",
67
+ category="happy/pick", expect="SUCCESS", needs_llm=False),
68
+
69
+ # ── Happy: pick → tray ────────────────────────────────────────────────
70
+ dict(id="banana_to_tray", command="gắp quả chuối bỏ vào khay",
71
+ category="happy/pick_place_tray", expect="SUCCESS", needs_llm=False),
72
+ # "lon chips" is in the rule planner's alias table; the colloquial "snák"
73
+ # variant below is an LLM-tier case (rule planner does not know that alias).
74
+ dict(id="chips_to_tray", command="gắp lon chips bỏ vào khay",
75
+ category="happy/pick_place_tray", expect="SUCCESS", needs_llm=False),
76
+
77
+ # ── Happy: pick → table ───────────────────────────────────────────────
78
+ dict(id="soup_to_table", command="gắp lon súp đặt lên bàn",
79
+ category="happy/pick_place_table", expect="SUCCESS", needs_llm=False),
80
+ dict(id="soup_to_table_en",
81
+ command="Pick up the soup can and place it on the table",
82
+ category="happy/pick_place_table", expect="SUCCESS", needs_llm=False),
83
+
84
+ # ── Happy: spatial relations (exercise A* + trajectory efficiency) ────
85
+ dict(id="rel_next_to", command="đặt quả chuối cạnh lon súp",
86
+ category="happy/relation", expect="SUCCESS", needs_llm=False),
87
+ dict(id="rel_right_of", command="đặt lon súp bên phải quả chuối",
88
+ category="happy/relation", expect="SUCCESS", needs_llm=False),
89
+ dict(id="rel_behind", command="đặt lon súp ra phía sau quả chuối",
90
+ category="happy/relation", expect="SUCCESS", needs_llm=False),
91
+
92
+ # ── Edge: guardrail-triggering / degenerate NL → expect FAIL ──────────
93
+ dict(id="place_nothing_held", command="đặt vào khay",
94
+ category="edge/guardrail", expect="FAIL", needs_llm=False),
95
+ dict(id="no_target_gibberish", command="xin chào robot hôm nay thế nào",
96
+ category="edge/empty_plan", expect="FAIL", needs_llm=False),
97
+
98
+ # ── LLM-tier: colloquial alias the offline planner does not resolve ───
99
+ dict(id="colloquial_snack_tray", command="gắp hộp snák bỏ vô khay",
100
+ category="edge/colloquial_alias", expect="SUCCESS", needs_llm=True),
101
+
102
+ # ── LLM-tier: clear whole table (long multi-step; collisions/traj/replans)
103
+ dict(id="clear_table", command="dọn bàn đi",
104
+ category="edge/clear_table", expect="SUCCESS", needs_llm=True),
105
+
106
+ # ── Edge: LLM-only (compound / swap / semantic reasoning) ─────────────
107
+ dict(id="compound_two_moves",
108
+ command="di chuyển snack lên bàn và di chuyển lon súp vào khay",
109
+ category="edge/compound", expect="SUCCESS", needs_llm=True),
110
+ dict(id="swap_banana_snack", command="đổi vị trí quả chuối và snack",
111
+ category="edge/swap", expect="SUCCESS", needs_llm=True),
112
+ dict(id="edible_to_tray", command="để hoa quả vào khay đi",
113
+ category="edge/semantic", expect="SUCCESS", needs_llm=True),
114
+ ]
115
+
116
+
117
+ # --------------------------------------------------------------------------- #
118
+ # Family 2: guardrail checks (no simulation needed)
119
+ # --------------------------------------------------------------------------- #
120
+ def _scene(carried=None, unreachable=()):
121
+ """Synthetic scene_state with the catalog objects on the table."""
122
+ return {
123
+ "objects": [
124
+ {"name": n, "class": n, "location": "table",
125
+ "reachable": n not in unreachable}
126
+ for n in OBJ_NAMES
127
+ ],
128
+ "carried_object": carried,
129
+ }
130
+
131
+
132
+ # id, description, plan, scene, expect_ok (False => plan must be refused → []),
133
+ # expect_substr (text expected somewhere in violations+warnings).
134
+ GUARDRAIL_CASES = [
135
+ dict(id="g_valid_pick_place", desc="valid pick→move(tray)→place is accepted",
136
+ plan=[{"function": "pick_up", "args": {"object_id": "banana"}},
137
+ {"function": "move_to", "args": {"location_id": "tray"}},
138
+ {"function": "place_down", "args": {}}],
139
+ scene=_scene(), expect_ok=True, expect_substr=None),
140
+
141
+ dict(id="g_unknown_object", desc="pick_up of a non-existent object is refused",
142
+ plan=[{"function": "pick_up", "args": {"object_id": "red_cube"}}],
143
+ scene=_scene(), expect_ok=False, expect_substr="unknown object"),
144
+
145
+ dict(id="g_double_pick", desc="two pick_ups without a place between is refused",
146
+ plan=[{"function": "pick_up", "args": {"object_id": "banana"}},
147
+ {"function": "pick_up", "args": {"object_id": "soup_can"}}],
148
+ scene=_scene(), expect_ok=False, expect_substr="already holding"),
149
+
150
+ dict(id="g_move_empty_gripper", desc="move_to with nothing held is refused",
151
+ plan=[{"function": "move_to", "args": {"location_id": "tray"}}],
152
+ scene=_scene(), expect_ok=False, expect_substr="nothing held"),
153
+
154
+ dict(id="g_unknown_location", desc="move_to an undefined location is refused",
155
+ plan=[{"function": "pick_up", "args": {"object_id": "banana"}},
156
+ {"function": "move_to", "args": {"location_id": "shelf"}}],
157
+ scene=_scene(), expect_ok=False, expect_substr="unknown location"),
158
+
159
+ dict(id="g_bad_relative_to", desc="spatial reference to a ghost object is refused",
160
+ plan=[{"function": "pick_up", "args": {"object_id": "banana"}},
161
+ {"function": "move_to", "args": {"location_id": "table",
162
+ "relation": "next_to",
163
+ "relative_to": "ghost_obj"}}],
164
+ scene=_scene(), expect_ok=False, expect_substr="relative_to unknown"),
165
+
166
+ dict(id="g_unknown_action", desc="an unknown action verb is refused",
167
+ plan=[{"function": "teleport", "args": {"object_id": "banana"}}],
168
+ scene=_scene(), expect_ok=False, expect_substr="unknown action"),
169
+
170
+ dict(id="g_malformed_step", desc="a malformed step (no function) is refused",
171
+ plan=[{"foo": "bar"}],
172
+ scene=_scene(), expect_ok=False, expect_substr="malformed"),
173
+
174
+ dict(id="g_pick_while_carrying", desc="pick_up while already carrying is refused",
175
+ plan=[{"function": "pick_up", "args": {"object_id": "soup_can"}}],
176
+ scene=_scene(carried="banana"), expect_ok=False, expect_substr="already holding"),
177
+
178
+ # Advisory tier — these must NOT refuse the plan (ok=True), only warn.
179
+ dict(id="g_out_of_reach_warns", desc="out-of-reach target warns but is allowed",
180
+ plan=[{"function": "pick_up", "args": {"object_id": "pear"}}],
181
+ scene=_scene(unreachable=("pear",)), expect_ok=True, expect_substr="OUT OF REACH"),
182
+
183
+ dict(id="g_place_empty_warns", desc="place_down with empty gripper is a no-op warning",
184
+ plan=[{"function": "place_down", "args": {}}],
185
+ scene=_scene(), expect_ok=True, expect_substr="nothing held"),
186
+ ]
187
+
188
+
189
+ # --------------------------------------------------------------------------- #
190
+ # Execution-scenario runner
191
+ # --------------------------------------------------------------------------- #
192
+ def _build_agent(llm_choice):
193
+ if llm_choice == "openai":
194
+ planner = RemoteLLMPlanner()
195
+ if not planner.api_key:
196
+ sys.exit("ERROR: --llm openai needs OPENAI_API_KEY (set it in .env or the env).")
197
+ logger.info(f"[LLM ] OpenAI planner (model={planner.model})")
198
+ return LLMAgent(planner=planner)
199
+ logger.info("[LLM ] RuleBasedPlanner (offline, deterministic)")
200
+ return LLMAgent()
201
+
202
+
203
+ def _capture_new_eval(before_set):
204
+ """The eval_*.json that run_command(evaluate=True) just wrote, if any."""
205
+ after = set(glob.glob(os.path.join(LOG_DIR, "eval_*.json")))
206
+ new = after - before_set
207
+ if not new:
208
+ return None
209
+ return max(new, key=os.path.getmtime)
210
+
211
+
212
+ def _run_scenario(sim, sc, seed, keep_eval_files):
213
+ """Reset the world and run one command under evaluation."""
214
+ sim.reset_objects(seed=seed)
215
+ before = set(glob.glob(os.path.join(LOG_DIR, "eval_*.json")))
216
+ rec = dict(sc)
217
+ try:
218
+ sim.run_command(sc["command"], evaluate=True)
219
+ except Exception as exc:
220
+ logger.error(f"[{sc['id']}] raised {type(exc).__name__}: {exc}")
221
+ rec["error"] = f"{type(exc).__name__}: {exc}"
222
+ rec["status"] = "ERROR"
223
+ rec["functional_pass"] = False
224
+ rec["metrics_pass"] = False
225
+ return rec
226
+
227
+ path = _capture_new_eval(before)
228
+ if path is None:
229
+ rec["error"] = "no eval JSON produced"
230
+ rec["status"] = "ERROR"
231
+ rec["functional_pass"] = False
232
+ rec["metrics_pass"] = False
233
+ return rec
234
+ with open(path, encoding="utf-8") as fh:
235
+ ev = json.load(fh)
236
+ if not keep_eval_files:
237
+ # Consolidate into the single suite report; drop the transient per-run file.
238
+ try:
239
+ os.remove(path)
240
+ except OSError:
241
+ pass
242
+
243
+ status = ev["metrics"]["task_status"]["value"]
244
+ rec["status"] = status
245
+ rec["metrics"] = ev["metrics"]
246
+ rec["thresholds"] = ev["thresholds"]
247
+ rec["overall_pass"] = ev["overall_pass"]
248
+ rec["functional_pass"] = (status == sc["expect"])
249
+ # metrics_pass only meaningful when we expected (and got) a SUCCESS.
250
+ rec["metrics_pass"] = bool(ev["overall_pass"]) if status == "SUCCESS" else None
251
+ return rec
252
+
253
+
254
+ def _exec_verdict(rec):
255
+ """PASS = functional ok and metrics ok; WARN = functional ok but a metric
256
+ threshold breached; FAIL = wrong task status / crash."""
257
+ if not rec.get("functional_pass"):
258
+ return "FAIL"
259
+ if rec.get("metrics_pass") is False:
260
+ return "WARN"
261
+ return "PASS"
262
+
263
+
264
+ # --------------------------------------------------------------------------- #
265
+ # Guardrail runner
266
+ # --------------------------------------------------------------------------- #
267
+ def _run_guardrail(case):
268
+ safe_plan, report = SafetyGuardrails.verify_safety(case["plan"], case["scene"])
269
+ text = " ".join(report.violations + report.warnings)
270
+ ok_match = report.ok == case["expect_ok"]
271
+ refused_match = (safe_plan == []) if not case["expect_ok"] else (safe_plan == case["plan"])
272
+ substr_match = case["expect_substr"] is None or case["expect_substr"] in text
273
+ passed = ok_match and refused_match and substr_match
274
+ return dict(
275
+ id=case["id"], description=case["desc"],
276
+ expect_ok=case["expect_ok"], ok=report.ok,
277
+ refused=(safe_plan == []),
278
+ violations=report.violations, warnings=report.warnings,
279
+ verdict="PASS" if passed else "FAIL",
280
+ )
281
+
282
+
283
+ # --------------------------------------------------------------------------- #
284
+ # Reporting
285
+ # --------------------------------------------------------------------------- #
286
+ def _print_exec_table(records):
287
+ cols = ("id", "category", "status", "llm_s", "astar_s", "repl", "col",
288
+ "tcp_m", "traj", "verdict")
289
+ rows = []
290
+ for r in records:
291
+ if "metrics" not in r:
292
+ rows.append(dict(id=r["id"], category=r["category"],
293
+ status=r.get("status", "SKIP"), llm_s="-", astar_s="-",
294
+ repl="-", col="-", tcp_m="-", traj="-",
295
+ verdict=r.get("verdict", "SKIP")))
296
+ continue
297
+ m = r["metrics"]
298
+ bang = lambda x: "" if x.get("pass", True) else "!"
299
+ rows.append(dict(
300
+ id=r["id"], category=r["category"], status=r["status"],
301
+ llm_s=f"{m['llm_reasoning_time_s']['value']:.2f}{bang(m['llm_reasoning_time_s'])}",
302
+ astar_s=f"{m['astar_planning_time_s']['value']:.3f}{bang(m['astar_planning_time_s'])}",
303
+ repl=f"{m['replanning_count']['value']}{bang(m['replanning_count'])}",
304
+ col=f"{m['collisions_detected']['value']}{bang(m['collisions_detected'])}",
305
+ tcp_m=f"{m['final_tcp_error_m']['value']:.3f}{bang(m['final_tcp_error_m'])}",
306
+ traj=f"{m['trajectory_efficiency']['value']:.2f}{bang(m['trajectory_efficiency'])}",
307
+ verdict=r["verdict"]))
308
+ _grid("EXECUTION SCENARIOS ('!' = metric exceeded its threshold)", cols, rows)
309
+
310
+
311
+ def _print_guardrail_table(records):
312
+ cols = ("id", "expect_ok", "ok", "refused", "verdict")
313
+ rows = [dict(id=r["id"], expect_ok=r["expect_ok"], ok=r["ok"],
314
+ refused=r["refused"], verdict=r["verdict"]) for r in records]
315
+ _grid("GUARDRAIL CHECKS", cols, rows)
316
+
317
+
318
+ def _grid(title, cols, rows):
319
+ if not rows:
320
+ return
321
+ w = {c: max(len(c), *(len(str(r[c])) for r in rows)) for c in cols}
322
+ header = " ".join(c.ljust(w[c]) for c in cols)
323
+ print("\n" + "=" * len(header))
324
+ print(title)
325
+ print("=" * len(header))
326
+ print(header)
327
+ print("-" * len(header))
328
+ for r in rows:
329
+ print(" ".join(str(r[c]).ljust(w[c]) for c in cols))
330
+ print("=" * len(header))
331
+
332
+
333
+ # --------------------------------------------------------------------------- #
334
+ # Entry point
335
+ # --------------------------------------------------------------------------- #
336
+ def main():
337
+ parser = argparse.ArgumentParser(
338
+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
339
+ parser.add_argument("--llm", choices=["rule", "openai"], default="rule",
340
+ help="planner backend (default: rule = offline/deterministic)")
341
+ parser.add_argument("--seed", type=int, default=0,
342
+ help="object-placement RNG seed (default: 0)")
343
+ parser.add_argument("--filter", type=str, default=None,
344
+ help="comma-separated substrings; keep scenarios whose id/category matches")
345
+ parser.add_argument("--only", choices=["all", "execution", "guardrails"],
346
+ default="all", help="which families to run (default: all)")
347
+ parser.add_argument("--gui", action="store_true", help="show the PyBullet GUI")
348
+ parser.add_argument("--keep-eval-json", action="store_true",
349
+ help="keep the per-run test_log/eval_*.json files (default: consolidate + delete)")
350
+ parser.add_argument("--out", type=str, default=None,
351
+ help="output JSON path (default: test_log/suite_<timestamp>.json)")
352
+ args = parser.parse_args()
353
+
354
+ _logger_setup.setup()
355
+ timestamp = time.strftime("%Y-%m-%d_%H-%M-%S")
356
+ os.makedirs(LOG_DIR, exist_ok=True)
357
+
358
+ report = {
359
+ "meta": dict(timestamp=timestamp, llm=args.llm, seed=args.seed,
360
+ thresholds_doc="docs/EVALUATION_METRICS.md §4"),
361
+ "execution": {"results": []},
362
+ "guardrails": {"results": []},
363
+ }
364
+
365
+ # ── Family 2: guardrails (always cheap; run unless excluded) ──
366
+ if args.only in ("all", "guardrails"):
367
+ logger.info("\n[GUARDRAILS] running %d checks", len(GUARDRAIL_CASES))
368
+ report["guardrails"]["results"] = [_run_guardrail(c) for c in GUARDRAIL_CASES]
369
+
370
+ # ── Family 1: execution scenarios ──
371
+ if args.only in ("all", "execution"):
372
+ scenarios = SCENARIOS
373
+ if args.filter:
374
+ keys = [k.strip() for k in args.filter.split(",") if k.strip()]
375
+ scenarios = [s for s in scenarios
376
+ if any(k in s["id"] or k in s["category"] for k in keys)]
377
+ agent = _build_agent(args.llm)
378
+ sim = PandaSimulation(gui=args.gui, seed=args.seed, agent=agent)
379
+ try:
380
+ for s in scenarios:
381
+ if s["needs_llm"] and args.llm != "openai":
382
+ logger.info(f"[SKIP ] {s['id']} (needs --llm openai)")
383
+ rec = dict(s, status="SKIP", verdict="SKIP")
384
+ report["execution"]["results"].append(rec)
385
+ continue
386
+ logger.info(f"\n[RUN ] {s['id']}: {s['command']!r}")
387
+ rec = _run_scenario(sim, s, args.seed, args.keep_eval_json)
388
+ rec["verdict"] = _exec_verdict(rec)
389
+ report["execution"]["results"].append(rec)
390
+ finally:
391
+ sim.disconnect()
392
+
393
+ # ── Summaries ──
394
+ ex = [r for r in report["execution"]["results"] if r.get("verdict") != "SKIP"]
395
+ gd = report["guardrails"]["results"]
396
+ report["execution"]["summary"] = dict(
397
+ total=len(report["execution"]["results"]),
398
+ ran=len(ex),
399
+ functional_pass=sum(1 for r in ex if r.get("functional_pass")),
400
+ metrics_pass=sum(1 for r in ex if r.get("metrics_pass")),
401
+ verdicts={v: sum(1 for r in ex if r.get("verdict") == v)
402
+ for v in ("PASS", "WARN", "FAIL")},
403
+ )
404
+ report["guardrails"]["summary"] = dict(
405
+ total=len(gd), passed=sum(1 for r in gd if r["verdict"] == "PASS"))
406
+
407
+ # ── Console + JSON ──
408
+ if report["execution"]["results"]:
409
+ _print_exec_table(report["execution"]["results"])
410
+ if gd:
411
+ _print_guardrail_table(gd)
412
+
413
+ out_path = args.out or os.path.join(LOG_DIR, f"suite_{timestamp}.json")
414
+ with open(out_path, "w", encoding="utf-8") as fh:
415
+ json.dump(report, fh, indent=2, ensure_ascii=False)
416
+
417
+ es, gs = report["execution"]["summary"], report["guardrails"]["summary"]
418
+ print(f"\nReport written: {out_path}")
419
+ print(f"EXECUTION : {es['functional_pass']}/{es['ran']} functional-pass "
420
+ f"(verdicts {es['verdicts']})")
421
+ print(f"GUARDRAILS: {gs['passed']}/{gs['total']} passed")
422
+
423
+ functional_fail = es["ran"] - es["functional_pass"]
424
+ guardrail_fail = gs["total"] - gs["passed"]
425
+ sys.exit(1 if (functional_fail or guardrail_fail) else 0)
426
+
427
+
428
+ if __name__ == "__main__":
429
+ main()
tests/__pycache__/test_geofik.cpython-310-pytest-8.3.5.pyc CHANGED
Binary files a/tests/__pycache__/test_geofik.cpython-310-pytest-8.3.5.pyc and b/tests/__pycache__/test_geofik.cpython-310-pytest-8.3.5.pyc differ
 
tests/__pycache__/test_llm_plan.cpython-310-pytest-8.3.5.pyc CHANGED
Binary files a/tests/__pycache__/test_llm_plan.cpython-310-pytest-8.3.5.pyc and b/tests/__pycache__/test_llm_plan.cpython-310-pytest-8.3.5.pyc differ
 
tests/__pycache__/test_new_pipeline.cpython-310-pytest-8.3.5.pyc CHANGED
Binary files a/tests/__pycache__/test_new_pipeline.cpython-310-pytest-8.3.5.pyc and b/tests/__pycache__/test_new_pipeline.cpython-310-pytest-8.3.5.pyc differ
 
tests/__pycache__/test_occupancy.cpython-310-pytest-8.3.5.pyc CHANGED
Binary files a/tests/__pycache__/test_occupancy.cpython-310-pytest-8.3.5.pyc and b/tests/__pycache__/test_occupancy.cpython-310-pytest-8.3.5.pyc differ
 
tests/__pycache__/test_pipeline.cpython-310-pytest-8.3.5.pyc CHANGED
Binary files a/tests/__pycache__/test_pipeline.cpython-310-pytest-8.3.5.pyc and b/tests/__pycache__/test_pipeline.cpython-310-pytest-8.3.5.pyc differ
 
tests/__pycache__/test_task_nullspace.cpython-310-pytest-8.3.5.pyc CHANGED
Binary files a/tests/__pycache__/test_task_nullspace.cpython-310-pytest-8.3.5.pyc and b/tests/__pycache__/test_task_nullspace.cpython-310-pytest-8.3.5.pyc differ
 
tests/test_llm_expected.json CHANGED
@@ -79,7 +79,7 @@
79
  {
80
  "id": 5,
81
  "category": "error_case",
82
- "note": "Instruction references an object that does not exist ('con mèo' = a cat). No match -> empty plan.",
83
  "instruction": "gắp con mèo lên",
84
  "scene_state": {
85
  "objects": [
@@ -90,7 +90,9 @@
90
  "carried_object": null,
91
  "tray": {"empty": true, "occupants": []}
92
  },
93
- "expected_plan": []
 
 
94
  },
95
  {
96
  "id": 6,
@@ -133,5 +135,91 @@
133
  {"function": "move_to", "args": {"location_id": "tray"}},
134
  {"function": "place_down", "args": {}}
135
  ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  }
137
  ]
 
79
  {
80
  "id": 5,
81
  "category": "error_case",
82
+ "note": "Instruction references an object that does not exist ('con mèo' = a cat). No match -> reject plan.",
83
  "instruction": "gắp con mèo lên",
84
  "scene_state": {
85
  "objects": [
 
90
  "carried_object": null,
91
  "tray": {"empty": true, "occupants": []}
92
  },
93
+ "expected_plan": [
94
+ {"function": "reject", "args": {"message": "Trong môi trường không có con mèo nào cả, tôi không thể thực hiện được."}}
95
+ ]
96
  },
97
  {
98
  "id": 6,
 
135
  {"function": "move_to", "args": {"location_id": "tray"}},
136
  {"function": "place_down", "args": {}}
137
  ]
138
+ },
139
+ {
140
+ "id": 8,
141
+ "category": "spatial_reasoning",
142
+ "note": "Relative direction: pick the object to the left of the banana and place on tray.",
143
+ "instruction": "gắp vật nằm bên trái quả chuối đặt vào khay",
144
+ "scene_state": {
145
+ "objects": [
146
+ {
147
+ "name": "banana",
148
+ "class": "banana",
149
+ "location": "table",
150
+ "reachable": true,
151
+ "distances": {"soup_can": 0.12},
152
+ "relations": {"left_of": ["soup_can"], "right_of": [], "front_of": [], "behind": [], "on_top_of": null, "supporting": []}
153
+ },
154
+ {
155
+ "name": "soup_can",
156
+ "class": "can",
157
+ "location": "table",
158
+ "reachable": true,
159
+ "distances": {"banana": 0.12},
160
+ "relations": {"left_of": [], "right_of": ["banana"], "front_of": [], "behind": [], "on_top_of": null, "supporting": []}
161
+ }
162
+ ],
163
+ "carried_object": null,
164
+ "tray": {"empty": true, "occupants": []}
165
+ },
166
+ "expected_plan": [
167
+ {"function": "pick_up", "args": {"object_id": "soup_can"}},
168
+ {"function": "move_to", "args": {"location_id": "tray"}},
169
+ {"function": "place_down", "args": {}}
170
+ ]
171
+ },
172
+ {
173
+ "id": 9,
174
+ "category": "spatial_reasoning",
175
+ "note": "Stack placement: place the banana on top of the soup can.",
176
+ "instruction": "đặt quả chuối lên trên lon súp",
177
+ "scene_state": {
178
+ "objects": [
179
+ {"name": "banana", "class": "banana", "location": "table", "reachable": true, "distances": {"soup_can": 0.15}, "relations": {"left_of": [], "right_of": [], "front_of": [], "behind": [], "on_top_of": null, "supporting": []}},
180
+ {"name": "soup_can", "class": "can", "location": "table", "reachable": true, "distances": {"banana": 0.15}, "relations": {"left_of": [], "right_of": [], "front_of": [], "behind": [], "on_top_of": null, "supporting": []}}
181
+ ],
182
+ "carried_object": null,
183
+ "tray": {"empty": true, "occupants": []}
184
+ },
185
+ "expected_plan": [
186
+ {"function": "pick_up", "args": {"object_id": "banana"}},
187
+ {"function": "move_to", "args": {"location_id": "table", "relation": "on_top_of", "relative_to": "soup_can"}},
188
+ {"function": "place_down", "args": {}}
189
+ ]
190
+ },
191
+ {
192
+ "id": 10,
193
+ "category": "spatial_reasoning",
194
+ "note": "Stack clearing: must pick up banana and put it down on table before picking up the soup can below.",
195
+ "instruction": "gắp lon súp",
196
+ "scene_state": {
197
+ "objects": [
198
+ {
199
+ "name": "banana",
200
+ "class": "banana",
201
+ "location": "table",
202
+ "reachable": true,
203
+ "distances": {"soup_can": 0.01},
204
+ "relations": {"left_of": [], "right_of": [], "front_of": [], "behind": [], "on_top_of": "soup_can", "supporting": []}
205
+ },
206
+ {
207
+ "name": "soup_can",
208
+ "class": "can",
209
+ "location": "table",
210
+ "reachable": true,
211
+ "distances": {"banana": 0.01},
212
+ "relations": {"left_of": [], "right_of": [], "front_of": [], "behind": [], "on_top_of": null, "supporting": ["banana"]}
213
+ }
214
+ ],
215
+ "carried_object": null,
216
+ "tray": {"empty": true, "occupants": []}
217
+ },
218
+ "expected_plan": [
219
+ {"function": "pick_up", "args": {"object_id": "banana"}},
220
+ {"function": "move_to", "args": {"location_id": "table"}},
221
+ {"function": "place_down", "args": {}},
222
+ {"function": "pick_up", "args": {"object_id": "soup_can"}}
223
+ ]
224
  }
225
  ]