C2-151 commited on
Commit
5b4c023
Β·
1 Parent(s): 563e902
This view is limited to 50 files because it contains too many changes. Β  See raw diff
Files changed (50) hide show
  1. .env +5 -0
  2. .history/.env_20260704103453 +22 -0
  3. .history/note_20260704093813.md +0 -0
  4. .history/note_20260704093816.md +34 -0
  5. .pytest_cache/v/cache/lastfailed +1 -10
  6. .pytest_cache/v/cache/nodeids +54 -1
  7. __pycache__/main.cpython-310.pyc +0 -0
  8. development_logs/2026-07-04_10-13-19_semantic-conversation-boundary-and-generalization-audit.md +64 -0
  9. development_logs/2026-07-04_10-28-46_implement-adaptive-environment-prompts.md +75 -0
  10. development_logs/2026-07-04_10-41-41_fix-follow-up-slot-grounding.md +69 -0
  11. development_logs/2026-07-04_10-54-16_fix-composite-replacement-memory.md +73 -0
  12. development_logs/2026-07-04_11-07-56_improve-adaptive-dialogue-grounding.md +71 -0
  13. development_logs/2026-07-04_11-18-47_normalize-intent-object-surface-namespaces.md +66 -0
  14. development_logs/2026-07-04_11-35-55_separate-user-constraints-from-intermediate-planning.md +81 -0
  15. development_logs/2026-07-04_11-59-33_implement-swap-former-location-anchors.md +77 -0
  16. development_logs/2026-07-04_13-42-09_implement-reload-persistence-and-live-interrupt.md +96 -0
  17. development_logs/2026-07-04_13-56-53_add-live-command-stop-button.md +71 -0
  18. development_logs/2026-07-04_17-10-44_restore-web-runtime-and-live-command-ui.md +78 -0
  19. development_logs/2026-07-04_17-21-10_restore-context-goal-and-clarification-behavior.md +82 -0
  20. development_logs/2026-07-04_17-34-05_normalize-standalone-compound-intents.md +78 -0
  21. development_logs/2026-07-04_17-53-16_add-web-manual-drag-and-catalog-spawn.md +97 -0
  22. development_logs/2026-07-04_18-00-40_fix-web-object-drag-and-runtime-visuals.md +83 -0
  23. docs/CONTEXT_AWARE_GOAL_CHECK_PLAN.md +6 -0
  24. docs/CONVERSATION_MEMORY_PLAN.md +27 -0
  25. docs/ENVIRONMENT_SEMANTIC_CATALOG.md +78 -0
  26. docs/GENERALIZATION_AUDIT.md +382 -0
  27. docs/WEB_RUNTIME_INTERRUPTION_PLAN.md +117 -0
  28. envs/default_desk.json +1 -0
  29. envs/default_desk.semantics.json +18 -0
  30. envs/env1.json +1 -0
  31. envs/env1.semantics.json +83 -0
  32. envs/scenarios/scenario_1.json +1 -0
  33. frontend/__pycache__/interactive_server.cpython-310.pyc +0 -0
  34. frontend/app.js +515 -225
  35. frontend/index.css +71 -6
  36. frontend/index.html +3 -3
  37. frontend/interactive_server.py +664 -204
  38. frontend/web_runtime.py +225 -0
  39. llm_panda/__pycache__/config.cpython-310.pyc +0 -0
  40. llm_panda/__pycache__/llm_agent.cpython-310.pyc +0 -0
  41. llm_panda/__pycache__/robot_controller.cpython-310.pyc +0 -0
  42. llm_panda/__pycache__/scene_manager.cpython-310.pyc +0 -0
  43. llm_panda/conversation/manager.py +12 -2
  44. llm_panda/conversation/models.py +2 -0
  45. llm_panda/core/env_builder.py +76 -0
  46. llm_panda/execution/cancellation.py +30 -0
  47. llm_panda/execution/monitor.py +28 -0
  48. llm_panda/execution/pipeline.py +31 -0
  49. llm_panda/llm_agent.py +1034 -82
  50. llm_panda/robot_controller.py +41 -14
.env CHANGED
@@ -2,6 +2,11 @@
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
  # 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
6
  # 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 cα»§a tΓ΄i
7
  # Default model
 
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
+ CONVERSATION_MEMORY_ENABLED=true
6
+ LLM_GOAL_RESOLUTION_ENABLED=true
7
+ STRUCTURED_GOAL_CHECK_ENABLED=true
8
+ MAX_REPLANS=3
9
+ LLM_STRUCTURED_OUTPUTS_ENABLED=auto
10
  # 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
11
  # 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 cα»§a tΓ΄i
12
  # Default model
.history/.env_20260704103453 ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ CONVERSATION_MEMORY_ENABLED=true
6
+ LLM_GOAL_RESOLUTION_ENABLED=true
7
+ STRUCTURED_GOAL_CHECK_ENABLED=true
8
+ MAX_REPLANS=3
9
+ LLM_STRUCTURED_OUTPUTS_ENABLED=auto
10
+ # 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
11
+ # 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 cα»§a tΓ΄i
12
+ # Default model
13
+ DEFAULT_MODEL=claude-sonnet-4-20250514
14
+ # DEFAULT_MODEL=gpt-4o
15
+
16
+ # Logging
17
+ LOG_LEVEL=INFO
18
+
19
+ # AI Hook Logging (set by instructor)
20
+ AI_LOG_SERVER=https://ai-logs.note.transformerlabs.ai/api/ingest
21
+ AI_LOG_API_KEY=ai20k__9Mr6_Jl3j3E0JKOiFh499mhxzSl0A47
22
+ AI_LOG_DIR=.ai-log
.history/note_20260704093813.md ADDED
File without changes
.history/note_20260704093816.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ > Gα»­i yΓͺu cαΊ§u: "cho quαΊ£ lΓͺ lΓͺn lon chip"
2
+ > TΓ΄i Δ‘ang suy nghΔ© cΓ‘ch thα»±c hiện...
3
+ > TΓ΄i Δ‘ang phΓ’n tΓ­ch yΓͺu cαΊ§u...
4
+ > I will pick up the tennis ball, soup can, chips can and pear and move to the table.
5
+ > TΓ΄i Δ‘ang kiểm tra mα»©c Δ‘α»™ an toΓ n cα»§a kαΊΏ hoαΊ‘ch...
6
+ > KαΊΏ hoαΊ‘ch an toΓ n vΓ  hợp lệ.
7
+ > TΓ΄i bαΊ―t Δ‘αΊ§u thα»±c hiện cΓ‘c bΖ°α»›c...
8
+ > TΓ΄i Δ‘ang gαΊ―p quαΊ£ bΓ³ng tennis lΓͺn...
9
+ > TΓ΄i Δ‘ang di chuyển Δ‘αΊΏn bΓ n...
10
+ > TΓ΄i Δ‘ang Δ‘αΊ·t Δ‘α»“ vαΊ­t xuα»‘ng...
11
+ > TΓ΄i Δ‘ang gαΊ―p lon sΓΊp lΓͺn...
12
+ > TΓ΄i Δ‘ang di chuyển Δ‘αΊΏn bΓ n...
13
+ > TΓ΄i Δ‘ang Δ‘αΊ·t Δ‘α»“ vαΊ­t xuα»‘ng...
14
+ > TΓ΄i Δ‘ang gαΊ―p lon snack lΓͺn...
15
+ > TΓ΄i Δ‘ang di chuyển Δ‘αΊΏn bΓ n...
16
+ > TΓ΄i Δ‘ang Δ‘αΊ·t Δ‘α»“ vαΊ­t xuα»‘ng...
17
+ > TΓ΄i Δ‘ang gαΊ―p quαΊ£ lΓͺ lΓͺn...
18
+ > Thα»±c thi lα»—i tαΊ‘i bΖ°α»›c 10 'pick_up': pick_up('pear') did not secure the object (gripper missed)
19
+ > [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 1)...
20
+ > [MONITOR] Re-plan attempt 1/3 due to: Step 10 'pick_up' failed: pick_up('pear') did not secure the object (gripper missed)
21
+ > TΓ΄i Δ‘ang suy nghΔ© cΓ‘ch thα»±c hiện...
22
+ > I will pick up the chips can, banana, soup can, chips can and pear and move to the table.
23
+ > TΓ΄i Δ‘ang kiểm tra mα»©c Δ‘α»™ an toΓ n cα»§a kαΊΏ hoαΊ‘ch...
24
+ > PhΓ‘t hiện 1 rα»§i ro tiềm αΊ©n.
25
+ > - step 12: pick_up target 'pear' is OUT OF REACH
26
+ > TΓ΄i bαΊ―t Δ‘αΊ§u thα»±c hiện cΓ‘c bΖ°α»›c...
27
+ > TΓ΄i Δ‘ang gαΊ―p lon snack lΓͺn...
28
+ > Thα»±c thi lα»—i tαΊ‘i bΖ°α»›c 1 'pick_up': pick_up('chips_can') did not secure the object (gripper missed)
29
+ > [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 2)...
30
+ > [MONITOR] Re-plan attempt 2/3 due to: Step 1 'pick_up' failed: pick_up('chips_can') did not secure the object (gripper missed)
31
+ > TΓ΄i Δ‘ang suy nghΔ© cΓ‘ch thα»±c hiện...
32
+ > TΓ΄i chΖ°a cΓ³ Δ‘α»§ thΓ΄ng tin để tαΊ‘o kαΊΏ hoαΊ‘ch an toΓ n. BαΊ‘n muα»‘n thao tΓ‘c vα»›i vαΊ­t nΓ o vΓ  Δ‘αΊ·t nΓ³ ở Δ‘Γ’u?
33
+ > Robot phαΊ£n hα»“i: TΓ΄i chΖ°a cΓ³ Δ‘α»§ thΓ΄ng tin để tαΊ‘o kαΊΏ hoαΊ‘ch an toΓ n. BαΊ‘n muα»‘n thao tΓ‘c vα»›i vαΊ­t nΓ o vΓ  Δ‘αΊ·t nΓ³ ở Δ‘Γ’u?
34
+
.pytest_cache/v/cache/lastfailed CHANGED
@@ -1,15 +1,6 @@
1
  {
2
- "tests/test_new_pipeline.py::test_pipeline_executor_completes_pick_and_place": true,
3
- "tests/test_pipeline.py::test_grasp_survives_fast_translation": true,
4
- "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_1_g\\u1eafp qu\\u1ea3 chu\\u1ed1i l\\xean]": true,
5
- "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_2_g\\u1eafp lon s\\xfap \\u0111\\u1eb7t l\\xean b\\xe0n]": true,
6
- "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_3_g\\u1eafp bim bim b\\u1ecf v\\xe0o khay]": true,
7
  "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_4_\\u0111\\u1eb7t v\\xe0o khay]": true,
8
  "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_5_g\\u1eafp con m\\xe8o l\\xean]": true,
9
- "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_6_g\\u1eafp lon chips \\u0111\\u1eb7t c\\u1ea1nh qu\\u1ea3 chu\\u1ed1i]": true,
10
- "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_7_d\\u1ecdn b\\xe0n \\u0111i]": true,
11
  "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]": true,
12
- "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]": true,
13
- "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_10_g\\u1eafp lon s\\xfap]": true,
14
- "tests/test_multi_angle.py::test_side_grasp_pose_is_tilted": true
15
  }
 
1
  {
 
 
 
 
 
2
  "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_4_\\u0111\\u1eb7t v\\xe0o khay]": true,
3
  "tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_5_g\\u1eafp con m\\xe8o l\\xean]": true,
 
 
4
  "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]": true,
5
+ "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]": true
 
 
6
  }
.pytest_cache/v/cache/nodeids CHANGED
@@ -5,26 +5,43 @@
5
  "tests/test_conversation_memory.py::test_clear_removes_pending_and_recent_turns",
6
  "tests/test_conversation_memory.py::test_complete_new_command_replaces_pending_request",
7
  "tests/test_conversation_memory.py::test_default_replan_limit_is_finite",
 
 
8
  "tests/test_conversation_memory.py::test_feature_flag_can_restore_stateless_behavior",
 
9
  "tests/test_conversation_memory.py::test_follow_up_completes_rule_based_plan_without_extra_api_call",
10
  "tests/test_conversation_memory.py::test_follow_up_marks_changed_scene_and_uses_fresh_state",
11
  "tests/test_conversation_memory.py::test_follow_up_uses_exactly_one_planner_call_per_user_turn",
 
12
  "tests/test_conversation_memory.py::test_goal_check_falls_back_to_live_geometry_for_on_top_relation",
13
  "tests/test_conversation_memory.py::test_goal_resolution_parser_accepts_structured_clarification",
14
  "tests/test_conversation_memory.py::test_goal_resolution_parser_rejects_ready_without_canonical_goal",
 
 
 
15
  "tests/test_conversation_memory.py::test_invalid_clarification_choice_keeps_original_request_pending",
16
  "tests/test_conversation_memory.py::test_invalid_physical_action_is_converted_to_clarification",
 
17
  "tests/test_conversation_memory.py::test_one_shot_command_is_not_rewritten",
18
  "tests/test_conversation_memory.py::test_pending_clarification_expires",
19
  "tests/test_conversation_memory.py::test_pipeline_agent_setter_keeps_monitor_agent_in_sync",
20
  "tests/test_conversation_memory.py::test_ready_goal_is_canonicalized_before_planning",
21
  "tests/test_conversation_memory.py::test_remote_parser_accepts_structured_plan_wrapper",
 
 
22
  "tests/test_conversation_memory.py::test_replan_can_skip_goal_resolution_gate",
23
  "tests/test_conversation_memory.py::test_rule_based_move_request_tracks_missing_destination",
 
24
  "tests/test_conversation_memory.py::test_sessions_do_not_share_pending_clarification",
 
25
  "tests/test_conversation_memory.py::test_structured_clarification_metadata_is_preserved",
26
  "tests/test_conversation_memory.py::test_structured_goal_check_uses_resolved_goal_not_raw_follow_up",
27
  "tests/test_conversation_memory.py::test_structured_output_falls_back_once_when_provider_rejects",
 
 
 
 
 
28
  "tests/test_cost_map.py::test_astar_finds_straight_path_on_empty_workspace",
29
  "tests/test_cost_map.py::test_astar_routes_around_tall_obstacle",
30
  "tests/test_cost_map.py::test_clearance_scales_with_carried_height",
@@ -37,6 +54,11 @@
37
  "tests/test_cost_map.py::test_tall_obstacle_is_a_cost_wall",
38
  "tests/test_cost_map.py::test_tray_obstacle_routes_within_workspace",
39
  "tests/test_cost_map.py::test_workspace_covers_table_and_tray",
 
 
 
 
 
40
  "tests/test_geofik.py::test_clamp_acos_input",
41
  "tests/test_geofik.py::test_franka_geometry",
42
  "tests/test_geofik.py::test_rotations",
@@ -69,9 +91,12 @@
69
  "tests/test_llm_plan.py::test_rule_based_planner_expected[Case_7_d\\u1ecdn b\\xe0n \\u0111i]",
70
  "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]",
71
  "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]",
 
72
  "tests/test_monitor.py::test_monitor_aborts_when_replan_repeats_failing_plan",
73
  "tests/test_monitor.py::test_monitor_replans_until_attempts_exhausted",
74
  "tests/test_monitor.py::test_monitor_stops_on_success",
 
 
75
  "tests/test_monitor.py::test_recover_returns_arm_to_safe_height",
76
  "tests/test_monitor.py::test_verify_step_flags_failed_grasp",
77
  "tests/test_monitor.py::test_verify_step_flags_joint_stuck",
@@ -100,6 +125,7 @@
100
  "tests/test_occupancy.py::test_on_top_detection_accepts_small_physics_interpenetration",
101
  "tests/test_occupancy.py::test_on_top_detection_rejects_object_floating_too_high",
102
  "tests/test_occupancy.py::test_on_top_detection_rejects_side_contact_with_tiny_overlap",
 
103
  "tests/test_occupancy.py::test_reachable_filter_is_applied",
104
  "tests/test_occupancy.py::test_relation_left_of_places_on_correct_side",
105
  "tests/test_occupancy.py::test_tray_object_does_not_count_against_the_table",
@@ -131,5 +157,32 @@
131
  "tests/test_pipeline.py::test_relation_word_inside_object_alias_does_not_trigger",
132
  "tests/test_pipeline.py::test_rule_based_planner_two_step_pick_place",
133
  "tests/test_task_nullspace.py::test_box_manifold_jacobian",
134
- "tests/test_task_nullspace.py::test_cylinder_manifold_jacobian"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  ]
 
5
  "tests/test_conversation_memory.py::test_clear_removes_pending_and_recent_turns",
6
  "tests/test_conversation_memory.py::test_complete_new_command_replaces_pending_request",
7
  "tests/test_conversation_memory.py::test_default_replan_limit_is_finite",
8
+ "tests/test_conversation_memory.py::test_directional_relation_to_surface_is_not_silently_rewritten",
9
+ "tests/test_conversation_memory.py::test_explicit_relation_without_reference_still_requires_clarification",
10
  "tests/test_conversation_memory.py::test_feature_flag_can_restore_stateless_behavior",
11
+ "tests/test_conversation_memory.py::test_follow_up_cannot_overwrite_manipulated_object_slot",
12
  "tests/test_conversation_memory.py::test_follow_up_completes_rule_based_plan_without_extra_api_call",
13
  "tests/test_conversation_memory.py::test_follow_up_marks_changed_scene_and_uses_fresh_state",
14
  "tests/test_conversation_memory.py::test_follow_up_uses_exactly_one_planner_call_per_user_turn",
15
+ "tests/test_conversation_memory.py::test_former_location_infers_anchor_surface_from_scene",
16
  "tests/test_conversation_memory.py::test_goal_check_falls_back_to_live_geometry_for_on_top_relation",
17
  "tests/test_conversation_memory.py::test_goal_resolution_parser_accepts_structured_clarification",
18
  "tests/test_conversation_memory.py::test_goal_resolution_parser_rejects_ready_without_canonical_goal",
19
+ "tests/test_conversation_memory.py::test_goal_resolution_repairs_empty_provider_response_without_losing_context",
20
+ "tests/test_conversation_memory.py::test_intermediate_execution_is_excluded_from_resolved_goal",
21
+ "tests/test_conversation_memory.py::test_intermediate_task_needs_no_user_selected_destination_or_relation",
22
  "tests/test_conversation_memory.py::test_invalid_clarification_choice_keeps_original_request_pending",
23
  "tests/test_conversation_memory.py::test_invalid_physical_action_is_converted_to_clarification",
24
+ "tests/test_conversation_memory.py::test_llm_semantically_replaces_pending_without_fixed_verb_list",
25
  "tests/test_conversation_memory.py::test_one_shot_command_is_not_rewritten",
26
  "tests/test_conversation_memory.py::test_pending_clarification_expires",
27
  "tests/test_conversation_memory.py::test_pipeline_agent_setter_keeps_monitor_agent_in_sync",
28
  "tests/test_conversation_memory.py::test_ready_goal_is_canonicalized_before_planning",
29
  "tests/test_conversation_memory.py::test_remote_parser_accepts_structured_plan_wrapper",
30
+ "tests/test_conversation_memory.py::test_replacement_follow_up_preserves_all_ordered_tasks",
31
+ "tests/test_conversation_memory.py::test_replacement_plan_missing_second_task_is_rejected",
32
  "tests/test_conversation_memory.py::test_replan_can_skip_goal_resolution_gate",
33
  "tests/test_conversation_memory.py::test_rule_based_move_request_tracks_missing_destination",
34
+ "tests/test_conversation_memory.py::test_self_referential_spatial_goal_is_blocked_before_planner",
35
  "tests/test_conversation_memory.py::test_sessions_do_not_share_pending_clarification",
36
+ "tests/test_conversation_memory.py::test_standalone_compound_intent_normalizes_every_task_adaptively",
37
  "tests/test_conversation_memory.py::test_structured_clarification_metadata_is_preserved",
38
  "tests/test_conversation_memory.py::test_structured_goal_check_uses_resolved_goal_not_raw_follow_up",
39
  "tests/test_conversation_memory.py::test_structured_output_falls_back_once_when_provider_rejects",
40
+ "tests/test_conversation_memory.py::test_surface_reference_is_normalized_to_surface_destination",
41
+ "tests/test_conversation_memory.py::test_surface_reference_normalization_applies_to_every_sequence_task",
42
+ "tests/test_conversation_memory.py::test_swap_former_locations_are_anchored_from_initial_scene",
43
+ "tests/test_conversation_memory.py::test_swap_goal_compiles_position_predicates_not_surface_only",
44
+ "tests/test_conversation_memory.py::test_unconstrained_dangling_relation_is_removed_after_destination_reply",
45
  "tests/test_cost_map.py::test_astar_finds_straight_path_on_empty_workspace",
46
  "tests/test_cost_map.py::test_astar_routes_around_tall_obstacle",
47
  "tests/test_cost_map.py::test_clearance_scales_with_carried_height",
 
54
  "tests/test_cost_map.py::test_tall_obstacle_is_a_cost_wall",
55
  "tests/test_cost_map.py::test_tray_obstacle_routes_within_workspace",
56
  "tests/test_cost_map.py::test_workspace_covers_table_and_tray",
57
+ "tests/test_environment_semantics.py::test_adaptive_prompt_uses_only_active_environment_catalog",
58
+ "tests/test_environment_semantics.py::test_entity_grounding_uses_unique_aliases_from_active_catalog",
59
+ "tests/test_environment_semantics.py::test_env1_references_catalog_covering_every_configured_object",
60
+ "tests/test_environment_semantics.py::test_env_builder_loads_referenced_catalog_into_scene",
61
+ "tests/test_environment_semantics.py::test_remote_core_prompt_no_longer_contains_env1_object_catalog",
62
  "tests/test_geofik.py::test_clamp_acos_input",
63
  "tests/test_geofik.py::test_franka_geometry",
64
  "tests/test_geofik.py::test_rotations",
 
91
  "tests/test_llm_plan.py::test_rule_based_planner_expected[Case_7_d\\u1ecdn b\\xe0n \\u0111i]",
92
  "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]",
93
  "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]",
94
+ "tests/test_monitor.py::test_controller_cancellation_stops_inside_cartesian_motion",
95
  "tests/test_monitor.py::test_monitor_aborts_when_replan_repeats_failing_plan",
96
  "tests/test_monitor.py::test_monitor_replans_until_attempts_exhausted",
97
  "tests/test_monitor.py::test_monitor_stops_on_success",
98
+ "tests/test_monitor.py::test_pipeline_interrupts_between_steps_without_recovery",
99
+ "tests/test_monitor.py::test_position_near_goal_requires_actual_swap_coordinate",
100
  "tests/test_monitor.py::test_recover_returns_arm_to_safe_height",
101
  "tests/test_monitor.py::test_verify_step_flags_failed_grasp",
102
  "tests/test_monitor.py::test_verify_step_flags_joint_stuck",
 
125
  "tests/test_occupancy.py::test_on_top_detection_accepts_small_physics_interpenetration",
126
  "tests/test_occupancy.py::test_on_top_detection_rejects_object_floating_too_high",
127
  "tests/test_occupancy.py::test_on_top_detection_rejects_side_contact_with_tiny_overlap",
128
+ "tests/test_occupancy.py::test_preferred_position_biases_free_placement_to_swap_anchor",
129
  "tests/test_occupancy.py::test_reachable_filter_is_applied",
130
  "tests/test_occupancy.py::test_relation_left_of_places_on_correct_side",
131
  "tests/test_occupancy.py::test_tray_object_does_not_count_against_the_table",
 
157
  "tests/test_pipeline.py::test_relation_word_inside_object_alias_does_not_trigger",
158
  "tests/test_pipeline.py::test_rule_based_planner_two_step_pick_place",
159
  "tests/test_task_nullspace.py::test_box_manifold_jacobian",
160
+ "tests/test_task_nullspace.py::test_cylinder_manifold_jacobian",
161
+ "tests/test_web_command_button.py::test_clarification_result_is_not_recorded_as_failed_execution",
162
+ "tests/test_web_command_button.py::test_click_stops_but_enter_submits_replacement_command",
163
+ "tests/test_web_command_button.py::test_command_input_stays_enabled_while_execution_is_active",
164
+ "tests/test_web_command_button.py::test_execution_button_has_spinner_and_stop_square",
165
+ "tests/test_web_command_button.py::test_html_cache_busts_live_command_assets",
166
+ "tests/test_web_drag_drop.py::test_catalog_rows_spawn_real_runtime_objects",
167
+ "tests/test_web_drag_drop.py::test_delete_ui_and_incremental_object_events_exist",
168
+ "tests/test_web_drag_drop.py::test_disconnect_cleans_up_physics_constraint",
169
+ "tests/test_web_drag_drop.py::test_environment_dropdown_excludes_semantic_catalogs",
170
+ "tests/test_web_drag_drop.py::test_environment_listing_keeps_valid_empty_scene_templates",
171
+ "tests/test_web_drag_drop.py::test_frontend_uses_complete_pointer_lifecycle_and_drag_ids",
172
+ "tests/test_web_drag_drop.py::test_manual_target_is_clamped_to_workspace_and_surface",
173
+ "tests/test_web_drag_drop.py::test_manual_target_rejects_non_finite_coordinates",
174
+ "tests/test_web_drag_drop.py::test_objects_are_selected_for_deletion_not_manually_dragged",
175
+ "tests/test_web_drag_drop.py::test_robot_and_object_drag_have_separate_backend_paths",
176
+ "tests/test_web_drag_drop.py::test_runtime_visual_metadata_uses_mesh_matching_material",
177
+ "tests/test_web_runtime.py::test_cancel_all_interrupts_active_and_discards_pending_command",
178
+ "tests/test_web_runtime.py::test_cancellation_token_raises_only_after_request",
179
+ "tests/test_web_runtime.py::test_event_journal_is_bounded_and_replayable",
180
+ "tests/test_web_runtime.py::test_explicit_reset_clears_ui_history_but_keeps_monotonic_sequence",
181
+ "tests/test_web_runtime.py::test_new_command_cancels_active_and_latest_pending_wins",
182
+ "tests/test_web_runtime.py::test_reload_snapshot_preserves_runtime_state_and_event_history",
183
+ "tests/test_web_runtime.py::test_runtime_conversation_survives_client_disconnect",
184
+ "tests/test_web_runtime.py::test_scene_reset_clears_cli_conversation_memory",
185
+ "tests/test_web_runtime.py::test_stale_result_is_journaled_but_does_not_replace_latest_result",
186
+ "tests/test_web_runtime.py::test_web_pipeline_keeps_resolved_goal_across_replans_and_goal_check",
187
+ "tests/test_web_runtime.py::test_web_replan_limit_uses_environment_configuration"
188
  ]
__pycache__/main.cpython-310.pyc CHANGED
Binary files a/__pycache__/main.cpython-310.pyc and b/__pycache__/main.cpython-310.pyc differ
 
development_logs/2026-07-04_10-13-19_semantic-conversation-boundary-and-generalization-audit.md ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Semantic conversation boundary vΓ  generalization audit
2
+
3
+ ## YΓͺu cαΊ§u
4
+
5
+ - Cho Remote LLM tα»± reasoning lệnh mα»›i/follow-up thay vΓ¬ dα»±a trΓͺn danh sΓ‘ch Δ‘α»™ng tα»«
6
+ cα»‘ Δ‘α»‹nh.
7
+ - Kiểm kΓͺ toΓ n bα»™ phαΊ§n hard-code khiαΊΏn dα»± Γ‘n chỉ tα»‘i Ζ°u cho mα»™t sα»‘ object, hΓ nh vi
8
+ hoặc môi trường.
9
+
10
+ ## PhαΊ‘m vi vΓ  giαΊ£ Δ‘α»‹nh
11
+
12
+ - Thay Δ‘α»•i runtime chỉ ở conversation boundary cα»§a luα»“ng Remote LLM.
13
+ - Giα»― lexical heuristic cho RuleBasedPlanner/offline fallback để khΓ΄ng phΓ‘ tΓ­nh nΔƒng.
14
+ - Chưa tự động thay toàn bộ action/location/robot architecture vì đÒy là thay đổi
15
+ nhiều phase và ảnh hưởng tưƑng thích.
16
+ - TαΊ‘o tΓ i liệu audit vΓ  lα»™ trΓ¬nh chi tiαΊΏt cho phαΊ§n cΓ²n lαΊ‘i.
17
+
18
+ ## File sα»­a/thΓͺm
19
+
20
+ - Sα»­a `llm_panda/conversation/manager.py`.
21
+ - Sα»­a `llm_panda/llm_agent.py`.
22
+ - Sα»­a `tests/test_conversation_memory.py`.
23
+ - ThΓͺm `docs/GENERALIZATION_AUDIT.md`.
24
+ - ThΓͺm development log nΓ y.
25
+
26
+ ## HΓ nh vi trΖ°α»›c
27
+
28
+ - Khi cΓ³ pending clarification, `_ACTION_WORDS` + `_OBJECT_WORDS` quyαΊΏt Δ‘α»‹nh cΓ’u mα»›i.
29
+ - `cho quαΊ£ lΓͺ lΓͺn lon chip` khΓ΄ng cΓ³ Δ‘α»™ng tα»« trong list nΓͺn bα»‹ ghΓ©p vα»›i pending cΕ©.
30
+ - Plan output lα»—i bα»‹ bΓ‘o sai thΓ nh β€œngười dΓΉng chΖ°a cung cαΊ₯p Δ‘α»§ thΓ΄ng tin”.
31
+
32
+ ## HΓ nh vi sau
33
+
34
+ - Khi planner cΓ³ Goal Resolver, `ConversationManager` luΓ΄n cung cαΊ₯p pending context
35
+ vΓ  khΓ΄ng tα»± phΓ’n loαΊ‘i bαΊ±ng lexical list.
36
+ - Goal Resolver trαΊ£ `conversation_mode=standalone|follow_up`.
37
+ - `standalone` Δ‘Γ³ng pending cΕ©; `follow_up` tiαΊΏp tα»₯c bα»• sung intent.
38
+ - Prompt nΓͺu rΓ΅ phαΊ£i reasoning semantic, kể cαΊ£ wording chΖ°a cΓ³ trong examples.
39
+ - Plan rα»—ng/sai schema được bΓ‘o lΓ  lα»—i model output, khΓ΄ng Δ‘α»• lα»—i cho người dΓΉng.
40
+ - Rule-based/offline vαΊ«n giα»― heuristic cΕ© lΓ m fallback.
41
+
42
+ ## Kiểm tra
43
+
44
+ - Test Δ‘ang cΓ³ pending `Δ‘αΊ·t vΓ o khay`, sau Δ‘Γ³ nhαΊ­p
45
+ `cho quαΊ£ lΓͺ lΓͺn lon chip`.
46
+ - XΓ‘c nhαΊ­n LLM resolver nhαΊ­n cαΊ£ context, quyαΊΏt Δ‘α»‹nh `standalone`.
47
+ - XΓ‘c nhαΊ­n planner chỉ nhαΊ­n canonical goal
48
+ `Δ‘αΊ·t pear on_top_of chips_can trΓͺn table`.
49
+ - XΓ‘c nhαΊ­n pending cΕ© bα»‹ Δ‘Γ³ng vΓ  plan ba bΖ°α»›c được giα»― nguyΓͺn.
50
+ - Regression liΓͺn quan: **64 passed**.
51
+ - Python compile vΓ  `git diff --check` chαΊ‘y ở bΖ°α»›c xΓ‘c minh cuα»‘i.
52
+
53
+ ## BαΊ£o toΓ n
54
+
55
+ - KhΓ΄ng sα»­a `.env`, secret, robot speed, motion executor hoαΊ·c physics.
56
+ - KhΓ΄ng xΓ³a RuleBasedPlanner.
57
+ - API `LLMAgent.plan()` vΓ  action list hiện tαΊ‘i vαΊ«n tΖ°Ζ‘ng thΓ­ch.
58
+
59
+ ## VαΊ₯n đề cΓ²n lαΊ‘i
60
+
61
+ - Core action/location/relation ontology, prompt object catalog, grasp classes,
62
+ table/tray world model, motion planner, monitor, UI vΓ  scoring vαΊ«n cΓ³ hard-code.
63
+ - ToΓ n bα»™ danh sΓ‘ch vΓ  lα»™ trΓ¬nh loαΊ‘i bỏ được ghi tαΊ‘i
64
+ `docs/GENERALIZATION_AUDIT.md`.
development_logs/2026-07-04_10-28-46_implement-adaptive-environment-prompts.md ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Triển khai adaptive environment prompts
2
+
3
+ ## YΓͺu cαΊ§u
4
+
5
+ - Giα»― nguyΓͺn Panda model, A* 2D/U-trajectory, Goal Predicate vΓ  scoring vΓ¬ thuα»™c
6
+ scope bΓ i toΓ‘n.
7
+ - Tα»•ng quΓ‘t hΓ³a semantic information theo tα»«ng mΓ΄i trường.
8
+ - Mα»—i environment lΖ°u thΓ΄ng tin trong file riΓͺng vΓ  prompt phαΊ£i tα»± thay Δ‘α»•i khi Δ‘α»•i
9
+ environment.
10
+
11
+ ## PhαΊ‘m vi vΓ  giαΊ£ Δ‘α»‹nh
12
+
13
+ - Thα»±c hiện Phase G1 cα»§a generalization audit.
14
+ - KhΓ΄ng thay robot/controller, motion planning, predicates hoαΊ·c scoring.
15
+ - Giα»― RuleBasedPlanner hard-code lΓ m offline fallback.
16
+ - Remote Goal Resolver, Planner vΓ  fallback Goal Check dΓΉng adaptive catalog.
17
+
18
+ ## File thΓͺm/sα»­a
19
+
20
+ - Sα»­a `envs/env1.json`.
21
+ - Sα»­a `envs/default_desk.json`.
22
+ - Sα»­a `envs/scenarios/scenario_1.json`.
23
+ - ThΓͺm `envs/env1.semantics.json`.
24
+ - ThΓͺm `envs/default_desk.semantics.json`.
25
+ - Sα»­a `llm_panda/core/env_builder.py`.
26
+ - Sα»­a `llm_panda/scene_manager.py`.
27
+ - Sα»­a `llm_panda/llm_agent.py`.
28
+ - ThΓͺm `tests/test_environment_semantics.py`.
29
+ - Sα»­a `docs/GENERALIZATION_AUDIT.md`.
30
+ - ThΓͺm `docs/ENVIRONMENT_SEMANTIC_CATALOG.md`.
31
+ - ThΓͺm development log nΓ y.
32
+
33
+ ## HΓ nh vi trΖ°α»›c
34
+
35
+ - Object properties vΓ  synonym cα»§a sΓ‘u object nαΊ±m trα»±c tiαΊΏp trong Remote LLM prompt.
36
+ - Đổi object/environment khΓ΄ng tα»± Δ‘α»•i semantic prompt.
37
+ - Environment JSON chỉ chα»©a geometry/asset; scene state khΓ΄ng mang semantic metadata.
38
+ - Fallback Goal Check lαΊ·p lαΊ‘i object facts hard-code.
39
+
40
+ ## HΓ nh vi sau
41
+
42
+ - Environment tham chiαΊΏu semantic catalog bαΊ±ng relative path.
43
+ - Catalog lΖ°u display name, aliases, categories, attributes vΓ  affordances.
44
+ - EnvBuilder kiểm tra mọi configured object vΓ  table/tray đều được mΓ΄ tαΊ£.
45
+ - Scene state chα»©a environment metadata vΓ  semantic data cα»§a object hiện cΓ³.
46
+ - Prompt được tαΊ‘o Δ‘α»™ng theo environment/objects cα»§a scene hiện tαΊ‘i.
47
+ - Core Remote prompt khΓ΄ng cΓ²n catalog/synonym/examples riΓͺng cα»§a `env1`.
48
+ - Fallback Goal Check dΓΉng cΓΉng adaptive context.
49
+
50
+ ## Kiểm tra
51
+
52
+ - XΓ‘c minh catalog `env1` bao phα»§ toΓ n bα»™ configured objects.
53
+ - XΓ‘c minh EnvBuilder nαΊ‘p Δ‘ΓΊng catalog referenced.
54
+ - DΓΉng hai scene giαΊ£ lαΊ­p `orchard` vΓ  `workshop`; prompt chα»©a Δ‘ΓΊng object/surface cα»§a
55
+ tα»«ng scene vΓ  khΓ΄ng rΓ² catalog scene kia.
56
+ - XΓ‘c minh core Remote prompt khΓ΄ng chα»©a ID riΓͺng `soup_can`, `chips_can`,
57
+ `tennis_ball`.
58
+ - Regression liΓͺn quan: **68 passed**.
59
+ - Python compile vΓ  `git diff --check` chαΊ‘y ở bΖ°α»›c xΓ‘c minh cuα»‘i.
60
+
61
+ ## BαΊ£o toΓ n
62
+
63
+ - KhΓ΄ng sα»­a `.env`, secrets, `.history` hoαΊ·c thay Δ‘α»•i local ngoΓ i phαΊ‘m vi.
64
+ - KhΓ΄ng sα»­a Panda model/controller.
65
+ - KhΓ΄ng sα»­a A* 2D/U-trajectory.
66
+ - KhΓ΄ng sα»­a Goal Predicate.
67
+ - KhΓ΄ng sα»­a scoring.
68
+ - API plan/action hiện tαΊ‘i giα»― nguyΓͺn.
69
+
70
+ ## VαΊ₯n đề cΓ²n lαΊ‘i
71
+
72
+ - UI/server vαΊ«n cΓ³ map tΓͺn hiển thα»‹ cα»§a sΓ‘u object; Phase G1 tiαΊΏp theo nΓͺn đọc display
73
+ name tα»« scene catalog.
74
+ - RuleBasedPlanner vαΊ«n dΓΉng synonym hard-code theo chα»§ Δ‘Γ­ch offline fallback.
75
+ - Action/location/relation schema vαΊ«n thuα»™c scope pick-and-place hiện tαΊ‘i.
development_logs/2026-07-04_10-41-41_fix-follow-up-slot-grounding.md ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Sα»­a follow-up ghi Δ‘Γ¨ object vΓ  tαΊ‘o self-reference
2
+
3
+ ## YΓͺu cαΊ§u
4
+
5
+ Sα»­a ca hα»™i thoαΊ‘i:
6
+
7
+ 1. `cho kαΊΉp lΓͺn trΓͺn lon`;
8
+ 2. robot hỏi chọn lon súp hay lon chips;
9
+ 3. người dùng chọn lon súp;
10
+ 4. hệ thα»‘ng lαΊ‘i lαΊ­p plan `soup_can on_top_of soup_can`.
11
+
12
+ ## NguyΓͺn nhΓ’n
13
+
14
+ - Prompt chΖ°a Δ‘α»‹nh nghΔ©a rΓ΅ vai trΓ² tα»«ng slot.
15
+ - `object_id` bα»‹ dΓΉng Δ‘α»“ng thời cho vαΊ­t cαΊ§n thao tΓ‘c vΓ  object tham chiαΊΏu.
16
+ - `destination` Δ‘Γ΄i khi bα»‹ dΓΉng cho reference object dΓΉ nΓ³ phαΊ£i lΓ  surface.
17
+ - Follow-up cΓ³ thể ghi Δ‘Γ¨ `object_id=clamp` Δ‘Γ£ biαΊΏt bαΊ±ng cΓ’u trαΊ£ lời
18
+ `object_id=soup_can`.
19
+ - Không có guard ngăn `object_id == relative_to`.
20
+ - KhΓ΄ng cΓ³ kiểm tra plan sinh ra cΓ³ khα»›p resolved intent hay khΓ΄ng.
21
+
22
+ ## PhαΊ‘m vi
23
+
24
+ - SiαΊΏt Goal Resolution schema semantics vΓ  deterministic intent merge.
25
+ - KhΓ΄ng thay Δ‘α»•i Panda, A* 2D/U-trajectory, Goal Predicate hoαΊ·c scoring.
26
+ - KhΓ΄ng thay Δ‘α»•i chuyển Δ‘α»™ng/grasp/placement.
27
+
28
+ ## File sα»­a
29
+
30
+ - `llm_panda/llm_agent.py`
31
+ - `tests/test_conversation_memory.py`
32
+ - `docs/CONTEXT_AWARE_GOAL_CHECK_PLAN.md`
33
+ - ThΓͺm development log nΓ y.
34
+
35
+ ## HΓ nh vi sau
36
+
37
+ - Slot cΓ³ nghΔ©a duy nhαΊ₯t:
38
+ - `object_id`: vαΊ­t robot thao tΓ‘c;
39
+ - `destination`: surface table/tray;
40
+ - `relation`: quan hệ khΓ΄ng gian;
41
+ - `relative_to`: object tham chiαΊΏu.
42
+ - Follow-up chỉ được Δ‘iền field Δ‘ang thiαΊΏu.
43
+ - Slot Δ‘Γ£ biαΊΏt tα»« pending intent được bαΊ£o vệ khỏi model overwrite.
44
+ - Metadata cΕ© dΓΉng object lΓ m `destination` được migrate sang `relative_to`.
45
+ - Canonical instruction được dα»±ng deterministic tα»« merged intent.
46
+ - Object/reference khΓ΄ng tα»“n tαΊ‘i vΓ  self-reference bα»‹ clarify trΖ°α»›c planner.
47
+ - Plan khΓ΄ng khα»›p resolved intent bα»‹ reject trΖ°α»›c executor.
48
+
49
+ ## Kiểm tra
50
+
51
+ - TΓ‘i hiện pending intent `object_id=clamp`, `relation=on_top_of`.
52
+ - Cho resolver cα»‘ trαΊ£ sai `soup_can on_top_of soup_can`.
53
+ - XΓ‘c nhαΊ­n planner thα»±c tαΊΏ nhαΊ­n
54
+ `place clamp on_top_of soup_can on table`.
55
+ - XΓ‘c nhαΊ­n self-reference bα»‹ chαΊ·n vΓ  planner khΓ΄ng được gọi.
56
+ - Regression liΓͺn quan: **70 passed**.
57
+ - Python compile vΓ  `git diff --check` chαΊ‘y ở bΖ°α»›c xΓ‘c minh cuα»‘i.
58
+
59
+ ## BαΊ£o toΓ n
60
+
61
+ - KhΓ΄ng sα»­a `.env`, secrets, `.history` hoαΊ·c robot speed.
62
+ - KhΓ΄ng sα»­a motion planner, Goal Predicate vΓ  scoring.
63
+ - API plan/action hiện tαΊ‘i giα»― nguyΓͺn.
64
+
65
+ ## VαΊ₯n đề cΓ²n lαΊ‘i
66
+
67
+ - Live OpenRouter vαΊ«n cαΊ§n kiểm thα»­ sau khi restart α»©ng dα»₯ng.
68
+ - NαΊΏu bα»• sung action phα»©c hợp ngoΓ i pick-and-place, typed intent cαΊ§n được version hΓ³a
69
+ thay vΓ¬ mở rα»™ng mα»™t dict khΓ΄ng schema.
development_logs/2026-07-04_10-54-16_fix-composite-replacement-memory.md ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Sα»­a composite replacement bα»‹ mαΊ₯t task sau clarification
2
+
3
+ ## YΓͺu cαΊ§u
4
+
5
+ Sα»­a lα»—i robot chỉ dời chiαΊΏc kαΊΉp nhΖ°ng khΓ΄ng thα»±c hiện phαΊ§n β€œthαΊΏ chα»— cΓ‘i kαΊΉp bαΊ±ng
6
+ quαΊ£ bΓ³ng”.
7
+
8
+ ## PhΓ’n tΓ­ch log
9
+
10
+ Goal Resolver ban Δ‘αΊ§u hiểu Δ‘ΓΊng hai hiệu α»©ng:
11
+
12
+ 1. lαΊ₯y kαΊΉp khỏi trΓͺn lon sΓΊp vΓ  Δ‘αΊ·t kαΊΉp sang nΖ‘i khΓ‘c;
13
+ 2. Δ‘αΊ·t bΓ³ng tennis lΓͺn trΓͺn lon sΓΊp.
14
+
15
+ VΓ¬ chΖ°a biαΊΏt vα»‹ trΓ­ mα»›i cα»§a kαΊΉp, robot hỏi lαΊ‘i. Khi người dΓΉng trαΊ£ lời β€œΔ‘α»ƒ trΓͺn
16
+ bΓ n”, resolved intent phαΊ³ng chỉ giα»― task dời kαΊΉp. Planner vΓ¬ vαΊ­y sinh Δ‘ΓΊng ba bΖ°α»›c
17
+ cho kαΊΉp nhΖ°ng lΓ m mαΊ₯t task Δ‘αΊ·t bΓ³ng.
18
+
19
+ ## NguyΓͺn nhΓ’n
20
+
21
+ - Intent model trΖ°α»›c Δ‘Γ’y chỉ cΓ³ mα»™t `object_id/destination/relation/relative_to`.
22
+ - KhΓ΄ng cΓ³ representation cho ordered multi-object task.
23
+ - Follow-up merge chỉ bαΊ£o vệ slot cα»§a mα»™t task.
24
+ - Plan/goal guard chỉ kiểm tra mα»™t hiệu α»©ng cuα»‘i.
25
+
26
+ ## PhαΊ‘m vi
27
+
28
+ - Mở rα»™ng resolved intent trong scope pick-and-place hiện tαΊ‘i.
29
+ - KhΓ΄ng thay Panda, A* 2D/U-trajectory, Goal Predicate hoαΊ·c scoring.
30
+ - KhΓ΄ng thay executor action primitives.
31
+
32
+ ## File sα»­a
33
+
34
+ - `llm_panda/llm_agent.py`
35
+ - `tests/test_conversation_memory.py`
36
+ - `docs/CONTEXT_AWARE_GOAL_CHECK_PLAN.md`
37
+ - ThΓͺm development log nΓ y.
38
+
39
+ ## HΓ nh vi sau
40
+
41
+ - Compound/swap/replacement dΓΉng:
42
+ `{"action":"sequence","tasks":[...]}`.
43
+ - Replacement lΖ°u hai task:
44
+ - relocate displaced object;
45
+ - place replacement object vΓ o semantic position/relation cΕ©.
46
+ - Follow-up chỉ Δ‘iền field cΓ²n thiαΊΏu cα»§a task tΖ°Ζ‘ng α»©ng.
47
+ - CΓ‘c task hoΓ n chỉnh cΓ²n lαΊ‘i luΓ΄n được giα»―.
48
+ - Canonical instruction nα»‘i ordered tasks bαΊ±ng `; then`.
49
+ - Plan guard xΓ‘c minh mọi task xuαΊ₯t hiện Δ‘ΓΊng thα»© tα»±; thiαΊΏu bαΊ₯t kα»³ task nΓ o thΓ¬
50
+ reject trΖ°α»›c execution.
51
+ - Goal compiler hiện cΓ³ tα»± tαΊ‘o predicate cho mọi move/place trong sequence.
52
+
53
+ ## Kiểm tra
54
+
55
+ - Pending replacement cΓ³ task dời clamp vΓ  task Δ‘αΊ·t tennis ball trΓͺn soup can.
56
+ - Resolver follow-up cα»‘ tΓ¬nh chỉ trαΊ£ task clamp.
57
+ - XΓ‘c nhαΊ­n canonical goal vαΊ«n chα»©a Δ‘α»§ hai task.
58
+ - XΓ‘c nhαΊ­n plan sΓ‘u bΖ°α»›c được chαΊ₯p nhαΊ­n.
59
+ - XΓ‘c nhαΊ­n plan ba bΖ°α»›c chỉ dời clamp bα»‹ `plan_goal_mismatch`.
60
+ - Regression liΓͺn quan: **72 passed**.
61
+ - Python compile vΓ  `git diff --check` chαΊ‘y ở bΖ°α»›c xΓ‘c minh cuα»‘i.
62
+
63
+ ## BαΊ£o toΓ n
64
+
65
+ - KhΓ΄ng sα»­a `.env`, secrets, `.history` hoαΊ·c tα»‘c Δ‘α»™ robot.
66
+ - KhΓ΄ng sα»­a motion planner, Goal Predicate vΓ  scoring.
67
+ - Action schema pick/move/place giα»― nguyΓͺn.
68
+
69
+ ## VαΊ₯n đề cΓ²n lαΊ‘i
70
+
71
+ - CαΊ§n restart vΓ  thα»­ live OpenRouter để xΓ‘c nhαΊ­n model tuΓ’n thα»§ `tasks` ngay tα»« lượt
72
+ clarification Δ‘αΊ§u tiΓͺn.
73
+ - Composite task hiện tuαΊ§n tα»±; chΖ°a hα»— trợ parallel/conditional/loop.
development_logs/2026-07-04_11-07-56_improve-adaptive-dialogue-grounding.md ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CαΊ£i thiện adaptive dialogue grounding vΓ  schema repair
2
+
3
+ ## YΓͺu cαΊ§u
4
+
5
+ Sα»­a hα»™i thoαΊ‘i:
6
+
7
+ 1. người dΓΉng yΓͺu cαΊ§u Δ‘α»•i vα»‹ trΓ­ quαΊ£ bΓ³ng vΓ  quαΊ£ chuα»‘i;
8
+ 2. robot hỏi xÑc nhận quả bóng tennis;
9
+ 3. người dΓΉng trαΊ£ lời `Tennis vΓ  quαΊ£ chuα»‘i`;
10
+ 4. hệ thα»‘ng lαΊ‘i trαΊ£ cΓ’u hỏi chung vΓ¬ khΓ΄ng parse được Goal Resolution.
11
+
12
+ Mα»₯c tiΓͺu lΓ  kαΊΏt hợp chΓ­nh xΓ‘c lα»‹ch sα»­ hα»™i thoαΊ‘i theo cΓ‘ch adaptive.
13
+
14
+ ## NguyΓͺn nhΓ’n
15
+
16
+ - Goal Resolver chΖ°a được nhαΊ―c rΓ΅ rαΊ±ng alias chỉ khα»›p mα»™t object thΓ¬ khΓ΄ng mΖ‘ hα»“.
17
+ - Semantic catalog thiαΊΏu alias ngαΊ―n `tennis`.
18
+ - Alias catalog chΖ°a được tiền xα»­ lΓ½ thΓ nh grounding hints cho model.
19
+ - Khi provider trαΊ£ `content=None` hoαΊ·c JSON lệch schema, parser trαΊ£ `None` vΓ  hệ
20
+ thα»‘ng lαΊ­p tα»©c dΓΉng generic clarification.
21
+ - KhΓ΄ng cΓ³ repair turn giα»― nguyΓͺn pending partial intent vΓ  ordered tasks.
22
+
23
+ ## PhαΊ‘m vi
24
+
25
+ - CαΊ£i thiện Goal Resolution vΓ  conversation grounding.
26
+ - KhΓ΄ng thay Panda, A* 2D/U-trajectory, Goal Predicate hoαΊ·c scoring.
27
+ - KhΓ΄ng thay executor action primitives.
28
+
29
+ ## File sα»­a
30
+
31
+ - `envs/env1.semantics.json`
32
+ - `llm_panda/llm_agent.py`
33
+ - `tests/test_environment_semantics.py`
34
+ - `tests/test_conversation_memory.py`
35
+ - `docs/CONVERSATION_MEMORY_PLAN.md`
36
+ - ThΓͺm development log nΓ y.
37
+
38
+ ## HΓ nh vi sau
39
+
40
+ - `tennis` lΓ  alias data-driven cα»§a `tennis_ball`.
41
+ - TrΖ°α»›c Goal Resolution, hệ thα»‘ng quΓ©t alias/display names trong active semantic
42
+ catalog vΓ  gα»­i canonical grounding hints.
43
+ - Mα»™t mention chỉ khα»›p mα»™t current object được coi lΓ  resolved, khΓ΄ng hỏi xΓ‘c nhαΊ­n.
44
+ - Prompt yΓͺu cαΊ§u follow-up fragment Δ‘iền missing slots vΓ  khΓ΄ng bαΊ―t người dΓΉng nhαΊ―c
45
+ lαΊ‘i action/destination/relation Δ‘Γ£ biαΊΏt.
46
+ - Swap/replace/compound follow-up phαΊ£i trαΊ£ toΓ n bα»™ ordered tasks.
47
+ - Parser chαΊ₯p nhαΊ­n wrapper phα»• biαΊΏn, alias conversation mode, missing field dαΊ‘ng
48
+ string vΓ  ready response cΓ³ structured partial intent.
49
+ - Response rα»—ng/sai schema kΓ­ch hoαΊ‘t Δ‘ΓΊng mα»™t repair turn vα»›i nguyΓͺn conversation
50
+ context; chỉ sau khi repair vαΊ«n lα»—i mα»›i dΓΉng fallback clarification.
51
+
52
+ ## Kiểm tra
53
+
54
+ - `Tennis vΓ  quαΊ£ chuα»‘i` ground thΓ nh `tennis_ball` vΓ  `banana`, khΓ΄ng match `pear`.
55
+ - Fake provider trαΊ£ `content=None` ở lượt Δ‘αΊ§u vΓ  valid follow-up JSON ở repair turn.
56
+ - XΓ‘c nhαΊ­n repair giα»― `conversation_mode=follow_up` cΓΉng ordered tasks.
57
+ - Regression liΓͺn quan: **74 passed**.
58
+ - Python compile vΓ  `git diff --check` chαΊ‘y ở bΖ°α»›c xΓ‘c minh cuα»‘i.
59
+
60
+ ## BαΊ£o toΓ n
61
+
62
+ - KhΓ΄ng sα»­a `.env`, secrets, `.history` hoαΊ·c tα»‘c Δ‘α»™ robot.
63
+ - KhΓ΄ng sα»­a motion planner, Goal Predicate vΓ  scoring.
64
+ - Adaptive prompt vαΊ«n chỉ dΓΉng metadata cα»§a active environment.
65
+
66
+ ## VαΊ₯n đề cΓ²n lαΊ‘i
67
+
68
+ - Exact geometric swap vαΊ«n bα»‹ giα»›i hαΊ‘n bởi action/location primitives hiện tαΊ‘i; thay
69
+ Δ‘α»•i Δ‘Γ³ nαΊ±m ngoΓ i scope cα»§a bαΊ£n sα»­a conversation grounding nΓ y.
70
+ - Không mô hình LLM nào bảo đảm 100% semantic output; schema repair và deterministic
71
+ grounding giαΊ£m failure nhΖ°ng vαΊ«n cαΊ§n guardrails.
development_logs/2026-07-04_11-18-47_normalize-intent-object-surface-namespaces.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ChuαΊ©n hΓ³a namespace object/surface trong intent
2
+
3
+ ## YΓͺu cαΊ§u cα»§a người dΓΉng
4
+
5
+ Sα»­a triệt để lα»—i hệ thα»‘ng coi `table` lΓ  vαΊ­t tham chiαΊΏu, Δ‘α»“ng thời chuαΊ©n hΓ³a
6
+ intent theo hΖ°α»›ng tα»•ng quΓ‘t.
7
+
8
+ ## PhαΊ‘m vi vΓ  giαΊ£ Δ‘α»‹nh
9
+
10
+ - Chỉ thay Δ‘α»•i semantic boundary giα»―a Goal Resolution vΓ  planner.
11
+ - `destination` chỉ nhαΊ­n ID cα»§a surface trong scene.
12
+ - `relative_to` chỉ nhαΊ­n ID cα»§a manipulable object trong scene.
13
+ - `on_top_of + surface` cΓ³ cΓΉng Γ½ nghΔ©a vα»›i Δ‘αΊ·t trα»±c tiαΊΏp lΓͺn surface nΓͺn cΓ³
14
+ thể chuαΊ©n hΓ³a xΓ‘c Δ‘α»‹nh, khΓ΄ng cαΊ§n hỏi lαΊ‘i.
15
+ - Quan hệ Δ‘α»‹nh hΖ°α»›ng vα»›i surface nhΖ° `left_of(table)` khΓ΄ng cΓ³ reference frame
16
+ Δ‘α»§ rΓ΅ nΓͺn phαΊ£i fail-closed vΓ  yΓͺu cαΊ§u người dΓΉng chọn vαΊ­t tham chiαΊΏu.
17
+ - KhΓ΄ng thay Δ‘α»•i model Panda, A* 2D, U-trajectory, goal predicate, scoring,
18
+ executor hoαΊ·c cαΊ₯u hΓ¬nh tα»‘c Δ‘α»™.
19
+
20
+ ## File Δ‘Γ£ sα»­a
21
+
22
+ - `llm_panda/llm_agent.py`
23
+ - `tests/test_conversation_memory.py`
24
+
25
+ KhΓ΄ng thΓͺm, xΓ³a hoαΊ·c Δ‘α»•i tΓͺn tΓ­nh nΔƒng hiện cΓ³.
26
+
27
+ ## HΓ nh vi trΖ°α»›c vΓ  sau
28
+
29
+ ### TrΖ°α»›c
30
+
31
+ Intent `on_top_of(table)` giα»― `table` trong `relative_to`. Validator chỉ tΓ¬m
32
+ `relative_to` trong danh sΓ‘ch object nΓͺn bΓ‘o khΓ΄ng tΓ¬m thαΊ₯y vαΊ­t tham chiαΊΏu dΓΉ
33
+ `table` tα»“n tαΊ‘i trong danh sΓ‘ch surface.
34
+
35
+ ### Sau
36
+
37
+ - `on_top_of(table|surface khΓ‘c)` được chuαΊ©n hΓ³a thΓ nh
38
+ `destination=<surface>` và loẑi bỏ `relation/relative_to` thừa.
39
+ - Quy tαΊ―c Γ‘p dα»₯ng cho intent Δ‘Ζ‘n vΓ  tα»«ng task trong compound/sequence intent.
40
+ - `relative_to=<surface>` vα»›i quan hệ Δ‘α»‹nh hΖ°α»›ng khΓ΄ng được Γ’m thαΊ§m chuyển Δ‘α»•i;
41
+ validator trαΊ£ cΓ’u hỏi lΓ m rΓ΅ Δ‘ΓΊng kiểu dα»― liệu.
42
+ - `relative_to` cΓ³ object nhΖ°ng thiαΊΏu relation cΕ©ng được phΓ‘t hiện trΖ°α»›c planner.
43
+ - Danh sΓ‘ch surface được lαΊ₯y tα»« scene hiện hΓ nh, khΓ΄ng gαΊ―n riΓͺng vα»›i `env1`.
44
+
45
+ ## Kiểm tra vΓ  kαΊΏt quαΊ£
46
+
47
+ - `python -m py_compile llm_panda\llm_agent.py`
48
+ - ThΓ nh cΓ΄ng.
49
+ - `python -m pytest tests\test_conversation_memory.py tests\test_environment_semantics.py -q`
50
+ - `40 passed`.
51
+ - `python -m pytest tests\test_conversation_memory.py tests\test_environment_semantics.py tests\test_monitor.py tests\test_obstacle_graph.py tests\test_occupancy.py tests\test_cost_map.py -q`
52
+ - `77 passed`.
53
+ - `git diff --check`
54
+ - ThΓ nh cΓ΄ng; chỉ cΓ³ cαΊ£nh bΓ‘o LF/CRLF Δ‘Γ£ tα»“n tαΊ‘i trong working tree.
55
+
56
+ ## BαΊ£o toΓ n hΓ nh vi hiện cΓ³
57
+
58
+ - KhΓ΄ng sα»­a `.env`, scene geometry, semantic catalog, frontend hay executor.
59
+ - KhΓ΄ng Δ‘α»₯ng tα»›i cΓ‘c thay Δ‘α»•i local khΓ΄ng liΓͺn quan.
60
+ - Quan hệ object-to-object nhΖ° `pear on_top_of chips_can` giα»― nguyΓͺn.
61
+ - Destination surface hợp lệ nhΖ° `table` vΓ  `tray` giα»― nguyΓͺn.
62
+
63
+ ## VαΊ₯n đề cΓ²n lαΊ‘i
64
+
65
+ - Lệnh hoΓ‘n Δ‘α»•i β€œΔ‘ΓΊng tọa Δ‘α»™ cũ” vαΊ«n phα»₯ thuα»™c primitive biểu diα»…n vα»‹ trΓ­ hiện
66
+ cΓ³. Thay Δ‘α»•i nΓ y chỉ bαΊ£o Δ‘αΊ£m intent khΓ΄ng nhαΊ§m namespace vΓ  khΓ΄ng bα»‹ chαΊ·n sai.
development_logs/2026-07-04_11-35-55_separate-user-constraints-from-intermediate-planning.md ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TΓ‘ch rΓ ng buα»™c người dΓΉng khỏi bΖ°α»›c lαΊ­p kαΊΏ hoαΊ‘ch trung gian
2
+
3
+ ## YΓͺu cαΊ§u cα»§a người dΓΉng
4
+
5
+ Chỉ xΓ©t quan hệ khΓ΄ng gian khi người dΓΉng thα»±c sα»± yΓͺu cαΊ§u. Vα»›i task dΓ i, cΓ‘c
6
+ giai Δ‘oαΊ‘n trung gian khΓ΄ng cΓ³ rΓ ng buα»™c phαΊ£i được hệ thα»‘ng tα»± lαΊ­p kαΊΏ hoαΊ‘ch an
7
+ toàn, không hỏi người dùng những chi tiết không cần thiết.
8
+
9
+ ## PhαΊ‘m vi vΓ  giαΊ£ Δ‘α»‹nh
10
+
11
+ - Giα»― nguyΓͺn model Panda, A* 2D, U-trajectory, goal predicate, scoring vΓ 
12
+ execution primitive hiện tαΊ‘i.
13
+ - KhΓ΄ng thay Δ‘α»•i `.env`, scene geometry hoαΊ·c semantic catalog.
14
+ - Thay Δ‘α»•i nαΊ±m ở prompt, intent normalization, plan/intent matching vΓ  bΖ°α»›c
15
+ biΓͺn dα»‹ch resolved goal.
16
+ - BαΊ£o toΓ n tΖ°Ζ‘ng thΓ­ch vα»›i intent cΕ© chΖ°a cΓ³ provenance.
17
+
18
+ ## File Δ‘Γ£ sα»­a
19
+
20
+ - `llm_panda/llm_agent.py`
21
+ - `tests/test_conversation_memory.py`
22
+ - `docs/CONVERSATION_MEMORY_PLAN.md`
23
+
24
+ KhΓ΄ng xΓ³a hoαΊ·c Δ‘α»•i tΓͺn file/tΓ­nh nΔƒng.
25
+
26
+ ## HΓ nh vi trΖ°α»›c vΓ  sau
27
+
28
+ ### TrΖ°α»›c
29
+
30
+ - Relation rời nhΖ° `relation=on_top_of, relative_to=null` bα»‹ coi lΓ  constraint
31
+ bαΊ―t buα»™c vΓ  hệ thα»‘ng hỏi vαΊ­t tham chiαΊΏu dΓΉ người dΓΉng chỉ chọn khay.
32
+ - Mọi bΖ°α»›c trong execution plan cΓ³ thể được biΓͺn dα»‹ch thΓ nh Goal Predicate,
33
+ kể cαΊ£ bΖ°α»›c dời tαΊ‘m.
34
+ - Mα»™t bΖ°α»›c trung gian thiαΊΏu destination cΓ³ thể gΓ’y clarification khΓ΄ng cαΊ§n thiαΊΏt.
35
+
36
+ ### Sau
37
+
38
+ - `relation`/`relative_to` lΓ  cαΊ·p nguyΓͺn tα»­ vΓ  cΓ³ provenance
39
+ `constraint_sources`.
40
+ - Relation rời khΓ΄ng cΓ³ nguα»“n tα»« người dΓΉng/context được loαΊ‘i bỏ.
41
+ - Relation được người dΓΉng yΓͺu cαΊ§u nhΖ°ng thiαΊΏu reference vαΊ«n fail-closed vΓ  hỏi
42
+ Δ‘ΓΊng thΓ΄ng tin.
43
+ - Task `purpose=intermediate` tự dùng `placement_policy=auto_safe`; planner chọn
44
+ vα»‹ trΓ­ an toΓ n tα»« scene.
45
+ - Intent/plan matcher chαΊ₯p nhαΊ­n bαΊ₯t kα»³ destination hợp lệ cho bΖ°α»›c auto-safe.
46
+ - Goal Check chỉ nhαΊ­n predicate tα»« task mα»₯c tiΓͺu; intermediate task khΓ΄ng trở
47
+ thΓ nh Δ‘iều kiện hoΓ n thΓ nh.
48
+ - Prompt cαΊ₯m LLM tα»± thΓͺm quan hệ cho lệnh chỉ nΓͺu surface.
49
+
50
+ ## Kiểm tra vΓ  kαΊΏt quαΊ£
51
+
52
+ - `python -m py_compile llm_panda\llm_agent.py`
53
+ - ThΓ nh cΓ΄ng.
54
+ - `python -m pytest tests\test_conversation_memory.py tests\test_environment_semantics.py -q`
55
+ - `44 passed`.
56
+ - `python -m pytest tests\test_conversation_memory.py tests\test_environment_semantics.py tests\test_monitor.py tests\test_obstacle_graph.py tests\test_occupancy.py tests\test_cost_map.py -q`
57
+ - `81 passed`.
58
+ - Hα»“i quy mở rα»™ng ban Δ‘αΊ§u:
59
+ - `106 passed`, `1 failed`.
60
+ - Lα»—i duy nhαΊ₯t tαΊ‘i `tests/test_pipeline.py::test_grasp_survives_fast_translation`:
61
+ fixture `PandaApp` khΓ΄ng cΓ³ thuα»™c tΓ­nh `grasp_planner`.
62
+ - Lα»—i khΓ΄ng Δ‘i qua code intent vα»«a sα»­a vΓ  thuα»™c thay Δ‘α»•i local cΓ³ sαΊ΅n trong
63
+ `main.py`; khΓ΄ng tα»± Γ½ sα»­a ngoΓ i phαΊ‘m vi.
64
+ - `git diff --check`
65
+ - ThΓ nh cΓ΄ng; chỉ cΓ³ cαΊ£nh bΓ‘o LF/CRLF cα»§a working tree.
66
+
67
+ ## TΓ­nh nΔƒng hiện cΓ³ được bαΊ£o toΓ n
68
+
69
+ - Object-to-object relation hợp lệ vαΊ«n giα»― nguyΓͺn.
70
+ - Surface destination khΓ΄ng relation vαΊ«n giα»― nguyΓͺn.
71
+ - Explicit relation thiαΊΏu reference vαΊ«n yΓͺu cαΊ§u lΓ m rΓ΅.
72
+ - Blocker clearing, safety guardrail vΓ  executor vαΊ«n hoαΊ‘t Δ‘α»™ng theo luα»“ng cΕ©.
73
+ - KhΓ΄ng ghi Δ‘Γ¨ hoαΊ·c hoΓ n tΓ‘c thay Δ‘α»•i local khΓ‘c.
74
+
75
+ ## VαΊ₯n đề cΓ²n lαΊ‘i
76
+
77
+ - Primitive hiện tαΊ‘i biểu diα»…n β€œvα»‹ trΓ­ cũ” ở mα»©c semantic surface/support, chΖ°a
78
+ cΓ³ predicate tọa Δ‘α»™ riΓͺng. Việc mở rα»™ng exact-pose goal sαΊ½ thay Δ‘α»•i scope goal
79
+ predicate nΓͺn chΖ°a thα»±c hiện.
80
+ - Test pipeline nΓͺu trΓͺn cαΊ§n được xα»­ lΓ½ riΓͺng nαΊΏu người dΓΉng yΓͺu cαΊ§u sα»­a fixture
81
+ hoαΊ·c khΓ΄i phα»₯c API `PandaApp.grasp_planner`.
development_logs/2026-07-04_11-59-33_implement-swap-former-location-anchors.md ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Triển khai former-location anchor cho thao tΓ‘c hoΓ‘n Δ‘α»•i
2
+
3
+ ## YΓͺu cαΊ§u cα»§a người dΓΉng
4
+
5
+ Sα»­a thao tΓ‘c hoΓ‘n Δ‘α»•i để hai vαΊ­t được Δ‘αΊ·t vΓ o vα»‹ trΓ­ ban Δ‘αΊ§u cα»§a nhau trΓͺn
6
+ surface, thay vΓ¬ chỉ Δ‘αΊ·t cαΊ£ hai vΓ o mα»™t vα»‹ trΓ­ bαΊ₯t kα»³ trΓͺn bΓ n.
7
+
8
+ ## PhαΊ‘m vi vΓ  giαΊ£ Δ‘α»‹nh
9
+
10
+ - LLM chỉ xΓ‘c Δ‘α»‹nh semantic intent: vαΊ­t nΓ o phαΊ£i Δ‘αΊΏn vα»‹ trΓ­ cΕ© cα»§a vαΊ­t nΓ o.
11
+ - Tọa Δ‘α»™ khΓ΄ng do LLM sinh; hệ thα»‘ng snapshot tα»« scene state ban Δ‘αΊ§u.
12
+ - Giα»― nguyΓͺn Panda, A*, U-trajectory vΓ  scoring hiện cΓ³. Chỉ bα»• sung preferred
13
+ position vΓ o scoring free-space.
14
+ - Mở rα»™ng Goal Predicate theo hΖ°α»›ng tΖ°Ζ‘ng thΓ­ch ngược bαΊ±ng `position_near`;
15
+ cΓ‘c predicate cΕ© khΓ΄ng Δ‘α»•i.
16
+ - NαΊΏu anchor chΓ­nh xΓ‘c khΓ΄ng cΓ²n an toΓ n/khαΊ£ dα»₯ng, optimiser chọn Δ‘iểm hợp lệ
17
+ gαΊ§n nhαΊ₯t thay vΓ¬ bỏ qua collision/reachability.
18
+
19
+ ## File Δ‘Γ£ sα»­a
20
+
21
+ - `llm_panda/llm_agent.py`
22
+ - `llm_panda/conversation/models.py`
23
+ - `llm_panda/execution/pipeline.py`
24
+ - `llm_panda/execution/monitor.py`
25
+ - `llm_panda/scene_manager.py`
26
+ - `tests/test_conversation_memory.py`
27
+ - `tests/test_monitor.py`
28
+ - `tests/test_occupancy.py`
29
+ - `docs/CONVERSATION_MEMORY_PLAN.md`
30
+
31
+ KhΓ΄ng xΓ³a hoαΊ·c Δ‘α»•i tΓͺn file/tΓ­nh nΔƒng.
32
+
33
+ ## HΓ nh vi trΖ°α»›c vΓ  sau
34
+
35
+ ### TrΖ°α»›c
36
+
37
+ - Swap được hαΊ‘ xuα»‘ng hai goal `location_is(table)`.
38
+ - Executor chọn hai free spot thΓ΄ng thường trΓͺn bΓ n.
39
+ - Goal Check bΓ‘o thΓ nh cΓ΄ng chỉ vΓ¬ cαΊ£ hai vαΊ­t vαΊ«n ở `table`.
40
+
41
+ ### Sau
42
+
43
+ - Goal Resolution được hΖ°α»›ng dαΊ«n biểu diα»…n swap bαΊ±ng:
44
+ - mα»™t task tαΊ‘m `auto_safe`;
45
+ - hai task `former_location` neo vΓ o hai object ban Δ‘αΊ§u.
46
+ - Intent layer lαΊ₯y position cα»§a anchor tα»« initial scene snapshot.
47
+ - Matching `move_to` nhαΊ­n `target_position` vΓ  `placement_anchor` nα»™i bα»™.
48
+ - Surface được suy ra tα»« vα»‹ trΓ­ ban Δ‘αΊ§u cα»§a anchor nαΊΏu LLM khΓ΄ng lαΊ·p lαΊ‘i.
49
+ - Placement optimiser Ζ°u tiΓͺn free/reachable spot gαΊ§n anchor nhαΊ₯t.
50
+ - Goal Check tαΊ‘o hai predicate `position_near`, mαΊ·c Δ‘α»‹nh tolerance 4 cm.
51
+ - Output cΕ© dΓΉng free-text `details="... original/former location ..."` được
52
+ migrate best-effort sang schema mα»›i.
53
+
54
+ ## Kiểm tra vΓ  kαΊΏt quαΊ£
55
+
56
+ - `python -m py_compile llm_panda\llm_agent.py llm_panda\conversation\models.py llm_panda\execution\monitor.py llm_panda\execution\pipeline.py llm_panda\scene_manager.py`
57
+ - ThΓ nh cΓ΄ng.
58
+ - `python -m pytest tests\test_conversation_memory.py tests\test_monitor.py tests\test_occupancy.py -q`
59
+ - `63 passed` sau khi bα»• sung test cuα»‘i.
60
+ - `python -m pytest tests\test_conversation_memory.py tests\test_environment_semantics.py tests\test_monitor.py tests\test_obstacle_graph.py tests\test_occupancy.py tests\test_cost_map.py -q`
61
+ - `86 passed`.
62
+ - `git diff --check`
63
+ - ThΓ nh cΓ΄ng; chỉ cΓ³ cαΊ£nh bΓ‘o LF/CRLF cα»§a working tree.
64
+
65
+ ## TΓ­nh nΔƒng hiện cΓ³ được bαΊ£o toΓ n
66
+
67
+ - Placement khΓ΄ng cΓ³ anchor vαΊ«n dΓΉng scoring cΕ©.
68
+ - Relation object-to-object, table/tray placement vΓ  blocker clearing giα»― nguyΓͺn.
69
+ - A* vΓ  U-trajectory vαΊ«n nhαΊ­n target cuα»‘i theo luα»“ng cΕ©.
70
+ - KhΓ΄ng thay Δ‘α»•i `.env`, semantic catalog hoαΊ·c thay Δ‘α»•i local ngoΓ i phαΊ‘m vi.
71
+
72
+ ## VαΊ₯n đề cΓ²n lαΊ‘i
73
+
74
+ - Tolerance hiện lΓ  4 cm để hαΊ₯p thα»₯ sai sα»‘ raster/physics. CΓ³ thể cαΊ₯u hΓ¬nh hΓ³a
75
+ sau nαΊΏu benchmark cho thαΊ₯y cαΊ§n Δ‘α»™ chΓ­nh xΓ‘c khΓ‘c.
76
+ - Test pipeline cΕ© `test_grasp_survives_fast_translation` vαΊ«n cΓ³ lα»—i ngoΓ i phαΊ‘m
77
+ vi do `PandaApp` khΓ΄ng cΓ³ `grasp_planner`; khΓ΄ng tα»± Γ½ sα»­a trong thay Δ‘α»•i nΓ y.
development_logs/2026-07-04_13-42-09_implement-reload-persistence-and-live-interrupt.md ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Triển khai reload persistence vΓ  live interrupt/re-plan
2
+
3
+ ## YΓͺu cαΊ§u cα»§a người dΓΉng
4
+
5
+ - Reload trang web khΓ΄ng reset trαΊ‘ng thΓ‘i; giα»― mọi thα»© Δ‘ang diα»…n ra.
6
+ - Cho phΓ©p gα»­i prompt trong lΓΊc robot thα»±c thi; robot dα»«ng ngay theo cΖ‘ chαΊΏ an
7
+ toΓ n, giα»― live state rα»“i lαΊ­p kαΊΏ hoαΊ‘ch mα»›i tα»« state Δ‘Γ³.
8
+ - Thα»±c hiện Δ‘αΊ§y Δ‘α»§ cΓ‘c phase Δ‘Γ£ lαΊ­p kαΊΏ hoαΊ‘ch.
9
+
10
+ ## PhαΊ‘m vi vΓ  giαΊ£ Δ‘α»‹nh
11
+
12
+ - Persistence Γ‘p dα»₯ng cho browser reload/WebSocket reconnect trong cΓΉng process
13
+ server, khΓ΄ng phαΊ£i restart backend.
14
+ - Giα»― mα»™t shared simulation nhΖ° kiαΊΏn trΓΊc `current_sim` hiện tαΊ‘i.
15
+ - Cooperative cancellation, khΓ΄ng kill thread.
16
+ - KhΓ΄ng thay Δ‘α»•i Panda model, A*, U-trajectory, cost scoring, environment semantic
17
+ catalog hoαΊ·c tα»‘c Δ‘α»™ robot.
18
+ - CΓ‘c thay Δ‘α»•i local cΓ³ sαΊ΅n được bαΊ£o toΓ n.
19
+
20
+ ## File Δ‘Γ£ thΓͺm
21
+
22
+ - `frontend/web_runtime.py`
23
+ - `llm_panda/execution/cancellation.py`
24
+ - `tests/test_web_runtime.py`
25
+ - `docs/WEB_RUNTIME_INTERRUPTION_PLAN.md`
26
+ - `development_logs/2026-07-04_13-42-09_implement-reload-persistence-and-live-interrupt.md`
27
+
28
+ ## File Δ‘Γ£ sα»­a
29
+
30
+ - `frontend/interactive_server.py`
31
+ - `frontend/app.js`
32
+ - `llm_panda/execution/pipeline.py`
33
+ - `llm_panda/robot_controller.py`
34
+ - `tests/test_monitor.py`
35
+
36
+ KhΓ΄ng xΓ³a hoαΊ·c Δ‘α»•i tΓͺn file.
37
+
38
+ ## HΓ nh vi trΖ°α»›c vΓ  sau
39
+
40
+ ### TrΖ°α»›c
41
+
42
+ - Mα»—i WebSocket mα»›i reset object vΓ  Δ‘Ζ°a robot về home.
43
+ - ConversationManager thuα»™c connection vΓ  bα»‹ xΓ³a khi disconnect.
44
+ - Pipeline gα»­i thαΊ³ng vΓ o socket cΕ© nΓͺn reload mαΊ₯t log/plan/result.
45
+ - Frontend khΓ³a input khi robot chαΊ‘y.
46
+ - KhΓ΄ng cΓ³ cancellation token; nhiều run cΓ³ thể cαΊ‘nh tranh simulation.
47
+
48
+ ### Sau
49
+
50
+ - Server-owned runtime sα»‘ng qua reconnect vΓ  broadcast Δ‘αΊΏn subscriber hiện tαΊ‘i.
51
+ - Reconnect khΓ΄ng reset scene; nhαΊ­n init cache, latest physical state vΓ  runtime
52
+ snapshot.
53
+ - Conversation, event journal, plan, result vΓ  task lifecycle được giα»―.
54
+ - Input luΓ΄n nhαΊ­n prompt; prompt mα»›i interrupt task cΕ© vΓ  dΓΉng latest-wins.
55
+ - Mα»™t command worker duy nhαΊ₯t serialize quyền Δ‘iều khiển robot.
56
+ - Cancellation checkpoint hoαΊ‘t Δ‘α»™ng giα»―a steps vΓ  trong motion loops.
57
+ - Safe hold giα»― joint pose vΓ  grasp constraint; khΓ΄ng tα»± home/recover khi
58
+ interrupted.
59
+ - LLM response/task event cΕ© bα»‹ chαΊ·n bαΊ±ng generation.
60
+ - Reset/change-env lΓ  transactional: cancel-all, chờ stop acknowledgement rα»“i
61
+ mα»›i mutate scene.
62
+ - Manual pose controls bα»‹ khΓ³a khi active task Δ‘ang chαΊ‘y.
63
+
64
+ ## Kiểm tra vΓ  kαΊΏt quαΊ£
65
+
66
+ - `node --check frontend\app.js`
67
+ - ThΓ nh cΓ΄ng.
68
+ - `python -m py_compile frontend\interactive_server.py frontend\web_runtime.py llm_panda\execution\cancellation.py llm_panda\execution\pipeline.py llm_panda\robot_controller.py`
69
+ - ThΓ nh cΓ΄ng.
70
+ - `python -m pytest tests\test_web_runtime.py tests\test_monitor.py -q`
71
+ - `17 passed` sau test hardening cuα»‘i.
72
+ - Regression liΓͺn quan:
73
+ - `96 passed`.
74
+ - ToΓ n bα»™ suite:
75
+ - `141 passed`, `3 skipped`, `13 failed`.
76
+ - 10 failure lΓ  test RemoteLLM gọi OpenRouter nhΖ°ng network bα»‹ sandbox chαΊ·n.
77
+ - 2 failure cΓ³ sαΊ΅n do `PandaApp` thiαΊΏu `grasp_planner`.
78
+ - 1 failure cΓ³ sαΊ΅n do `config.YCB_CATALOG` khΓ΄ng tα»“n tαΊ‘i.
79
+ - KhΓ΄ng failure nΓ o Δ‘i qua runtime/cancellation mα»›i.
80
+ - `git diff --check`
81
+ - ThΓ nh cΓ΄ng; chỉ cΓ³ cαΊ£nh bΓ‘o LF/CRLF cα»§a working tree.
82
+
83
+ ## TΓ­nh nΔƒng hiện cΓ³ được bαΊ£o toΓ n
84
+
85
+ - CLI/GUI khΓ΄ng truyền cancellation token nΓͺn giα»― luα»“ng cΕ©.
86
+ - Grasp/release vαΊ«n atomic; interrupt khΓ΄ng thΓ‘o constraint.
87
+ - Explicit reset vΓ  change environment vαΊ«n tα»“n tαΊ‘i.
88
+ - Web drag/manual controls vαΊ«n hoαΊ‘t Δ‘α»™ng khi runtime idle.
89
+ - Goal resolution, conversation memory, swap anchor vΓ  goal check giα»― nguyΓͺn.
90
+
91
+ ## VαΊ₯n đề cΓ²n lαΊ‘i
92
+
93
+ - ChΖ°a checkpoint PyBullet xuα»‘ng disk để phα»₯c hα»“i sau backend restart.
94
+ - Shared runtime chưa tÑch simulation theo nhiều người dùng.
95
+ - CΓ‘c failure toΓ n-suite nΓͺu trΓͺn cαΊ§n yΓͺu cαΊ§u riΓͺng nαΊΏu muα»‘n xα»­ lΓ½.
96
+
development_logs/2026-07-04_13-56-53_add-live-command-stop-button.md ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ThΓͺm nΓΊt gα»­i/dα»«ng lệnh trong lΓΊc robot thα»±c thi
2
+
3
+ ## YΓͺu cαΊ§u cα»§a người dΓΉng
4
+
5
+ Sau khi gα»­i lệnh, nΓΊt gα»­i chuyển thΓ nh icon Δ‘ang thα»±c thi giα»‘ng Codex. Người
6
+ dΓΉng vαΊ«n nhαΊ­p được lệnh mα»›i; click nΓΊt để dα»«ng task hiện tαΊ‘i hoαΊ·c nhαΊ₯n Enter để
7
+ dα»«ng vΓ  gα»­i lệnh mα»›i.
8
+
9
+ ## PhαΊ‘m vi vΓ  giαΊ£ Δ‘α»‹nh
10
+
11
+ - TαΊ­n dα»₯ng WebRuntime/cancellation protocol Δ‘Γ£ cΓ³ (`run` vΓ  `cancel`).
12
+ - Chỉ thay Δ‘α»•i UX frontend vΓ  test contract, khΓ΄ng sα»­a robot, planner, trajectory
13
+ hoαΊ·c semantic behavior.
14
+ - Click nΓΊt khi busy luΓ΄n cΓ³ nghΔ©a lΓ  cancel; Enter trong chat input vα»›i nα»™i
15
+ dung cΓ³ nghΔ©a lΓ  interrupt-and-send.
16
+
17
+ ## File Δ‘Γ£ sα»­a
18
+
19
+ - `frontend/app.js`
20
+ - `frontend/index.css`
21
+ - `docs/WEB_RUNTIME_INTERRUPTION_PLAN.md`
22
+
23
+ ## File Δ‘Γ£ thΓͺm
24
+
25
+ - `tests/test_web_command_button.py`
26
+ - `development_logs/2026-07-04_13-56-53_add-live-command-stop-button.md`
27
+
28
+ KhΓ΄ng xΓ³a hoαΊ·c Δ‘α»•i tΓͺn file.
29
+
30
+ ## HΓ nh vi trΖ°α»›c vΓ  sau
31
+
32
+ ### TrΖ°α»›c
33
+
34
+ - NΓΊt vαΊ«n hiển thα»‹ icon gα»­i trong lΓΊc task chαΊ‘y.
35
+ - KhΓ΄ng cΓ³ thao tΓ‘c click rΓ΅ rΓ ng để gα»­i `cancel`.
36
+ - Enter vΓ  click dΓΉng cΓΉng submit path nΓͺn chΖ°a phΓ’n biệt stop vα»›i replacement
37
+ command.
38
+
39
+ ### Sau
40
+
41
+ - Busy state hiển thα»‹ stop square vΓ  spinner.
42
+ - Chat input vΓ  submit button khΓ΄ng bα»‹ disable.
43
+ - Click stop gα»­i `{"type":"cancel"}` vΓ  giα»― nα»™i dung Δ‘ang gΓ΅.
44
+ - Enter tα»« chat input gα»­i `{"type":"run"}`; backend interrupt task cΕ© vΓ  chαΊ‘y
45
+ command mα»›i.
46
+ - Stale `interrupted` event khΓ΄ng lΓ m nΓΊt task mα»›i quay lαΊ‘i mode gα»­i.
47
+ - Runtime snapshot khΓ΄i phα»₯c Δ‘ΓΊng mode gα»­i/dα»«ng sau reload.
48
+ - Button cΓ³ title/ARIA tΖ°Ζ‘ng α»©ng.
49
+
50
+ ## Kiểm tra vΓ  kαΊΏt quαΊ£
51
+
52
+ - `node --check frontend\app.js`
53
+ - ThΓ nh cΓ΄ng.
54
+ - `python -m pytest tests\test_web_command_button.py tests\test_web_runtime.py -q`
55
+ - `11 passed`.
56
+ - `python -m pytest tests\test_web_command_button.py tests\test_web_runtime.py tests\test_monitor.py -q`
57
+ - `20 passed`.
58
+ - `git diff --check`
59
+ - ThΓ nh cΓ΄ng; chỉ cΓ³ cαΊ£nh bΓ‘o LF/CRLF cα»§a working tree.
60
+
61
+ ## TΓ­nh nΔƒng hiện cΓ³ được bαΊ£o toΓ n
62
+
63
+ - Gα»­i lệnh lΓΊc idle vαΊ«n dΓΉng form submit cΕ©.
64
+ - Reset button, microphone, autocomplete vΓ  preset command khΓ΄ng bα»‹ xΓ³a.
65
+ - Backend cancellation, latest-wins vΓ  live-state re-plan giα»― nguyΓͺn.
66
+ - KhΓ΄ng thay Δ‘α»•i cΓ‘c local edit ngoΓ i phαΊ‘m vi.
67
+
68
+ ## VαΊ₯n đề cΓ²n lαΊ‘i
69
+
70
+ - CαΊ§n restart backend vΓ  hard-refresh browser để chαΊ―c chαΊ―n JavaScript/CSS mα»›i
71
+ khΓ΄ng bα»‹ cache.
development_logs/2026-07-04_17-10-44_restore-web-runtime-and-live-command-ui.md ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # KhΓ΄i phα»₯c web runtime vΓ  giao diện lệnh trα»±c tiαΊΏp
2
+
3
+ ## YΓͺu cαΊ§u cα»§a người dΓΉng
4
+
5
+ KhΓ΄i phα»₯c trαΊ‘ng thΓ‘i mα»›i nhαΊ₯t cα»§a cΓ‘c tΓ­nh nΔƒng Δ‘Γ£ phΓ‘t triển trΖ°α»›c Δ‘Γ³ sau khi mα»™t
6
+ agent khΓ‘c hoΓ n tΓ‘c hoαΊ·c ghi Δ‘Γ¨ cΓ‘c file frontend.
7
+
8
+ ## PhαΊ‘m vi vΓ  giαΊ£ Δ‘α»‹nh
9
+
10
+ - Đối chiαΊΏu working tree vα»›i cΓ‘c development log vΓ  test hợp Δ‘α»“ng Δ‘Γ£ tα»“n tαΊ‘i.
11
+ - KhΓ΄i phα»₯c phαΊ§n bα»‹ mαΊ₯t: runtime sα»‘ng qua reload, conversation sα»‘ng qua reconnect,
12
+ worker thα»±c thi tuαΊ§n tα»±, interrupt/re-plan tα»« live state vΓ  nΓΊt gα»­i/dα»«ng.
13
+ - KhΓ΄ng Δ‘Ζ°a phαΊ§n kΓ©o-thαΊ£ web Δ‘ang lΓ m dở sau Δ‘Γ³ vΓ o bαΊ£n khΓ΄i phα»₯c.
14
+ - KhΓ΄ng ghi Δ‘Γ¨ cΓ‘c thay Δ‘α»•i local ngoΓ i phαΊ‘m vi.
15
+ - `main.py` vΓ  `llm_panda/config.py` sαΊ‘ch so vα»›i commit hiện tαΊ‘i nΓͺn chỉ được kiểm
16
+ tra, khΓ΄ng sα»­a.
17
+
18
+ ## File Δ‘Γ£ sα»­a
19
+
20
+ - `frontend/interactive_server.py`
21
+ - `frontend/app.js`
22
+ - `frontend/index.css`
23
+ - `frontend/index.html`
24
+
25
+ KhΓ΄ng thΓͺm hoαΊ·c xΓ³a file chα»©c nΔƒng. File hiện tαΊ‘i lΓ  development log duy nhαΊ₯t được
26
+ thΓͺm trong lαΊ§n thα»±c thi nΓ y.
27
+
28
+ ## HΓ nh vi trΖ°α»›c vΓ  sau
29
+
30
+ ### TrΖ°α»›c
31
+
32
+ - Mα»—i WebSocket reconnect reset object vΓ  robot về home.
33
+ - Pipeline gα»­i sα»± kiện vΓ o socket cΕ©; reload lΓ m mαΊ₯t task/log/plan/result.
34
+ - Conversation manager khΓ΄ng được nα»‘i vΓ o server-owned runtime.
35
+ - CΓ‘c lệnh cΓ³ thể chαΊ‘y bαΊ±ng thread riΓͺng vΓ  tranh chαΊ₯p simulation.
36
+ - Frontend khΓ³a input khi task chαΊ‘y vΓ  khΓ΄ng cΓ³ nΓΊt dα»«ng.
37
+ - Asset quay về `app.js?v=25` và `index.css?v=8`.
38
+
39
+ ### Sau
40
+
41
+ - Reload/reconnect giα»― nguyΓͺn PyBullet state, conversation, log, plan, result vΓ 
42
+ vΓ²ng đời task trong cΓΉng backend process.
43
+ - Mα»™t command worker serialize quyền Δ‘iều khiển robot.
44
+ - Prompt mα»›i yΓͺu cαΊ§u dα»«ng task cΕ© vΓ  task mα»›i bαΊ―t Δ‘αΊ§u tα»« live state; cancel giα»―
45
+ robot ở pose an toàn.
46
+ - Runtime event cΓ³ generation để frontend bỏ qua kαΊΏt quαΊ£ cΕ©.
47
+ - Reset vΓ  Δ‘α»•i mΓ΄i trường chờ task dα»«ng rα»“i mα»›i mutate scene.
48
+ - Input vαΊ«n dΓΉng được khi robot chαΊ‘y; click nΓΊt busy để dα»«ng, Enter để gα»­i lệnh
49
+ thay thαΊΏ.
50
+ - NΓΊt busy hiển thα»‹ stop square vΓ  spinner.
51
+ - Asset được cache-bust bαΊ±ng `app.js?v=26` vΓ  `index.css?v=9`; HTML dΓΉng no-cache.
52
+
53
+ ## Lệnh kiểm tra vΓ  kαΊΏt quαΊ£
54
+
55
+ - `node --check frontend\app.js`
56
+ - ThΓ nh cΓ΄ng.
57
+ - Python 3.10 `-m py_compile` cho server/runtime/cancellation/pipeline/controller
58
+ - ThΓ nh cΓ΄ng.
59
+ - Python 3.10 `-m pytest tests\test_web_command_button.py tests\test_web_runtime.py tests\test_monitor.py -q`
60
+ - `21 passed`.
61
+ - `git diff --check`
62
+ - ThΓ nh cΓ΄ng; chỉ cΓ³ cαΊ£nh bΓ‘o chuyển Δ‘α»•i LF/CRLF cα»§a working tree.
63
+
64
+ ## TΓ­nh nΔƒng hiện cΓ³ được bαΊ£o toΓ n
65
+
66
+ - Conversation memory, semantic catalog, goal resolution/check, former-location
67
+ swap, A*, U-trajectory vΓ  robot model khΓ΄ng bα»‹ sα»­a.
68
+ - Manual drag/pose controls hiện cΓ³ vαΊ«n hoαΊ‘t Δ‘α»™ng khi runtime idle.
69
+ - Reset scene, Δ‘α»•i environment, microphone, autocomplete vΓ  lα»‹ch sα»­ UI vαΊ«n cΓ²n.
70
+ - `llm_panda/robot_controller.py` vαΊ«n giα»― `time_scale = 0.1`.
71
+ - CΓ‘c thay Δ‘α»•i local ngoΓ i bα»‘n file frontend khΓ΄ng bα»‹ dọn dαΊΉp hoαΊ·c hoΓ n tΓ‘c.
72
+
73
+ ## VαΊ₯n đề cΓ²n lαΊ‘i hoαΊ·c cαΊ§n người dΓΉng quyαΊΏt Δ‘α»‹nh
74
+
75
+ - Persistence chỉ sα»‘ng qua browser reload/WebSocket reconnect trong cΓΉng backend
76
+ process; restart backend chΖ°a cΓ³ checkpoint PyBullet xuα»‘ng disk.
77
+ - ChΖ°a chαΊ‘y kiểm thα»­ thao tΓ‘c thαΊ­t trong browser ở lαΊ§n nΓ y; cΓ‘c kiểm tra tα»± Δ‘α»™ng,
78
+ cΓΊ phΓ‘p vΓ  hợp Δ‘α»“ng runtime đều Δ‘Γ£ qua.
development_logs/2026-07-04_17-21-10_restore-context-goal-and-clarification-behavior.md ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # KhΓ΄i phα»₯c context goal vΓ  hΓ nh vi clarification
2
+
3
+ ## YΓͺu cαΊ§u cα»§a người dΓΉng
4
+
5
+ KhΓ΄i phα»₯c cΓ‘c tΓ­nh nΔƒng cΓ²n bα»‹ thay Δ‘α»•i hoαΊ·c loαΊ‘i bỏ sau khi Δ‘α»‘i chiαΊΏu code hiện
6
+ tαΊ‘i vα»›i docs vΓ  development log trΖ°α»›c Δ‘Γ³.
7
+
8
+ ## PhαΊ‘m vi vΓ  giαΊ£ Δ‘α»‹nh
9
+
10
+ - Chỉ khΓ΄i phα»₯c bα»‘n sai lệch Δ‘Γ£ xΓ‘c nhαΊ­n trong audit:
11
+ - web giα»― cΓΉng `ResolvedGoal` qua planning, re-plan vΓ  Goal Check;
12
+ - giα»›i hαΊ‘n re-plan web lαΊ₯y tα»« `MAX_REPLANS`, mαΊ·c Δ‘α»‹nh 3;
13
+ - clarification/reject khΓ΄ng bα»‹ ghi thΓ nh mα»™t lαΊ§n robot thα»±c thi thαΊ₯t bαΊ‘i;
14
+ - reset scene hoαΊ·c Δ‘α»•i environment trong CLI/Tk xΓ³a conversation memory.
15
+ - KhΓ΄ng thay Δ‘α»•i Panda model, A*, U-trajectory, placement scoring, semantic
16
+ catalog, action primitive hoαΊ·c tα»‘c Δ‘α»™ robot.
17
+ - BαΊ£o toΓ n mọi thay Δ‘α»•i local Δ‘Γ£ tα»“n tαΊ‘i ngoΓ i phαΊ‘m vi.
18
+
19
+ ## File Δ‘Γ£ sα»­a
20
+
21
+ - `frontend/interactive_server.py`
22
+ - `frontend/app.js`
23
+ - `frontend/index.html`
24
+ - `main.py`
25
+ - `tests/test_web_runtime.py`
26
+ - `tests/test_web_command_button.py`
27
+
28
+ KhΓ΄ng xΓ³a hoαΊ·c Δ‘α»•i tΓͺn file. File development log nΓ y lΓ  file mα»›i duy nhαΊ₯t được
29
+ tαΊ‘o trong lαΊ§n thα»±c thi.
30
+
31
+ ## HΓ nh vi trΖ°α»›c vΓ  sau
32
+
33
+ ### TrΖ°α»›c
34
+
35
+ - Web re-plan gọi Goal Resolution lẑi bằng raw prompt ở mọi attempt.
36
+ - Web Goal Check khΓ΄ng nhαΊ­n `ResolvedGoal`, cΓ³ thể diα»…n giαΊ£i lαΊ‘i cΓ’u follow-up.
37
+ - Web cho phΓ©p tα»‘i Δ‘a 999999 lαΊ§n re-plan.
38
+ - Clarification được gα»­i vα»›i `success=false` vΓ  frontend ghi vΓ o history/analytics
39
+ nhΖ° task thαΊ₯t bαΊ‘i.
40
+ - `PandaApp.reset_objects()` giα»― pending conversation cα»§a scene cΕ©.
41
+
42
+ ### Sau
43
+
44
+ - Attempt Δ‘αΊ§u lΖ°u `PlanningOutcome.resolved_goal`.
45
+ - Re-plan dΓΉng `resolved_goal.canonical_instruction` vΓ  `resolve_goal=False`.
46
+ - Goal Check nhαΊ­n Δ‘ΓΊng cΓΉng `resolved_goal` để dΓΉng deterministic predicates.
47
+ - Web đọc `MAX_REPLANS` tα»« environment, mαΊ·c Δ‘α»‹nh vΓ  fallback lΓ  3.
48
+ - Result có `response_type=clarify|reject`; frontend mở khóa input nhưng không ghi
49
+ execution history, analytics hoαΊ·c phΓ‘t thΓ΄ng bΓ‘o hoΓ n thΓ nh.
50
+ - `PandaApp.reset_objects()` clear conversation manager; Δ‘α»•i environment Δ‘i qua
51
+ reset nΓͺn cΕ©ng clear memory.
52
+ - JavaScript cache version tΔƒng tα»« `v26` lΓͺn `v27`.
53
+
54
+ ## Lệnh kiểm tra vΓ  kαΊΏt quαΊ£
55
+
56
+ - `node --check frontend\app.js`
57
+ - ThΓ nh cΓ΄ng.
58
+ - Python 3.10 `-m py_compile` cho main, web server/runtime, pipeline, monitor vΓ 
59
+ LLM agent
60
+ - ThΓ nh cΓ΄ng.
61
+ - Regression gα»“m conversation, semantics, monitor, obstacle graph, occupancy,
62
+ cost map vΓ  web runtime/UI:
63
+ - `104 passed`.
64
+ - `git diff --check`
65
+ - ThΓ nh cΓ΄ng; chỉ cΓ³ cαΊ£nh bΓ‘o LF/CRLF cα»§a working tree.
66
+
67
+ ## TΓ­nh nΔƒng hiện cΓ³ được bαΊ£o toΓ n
68
+
69
+ - Adaptive semantic prompt, dialogue grounding, namespace normalization,
70
+ auto-safe intermediate task vΓ  former-location swap giα»― nguyΓͺn.
71
+ - Web reload persistence, live interrupt, safe hold vΓ  send/stop UI giα»― nguyΓͺn.
72
+ - Clarification vαΊ«n được lΖ°u trong conversation manager để lượt trαΊ£ lời tiαΊΏp theo
73
+ bα»• sung intent.
74
+ - Reset/change environment, manual controls, microphone, autocomplete vΓ  UI
75
+ history vαΊ«n tα»“n tαΊ‘i.
76
+ - `time_scale = 0.1` khΓ΄ng thay Δ‘α»•i.
77
+
78
+ ## VαΊ₯n đề cΓ²n lαΊ‘i hoαΊ·c cαΊ§n người dΓΉng quyαΊΏt Δ‘α»‹nh
79
+
80
+ - ChΖ°a chαΊ‘y live OpenRouter trong lαΊ§n nΓ y; schema/behavior được kiểm tra offline.
81
+ - Persistence vαΊ«n chỉ sα»‘ng trong cΓΉng backend process; restart backend chΖ°a phα»₯c
82
+ hα»“i PyBullet state tα»« disk.
development_logs/2026-07-04_17-34-05_normalize-standalone-compound-intents.md ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ChuαΊ©n hΓ³a đệ quy standalone compound intents
2
+
3
+ ## YΓͺu cαΊ§u cα»§a người dΓΉng
4
+
5
+ Sα»­a trường hợp lệnh `hoΓ‘n Δ‘α»•i vα»‹ trΓ­ giα»―a quαΊ£ bΓ³ng vΓ  lon chip` vαΊ«n hỏi bề mαΊ·t
6
+ Δ‘Γ­ch, theo hΖ°α»›ng scalable vΓ  adaptive cho nhiều hΓ nh Δ‘α»™ng vΓ  mΓ΄i trường.
7
+
8
+ ## PhαΊ‘m vi vΓ  giαΊ£ Δ‘α»‹nh
9
+
10
+ - Sα»­a semantic boundary dΓΉng chung, khΓ΄ng hard-code cΓ’u lệnh, object hoαΊ·c
11
+ environment cα»₯ thể.
12
+ - Mọi intent cΓ³ `tasks` đều phαΊ£i được chuαΊ©n hΓ³a theo object/surface namespace cα»§a
13
+ scene hiện hΓ nh, dΓΉ lΓ  lệnh standalone hay follow-up.
14
+ - Giα»― nguyΓͺn Panda, A*, U-trajectory, goal predicate, scoring, executor vΓ  tα»‘c Δ‘α»™.
15
+ - BαΊ£o toΓ n toΓ n bα»™ thay Δ‘α»•i local cΓ³ sαΊ΅n ngoΓ i phαΊ‘m vi.
16
+
17
+ ## File Δ‘Γ£ sα»­a
18
+
19
+ - `llm_panda/llm_agent.py`
20
+ - `tests/test_conversation_memory.py`
21
+
22
+ ## File Δ‘Γ£ thΓͺm
23
+
24
+ - `development_logs/2026-07-04_17-34-05_normalize-standalone-compound-intents.md`
25
+
26
+ KhΓ΄ng xΓ³a hoαΊ·c Δ‘α»•i tΓͺn file.
27
+
28
+ ## HΓ nh vi trΖ°α»›c vΓ  sau
29
+
30
+ ### TrΖ°α»›c
31
+
32
+ - Sequence tα»« pending conversation được chuαΊ©n hΓ³a tα»«ng task.
33
+ - Sequence mα»›i do Goal Resolver trαΊ£ cho mα»™t lệnh standalone chỉ được chuαΊ©n hΓ³a ở
34
+ object ngoΓ i cΓΉng.
35
+ - Task `former_location` bΓͺn trong giα»― `destination=None`, dΓΉ scene Δ‘Γ£ biαΊΏt surface
36
+ cα»§a anchor.
37
+ - Validator vΓ¬ vαΊ­y hỏi người dΓΉng chọn bề mαΊ·t cho mα»™t swap vα»‘n Δ‘Γ£ Δ‘α»§ rΓ΅.
38
+
39
+ ### Sau
40
+
41
+ - `_merge_resolved_intent()` dΓΉng mα»™t đường chuαΊ©n hΓ³a task chung cho cαΊ£ standalone
42
+ vΓ  follow-up sequences.
43
+ - Mα»—i child task được:
44
+ - loẑi bỏ placeholder/null;
45
+ - chuαΊ©n hΓ³a object/surface namespace;
46
+ - gΓ‘n `auto_safe` cho intermediate task;
47
+ - suy ra destination cα»§a `former_location` tα»« anchor trong scene hiện tαΊ‘i.
48
+ - CΖ‘ chαΊΏ Γ‘p dα»₯ng cho swap, replacement vΓ  compound action bαΊ₯t kα»³ cΓ³ `tasks`.
49
+ - Surface được đọc Δ‘α»™ng tα»« environment; test dΓΉng `workbench`, khΓ΄ng phα»₯ thuα»™c
50
+ `table` hoαΊ·c `tray`.
51
+
52
+ ## Lệnh kiểm tra vΓ  kαΊΏt quαΊ£
53
+
54
+ - Python 3.10 `-m py_compile llm_panda\llm_agent.py`
55
+ - ThΓ nh cΓ΄ng.
56
+ - Focused conversation vΓ  environment semantics:
57
+ - `48 passed`.
58
+ - Regression conversation, semantics, monitor, obstacle graph, occupancy, cost
59
+ map vΓ  web runtime/UI:
60
+ - `105 passed`.
61
+ - `git diff --check`
62
+ - ThΓ nh cΓ΄ng; chỉ cΓ³ cαΊ£nh bΓ‘o LF/CRLF cα»§a working tree.
63
+
64
+ ## TΓ­nh nΔƒng hiện cΓ³ được bαΊ£o toΓ n
65
+
66
+ - Pending follow-up merge vΓ  bαΊ£o vệ known slots giα»― nguyΓͺn.
67
+ - Namespace object/surface, constraint provenance vΓ  fail-closed validation giα»―
68
+ nguyΓͺn.
69
+ - Intermediate task vαΊ«n khΓ΄ng tαΊ‘o Goal Predicate.
70
+ - Former-location anchor vαΊ«n dΓΉng tọa Δ‘α»™ scene, khΓ΄ng lαΊ₯y tọa Δ‘α»™ do LLM sinh.
71
+ - Adaptive semantic catalog vΓ  aliases cα»§a environment hiện hΓ nh giα»― nguyΓͺn.
72
+
73
+ ## VαΊ₯n đề cΓ²n lαΊ‘i hoαΊ·c cαΊ§n người dΓΉng quyαΊΏt Δ‘α»‹nh
74
+
75
+ - Live OpenRouter cαΊ§n chαΊ‘y lαΊ‘i sau khi restart backend để quan sΓ‘t trọn pipeline.
76
+ - NαΊΏu model trαΊ£ intent khΓ΄ng cΓ³ `tasks` cho mα»™t yΓͺu cαΊ§u compound, schema guard vαΊ«n
77
+ cΓ³ thể yΓͺu cαΊ§u repair/clarification; thay Δ‘α»•i nΓ y xα»­ lΓ½ chΓ­nh xΓ‘c mọi structured
78
+ compound intent hợp lệ.
development_logs/2026-07-04_17-53-16_add-web-manual-drag-and-catalog-spawn.md ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ThΓͺm kΓ©o thαΊ£ thα»§ cΓ΄ng vΓ  spawn vαΊ­t tα»« thΖ° viện trΓͺn web
2
+
3
+ ## YΓͺu cαΊ§u cα»§a người dΓΉng
4
+
5
+ - Cho phΓ©p người dΓΉng kΓ©o thαΊ£ vαΊ­t thể vΓ  cΓ‘nh tay robot trα»±c tiαΊΏp trong mΓ΄i trường
6
+ web tΖ°Ζ‘ng tα»± PyBullet GUI.
7
+ - Cho phΓ©p kΓ©o avatar/hΓ ng vαΊ­t thể tα»« tab thΖ° viện vΓ o viewport để thΓͺm vαΊ­t thαΊ­t
8
+ vΓ o simulation.
9
+ - Thα»±c hiện theo kαΊΏ hoαΊ‘ch interaction Δ‘Γ£ cung cαΊ₯p, Δ‘α»“ng thời bαΊ£o toΓ n cΓ‘c tΓ­nh
10
+ nΔƒng hiện cΓ³.
11
+
12
+ ## PhαΊ‘m vi vΓ  giαΊ£ Δ‘α»‹nh
13
+
14
+ - PyBullet lΓ  nguα»“n sα»± thαΊ­t vαΊ­t lΓ½; Three.js chỉ gα»­i Γ½ Δ‘α»‹nh tΖ°Ζ‘ng tΓ‘c.
15
+ - VαΊ­t thể dΓΉng point-to-point constraint; robot dΓΉng end-effector IK để trΓ‘nh
16
+ constraint chα»‘ng lαΊ‘i joint motors.
17
+ - Manual interaction tα»± interrupt task Δ‘ang chαΊ‘y vΓ  chờ safe hold.
18
+ - Runtime-spawned YCB object nhαΊ­n semantic metadata generic, data-driven để xuαΊ₯t
19
+ hiện trong scene state vΓ  adaptive prompt.
20
+ - KhΓ΄ng thay planner, Goal Check, A*, U-trajectory, scoring hoαΊ·c tα»‘c Δ‘α»™ robot.
21
+
22
+ ## File Δ‘Γ£ sα»­a
23
+
24
+ - `frontend/app.js`
25
+ - `frontend/index.css`
26
+ - `frontend/index.html`
27
+ - `frontend/interactive_server.py`
28
+ - `llm_panda/core/env_builder.py`
29
+ - `llm_panda/scene_manager.py`
30
+ - `tests/test_web_command_button.py`
31
+
32
+ ## File Δ‘Γ£ thΓͺm
33
+
34
+ - `tests/test_web_drag_drop.py`
35
+ - `development_logs/2026-07-04_17-53-16_add-web-manual-drag-and-catalog-spawn.md`
36
+
37
+ KhΓ΄ng xΓ³a hoαΊ·c Δ‘α»•i tΓͺn file.
38
+
39
+ ## HΓ nh vi trΖ°α»›c vΓ  sau
40
+
41
+ ### TrΖ°α»›c
42
+
43
+ - Frontend chỉ dΓΉng mouse down/move; thiαΊΏu mouseup Δ‘αΊ§y Δ‘α»§ vΓ  pointer capture.
44
+ - Object vΓ  robot cΓΉng Δ‘i qua physics constraint.
45
+ - Client/server khΓ΄ng cΓ³ drag session ID.
46
+ - Manual drag bα»‹ bỏ qua khi task Δ‘ang chαΊ‘y.
47
+ - Disconnect cΓ³ thể để lαΊ‘i constraint.
48
+ - Library chỉ hiển thα»‹ catalog, chΖ°a thể thΓͺm object vΓ o simulation.
49
+
50
+ ### Sau
51
+
52
+ - DΓΉng Δ‘αΊ§y Δ‘α»§ Pointer Events: down, move, up, cancel, lost capture.
53
+ - Mα»—i thao tΓ‘c cΓ³ `drag_id`; update/end sai session bα»‹ bỏ qua.
54
+ - Backend raycast xΓ‘c nhαΊ­n object được client chọn.
55
+ - YCB object dΓΉng point-to-point constraint vΓ  state được broadcast 60 Hz.
56
+ - Robot dΓΉng IK theo end-effector, clamp workspace vΓ  giα»― pose khi thαΊ£.
57
+ - Target được kiểm tra finite, giα»›i hαΊ‘n workspace vΓ  khΓ΄ng Δ‘i xuyΓͺn table/tray.
58
+ - BαΊ―t Δ‘αΊ§u manual interaction tα»± cancel task, chờ robot dα»«ng an toΓ n rα»“i mα»›i kΓ©o.
59
+ - Constraint được dọn khi pointer kαΊΏt thΓΊc hoαΊ·c WebSocket disconnect.
60
+ - Row/avatar trong catalog cΓ³ thể kΓ©o vΓ o canvas.
61
+ - Điểm thαΊ£ được raycast xuα»‘ng mαΊ·t placement; backend load URDF YCB thαΊ­t, tαΊ‘o tΓͺn
62
+ instance duy nhαΊ₯t, Δ‘Δƒng kΓ½ SceneManager vΓ  broadcast init/state mα»›i.
63
+ - Runtime object nhαΊ­n aliases, category, attributes vΓ  affordances generic để LLM
64
+ nhΓ¬n thαΊ₯y trong active scene.
65
+ - Asset cache version tΔƒng lΓͺn `app.js?v=28`, `index.css?v=10`.
66
+
67
+ ## Lệnh kiểm tra vΓ  kαΊΏt quαΊ£
68
+
69
+ - `node --check frontend\app.js`
70
+ - ThΓ nh cΓ΄ng.
71
+ - Python 3.10 `-m py_compile` cho web server, EnvBuilder vΓ  SceneManager
72
+ - ThΓ nh cΓ΄ng.
73
+ - Test web drag/runtime/button:
74
+ - `22 passed`.
75
+ - Regression conversation, semantics, monitor, obstacle graph, occupancy, cost
76
+ map vΓ  web:
77
+ - `111 passed`.
78
+ - `git diff --check`
79
+ - ThΓ nh cΓ΄ng; chỉ cΓ³ cαΊ£nh bΓ‘o LF/CRLF cα»§a working tree.
80
+
81
+ ## TΓ­nh nΔƒng hiện cΓ³ được bαΊ£o toΓ n
82
+
83
+ - Reload persistence, live interrupt/re-plan vΓ  send/stop UI giα»― nguyΓͺn.
84
+ - Conversation memory vΓ  adaptive environment prompts giα»― nguyΓͺn.
85
+ - Existing object pose/joint controls vαΊ«n cΓ²n.
86
+ - Reset/change environment vαΊ«n xΓ³a runtime additions theo scene lifecycle cΕ©.
87
+ - Planner vΓ  robot execution khΓ΄ng chαΊ‘y song song vα»›i manual manipulation.
88
+
89
+ ## VαΊ₯n đề cΓ²n lαΊ‘i hoαΊ·c cαΊ§n người dΓΉng quyαΊΏt Δ‘α»‹nh
90
+
91
+ - PhiΓͺn bαΊ£n nΓ y hα»— trợ translate tα»± do theo camera plane; chΖ°a cΓ³ gizmo riΓͺng cho
92
+ rotate, trα»₯c Z hoαΊ·c local-axis transform.
93
+ - Runtime object dΓΉng semantics generic tα»« catalog folder. Muα»‘n tΓͺn tiαΊΏng Việt,
94
+ category vΓ  thuα»™c tΓ­nh chuyΓͺn biệt cho mọi YCB item cαΊ§n mα»™t semantic catalog mở
95
+ rα»™ng tΖ°Ζ‘ng α»©ng.
96
+ - CαΊ§n kiểm thα»­ trα»±c tiαΊΏp trong browser vα»›i nhiều model YCB vΓ¬ tα»«ng asset cΓ³
97
+ footprint, mesh material vΓ  khα»‘i lượng khΓ‘c nhau.
development_logs/2026-07-04_18-00-40_fix-web-object-drag-and-runtime-visuals.md ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Sα»­a object drag vΓ  visual cα»§a runtime-spawned YCB
2
+
3
+ ## YΓͺu cαΊ§u cα»§a người dΓΉng
4
+
5
+ Sα»­a hai lα»—i sau khi triển khai kΓ©o thαΊ£ web:
6
+
7
+ - chỉ kΓ©o được robot, object luΓ΄n bΓ‘o khΓ΄ng khα»›p scene vαΊ­t lΓ½;
8
+ - object thΓͺm tα»« thΖ° viện cΓ³ physics shape nhΖ°ng chΖ°a hiển thα»‹ visual Δ‘ΓΊng.
9
+
10
+ ## PhαΊ‘m vi vΓ  giαΊ£ Δ‘α»‹nh
11
+
12
+ - Giα»― PyBullet body được Δ‘Δƒng kΓ½ theo object name lΓ m nguα»“n xΓ‘c thα»±c cho object
13
+ drag.
14
+ - KhΓ΄ng quay lαΊ‘i cΖ‘ chαΊΏ constraint trΓͺn robot; robot vαΊ«n dΓΉng end-effector IK.
15
+ - Chỉ sα»­a drag anchor vΓ  suy luαΊ­n metadata visual cα»§a runtime-spawned YCB.
16
+ - BαΊ£o toΓ n mọi thay Δ‘α»•i local vΓ  tΓ­nh nΔƒng hiện cΓ³ ngoΓ i phαΊ‘m vi.
17
+
18
+ ## File Δ‘Γ£ sα»­a
19
+
20
+ - `frontend/app.js`
21
+ - `frontend/interactive_server.py`
22
+ - `frontend/index.html`
23
+ - `tests/test_web_drag_drop.py`
24
+ - `tests/test_web_command_button.py`
25
+
26
+ ## File Δ‘Γ£ thΓͺm
27
+
28
+ - `development_logs/2026-07-04_18-00-40_fix-web-object-drag-and-runtime-visuals.md`
29
+
30
+ KhΓ΄ng xΓ³a hoαΊ·c Δ‘α»•i tΓͺn file.
31
+
32
+ ## HΓ nh vi trΖ°α»›c vΓ  sau
33
+
34
+ ### TrΖ°α»›c
35
+
36
+ - Backend yΓͺu cαΊ§u PyBullet ray phαΊ£i trΓΊng Δ‘ΓΊng cΓΉng body mΓ  Three.js ray Δ‘Γ£ chọn.
37
+ - Sai khΓ‘c giα»―a visual mesh vΓ  collision mesh lΓ m object hợp lệ bα»‹ tα»« chα»‘i.
38
+ - Constraint dΓΉng Δ‘iểm hit tα»« collision ray trong khi client di chuyển theo visual
39
+ hit point, cΓ³ nguy cΖ‘ nhαΊ£y offset.
40
+ - Runtime visual tìm cố định `model.mtl`, trong khi YCB dùng cÑc cặp như
41
+ `textured_simple_reoriented.obj/.mtl`.
42
+
43
+ ### Sau
44
+
45
+ - Frontend gα»­i target theo base position cα»§a Three.js object group.
46
+ - Backend resolve object name sang body Δ‘Γ£ Δ‘Δƒng kΓ½ vΓ  khΓ΄ng bαΊ―t hai ray engine
47
+ phαΊ£i trΓΊng cΓΉng triangle/body.
48
+ - Object constraint gαΊ―n vΓ o base frame `[0,0,0]`, child target bαΊ―t Δ‘αΊ§u tαΊ‘i live
49
+ base pose nΓͺn khΓ΄ng nhαΊ£y khi drag.
50
+ - Robot ray validation vΓ  IK path giα»― nguyΓͺn.
51
+ - Runtime visual lαΊ₯y material cΓ³ cΓΉng stem vα»›i visual mesh được PyBullet bΓ‘o.
52
+ - Smoke test thα»±c tαΊΏ xΓ‘c nhαΊ­n `YcbCrackerBox` trαΊ£:
53
+ - `textured_simple_reoriented.obj`;
54
+ - `textured_simple_reoriented.mtl`.
55
+ - JavaScript cache version tΔƒng lΓͺn `v29`.
56
+
57
+ ## Lệnh kiểm tra vΓ  kαΊΏt quαΊ£
58
+
59
+ - `node --check frontend\app.js`
60
+ - ThΓ nh cΓ΄ng.
61
+ - Python 3.10 `-m py_compile frontend\interactive_server.py`
62
+ - ThΓ nh cΓ΄ng.
63
+ - Test web drag/button/runtime:
64
+ - `23 passed`.
65
+ - Headless PyBullet smoke test spawn `YcbCrackerBox` vΓ  đọc init payload:
66
+ - ThΓ nh cΓ΄ng, folder/OBJ/MTL Δ‘ΓΊng.
67
+ - Regression conversation, semantics, monitor, occupancy, cost map vΓ  web:
68
+ - `112 passed`.
69
+ - `git diff --check`
70
+ - ThΓ nh cΓ΄ng; chỉ cΓ³ cαΊ£nh bΓ‘o LF/CRLF cα»§a working tree.
71
+
72
+ ## TΓ­nh nΔƒng hiện cΓ³ được bαΊ£o toΓ n
73
+
74
+ - Robot end-effector drag bαΊ±ng IK giα»― nguyΓͺn.
75
+ - Drag ID, pointer capture, workspace clamp vΓ  disconnect cleanup giα»― nguyΓͺn.
76
+ - Catalog spawn tαΊ‘o body vαΊ­t lΓ½ thαΊ­t vΓ  semantic metadata giα»― nguyΓͺn.
77
+ - Reload persistence, cancellation vΓ  conversation memory giα»― nguyΓͺn.
78
+
79
+ ## VαΊ₯n đề cΓ²n lαΊ‘i hoαΊ·c cαΊ§n người dΓΉng quyαΊΏt Δ‘α»‹nh
80
+
81
+ - CαΊ§n restart backend vΓ  hard-refresh để browser nhαΊ­n `app.js?v=29`.
82
+ - Mα»™t sα»‘ YCB model cΓ³ thể cΓ³ material/texture Δ‘αΊ·c thΓΉ khΓ‘c; loader vαΊ«n hα»— trợ OBJ
83
+ khΓ΄ng cΓ³ MTL lΓ m fallback.
docs/CONTEXT_AWARE_GOAL_CHECK_PLAN.md CHANGED
@@ -5,6 +5,12 @@
5
  Đã triển khai ngΓ y 2026-07-03:
6
 
7
  - pre-planning LLM Goal Resolution Gate: `ready | clarify | reject`;
 
 
 
 
 
 
8
  - planner chỉ nhαΊ­n canonical goal khi gate trαΊ£ `ready`;
9
  - action thiαΊΏu tham sα»‘ bαΊ―t buα»™c bα»‹ chαΊ·n vΓ  chuyển thΓ nh clarification;
10
  - `ResolvedGoal`/`PlanningOutcome` vΓ  goal predicates;
 
5
  Đã triển khai ngΓ y 2026-07-03:
6
 
7
  - pre-planning LLM Goal Resolution Gate: `ready | clarify | reject`;
8
+ - typed intent slots: manipulated `object_id`, surface `destination`, spatial
9
+ `relation`, reference-object `relative_to`;
10
+ - follow-up chỉ được Δ‘iền missing slots, khΓ΄ng được ghi Δ‘Γ¨ slot Δ‘Γ£ biαΊΏt;
11
+ - self-reference vΓ  plan/goal mismatch bα»‹ chαΊ·n trΖ°α»›c execution;
12
+ - compound/swap/replacement goal được lΖ°u thΓ nh ordered `tasks`; clarification chỉ
13
+ Δ‘iền slot thiαΊΏu cα»§a mα»™t task vΓ  khΓ΄ng được lΓ m mαΊ₯t cΓ‘c task cΓ²n lαΊ‘i;
14
  - planner chỉ nhαΊ­n canonical goal khi gate trαΊ£ `ready`;
15
  - action thiαΊΏu tham sα»‘ bαΊ―t buα»™c bα»‹ chαΊ·n vΓ  chuyển thΓ nh clarification;
16
  - `ResolvedGoal`/`PlanningOutcome` vΓ  goal predicates;
docs/CONVERSATION_MEMORY_PLAN.md CHANGED
@@ -7,6 +7,9 @@ NgΓ y lαΊ­p kαΊΏ hoαΊ‘ch: 2026-07-03
7
  - 2026-07-03: HoΓ n thΓ nh Phase 1 β€” pending clarification memory trong phiΓͺn.
8
  - 2026-07-03: HoΓ n thΓ nh Phase 2 β€” structured dialogue state, cancel/replace,
9
  scene revision vΓ  structured-output fallback.
 
 
 
10
  - Đã tΓ­ch hợp core agent, CLI/Tkinter, WebSocket, PySide vΓ  overlay.
11
  - Reset scene/change environment sαΊ½ xΓ³a conversation context.
12
  - CΓ³ feature flag `CONVERSATION_MEMORY_ENABLED` để quay về stateless mode.
@@ -435,3 +438,27 @@ KhuyαΊΏn nghα»‹ mαΊ·c Δ‘α»‹nh:
435
 
436
  Việc bαΊ­t persistence qua Redis/SQLite, lΖ°u dα»― liệu dΓ i hαΊ‘n hoαΊ·c tΓ‘ch simulation
437
  theo tα»«ng người dΓΉng lΓ  thay Δ‘α»•i phαΊ‘m vi vΓ  cαΊ§n phΓͺ duyệt riΓͺng.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  - 2026-07-03: HoΓ n thΓ nh Phase 1 β€” pending clarification memory trong phiΓͺn.
8
  - 2026-07-03: HoΓ n thΓ nh Phase 2 β€” structured dialogue state, cancel/replace,
9
  scene revision vΓ  structured-output fallback.
10
+ - 2026-07-04: Bα»• sung adaptive entity grounding tα»« environment catalog vΓ  mα»™t
11
+ schema-repair turn cho Goal Resolution; unique alias khΓ΄ng cΓ²n bα»‹ hỏi xΓ‘c nhαΊ­n,
12
+ malformed provider response khΓ΄ng lΓ m mαΊ₯t pending context.
13
  - Đã tΓ­ch hợp core agent, CLI/Tkinter, WebSocket, PySide vΓ  overlay.
14
  - Reset scene/change environment sαΊ½ xΓ³a conversation context.
15
  - CΓ³ feature flag `CONVERSATION_MEMORY_ENABLED` để quay về stateless mode.
 
438
 
439
  Việc bαΊ­t persistence qua Redis/SQLite, lΖ°u dα»― liệu dΓ i hαΊ‘n hoαΊ·c tΓ‘ch simulation
440
  theo tα»«ng người dΓΉng lΓ  thay Δ‘α»•i phαΊ‘m vi vΓ  cαΊ§n phΓͺ duyệt riΓͺng.
441
+
442
+ ## 17. Optional constraints vΓ  intermediate-task boundary
443
+
444
+ - TrαΊ‘ng thΓ‘i: hoΓ n thΓ nh ngΓ y 2026-07-04.
445
+ - Goal Resolution chỉ yΓͺu cαΊ§u lΓ m rΓ΅ constraint bαΊ―t buα»™c cα»§a kαΊΏt quαΊ£ người dΓΉng.
446
+ - `relation` vΓ  `relative_to` lΓ  mα»™t cαΊ·p nguyΓͺn tα»­, chỉ giα»― khi cΓ³ provenance
447
+ `user`/`conversation` hoαΊ·c Δ‘ang lΓ  field được người dΓΉng lΓ m rΓ΅.
448
+ - Relation rời do model tα»± suy diα»…n được loαΊ‘i bỏ trΖ°α»›c validation.
449
+ - Task `purpose=intermediate` dΓΉng `placement_policy=auto_safe`; planner chọn vα»‹
450
+ trΓ­ an toΓ n mΓ  khΓ΄ng hỏi người dΓΉng nαΊΏu họ khΓ΄ng Δ‘αΊ·t rΓ ng buα»™c.
451
+ - Goal Check được biΓͺn dα»‹ch tα»« resolved intent vΓ  bỏ qua intermediate task, thay
452
+ vΓ¬ biαΊΏn toΓ n bα»™ execution plan thΓ nh Δ‘iều kiện hoΓ n thΓ nh.
453
+
454
+ ## 18. Former-location anchor cho swap/replace
455
+
456
+ - TrαΊ‘ng thΓ‘i: hoΓ n thΓ nh ngΓ y 2026-07-04.
457
+ - Swap được biểu diα»…n bαΊ±ng temporary relocation vΓ  hai goal task cΓ³
458
+ `placement_policy=former_location`.
459
+ - Mα»—i goal task dΓΉng `anchor_object_id`; tọa Δ‘α»™ được snapshot tα»« scene ban Δ‘αΊ§u,
460
+ khΓ΄ng nhαΊ­n sα»‘ do LLM tαΊ‘o.
461
+ - `move_to` được annotate nα»™i bα»™ bαΊ±ng `target_position`; free-space optimiser
462
+ chọn vα»‹ trΓ­ khαΊ£ dα»₯ng gαΊ§n anchor nhαΊ₯t trong khi vαΊ«n giα»― reachability/clearance.
463
+ - Goal Check dΓΉng predicate `position_near` vα»›i sai sα»‘ 4 cm thay vΓ¬ chỉ kiểm tra
464
+ hai vαΊ­t vαΊ«n nαΊ±m trΓͺn cΓΉng surface.
docs/ENVIRONMENT_SEMANTIC_CATALOG.md ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Environment Semantic Catalog
2
+
3
+ ## Mα»₯c Δ‘Γ­ch
4
+
5
+ Mα»—i mΓ΄i trường cΓ³ hai phαΊ§n dα»― liệu:
6
+
7
+ - file environment: robot, geometry, asset vΓ  initial pose;
8
+ - file semantic catalog: thΓ΄ng tin để LLM hiểu object vΓ  surface.
9
+
10
+ VΓ­ dα»₯:
11
+
12
+ ```json
13
+ {
14
+ "semantic_catalog": "env1.semantics.json",
15
+ "robot": {},
16
+ "table": {},
17
+ "tray": {},
18
+ "objects": []
19
+ }
20
+ ```
21
+
22
+ Catalog tΖ°Ζ‘ng α»©ng:
23
+
24
+ ```json
25
+ {
26
+ "schema_version": 1,
27
+ "environment_id": "env1",
28
+ "description": "...",
29
+ "surfaces": {
30
+ "table": {
31
+ "display_name": {"vi": "bΓ n", "en": "table"},
32
+ "aliases": ["bΓ n", "table"],
33
+ "kind": "support_surface"
34
+ }
35
+ },
36
+ "objects": {
37
+ "object_id": {
38
+ "display_name": {"vi": "...", "en": "..."},
39
+ "aliases": [],
40
+ "categories": [],
41
+ "attributes": {},
42
+ "affordances": []
43
+ }
44
+ }
45
+ }
46
+ ```
47
+
48
+ ## Trường dα»― liệu
49
+
50
+ - `environment_id`: Δ‘α»‹nh danh α»•n Δ‘α»‹nh cα»§a mΓ΄i trường.
51
+ - `description`: mΓ΄ tαΊ£ ngαΊ―n cho LLM.
52
+ - `surfaces`: metadata cα»§a cΓ‘c surface hiện cΓ³.
53
+ - `objects`: map theo Δ‘ΓΊng object ID trong environment.
54
+ - `display_name`: tΓͺn hiển thα»‹, khΓ΄ng dΓΉng lΓ m ID thα»±c thi.
55
+ - `aliases`: cΓ‘ch người dΓΉng cΓ³ thể gọi object/surface.
56
+ - `categories`: phΓ’n loαΊ‘i semantic nhΖ° fruit, tool, food.
57
+ - `attributes`: color, material, weight hoαΊ·c thuα»™c tΓ­nh tΓΉy mΓ΄i trường.
58
+ - `affordances`: khả năng semantic như pickable, placeable, support_surface.
59
+
60
+ ## Quy tαΊ―c
61
+
62
+ - Mọi object trong environment phαΊ£i cΓ³ entry trong catalog được tham chiαΊΏu.
63
+ - Catalog phαΊ£i mΓ΄ tαΊ£ `table` vΓ  `tray` trong scope hiện tαΊ‘i.
64
+ - Planner luΓ΄n dΓΉng canonical object ID; alias chỉ phα»₯c vα»₯ grounding.
65
+ - Chỉ object thαΊ­t sα»± cΓ³ trong scene hiện tαΊ‘i được Δ‘Ζ°a vΓ o adaptive prompt.
66
+ - KhΓ΄ng Δ‘Ζ°a API key, credential hoαΊ·c dα»― liệu người dΓΉng vΓ o catalog.
67
+
68
+ ## ThΓͺm mΓ΄i trường mα»›i
69
+
70
+ 1. TαΊ‘o `envs/<name>.json`.
71
+ 2. TαΊ‘o `envs/<name>.semantics.json`.
72
+ 3. ThΓͺm trường `semantic_catalog` vΓ o environment.
73
+ 4. MΓ΄ tαΊ£ Δ‘αΊ§y Δ‘α»§ tα»«ng object vΓ  surface.
74
+ 5. ChαΊ‘y `tests/test_environment_semantics.py`.
75
+
76
+ KhΓ΄ng cαΊ§n sα»­a `RemoteLLMPlanner.SYSTEM_PROMPT` khi thΓͺm object, alias, category hoαΊ·c
77
+ thuα»™c tΓ­nh mα»›i.
78
+
docs/GENERALIZATION_AUDIT.md ADDED
@@ -0,0 +1,382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Kiểm kΓͺ giα»›i hαΊ‘n hard-code vΓ  lα»™ trΓ¬nh tα»•ng quΓ‘t hΓ³a LLM-Panda
2
+
3
+ ## 1. Mα»₯c tiΓͺu
4
+
5
+ TΓ i liệu nΓ y phΓ’n biệt ba loαΊ‘i rΓ ng buα»™c:
6
+
7
+ 1. **BαΊ₯t biαΊΏn phαΊ§n cα»©ng** β€” phαΊ£i tα»“n tαΊ‘i nhΖ°ng nΓͺn nαΊ±m trong robot profile/capability
8
+ registry, khΓ΄ng nαΊ±m rαΊ£i rΓ‘c trong logic.
9
+ 2. **Tham sα»‘ heuristic** β€” cαΊ§n cαΊ₯u hΓ¬nh hoαΊ·c hiệu chỉnh theo scene/robot.
10
+ 3. **Hard-code miền bΓ i toΓ‘n** β€” Δ‘ang khiαΊΏn hệ thα»‘ng chỉ lΓ m tα»‘t vα»›i vΓ i object,
11
+ bề mαΊ·t, cΓ’u lệnh vΓ  hΓ nh vi; Δ‘Γ’y lΓ  nhΓ³m cαΊ§n loαΊ‘i bỏ để tα»•ng quΓ‘t hΓ³a.
12
+
13
+ Thay Δ‘α»•i Δ‘αΊ§u tiΓͺn Δ‘Γ£ thα»±c hiện: Remote LLM khΓ΄ng cΓ²n dΓΉng danh sΓ‘ch Δ‘α»™ng tα»«/object
14
+ trong `ConversationManager` để quyαΊΏt Δ‘α»‹nh cΓ’u mα»›i hay follow-up. LLM Goal Resolution
15
+ trαΊ£ `conversation_mode=standalone|follow_up` bαΊ±ng semantic reasoning.
16
+
17
+ ## QuyαΊΏt Δ‘α»‹nh phαΊ‘m vi cα»§a dα»± Γ‘n
18
+
19
+ Theo yΓͺu cαΊ§u ngΓ y 2026-07-04, cΓ‘c giα»›i hαΊ‘n sau **được giα»― nguyΓͺn cΓ³ chα»§ Δ‘Γ­ch** vΓ¬
20
+ thuα»™c scope bΓ i toΓ‘n:
21
+
22
+ - model vΓ  controller cα»§a Franka Panda;
23
+ - A* 2D vΓ  U-trajectory;
24
+ - bα»™ Goal Predicate hiện tαΊ‘i;
25
+ - scoring hiện tαΊ‘i.
26
+
27
+ CΓ‘c mα»₯c nΓ y khΓ΄ng cΓ²n nαΊ±m trong backlog bαΊ―t buα»™c tα»•ng quΓ‘t hΓ³a. Trọng tΓ’m trΖ°α»›c mαΊ―t
28
+ lΓ  tα»•ng quΓ‘t hΓ³a thΓ΄ng tin mΓ΄i trường vΓ  semantic grounding.
29
+
30
+ ## TrαΊ‘ng thΓ‘i Phase G1
31
+
32
+ Đã triển khai:
33
+
34
+ - mα»—i environment trỏ Δ‘αΊΏn mα»™t semantic catalog JSON riΓͺng;
35
+ - aliases, display names, categories, attributes vΓ  affordances được chuyển khỏi
36
+ Remote LLM prompt vΓ o catalog;
37
+ - `EnvBuilder` nαΊ‘p vΓ  kiểm tra catalog;
38
+ - `SceneManager` Δ‘Ζ°a semantics cα»§a object/surface hiện hΓ nh vΓ o scene state;
39
+ - Goal Resolver, Planner vΓ  LLM fallback Goal Check xΓ’y prompt adaptive tα»« scene;
40
+ - Δ‘α»•i environment lΓ m thay Δ‘α»•i prompt mΓ  khΓ΄ng sα»­a Python;
41
+ - core Remote LLM prompt khΓ΄ng cΓ²n chα»©a catalog sΓ‘u object cα»§a `env1`.
42
+
43
+ ## 2. Quy trΓ¬nh hiện tαΊ‘i vΓ  cΓ‘c Δ‘iểm bα»‹ giα»›i hαΊ‘n
44
+
45
+ ### BΖ°α»›c 1 β€” NhαΊ­n hα»™i thoαΊ‘i
46
+
47
+ **Hiện tαΊ‘i**
48
+
49
+ - `ConversationManager` giα»― pending clarification, sΓ‘u lượt gαΊ§n nhαΊ₯t vΓ  TTL 10 phΓΊt.
50
+ - Cancel dΓΉng tαΊ­p cΓ’u cα»‘ Δ‘α»‹nh Việt/Anh.
51
+ - Fallback offline nhαΊ­n diện lệnh mα»›i bαΊ±ng `_ACTION_WORDS` vΓ  `_OBJECT_WORDS`.
52
+ - Remote LLM nay dΓΉng `conversation_mode` thay cho hai danh sΓ‘ch Δ‘Γ³.
53
+
54
+ **Giα»›i hαΊ‘n cΓ²n lαΊ‘i**
55
+
56
+ - Cancel vαΊ«n phα»₯ thuα»™c danh sΓ‘ch cα»₯m tα»«.
57
+ - KhΓ΄ng cΓ³ dialogue-act ontology tα»•ng quΓ‘t nhΖ° cancel/correct/replace/confirm.
58
+ - KhΓ΄ng cΓ³ entity memory sau khi task Δ‘Γ£ hoΓ n tαΊ₯t; chα»§ yαΊΏu nhα»› pending clarification.
59
+ - KhΓ΄ng cΓ³ rolling summary/persistence.
60
+
61
+ **HΖ°α»›ng tα»•ng quΓ‘t**
62
+
63
+ - Để Goal Resolver trαΊ£ dialogue act cΓ³ cαΊ₯u trΓΊc.
64
+ - Entity grounding theo scene ID thay vì từ khóa.
65
+ - DΓΉng bounded semantic state, khΓ΄ng Δ‘Ζ°a toΓ n bα»™ chat thΓ΄ vΓ o planner.
66
+
67
+ ### BΖ°α»›c 2 β€” Goal Resolution
68
+
69
+ **Hiện tαΊ‘i**
70
+
71
+ - Output cα»‘ Δ‘α»‹nh: `ready|clarify|reject`.
72
+ - Missing fields cα»‘ Δ‘α»‹nh: object, destination, relation, relative object, details.
73
+ - Prompt cΓ³ vΓ­ dα»₯ cα»₯ thể banana, pear, chips can.
74
+
75
+ **Giα»›i hαΊ‘n**
76
+
77
+ - Goal schema thiΓͺn về pick-and-place.
78
+ - ChΖ°a biểu diα»…n sα»‘ lượng, thα»© tα»±, Δ‘iều kiện, vΓ²ng lαΊ·p, vΓΉng tΓΉy Γ½, orientation,
79
+ force, temporal constraint hoαΊ·c composite goal.
80
+ - VΓ­ dα»₯ cα»₯ thể cΓ³ thể bias model về sΓ‘u object thα»­ nghiệm.
81
+
82
+ **HΖ°α»›ng tα»•ng quΓ‘t**
83
+
84
+ - Goal AST/versioned schema: action intent, entity query, constraints, success
85
+ predicates vΓ  ambiguity set.
86
+ - Sinh schema tα»« capability registry cα»§a robot.
87
+ - Inject object catalog hiện tαΊ‘i tα»« scene thay vΓ¬ viαΊΏt object trong prompt.
88
+
89
+ ### BΖ°α»›c 3 β€” Semantic planner
90
+
91
+ **Hard-code nghiΓͺm trọng trong `llm_agent.py`**
92
+
93
+ - `ACTIONS`: chỉ `pick_up`, `move_to`, `place_down`, `clarify`, `reject`.
94
+ - Destination chỉ `table`, `tray`; `buffer` lΓ  location kα»Ή thuαΊ­t.
95
+ - Relation chỉ `next_to`, `left_of`, `right_of`, `front_of`, `behind`,
96
+ `on_top_of`.
97
+ - `SYSTEM_PROMPT` ghi trα»±c tiαΊΏp thuα»™c tΓ­nh cα»§a banana, pear, soup can, chips can,
98
+ tennis ball, clamp.
99
+ - Synonym map vΓ  examples ghi trα»±c tiαΊΏp sΓ‘u object.
100
+ - RuleBasedPlanner chα»©a danh sΓ‘ch Δ‘α»™ng tα»«, synonym, clear-table phrase vΓ  cΓ‘ch xα»­ lΓ½
101
+ riΓͺng cho table/tray.
102
+ - JSON schema dΓΉng enum action/location/relation Δ‘Γ³ng.
103
+
104
+ **Hệ quαΊ£**
105
+
106
+ - ThΓͺm object mα»›i trong JSON chΖ°a Δ‘α»§; LLM cΓ³ thể khΓ΄ng biαΊΏt alias/thuα»™c tΓ­nh.
107
+ - ThΓͺm skill mα»›i bαΊ―t buα»™c sα»­a prompt, schema, validator, executor, monitor vΓ  UI.
108
+ - KhΓ΄ng thể mở cα»­a, Δ‘αΊ©y, xoay, rΓ³t, lau, sα»­ dα»₯ng dα»₯ng cα»₯ hoαΊ·c thao tΓ‘c hai tay.
109
+
110
+ **HΖ°α»›ng tα»•ng quΓ‘t**
111
+
112
+ - `CapabilityRegistry`: mα»—i skill tα»± cΓ΄ng bα»‘ JSON schema, precondition, effect vΓ 
113
+ verifier.
114
+ - Prompt/tool schema được sinh Δ‘α»™ng tα»« registry.
115
+ - Object properties lαΊ₯y tα»« environment metadata/perception.
116
+ - Planner trαΊ£ skill calls dα»±a trΓͺn capability hiện cΓ³, khΓ΄ng dα»±a vΓ o enum viαΊΏt tay.
117
+
118
+ ### BΖ°α»›c 4 β€” Plan validation vΓ  obstacle normalization
119
+
120
+ **Hiện tαΊ‘i**
121
+
122
+ - `PlanVerifier` chỉ hiểu pick/move/place vΓ  location table/tray/buffer.
123
+ - Obstacle graph giαΊ£ Δ‘α»‹nh blocker phαΊ£i được dời sang table.
124
+ - Deadlock cycle được giαΊ£i bαΊ±ng side grasp trα»±c tiαΊΏp.
125
+ - Mα»™t gripper, giα»― tα»‘i Δ‘a mα»™t vαΊ­t.
126
+
127
+ **Giα»›i hαΊ‘n**
128
+
129
+ - Policy clear blocker tα»‘i Ζ°u cho tabletop pick-and-place.
130
+ - KhΓ΄ng search nhiều chiαΊΏn lược: Δ‘α»•i grasp, Δ‘α»•i thα»© tα»±, Δ‘α»•i buffer/surface, Δ‘αΊ©y vαΊ­t,
131
+ hoαΊ·c yΓͺu cαΊ§u người hα»— trợ.
132
+ - KhΓ΄ng cΓ³ symbolic precondition/effect checker tα»•ng quΓ‘t.
133
+
134
+ **HΖ°α»›ng tα»•ng quΓ‘t**
135
+
136
+ - Validator đọc precondition/effect tα»« skill registry.
137
+ - Task-and-motion planning tìm kiếm nhiều strategy và cost.
138
+ - Buffer allocator lΓ m việc trΓͺn danh sΓ‘ch support surface Δ‘α»™ng.
139
+
140
+ ### BΖ°α»›c 5 β€” Scene representation
141
+
142
+ **Hard-code trong `SceneManager`/config**
143
+
144
+ - Location chỉ `table`, `tray`, `elsewhere`.
145
+ - Scene cΓ³ Δ‘ΓΊng mα»™t table vΓ  mα»™t tray.
146
+ - Quan hệ khΓ΄ng gian lΓ  mα»™t tαΊ­p sΓ‘u relation cα»‘ Δ‘α»‹nh.
147
+ - Quy Ζ°α»›c +Y=left, -X=front gαΊ―n vα»›i robot/table hiện tαΊ‘i.
148
+ - CΓ‘c ngΖ°α»‘ng location, neighbor, blocker, stack vΓ  overlap được hiệu chỉnh theo
149
+ desktop scene hiện tαΊ‘i.
150
+ - Scene state khΓ΄ng chα»©a semantic properties tα»•ng quΓ‘t tα»« file mΓ΄i trường.
151
+
152
+ **HΖ°α»›ng tα»•ng quΓ‘t**
153
+
154
+ - Scene graph cΓ³ danh sΓ‘ch surface/container/region Δ‘α»™ng.
155
+ - Relation registry vΓ  coordinate frame được khai bΓ‘o theo workspace.
156
+ - Object metadata: aliases, category, material, affordances, graspability, support
157
+ surfaces.
158
+ - NgΖ°α»‘ng theo kΓ­ch thΖ°α»›c object/uncertainty thay vΓ¬ mα»™t hαΊ±ng sα»‘ toΓ n cα»₯c.
159
+
160
+ ### BΖ°α»›c 6 β€” Spawn vΓ  environment
161
+
162
+ **Hiện tαΊ‘i**
163
+
164
+ - Object list trong `envs/*.json` lΓ  data-driven, Δ‘Γ’y lΓ  Δ‘iểm tα»‘t.
165
+ - NhΖ°ng environment schema vαΊ«n bαΊ―t buα»™c table + tray.
166
+ - Spawn fallback cΓ³ sΓ‘u tọa Δ‘α»™, khoαΊ£ng cΓ‘ch 0.11 m, tα»‘i Δ‘a 100 lαΊ§n thα»­.
167
+ - Loader gαΊ―n vα»›i YCB folder.
168
+
169
+ **HΖ°α»›ng tα»•ng quΓ‘t**
170
+
171
+ - Environment schema khai bΓ‘o arbitrary static bodies, articulated bodies,
172
+ surfaces, containers vΓ  semantic regions.
173
+ - Collision-aware sampler dα»±a trΓͺn footprint.
174
+ - Asset adapter cho YCB/URDF/MJCF/mesh thay vì một loader.
175
+
176
+ ### BΖ°α»›c 7 β€” Grasp planning
177
+
178
+ **Hard-code**
179
+
180
+ - Grasp database cΓ³ class cube/cylinder/can/box/chips/banana/ball/pear/clamp.
181
+ - Fallback luΓ΄n top-down tαΊ‘i tΓ’m AABB.
182
+ - Chỉ cΓ³ top-down vΓ  mα»™t side-grasp tilt cα»‘ Δ‘α»‹nh.
183
+ - Mesh orientation bα»‹ rΓΊt cΓ²n yaw để cα»©u cΓ‘c case tipped object.
184
+ - Side grasp trigger, tilt, pre-distance vΓ  height được tune cho bα»™ vαΊ­t hiện tαΊ‘i.
185
+
186
+ **Hệ quαΊ£**
187
+
188
+ - Object mα»›i vαΊ«n chαΊ‘y nhΖ°ng chαΊ₯t lượng phα»₯ thuα»™c AABB fallback.
189
+ - VαΊ­t lΓ΅m, cΓ³ tay cαΊ§m, dα»… vα»‘, mềm hoαΊ·c cαΊ§n orientation cα»₯ thể khΓ΄ng được xα»­ lΓ½ Δ‘ΓΊng.
190
+
191
+ **HΖ°α»›ng tα»•ng quΓ‘t**
192
+
193
+ - Sinh nhiều grasp candidate từ geometry/point cloud/affordance.
194
+ - Collision checking + IK + force closure để xαΊΏp hαΊ‘ng.
195
+ - Grasp policy theo object metadata, khΓ΄ng theo tΓͺn class cα»‘ Δ‘α»‹nh.
196
+
197
+ ### BΖ°α»›c 8 β€” Placement
198
+
199
+ **Hard-code**
200
+
201
+ - Chỉ Δ‘αΊ·t trΓͺn table/tray/buffer.
202
+ - `on_top_of` Δ‘αΊ·t thαΊ³ng tΓ’m reference.
203
+ - Footprint bα»‹ cap ở 0.115 m.
204
+ - Margin thα»­ theo chuα»—i cα»‘ Δ‘α»‹nh: configured, 1 cm, 0.
205
+ - `TRAY_CLASS_OFFSET_X` cΓ³ offset riΓͺng cho sΓ‘u class khi fallback.
206
+ - NαΊΏu thαΊ₯t bαΊ‘i cuα»‘i cΓΉng Δ‘αΊ·t vΓ o table center hoαΊ·c class offset.
207
+
208
+ **Rα»§i ro**
209
+
210
+ - Object mα»›i dΓΉng offset 0, dα»… chα»“ng nhau.
211
+ - VαΊ­t lα»›n bα»‹ thu footprint giαΊ£ tαΊ‘o.
212
+ - Best-effort cΓ³ thể chọn vα»‹ trΓ­ overlap thay vΓ¬ tα»« chα»‘i.
213
+
214
+ **HΖ°α»›ng tα»•ng quΓ‘t**
215
+
216
+ - Support-surface sampler Δ‘α»™ng theo geometry thαΊ­t.
217
+ - Stable placement/orientation sampling.
218
+ - KhΓ΄ng dΓΉng class offset; dΓΉng optimization vΓ  explicit failure.
219
+
220
+ ### BΖ°α»›c 9 β€” Motion planning
221
+
222
+ **Hard-code/giαΊ£ Δ‘α»‹nh**
223
+
224
+ - Global cost map 2D cho union cα»§a table vΓ  tray.
225
+ - A* grid 100Γ—100, heuristic weight 1.2, inflation cα»‘ Δ‘α»‹nh.
226
+ - U-shaped lift-horizontal-lower trajectory.
227
+ - Safe Z, reach margin, lift height vΓ  clearance cα»‘ Δ‘α»‹nh.
228
+ - Panda rest pose vΓ  workspace hiện tαΊ‘i được tune thα»§ cΓ΄ng.
229
+
230
+ **Hệ quαΊ£**
231
+
232
+ - KhΓ΄ng tα»•ng quΓ‘t cho shelf, drawer, khΓ΄ng gian 3D chαΊ­t, obstacle chuyển Δ‘α»™ng hoαΊ·c
233
+ robot khΓ‘c.
234
+
235
+ **HΖ°α»›ng tα»•ng quΓ‘t**
236
+
237
+ - Robot/workspace profile.
238
+ - Sampling-based hoαΊ·c optimization-based 3D motion planner vα»›i collision scene.
239
+ - Adaptive clearance theo carried geometry vΓ  uncertainty.
240
+
241
+ ### BΖ°α»›c 10 β€” Robot controller/phαΊ§n cα»©ng
242
+
243
+ **BαΊ₯t biαΊΏn hợp lΓ½ nhΖ°ng Δ‘ang gαΊ―n chαΊ·t**
244
+
245
+ - Panda 7 joint, hai finger, mα»™t end effector.
246
+ - Joint indices, force, home pose, URDF vΓ  kinematic assumptions.
247
+ - Frontend cΓ³ Δ‘oαΊ‘n chỉ lαΊ₯y 7 joint.
248
+
249
+ **HΖ°α»›ng tα»•ng quΓ‘t**
250
+
251
+ - `RobotModelAdapter` đọc URDF/SRDF vΓ  capability.
252
+ - Controller plugin theo robot.
253
+ - UI render sα»‘ joint Δ‘α»™ng.
254
+
255
+ ĐÒy lΓ  giα»›i hαΊ‘n phαΊ§n cα»©ng, khΓ΄ng nΓͺn giao cho LLM tα»± reasoning để thay thαΊΏ.
256
+
257
+ ### BΖ°α»›c 11 β€” Execution monitor vΓ  Goal Check
258
+
259
+ **Hard-code**
260
+
261
+ - Step verifier chỉ hiểu ba physical actions.
262
+ - Goal predicate chỉ `carried_object_is`, `location_is`, `relation_is`.
263
+ - Tolerance XY 0.12 m, lift 0.05 m, fall threshold 0.10 m.
264
+ - `next_to` dΓΉng threshold 0.20 m hoαΊ·c 1.5Γ— gap.
265
+ - `on_top_of` dΓΉng AABB tolerance tune cho object hiện tαΊ‘i.
266
+ - Re-plan mαΊ·c Δ‘α»‹nh 3.
267
+
268
+ **HΖ°α»›ng tα»•ng quΓ‘t**
269
+
270
+ - Mα»—i skill cung cαΊ₯p verifier vΓ  telemetry riΓͺng.
271
+ - Predicate plugin/scene-query language.
272
+ - Tolerance theo object, skill vΓ  sensor uncertainty.
273
+
274
+ ### BΖ°α»›c 12 β€” UI, log vΓ  scoring
275
+
276
+ **Hard-code**
277
+
278
+ - TΓͺn Việt/Anh cα»§a sΓ‘u object được lαΊ·p trong Python vΓ  JavaScript.
279
+ - UI mΓ΄ tαΊ£ sΓ‘u relation bαΊ±ng chuα»—i `if/else`.
280
+ - Scoring Web chỉ tΓ¬m target object/location cuα»‘i trong plan.
281
+ - Điểm cα»‘ Δ‘α»‹nh: target 50, knock 15, no-knock 30, execution 20/30.
282
+ - Success threshold 50.
283
+
284
+ **Hệ quαΊ£**
285
+
286
+ - Multi-object/category/composite task được chαΊ₯m sai hoαΊ·c thiαΊΏu.
287
+ - Object/skill mα»›i hiển thα»‹ tΓͺn kα»Ή thuαΊ­t.
288
+
289
+ **HΖ°α»›ng tα»•ng quΓ‘t**
290
+
291
+ - UI metadata lαΊ₯y tα»« scene/capability registry.
292
+ - Scoring theo resolved-goal predicates vΓ  execution metrics, khΓ΄ng parse plan cuα»‘i.
293
+
294
+ ### BΖ°α»›c 13 β€” Multi-user vΓ  deployment
295
+
296
+ **Giα»›i hαΊ‘n**
297
+
298
+ - Conversation memory tΓ‘ch theo WebSocket nhΖ°ng simulation lΓ  `current_sim` global.
299
+ - Nhiều user cΓ³ thể khΓ΄ng cΓ³ world state Δ‘α»™c lαΊ­p.
300
+ - Memory chỉ trong process; restart mαΊ₯t.
301
+
302
+ **HΖ°α»›ng tα»•ng quΓ‘t**
303
+
304
+ - Session owns simulation instance hoαΊ·c job queue/lease rΓ΅ rΓ ng.
305
+ - Optional persistent conversation store vα»›i TTL vΓ  privacy policy.
306
+
307
+ ## 3. Nhα»―ng phαΊ§n Δ‘Γ£ data-driven hoαΊ·c cΓ³ fallback tα»‘t
308
+
309
+ - Danh sΓ‘ch object vΓ  pose cΓ³ thể khai bΓ‘o trong environment JSON.
310
+ - Grasp database nαΊ±m trong JSON vΓ  cΓ³ AABB fallback.
311
+ - Table/tray dimensions đọc tα»« environment.
312
+ - Occupancy grid dΓΉng footprint hΓ¬nh học thay vΓ¬ slot cα»‘ Δ‘α»‹nh.
313
+ - Obstacle graph lαΊ₯y tα»« scene geometry.
314
+ - Conversation vΓ  goal state tΓ‘ch theo session.
315
+ - Feature flags cho memory, goal resolution vΓ  structured goal check.
316
+
317
+ CΓ‘c phαΊ§n nΓ y lΓ  nền tα»‘t, nhΖ°ng chΖ°a Δ‘α»§ để gọi hệ thα»‘ng lΓ  domain-general.
318
+
319
+ ## 4. KiαΊΏn trΓΊc Δ‘Γ­ch đề xuαΊ₯t
320
+
321
+ ```text
322
+ Environment/Perception
323
+ β†’ Dynamic Scene Graph + Object Metadata
324
+ β†’ LLM Goal Resolver β†’ versioned Goal AST
325
+ β†’ Capability Registry β†’ dynamic tool schemas
326
+ β†’ Task-and-Motion Planner
327
+ β†’ Skill plugins
328
+ β”œβ”€ preconditions/effects
329
+ β”œβ”€ motion/grasp/placement policy
330
+ └─ verifier
331
+ β†’ Predicate-based Goal Monitor
332
+ β†’ UI/Scoring generated from the same metadata
333
+ ```
334
+
335
+ NguyΓͺn tαΊ―c: LLM reasoning về Γ½ Δ‘α»‹nh vΓ  lα»±a chọn capability; geometry, safety,
336
+ kinematics vΓ  success verification vαΊ«n phαΊ£i deterministic.
337
+
338
+ ## 5. Lα»™ trΓ¬nh tα»•ng quΓ‘t hΓ³a theo Ζ°u tiΓͺn
339
+
340
+ ### Phase G1 β€” Dynamic semantic catalog
341
+
342
+ - Chuyển object properties/aliases ra environment metadata. **Đã hoΓ n thΓ nh.**
343
+ - Sinh prompt từ scene. **Đã hoàn thành.**
344
+ - XΓ³a map tΓͺn object lαΊ·p ở UI/server.
345
+
346
+ ### Phase G2 β€” Capability registry
347
+
348
+ - TÑch action schema khỏi `llm_agent.py`.
349
+ - Planner tools, validator, executor vΓ  monitor đọc cΓΉng registry.
350
+ - Giα»― ba skill hiện tαΊ‘i dΖ°α»›i dαΊ‘ng plugin để tΖ°Ζ‘ng thΓ­ch.
351
+
352
+ ### Phase G3 β€” Dynamic scene graph
353
+
354
+ - Nhiều surface/container/region.
355
+ - Location/relation registry vΓ  frame semantics Δ‘α»™ng.
356
+ - Bỏ giαΊ£ Δ‘α»‹nh table/tray trong cost map vΓ  placement.
357
+
358
+ ### Phase G4 β€” General grasp/place
359
+
360
+ - Multi-candidate grasp generation vΓ  ranking.
361
+ - Stable placement sampling theo geometry.
362
+ - LoαΊ‘i `TRAY_CLASS_OFFSET_X` vΓ  footprint cap.
363
+
364
+ ### Phase G5 β€” General task-and-motion planning
365
+
366
+ - Search strategy, 3D collision-aware planning.
367
+ - Composite goals, ordering, quantities vΓ  conditional tasks.
368
+
369
+ ### Phase G6 β€” Evaluation vΓ  multi-user
370
+
371
+ - ChαΊ₯m theo Goal AST/predicates.
372
+ - Session-isolated simulations.
373
+ - Bα»™ benchmark cΓ³ unseen objects, unseen wording vΓ  unseen layouts.
374
+
375
+ ## 6. TiΓͺu chΓ­ để chα»©ng minh tΓ­nh tα»•ng quΓ‘t
376
+
377
+ - ThΓͺm object mα»›i chỉ bαΊ±ng asset + metadata, khΓ΄ng sα»­a Python/JS/prompt.
378
+ - ThΓͺm skill mα»›i bαΊ±ng plugin, khΓ΄ng sα»­a planner core/executor dispatcher.
379
+ - ThΓͺm surface mα»›i khΓ΄ng sα»­a location enum.
380
+ - CΓ’u lệnh dΓΉng Δ‘α»™ng tα»« chΖ°a tα»«ng cΓ³ vαΊ«n được Goal Resolver hiểu hoαΊ·c hỏi lαΊ‘i Δ‘ΓΊng.
381
+ - Benchmark tΓ‘ch train-like vΓ  unseen wording/object/layout.
382
+ - KhΓ΄ng dΓΉng object name cα»₯ thể trong core prompt hoαΊ·c core control logic.
docs/WEB_RUNTIME_INTERRUPTION_PLAN.md ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Web runtime persistence vΓ  interrupt/re-plan
2
+
3
+ ## TrαΊ‘ng thΓ‘i
4
+
5
+ Đã triển khai Δ‘α»§ bα»‘n phase ngΓ y 2026-07-04.
6
+
7
+ ## Mα»₯c tiΓͺu
8
+
9
+ 1. Reload/reconnect trΓ¬nh duyệt khΓ΄ng reset PyBullet, robot, object, conversation,
10
+ plan, log hoαΊ·c task Δ‘ang chαΊ‘y.
11
+ 2. Người dΓΉng cΓ³ thể gα»­i prompt mα»›i khi robot Δ‘ang thα»±c thi. Task cΕ© dα»«ng
12
+ cooperative tαΊ‘i checkpoint gαΊ§n nhαΊ₯t, giα»― pose/gripper/object, rα»“i task mα»›i
13
+ lαΊ­p kαΊΏ hoαΊ‘ch tα»« live scene.
14
+
15
+ ## KiαΊΏn trΓΊc
16
+
17
+ ### Server-owned runtime
18
+
19
+ `frontend.web_runtime.WebRuntime` sα»‘ng Δ‘α»™c lαΊ­p vα»›i WebSocket vΓ  sở hα»―u:
20
+
21
+ - `ConversationManager`;
22
+ - active/pending command;
23
+ - generation vΓ  cancellation token;
24
+ - execution state;
25
+ - latest init/state/plan/result;
26
+ - event journal cΓ³ sequence;
27
+ - tαΊ­p WebSocket subscriber.
28
+
29
+ PyBullet vαΊ«n lΓ  nguα»“n sα»± thαΊ­t vαΊ­t lΓ½ duy nhαΊ₯t. Runtime khΓ΄ng ghi Δ‘Γ¨ pose tα»« dα»―
30
+ liệu trΓ¬nh duyệt.
31
+
32
+ ### Task lifecycle
33
+
34
+ CΓ‘c trαΊ‘ng thΓ‘i chΓ­nh:
35
+
36
+ ```text
37
+ idle -> planning -> executing -> completed
38
+ |
39
+ -> interrupt_requested -> interrupted -> planning
40
+ ```
41
+
42
+ Re-plan nα»™i bα»™ dΓΉng trαΊ‘ng thΓ‘i `replanning`.
43
+
44
+ Command chΖ°a chαΊ‘y dΓΉng chΓ­nh sΓ‘ch latest-wins. Mα»—i command cΓ³ `task_id` vΓ 
45
+ `generation`; plan/result/log cΕ© khΓ΄ng được phΓ©p ghi Δ‘Γ¨ task mα»›i.
46
+
47
+ ### Cooperative cancellation
48
+
49
+ `CancellationToken` được kiểm tra:
50
+
51
+ - trΖ°α»›c command/step;
52
+ - trΖ°α»›c vΓ  sau planning;
53
+ - giα»―a cΓ‘c waypoint;
54
+ - trong joint interpolation;
55
+ - trong catch-up vΓ  settle loop;
56
+ - trong simulation streaming hook.
57
+
58
+ `ExecutionInterrupted` unwind về runtime. Controller gọi `hold_current_pose()`,
59
+ khΓ΄ng home/recover vΓ  khΓ΄ng thΓ‘o grasp constraint.
60
+
61
+ ### Reload/reconnect
62
+
63
+ Frontend giα»― `client_id` vΓ  event sequence trong `localStorage`. Khi reconnect:
64
+
65
+ - server không gọi `reset_objects()` hoặc `reset_to_home()`;
66
+ - static init dΓΉng cache;
67
+ - dynamic pose lαΊ₯y tα»« latest server state;
68
+ - runtime snapshot phα»₯c hα»“i log, plan, result, pipeline state vΓ  pending
69
+ conversation;
70
+ - execution tiαΊΏp tα»₯c phΓ‘t sα»± kiện qua subscriber mα»›i.
71
+
72
+ ### NΓΊt gα»­i/dα»«ng
73
+
74
+ - Khi runtime idle/completed/interrupted, nΓΊt hiển thα»‹ icon gα»­i.
75
+ - Khi planning/executing/replanning/interrupt-requested, nΓΊt hiển thα»‹ stop square
76
+ vα»›i vΓ²ng quay trαΊ‘ng thΓ‘i.
77
+ - Γ” nhαΊ­p vΓ  Enter luΓ΄n hoαΊ‘t Δ‘α»™ng:
78
+ - click nΓΊt trαΊ‘ng thΓ‘i gα»­i `cancel`;
79
+ - Enter trong Γ΄ cΓ³ nα»™i dung gα»­i command mα»›i, lΓ m task cΕ© bα»‹ supersede rα»“i
80
+ re-plan tα»« live state.
81
+ - `title` vΓ  `aria-label` Δ‘α»•i theo mode để hα»— trợ keyboard/screen reader.
82
+
83
+ ### Reset/change environment
84
+
85
+ Hai thao tÑc này gọi `cancel_all()`, xóa pending command và chờ active task xÑc
86
+ nhαΊ­n dα»«ng. NαΊΏu timeout, scene mutation bα»‹ tα»« chα»‘i. KhΓ΄ng reset/Δ‘α»•i environment
87
+ song song vα»›i chuyển Δ‘α»™ng.
88
+
89
+ ## WebSocket messages
90
+
91
+ Client gα»­i:
92
+
93
+ ```json
94
+ {"type": "run", "prompt": "...", "mock": false}
95
+ {"type": "cancel"}
96
+ {"type": "reset"}
97
+ {"type": "change_env", "env": "..."}
98
+ ```
99
+
100
+ Server phΓ‘t:
101
+
102
+ ```json
103
+ {"type": "runtime_snapshot"}
104
+ {"type": "command_accepted", "task_id": "...", "generation": 2}
105
+ {"type": "execution_status", "state": "executing"}
106
+ {"type": "interrupt_requested"}
107
+ {"type": "interrupted"}
108
+ ```
109
+
110
+ CΓ‘c event task cΓ³ `task_id`, `generation`; event journal cΓ³ thΓͺm `seq`.
111
+
112
+ ## Giα»›i hαΊ‘n
113
+
114
+ - Runtime tα»“n tαΊ‘i trong memory cα»§a process server. Restart backend vαΊ«n tαΊ‘o lαΊ‘i
115
+ PyBullet scene; persistence qua process restart chΖ°a nαΊ±m trong yΓͺu cαΊ§u nΓ y.
116
+ - DΓΉng mα»™t shared simulation runtime, phΓΉ hợp kiαΊΏn trΓΊc `current_sim` hiện tαΊ‘i.
117
+ Multi-tenant simulation isolation lΓ  scope riΓͺng.
envs/default_desk.json CHANGED
@@ -1,4 +1,5 @@
1
  {
 
2
  "robot": {
3
  "urdf": "franka_panda/panda.urdf",
4
  "base_position": [0.0, 0.0, 0.08],
 
1
  {
2
+ "semantic_catalog": "default_desk.semantics.json",
3
  "robot": {
4
  "urdf": "franka_panda/panda.urdf",
5
  "base_position": [0.0, 0.0, 0.08],
envs/default_desk.semantics.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "environment_id": "default_desk",
4
+ "description": "Default Franka Panda desk. Object semantics are available for scenarios that populate this workspace.",
5
+ "surfaces": {
6
+ "table": {
7
+ "display_name": {"vi": "bΓ n", "en": "table"},
8
+ "aliases": ["bΓ n", "mαΊ·t bΓ n", "table"],
9
+ "kind": "support_surface"
10
+ },
11
+ "tray": {
12
+ "display_name": {"vi": "khay", "en": "tray"},
13
+ "aliases": ["khay", "khay chα»©a", "tray"],
14
+ "kind": "container_surface"
15
+ }
16
+ },
17
+ "objects": {}
18
+ }
envs/env1.json CHANGED
@@ -1,4 +1,5 @@
1
  {
 
2
  "robot": {
3
  "urdf": "franka_panda/panda.urdf",
4
  "base_position": [0.0, 0.0, 0.08],
 
1
  {
2
+ "semantic_catalog": "env1.semantics.json",
3
  "robot": {
4
  "urdf": "franka_panda/panda.urdf",
5
  "base_position": [0.0, 0.0, 0.08],
envs/env1.semantics.json ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "environment_id": "env1",
4
+ "description": "Franka Panda tabletop workspace with one table, one tray, and six manipulable YCB objects.",
5
+ "surfaces": {
6
+ "table": {
7
+ "display_name": {"vi": "bΓ n", "en": "table"},
8
+ "aliases": ["bΓ n", "mαΊ·t bΓ n", "table"],
9
+ "kind": "support_surface"
10
+ },
11
+ "tray": {
12
+ "display_name": {"vi": "khay", "en": "tray"},
13
+ "aliases": ["khay", "khay chα»©a", "tray"],
14
+ "kind": "container_surface"
15
+ }
16
+ },
17
+ "objects": {
18
+ "banana": {
19
+ "display_name": {"vi": "quαΊ£ chuα»‘i", "en": "banana"},
20
+ "aliases": ["chuα»‘i", "quαΊ£ chuα»‘i", "trΓ‘i chuα»‘i", "banana"],
21
+ "categories": ["fruit", "food", "edible"],
22
+ "attributes": {
23
+ "color": ["yellow"],
24
+ "material": ["organic", "non-metal"],
25
+ "weight": "light"
26
+ },
27
+ "affordances": ["pickable", "placeable", "stackable"]
28
+ },
29
+ "pear": {
30
+ "display_name": {"vi": "quαΊ£ lΓͺ", "en": "pear"},
31
+ "aliases": ["lΓͺ", "quαΊ£ lΓͺ", "trΓ‘i lΓͺ", "pear"],
32
+ "categories": ["fruit", "food", "edible"],
33
+ "attributes": {
34
+ "color": ["yellow-green"],
35
+ "material": ["organic", "non-metal"],
36
+ "weight": "light"
37
+ },
38
+ "affordances": ["pickable", "placeable", "stackable"]
39
+ },
40
+ "soup_can": {
41
+ "display_name": {"vi": "lon sΓΊp", "en": "soup can"},
42
+ "aliases": ["sΓΊp", "canh", "hα»™p sΓΊp", "lon sΓΊp", "soup can"],
43
+ "categories": ["can", "food", "edible"],
44
+ "attributes": {
45
+ "contents": ["soup"],
46
+ "material": ["metal"],
47
+ "weight": "heavy"
48
+ },
49
+ "affordances": ["pickable", "placeable", "support_surface"]
50
+ },
51
+ "chips_can": {
52
+ "display_name": {"vi": "lon chips", "en": "chips can"},
53
+ "aliases": ["chips", "chip", "snack", "bim bim", "lon chip", "lon chips", "chips can"],
54
+ "categories": ["can", "snack", "food", "edible"],
55
+ "attributes": {
56
+ "contents": ["chips"],
57
+ "material": ["metal", "cardboard"],
58
+ "weight": "light"
59
+ },
60
+ "affordances": ["pickable", "placeable", "support_surface"]
61
+ },
62
+ "tennis_ball": {
63
+ "display_name": {"vi": "quαΊ£ bΓ³ng tennis", "en": "tennis ball"},
64
+ "aliases": ["bΓ³ng", "quαΊ£ bΓ³ng", "tennis", "bΓ³ng tennis", "tennis ball"],
65
+ "categories": ["ball", "sports equipment", "non-food"],
66
+ "attributes": {
67
+ "material": ["felt", "rubber", "non-metal"],
68
+ "weight": "light"
69
+ },
70
+ "affordances": ["pickable", "placeable", "rollable"]
71
+ },
72
+ "clamp": {
73
+ "display_name": {"vi": "chiαΊΏc kαΊΉp", "en": "clamp"},
74
+ "aliases": ["kẹp", "cÑi kẹp", "kìm", "cÑi kìm", "clamp"],
75
+ "categories": ["tool", "non-food"],
76
+ "attributes": {
77
+ "material": ["steel", "metal"],
78
+ "weight": "heavy"
79
+ },
80
+ "affordances": ["pickable", "placeable"]
81
+ }
82
+ }
83
+ }
envs/scenarios/scenario_1.json CHANGED
@@ -1,4 +1,5 @@
1
  {
 
2
  "objects": [
3
  {
4
  "name": "banana",
 
1
  {
2
+ "semantic_catalog": "../env1.semantics.json",
3
  "objects": [
4
  {
5
  "name": "banana",
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
@@ -6,13 +6,19 @@ let robotGroup, tableMesh, trayMesh;
6
  const slotHelpers = [];
7
  const joints = {};
8
  const ycbMeshes = {};
9
- let isDragging = false;
10
- let dragPlane = new THREE.Plane();
11
- let eeDummy = null;
 
12
  const OBJ_LOADER = new THREE.OBJLoader();
13
  const MTL_LOADER = new THREE.MTLLoader();
14
- let socket = null;
15
- let currentPrompt = '';
 
 
 
 
 
16
  function initVisualizer() {
17
  // Set default coordinate system to Z-up
18
  THREE.Object3D.DefaultUp.set(0, 0, 1);
@@ -168,13 +174,14 @@ function animate() {
168
  }
169
 
170
  // Align eeDummy position to handJoint if not being dragged
171
- if (eeDummy && joints.handJoint) {
172
  const handWorldPos = new THREE.Vector3();
173
  joints.handJoint.getWorldPosition(handWorldPos);
174
- eeDummy.position.copy(handWorldPos);
175
- }
176
-
177
- renderer.render(scene, camera);
 
178
  }
179
  // Window resizing
180
  window.addEventListener('resize', () => {
@@ -187,14 +194,15 @@ window.addEventListener('resize', () => {
187
  }
188
  });
189
  // ─── Three.js Scene Construction ────────────────────────────────────────────
190
- function createTable(tableConfig) {
191
  if (tableMesh) scene.remove(tableMesh);
192
  const ext = tableConfig.half_extents;
193
  const geo = new THREE.BoxGeometry(ext[0] * 2, ext[1] * 2, ext[2] * 2);
194
  const color = new THREE.Color().fromArray(tableConfig.color.slice(0, 3));
195
  const mat = new THREE.MeshStandardMaterial({ color: color, roughness: 0.6, metalness: 0.1 });
196
  tableMesh = new THREE.Mesh(geo, mat);
197
- tableMesh.position.set(tableConfig.center[0], tableConfig.center[1], tableConfig.center[2]);
 
198
  tableMesh.castShadow = true;
199
  tableMesh.receiveShadow = true;
200
  scene.add(tableMesh);
@@ -376,55 +384,78 @@ function initRobotStructure() {
376
  eeDummy.visible = false;
377
  scene.add(eeDummy);
378
  }
379
- function loadYcbObjects(objectsConfig) {
380
- // Clear old meshes/groups from scene
381
- Object.values(ycbMeshes).forEach(group => scene.remove(group));
382
- for (const key in ycbMeshes) delete ycbMeshes[key];
383
-
384
- Object.entries(objectsConfig).forEach(([name, config]) => {
385
- const folder = config.folder;
386
- let objFile = config.web_obj ? `/assets/ycb/${folder}/${config.web_obj}` : "";
387
- let mtlFile = config.web_mtl ? `/assets/ycb/${folder}/${config.web_mtl}` : "";
388
-
389
- if (!objFile) return;
390
- // Create a parent group to represent the object's body link pose
391
- const objectGroup = new THREE.Group();
392
- objectGroup.name = name;
393
- objectGroup.position.fromArray(config.initial_pos);
394
- objectGroup.quaternion.fromArray(config.initial_ori);
395
- scene.add(objectGroup);
396
- ycbMeshes[name] = objectGroup;
397
- // 1. Load Visual Mesh
398
- MTL_LOADER.load(mtlFile, (materials) => {
399
- materials.preload();
400
-
401
- const objLoader = new THREE.OBJLoader();
402
- objLoader.setMaterials(materials);
403
- objLoader.load(objFile, (visObj) => {
404
- visObj.traverse(child => {
405
- if (child.isMesh) {
406
- child.castShadow = true;
407
- child.receiveShadow = true;
408
- if (child.material) {
409
- const mats = Array.isArray(child.material) ? child.material : [child.material];
410
- mats.forEach(m => {
411
- if (m.map) m.color.setHex(0xffffff);
412
- });
413
- }
414
- }
415
- });
416
-
417
- // Position, rotate and scale relative to parent group
418
- if (config.vis_local_pos) visObj.position.fromArray(config.vis_local_pos);
419
- if (config.vis_local_ori) visObj.quaternion.fromArray(config.vis_local_ori);
420
- if (config.vis_scale) visObj.scale.fromArray(config.vis_scale);
421
-
422
- objectGroup.add(visObj);
423
- });
424
- });
425
- // Removed collision mesh loading per user request
426
- });
427
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
428
  function updateSimulationState(jointsData, objectsData) {
429
  if (jointsData && jointsData.length >= 11) {
430
  targetJoints = jointsData;
@@ -446,7 +477,7 @@ function connectWebSocket() {
446
  reconnectTimeout = null;
447
  }
448
  const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
449
- const wsUrl = `${wsProtocol}//${window.location.host}/ws?gui=false`;
450
 
451
  updateBadgeStatus('disconnected');
452
 
@@ -455,9 +486,15 @@ function connectWebSocket() {
455
  console.log("WebSocket connected.");
456
  updateBadgeStatus('connected');
457
  };
458
- socket.onmessage = (event) => {
459
- const msg = JSON.parse(event.data);
460
- handleSocketMessage(msg);
 
 
 
 
 
 
461
  };
462
  socket.onclose = () => {
463
  console.log("WebSocket disconnected.");
@@ -469,9 +506,85 @@ function connectWebSocket() {
469
  console.error("WebSocket Error: ", err);
470
  };
471
  }
472
- function handleSocketMessage(msg) {
473
- switch(msg.type) {
474
- case 'env_list':
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
475
  const envSelect = document.getElementById('env-select');
476
  if (envSelect && msg.envs) {
477
  envSelect.innerHTML = msg.envs.map(env => `<option value="${env}">${env}</option>`).join('');
@@ -510,19 +623,17 @@ function handleSocketMessage(msg) {
510
  break;
511
 
512
  case 'result':
513
- unlockInput();
514
-
515
- // Clarifications and rejections are conversational turns, not
516
- // completed robot executions. Keep the input ready for the reply
517
- // and do not record a misleading failed run in analytics.
518
- if (msg.response_type === 'clarify' || msg.response_type === 'reject') {
519
  window.currentPlan = null;
520
  window.currentLlmTime = 0;
521
- chatInput.focus();
522
  break;
523
  }
524
-
525
- // Add new run record to history log dynamically
 
 
526
  const now = new Date();
527
  const timeStr = now.toTimeString().split(' ')[0];
528
 
@@ -633,9 +744,10 @@ function renderObjectsTable(catalogMap) {
633
  const rows = Object.entries(catalogMap).map(([name, config]) => {
634
  const displayName = objDict[name] || name;
635
  const imageUrl = `/static/thumbnails/${config.folder}.png?v=${new Date().getTime()}`;
636
- return `
637
- <tr>
638
- <td>
 
639
  <div style="width: 50px; height: 50px; overflow: hidden; border-radius: 8px; border: 1px solid #e2e8f0; display: flex; align-items: center; justify-content: center; background: #fff;">
640
  <img src="${imageUrl}" alt="${displayName}" style="max-width: 100%; max-height: 100%; object-fit: contain;">
641
  </div>
@@ -645,8 +757,25 @@ function renderObjectsTable(catalogMap) {
645
  `;
646
  });
647
 
648
- objectsTableBody.innerHTML = rows.join('');
649
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
650
  // 4. History Logs Data & Render
651
  const historyData = [];
652
 
@@ -1055,14 +1184,31 @@ function displayPlan(plan) {
1055
  });
1056
  }
1057
 
1058
- function lockInput() {
1059
- chatInput.disabled = true;
1060
- submitBtn.disabled = true;
1061
- resetBtn.disabled = true;
1062
- }
1063
- document.getElementById('chat-form').addEventListener('submit', (e) => {
1064
- e.preventDefault();
1065
- const prompt = chatInput.value.trim();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1066
  if (!prompt || !socket || socket.readyState !== WebSocket.OPEN) return;
1067
  currentPrompt = prompt;
1068
  chatInput.value = '';
@@ -1075,20 +1221,31 @@ document.getElementById('chat-form').addEventListener('submit', (e) => {
1075
  });
1076
  window.currentRunStartTime = Date.now();
1077
  writeLog(`Gα»­i yΓͺu cαΊ§u: "${prompt}"`, "info");
1078
- lockInput();
 
1079
 
1080
  speakFeedback("Start processing your command.");
1081
- socket.send(JSON.stringify({
1082
- type: 'run',
1083
  prompt: prompt,
1084
  mock: false
1085
  }));
1086
  });
1087
- function unlockInput() {
1088
- chatInput.disabled = false;
1089
- submitBtn.disabled = false;
1090
- resetBtn.disabled = false;
1091
- }
 
 
 
 
 
 
 
 
 
 
1092
  resetBtn.addEventListener('click', () => {
1093
  if (!socket || socket.readyState !== WebSocket.OPEN) return;
1094
 
@@ -1133,30 +1290,107 @@ slidersList.forEach(id => {
1133
  });
1134
  }
1135
  });
1136
- // 11. Interactive Drag and Drop for YCB objects and Robot End Effector using THREE.TransformControls
1137
- const raycaster = new THREE.Raycaster();
1138
- const mouse = new THREE.Vector2();
1139
- // State variables for Hover Highlight
1140
- let hoveredGroup = null;
1141
- canvas.addEventListener('mousedown', onMouseDown);
1142
- canvas.addEventListener('mousemove', onMouseMove);
1143
- // Helper to determine if an intersected object belongs to a draggable group (YCB or Robot)
1144
- function findDraggableTarget(hitObject) {
1145
- let curr = hitObject;
1146
- while (curr && curr !== scene) {
1147
- if (curr === robotGroup) {
1148
- return { type: 'robot', group: robotGroup, name: 'robot' };
1149
- }
1150
- const ycbEntry = Object.entries(ycbMeshes).find(([name, group]) => group === curr);
1151
- if (ycbEntry) {
1152
- return { type: 'ycb', group: ycbEntry[1], name: ycbEntry[0] };
1153
- }
1154
- curr = curr.parent;
1155
- }
1156
- return null;
1157
- }
1158
- // Helper to set/restore emissive highlight glow on all child meshes of a group
1159
- function highlightGroup(group, highlightColor = null) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1160
  if (!group) return;
1161
  group.traverse(child => {
1162
  if (child.isMesh) {
@@ -1180,109 +1414,165 @@ function highlightGroup(group, highlightColor = null) {
1180
  }
1181
  }
1182
  });
1183
- }
1184
- function onMouseDown(event) {
1185
- if (event.button !== 0 || chatInput.disabled) return;
1186
-
1187
- const rect = canvas.getBoundingClientRect();
1188
- mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
1189
- mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
1190
- raycaster.setFromCamera(mouse, camera);
1191
- const hits = raycaster.intersectObjects(scene.children, true);
1192
- let targetHit = null;
1193
-
1194
- for (let i = 0; i < hits.length; i++) {
1195
- const found = findDraggableTarget(hits[i].object);
1196
- if (found) {
1197
- targetHit = hits[i];
1198
- break;
1199
- }
1200
- }
1201
-
1202
- if (targetHit) {
1203
- isDragging = true;
1204
- controls.enabled = false;
1205
- dragPlane.setFromNormalAndCoplanarPoint(camera.getWorldDirection(new THREE.Vector3()), targetHit.point);
1206
-
1207
- if (socket && socket.readyState === WebSocket.OPEN) {
1208
- const rayTo = new THREE.Vector3().copy(raycaster.ray.origin).add(raycaster.ray.direction.clone().multiplyScalar(100));
1209
- socket.send(JSON.stringify({
1210
- type: 'mouse_pick_start',
1211
- rayFrom: [raycaster.ray.origin.x, raycaster.ray.origin.y, raycaster.ray.origin.z],
1212
- rayTo: [rayTo.x, rayTo.y, rayTo.z]
1213
- }));
1214
- }
1215
- }
1216
- }
1217
-
1218
- function onMouseMove(event) {
1219
- const rect = canvas.getBoundingClientRect();
1220
- mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
1221
- mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
1222
- raycaster.setFromCamera(mouse, camera);
1223
-
1224
- if (isDragging) {
1225
- const targetPos = new THREE.Vector3();
1226
- raycaster.ray.intersectPlane(dragPlane, targetPos);
1227
- if (targetPos && socket && socket.readyState === WebSocket.OPEN) {
1228
- socket.send(JSON.stringify({
1229
- type: 'mouse_pick_update',
1230
- targetPos: [targetPos.x, targetPos.y, targetPos.z]
1231
- }));
1232
- }
1233
- return;
1234
- }
1235
-
1236
- // Hover logic
1237
- const hits = raycaster.intersectObjects(scene.children, true);
1238
- let hoverTarget = null;
1239
-
1240
- for (let i = 0; i < hits.length; i++) {
1241
- const found = findDraggableTarget(hits[i].object);
1242
- if (found) {
1243
- hoverTarget = found;
1244
- break;
1245
- }
1246
- }
1247
-
1248
- if (hoverTarget) {
1249
- if (hoveredGroup !== hoverTarget.group) {
1250
- if (hoveredGroup) {
1251
- highlightGroup(hoveredGroup, null);
1252
- }
1253
- hoveredGroup = hoverTarget.group;
1254
- highlightGroup(hoveredGroup, 0x555555);
1255
- canvas.style.cursor = 'pointer';
1256
- }
1257
- } else {
1258
- if (hoveredGroup) {
1259
- highlightGroup(hoveredGroup, null);
1260
- hoveredGroup = null;
1261
- canvas.style.cursor = 'default';
1262
- }
1263
- }
1264
- }
1265
-
1266
- function onMouseUp(event) {
1267
- if (event.button !== 0) return;
1268
- if (isDragging) {
1269
- isDragging = false;
1270
- controls.enabled = true;
1271
- if (socket && socket.readyState === WebSocket.OPEN) {
1272
- socket.send(JSON.stringify({ type: 'mouse_pick_end' }));
1273
- }
1274
- }
1275
- }
1276
-
1277
- canvas.addEventListener('mouseleave', () => {
1278
- if (isDragging) {
1279
- isDragging = false;
1280
- controls.enabled = true;
1281
- if (socket && socket.readyState === WebSocket.OPEN) {
1282
- socket.send(JSON.stringify({ type: 'mouse_pick_end' }));
1283
- }
1284
- }
1285
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1286
 
1287
 
1288
  // Initialize
 
6
  const slotHelpers = [];
7
  const joints = {};
8
  const ycbMeshes = {};
9
+ let isDragging = false;
10
+ let dragPlane = new THREE.Plane();
11
+ let eeDummy = null;
12
+ let placementSurfaceZ = 0.3;
13
  const OBJ_LOADER = new THREE.OBJLoader();
14
  const MTL_LOADER = new THREE.MTLLoader();
15
+ let socket = null;
16
+ let currentPrompt = '';
17
+ const runtimeClientId = localStorage.getItem('llm-panda-client-id') || crypto.randomUUID();
18
+ localStorage.setItem('llm-panda-client-id', runtimeClientId);
19
+ let lastEventSeq = Number(localStorage.getItem('llm-panda-last-event-seq') || 0);
20
+ let activeGeneration = 0;
21
+ let executionState = 'idle';
22
  function initVisualizer() {
23
  // Set default coordinate system to Z-up
24
  THREE.Object3D.DefaultUp.set(0, 0, 1);
 
174
  }
175
 
176
  // Align eeDummy position to handJoint if not being dragged
177
+ if (eeDummy && joints.handJoint) {
178
  const handWorldPos = new THREE.Vector3();
179
  joints.handJoint.getWorldPosition(handWorldPos);
180
+ eeDummy.position.copy(handWorldPos);
181
+ }
182
+ updateObjectSelectionOverlay();
183
+
184
+ renderer.render(scene, camera);
185
  }
186
  // Window resizing
187
  window.addEventListener('resize', () => {
 
194
  }
195
  });
196
  // ─── Three.js Scene Construction ────────────────────────────────────────────
197
+ function createTable(tableConfig) {
198
  if (tableMesh) scene.remove(tableMesh);
199
  const ext = tableConfig.half_extents;
200
  const geo = new THREE.BoxGeometry(ext[0] * 2, ext[1] * 2, ext[2] * 2);
201
  const color = new THREE.Color().fromArray(tableConfig.color.slice(0, 3));
202
  const mat = new THREE.MeshStandardMaterial({ color: color, roughness: 0.6, metalness: 0.1 });
203
  tableMesh = new THREE.Mesh(geo, mat);
204
+ tableMesh.position.set(tableConfig.center[0], tableConfig.center[1], tableConfig.center[2]);
205
+ placementSurfaceZ = Number(tableConfig.top_z || 0.3);
206
  tableMesh.castShadow = true;
207
  tableMesh.receiveShadow = true;
208
  scene.add(tableMesh);
 
384
  eeDummy.visible = false;
385
  scene.add(eeDummy);
386
  }
387
+ function loadYcbObjects(objectsConfig) {
388
+ // Clear old meshes/groups from scene
389
+ Object.values(ycbMeshes).forEach(group => scene.remove(group));
390
+ for (const key in ycbMeshes) delete ycbMeshes[key];
391
+ clearObjectSelection();
392
+ Object.entries(objectsConfig).forEach(([name, config]) => {
393
+ addYcbObject(name, config);
394
+ });
395
+ }
396
+
397
+ function addYcbObject(name, config) {
398
+ if (!config || !config.folder || !config.web_obj) return null;
399
+ if (ycbMeshes[name]) {
400
+ scene.remove(ycbMeshes[name]);
401
+ delete ycbMeshes[name];
402
+ }
403
+ const objFile = `/assets/ycb/${config.folder}/${config.web_obj}`;
404
+ const mtlFile = config.web_mtl
405
+ ? `/assets/ycb/${config.folder}/${config.web_mtl}`
406
+ : "";
407
+ const objectGroup = new THREE.Group();
408
+ objectGroup.name = name;
409
+ objectGroup.position.fromArray(config.initial_pos);
410
+ objectGroup.quaternion.fromArray(config.initial_ori);
411
+ scene.add(objectGroup);
412
+ ycbMeshes[name] = objectGroup;
413
+
414
+ const attachVisual = (objLoader) => {
415
+ objLoader.load(objFile, (visObj) => {
416
+ if (ycbMeshes[name] !== objectGroup) return;
417
+ visObj.traverse(child => {
418
+ if (!child.isMesh) return;
419
+ child.castShadow = true;
420
+ child.receiveShadow = true;
421
+ const materials = Array.isArray(child.material)
422
+ ? child.material
423
+ : [child.material];
424
+ materials.filter(Boolean).forEach(material => {
425
+ if (material.map) {
426
+ material.color.setHex(0xffffff);
427
+ material.map.encoding = THREE.sRGBEncoding;
428
+ material.map.needsUpdate = true;
429
+ }
430
+ });
431
+ });
432
+ if (config.vis_local_pos) visObj.position.fromArray(config.vis_local_pos);
433
+ if (config.vis_local_ori) visObj.quaternion.fromArray(config.vis_local_ori);
434
+ if (config.vis_scale) visObj.scale.fromArray(config.vis_scale);
435
+ objectGroup.add(visObj);
436
+ });
437
+ };
438
+ if (mtlFile) {
439
+ MTL_LOADER.load(mtlFile, materials => {
440
+ materials.preload();
441
+ const objLoader = new THREE.OBJLoader();
442
+ objLoader.setMaterials(materials);
443
+ attachVisual(objLoader);
444
+ });
445
+ } else {
446
+ attachVisual(new THREE.OBJLoader());
447
+ }
448
+ return objectGroup;
449
+ }
450
+
451
+ function removeYcbObject(name) {
452
+ const group = ycbMeshes[name];
453
+ if (!group) return;
454
+ if (selectedObjectName === name) clearObjectSelection();
455
+ scene.remove(group);
456
+ delete ycbMeshes[name];
457
+ delete targetObjects[name];
458
+ }
459
  function updateSimulationState(jointsData, objectsData) {
460
  if (jointsData && jointsData.length >= 11) {
461
  targetJoints = jointsData;
 
477
  reconnectTimeout = null;
478
  }
479
  const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
480
+ const wsUrl = `${wsProtocol}//${window.location.host}/ws?gui=false&client_id=${runtimeClientId}&last_event_seq=${lastEventSeq}`;
481
 
482
  updateBadgeStatus('disconnected');
483
 
 
486
  console.log("WebSocket connected.");
487
  updateBadgeStatus('connected');
488
  };
489
+ socket.onmessage = (event) => {
490
+ const msg = JSON.parse(event.data);
491
+ if (msg.seq) {
492
+ lastEventSeq = Math.max(lastEventSeq, Number(msg.seq));
493
+ localStorage.setItem('llm-panda-last-event-seq', String(lastEventSeq));
494
+ }
495
+ if (msg.generation && ['log', 'plan', 'result', 'execution_status', 'current_step'].includes(msg.type)
496
+ && Number(msg.generation) < activeGeneration) return;
497
+ handleSocketMessage(msg);
498
  };
499
  socket.onclose = () => {
500
  console.log("WebSocket disconnected.");
 
506
  console.error("WebSocket Error: ", err);
507
  };
508
  }
509
+ function handleSocketMessage(msg) {
510
+ switch(msg.type) {
511
+ case 'runtime_snapshot': {
512
+ activeGeneration = Number(msg.generation || 0);
513
+ executionState = msg.execution_state || 'idle';
514
+ if (msg.active_prompt) currentPrompt = msg.active_prompt;
515
+ if (msg.state) updateSimulationState(msg.state.joints, msg.state.objects);
516
+ if (msg.events) {
517
+ logConsole.innerHTML = '';
518
+ msg.events.filter(item => item.type === 'log').forEach(item => {
519
+ writeLog(item.message, getLogClass(item.message));
520
+ updatePipelineUI(item.message);
521
+ });
522
+ }
523
+ if (msg.plan && msg.plan.plan) displayPlan(msg.plan.plan);
524
+ if (['idle', 'completed', 'interrupted', 'failed'].includes(executionState)) {
525
+ unlockInput();
526
+ } else {
527
+ lockInput();
528
+ }
529
+ break;
530
+ }
531
+
532
+ case 'command_accepted':
533
+ activeGeneration = Math.max(activeGeneration, Number(msg.generation || 0));
534
+ currentPrompt = msg.prompt || currentPrompt;
535
+ executionState = 'planning';
536
+ lockInput();
537
+ break;
538
+
539
+ case 'execution_status':
540
+ activeGeneration = Math.max(activeGeneration, Number(msg.generation || 0));
541
+ executionState = msg.state || executionState;
542
+ lockInput();
543
+ break;
544
+
545
+ case 'interrupt_requested':
546
+ activeGeneration = Math.max(activeGeneration, Number(msg.generation || 0));
547
+ executionState = 'interrupt_requested';
548
+ lockInput();
549
+ break;
550
+
551
+ case 'interrupted':
552
+ writeLog('Đã dα»«ng lệnh Δ‘ang thα»±c thi.', 'warn');
553
+ if (msg.generation && Number(msg.generation) < activeGeneration) {
554
+ lockInput();
555
+ } else {
556
+ executionState = 'interrupted';
557
+ unlockInput();
558
+ }
559
+ break;
560
+
561
+ case 'drag_started':
562
+ if (activeDrag) {
563
+ activeDrag.dragId = msg.drag_id;
564
+ activeDrag.type = msg.target_type;
565
+ }
566
+ break;
567
+
568
+ case 'drag_rejected':
569
+ case 'spawn_rejected':
570
+ case 'delete_rejected':
571
+ case 'environment_rejected':
572
+ endActiveDrag(false);
573
+ writeLog(msg.reason || 'KhΓ΄ng thể thα»±c hiện thao tΓ‘c kΓ©o thαΊ£.', 'warn');
574
+ break;
575
+
576
+ case 'object_added':
577
+ addYcbObject(msg.name, msg.config);
578
+ if (msg.state) {
579
+ updateSimulationState(null, { [msg.name]: msg.state });
580
+ }
581
+ break;
582
+
583
+ case 'object_removed':
584
+ removeYcbObject(msg.name);
585
+ break;
586
+
587
+ case 'env_list':
588
  const envSelect = document.getElementById('env-select');
589
  if (envSelect && msg.envs) {
590
  envSelect.innerHTML = msg.envs.map(env => `<option value="${env}">${env}</option>`).join('');
 
623
  break;
624
 
625
  case 'result':
626
+ if (['clarify', 'reject'].includes(msg.response_type)) {
627
+ executionState = 'idle';
628
+ unlockInput();
 
 
 
629
  window.currentPlan = null;
630
  window.currentLlmTime = 0;
 
631
  break;
632
  }
633
+ executionState = msg.success === false ? 'failed' : 'completed';
634
+ unlockInput();
635
+
636
+ // Add new run record to history log dynamically
637
  const now = new Date();
638
  const timeStr = now.toTimeString().split(' ')[0];
639
 
 
744
  const rows = Object.entries(catalogMap).map(([name, config]) => {
745
  const displayName = objDict[name] || name;
746
  const imageUrl = `/static/thumbnails/${config.folder}.png?v=${new Date().getTime()}`;
747
+ return `
748
+ <tr class="catalog-object-row" draggable="true"
749
+ data-catalog-folder="${config.folder}" data-catalog-name="${name}">
750
+ <td>
751
  <div style="width: 50px; height: 50px; overflow: hidden; border-radius: 8px; border: 1px solid #e2e8f0; display: flex; align-items: center; justify-content: center; background: #fff;">
752
  <img src="${imageUrl}" alt="${displayName}" style="max-width: 100%; max-height: 100%; object-fit: contain;">
753
  </div>
 
757
  `;
758
  });
759
 
760
+ objectsTableBody.innerHTML = rows.join('');
761
+ objectsTableBody.querySelectorAll('.catalog-object-row').forEach(row => {
762
+ row.addEventListener('dragstart', event => {
763
+ event.dataTransfer.effectAllowed = 'copy';
764
+ event.dataTransfer.setData(
765
+ 'application/x-llm-panda-ycb',
766
+ JSON.stringify({
767
+ folder: row.dataset.catalogFolder,
768
+ name: row.dataset.catalogName
769
+ })
770
+ );
771
+ row.classList.add('is-dragging');
772
+ });
773
+ row.addEventListener('dragend', () => {
774
+ row.classList.remove('is-dragging');
775
+ canvas.classList.remove('catalog-drop-target');
776
+ });
777
+ });
778
+ }
779
  // 4. History Logs Data & Render
780
  const historyData = [];
781
 
 
1184
  });
1185
  }
1186
 
1187
+ function lockInput() {
1188
+ chatInput.disabled = false;
1189
+ submitBtn.disabled = false;
1190
+ resetBtn.disabled = true;
1191
+ setSubmitButtonMode(true);
1192
+ chatInput.placeholder = 'NhαΊ­p lệnh mα»›i rα»“i Enter để thay thαΊΏ lệnh hiện tαΊ‘i';
1193
+ }
1194
+ let enterSubmittedFromChatInput = false;
1195
+ chatInput.addEventListener('keydown', (e) => {
1196
+ if (e.key === 'Enter' && !e.shiftKey) {
1197
+ enterSubmittedFromChatInput = true;
1198
+ }
1199
+ });
1200
+ document.getElementById('chat-form').addEventListener('submit', (e) => {
1201
+ e.preventDefault();
1202
+ const submittedWithEnter = enterSubmittedFromChatInput;
1203
+ enterSubmittedFromChatInput = false;
1204
+ const busy = !['idle', 'completed', 'interrupted', 'failed'].includes(executionState);
1205
+ if (busy && e.submitter === submitBtn && !submittedWithEnter) {
1206
+ if (socket && socket.readyState === WebSocket.OPEN) {
1207
+ socket.send(JSON.stringify({ type: 'cancel' }));
1208
+ }
1209
+ return;
1210
+ }
1211
+ const prompt = chatInput.value.trim();
1212
  if (!prompt || !socket || socket.readyState !== WebSocket.OPEN) return;
1213
  currentPrompt = prompt;
1214
  chatInput.value = '';
 
1221
  });
1222
  window.currentRunStartTime = Date.now();
1223
  writeLog(`Gα»­i yΓͺu cαΊ§u: "${prompt}"`, "info");
1224
+ executionState = 'planning';
1225
+ lockInput();
1226
 
1227
  speakFeedback("Start processing your command.");
1228
+ socket.send(JSON.stringify({
1229
+ type: 'run',
1230
  prompt: prompt,
1231
  mock: false
1232
  }));
1233
  });
1234
+ function unlockInput() {
1235
+ chatInput.disabled = false;
1236
+ submitBtn.disabled = false;
1237
+ resetBtn.disabled = false;
1238
+ chatInput.placeholder = 'NhαΊ­p cΓ’u lệnh cα»§a bαΊ‘n cho robot';
1239
+ setSubmitButtonMode(false);
1240
+ }
1241
+ function setSubmitButtonMode(executing) {
1242
+ submitBtn.classList.toggle('is-executing', executing);
1243
+ submitBtn.title = executing ? 'Dα»«ng lệnh Δ‘ang thα»±c thi' : 'Gα»­i lệnh';
1244
+ submitBtn.setAttribute('aria-label', submitBtn.title);
1245
+ submitBtn.innerHTML = executing
1246
+ ? '<span class="stop-square" aria-hidden="true"></span>'
1247
+ : '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>';
1248
+ }
1249
  resetBtn.addEventListener('click', () => {
1250
  if (!socket || socket.readyState !== WebSocket.OPEN) return;
1251
 
 
1290
  });
1291
  }
1292
  });
1293
+ // 11. Authoritative pointer dragging for YCB objects and robot end-effector
1294
+ const raycaster = new THREE.Raycaster();
1295
+ const mouse = new THREE.Vector2();
1296
+ let hoveredGroup = null;
1297
+ let activeDrag = null;
1298
+ let lastDragUpdateAt = 0;
1299
+ let selectedObjectName = null;
1300
+ let selectionHelper = null;
1301
+ const objectDeleteButton = document.createElement('button');
1302
+ objectDeleteButton.type = 'button';
1303
+ objectDeleteButton.className = 'object-delete-button hidden';
1304
+ objectDeleteButton.textContent = 'Γ—';
1305
+ objectDeleteButton.title = 'XΓ³a vαΊ­t thể';
1306
+ objectDeleteButton.setAttribute('aria-label', 'XΓ³a vαΊ­t thể Δ‘Γ£ chọn');
1307
+ document.body.appendChild(objectDeleteButton);
1308
+ objectDeleteButton.addEventListener('click', event => {
1309
+ event.stopPropagation();
1310
+ if (
1311
+ selectedObjectName
1312
+ && socket
1313
+ && socket.readyState === WebSocket.OPEN
1314
+ ) {
1315
+ socket.send(JSON.stringify({
1316
+ type: 'delete_object',
1317
+ name: selectedObjectName
1318
+ }));
1319
+ }
1320
+ });
1321
+
1322
+ function clearObjectSelection() {
1323
+ selectedObjectName = null;
1324
+ if (selectionHelper) {
1325
+ scene.remove(selectionHelper);
1326
+ selectionHelper.geometry.dispose();
1327
+ selectionHelper.material.dispose();
1328
+ selectionHelper = null;
1329
+ }
1330
+ objectDeleteButton.classList.add('hidden');
1331
+ }
1332
+
1333
+ function selectSceneObject(name) {
1334
+ clearObjectSelection();
1335
+ const group = ycbMeshes[name];
1336
+ if (!group) return;
1337
+ selectedObjectName = name;
1338
+ selectionHelper = new THREE.BoxHelper(group, 0xef4444);
1339
+ selectionHelper.material.depthTest = false;
1340
+ selectionHelper.material.transparent = true;
1341
+ selectionHelper.material.opacity = 0.95;
1342
+ selectionHelper.renderOrder = 999;
1343
+ scene.add(selectionHelper);
1344
+ objectDeleteButton.classList.remove('hidden');
1345
+ }
1346
+
1347
+ function updateObjectSelectionOverlay() {
1348
+ if (!selectedObjectName || !selectionHelper) return;
1349
+ const group = ycbMeshes[selectedObjectName];
1350
+ if (!group) {
1351
+ clearObjectSelection();
1352
+ return;
1353
+ }
1354
+ selectionHelper.setFromObject(group);
1355
+ const box = new THREE.Box3().setFromObject(group);
1356
+ const anchor = new THREE.Vector3(
1357
+ (box.min.x + box.max.x) / 2,
1358
+ (box.min.y + box.max.y) / 2,
1359
+ box.max.z + 0.04
1360
+ );
1361
+ anchor.project(camera);
1362
+ const rect = canvas.getBoundingClientRect();
1363
+ objectDeleteButton.style.left =
1364
+ `${rect.left + (anchor.x + 1) * rect.width / 2}px`;
1365
+ objectDeleteButton.style.top =
1366
+ `${rect.top + (-anchor.y + 1) * rect.height / 2}px`;
1367
+ }
1368
+
1369
+ // Helper to determine if an intersected object belongs to a draggable group (YCB or Robot)
1370
+ function findDraggableTarget(hitObject) {
1371
+ let curr = hitObject;
1372
+ while (curr && curr !== scene) {
1373
+ if (curr === robotGroup) {
1374
+ return { type: 'robot_ee', group: robotGroup, name: 'robot' };
1375
+ }
1376
+ const ycbEntry = Object.entries(ycbMeshes).find(([name, group]) => group === curr);
1377
+ if (ycbEntry) {
1378
+ return { type: 'object', group: ycbEntry[1], name: ycbEntry[0] };
1379
+ }
1380
+ curr = curr.parent;
1381
+ }
1382
+ return null;
1383
+ }
1384
+
1385
+ function updatePointerRay(event) {
1386
+ const rect = canvas.getBoundingClientRect();
1387
+ mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
1388
+ mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
1389
+ raycaster.setFromCamera(mouse, camera);
1390
+ }
1391
+
1392
+ // Helper to set/restore emissive highlight glow on all child meshes of a group
1393
+ function highlightGroup(group, highlightColor = null) {
1394
  if (!group) return;
1395
  group.traverse(child => {
1396
  if (child.isMesh) {
 
1414
  }
1415
  }
1416
  });
1417
+ }
1418
+
1419
+ function onPointerDown(event) {
1420
+ if (event.button !== 0 || !socket || socket.readyState !== WebSocket.OPEN) return;
1421
+ updatePointerRay(event);
1422
+ const hits = raycaster.intersectObjects(scene.children, true);
1423
+ const hit = hits.find(item => findDraggableTarget(item.object));
1424
+ if (!hit) {
1425
+ clearObjectSelection();
1426
+ return;
1427
+ }
1428
+ const target = findDraggableTarget(hit.object);
1429
+ if (target.type === 'object') {
1430
+ selectSceneObject(target.name);
1431
+ event.preventDefault();
1432
+ return;
1433
+ }
1434
+
1435
+ const planePoint = hit.point.clone();
1436
+ if (target.type === 'robot_ee' && joints.handJoint) {
1437
+ joints.handJoint.getWorldPosition(planePoint);
1438
+ }
1439
+ dragPlane.setFromNormalAndCoplanarPoint(
1440
+ camera.getWorldDirection(new THREE.Vector3()),
1441
+ planePoint
1442
+ );
1443
+ const initialPlaneHit = new THREE.Vector3();
1444
+ raycaster.ray.intersectPlane(dragPlane, initialPlaneHit);
1445
+ activeDrag = {
1446
+ dragId: null,
1447
+ type: target.type,
1448
+ name: target.name,
1449
+ pointerId: event.pointerId,
1450
+ group: target.group,
1451
+ offset: planePoint.clone().sub(initialPlaneHit)
1452
+ };
1453
+ isDragging = true;
1454
+ controls.enabled = false;
1455
+ canvas.setPointerCapture(event.pointerId);
1456
+ const rayTo = raycaster.ray.origin.clone().add(
1457
+ raycaster.ray.direction.clone().multiplyScalar(100)
1458
+ );
1459
+ socket.send(JSON.stringify({
1460
+ type: 'mouse_pick_start',
1461
+ target_type: target.type,
1462
+ object_id: target.name,
1463
+ rayFrom: raycaster.ray.origin.toArray(),
1464
+ rayTo: rayTo.toArray()
1465
+ }));
1466
+ event.preventDefault();
1467
+ }
1468
+
1469
+ function onPointerMove(event) {
1470
+ updatePointerRay(event);
1471
+ if (activeDrag && event.pointerId === activeDrag.pointerId) {
1472
+ const now = performance.now();
1473
+ if (!activeDrag.dragId || now - lastDragUpdateAt < 25) return;
1474
+ lastDragUpdateAt = now;
1475
+ const targetPos = new THREE.Vector3();
1476
+ if (raycaster.ray.intersectPlane(dragPlane, targetPos)) {
1477
+ targetPos.add(activeDrag.offset);
1478
+ socket.send(JSON.stringify({
1479
+ type: 'mouse_pick_update',
1480
+ drag_id: activeDrag.dragId,
1481
+ targetPos: [targetPos.x, targetPos.y, targetPos.z]
1482
+ }));
1483
+ }
1484
+ return;
1485
+ }
1486
+
1487
+ const hits = raycaster.intersectObjects(scene.children, true);
1488
+ const hoverHit = hits.find(item => findDraggableTarget(item.object));
1489
+ const hoverTarget = hoverHit ? findDraggableTarget(hoverHit.object) : null;
1490
+ if (hoverTarget) {
1491
+ if (hoveredGroup !== hoverTarget.group) {
1492
+ if (hoveredGroup) highlightGroup(hoveredGroup, null);
1493
+ hoveredGroup = hoverTarget.group;
1494
+ highlightGroup(hoveredGroup, 0x555555);
1495
+ canvas.style.cursor = 'pointer';
1496
+ }
1497
+ } else {
1498
+ if (hoveredGroup) {
1499
+ highlightGroup(hoveredGroup, null);
1500
+ hoveredGroup = null;
1501
+ }
1502
+ canvas.style.cursor = 'default';
1503
+ }
1504
+ }
1505
+
1506
+ function endActiveDrag(notifyServer = true) {
1507
+ if (!activeDrag) return;
1508
+ if (
1509
+ notifyServer
1510
+ && activeDrag.dragId
1511
+ && socket
1512
+ && socket.readyState === WebSocket.OPEN
1513
+ ) {
1514
+ socket.send(JSON.stringify({
1515
+ type: 'mouse_pick_end',
1516
+ drag_id: activeDrag.dragId
1517
+ }));
1518
+ }
1519
+ const pointerId = activeDrag.pointerId;
1520
+ activeDrag = null;
1521
+ isDragging = false;
1522
+ controls.enabled = true;
1523
+ if (canvas.hasPointerCapture(pointerId)) {
1524
+ canvas.releasePointerCapture(pointerId);
1525
+ }
1526
+ }
1527
+
1528
+ function onPointerEnd(event) {
1529
+ if (activeDrag && event.pointerId === activeDrag.pointerId) {
1530
+ endActiveDrag(true);
1531
+ }
1532
+ }
1533
+
1534
+ canvas.addEventListener('pointerdown', onPointerDown);
1535
+ canvas.addEventListener('pointermove', onPointerMove);
1536
+ canvas.addEventListener('pointerup', onPointerEnd);
1537
+ canvas.addEventListener('pointercancel', onPointerEnd);
1538
+ canvas.addEventListener('lostpointercapture', () => endActiveDrag(true));
1539
+
1540
+ canvas.addEventListener('dragover', event => {
1541
+ if (!event.dataTransfer.types.includes('application/x-llm-panda-ycb')) return;
1542
+ event.preventDefault();
1543
+ event.dataTransfer.dropEffect = 'copy';
1544
+ canvas.classList.add('catalog-drop-target');
1545
+ });
1546
+
1547
+ canvas.addEventListener('dragleave', () => {
1548
+ canvas.classList.remove('catalog-drop-target');
1549
+ });
1550
+
1551
+ canvas.addEventListener('drop', event => {
1552
+ event.preventDefault();
1553
+ canvas.classList.remove('catalog-drop-target');
1554
+ if (!socket || socket.readyState !== WebSocket.OPEN) return;
1555
+ let item;
1556
+ try {
1557
+ item = JSON.parse(
1558
+ event.dataTransfer.getData('application/x-llm-panda-ycb')
1559
+ );
1560
+ } catch (_) {
1561
+ return;
1562
+ }
1563
+ updatePointerRay(event);
1564
+ const surfacePlane = new THREE.Plane(
1565
+ new THREE.Vector3(0, 0, 1),
1566
+ -placementSurfaceZ
1567
+ );
1568
+ const position = new THREE.Vector3();
1569
+ if (!raycaster.ray.intersectPlane(surfacePlane, position)) return;
1570
+ socket.send(JSON.stringify({
1571
+ type: 'spawn_catalog_object',
1572
+ folder: item.folder,
1573
+ position: [position.x, position.y, placementSurfaceZ + 0.08]
1574
+ }));
1575
+ });
1576
 
1577
 
1578
  // Initialize
frontend/index.css CHANGED
@@ -662,10 +662,37 @@ button, input, select, table {
662
  background: var(--primary-color);
663
  color: white;
664
  }
665
- #submit-btn:hover {
666
- background: #1d4ed8;
667
- }
668
- #submit-btn:disabled, #chat-input:disabled, #mic-btn:disabled {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
669
  opacity: 0.4;
670
  cursor: not-allowed;
671
  box-shadow: none;
@@ -962,7 +989,7 @@ button, input, select, table {
962
  color: var(--text-muted);
963
  }
964
 
965
- .objects-table tbody td {
966
  padding: 12px 16px;
967
  border-bottom: 1px solid #f1f5f9;
968
  }
@@ -989,4 +1016,42 @@ button, input, select, table {
989
  border-color: #94a3b8;
990
  opacity: 1;
991
  transform: scale(1.1);
992
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
662
  background: var(--primary-color);
663
  color: white;
664
  }
665
+ #submit-btn:hover {
666
+ background: #1d4ed8;
667
+ }
668
+ #submit-btn.is-executing {
669
+ position: relative;
670
+ background: #1e3a8a;
671
+ }
672
+ #submit-btn.is-executing:hover {
673
+ background: #172554;
674
+ }
675
+ #submit-btn.is-executing::before {
676
+ content: "";
677
+ position: absolute;
678
+ inset: 5px;
679
+ border: 2px solid rgba(255, 255, 255, 0.3);
680
+ border-top-color: #fff;
681
+ border-radius: 50%;
682
+ animation: submitExecutionSpin 0.8s linear infinite;
683
+ }
684
+ #submit-btn .stop-square {
685
+ width: 10px;
686
+ height: 10px;
687
+ border-radius: 2px;
688
+ background: #fff;
689
+ position: relative;
690
+ z-index: 1;
691
+ }
692
+ @keyframes submitExecutionSpin {
693
+ to { transform: rotate(360deg); }
694
+ }
695
+ #submit-btn:disabled, #chat-input:disabled, #mic-btn:disabled {
696
  opacity: 0.4;
697
  cursor: not-allowed;
698
  box-shadow: none;
 
989
  color: var(--text-muted);
990
  }
991
 
992
+ .objects-table tbody td {
993
  padding: 12px 16px;
994
  border-bottom: 1px solid #f1f5f9;
995
  }
 
1016
  border-color: #94a3b8;
1017
  opacity: 1;
1018
  transform: scale(1.1);
1019
+ }
1020
+ .catalog-object-row {
1021
+ cursor: grab;
1022
+ user-select: none;
1023
+ }
1024
+ .catalog-object-row:active {
1025
+ cursor: grabbing;
1026
+ }
1027
+ .catalog-object-row.is-dragging {
1028
+ opacity: 0.45;
1029
+ }
1030
+ #pybullet-viewport.catalog-drop-target {
1031
+ outline: 3px dashed #2563eb;
1032
+ outline-offset: -6px;
1033
+ filter: saturate(1.1);
1034
+ }
1035
+ .object-delete-button {
1036
+ position: fixed;
1037
+ z-index: 1000;
1038
+ width: 28px;
1039
+ height: 28px;
1040
+ transform: translate(-50%, -50%);
1041
+ border: 2px solid #fff;
1042
+ border-radius: 50%;
1043
+ background: #ef4444;
1044
+ color: #fff;
1045
+ font-size: 21px;
1046
+ line-height: 20px;
1047
+ font-weight: 700;
1048
+ cursor: pointer;
1049
+ box-shadow: 0 3px 10px rgba(127, 29, 29, 0.4);
1050
+ }
1051
+ .object-delete-button:hover {
1052
+ background: #dc2626;
1053
+ transform: translate(-50%, -50%) scale(1.08);
1054
+ }
1055
+ .object-delete-button.hidden {
1056
+ display: none;
1057
+ }
frontend/index.html CHANGED
@@ -15,7 +15,7 @@
15
  <script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/OrbitControls.js"></script>
16
  <script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/TransformControls.js"></script>
17
  <!-- Main Style -->
18
- <link rel="stylesheet" href="/static/index.css?v=8">
19
  </head>
20
  <body>
21
  <!-- Real-Time PyBullet Streaming Viewport -->
@@ -300,6 +300,6 @@
300
  </div>
301
 
302
  <!-- Application Script -->
303
- <script src="/static/app.js?v=25"></script>
304
  </body>
305
- </html>
 
15
  <script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/OrbitControls.js"></script>
16
  <script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/TransformControls.js"></script>
17
  <!-- Main Style -->
18
+ <link rel="stylesheet" href="/static/index.css?v=11">
19
  </head>
20
  <body>
21
  <!-- Real-Time PyBullet Streaming Viewport -->
 
300
  </div>
301
 
302
  <!-- Application Script -->
303
+ <script src="/static/app.js?v=30"></script>
304
  </body>
305
+ </html>
frontend/interactive_server.py CHANGED
@@ -2,9 +2,10 @@ import sys
2
  import os
3
  import json
4
  import asyncio
5
- import math
6
- import time
7
- import threading
 
8
  from typing import Optional
9
  from fastapi import FastAPI, WebSocket, WebSocketDisconnect
10
  from fastapi.staticfiles import StaticFiles
@@ -19,11 +20,12 @@ if PROJECT_SRC not in sys.path:
19
  sys.path.insert(0, PROJECT_SRC)
20
  from dotenv import load_dotenv
21
  load_dotenv()
22
- from main import PandaApp
23
- from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner
24
- from llm_panda.conversation import ConversationManager
25
- from llm_panda.plan_verifier import PlanVerifier
26
- from llm_panda import config
 
27
  import pybullet_data
28
  from pybullet_object_models import ycb_objects
29
  app = FastAPI(title="LLM-Panda Web-Embedded PyBullet Simulation")
@@ -39,14 +41,82 @@ app.mount("/assets/ycb", StaticFiles(directory=ycb_data_path), name="ycb")
39
  async def get():
40
  html_file = os.path.join(static_dir, "index.html")
41
  if os.path.exists(html_file):
42
- with open(html_file, "r", encoding="utf-8") as f:
43
- return HTMLResponse(content=f.read(), status_code=200)
 
 
 
 
 
 
 
 
44
  return HTMLResponse(content="<h1>index.html not found!</h1>", status_code=404)
45
  # Global variables to track the current active simulation, lock, and thread lock
46
  current_sim: Optional[PandaApp] = None
47
  executor_lock = asyncio.Lock()
48
  pybullet_lock = threading.RLock()
49
- pipeline_executing = False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  def get_init_payload(sim: PandaApp) -> dict:
51
  """Gathers the initial static geometry and YCB object definitions."""
52
  with pybullet_lock:
@@ -92,10 +162,26 @@ def get_init_payload(sim: PandaApp) -> dict:
92
  vis_local_pos = list(vis_pos_com)
93
  vis_local_ori = list(vis_ori_com)
94
 
95
- import os
96
- if not web_obj and vd[4]:
97
- mesh_path = vd[4].decode('utf-8')
98
- web_obj = os.path.basename(mesh_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
 
100
  objects_info[name] = {
101
  "class": cls,
@@ -273,26 +359,30 @@ def compute_and_format_score(sim: PandaApp, plan: list, executed_successfully: b
273
  return score, md
274
 
275
  def run_pipeline_threadsafe(
276
- websocket: WebSocket,
277
  user_prompt: str,
278
  loop,
279
  use_mock: bool,
 
 
 
 
280
  camera_state: Optional[dict] = None,
281
- conversation_manager: Optional[ConversationManager] = None,
282
  ):
283
  """Runs the planning, validation, execution with image streaming, and scoring using closed-loop execution monitor."""
284
  global current_sim, pipeline_executing
285
- pipeline_executing = True
 
 
 
 
 
286
 
287
  def log(message: str, step: Optional[int] = None):
288
  try:
289
  print(f"[WS Log] {message}", flush=True)
290
  except Exception:
291
  pass
292
- asyncio.run_coroutine_threadsafe(
293
- websocket.send_json({"type": "log", "message": message, "step": step}),
294
- loop
295
- )
296
 
297
  # Step 1: Planning
298
  log("⏳ [1/5] TΓ΄i Δ‘ang suy nghΔ© cΓ‘ch thα»±c hiện...")
@@ -312,10 +402,13 @@ def run_pipeline_threadsafe(
312
  with pybullet_lock:
313
  current_sim.pipeline.agent = LLMAgent(
314
  planner=planner,
315
- conversation_manager=conversation_manager,
316
  )
317
 
318
- MAX_REPLANS = current_sim.pipeline.MAX_REPLANS
 
 
 
319
  last_failed_sig = None
320
  last_failed_state_sig = None
321
  resolved_goal = None
@@ -325,8 +418,9 @@ def run_pipeline_threadsafe(
325
  last_stream_time = [0.0]
326
  throttle_interval = 0.033
327
 
328
- def wrapped_step():
329
- original_step()
 
330
  if not current_sim.gui:
331
  time.sleep(0.001)
332
  curr_time = time.time()
@@ -334,13 +428,13 @@ def run_pipeline_threadsafe(
334
  last_stream_time[0] = curr_time
335
  state_payload = get_simulation_state_payload(current_sim)
336
  if state_payload:
337
- asyncio.run_coroutine_threadsafe(
338
- websocket.send_json(state_payload),
339
- loop
340
- )
341
 
342
- for attempt in range(MAX_REPLANS + 1):
343
- if attempt > 0:
 
 
 
344
  log(f"[MONITOR] Re-plan attempt {attempt}/{MAX_REPLANS} due to: {last_failed_sig}")
345
  log("⏳ [1/5] TΓ΄i Δ‘ang suy nghΔ© cΓ‘ch thα»±c hiện...")
346
 
@@ -368,31 +462,30 @@ def run_pipeline_threadsafe(
368
  }
369
  state_sig = json.dumps(state_sig_dict, sort_keys=True)
370
 
371
- try:
372
- with pybullet_lock:
373
- llm_start_time = time.time()
374
- planning_command = (
375
  resolved_goal.canonical_instruction
376
  if attempt > 0 and resolved_goal is not None
377
  else user_prompt
378
  )
379
  current_sim.pipeline.agent.last_outcome = None
380
  plan_kwargs = {
381
- "previous_failed_reasons": last_failed_sig
382
  }
383
  if attempt > 0:
384
  plan_kwargs["resolve_goal"] = False
385
  plan = current_sim.pipeline.agent.plan(
386
- planning_command,
387
  state_text,
388
  **plan_kwargs,
389
  )
390
- outcome = getattr(
391
- current_sim.pipeline.agent, "last_outcome", None
392
- )
393
  if attempt == 0 and outcome is not None:
394
  resolved_goal = outcome.resolved_goal
395
  llm_time = time.time() - llm_start_time
 
396
 
397
  # Summarize plan
398
  targets = []
@@ -440,28 +533,22 @@ def run_pipeline_threadsafe(
440
  "args": args
441
  })
442
 
443
- asyncio.run_coroutine_threadsafe(
444
- websocket.send_json({"type": "plan", "plan": plan_steps, "summary": summary_msg, "llm_time": llm_time}),
445
- loop
446
- )
447
 
448
  if plan and plan[0].get("function") in ("clarify", "reject"):
449
  log(f"Robot phαΊ£n hα»“i: {summary_msg}")
450
  header_title = "PhαΊ£n hα»“i tα»« Robot" if plan[0].get("function") == "clarify" else "YΓͺu cαΊ§u bα»‹ tα»« chα»‘i"
451
  score_md = f"### {header_title}\n\n**Robot phαΊ£n hα»“i:** {summary_msg}\n"
452
- asyncio.run_coroutine_threadsafe(
453
- websocket.send_json({
454
- "type": "result",
455
- "response_type": plan[0].get("function"),
456
- "score_display": score_md,
457
- "score_value": 0,
458
- "success": False
459
- }),
460
- loop
461
- )
462
  state_payload = get_simulation_state_payload(current_sim)
463
  if state_payload:
464
- asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
465
  pipeline_executing = False
466
  return
467
 
@@ -469,17 +556,14 @@ def run_pipeline_threadsafe(
469
  log("⚠️ [1] KαΊΏ hoαΊ‘ch rα»—ng.")
470
  log("⏳ [5/5] Đang tΓ­nh toΓ‘n Δ‘iểm sαΊ―p xαΊΏp...")
471
  score_val, score_md = compute_and_format_score(current_sim, [], True)
472
- asyncio.run_coroutine_threadsafe(
473
- websocket.send_json({
474
- "type": "result",
475
- "score_display": score_md,
476
- "score_value": score_val
477
- }),
478
- loop
479
- )
480
  state_payload = get_simulation_state_payload(current_sim)
481
  if state_payload:
482
- asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
483
  pipeline_executing = False
484
  return
485
 
@@ -499,8 +583,10 @@ def run_pipeline_threadsafe(
499
  pipeline_executing = False
500
  return
501
 
502
- # Step 3: PyBullet Execution (Live!)
503
- log("⏳ [3/5] TΓ΄i bαΊ―t Δ‘αΊ§u thα»±c hiện cΓ‘c bΖ°α»›c...")
 
 
504
 
505
  with pybullet_lock:
506
  pb.stepSimulation = wrapped_step
@@ -514,7 +600,7 @@ def run_pipeline_threadsafe(
514
  # Trigger an initial simulation state transmission
515
  state_payload = get_simulation_state_payload(current_sim)
516
  if state_payload:
517
- asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
518
 
519
  def format_skill_vn(step_data):
520
  fn = step_data.get("function", "")
@@ -540,9 +626,12 @@ def run_pipeline_threadsafe(
540
  if fn == "close_gripper": return "Đóng tay kαΊΉp"
541
  return f"{fn}"
542
 
543
- expected_location = None
544
- for i, step in enumerate(plan, 1):
545
- friendly_text = format_skill_vn(step)
 
 
 
546
  # Make the first letter lowercase for natural sentence integration
547
  if friendly_text:
548
  friendly_text = friendly_text[0].lower() + friendly_text[1:]
@@ -577,7 +666,11 @@ def run_pipeline_threadsafe(
577
  log("βœ… [3] TΓ΄i Δ‘Γ£ hoΓ n tαΊ₯t cΓ‘c bΖ°α»›c.")
578
  else:
579
  log(f"❌ [3] Thα»±c thi lα»—i tαΊ‘i bΖ°α»›c {failed_step_index} '{failed_step_data.get('function')}': {step_failure_reason}")
580
- except Exception as e:
 
 
 
 
581
  log(f"❌ Lα»—i trong lΓΊc thα»±c thi mΓ΄ phỏng: {e}")
582
  executed_successfully = False
583
  step_failure_reason = str(e)
@@ -588,7 +681,7 @@ def run_pipeline_threadsafe(
588
  # Send a final state to ensure visual sync
589
  state_payload = get_simulation_state_payload(current_sim)
590
  if state_payload:
591
- asyncio.run_coroutine_threadsafe(websocket.send_json(state_payload), loop)
592
 
593
  # Now check overall goal using execution monitor
594
  goal_completed = False
@@ -641,23 +734,107 @@ def run_pipeline_threadsafe(
641
 
642
  is_success = executed_successfully and goal_completed and score_val >= 50
643
 
644
- asyncio.run_coroutine_threadsafe(
645
- websocket.send_json({
646
- "type": "result",
647
- "score_display": score_md,
648
- "score_value": score_val,
649
- "error_cause": error_cause,
650
- "success": is_success
651
- }),
652
- loop
653
- )
654
- pipeline_executing = False
655
- @app.websocket("/ws")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
656
  async def websocket_endpoint(websocket: WebSocket):
657
- global current_sim
658
  await websocket.accept()
659
- loop = asyncio.get_running_loop()
660
- conversation_manager = ConversationManager()
661
 
662
  # Retrieve user's desktop display preference from client query params
663
  client_wants_gui = websocket.query_params.get("gui", "false").lower() == "true"
@@ -665,16 +842,15 @@ async def websocket_endpoint(websocket: WebSocket):
665
  # Force gui = False to run PyBullet completely headless (DIRECT mode)
666
  gui = False
667
 
668
- camera_state = {
669
  "target": [0.5, 0.0, 0.3],
670
  "dist": 1.3,
671
  "yaw": 45.0,
672
- "pitch": -35.0
673
- }
674
-
675
- settle_task = None
676
 
677
- async def physics_settle_loop():
678
  try:
679
  while True:
680
  global pipeline_executing
@@ -698,9 +874,9 @@ async def websocket_endpoint(websocket: WebSocket):
698
  pb.stepSimulation(physicsClientId=current_sim.client)
699
  await asyncio.to_thread(step)
700
 
701
- state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
702
- if state_payload:
703
- await websocket.send_json(state_payload)
704
  await asyncio.sleep(1/30.0)
705
  except asyncio.CancelledError:
706
  pass
@@ -733,90 +909,165 @@ async def websocket_endpoint(websocket: WebSocket):
733
  except Exception:
734
  is_connected = False
735
 
736
- if is_connected:
737
- current_sim.reset_objects(seed=0)
738
- current_sim.controller.reset_to_home()
739
- for _ in range(5):
740
- pb.stepSimulation(physicsClientId=current_sim.client)
741
  await asyncio.to_thread(init_sim)
742
  # Apply the client's visibility preference to show/hide the PyBullet GUI window on the desktop
743
  await asyncio.to_thread(set_pybullet_window_visibility, client_wants_gui)
744
 
745
  # Send environment list
746
  try:
747
- env_files = [f for f in os.listdir(os.path.join(PROJECT_SRC, "envs")) if f.endswith('.json')]
748
- await websocket.send_json({"type": "env_list", "envs": env_files})
 
 
749
 
750
  # Send initial static scene data (only needs to be sent once)
751
- init_payload = await asyncio.to_thread(get_init_payload, current_sim)
752
- await websocket.send_json(init_payload)
 
753
  # Send the first simulation state to sync objects and joints
754
  state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
755
- if state_payload:
756
- await websocket.send_json(state_payload)
757
-
758
- settle_task = asyncio.create_task(physics_settle_loop())
 
 
 
759
 
760
- drag_state = {"constraint_id": None}
761
- while True:
762
  data = await websocket.receive_text()
763
  payload = json.loads(data)
764
 
765
  p_type = payload.get("type")
766
- if p_type == "run":
767
- prompt = payload.get("prompt", "")
768
- use_mock = payload.get("mock", False)
769
- asyncio.create_task(
770
- asyncio.to_thread(
771
- run_pipeline_threadsafe,
772
- websocket,
773
- prompt,
774
- loop,
775
- use_mock,
776
- conversation_manager=conversation_manager,
777
- )
778
- )
 
 
 
 
 
 
 
 
779
 
780
 
781
- elif p_type == "mouse_pick_start":
782
- rayFrom = payload.get("rayFrom")
783
- rayTo = payload.get("rayTo")
784
- if rayFrom and rayTo:
785
- async with executor_lock:
786
- def do_pick():
787
- with pybullet_lock:
788
- hit = pb.rayTest(rayFrom, rayTo, physicsClientId=current_sim.client)[0]
789
- obj_uid = hit[0]
790
- link_index = hit[1]
791
- hit_pos = hit[3]
792
- if obj_uid >= 0:
793
- mass = pb.getDynamicsInfo(obj_uid, link_index, physicsClientId=current_sim.client)[0]
794
- is_robot = (obj_uid == current_sim.controller.robot_id)
795
- if mass > 0 or is_robot:
796
- if link_index >= 0:
797
- pos, ori = pb.getLinkState(obj_uid, link_index, physicsClientId=current_sim.client)[4:6]
798
- else:
799
- pos, ori = pb.getBasePositionAndOrientation(obj_uid, physicsClientId=current_sim.client)
800
- inv_pos, inv_ori = pb.invertTransform(pos, ori)
801
- local_pivot, _ = pb.multiplyTransforms(inv_pos, inv_ori, hit_pos, [0,0,0,1])
802
- drag_state["constraint_id"] = pb.createConstraint(
803
- parentBodyUniqueId=obj_uid,
804
- parentLinkIndex=link_index,
805
- childBodyUniqueId=-1,
806
- childLinkIndex=-1,
807
- jointType=pb.JOINT_POINT2POINT,
808
- jointAxis=[0,0,0],
809
- parentFramePosition=local_pivot,
810
- childFramePosition=hit_pos,
811
- physicsClientId=current_sim.client
812
- )
813
- pb.changeConstraint(drag_state["constraint_id"], maxForce=500, physicsClientId=current_sim.client)
814
- await asyncio.to_thread(do_pick)
815
-
816
- drag_state["active"] = True
817
- if drag_state.get("task") is None or drag_state["task"].done():
818
- async def drag_loop():
819
- while drag_state.get("active") and drag_state.get("constraint_id") is not None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
820
  async with executor_lock:
821
  def step():
822
  with pybullet_lock:
@@ -826,67 +1077,263 @@ async def websocket_endpoint(websocket: WebSocket):
826
  state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
827
  if state_payload:
828
  try:
829
- await websocket.send_json(state_payload)
830
  except Exception:
831
  break
832
  await asyncio.sleep(1/60.0)
833
  drag_state["task"] = asyncio.create_task(drag_loop())
834
 
835
- elif p_type == "mouse_pick_update":
836
- targetPos = payload.get("targetPos")
837
- if targetPos:
838
- async with executor_lock:
839
- def do_update():
840
- with pybullet_lock:
841
- if drag_state.get("constraint_id") is not None:
842
- pb.changeConstraint(drag_state["constraint_id"], targetPos, maxForce=500, physicsClientId=current_sim.client)
843
- await asyncio.to_thread(do_update)
844
-
845
- elif p_type == "mouse_pick_end":
846
- drag_state["active"] = False
847
- async with executor_lock:
848
- def do_end():
849
- with pybullet_lock:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
850
  if drag_state.get("constraint_id") is not None:
851
- pb.removeConstraint(drag_state["constraint_id"], physicsClientId=current_sim.client)
852
- drag_state["constraint_id"] = None
853
- await asyncio.to_thread(do_end)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
854
 
855
  elif p_type == "reset":
856
- conversation_manager.clear()
 
 
 
 
 
857
  async with executor_lock:
858
  def reset_sim():
859
  with pybullet_lock:
860
  current_sim.reset_objects(seed=0)
861
  current_sim.controller.reset_to_home()
862
- await asyncio.to_thread(reset_sim)
 
 
863
 
864
  state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
865
  if state_payload:
866
- await websocket.send_json(state_payload)
867
- await websocket.send_json({"type": "log", "message": "πŸ”„ Đã reset mΓ΄i trường mΓ΄ phỏng."})
868
 
869
  elif p_type == "change_env":
870
- conversation_manager.clear()
 
 
 
 
 
871
  env_file = payload.get("env")
872
- env_path = os.path.join(PROJECT_SRC, "envs", env_file)
873
- async with executor_lock:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
874
  def change_sim_env():
875
  with pybullet_lock:
876
  current_sim.change_environment(env_path)
877
- await asyncio.to_thread(change_sim_env)
 
 
878
 
879
  # Send the new static data
880
- init_payload = await asyncio.to_thread(get_init_payload, current_sim)
881
- await websocket.send_json(init_payload)
 
882
 
883
  # Send the new dynamic state
884
  state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
885
  if state_payload:
886
- await websocket.send_json(state_payload)
887
- await websocket.send_json({"type": "log", "message": f"🌍 Đã chuyển sang mΓ΄i trường {env_file}."})
888
 
889
- elif p_type == "update_object_pose":
 
 
890
  name = payload.get("name")
891
  pos = payload.get("pos")
892
  ori = payload.get("ori")
@@ -900,9 +1347,11 @@ async def websocket_endpoint(websocket: WebSocket):
900
 
901
  state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
902
  if state_payload:
903
- await websocket.send_json(state_payload)
904
 
905
- elif p_type == "update_joints":
 
 
906
  joints_data = payload.get("joints")
907
  async with executor_lock:
908
  def move_joints():
@@ -916,8 +1365,10 @@ async def websocket_endpoint(websocket: WebSocket):
916
 
917
  state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
918
  if state_payload:
919
- await websocket.send_json(state_payload)
920
- elif p_type == "update_robot_ee":
 
 
921
  pos = payload.get("pos")
922
  async with executor_lock:
923
  def move_robot_ee():
@@ -954,7 +1405,7 @@ async def websocket_endpoint(websocket: WebSocket):
954
 
955
  state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
956
  if state_payload:
957
- await websocket.send_json(state_payload)
958
  elif p_type in ("camera_rotate", "camera_pan", "camera_zoom"):
959
  pass
960
 
@@ -963,9 +1414,18 @@ async def websocket_endpoint(websocket: WebSocket):
963
  except Exception as e:
964
  print(f"WS Exception: {e}")
965
  finally:
966
- conversation_manager.clear()
967
- if settle_task:
968
- settle_task.cancel()
 
 
 
 
 
 
 
 
 
969
  if __name__ == "__main__":
970
  port = int(os.environ.get("PORT", 8000))
971
  uvicorn.run("interactive_server:app", host="0.0.0.0", port=port, reload=False)
 
2
  import os
3
  import json
4
  import asyncio
5
+ import math
6
+ import time
7
+ import threading
8
+ import uuid
9
  from typing import Optional
10
  from fastapi import FastAPI, WebSocket, WebSocketDisconnect
11
  from fastapi.staticfiles import StaticFiles
 
20
  sys.path.insert(0, PROJECT_SRC)
21
  from dotenv import load_dotenv
22
  load_dotenv()
23
+ from main import PandaApp
24
+ from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner
25
+ from llm_panda.plan_verifier import PlanVerifier
26
+ from llm_panda import config
27
+ from llm_panda.execution.cancellation import ExecutionInterrupted
28
+ from frontend.web_runtime import WebRuntime
29
  import pybullet_data
30
  from pybullet_object_models import ycb_objects
31
  app = FastAPI(title="LLM-Panda Web-Embedded PyBullet Simulation")
 
41
  async def get():
42
  html_file = os.path.join(static_dir, "index.html")
43
  if os.path.exists(html_file):
44
+ with open(html_file, "r", encoding="utf-8") as f:
45
+ return HTMLResponse(
46
+ content=f.read(),
47
+ status_code=200,
48
+ headers={
49
+ "Cache-Control": "no-store, no-cache, must-revalidate",
50
+ "Pragma": "no-cache",
51
+ "Expires": "0",
52
+ },
53
+ )
54
  return HTMLResponse(content="<h1>index.html not found!</h1>", status_code=404)
55
  # Global variables to track the current active simulation, lock, and thread lock
56
  current_sim: Optional[PandaApp] = None
57
  executor_lock = asyncio.Lock()
58
  pybullet_lock = threading.RLock()
59
+ pipeline_executing = False
60
+ web_runtime = WebRuntime()
61
+ command_worker_task = None
62
+ physics_settle_task = None
63
+
64
+
65
+ def _finite_vec3(value):
66
+ return (
67
+ isinstance(value, (list, tuple))
68
+ and len(value) >= 3
69
+ and all(
70
+ isinstance(component, (int, float))
71
+ and math.isfinite(component)
72
+ for component in value[:3]
73
+ )
74
+ )
75
+
76
+
77
+ def _clamp_manual_target(position, target_type="object"):
78
+ """Keep browser-controlled targets inside the supported workspace."""
79
+ if not _finite_vec3(position):
80
+ raise ValueError("Manual target must contain three finite coordinates")
81
+ x, y, z = (float(value) for value in position[:3])
82
+ x = min(max(x, -0.10), 0.90)
83
+ y = min(max(y, -0.65), 0.65)
84
+ z = min(max(z, 0.08 if target_type == "robot_ee" else 0.03), 0.90)
85
+
86
+ cx, cy = config.TABLE_CENTER
87
+ hx, hy = config.TABLE_HALF_EXTENTS[:2]
88
+ if cx - hx <= x <= cx + hx and cy - hy <= y <= cy + hy:
89
+ z = max(z, config.TABLE_TOP_Z + 0.01)
90
+ tx, ty, tz = config.TRAY_POSITION
91
+ thx, thy = config.TRAY_HALF_EXTENTS[:2]
92
+ if tx - thx <= x <= tx + thx and ty - thy <= y <= ty + thy:
93
+ z = max(z, tz + 0.01)
94
+ return [x, y, z]
95
+
96
+
97
+ def _load_environment_config(path):
98
+ with open(path, "r", encoding="utf-8") as handle:
99
+ data = json.load(handle)
100
+ required = {"table", "tray", "robot"}
101
+ if not isinstance(data, dict) or not required.issubset(data):
102
+ raise ValueError("File được chọn khΓ΄ng phαΊ£i environment JSON hợp lệ.")
103
+ if "objects" in data and not isinstance(data["objects"], list):
104
+ raise ValueError("Trường objects cα»§a environment phαΊ£i lΓ  mα»™t danh sΓ‘ch.")
105
+ return data
106
+
107
+
108
+ def _list_environment_files(directory):
109
+ files = []
110
+ for filename in sorted(os.listdir(directory)):
111
+ if not filename.endswith(".json") or filename.endswith(".semantics.json"):
112
+ continue
113
+ path = os.path.join(directory, filename)
114
+ try:
115
+ _load_environment_config(path)
116
+ except (OSError, ValueError, json.JSONDecodeError):
117
+ continue
118
+ files.append(filename)
119
+ return files
120
  def get_init_payload(sim: PandaApp) -> dict:
121
  """Gathers the initial static geometry and YCB object definitions."""
122
  with pybullet_lock:
 
162
  vis_local_pos = list(vis_pos_com)
163
  vis_local_ori = list(vis_ori_com)
164
 
165
+ import os
166
+ if not web_obj and vd[4]:
167
+ mesh_path = vd[4].decode('utf-8')
168
+ web_obj = os.path.basename(mesh_path)
169
+ if not folder:
170
+ folder = os.path.basename(os.path.dirname(mesh_path))
171
+ candidate_mtls = [
172
+ mesh_path + ".mtl",
173
+ os.path.splitext(mesh_path)[0] + ".mtl",
174
+ ]
175
+ matching_mtl = next(
176
+ (
177
+ candidate
178
+ for candidate in candidate_mtls
179
+ if os.path.isfile(candidate)
180
+ ),
181
+ None,
182
+ )
183
+ if not web_mtl and matching_mtl:
184
+ web_mtl = os.path.basename(matching_mtl)
185
 
186
  objects_info[name] = {
187
  "class": cls,
 
359
  return score, md
360
 
361
  def run_pipeline_threadsafe(
 
362
  user_prompt: str,
363
  loop,
364
  use_mock: bool,
365
+ runtime: WebRuntime,
366
+ cancellation_token,
367
+ generation: int,
368
+ task_id: str,
369
  camera_state: Optional[dict] = None,
 
370
  ):
371
  """Runs the planning, validation, execution with image streaming, and scoring using closed-loop execution monitor."""
372
  global current_sim, pipeline_executing
373
+ pipeline_executing = True
374
+ current_sim.pipeline.set_cancellation_token(cancellation_token)
375
+
376
+ def publish(payload: dict, journal: bool = True):
377
+ payload = {**payload, "task_id": task_id, "generation": generation}
378
+ runtime.publish_threadsafe(payload, loop, journal=journal)
379
 
380
  def log(message: str, step: Optional[int] = None):
381
  try:
382
  print(f"[WS Log] {message}", flush=True)
383
  except Exception:
384
  pass
385
+ publish({"type": "log", "message": message, "step": step})
 
 
 
386
 
387
  # Step 1: Planning
388
  log("⏳ [1/5] TΓ΄i Δ‘ang suy nghΔ© cΓ‘ch thα»±c hiện...")
 
402
  with pybullet_lock:
403
  current_sim.pipeline.agent = LLMAgent(
404
  planner=planner,
405
+ conversation_manager=runtime.conversation_manager,
406
  )
407
 
408
+ try:
409
+ MAX_REPLANS = max(0, int(os.environ.get("MAX_REPLANS", "3")))
410
+ except ValueError:
411
+ MAX_REPLANS = 3
412
  last_failed_sig = None
413
  last_failed_state_sig = None
414
  resolved_goal = None
 
418
  last_stream_time = [0.0]
419
  throttle_interval = 0.033
420
 
421
+ def wrapped_step():
422
+ cancellation_token.checkpoint()
423
+ original_step()
424
  if not current_sim.gui:
425
  time.sleep(0.001)
426
  curr_time = time.time()
 
428
  last_stream_time[0] = curr_time
429
  state_payload = get_simulation_state_payload(current_sim)
430
  if state_payload:
431
+ publish(state_payload, journal=False)
 
 
 
432
 
433
+ for attempt in range(MAX_REPLANS + 1):
434
+ cancellation_token.checkpoint()
435
+ if attempt > 0:
436
+ runtime.set_status("replanning", generation=generation)
437
+ publish({"type": "execution_status", "state": "replanning"})
438
  log(f"[MONITOR] Re-plan attempt {attempt}/{MAX_REPLANS} due to: {last_failed_sig}")
439
  log("⏳ [1/5] TΓ΄i Δ‘ang suy nghΔ© cΓ‘ch thα»±c hiện...")
440
 
 
462
  }
463
  state_sig = json.dumps(state_sig_dict, sort_keys=True)
464
 
465
+ try:
466
+ with pybullet_lock:
467
+ llm_start_time = time.time()
468
+ planning_instruction = (
469
  resolved_goal.canonical_instruction
470
  if attempt > 0 and resolved_goal is not None
471
  else user_prompt
472
  )
473
  current_sim.pipeline.agent.last_outcome = None
474
  plan_kwargs = {
475
+ "previous_failed_reasons": last_failed_sig,
476
  }
477
  if attempt > 0:
478
  plan_kwargs["resolve_goal"] = False
479
  plan = current_sim.pipeline.agent.plan(
480
+ planning_instruction,
481
  state_text,
482
  **plan_kwargs,
483
  )
484
+ outcome = current_sim.pipeline.agent.last_outcome
 
 
485
  if attempt == 0 and outcome is not None:
486
  resolved_goal = outcome.resolved_goal
487
  llm_time = time.time() - llm_start_time
488
+ cancellation_token.checkpoint()
489
 
490
  # Summarize plan
491
  targets = []
 
533
  "args": args
534
  })
535
 
536
+ publish({"type": "plan", "plan": plan_steps, "summary": summary_msg, "llm_time": llm_time})
 
 
 
537
 
538
  if plan and plan[0].get("function") in ("clarify", "reject"):
539
  log(f"Robot phαΊ£n hα»“i: {summary_msg}")
540
  header_title = "PhαΊ£n hα»“i tα»« Robot" if plan[0].get("function") == "clarify" else "YΓͺu cαΊ§u bα»‹ tα»« chα»‘i"
541
  score_md = f"### {header_title}\n\n**Robot phαΊ£n hα»“i:** {summary_msg}\n"
542
+ publish({
543
+ "type": "result",
544
+ "response_type": plan[0].get("function"),
545
+ "score_display": score_md,
546
+ "score_value": 0,
547
+ "success": False,
548
+ })
 
 
 
549
  state_payload = get_simulation_state_payload(current_sim)
550
  if state_payload:
551
+ publish(state_payload, journal=False)
552
  pipeline_executing = False
553
  return
554
 
 
556
  log("⚠️ [1] KαΊΏ hoαΊ‘ch rα»—ng.")
557
  log("⏳ [5/5] Đang tΓ­nh toΓ‘n Δ‘iểm sαΊ―p xαΊΏp...")
558
  score_val, score_md = compute_and_format_score(current_sim, [], True)
559
+ publish({
560
+ "type": "result",
561
+ "score_display": score_md,
562
+ "score_value": score_val,
563
+ })
 
 
 
564
  state_payload = get_simulation_state_payload(current_sim)
565
  if state_payload:
566
+ publish(state_payload, journal=False)
567
  pipeline_executing = False
568
  return
569
 
 
583
  pipeline_executing = False
584
  return
585
 
586
+ # Step 3: PyBullet Execution (Live!)
587
+ log("⏳ [3/5] TΓ΄i bαΊ―t Δ‘αΊ§u thα»±c hiện cΓ‘c bΖ°α»›c...")
588
+ runtime.set_status("executing", generation=generation)
589
+ publish({"type": "execution_status", "state": "executing"})
590
 
591
  with pybullet_lock:
592
  pb.stepSimulation = wrapped_step
 
600
  # Trigger an initial simulation state transmission
601
  state_payload = get_simulation_state_payload(current_sim)
602
  if state_payload:
603
+ publish(state_payload, journal=False)
604
 
605
  def format_skill_vn(step_data):
606
  fn = step_data.get("function", "")
 
626
  if fn == "close_gripper": return "Đóng tay kαΊΉp"
627
  return f"{fn}"
628
 
629
+ expected_location = None
630
+ for i, step in enumerate(plan, 1):
631
+ cancellation_token.checkpoint()
632
+ runtime.set_status("executing", generation=generation, current_step=i)
633
+ publish({"type": "current_step", "step": i})
634
+ friendly_text = format_skill_vn(step)
635
  # Make the first letter lowercase for natural sentence integration
636
  if friendly_text:
637
  friendly_text = friendly_text[0].lower() + friendly_text[1:]
 
666
  log("βœ… [3] TΓ΄i Δ‘Γ£ hoΓ n tαΊ₯t cΓ‘c bΖ°α»›c.")
667
  else:
668
  log(f"❌ [3] Thα»±c thi lα»—i tαΊ‘i bΖ°α»›c {failed_step_index} '{failed_step_data.get('function')}': {step_failure_reason}")
669
+ except ExecutionInterrupted:
670
+ with pybullet_lock:
671
+ current_sim.pipeline.interrupt_hold()
672
+ raise
673
+ except Exception as e:
674
  log(f"❌ Lα»—i trong lΓΊc thα»±c thi mΓ΄ phỏng: {e}")
675
  executed_successfully = False
676
  step_failure_reason = str(e)
 
681
  # Send a final state to ensure visual sync
682
  state_payload = get_simulation_state_payload(current_sim)
683
  if state_payload:
684
+ publish(state_payload, journal=False)
685
 
686
  # Now check overall goal using execution monitor
687
  goal_completed = False
 
734
 
735
  is_success = executed_successfully and goal_completed and score_val >= 50
736
 
737
+ publish({
738
+ "type": "result",
739
+ "score_display": score_md,
740
+ "score_value": score_val,
741
+ "error_cause": error_cause,
742
+ "success": is_success,
743
+ })
744
+ current_sim.pipeline.set_cancellation_token(None)
745
+ pipeline_executing = False
746
+
747
+
748
+ async def command_worker_loop(loop):
749
+ """Serialize robot commands while allowing the newest prompt to interrupt."""
750
+ global command_worker_task, pipeline_executing
751
+ try:
752
+ while True:
753
+ command = web_runtime.take_pending()
754
+ if command is None:
755
+ return
756
+ generation = command["generation"]
757
+ task_id = command["task_id"]
758
+ interrupted = False
759
+ await web_runtime.publish({
760
+ "type": "command_accepted",
761
+ "prompt": command["prompt"],
762
+ "task_id": task_id,
763
+ "generation": generation,
764
+ })
765
+ await web_runtime.publish({
766
+ "type": "execution_status",
767
+ "state": "planning",
768
+ "task_id": task_id,
769
+ "generation": generation,
770
+ })
771
+ try:
772
+ await asyncio.to_thread(
773
+ run_pipeline_threadsafe,
774
+ command["prompt"],
775
+ loop,
776
+ command["use_mock"],
777
+ web_runtime,
778
+ command["token"],
779
+ generation,
780
+ task_id,
781
+ )
782
+ except ExecutionInterrupted as exc:
783
+ interrupted = True
784
+ pipeline_executing = False
785
+ with pybullet_lock:
786
+ if current_sim is not None and current_sim.pipeline is not None:
787
+ current_sim.pipeline.interrupt_hold()
788
+ web_runtime.set_status("interrupted", generation=generation)
789
+ await web_runtime.publish({
790
+ "type": "interrupted",
791
+ "reason": str(exc),
792
+ "task_id": task_id,
793
+ "generation": generation,
794
+ })
795
+ state_payload = await asyncio.to_thread(
796
+ get_simulation_state_payload,
797
+ current_sim,
798
+ )
799
+ if state_payload:
800
+ await web_runtime.publish(state_payload, journal=False)
801
+ except Exception as exc:
802
+ pipeline_executing = False
803
+ await web_runtime.publish({
804
+ "type": "result",
805
+ "success": False,
806
+ "error_cause": "runtime",
807
+ "score_display": f"### Lα»—i thα»±c thi\n\n{exc}",
808
+ "task_id": task_id,
809
+ "generation": generation,
810
+ })
811
+ finally:
812
+ if current_sim is not None and current_sim.pipeline is not None:
813
+ current_sim.pipeline.set_cancellation_token(None)
814
+ web_runtime.complete(
815
+ generation,
816
+ state="interrupted" if interrupted else "completed",
817
+ )
818
+ finally:
819
+ command_worker_task = None
820
+ if web_runtime.has_pending:
821
+ command_worker_task = asyncio.create_task(command_worker_loop(loop))
822
+
823
+
824
+ async def wait_for_active_task_stop(timeout=5.0):
825
+ web_runtime.cancel_all("runtime_mutation")
826
+ deadline = time.monotonic() + timeout
827
+ while web_runtime.active_token is not None and time.monotonic() < deadline:
828
+ await asyncio.sleep(0.02)
829
+ return web_runtime.active_token is None
830
+
831
+
832
+ @app.websocket("/ws")
833
  async def websocket_endpoint(websocket: WebSocket):
834
+ global current_sim, command_worker_task, physics_settle_task
835
  await websocket.accept()
836
+ await web_runtime.subscribe(websocket)
837
+ loop = asyncio.get_running_loop()
838
 
839
  # Retrieve user's desktop display preference from client query params
840
  client_wants_gui = websocket.query_params.get("gui", "false").lower() == "true"
 
842
  # Force gui = False to run PyBullet completely headless (DIRECT mode)
843
  gui = False
844
 
845
+ camera_state = {
846
  "target": [0.5, 0.0, 0.3],
847
  "dist": 1.3,
848
  "yaw": 45.0,
849
+ "pitch": -35.0
850
+ }
851
+ drag_state = {"constraint_id": None, "active": False}
 
852
 
853
+ async def physics_settle_loop():
854
  try:
855
  while True:
856
  global pipeline_executing
 
874
  pb.stepSimulation(physicsClientId=current_sim.client)
875
  await asyncio.to_thread(step)
876
 
877
+ state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
878
+ if state_payload:
879
+ await web_runtime.publish(state_payload, journal=False)
880
  await asyncio.sleep(1/30.0)
881
  except asyncio.CancelledError:
882
  pass
 
909
  except Exception:
910
  is_connected = False
911
 
912
+ # Reconnect/reload deliberately keeps the live PyBullet state.
 
 
 
 
913
  await asyncio.to_thread(init_sim)
914
  # Apply the client's visibility preference to show/hide the PyBullet GUI window on the desktop
915
  await asyncio.to_thread(set_pybullet_window_visibility, client_wants_gui)
916
 
917
  # Send environment list
918
  try:
919
+ env_files = _list_environment_files(
920
+ os.path.join(PROJECT_SRC, "envs")
921
+ )
922
+ await websocket.send_json({"type": "env_list", "envs": env_files})
923
 
924
  # Send initial static scene data (only needs to be sent once)
925
+ init_payload = await asyncio.to_thread(get_init_payload, current_sim)
926
+ web_runtime.latest_init = init_payload
927
+ await websocket.send_json(init_payload)
928
  # Send the first simulation state to sync objects and joints
929
  state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
930
+ if state_payload:
931
+ web_runtime.latest_state = state_payload
932
+ await websocket.send_json(state_payload)
933
+ await websocket.send_json(web_runtime.snapshot())
934
+
935
+ if physics_settle_task is None or physics_settle_task.done():
936
+ physics_settle_task = asyncio.create_task(physics_settle_loop())
937
 
938
+ while True:
 
939
  data = await websocket.receive_text()
940
  payload = json.loads(data)
941
 
942
  p_type = payload.get("type")
943
+ if p_type == "run":
944
+ prompt = payload.get("prompt", "")
945
+ use_mock = payload.get("mock", False)
946
+ if prompt.strip():
947
+ command = web_runtime.submit(prompt.strip(), use_mock)
948
+ await web_runtime.publish({
949
+ "type": "interrupt_requested",
950
+ "generation": command["generation"],
951
+ "task_id": command["task_id"],
952
+ })
953
+ if command_worker_task is None or command_worker_task.done():
954
+ command_worker_task = asyncio.create_task(
955
+ command_worker_loop(loop)
956
+ )
957
+
958
+ elif p_type == "cancel":
959
+ if web_runtime.cancel_all("user_cancelled"):
960
+ await web_runtime.publish({
961
+ "type": "interrupt_requested",
962
+ "generation": web_runtime.active_generation,
963
+ })
964
 
965
 
966
+ elif p_type == "mouse_pick_start":
967
+ if web_runtime.active_token is not None:
968
+ if not await wait_for_active_task_stop():
969
+ await websocket.send_json({
970
+ "type": "drag_rejected",
971
+ "reason": "Robot chΖ°a dα»«ng an toΓ n.",
972
+ })
973
+ continue
974
+ rayFrom = payload.get("rayFrom")
975
+ rayTo = payload.get("rayTo")
976
+ requested_type = payload.get("target_type")
977
+ requested_name = payload.get("object_id")
978
+ if _finite_vec3(rayFrom) and _finite_vec3(rayTo):
979
+ async with executor_lock:
980
+ def do_pick():
981
+ with pybullet_lock:
982
+ if drag_state.get("constraint_id") is not None:
983
+ pb.removeConstraint(
984
+ drag_state["constraint_id"],
985
+ physicsClientId=current_sim.client,
986
+ )
987
+ hit = pb.rayTest(
988
+ rayFrom,
989
+ rayTo,
990
+ physicsClientId=current_sim.client,
991
+ )[0]
992
+ hit_uid, link_index, hit_pos = hit[0], hit[1], hit[3]
993
+ drag_id = uuid.uuid4().hex
994
+
995
+ if requested_type == "robot_ee":
996
+ if hit_uid != current_sim.controller.robot_id:
997
+ return None
998
+ drag_state.update({
999
+ "drag_id": drag_id,
1000
+ "target_type": "robot_ee",
1001
+ "object_name": None,
1002
+ "constraint_id": None,
1003
+ "active": True,
1004
+ })
1005
+ return dict(drag_state)
1006
+
1007
+ object_id = current_sim.scene.name_to_id(
1008
+ requested_name
1009
+ )
1010
+ if object_id is None:
1011
+ return None
1012
+ mass = pb.getDynamicsInfo(
1013
+ object_id,
1014
+ -1,
1015
+ physicsClientId=current_sim.client,
1016
+ )[0]
1017
+ if mass <= 0:
1018
+ return None
1019
+ pos, _ = pb.getBasePositionAndOrientation(
1020
+ object_id,
1021
+ physicsClientId=current_sim.client,
1022
+ )
1023
+ constraint_id = pb.createConstraint(
1024
+ parentBodyUniqueId=object_id,
1025
+ parentLinkIndex=-1,
1026
+ childBodyUniqueId=-1,
1027
+ childLinkIndex=-1,
1028
+ jointType=pb.JOINT_POINT2POINT,
1029
+ jointAxis=[0, 0, 0],
1030
+ parentFramePosition=[0, 0, 0],
1031
+ childFramePosition=pos,
1032
+ physicsClientId=current_sim.client,
1033
+ )
1034
+ pb.changeConstraint(
1035
+ constraint_id,
1036
+ maxForce=500,
1037
+ physicsClientId=current_sim.client,
1038
+ )
1039
+ drag_state.update({
1040
+ "drag_id": drag_id,
1041
+ "target_type": "object",
1042
+ "object_name": requested_name,
1043
+ "constraint_id": constraint_id,
1044
+ "active": True,
1045
+ })
1046
+ return dict(drag_state)
1047
+ started = await asyncio.to_thread(do_pick)
1048
+
1049
+ if not started:
1050
+ await websocket.send_json({
1051
+ "type": "drag_rejected",
1052
+ "reason": "VαΊ­t được chọn trΓͺn web khΓ΄ng khα»›p scene vαΊ­t lΓ½.",
1053
+ })
1054
+ continue
1055
+ await websocket.send_json({
1056
+ "type": "drag_started",
1057
+ "drag_id": started["drag_id"],
1058
+ "target_type": started["target_type"],
1059
+ "object_id": started.get("object_name"),
1060
+ })
1061
+
1062
+ if (
1063
+ started["target_type"] == "object"
1064
+ and (
1065
+ drag_state.get("task") is None
1066
+ or drag_state["task"].done()
1067
+ )
1068
+ ):
1069
+ async def drag_loop():
1070
+ while drag_state.get("active") and drag_state.get("constraint_id") is not None:
1071
  async with executor_lock:
1072
  def step():
1073
  with pybullet_lock:
 
1077
  state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
1078
  if state_payload:
1079
  try:
1080
+ await web_runtime.publish(state_payload, journal=False)
1081
  except Exception:
1082
  break
1083
  await asyncio.sleep(1/60.0)
1084
  drag_state["task"] = asyncio.create_task(drag_loop())
1085
 
1086
+ elif p_type == "mouse_pick_update":
1087
+ targetPos = payload.get("targetPos")
1088
+ drag_id = payload.get("drag_id")
1089
+ if (
1090
+ drag_id
1091
+ and drag_id == drag_state.get("drag_id")
1092
+ and _finite_vec3(targetPos)
1093
+ ):
1094
+ target_pos = _clamp_manual_target(
1095
+ targetPos,
1096
+ drag_state.get("target_type", "object"),
1097
+ )
1098
+ async with executor_lock:
1099
+ def do_update():
1100
+ with pybullet_lock:
1101
+ if drag_state.get("target_type") == "robot_ee":
1102
+ link_state = pb.getLinkState(
1103
+ current_sim.controller.robot_id,
1104
+ current_sim.controller.ee_index,
1105
+ physicsClientId=current_sim.client,
1106
+ )
1107
+ solution = pb.calculateInverseKinematics(
1108
+ current_sim.controller.robot_id,
1109
+ current_sim.controller.ee_index,
1110
+ target_pos,
1111
+ link_state[1],
1112
+ lowerLimits=current_sim.controller._lower_limits,
1113
+ upperLimits=current_sim.controller._upper_limits,
1114
+ jointRanges=current_sim.controller._joint_ranges,
1115
+ restPoses=current_sim.controller._rest_poses,
1116
+ maxNumIterations=200,
1117
+ residualThreshold=1e-5,
1118
+ physicsClientId=current_sim.client,
1119
+ )
1120
+ for idx, q in enumerate(solution[:7]):
1121
+ pb.resetJointState(
1122
+ current_sim.controller.robot_id,
1123
+ idx,
1124
+ q,
1125
+ physicsClientId=current_sim.client,
1126
+ )
1127
+ elif drag_state.get("constraint_id") is not None:
1128
+ pb.changeConstraint(
1129
+ drag_state["constraint_id"],
1130
+ target_pos,
1131
+ maxForce=500,
1132
+ physicsClientId=current_sim.client,
1133
+ )
1134
+ await asyncio.to_thread(do_update)
1135
+ state_payload = await asyncio.to_thread(
1136
+ get_simulation_state_payload,
1137
+ current_sim,
1138
+ )
1139
+ if state_payload:
1140
+ await web_runtime.publish(state_payload, journal=False)
1141
+
1142
+ elif p_type == "mouse_pick_end":
1143
+ drag_id = payload.get("drag_id")
1144
+ if drag_id != drag_state.get("drag_id"):
1145
+ continue
1146
+ drag_state["active"] = False
1147
+ async with executor_lock:
1148
+ def do_end():
1149
+ with pybullet_lock:
1150
  if drag_state.get("constraint_id") is not None:
1151
+ pb.removeConstraint(drag_state["constraint_id"], physicsClientId=current_sim.client)
1152
+ drag_state["constraint_id"] = None
1153
+ if drag_state.get("target_type") == "robot_ee":
1154
+ current_sim.controller.hold_current_pose()
1155
+ await asyncio.to_thread(do_end)
1156
+ drag_state["drag_id"] = None
1157
+ drag_state["target_type"] = None
1158
+ for _ in range(20):
1159
+ with pybullet_lock:
1160
+ pb.stepSimulation(physicsClientId=current_sim.client)
1161
+ state_payload = await asyncio.to_thread(
1162
+ get_simulation_state_payload,
1163
+ current_sim,
1164
+ )
1165
+ if state_payload:
1166
+ await web_runtime.publish(state_payload, journal=False)
1167
+
1168
+ elif p_type == "spawn_catalog_object":
1169
+ if web_runtime.active_token is not None:
1170
+ if not await wait_for_active_task_stop():
1171
+ continue
1172
+ folder = payload.get("folder")
1173
+ position = payload.get("position")
1174
+ if not _finite_vec3(position):
1175
+ continue
1176
+ spawn_position = _clamp_manual_target(position, "object")
1177
+ async with executor_lock:
1178
+ def spawn_object():
1179
+ with pybullet_lock:
1180
+ return current_sim.env_builder.spawn_catalog_object(
1181
+ folder,
1182
+ spawn_position,
1183
+ )
1184
+ try:
1185
+ _, object_name = await asyncio.to_thread(spawn_object)
1186
+ except (ValueError, OSError) as exc:
1187
+ await websocket.send_json({
1188
+ "type": "spawn_rejected",
1189
+ "reason": str(exc),
1190
+ })
1191
+ continue
1192
+ for _ in range(30):
1193
+ with pybullet_lock:
1194
+ pb.stepSimulation(physicsClientId=current_sim.client)
1195
+ init_payload = await asyncio.to_thread(
1196
+ get_init_payload,
1197
+ current_sim,
1198
+ )
1199
+ web_runtime.latest_init = init_payload
1200
+ state_payload = await asyncio.to_thread(
1201
+ get_simulation_state_payload,
1202
+ current_sim,
1203
+ )
1204
+ await web_runtime.publish({
1205
+ "type": "object_added",
1206
+ "name": object_name,
1207
+ "config": init_payload["objects"][object_name],
1208
+ "state": (
1209
+ state_payload.get("objects", {}).get(object_name)
1210
+ if state_payload
1211
+ else None
1212
+ ),
1213
+ }, journal=False)
1214
+ if state_payload:
1215
+ await web_runtime.publish(state_payload, journal=False)
1216
+ await web_runtime.publish({
1217
+ "type": "log",
1218
+ "message": f"Đã thΓͺm '{object_name}' vΓ o mΓ΄i trường.",
1219
+ })
1220
+
1221
+ elif p_type == "delete_object":
1222
+ if web_runtime.active_token is not None:
1223
+ if not await wait_for_active_task_stop():
1224
+ continue
1225
+ object_name = payload.get("name")
1226
+ async with executor_lock:
1227
+ def delete_object():
1228
+ with pybullet_lock:
1229
+ object_id = current_sim.scene.name_to_id(
1230
+ object_name
1231
+ )
1232
+ if object_id is None:
1233
+ return False
1234
+ if current_sim.pipeline._carried == object_id:
1235
+ return False
1236
+ pb.removeBody(
1237
+ object_id,
1238
+ physicsClientId=current_sim.client,
1239
+ )
1240
+ current_sim.scene.unregister_object(object_id)
1241
+ return True
1242
+ deleted = await asyncio.to_thread(delete_object)
1243
+ if not deleted:
1244
+ await websocket.send_json({
1245
+ "type": "delete_rejected",
1246
+ "reason": "KhΓ΄ng thể xΓ³a vαΊ­t Δ‘ang được giα»― hoαΊ·c khΓ΄ng tα»“n tαΊ‘i.",
1247
+ })
1248
+ continue
1249
+ await web_runtime.publish({
1250
+ "type": "object_removed",
1251
+ "name": object_name,
1252
+ }, journal=False)
1253
+ state_payload = await asyncio.to_thread(
1254
+ get_simulation_state_payload,
1255
+ current_sim,
1256
+ )
1257
+ if state_payload:
1258
+ await web_runtime.publish(state_payload, journal=False)
1259
+ await web_runtime.publish({
1260
+ "type": "log",
1261
+ "message": f"Đã xóa '{object_name}' khỏi môi trường.",
1262
+ })
1263
 
1264
  elif p_type == "reset":
1265
+ if not await wait_for_active_task_stop():
1266
+ await web_runtime.publish({
1267
+ "type": "log",
1268
+ "message": "KhΓ΄ng thể reset khi robot chΖ°a dα»«ng an toΓ n.",
1269
+ })
1270
+ continue
1271
  async with executor_lock:
1272
  def reset_sim():
1273
  with pybullet_lock:
1274
  current_sim.reset_objects(seed=0)
1275
  current_sim.controller.reset_to_home()
1276
+ await asyncio.to_thread(reset_sim)
1277
+ web_runtime.conversation_manager.clear()
1278
+ web_runtime.clear_task_history()
1279
 
1280
  state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
1281
  if state_payload:
1282
+ await web_runtime.publish(state_payload, journal=False)
1283
+ await web_runtime.publish({"type": "log", "message": "πŸ”„ Đã reset mΓ΄i trường mΓ΄ phỏng."})
1284
 
1285
  elif p_type == "change_env":
1286
+ if not await wait_for_active_task_stop():
1287
+ await web_runtime.publish({
1288
+ "type": "log",
1289
+ "message": "KhΓ΄ng thể Δ‘α»•i mΓ΄i trường khi robot chΖ°a dα»«ng an toΓ n.",
1290
+ })
1291
+ continue
1292
  env_file = payload.get("env")
1293
+ if (
1294
+ not isinstance(env_file, str)
1295
+ or os.path.basename(env_file) != env_file
1296
+ ):
1297
+ await websocket.send_json({
1298
+ "type": "environment_rejected",
1299
+ "reason": "TΓͺn environment khΓ΄ng hợp lệ.",
1300
+ })
1301
+ continue
1302
+ env_path = os.path.join(PROJECT_SRC, "envs", env_file)
1303
+ try:
1304
+ _load_environment_config(env_path)
1305
+ except (
1306
+ OSError,
1307
+ ValueError,
1308
+ json.JSONDecodeError,
1309
+ ) as exc:
1310
+ await websocket.send_json({
1311
+ "type": "environment_rejected",
1312
+ "reason": str(exc),
1313
+ })
1314
+ continue
1315
+ async with executor_lock:
1316
  def change_sim_env():
1317
  with pybullet_lock:
1318
  current_sim.change_environment(env_path)
1319
+ await asyncio.to_thread(change_sim_env)
1320
+ web_runtime.conversation_manager.clear()
1321
+ web_runtime.clear_task_history()
1322
 
1323
  # Send the new static data
1324
+ init_payload = await asyncio.to_thread(get_init_payload, current_sim)
1325
+ web_runtime.latest_init = init_payload
1326
+ await web_runtime.publish(init_payload, journal=False)
1327
 
1328
  # Send the new dynamic state
1329
  state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
1330
  if state_payload:
1331
+ await web_runtime.publish(state_payload, journal=False)
1332
+ await web_runtime.publish({"type": "log", "message": f"🌍 Đã chuyển sang mΓ΄i trường {env_file}."})
1333
 
1334
+ elif p_type == "update_object_pose":
1335
+ if web_runtime.active_token is not None:
1336
+ continue
1337
  name = payload.get("name")
1338
  pos = payload.get("pos")
1339
  ori = payload.get("ori")
 
1347
 
1348
  state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
1349
  if state_payload:
1350
+ await web_runtime.publish(state_payload, journal=False)
1351
 
1352
+ elif p_type == "update_joints":
1353
+ if web_runtime.active_token is not None:
1354
+ continue
1355
  joints_data = payload.get("joints")
1356
  async with executor_lock:
1357
  def move_joints():
 
1365
 
1366
  state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
1367
  if state_payload:
1368
+ await web_runtime.publish(state_payload, journal=False)
1369
+ elif p_type == "update_robot_ee":
1370
+ if web_runtime.active_token is not None:
1371
+ continue
1372
  pos = payload.get("pos")
1373
  async with executor_lock:
1374
  def move_robot_ee():
 
1405
 
1406
  state_payload = await asyncio.to_thread(get_simulation_state_payload, current_sim)
1407
  if state_payload:
1408
+ await web_runtime.publish(state_payload, journal=False)
1409
  elif p_type in ("camera_rotate", "camera_pan", "camera_zoom"):
1410
  pass
1411
 
 
1414
  except Exception as e:
1415
  print(f"WS Exception: {e}")
1416
  finally:
1417
+ drag_state["active"] = False
1418
+ if drag_state.get("constraint_id") is not None:
1419
+ try:
1420
+ with pybullet_lock:
1421
+ pb.removeConstraint(
1422
+ drag_state["constraint_id"],
1423
+ physicsClientId=current_sim.client,
1424
+ )
1425
+ except Exception:
1426
+ pass
1427
+ drag_state["constraint_id"] = None
1428
+ await web_runtime.unsubscribe(websocket)
1429
  if __name__ == "__main__":
1430
  port = int(os.environ.get("PORT", 8000))
1431
  uvicorn.run("interactive_server:app", host="0.0.0.0", port=port, reload=False)
frontend/web_runtime.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Server-owned web runtime surviving browser reconnects.
2
+
3
+ The PyBullet world remains the source of truth. This object persists only
4
+ session/UI metadata, conversation state, task lifecycle, and a bounded event
5
+ journal so a reloaded page can catch up without resetting the simulation.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ from collections import deque
12
+ import threading
13
+ import time
14
+ import uuid
15
+
16
+ from llm_panda.conversation import ConversationManager
17
+ from llm_panda.execution.cancellation import CancellationToken
18
+
19
+
20
+ class WebRuntime:
21
+ def __init__(self, max_events: int = 750):
22
+ self.runtime_id = uuid.uuid4().hex
23
+ self.conversation_manager = ConversationManager(
24
+ session_id=self.runtime_id
25
+ )
26
+ self._lock = threading.RLock()
27
+ self._subscribers = set()
28
+ self._events = deque(maxlen=max_events)
29
+ self._seq = 0
30
+ self._generation = 0
31
+ self._active = None
32
+ self._pending = None
33
+ self.execution_state = "idle"
34
+ self.latest_plan = None
35
+ self.latest_result = None
36
+ self.latest_state = None
37
+ self.latest_init = None
38
+ self.current_step = None
39
+
40
+ async def subscribe(self, websocket):
41
+ with self._lock:
42
+ self._subscribers.add(websocket)
43
+
44
+ async def unsubscribe(self, websocket):
45
+ with self._lock:
46
+ self._subscribers.discard(websocket)
47
+
48
+ def submit(self, prompt: str, use_mock: bool = False):
49
+ with self._lock:
50
+ self._generation += 1
51
+ command = {
52
+ "task_id": uuid.uuid4().hex,
53
+ "generation": self._generation,
54
+ "prompt": prompt,
55
+ "use_mock": bool(use_mock),
56
+ "created_at": time.time(),
57
+ }
58
+ if self._active is not None:
59
+ self._active["token"].request("superseded_by_new_command")
60
+ self.execution_state = "interrupt_requested"
61
+ else:
62
+ self.execution_state = "planning"
63
+ # Latest-wins for commands not yet started.
64
+ self._pending = command
65
+ return dict(command)
66
+
67
+ def take_pending(self):
68
+ with self._lock:
69
+ command = self._pending
70
+ self._pending = None
71
+ if command is None:
72
+ return None
73
+ token = CancellationToken()
74
+ command = {**command, "token": token}
75
+ self._active = command
76
+ self.execution_state = "planning"
77
+ self.current_step = None
78
+ self.latest_result = None
79
+ return command
80
+
81
+ def request_interrupt(self, reason="user_cancelled"):
82
+ with self._lock:
83
+ if self._active is None:
84
+ return False
85
+ self._active["token"].request(reason)
86
+ self.execution_state = "interrupt_requested"
87
+ return True
88
+
89
+ def cancel_all(self, reason="user_cancelled"):
90
+ """Cancel active work and discard commands that have not started."""
91
+ with self._lock:
92
+ self._pending = None
93
+ if self._active is None:
94
+ self.execution_state = "idle"
95
+ return False
96
+ self._active["token"].request(reason)
97
+ self.execution_state = "interrupt_requested"
98
+ return True
99
+
100
+ def set_status(self, state, generation=None, current_step=None):
101
+ with self._lock:
102
+ if (
103
+ generation is not None
104
+ and self._active is not None
105
+ and generation != self._active["generation"]
106
+ ):
107
+ return False
108
+ self.execution_state = state
109
+ self.current_step = current_step
110
+ return True
111
+
112
+ def complete(self, generation, state="completed"):
113
+ with self._lock:
114
+ if (
115
+ self._active is None
116
+ or generation != self._active["generation"]
117
+ ):
118
+ return False
119
+ self._active = None
120
+ self.execution_state = (
121
+ "planning" if self._pending is not None else state
122
+ )
123
+ self.current_step = None
124
+ return True
125
+
126
+ @property
127
+ def active_token(self):
128
+ with self._lock:
129
+ return self._active["token"] if self._active else None
130
+
131
+ @property
132
+ def active_generation(self):
133
+ with self._lock:
134
+ return self._active["generation"] if self._active else None
135
+
136
+ @property
137
+ def has_pending(self):
138
+ with self._lock:
139
+ return self._pending is not None
140
+
141
+ def _prepare_event(self, payload, journal=True):
142
+ event = dict(payload)
143
+ with self._lock:
144
+ event_generation = event.get("generation")
145
+ is_current = (
146
+ event_generation is None
147
+ or event_generation >= self._generation
148
+ )
149
+ if event.get("type") == "state":
150
+ self.latest_state = event
151
+ elif event.get("type") == "plan" and is_current:
152
+ self.latest_plan = event
153
+ elif event.get("type") == "result" and is_current:
154
+ self.latest_result = event
155
+ if journal:
156
+ self._seq += 1
157
+ event["seq"] = self._seq
158
+ self._events.append(event)
159
+ return event
160
+
161
+ async def publish(self, payload, journal=True):
162
+ event = self._prepare_event(payload, journal=journal)
163
+ with self._lock:
164
+ subscribers = list(self._subscribers)
165
+ stale = []
166
+ for websocket in subscribers:
167
+ try:
168
+ await websocket.send_json(event)
169
+ except Exception:
170
+ stale.append(websocket)
171
+ if stale:
172
+ with self._lock:
173
+ for websocket in stale:
174
+ self._subscribers.discard(websocket)
175
+ return event
176
+
177
+ def publish_threadsafe(self, payload, loop, journal=True):
178
+ return asyncio.run_coroutine_threadsafe(
179
+ self.publish(payload, journal=journal),
180
+ loop,
181
+ )
182
+
183
+ def events_after(self, seq):
184
+ with self._lock:
185
+ return [
186
+ dict(event)
187
+ for event in self._events
188
+ if event.get("seq", 0) > int(seq or 0)
189
+ ]
190
+
191
+ def clear_task_history(self):
192
+ """Clear UI/task history after an explicit reset, preserving sequence."""
193
+ with self._lock:
194
+ self._events.clear()
195
+ self.latest_plan = None
196
+ self.latest_result = None
197
+ self.current_step = None
198
+ self.execution_state = "idle"
199
+
200
+ def snapshot(self):
201
+ with self._lock:
202
+ pending = self.conversation_manager.pending
203
+ return {
204
+ "type": "runtime_snapshot",
205
+ "runtime_id": self.runtime_id,
206
+ "execution_state": self.execution_state,
207
+ "active_task_id": (
208
+ self._active["task_id"] if self._active else None
209
+ ),
210
+ "active_prompt": (
211
+ self._active["prompt"] if self._active else None
212
+ ),
213
+ "generation": (
214
+ self._active["generation"]
215
+ if self._active
216
+ else self._generation
217
+ ),
218
+ "current_step": self.current_step,
219
+ "plan": self.latest_plan,
220
+ "result": self.latest_result,
221
+ "state": self.latest_state,
222
+ "events": [dict(event) for event in self._events],
223
+ "last_event_seq": self._seq,
224
+ "conversation_pending": pending is not None,
225
+ }
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__/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__/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/conversation/manager.py CHANGED
@@ -119,7 +119,12 @@ class ConversationManager:
119
  self._pending = None
120
  return True
121
 
122
- def contextualize(self, user_command: str, scene_state=None) -> str:
 
 
 
 
 
123
  """Return the effective instruction for the planner.
124
 
125
  A normal one-shot command is returned byte-for-byte. Only a reply made
@@ -131,7 +136,7 @@ class ConversationManager:
131
  if self._pending is None:
132
  return command
133
 
134
- if self._looks_like_new_command(command):
135
  self._pending = None
136
  return command
137
 
@@ -251,6 +256,11 @@ class ConversationManager:
251
  self._pending = None
252
  self._turns.clear()
253
 
 
 
 
 
 
254
  def _expire_pending_locked(self, now: Optional[float] = None) -> None:
255
  if self._pending is None:
256
  return
 
119
  self._pending = None
120
  return True
121
 
122
+ def contextualize(
123
+ self,
124
+ user_command: str,
125
+ scene_state=None,
126
+ use_lexical_boundary: bool = True,
127
+ ) -> str:
128
  """Return the effective instruction for the planner.
129
 
130
  A normal one-shot command is returned byte-for-byte. Only a reply made
 
136
  if self._pending is None:
137
  return command
138
 
139
+ if use_lexical_boundary and self._looks_like_new_command(command):
140
  self._pending = None
141
  return command
142
 
 
256
  self._pending = None
257
  self._turns.clear()
258
 
259
+ def clear_pending(self) -> None:
260
+ """Close only the unresolved request while preserving bounded history."""
261
+ with self._lock:
262
+ self._pending = None
263
+
264
  def _expire_pending_locked(self, now: Optional[float] = None) -> None:
265
  if self._pending is None:
266
  return
llm_panda/conversation/models.py CHANGED
@@ -36,6 +36,8 @@ class GoalPredicate:
36
  location_id: Optional[str] = None
37
  relation: Optional[str] = None
38
  relative_to: Optional[str] = None
 
 
39
 
40
 
41
  @dataclass(frozen=True)
 
36
  location_id: Optional[str] = None
37
  relation: Optional[str] = None
38
  relative_to: Optional[str] = None
39
+ target_position: Optional[tuple[float, float]] = None
40
+ tolerance: Optional[float] = None
41
 
42
 
43
  @dataclass(frozen=True)
llm_panda/core/env_builder.py CHANGED
@@ -1,6 +1,7 @@
1
  import json
2
  import os
3
  import random
 
4
  import pybullet as pb
5
  from pybullet_object_models import ycb_objects
6
 
@@ -45,6 +46,38 @@ class EnvBuilder:
45
  def load_configs(self):
46
  with open(self.env_json_path, 'r', encoding='utf-8') as f:
47
  self.env_data = json.load(f)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
  # Dynamically patch config.py with loaded environment settings
50
  # to ensure backward compatibility with pipeline_executor.py and other modules
@@ -141,6 +174,49 @@ class EnvBuilder:
141
  spawned.append(spawn_pos)
142
  body = _load_ycb(ycb_folder, spawn_pos, spawn_ori)
143
  self.scene.register_object(body, obj_name, obj_class)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
 
145
  def build_all(self):
146
  self.load_configs()
 
1
  import json
2
  import os
3
  import random
4
+ import re
5
  import pybullet as pb
6
  from pybullet_object_models import ycb_objects
7
 
 
46
  def load_configs(self):
47
  with open(self.env_json_path, 'r', encoding='utf-8') as f:
48
  self.env_data = json.load(f)
49
+
50
+ catalog_ref = self.env_data.get("semantic_catalog")
51
+ catalog = {}
52
+ catalog_path = None
53
+ if catalog_ref:
54
+ catalog_path = catalog_ref
55
+ if not os.path.isabs(catalog_path):
56
+ catalog_path = os.path.join(
57
+ os.path.dirname(os.path.abspath(self.env_json_path)),
58
+ catalog_path,
59
+ )
60
+ with open(catalog_path, "r", encoding="utf-8") as f:
61
+ catalog = json.load(f)
62
+ configured_objects = {
63
+ obj["name"] for obj in self.env_data.get("objects", [])
64
+ }
65
+ described_objects = set(catalog.get("objects", {}))
66
+ missing_objects = sorted(configured_objects - described_objects)
67
+ if missing_objects:
68
+ raise ValueError(
69
+ "Semantic catalog is missing configured object(s): "
70
+ + ", ".join(missing_objects)
71
+ )
72
+ missing_surfaces = sorted(
73
+ {"table", "tray"} - set(catalog.get("surfaces", {}))
74
+ )
75
+ if missing_surfaces:
76
+ raise ValueError(
77
+ "Semantic catalog is missing surface(s): "
78
+ + ", ".join(missing_surfaces)
79
+ )
80
+ self.scene.set_semantic_catalog(catalog, source=catalog_path)
81
 
82
  # Dynamically patch config.py with loaded environment settings
83
  # to ensure backward compatibility with pipeline_executor.py and other modules
 
174
  spawned.append(spawn_pos)
175
  body = _load_ycb(ycb_folder, spawn_pos, spawn_ori)
176
  self.scene.register_object(body, obj_name, obj_class)
177
+
178
+ def spawn_catalog_object(self, folder, position, name=None):
179
+ """Spawn and register one YCB catalog item at runtime.
180
+
181
+ Runtime objects receive generic, data-driven semantics so they are
182
+ immediately visible to scene state and adaptive LLM prompts without
183
+ requiring an environment-specific hard-coded object list.
184
+ """
185
+ folder_path = os.path.join(_YCB_DATA, folder)
186
+ if not (
187
+ isinstance(folder, str)
188
+ and folder.startswith("Ycb")
189
+ and os.path.isdir(folder_path)
190
+ and os.path.isfile(os.path.join(folder_path, "model.urdf"))
191
+ ):
192
+ raise ValueError(f"Unknown YCB catalog folder: {folder!r}")
193
+
194
+ stem = folder[3:] or "object"
195
+ base_name = re.sub(r"(?<!^)(?=[A-Z])", "_", stem).lower()
196
+ base_name = re.sub(r"[^a-z0-9_]+", "_", base_name).strip("_")
197
+ object_name = name or base_name or "object"
198
+ suffix = 2
199
+ while self.scene.name_to_id(object_name) is not None:
200
+ object_name = f"{base_name}_{suffix}"
201
+ suffix += 1
202
+
203
+ body = _load_ycb(folder, position)
204
+ self.scene.register_object(body, object_name, base_name)
205
+ display_name = stem.replace("_", " ")
206
+ self.scene.register_semantic_object(
207
+ object_name,
208
+ {
209
+ "display_name": {
210
+ "en": display_name,
211
+ "vi": display_name,
212
+ },
213
+ "aliases": [object_name, base_name, display_name],
214
+ "categories": ["object"],
215
+ "attributes": {"source": "runtime_ycb_catalog"},
216
+ "affordances": ["pickable", "placeable"],
217
+ },
218
+ )
219
+ return body, object_name
220
 
221
  def build_all(self):
222
  self.load_configs()
llm_panda/execution/cancellation.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cooperative cancellation primitives for interruptible robot execution."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+
7
+
8
+ class ExecutionInterrupted(RuntimeError):
9
+ """Raised at a safe checkpoint after a newer command supersedes a task."""
10
+
11
+
12
+ class CancellationToken:
13
+ """Thread-safe, dependency-free cancellation token."""
14
+
15
+ def __init__(self):
16
+ self._event = threading.Event()
17
+ self.reason = ""
18
+
19
+ def request(self, reason: str = "superseded") -> None:
20
+ self.reason = reason
21
+ self._event.set()
22
+
23
+ @property
24
+ def requested(self) -> bool:
25
+ return self._event.is_set()
26
+
27
+ def checkpoint(self) -> None:
28
+ if self.requested:
29
+ raise ExecutionInterrupted(self.reason or "interrupted")
30
+
llm_panda/execution/monitor.py CHANGED
@@ -122,6 +122,34 @@ class ExecutionMonitor:
122
  f"{predicate.object_id}.location={actual!r}, expected "
123
  f"{expected!r}"
124
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  elif predicate.type == "relation_is":
126
  obj = objects.get(predicate.object_id, {})
127
  relations = obj.get("relations", {}) or {}
 
122
  f"{predicate.object_id}.location={actual!r}, expected "
123
  f"{expected!r}"
124
  )
125
+ elif predicate.type == "position_near":
126
+ obj = objects.get(predicate.object_id, {})
127
+ actual_position = obj.get("position")
128
+ target_position = predicate.target_position
129
+ tolerance = predicate.tolerance or 0.04
130
+ same_surface = (
131
+ not predicate.location_id
132
+ or obj.get("location") == predicate.location_id
133
+ )
134
+ if (
135
+ isinstance(actual_position, (list, tuple))
136
+ and len(actual_position) >= 2
137
+ and target_position
138
+ and len(target_position) >= 2
139
+ ):
140
+ distance = (
141
+ (actual_position[0] - target_position[0]) ** 2
142
+ + (actual_position[1] - target_position[1]) ** 2
143
+ ) ** 0.5
144
+ ok = distance <= tolerance and same_surface
145
+ else:
146
+ distance = None
147
+ ok = False
148
+ detail = (
149
+ f"{predicate.object_id}.position={actual_position!r}, "
150
+ f"expected near {target_position!r} "
151
+ f"(tolerance={tolerance:.3f}, distance={distance!r})"
152
+ )
153
  elif predicate.type == "relation_is":
154
  obj = objects.get(predicate.object_id, {})
155
  relations = obj.get("relations", {}) or {}
llm_panda/execution/pipeline.py CHANGED
@@ -68,6 +68,20 @@ class ExecutionPipeline:
68
 
69
  self._carried = None
70
  self._pending_target_pos = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
  @property
73
  def _PLACE_FALL_Z(self):
@@ -88,6 +102,7 @@ class ExecutionPipeline:
88
  return reachability_fn
89
 
90
  def run_command(self, nl_command, verbose=True):
 
91
  nl_command = self._SHORTCUTS.get(nl_command.strip(), nl_command)
92
  reachability_fn = self._reachability_fn()
93
  last_failed_sig = None
@@ -196,6 +211,7 @@ class ExecutionPipeline:
196
  expected_location = None
197
  n_steps = len(plan)
198
  for i, step in enumerate(plan):
 
199
  pre_positions = {
200
  oid: pb.getBasePositionAndOrientation(oid)[0]
201
  for oid in self.scene.object_ids
@@ -351,6 +367,16 @@ class ExecutionPipeline:
351
  footprint = (min(footprint[0], 0.115), min(footprint[1], 0.115))
352
  reachable_fn = self._reachable_placement_fn()
353
  margins = (config.PLACEMENT_SAFETY_MARGIN, 0.01, 0.0)
 
 
 
 
 
 
 
 
 
 
354
 
355
  if location_id == "buffer":
356
  avoid_names = args.get("avoid", [])
@@ -376,6 +402,7 @@ class ExecutionPipeline:
376
  spots = self.scene.find_free_tray_placements(
377
  footprint, exclude_ids=[self._carried], max_results=1,
378
  reachable_fn=reachable_fn, margin=m,
 
379
  )
380
  if spots:
381
  if m < config.PLACEMENT_SAFETY_MARGIN:
@@ -384,6 +411,7 @@ class ExecutionPipeline:
384
  spots = self.scene.find_free_tray_placements(
385
  footprint, exclude_ids=[self._carried], max_results=1,
386
  reachable_fn=reachable_fn, margin=0.0, best_effort=True,
 
387
  )
388
  if spots:
389
  logger.warning("[WARN ] Tray crowded β€” using least-overlap spot "
@@ -416,6 +444,7 @@ class ExecutionPipeline:
416
  footprint, exclude_ids=[self._carried], max_results=1,
417
  reachable_fn=reachable_fn, margin=m,
418
  relative_to_pos=relative_to_pos, relation=relation,
 
419
  )
420
  if spots:
421
  return spots[0]
@@ -423,6 +452,7 @@ class ExecutionPipeline:
423
  spots = self.scene.find_free_placements(
424
  footprint, exclude_ids=[self._carried], max_results=1,
425
  reachable_fn=reachable_fn, margin=m,
 
426
  )
427
  if spots:
428
  if m < config.PLACEMENT_SAFETY_MARGIN:
@@ -431,6 +461,7 @@ class ExecutionPipeline:
431
  spots = self.scene.find_free_placements(
432
  footprint, exclude_ids=[self._carried], max_results=1,
433
  reachable_fn=reachable_fn, margin=0.0, best_effort=True,
 
434
  )
435
  if spots:
436
  logger.warning("[WARN ] Table crowded β€” using least-overlap spot "
 
68
 
69
  self._carried = None
70
  self._pending_target_pos = None
71
+ self._cancellation_token = None
72
+
73
+ def set_cancellation_token(self, token):
74
+ self._cancellation_token = token
75
+ self.controller.set_cancellation_token(token)
76
+
77
+ def _checkpoint(self):
78
+ if self._cancellation_token is not None:
79
+ self._cancellation_token.checkpoint()
80
+
81
+ def interrupt_hold(self):
82
+ """Freeze the arm at its live pose without releasing a carried object."""
83
+ self.controller.hold_current_pose()
84
+ self._pending_target_pos = None
85
 
86
  @property
87
  def _PLACE_FALL_Z(self):
 
102
  return reachability_fn
103
 
104
  def run_command(self, nl_command, verbose=True):
105
+ self._checkpoint()
106
  nl_command = self._SHORTCUTS.get(nl_command.strip(), nl_command)
107
  reachability_fn = self._reachability_fn()
108
  last_failed_sig = None
 
211
  expected_location = None
212
  n_steps = len(plan)
213
  for i, step in enumerate(plan):
214
+ self._checkpoint()
215
  pre_positions = {
216
  oid: pb.getBasePositionAndOrientation(oid)[0]
217
  for oid in self.scene.object_ids
 
367
  footprint = (min(footprint[0], 0.115), min(footprint[1], 0.115))
368
  reachable_fn = self._reachable_placement_fn()
369
  margins = (config.PLACEMENT_SAFETY_MARGIN, 0.01, 0.0)
370
+ preferred_position = args.get("target_position")
371
+ if not (
372
+ isinstance(preferred_position, (list, tuple))
373
+ and len(preferred_position) >= 2
374
+ and all(
375
+ isinstance(value, (int, float))
376
+ for value in preferred_position[:2]
377
+ )
378
+ ):
379
+ preferred_position = None
380
 
381
  if location_id == "buffer":
382
  avoid_names = args.get("avoid", [])
 
402
  spots = self.scene.find_free_tray_placements(
403
  footprint, exclude_ids=[self._carried], max_results=1,
404
  reachable_fn=reachable_fn, margin=m,
405
+ preferred_position=preferred_position,
406
  )
407
  if spots:
408
  if m < config.PLACEMENT_SAFETY_MARGIN:
 
411
  spots = self.scene.find_free_tray_placements(
412
  footprint, exclude_ids=[self._carried], max_results=1,
413
  reachable_fn=reachable_fn, margin=0.0, best_effort=True,
414
+ preferred_position=preferred_position,
415
  )
416
  if spots:
417
  logger.warning("[WARN ] Tray crowded β€” using least-overlap spot "
 
444
  footprint, exclude_ids=[self._carried], max_results=1,
445
  reachable_fn=reachable_fn, margin=m,
446
  relative_to_pos=relative_to_pos, relation=relation,
447
+ preferred_position=preferred_position,
448
  )
449
  if spots:
450
  return spots[0]
 
452
  spots = self.scene.find_free_placements(
453
  footprint, exclude_ids=[self._carried], max_results=1,
454
  reachable_fn=reachable_fn, margin=m,
455
+ preferred_position=preferred_position,
456
  )
457
  if spots:
458
  if m < config.PLACEMENT_SAFETY_MARGIN:
 
461
  spots = self.scene.find_free_placements(
462
  footprint, exclude_ids=[self._carried], max_results=1,
463
  reachable_fn=reachable_fn, margin=0.0, best_effort=True,
464
+ preferred_position=preferred_position,
465
  )
466
  if spots:
467
  logger.warning("[WARN ] Table crowded β€” using least-overlap spot "
llm_panda/llm_agent.py CHANGED
@@ -375,6 +375,17 @@ The instruction has normally passed a Goal Resolution Gate. Plan only the stated
375
  canonical goal. Never guess, omit, or emit an empty object_id/location_id. If any
376
  critical field is still ambiguous, return one structured clarify step instead of
377
  an incomplete physical action.
 
 
 
 
 
 
 
 
 
 
 
378
 
379
  ## DESTINATIONS
380
  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.
@@ -396,13 +407,10 @@ Only two destinations exist: "table" and "tray". You do NOT compute coordinates
396
  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.
397
  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.
398
 
399
- ## OBJECT PROPERTIES (FACTS)
400
- - banana: fruit, edible, yellow, light, non-metal.
401
- - pear: fruit, edible, yellow-green, light, non-metal.
402
- - soup_can: canned food, edible (contains soup), metal, heavy.
403
- - chips_can: canned snack, edible (contains chips), metal/cardboard, light.
404
- - tennis_ball: sports ball, non-food, felt/rubber, light, non-metal.
405
- - clamp: metal clamp, tool, non-food, steel/metal, heavy.
406
 
407
  ## SEMANTIC CATEGORIZATION & GENERAL SORTING LOGIC
408
  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:
@@ -427,37 +435,10 @@ Analyze if the user's instruction is valid, complete, and physically possible gi
427
  1. CLARIFICATION (clarify): Use this when the instruction is missing critical information, is ambiguous, or we cannot determine what action/object is intended.
428
  - Schema: [{"function":"clarify","args":{"message":"<Vietnamese clarifying question>","missing_fields":["object_id|destination|relation|relative_to|details"],"partial_intent":{"action":"<known action or null>","object_id":"<known object or null>","destination":"<known location or null>"}}}]
429
  - Always include `missing_fields` and `partial_intent` for clarify. Omit unknown keys from `partial_intent` instead of inventing values.
430
- - Examples:
431
- - 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?","missing_fields":["object_id"],"partial_intent":{"action":"pick_up"}}}]
432
- - 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?","missing_fields":["object_id"],"partial_intent":{"action":"pick_and_place","destination":"tray"}}}]
433
- - 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)?","missing_fields":["destination"],"partial_intent":{"action":"pick_and_place","object_id":"banana"}}}]
434
-
435
- 2. REJECTION (reject): Use this when the instruction is impossible, unsafe, or violates physical/reachability rules.
436
- - Schema: [{"function":"reject","args":{"message":"<Vietnamese friendly rejection message explaining the reason>"}}]
437
- - Examples:
438
- - 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."}}]
439
- - 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Γ³."}}]
440
- - 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."}}]
441
- - 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."}}]
442
- - 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?"}}]
443
-
444
- ## SYNONYMS (VIETNAMESE/ENGLISH)
445
- 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.
446
-
447
- ## EXAMPLES (compact, one line each)
448
- "gαΊ―p quαΊ£ chuα»‘i lΓͺn" (no destination): [{"function":"pick_up","args":{"object_id":"banana"}}]
449
- "di chuyển lon sΓΊp vΓ o khay": [{"function":"pick_up","args":{"object_id":"soup_can"}},{"function":"move_to","args":{"location_id":"tray"}},{"function":"place_down","args":{}}]
450
- carried_object="banana", "để vΓ o khay": [{"function":"move_to","args":{"location_id":"tray"}},{"function":"place_down","args":{}}]
451
- "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":{}}]
452
- "Δ‘αΊ·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":{}}]
453
- 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":{}}]
454
- "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":{}}]
455
- "Δ‘αΊ·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":{}}]
456
- "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"}}]
457
- "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"}}]
458
- "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":{}}]
459
- # 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":{}}]
460
-
461
  Respond ONLY with the JSON array. No markdown, no code fences, no explanatory text."""
462
  )
463
 
@@ -474,23 +455,93 @@ Use the current SCENE and any conversation context embedded in the instruction.
474
  Rules:
475
  1. Never guess an object. Generic words such as "quαΊ£", "lon", "vαΊ­t", or "cΓ‘i Δ‘Γ³"
476
  are ambiguous whenever multiple scene objects match.
477
- 2. If banana and pear exist, "gαΊ―p quαΊ£ lΓͺn lon chip" MUST ask which fruit. Preserve
478
- the known on_top_of chips_can relation in partial_intent.
 
479
  3. A pick-up-only request needs no destination. A pick-and-place request does.
480
  4. Use only object IDs present in SCENE. Never emit an empty identifier.
481
  5. canonical_instruction must fully express the resolved intent with canonical IDs.
482
  6. The planner receives canonical_instruction, so preserve all stated constraints
483
  and never add an unstated destination or exclusivity constraint.
484
  7. Ask one concise Vietnamese question and offer scene-valid choices when possible.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
485
 
486
  Return one JSON object with exactly:
487
  {
488
  "status": "ready|clarify|reject",
 
489
  "canonical_instruction": "<resolved instruction or empty string>",
490
  "message": "<Vietnamese question/rejection, or empty when ready>",
491
  "missing_fields": ["object_id|destination|relation|relative_to|details"],
492
  "partial_intent": {}
493
- }"""
 
 
 
 
 
 
 
 
494
 
495
 
496
  def __init__(self, model=None, api_key=None, base_url=None):
@@ -516,6 +567,94 @@ Return one JSON object with exactly:
516
  "auto",
517
  ).lower()
518
  self._structured_outputs_available = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
519
 
520
  def plan(self, user_command, scene_state, previous_failed_reasons=None):
521
  if isinstance(scene_state, dict):
@@ -539,7 +678,7 @@ Return one JSON object with exactly:
539
  user_prompt += f"\n\nPREVIOUS FAILURE REASON:\n{previous_failed_reasons}\nPlease generate a new plan that avoids this failure."
540
 
541
  use_structured_outputs = self._should_use_structured_outputs()
542
- system_prompt = self.SYSTEM_PROMPT
543
  if use_structured_outputs:
544
  system_prompt += (
545
  "\n\nFor this request, return one JSON object with exactly one "
@@ -591,7 +730,7 @@ Return one JSON object with exactly:
591
  create_kwargs.pop("response_format", None)
592
  create_kwargs["messages"][0] = {
593
  "role": "system",
594
- "content": self.SYSTEM_PROMPT,
595
  }
596
  continue
597
 
@@ -632,7 +771,16 @@ Return one JSON object with exactly:
632
  create_kwargs = {
633
  "model": self.model,
634
  "messages": [
635
- {"role": "system", "content": self.GOAL_RESOLUTION_PROMPT},
 
 
 
 
 
 
 
 
 
636
  {
637
  "role": "user",
638
  "content": (
@@ -669,10 +817,42 @@ Return one JSON object with exactly:
669
  f"{reasoning}\n-----------------------------------\n"
670
  )
671
  result = self._parse_goal_resolution(message.content)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
672
  if result is not None:
673
  return result
674
  return {
675
  "status": "clarify",
 
 
 
 
 
676
  "canonical_instruction": "",
677
  "message": (
678
  "TΓ΄i chΖ°a xΓ‘c Δ‘α»‹nh chαΊ―c chαΊ―n mα»₯c tiΓͺu. "
@@ -713,23 +893,39 @@ Return one JSON object with exactly:
713
  return None
714
  if not isinstance(data, dict):
715
  return None
716
- status = data.get("status")
 
 
 
 
 
 
 
 
 
 
 
717
  canonical = data.get("canonical_instruction", "")
718
  message = data.get("message", "")
719
  missing = data.get("missing_fields", [])
720
  partial = data.get("partial_intent", {})
721
  if status not in {"ready", "clarify", "reject"}:
722
  return None
 
 
723
  if not isinstance(canonical, str) or not isinstance(message, str):
724
  return None
 
 
725
  if not isinstance(missing, list) or not isinstance(partial, dict):
726
  return None
727
- if status == "ready" and not canonical.strip():
728
  return None
729
  if status != "ready" and not message.strip():
730
  return None
731
  return {
732
  "status": status,
 
733
  "canonical_instruction": canonical.strip(),
734
  "message": message.strip(),
735
  "missing_fields": [
@@ -833,6 +1029,10 @@ Return one JSON object with exactly:
833
  "type": "string",
834
  "enum": ["ready", "clarify", "reject"],
835
  },
 
 
 
 
836
  "canonical_instruction": {"type": "string"},
837
  "message": {"type": "string"},
838
  "missing_fields": {
@@ -855,6 +1055,7 @@ Return one JSON object with exactly:
855
  },
856
  "required": [
857
  "status",
 
858
  "canonical_instruction",
859
  "message",
860
  "missing_fields",
@@ -866,23 +1067,17 @@ Return one JSON object with exactly:
866
  }
867
 
868
  def check_goal(self, user_command, scene_state):
869
- if isinstance(scene_state, dict):
870
- scene_state = json.dumps(scene_state)
871
- if not self.api_key:
872
- return True, "No API key"
873
 
874
  client = self._client if self._client else __import__('openai').OpenAI(api_key=self.api_key, base_url=self.base_url)
875
  prompt = (
876
- "You are an Execution Monitor. Given the Scene State and the User Instruction, "
877
- "determine if the user's instruction has been successfully completed.\n"
878
- "## OBJECT PROPERTIES (FACTS):\n"
879
- "- banana: fruit, edible, yellow, light, non-metal.\n"
880
- "- pear: fruit, edible, yellow-green, light, non-metal.\n"
881
- "- soup_can: canned food, edible (contains soup), metal, heavy.\n"
882
- "- chips_can: canned snack, edible (contains chips), metal/cardboard, light.\n"
883
- "- tennis_ball: sports ball, non-food, felt/rubber, light, non-metal.\n"
884
- "- clamp: metal clamp, tool, non-food, steel/metal, heavy.\n\n"
885
- "## GOAL EVALUATION LOGIC:\n"
886
  "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"
887
  "2. Match the instruction's criteria with the Object Properties.\n"
888
  "3. Compare the current locations of objects in the SCENE STATE against the goal requirements:\n"
@@ -933,11 +1128,16 @@ class LLMAgent:
933
  self.conversation_memory_enabled = bool(conversation_memory_enabled)
934
  self.last_outcome = None
935
 
936
- def build_prompt(self, user_command, scene_state_text):
937
- """The exact text a real LLM would be shown (useful for logging)."""
938
- return (
939
- f"{RemoteLLMPlanner.SYSTEM_PROMPT}\n\n"
940
- f"SCENE STATE:\n{scene_state_text}\n\n"
 
 
 
 
 
941
  f"USER INSTRUCTION:\n{user_command}\n"
942
  )
943
  def plan(
@@ -986,26 +1186,36 @@ class LLMAgent:
986
 
987
  effective_command = user_command
988
  pending_before = None
 
 
 
 
 
 
 
 
989
  if self.conversation_memory_enabled:
990
  pending_before = self.conversation_manager.pending
991
  effective_command = self.conversation_manager.contextualize(
992
  user_command,
993
  scene_state=scene_state,
 
994
  )
995
 
996
  planning_instruction = effective_command
997
- goal_resolution_enabled = os.environ.get(
998
- "LLM_GOAL_RESOLUTION_ENABLED", "true"
999
- ).lower() not in {"0", "false", "no", "off"}
1000
- if (
1001
- resolve_goal
1002
- and goal_resolution_enabled
1003
- and hasattr(self.planner, "resolve_goal")
1004
- ):
1005
  resolution = self.planner.resolve_goal(
1006
  effective_command,
1007
  scene_state,
1008
  )
 
 
 
 
 
 
 
1009
  status = resolution.get("status")
1010
  if status in {"clarify", "reject"}:
1011
  steps = [
@@ -1036,7 +1246,44 @@ class LLMAgent:
1036
  )
1037
  self.last_outcome = outcome
1038
  return outcome
1039
- planning_instruction = resolution["canonical_instruction"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1040
 
1041
  raw_plan = self.planner.plan(
1042
  planning_instruction,
@@ -1046,20 +1293,43 @@ class LLMAgent:
1046
  if not raw_plan or not all(self._valid(step) for step in raw_plan):
1047
  semantic_plan = [
1048
  {
1049
- "function": "clarify",
1050
  "args": {
1051
  "message": (
1052
- "TΓ΄i chΖ°a cΓ³ Δ‘α»§ thΓ΄ng tin để tαΊ‘o kαΊΏ hoαΊ‘ch an toΓ n. "
1053
- "BαΊ‘n muα»‘n thao tΓ‘c vα»›i vαΊ­t nΓ o vΓ  Δ‘αΊ·t nΓ³ ở Δ‘Γ’u?"
1054
  ),
1055
- "missing_fields": ["details"],
1056
- "partial_intent": {},
1057
  "reason": "invalid_or_empty_plan",
1058
  },
1059
  }
1060
  ]
1061
  else:
1062
  semantic_plan = list(raw_plan)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1063
  semantic_plan = self._align_with_pending_intent(
1064
  semantic_plan,
1065
  pending_before,
@@ -1077,6 +1347,7 @@ class LLMAgent:
1077
  planning_instruction,
1078
  semantic_plan,
1079
  scene_state,
 
1080
  )
1081
 
1082
  # Enforce obstacle clearing on EVERY planner's output, deterministically
@@ -1129,16 +1400,676 @@ class LLMAgent:
1129
  return plan
1130
 
1131
  @staticmethod
1132
- def _compile_goal(user_command, effective_command, plan, scene_state):
1133
- """Compile user-visible plan effects, excluding injected blocker moves."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1134
  try:
1135
  state = json.loads(scene_state) if isinstance(scene_state, str) else scene_state
1136
  except (TypeError, ValueError, json.JSONDecodeError):
1137
  state = {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1138
  carried = state.get("carried_object") if isinstance(state, dict) else None
1139
  held = carried
1140
  destination = None
1141
- predicates = []
1142
 
1143
  for step in plan:
1144
  function = step.get("function")
@@ -1178,6 +2109,22 @@ class LLMAgent:
1178
  if not predicates:
1179
  return None
1180
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1181
  descriptions = []
1182
  for predicate in predicates:
1183
  if predicate.type == "carried_object_is":
@@ -1186,6 +2133,11 @@ class LLMAgent:
1186
  descriptions.append(
1187
  f"Δ‘αΊ·t {predicate.object_id} vΓ o {predicate.location_id}"
1188
  )
 
 
 
 
 
1189
  else:
1190
  descriptions.append(
1191
  f"Δ‘αΊ·t {predicate.object_id} {predicate.relation} "
 
375
  canonical goal. Never guess, omit, or emit an empty object_id/location_id. If any
376
  critical field is still ambiguous, return one structured clarify step instead of
377
  an incomplete physical action.
378
+
379
+ User constraints and execution details are different:
380
+ - A plain surface destination does not require relation/relative_to.
381
+ - If the canonical goal says to relocate an object to an automatically selected
382
+ safe spot, choose a collision-free reachable surface using the current scene.
383
+ This is an execution decision; never ask the user for an exact temporary spot.
384
+ - If the canonical goal says "at the former location of <object>", emit the
385
+ normal move_to for that location's surface. The deterministic intent layer
386
+ attaches the original scene coordinate; do not invent coordinates yourself.
387
+ - Blocker clearing, temporary parking, route waypoints, and grasp approach are
388
+ planner/executor responsibilities unless the user explicitly constrained them.
389
 
390
  ## DESTINATIONS
391
  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.
 
407
  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.
408
  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.
409
 
410
+ ## ADAPTIVE ENVIRONMENT FACTS
411
+ The authoritative object IDs, aliases, categories, attributes, affordances, and
412
+ surface aliases are appended to this prompt from the active environment's semantic
413
+ catalog. Never assume an object exists unless it appears in the current scene.
 
 
 
414
 
415
  ## SEMANTIC CATEGORIZATION & GENERAL SORTING LOGIC
416
  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:
 
435
  1. CLARIFICATION (clarify): Use this when the instruction is missing critical information, is ambiguous, or we cannot determine what action/object is intended.
436
  - Schema: [{"function":"clarify","args":{"message":"<Vietnamese clarifying question>","missing_fields":["object_id|destination|relation|relative_to|details"],"partial_intent":{"action":"<known action or null>","object_id":"<known object or null>","destination":"<known location or null>"}}}]
437
  - Always include `missing_fields` and `partial_intent` for clarify. Omit unknown keys from `partial_intent` instead of inventing values.
438
+
439
+ 2. REJECTION (reject): Use this when the instruction is impossible, unsafe, or violates physical/reachability rules.
440
+ - Schema: [{"function":"reject","args":{"message":"<Vietnamese friendly rejection message explaining the reason>"}}]
441
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
442
  Respond ONLY with the JSON array. No markdown, no code fences, no explanatory text."""
443
  )
444
 
 
455
  Rules:
456
  1. Never guess an object. Generic words such as "quαΊ£", "lon", "vαΊ­t", or "cΓ‘i Δ‘Γ³"
457
  are ambiguous whenever multiple scene objects match.
458
+ 2. If a generic noun or category matches multiple current objects, ask the user
459
+ to choose among the matching display names. Preserve every already-known
460
+ relation and reference object in partial_intent.
461
  3. A pick-up-only request needs no destination. A pick-and-place request does.
462
  4. Use only object IDs present in SCENE. Never emit an empty identifier.
463
  5. canonical_instruction must fully express the resolved intent with canonical IDs.
464
  6. The planner receives canonical_instruction, so preserve all stated constraints
465
  and never add an unstated destination or exclusivity constraint.
466
  7. Ask one concise Vietnamese question and offer scene-valid choices when possible.
467
+ 8. Slot meanings are strict:
468
+ - object_id: the object the robot will pick/manipulate.
469
+ - destination: a destination surface ID such as table or tray.
470
+ - relation: the requested spatial relation such as on_top_of.
471
+ - relative_to: the reference OBJECT ID used by relation.
472
+ - purpose: "goal" for a user-visible outcome or "intermediate" for a
473
+ planner-selected temporary relocation.
474
+ - constraint_sources: an object mapping constrained field names to
475
+ "user" or "conversation". Omit fields that are merely planner choices.
476
+ Never put a reference object into destination and never replace object_id with
477
+ the user's answer when the missing field is relative_to.
478
+ 9. For every status, partial_intent must contain all known slots using canonical
479
+ IDs. Omit unknown slots; never write null, "unknown", or placeholders.
480
+ 10. For status="ready", partial_intent must describe the complete resolved goal.
481
+ When resolving a follow-up, copy all previously known slots unchanged and fill
482
+ only fields listed as missing.
483
+ 11. object_id and relative_to must never be the same for a spatial relation.
484
+ relation and relative_to are an atomic pair. Do not emit either field unless
485
+ the user explicitly requested a spatial relation. A plain destination such as
486
+ "table" or "tray" never needs relation/relative_to.
487
+ 12. Compound, swap, and replacement requests MUST use
488
+ partial_intent={"action":"sequence","tasks":[...]}.
489
+ Each task uses the same typed slots: object_id, destination, relation,
490
+ relative_to. Preserve task order and every task across clarification turns.
491
+ 13. "Replace X with Y", "thαΊΏ chα»— X bαΊ±ng Y", or equivalent means:
492
+ (a) relocate displaced X; if the user names a destination it is a goal task,
493
+ otherwise mark it purpose="intermediate", placement_policy="auto_safe"
494
+ and do NOT ask where to park it;
495
+ (b) place replacement Y at X's former semantic surface/support relation from
496
+ the current scene snapshot. Never encode this as Y relative_to X, because
497
+ X will already have moved.
498
+ Encode exact former-position placement with
499
+ placement_policy="former_location" and anchor_object_id="<X>".
500
+ Do not output coordinates; the system snapshots them deterministically.
501
+ For a mutual swap of X and Y, return three ordered tasks:
502
+ (1) X as intermediate/auto_safe,
503
+ (2) Y as former_location anchored to X,
504
+ (3) X as former_location anchored to Y.
505
+ 14. For status="ready" after a compound-goal clarification, return the complete
506
+ tasks array, not only the task completed by the latest user answer.
507
+ 15. Resolve names against ACTIVE ENVIRONMENT aliases. If a phrase matches exactly
508
+ one current object, it is unambiguous: use that canonical ID and do NOT ask the
509
+ user to confirm it. Clarify only when two or more current objects genuinely
510
+ match the same phrase, or no object matches.
511
+ 16. A follow-up may be only a noun phrase, option, correction, yes/no, or short
512
+ fragment. Combine it with pending partial_intent and robot_question. Never ask
513
+ the user to repeat action/destination/relation slots that are already known.
514
+ 17. For swap/replace/compound follow-ups, preserve and return the entire ordered
515
+ tasks array after filling the missing entity. A confirmation such as
516
+ "tennis vΓ  quαΊ£ chuα»‘i" grounds entities; it does not start an unrelated task.
517
+ 18. Ask only for constraints required by the USER'S requested final outcome.
518
+ Exact placement on a surface is optional unless the user requested it.
519
+ Temporary parking, blocker relocation, waypoints, approach direction, and
520
+ other execution details belong to the planner and must never trigger a
521
+ clarification.
522
+ 19. Never invent a relation for a task. When the user says only "put X on/in
523
+ surface S", emit object_id + destination and nothing else spatial.
524
+ 20. "Swap positions" means exchanging the original planar positions, not merely
525
+ leaving both objects on the same surface. Every goal task in a swap must use
526
+ placement_policy="former_location" plus anchor_object_id.
527
 
528
  Return one JSON object with exactly:
529
  {
530
  "status": "ready|clarify|reject",
531
+ "conversation_mode": "standalone|follow_up",
532
  "canonical_instruction": "<resolved instruction or empty string>",
533
  "message": "<Vietnamese question/rejection, or empty when ready>",
534
  "missing_fields": ["object_id|destination|relation|relative_to|details"],
535
  "partial_intent": {}
536
+ }
537
+
538
+ conversation_mode rules:
539
+ - "follow_up" only when the latest user message answers or completes the pending
540
+ request shown in context.
541
+ - "standalone" when the latest message expresses a complete new command, regardless
542
+ of its wording. Do semantic reasoning; do not depend on a fixed verb list.
543
+ - Example: "cho quαΊ£ lΓͺ lΓͺn lon chip" is a standalone complete command even if
544
+ "cho" was not used in earlier examples."""
545
 
546
 
547
  def __init__(self, model=None, api_key=None, base_url=None):
 
567
  "auto",
568
  ).lower()
569
  self._structured_outputs_available = None
570
+
571
+ @staticmethod
572
+ def _environment_prompt_context(scene_state):
573
+ """Build compact authoritative semantics from the active scene only."""
574
+ if isinstance(scene_state, str):
575
+ try:
576
+ state = json.loads(scene_state)
577
+ except (TypeError, ValueError, json.JSONDecodeError):
578
+ state = {}
579
+ else:
580
+ state = scene_state if isinstance(scene_state, dict) else {}
581
+
582
+ environment = state.get("environment", {})
583
+ objects = []
584
+ for obj in state.get("objects", []):
585
+ if not isinstance(obj, dict):
586
+ continue
587
+ objects.append(
588
+ {
589
+ "id": obj.get("name"),
590
+ "class": obj.get("class"),
591
+ "semantic": obj.get("semantic", {}),
592
+ }
593
+ )
594
+ catalog = {
595
+ "environment_id": environment.get("id", "unspecified"),
596
+ "description": environment.get("description", ""),
597
+ "surfaces": environment.get("surfaces", {}),
598
+ "objects_present": objects,
599
+ }
600
+ return (
601
+ "\n\n## ACTIVE ENVIRONMENT SEMANTIC CATALOG (AUTHORITATIVE)\n"
602
+ + json.dumps(catalog, ensure_ascii=False, sort_keys=True)
603
+ + "\nUse only IDs and facts from this catalog and the current scene state."
604
+ )
605
+
606
+ @staticmethod
607
+ def _entity_grounding_hints(user_command, scene_state):
608
+ """Ground user mentions using only aliases from the active environment."""
609
+ if isinstance(scene_state, str):
610
+ try:
611
+ state = json.loads(scene_state)
612
+ except (TypeError, ValueError, json.JSONDecodeError):
613
+ state = {}
614
+ else:
615
+ state = scene_state if isinstance(scene_state, dict) else {}
616
+ text = str(user_command or "").casefold()
617
+ matches = []
618
+ for obj in state.get("objects", []):
619
+ if not isinstance(obj, dict) or not obj.get("name"):
620
+ continue
621
+ semantic = obj.get("semantic", {}) or {}
622
+ aliases = list(semantic.get("aliases", []) or [])
623
+ display = semantic.get("display_name", {}) or {}
624
+ aliases.extend(
625
+ value for value in display.values() if isinstance(value, str)
626
+ )
627
+ aliases.append(obj["name"])
628
+ matched = sorted(
629
+ {
630
+ alias
631
+ for alias in aliases
632
+ if isinstance(alias, str)
633
+ and alias.strip()
634
+ and re.search(
635
+ rf"(?<!\w){re.escape(alias.casefold())}(?!\w)",
636
+ text,
637
+ )
638
+ },
639
+ key=len,
640
+ reverse=True,
641
+ )
642
+ if matched:
643
+ matches.append(
644
+ {
645
+ "object_id": obj["name"],
646
+ "matched_aliases": matched,
647
+ }
648
+ )
649
+ return (
650
+ "\n\n## DATA-DRIVEN ENTITY GROUNDING HINTS\n"
651
+ + json.dumps(matches, ensure_ascii=False)
652
+ + "\nA mention mapping to exactly one current object ID is resolved, "
653
+ "not ambiguous. These hints come from the active semantic catalog."
654
+ )
655
+
656
+ def build_adaptive_system_prompt(self, scene_state):
657
+ return self.SYSTEM_PROMPT + self._environment_prompt_context(scene_state)
658
 
659
  def plan(self, user_command, scene_state, previous_failed_reasons=None):
660
  if isinstance(scene_state, dict):
 
678
  user_prompt += f"\n\nPREVIOUS FAILURE REASON:\n{previous_failed_reasons}\nPlease generate a new plan that avoids this failure."
679
 
680
  use_structured_outputs = self._should_use_structured_outputs()
681
+ system_prompt = self.build_adaptive_system_prompt(scene_state)
682
  if use_structured_outputs:
683
  system_prompt += (
684
  "\n\nFor this request, return one JSON object with exactly one "
 
730
  create_kwargs.pop("response_format", None)
731
  create_kwargs["messages"][0] = {
732
  "role": "system",
733
+ "content": self.build_adaptive_system_prompt(scene_state),
734
  }
735
  continue
736
 
 
771
  create_kwargs = {
772
  "model": self.model,
773
  "messages": [
774
+ {
775
+ "role": "system",
776
+ "content": (
777
+ self.GOAL_RESOLUTION_PROMPT
778
+ + self._environment_prompt_context(scene_state)
779
+ + self._entity_grounding_hints(
780
+ user_command, scene_state
781
+ )
782
+ ),
783
+ },
784
  {
785
  "role": "user",
786
  "content": (
 
817
  f"{reasoning}\n-----------------------------------\n"
818
  )
819
  result = self._parse_goal_resolution(message.content)
820
+ if result is not None:
821
+ return result
822
+ logger.warning(
823
+ "[GOAL_RESOLUTION] Invalid/empty structured response; requesting "
824
+ "one schema-repair turn without discarding conversation context."
825
+ )
826
+ repair_messages = list(create_kwargs["messages"])
827
+ if message.content:
828
+ repair_messages.append(
829
+ {"role": "assistant", "content": message.content}
830
+ )
831
+ repair_messages.append(
832
+ {
833
+ "role": "user",
834
+ "content": (
835
+ "Repair your previous response. Re-evaluate the SAME scene, "
836
+ "latest user reply, robot question, and pending partial_intent. "
837
+ "Return ONLY the required Goal Resolution JSON object. Preserve "
838
+ "all known slots and ordered tasks; fill only missing slots."
839
+ ),
840
+ }
841
+ )
842
+ repair_kwargs = dict(create_kwargs)
843
+ repair_kwargs["messages"] = repair_messages
844
+ repaired_response = client.chat.completions.create(**repair_kwargs)
845
+ repaired_message = repaired_response.choices[0].message
846
+ result = self._parse_goal_resolution(repaired_message.content)
847
  if result is not None:
848
  return result
849
  return {
850
  "status": "clarify",
851
+ "conversation_mode": (
852
+ "follow_up"
853
+ if "YΓͺu cαΊ§u trΖ°α»›c chΖ°a hoΓ n chỉnh:" in user_command
854
+ else "standalone"
855
+ ),
856
  "canonical_instruction": "",
857
  "message": (
858
  "TΓ΄i chΖ°a xΓ‘c Δ‘α»‹nh chαΊ―c chαΊ―n mα»₯c tiΓͺu. "
 
893
  return None
894
  if not isinstance(data, dict):
895
  return None
896
+ for wrapper_key in ("goal_resolution", "result", "resolution"):
897
+ if isinstance(data.get(wrapper_key), dict):
898
+ data = data[wrapper_key]
899
+ break
900
+ status = str(data.get("status", "")).lower()
901
+ conversation_mode = data.get("conversation_mode", "standalone")
902
+ conversation_mode = {
903
+ "new_request": "standalone",
904
+ "new": "standalone",
905
+ "continuation": "follow_up",
906
+ "followup": "follow_up",
907
+ }.get(conversation_mode, conversation_mode)
908
  canonical = data.get("canonical_instruction", "")
909
  message = data.get("message", "")
910
  missing = data.get("missing_fields", [])
911
  partial = data.get("partial_intent", {})
912
  if status not in {"ready", "clarify", "reject"}:
913
  return None
914
+ if conversation_mode not in {"standalone", "follow_up"}:
915
+ return None
916
  if not isinstance(canonical, str) or not isinstance(message, str):
917
  return None
918
+ if isinstance(missing, str):
919
+ missing = [missing]
920
  if not isinstance(missing, list) or not isinstance(partial, dict):
921
  return None
922
+ if status == "ready" and not canonical.strip() and not partial:
923
  return None
924
  if status != "ready" and not message.strip():
925
  return None
926
  return {
927
  "status": status,
928
+ "conversation_mode": conversation_mode,
929
  "canonical_instruction": canonical.strip(),
930
  "message": message.strip(),
931
  "missing_fields": [
 
1029
  "type": "string",
1030
  "enum": ["ready", "clarify", "reject"],
1031
  },
1032
+ "conversation_mode": {
1033
+ "type": "string",
1034
+ "enum": ["standalone", "follow_up"],
1035
+ },
1036
  "canonical_instruction": {"type": "string"},
1037
  "message": {"type": "string"},
1038
  "missing_fields": {
 
1055
  },
1056
  "required": [
1057
  "status",
1058
+ "conversation_mode",
1059
  "canonical_instruction",
1060
  "message",
1061
  "missing_fields",
 
1067
  }
1068
 
1069
  def check_goal(self, user_command, scene_state):
1070
+ if isinstance(scene_state, dict):
1071
+ scene_state = json.dumps(scene_state, ensure_ascii=False)
1072
+ if not self.api_key:
1073
+ return True, "No API key"
1074
 
1075
  client = self._client if self._client else __import__('openai').OpenAI(api_key=self.api_key, base_url=self.base_url)
1076
  prompt = (
1077
+ "You are an Execution Monitor. Given the Scene State and the User Instruction, "
1078
+ "determine if the user's instruction has been successfully completed.\n"
1079
+ f"{self._environment_prompt_context(scene_state)}\n\n"
1080
+ "## GOAL EVALUATION LOGIC:\n"
 
 
 
 
 
 
1081
  "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"
1082
  "2. Match the instruction's criteria with the Object Properties.\n"
1083
  "3. Compare the current locations of objects in the SCENE STATE against the goal requirements:\n"
 
1128
  self.conversation_memory_enabled = bool(conversation_memory_enabled)
1129
  self.last_outcome = None
1130
 
1131
+ def build_prompt(self, user_command, scene_state_text):
1132
+ """The exact text a real LLM would be shown (useful for logging)."""
1133
+ system_prompt = (
1134
+ self.planner.build_adaptive_system_prompt(scene_state_text)
1135
+ if hasattr(self.planner, "build_adaptive_system_prompt")
1136
+ else RemoteLLMPlanner.SYSTEM_PROMPT
1137
+ )
1138
+ return (
1139
+ f"{system_prompt}\n\n"
1140
+ f"SCENE STATE:\n{scene_state_text}\n\n"
1141
  f"USER INSTRUCTION:\n{user_command}\n"
1142
  )
1143
  def plan(
 
1186
 
1187
  effective_command = user_command
1188
  pending_before = None
1189
+ goal_resolution_enabled = os.environ.get(
1190
+ "LLM_GOAL_RESOLUTION_ENABLED", "true"
1191
+ ).lower() not in {"0", "false", "no", "off"}
1192
+ semantic_boundary_available = (
1193
+ resolve_goal
1194
+ and goal_resolution_enabled
1195
+ and hasattr(self.planner, "resolve_goal")
1196
+ )
1197
  if self.conversation_memory_enabled:
1198
  pending_before = self.conversation_manager.pending
1199
  effective_command = self.conversation_manager.contextualize(
1200
  user_command,
1201
  scene_state=scene_state,
1202
+ use_lexical_boundary=not semantic_boundary_available,
1203
  )
1204
 
1205
  planning_instruction = effective_command
1206
+ resolved_intent = {}
1207
+ if semantic_boundary_available:
 
 
 
 
 
 
1208
  resolution = self.planner.resolve_goal(
1209
  effective_command,
1210
  scene_state,
1211
  )
1212
+ if (
1213
+ self.conversation_memory_enabled
1214
+ and resolution.get("conversation_mode", "standalone")
1215
+ == "standalone"
1216
+ ):
1217
+ self.conversation_manager.clear_pending()
1218
+ pending_before = None
1219
  status = resolution.get("status")
1220
  if status in {"clarify", "reject"}:
1221
  steps = [
 
1246
  )
1247
  self.last_outcome = outcome
1248
  return outcome
1249
+ resolved_intent = self._merge_resolved_intent(
1250
+ pending_before,
1251
+ resolution.get("partial_intent", {}),
1252
+ scene_state,
1253
+ )
1254
+ intent_error = self._resolved_intent_error(
1255
+ resolved_intent,
1256
+ scene_state,
1257
+ )
1258
+ if intent_error:
1259
+ steps = [
1260
+ {
1261
+ "function": "clarify",
1262
+ "args": {
1263
+ "message": intent_error,
1264
+ "missing_fields": ["details"],
1265
+ "partial_intent": resolved_intent,
1266
+ "reason": "invalid_resolved_intent",
1267
+ },
1268
+ }
1269
+ ]
1270
+ if self.conversation_memory_enabled:
1271
+ self.conversation_manager.observe(
1272
+ user_command,
1273
+ steps,
1274
+ scene_state=scene_state,
1275
+ )
1276
+ outcome = PlanningOutcome(
1277
+ steps=tuple(steps),
1278
+ response_type="clarify",
1279
+ effective_command=effective_command,
1280
+ )
1281
+ self.last_outcome = outcome
1282
+ return outcome
1283
+ planning_instruction = (
1284
+ self._canonical_instruction_from_intent(resolved_intent)
1285
+ or resolution["canonical_instruction"]
1286
+ )
1287
 
1288
  raw_plan = self.planner.plan(
1289
  planning_instruction,
 
1293
  if not raw_plan or not all(self._valid(step) for step in raw_plan):
1294
  semantic_plan = [
1295
  {
1296
+ "function": "reject",
1297
  "args": {
1298
  "message": (
1299
+ "TΓ΄i Δ‘Γ£ hiểu mα»₯c tiΓͺu nhΖ°ng mΓ΄ hΓ¬nh chΖ°a trαΊ£ về "
1300
+ "mα»™t kαΊΏ hoαΊ‘ch hợp lệ. BαΊ‘n vui lΓ²ng thα»­ lαΊ‘i."
1301
  ),
 
 
1302
  "reason": "invalid_or_empty_plan",
1303
  },
1304
  }
1305
  ]
1306
  else:
1307
  semantic_plan = list(raw_plan)
1308
+ if resolved_intent and semantic_plan:
1309
+ semantic_plan = self._apply_intent_placement_anchors(
1310
+ semantic_plan,
1311
+ resolved_intent,
1312
+ scene_state,
1313
+ )
1314
+ if (
1315
+ resolved_intent
1316
+ and semantic_plan
1317
+ and semantic_plan[0].get("function") not in {"clarify", "reject"}
1318
+ and not self._plan_matches_intent(semantic_plan, resolved_intent)
1319
+ ):
1320
+ semantic_plan = [
1321
+ {
1322
+ "function": "reject",
1323
+ "args": {
1324
+ "message": (
1325
+ "TΓ΄i Δ‘Γ£ hiểu mα»₯c tiΓͺu nhΖ°ng kαΊΏ hoαΊ‘ch sinh ra khΓ΄ng "
1326
+ "khα»›p vα»›i mα»₯c tiΓͺu Δ‘Γ³. TΓ΄i Δ‘Γ£ dα»«ng trΖ°α»›c khi robot "
1327
+ "thα»±c thi; bαΊ‘n vui lΓ²ng thα»­ lαΊ‘i."
1328
+ ),
1329
+ "reason": "plan_goal_mismatch",
1330
+ },
1331
+ }
1332
+ ]
1333
  semantic_plan = self._align_with_pending_intent(
1334
  semantic_plan,
1335
  pending_before,
 
1347
  planning_instruction,
1348
  semantic_plan,
1349
  scene_state,
1350
+ resolved_intent=resolved_intent,
1351
  )
1352
 
1353
  # Enforce obstacle clearing on EVERY planner's output, deterministically
 
1400
  return plan
1401
 
1402
  @staticmethod
1403
+ def _scene_ids_and_surfaces(scene_state):
1404
+ try:
1405
+ state = (
1406
+ json.loads(scene_state)
1407
+ if isinstance(scene_state, str)
1408
+ else scene_state
1409
+ )
1410
+ except (TypeError, ValueError, json.JSONDecodeError):
1411
+ state = {}
1412
+ if not isinstance(state, dict):
1413
+ return set(), {"table", "tray"}
1414
+ object_ids = {
1415
+ obj.get("name")
1416
+ for obj in state.get("objects", [])
1417
+ if isinstance(obj, dict) and obj.get("name")
1418
+ }
1419
+ surfaces = set(
1420
+ (state.get("environment", {}).get("surfaces", {}) or {}).keys()
1421
+ )
1422
+ return object_ids, surfaces or {"table", "tray"}
1423
+
1424
+ @staticmethod
1425
+ def _scene_object_locations(scene_state):
1426
+ try:
1427
+ state = (
1428
+ json.loads(scene_state)
1429
+ if isinstance(scene_state, str)
1430
+ else scene_state
1431
+ )
1432
+ except (TypeError, ValueError, json.JSONDecodeError):
1433
+ return {}
1434
+ if not isinstance(state, dict):
1435
+ return {}
1436
+ return {
1437
+ obj.get("name"): obj.get("location")
1438
+ for obj in state.get("objects", [])
1439
+ if isinstance(obj, dict) and obj.get("name")
1440
+ }
1441
+
1442
+ @classmethod
1443
+ def _fill_former_location_surface(cls, task, scene_state, surfaces):
1444
+ task = dict(task)
1445
+ if (
1446
+ task.get("placement_policy") == "former_location"
1447
+ and not task.get("destination")
1448
+ ):
1449
+ location = cls._scene_object_locations(scene_state).get(
1450
+ task.get("anchor_object_id")
1451
+ )
1452
+ if location in surfaces:
1453
+ task["destination"] = location
1454
+ return task
1455
+
1456
+ @classmethod
1457
+ def _merge_resolved_intent(cls, pending, candidate, scene_state):
1458
+ """Fill only missing slots; never overwrite established dialogue state."""
1459
+ candidate = {
1460
+ key: value
1461
+ for key, value in dict(candidate or {}).items()
1462
+ if value not in (None, "", "unknown")
1463
+ }
1464
+ known = dict(pending.partial_intent or {}) if pending else {}
1465
+ missing = set(pending.missing_fields or ()) if pending else set()
1466
+ object_ids, surfaces = cls._scene_ids_and_surfaces(scene_state)
1467
+
1468
+ def normalize_tasks(tasks):
1469
+ """Normalize every task against the active scene namespaces."""
1470
+ normalized = []
1471
+ for raw_task in tasks:
1472
+ if not isinstance(raw_task, dict):
1473
+ continue
1474
+ task = {
1475
+ key: value
1476
+ for key, value in raw_task.items()
1477
+ if value not in (None, "", "unknown")
1478
+ }
1479
+ normalized.append(
1480
+ cls._fill_former_location_surface(
1481
+ cls._normalize_intent_task(
1482
+ task,
1483
+ object_ids,
1484
+ surfaces,
1485
+ required_fields=missing,
1486
+ ),
1487
+ scene_state,
1488
+ surfaces,
1489
+ )
1490
+ )
1491
+ return normalized
1492
+
1493
+ known_tasks = known.get("tasks")
1494
+ if isinstance(known_tasks, list) and known_tasks:
1495
+ merged_tasks = [
1496
+ {
1497
+ key: value
1498
+ for key, value in dict(task).items()
1499
+ if value not in (None, "", "unknown")
1500
+ }
1501
+ for task in known_tasks
1502
+ if isinstance(task, dict)
1503
+ ]
1504
+ incoming_tasks = candidate.get("tasks")
1505
+ if not isinstance(incoming_tasks, list):
1506
+ flat_patch = {
1507
+ key: value
1508
+ for key, value in candidate.items()
1509
+ if key not in {"action", "tasks"}
1510
+ }
1511
+ incoming_tasks = [flat_patch] if flat_patch else []
1512
+
1513
+ for incoming in incoming_tasks:
1514
+ if not isinstance(incoming, dict):
1515
+ continue
1516
+ incoming = {
1517
+ key: value
1518
+ for key, value in incoming.items()
1519
+ if value not in (None, "", "unknown")
1520
+ }
1521
+ incoming_object = incoming.get("object_id")
1522
+ index = next(
1523
+ (
1524
+ i
1525
+ for i, task in enumerate(merged_tasks)
1526
+ if incoming_object
1527
+ and task.get("object_id") == incoming_object
1528
+ ),
1529
+ None,
1530
+ )
1531
+ if index is None:
1532
+ index = next(
1533
+ (
1534
+ i
1535
+ for i, task in enumerate(merged_tasks)
1536
+ if any(not task.get(field) for field in missing)
1537
+ ),
1538
+ 0 if len(merged_tasks) == 1 else None,
1539
+ )
1540
+ if index is None:
1541
+ # A complete additional task returned by the resolver.
1542
+ merged_tasks.append(incoming)
1543
+ continue
1544
+ base = merged_tasks[index]
1545
+ for key, value in incoming.items():
1546
+ if key in missing or not base.get(key):
1547
+ base[key] = value
1548
+
1549
+ return {
1550
+ "action": "sequence",
1551
+ "tasks": normalize_tasks(merged_tasks),
1552
+ }
1553
+
1554
+ # A newly resolved standalone compound intent has no pending task list.
1555
+ # It still needs the same recursive normalization as a follow-up:
1556
+ # namespace validation, intermediate auto-safe policy, and deterministic
1557
+ # former-location surface inference must apply to every child task.
1558
+ candidate_tasks = candidate.get("tasks")
1559
+ if isinstance(candidate_tasks, list):
1560
+ return {
1561
+ "action": candidate.get("action") or "sequence",
1562
+ "tasks": normalize_tasks(candidate_tasks),
1563
+ }
1564
+
1565
+ raw_candidate_object = candidate.get("object_id")
1566
+ for key, value in known.items():
1567
+ if key not in missing and value not in (None, "", "unknown"):
1568
+ candidate[key] = value
1569
+
1570
+ relation = candidate.get("relation") or known.get("relation")
1571
+ established_object = known.get("object_id")
1572
+ if (
1573
+ relation
1574
+ and established_object
1575
+ and raw_candidate_object in object_ids
1576
+ and raw_candidate_object != established_object
1577
+ and not candidate.get("relative_to")
1578
+ ):
1579
+ candidate["relative_to"] = raw_candidate_object
1580
+ candidate["object_id"] = established_object
1581
+
1582
+ # Migrate older clarification metadata which called the reference
1583
+ # object a "destination". Destination is reserved for surfaces.
1584
+ candidate = cls._normalize_intent_task(
1585
+ candidate,
1586
+ object_ids,
1587
+ surfaces,
1588
+ required_fields=missing,
1589
+ )
1590
+ candidate = cls._fill_former_location_surface(
1591
+ candidate,
1592
+ scene_state,
1593
+ surfaces,
1594
+ )
1595
+ if relation and not candidate.get("action"):
1596
+ candidate["action"] = "pick_and_place"
1597
+ return candidate
1598
+
1599
+ @staticmethod
1600
+ def _normalize_intent_task(
1601
+ task,
1602
+ object_ids,
1603
+ surfaces,
1604
+ required_fields=(),
1605
+ ):
1606
+ """Canonicalize object and surface slots at the semantic boundary.
1607
+
1608
+ ``destination`` belongs to the surface namespace, while
1609
+ ``relative_to`` belongs to the manipulable-object namespace. LLMs
1610
+ occasionally express "put X on the table" as
1611
+ ``on_top_of(table)``. That wording is equivalent to selecting the
1612
+ table surface, so collapse it without asking a redundant question.
1613
+ Directional relations to a surface are retained for validation:
1614
+ converting ``left_of(table)`` would invent a reference frame.
1615
+ """
1616
+ task = dict(task)
1617
+ relation = task.get("relation")
1618
+ destination = task.get("destination")
1619
+ reference = task.get("relative_to")
1620
+ required_fields = set(required_fields or ())
1621
+ explicit_constraints = set(task.get("explicit_constraints", []) or [])
1622
+ sources = task.get("constraint_sources", {}) or {}
1623
+ if not isinstance(sources, dict):
1624
+ sources = {}
1625
+
1626
+ def is_explicit(field):
1627
+ return (
1628
+ field in explicit_constraints
1629
+ or sources.get(field) in {"user", "conversation"}
1630
+ or field in required_fields
1631
+ )
1632
+
1633
+ # Backward-compatible migration for earlier resolver output which put
1634
+ # former-location semantics in a free-text ``details`` field.
1635
+ details = str(task.get("details", "") or "").lower()
1636
+ if (
1637
+ task.get("placement_policy") != "former_location"
1638
+ and ("former location" in details or "original location" in details)
1639
+ ):
1640
+ anchor = next(
1641
+ (object_id for object_id in object_ids if object_id.lower() in details),
1642
+ None,
1643
+ )
1644
+ if anchor:
1645
+ task["placement_policy"] = "former_location"
1646
+ task["anchor_object_id"] = anchor
1647
+ task.pop("details", None)
1648
+
1649
+ # A dangling relation is commonly an LLM-invented execution detail,
1650
+ # especially on an intermediate relocation. It is not a user
1651
+ # constraint unless provenance or the pending clarification says so.
1652
+ if relation and not reference and not (
1653
+ is_explicit("relation") or is_explicit("relative_to")
1654
+ ):
1655
+ task.pop("relation", None)
1656
+ relation = None
1657
+ if reference and not relation and not (
1658
+ is_explicit("relation") or is_explicit("relative_to")
1659
+ ):
1660
+ task.pop("relative_to", None)
1661
+ reference = None
1662
+
1663
+ if task.get("purpose") == "intermediate":
1664
+ task["placement_policy"] = task.get(
1665
+ "placement_policy", "auto_safe"
1666
+ )
1667
+ if not is_explicit("destination"):
1668
+ task.pop("destination", None)
1669
+ destination = None
1670
+ if not (
1671
+ is_explicit("relation") or is_explicit("relative_to")
1672
+ ):
1673
+ task.pop("relation", None)
1674
+ task.pop("relative_to", None)
1675
+ relation = None
1676
+ reference = None
1677
+
1678
+ if reference in surfaces and relation == "on_top_of":
1679
+ task["destination"] = reference
1680
+ task.pop("relation", None)
1681
+ task.pop("relative_to", None)
1682
+ relation = None
1683
+ destination = reference
1684
+ elif reference in surfaces and not relation:
1685
+ task["destination"] = reference
1686
+ task.pop("relative_to", None)
1687
+ destination = reference
1688
+
1689
+ if relation and destination in object_ids:
1690
+ task.setdefault("relative_to", destination)
1691
+ task["destination"] = "table"
1692
+ elif destination and destination not in surfaces:
1693
+ task.pop("destination", None)
1694
+ if relation and task.get("relative_to"):
1695
+ task.setdefault("destination", "table")
1696
+ if not explicit_constraints:
1697
+ task.pop("explicit_constraints", None)
1698
+ if not sources:
1699
+ task.pop("constraint_sources", None)
1700
+ return task
1701
+
1702
+ @staticmethod
1703
+ def _intent_tasks(intent):
1704
+ tasks = intent.get("tasks") if isinstance(intent, dict) else None
1705
+ if isinstance(tasks, list):
1706
+ return [task for task in tasks if isinstance(task, dict)]
1707
+ return [intent] if intent else []
1708
+
1709
+ @classmethod
1710
+ def _resolved_intent_error(cls, intent, scene_state):
1711
+ if not intent:
1712
+ return None
1713
+ object_ids, surfaces = cls._scene_ids_and_surfaces(scene_state)
1714
+ for task in cls._intent_tasks(intent):
1715
+ action = task.get("action") or intent.get("action")
1716
+ purpose = task.get("purpose", "goal")
1717
+ target = task.get("object_id")
1718
+ reference = task.get("relative_to")
1719
+ relation = task.get("relation")
1720
+ destination = task.get("destination")
1721
+ placement_policy = task.get("placement_policy")
1722
+ anchor_object_id = task.get("anchor_object_id")
1723
+ if not target:
1724
+ return "BαΊ‘n muα»‘n robot thao tΓ‘c vα»›i vαΊ­t nΓ o?"
1725
+ if target not in object_ids:
1726
+ return f"TΓ΄i khΓ΄ng tΓ¬m thαΊ₯y vαΊ­t cαΊ§n thao tΓ‘c '{target}' trong scene."
1727
+ if relation and not reference:
1728
+ return "BαΊ‘n muα»‘n Δ‘αΊ·t vαΊ­t Δ‘Γ³ tΖ°Ζ‘ng quan vα»›i vαΊ­t nΓ o?"
1729
+ if reference in surfaces:
1730
+ return (
1731
+ f"'{reference}' là bề mặt, không phải vật tham chiếu. "
1732
+ "BαΊ‘n hΓ£y chọn mα»™t vαΊ­t cα»₯ thể cho quan hệ khΓ΄ng gian nΓ y."
1733
+ )
1734
+ if reference and reference not in object_ids:
1735
+ return f"TΓ΄i khΓ΄ng tΓ¬m thαΊ₯y vαΊ­t tham chiαΊΏu '{reference}' trong scene."
1736
+ if reference and not relation:
1737
+ return (
1738
+ f"BαΊ‘n muα»‘n Δ‘αΊ·t vαΊ­t Δ‘Γ³ theo quan hệ nΓ o vα»›i "
1739
+ f"'{reference}'?"
1740
+ )
1741
+ if relation and target == reference:
1742
+ return (
1743
+ "VαΊ­t cαΊ§n di chuyển vΓ  vαΊ­t tham chiαΊΏu Δ‘ang lΓ  cΓΉng mα»™t vαΊ­t. "
1744
+ "BαΊ‘n muα»‘n Δ‘αΊ·t nΓ³ lΓͺn vαΊ­t nΓ o khΓ‘c?"
1745
+ )
1746
+ if placement_policy == "former_location":
1747
+ if not anchor_object_id:
1748
+ return "VαΊ­t nΓ y cαΊ§n được Δ‘αΊ·t vΓ o vα»‹ trΓ­ cΕ© cα»§a vαΊ­t nΓ o?"
1749
+ if anchor_object_id not in object_ids:
1750
+ return (
1751
+ "TΓ΄i khΓ΄ng tΓ¬m thαΊ₯y vαΊ­t neo vα»‹ trΓ­ "
1752
+ f"'{anchor_object_id}' trong scene."
1753
+ )
1754
+ if anchor_object_id == target:
1755
+ return (
1756
+ "VαΊ­t cαΊ§n di chuyển khΓ΄ng thể dΓΉng chΓ­nh vα»‹ trΓ­ hiện tαΊ‘i "
1757
+ "cα»§a nΓ³ lΓ m vα»‹ trΓ­ hoΓ‘n Δ‘α»•i."
1758
+ )
1759
+ if purpose == "intermediate":
1760
+ # Exact parking is deliberately delegated to planning and
1761
+ # free-space optimisation unless the user constrained it.
1762
+ continue
1763
+ if not destination and action != "pick_up":
1764
+ return f"BαΊ‘n muα»‘n Δ‘αΊ·t '{target}' lΓͺn bề mαΊ·t nΓ o?"
1765
+ if destination not in surfaces:
1766
+ return f"TΓ΄i khΓ΄ng tΓ¬m thαΊ₯y bề mαΊ·t Δ‘Γ­ch '{destination}' trong scene."
1767
+ return None
1768
+
1769
+ @classmethod
1770
+ def _canonical_instruction_from_intent(cls, intent):
1771
+ instructions = []
1772
+ for task in cls._intent_tasks(intent):
1773
+ target = task.get("object_id")
1774
+ action = task.get("action") or intent.get("action")
1775
+ purpose = task.get("purpose", "goal")
1776
+ destination = task.get("destination")
1777
+ relation = task.get("relation")
1778
+ reference = task.get("relative_to")
1779
+ placement_policy = task.get("placement_policy")
1780
+ anchor_object_id = task.get("anchor_object_id")
1781
+ if not target:
1782
+ continue
1783
+ if (
1784
+ purpose == "intermediate"
1785
+ or task.get("placement_policy") == "auto_safe"
1786
+ ):
1787
+ instructions.append(
1788
+ f"temporarily relocate {target} to an automatically "
1789
+ "selected safe free spot"
1790
+ )
1791
+ elif placement_policy == "former_location" and anchor_object_id:
1792
+ instructions.append(
1793
+ f"place {target} at the former location of "
1794
+ f"{anchor_object_id} on {destination}"
1795
+ )
1796
+ elif relation and reference:
1797
+ instructions.append(
1798
+ f"place {target} {relation} {reference} "
1799
+ f"on {destination or 'table'}"
1800
+ )
1801
+ elif destination:
1802
+ instructions.append(f"place {target} on {destination}")
1803
+ elif action == "pick_up":
1804
+ instructions.append(f"pick_up {target}")
1805
+ return "; then ".join(instructions)
1806
+
1807
+ @classmethod
1808
+ def _plan_matches_intent(cls, plan, intent):
1809
+ held = None
1810
+ completed = []
1811
+ for step in plan:
1812
+ function = step.get("function")
1813
+ args = step.get("args", {})
1814
+ if function == "pick_up":
1815
+ held = args.get("object_id")
1816
+ elif function == "move_to":
1817
+ completed.append(
1818
+ {
1819
+ "object_id": held,
1820
+ "destination": args.get("location_id"),
1821
+ "relation": args.get("relation"),
1822
+ "relative_to": args.get("relative_to"),
1823
+ "placement_anchor": args.get("placement_anchor"),
1824
+ }
1825
+ )
1826
+ elif function == "place_down":
1827
+ held = None
1828
+
1829
+ cursor = 0
1830
+ for task in cls._intent_tasks(intent):
1831
+ target = task.get("object_id")
1832
+ relation = task.get("relation")
1833
+ reference = task.get("relative_to")
1834
+ destination = task.get("destination")
1835
+ action = task.get("action") or intent.get("action")
1836
+ purpose = task.get("purpose", "goal")
1837
+ placement_policy = task.get("placement_policy")
1838
+ anchor_object_id = task.get("anchor_object_id")
1839
+ if (
1840
+ purpose == "intermediate"
1841
+ or task.get("placement_policy") == "auto_safe"
1842
+ ):
1843
+ match_index = next(
1844
+ (
1845
+ i
1846
+ for i in range(cursor, len(completed))
1847
+ if completed[i]["object_id"] == target
1848
+ and completed[i]["destination"]
1849
+ ),
1850
+ None,
1851
+ )
1852
+ if match_index is None:
1853
+ return False
1854
+ cursor = match_index + 1
1855
+ continue
1856
+ if action == "pick_up" and not destination and not relation:
1857
+ if not any(
1858
+ step.get("function") == "pick_up"
1859
+ and step.get("args", {}).get("object_id") == target
1860
+ for step in plan
1861
+ ):
1862
+ return False
1863
+ continue
1864
+ match_index = next(
1865
+ (
1866
+ i
1867
+ for i in range(cursor, len(completed))
1868
+ if completed[i]["object_id"] == target
1869
+ and (
1870
+ not destination
1871
+ or completed[i]["destination"] == destination
1872
+ )
1873
+ and (
1874
+ not relation
1875
+ or completed[i]["relation"] == relation
1876
+ )
1877
+ and (
1878
+ not reference
1879
+ or completed[i]["relative_to"] == reference
1880
+ )
1881
+ and (
1882
+ placement_policy != "former_location"
1883
+ or completed[i].get("placement_anchor")
1884
+ == anchor_object_id
1885
+ )
1886
+ ),
1887
+ None,
1888
+ )
1889
+ if match_index is None:
1890
+ return False
1891
+ cursor = match_index + 1
1892
+ return True
1893
+
1894
+ @classmethod
1895
+ def _apply_intent_placement_anchors(cls, plan, intent, scene_state):
1896
+ """Attach deterministic initial-scene coordinates to swap placements.
1897
+
1898
+ The LLM identifies the semantic anchor object but never supplies a
1899
+ coordinate. This method snapshots the authoritative scene position and
1900
+ annotates the matching ``move_to`` step without changing the public
1901
+ action sequence.
1902
+ """
1903
+ try:
1904
+ state = (
1905
+ json.loads(scene_state)
1906
+ if isinstance(scene_state, str)
1907
+ else scene_state
1908
+ )
1909
+ except (TypeError, ValueError, json.JSONDecodeError):
1910
+ state = {}
1911
+ objects = {
1912
+ obj.get("name"): obj
1913
+ for obj in (state.get("objects", []) if isinstance(state, dict) else [])
1914
+ if isinstance(obj, dict) and obj.get("name")
1915
+ }
1916
+ annotated = [
1917
+ {
1918
+ **step,
1919
+ "args": dict(step.get("args", {})),
1920
+ }
1921
+ for step in plan
1922
+ ]
1923
+
1924
+ completed = []
1925
+ held = state.get("carried_object") if isinstance(state, dict) else None
1926
+ for index, step in enumerate(annotated):
1927
+ function = step.get("function")
1928
+ if function == "pick_up":
1929
+ held = step.get("args", {}).get("object_id")
1930
+ elif function == "move_to":
1931
+ completed.append((index, held))
1932
+ elif function == "place_down":
1933
+ held = None
1934
+
1935
+ cursor = 0
1936
+ for task in cls._intent_tasks(intent):
1937
+ target = task.get("object_id")
1938
+ match = next(
1939
+ (
1940
+ (completion_index, plan_index)
1941
+ for completion_index, (plan_index, held_object) in enumerate(
1942
+ completed[cursor:],
1943
+ start=cursor,
1944
+ )
1945
+ if held_object == target
1946
+ ),
1947
+ None,
1948
+ )
1949
+ if match is None:
1950
+ continue
1951
+ completion_index, plan_index = match
1952
+ cursor = completion_index + 1
1953
+ if task.get("placement_policy") != "former_location":
1954
+ continue
1955
+ anchor_object_id = task.get("anchor_object_id")
1956
+ anchor = objects.get(anchor_object_id, {})
1957
+ position = anchor.get("position")
1958
+ if not (
1959
+ isinstance(position, (list, tuple))
1960
+ and len(position) >= 2
1961
+ and all(isinstance(value, (int, float)) for value in position[:2])
1962
+ ):
1963
+ continue
1964
+ args = annotated[plan_index]["args"]
1965
+ args["target_position"] = [
1966
+ float(position[0]),
1967
+ float(position[1]),
1968
+ ]
1969
+ args["placement_anchor"] = anchor_object_id
1970
+ return annotated
1971
+
1972
+ @staticmethod
1973
+ def _compile_goal(
1974
+ user_command,
1975
+ effective_command,
1976
+ plan,
1977
+ scene_state,
1978
+ resolved_intent=None,
1979
+ ):
1980
+ """Compile only user-visible outcomes into goal predicates.
1981
+
1982
+ When a resolved intent is available it is authoritative. In particular,
1983
+ tasks marked ``purpose=intermediate`` are execution mechanics and must
1984
+ not become conditions that Goal Check later enforces.
1985
+ """
1986
  try:
1987
  state = json.loads(scene_state) if isinstance(scene_state, str) else scene_state
1988
  except (TypeError, ValueError, json.JSONDecodeError):
1989
  state = {}
1990
+ predicates = []
1991
+
1992
+ if resolved_intent:
1993
+ initial_objects = {
1994
+ obj.get("name"): obj
1995
+ for obj in (
1996
+ state.get("objects", []) if isinstance(state, dict) else []
1997
+ )
1998
+ if isinstance(obj, dict) and obj.get("name")
1999
+ }
2000
+ for task in LLMAgent._intent_tasks(resolved_intent):
2001
+ if task.get("purpose", "goal") == "intermediate":
2002
+ continue
2003
+ target = task.get("object_id")
2004
+ action = task.get("action") or resolved_intent.get("action")
2005
+ destination = task.get("destination")
2006
+ relation = task.get("relation")
2007
+ reference = task.get("relative_to")
2008
+ placement_policy = task.get("placement_policy")
2009
+ anchor_object_id = task.get("anchor_object_id")
2010
+ if not target:
2011
+ continue
2012
+ if (
2013
+ placement_policy == "former_location"
2014
+ and anchor_object_id in initial_objects
2015
+ ):
2016
+ anchor_position = initial_objects[anchor_object_id].get(
2017
+ "position", []
2018
+ )
2019
+ if len(anchor_position) >= 2:
2020
+ predicates.append(
2021
+ GoalPredicate(
2022
+ type="position_near",
2023
+ object_id=target,
2024
+ location_id=destination,
2025
+ target_position=(
2026
+ float(anchor_position[0]),
2027
+ float(anchor_position[1]),
2028
+ ),
2029
+ tolerance=0.04,
2030
+ )
2031
+ )
2032
+ elif relation and reference:
2033
+ predicates.append(
2034
+ GoalPredicate(
2035
+ type="relation_is",
2036
+ object_id=target,
2037
+ location_id=destination,
2038
+ relation=relation,
2039
+ relative_to=reference,
2040
+ )
2041
+ )
2042
+ elif destination:
2043
+ predicates.append(
2044
+ GoalPredicate(
2045
+ type="location_is",
2046
+ object_id=target,
2047
+ location_id=destination,
2048
+ )
2049
+ )
2050
+ elif action == "pick_up":
2051
+ predicates.append(
2052
+ GoalPredicate(
2053
+ type="carried_object_is",
2054
+ object_id=target,
2055
+ )
2056
+ )
2057
+
2058
+ if predicates:
2059
+ return LLMAgent._resolved_goal_from_predicates(
2060
+ user_command,
2061
+ effective_command,
2062
+ predicates,
2063
+ scene_state,
2064
+ )
2065
+ # A resolved intent containing only execution mechanics has no
2066
+ # user-visible completion condition. Never fall back to compiling
2067
+ # those intermediate steps as if the user had requested them.
2068
+ return None
2069
+
2070
  carried = state.get("carried_object") if isinstance(state, dict) else None
2071
  held = carried
2072
  destination = None
 
2073
 
2074
  for step in plan:
2075
  function = step.get("function")
 
2109
  if not predicates:
2110
  return None
2111
 
2112
+ return LLMAgent._resolved_goal_from_predicates(
2113
+ user_command,
2114
+ effective_command,
2115
+ predicates,
2116
+ scene_state,
2117
+ )
2118
+
2119
+ @staticmethod
2120
+ def _resolved_goal_from_predicates(
2121
+ user_command,
2122
+ effective_command,
2123
+ predicates,
2124
+ scene_state,
2125
+ ):
2126
+ """Build the immutable goal without changing predicate semantics."""
2127
+
2128
  descriptions = []
2129
  for predicate in predicates:
2130
  if predicate.type == "carried_object_is":
 
2133
  descriptions.append(
2134
  f"Δ‘αΊ·t {predicate.object_id} vΓ o {predicate.location_id}"
2135
  )
2136
+ elif predicate.type == "position_near":
2137
+ descriptions.append(
2138
+ f"Δ‘αΊ·t {predicate.object_id} vΓ o vα»‹ trΓ­ "
2139
+ f"{predicate.target_position}"
2140
+ )
2141
  else:
2142
  descriptions.append(
2143
  f"Δ‘αΊ·t {predicate.object_id} {predicate.relation} "
llm_panda/robot_controller.py CHANGED
@@ -18,7 +18,7 @@ import logging
18
  import pybullet as pb
19
 
20
  from . import config
21
- from .gripper_controller import GripperController
22
 
23
  logger = logging.getLogger(__name__)
24
 
@@ -63,7 +63,29 @@ class RobotController:
63
  # resets it before each high-level action and reads it afterwards to
64
  # decide whether to abort, recover and re-plan. Sticky (not cleared on a
65
  # later successful sub-move) so a mid-trajectory stall is never masked.
66
- self._stuck = False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
  # ------------------------------------------------------------------ #
69
  # Kinematics helpers
@@ -204,10 +226,11 @@ class RobotController:
204
  z += step
205
  return min_z
206
 
207
- def _settle(self, steps=60):
208
- scaled_steps = int(steps * self.time_scale)
209
- for _ in range(scaled_steps):
210
- pb.stepSimulation()
 
211
 
212
  # ------------------------------------------------------------------ #
213
  # Stuck-state signalling (for the closed-loop monitor)
@@ -307,7 +330,8 @@ class RobotController:
307
  scaled_steps_per_wp = int(steps_per_wp * self.time_scale)
308
 
309
  # ── traverse waypoints ───────────────────────────────────────────
310
- for wp_idx, (wp_pos, wp_ori) in enumerate(waypoints):
 
311
  current_q = self._current_joint_positions()
312
  target_q = self._ik(wp_pos, wp_ori, seed_positions=current_q)
313
 
@@ -359,8 +383,9 @@ class RobotController:
359
 
360
  # Smooth joint-space interpolation toward this waypoint.
361
  start_q = self._current_joint_positions()
362
- for s in range(1, scaled_steps_per_wp + 1):
363
- alpha = s / scaled_steps_per_wp
 
364
  for k, j in enumerate(self.arm_indices):
365
  q = start_q[k] + alpha * (target_q[k] - start_q[k])
366
  pb.setJointMotorControl2(
@@ -372,8 +397,9 @@ class RobotController:
372
  # Catch-up phase: if the arm lagged behind due to velocity limits (e.g. near max reach),
373
  # give it some extra simulation steps to physically catch up to the final target_q.
374
  max_catch_up = int(400 * self.time_scale)
375
- for _ in range(max_catch_up):
376
- if _m.dist(self.tcp_position(), position) < 0.03:
 
377
  break
378
  pb.stepSimulation()
379
 
@@ -462,9 +488,10 @@ class RobotController:
462
  Cartesian-interpolated, ``stepSimulation``-paced motion (and its
463
  ``[IK-STUCK]`` guard). Returns the final TCP position.
464
  """
465
- orientation = orientation or self._down_ori
466
- for wp in waypoints:
467
- self.move_to_pose(wp, orientation, steps=steps, settle=settle)
 
468
  return self.tcp_position()
469
 
470
  # ------------------------------------------------------------------ #
 
18
  import pybullet as pb
19
 
20
  from . import config
21
+ from .gripper_controller import GripperController
22
 
23
  logger = logging.getLogger(__name__)
24
 
 
63
  # resets it before each high-level action and reads it afterwards to
64
  # decide whether to abort, recover and re-plan. Sticky (not cleared on a
65
  # later successful sub-move) so a mid-trajectory stall is never masked.
66
+ self._stuck = False
67
+ self._cancellation_token = None
68
+
69
+ def set_cancellation_token(self, token):
70
+ """Attach the active task token; ``None`` restores non-interruptible use."""
71
+ self._cancellation_token = token
72
+
73
+ def _checkpoint(self):
74
+ token = self._cancellation_token
75
+ if token is not None:
76
+ token.checkpoint()
77
+
78
+ def hold_current_pose(self):
79
+ """Stop trajectory progress while preserving grasp and physical state."""
80
+ current_q = self._current_joint_positions()
81
+ for index, joint in enumerate(self.arm_indices):
82
+ pb.setJointMotorControl2(
83
+ self.robot_id,
84
+ joint,
85
+ pb.POSITION_CONTROL,
86
+ targetPosition=current_q[index],
87
+ force=config.ARM_MAX_FORCE,
88
+ )
89
 
90
  # ------------------------------------------------------------------ #
91
  # Kinematics helpers
 
226
  z += step
227
  return min_z
228
 
229
+ def _settle(self, steps=60):
230
+ scaled_steps = int(steps * self.time_scale)
231
+ for _ in range(scaled_steps):
232
+ self._checkpoint()
233
+ pb.stepSimulation()
234
 
235
  # ------------------------------------------------------------------ #
236
  # Stuck-state signalling (for the closed-loop monitor)
 
330
  scaled_steps_per_wp = int(steps_per_wp * self.time_scale)
331
 
332
  # ── traverse waypoints ───────────────────────────────────────────
333
+ for wp_idx, (wp_pos, wp_ori) in enumerate(waypoints):
334
+ self._checkpoint()
335
  current_q = self._current_joint_positions()
336
  target_q = self._ik(wp_pos, wp_ori, seed_positions=current_q)
337
 
 
383
 
384
  # Smooth joint-space interpolation toward this waypoint.
385
  start_q = self._current_joint_positions()
386
+ for s in range(1, scaled_steps_per_wp + 1):
387
+ self._checkpoint()
388
+ alpha = s / scaled_steps_per_wp
389
  for k, j in enumerate(self.arm_indices):
390
  q = start_q[k] + alpha * (target_q[k] - start_q[k])
391
  pb.setJointMotorControl2(
 
397
  # Catch-up phase: if the arm lagged behind due to velocity limits (e.g. near max reach),
398
  # give it some extra simulation steps to physically catch up to the final target_q.
399
  max_catch_up = int(400 * self.time_scale)
400
+ for _ in range(max_catch_up):
401
+ self._checkpoint()
402
+ if _m.dist(self.tcp_position(), position) < 0.03:
403
  break
404
  pb.stepSimulation()
405
 
 
488
  Cartesian-interpolated, ``stepSimulation``-paced motion (and its
489
  ``[IK-STUCK]`` guard). Returns the final TCP position.
490
  """
491
+ orientation = orientation or self._down_ori
492
+ for wp in waypoints:
493
+ self._checkpoint()
494
+ self.move_to_pose(wp, orientation, steps=steps, settle=settle)
495
  return self.tcp_position()
496
 
497
  # ------------------------------------------------------------------ #