CommandExecutor.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using LLM.Editor.Commands;
  6. using LLM.Editor.Data;
  7. using UnityEditor;
  8. using UnityEngine;
  9. namespace LLM.Editor.Core
  10. {
  11. /// <summary>
  12. /// Responsible for finding and executing commands from the session queue.
  13. /// </summary>
  14. [InitializeOnLoad]
  15. public static class CommandExecutor
  16. {
  17. private static List<CommandData> _commandQueue;
  18. private static CommandContext _currentContext;
  19. public static Action OnQueueUpdated;
  20. public static event Action<string> OnContextReadyForNextTurn;
  21. static CommandExecutor()
  22. {
  23. // This will run when the editor loads, including after a recompile.
  24. EditorApplication.delayCall += Initialize;
  25. }
  26. private static void Initialize()
  27. {
  28. Debug.Log("[CommandExecutor] Initializing...");
  29. if (SessionManager.HasActiveSession())
  30. {
  31. _commandQueue = SessionManager.LoadCommandQueue();
  32. if (!_commandQueue.Any())
  33. {
  34. SessionManager.EndSession();
  35. return;
  36. }
  37. Debug.Log($"[CommandExecutor] Resuming session with {_commandQueue.Count} command(s) in queue.");
  38. _currentContext = new CommandContext();
  39. OnQueueUpdated?.Invoke();
  40. }
  41. else
  42. {
  43. _commandQueue = new List<CommandData>();
  44. }
  45. }
  46. public static void SetQueue(List<CommandData> commands)
  47. {
  48. _commandQueue = commands;
  49. _currentContext = new CommandContext();
  50. SessionManager.SaveCommandQueue(_commandQueue);
  51. OnQueueUpdated?.Invoke();
  52. Debug.Log($"[CommandExecutor] Queue {_commandQueue.Count} contents:");
  53. foreach (var command in commands)
  54. {
  55. Debug.Log($"<color=cyan>[CommandExecutor]: {command.commandName}</color>");
  56. }
  57. Debug.Log("[CommandExecutor] Queue set.");
  58. }
  59. private static void ClearQueue()
  60. {
  61. _commandQueue.Clear();
  62. SessionManager.SaveCommandQueue(_commandQueue);
  63. OnQueueUpdated?.Invoke();
  64. }
  65. public static bool HasPendingCommands() => _commandQueue != null;// && _commandQueue.Any();
  66. public static CommandData GetNextCommand() => HasPendingCommands() ? _commandQueue.First() : null;
  67. public static void ExecuteNextCommand()
  68. {
  69. if (!HasPendingCommands())
  70. {
  71. Debug.LogWarning("[CommandExecutor] No commands to execute.");
  72. return;
  73. }
  74. var commandData = _commandQueue.First();
  75. try
  76. {
  77. var commandInstance = CreateCommandInstance(commandData);
  78. if (commandInstance != null)
  79. {
  80. Debug.Log($"[CommandExecutor] Executing: {commandData.commandName}");
  81. var outcome = commandInstance.Execute(_currentContext);
  82. switch (outcome)
  83. {
  84. // Decide what to do based on the outcome
  85. case CommandOutcome.Success:
  86. // The command succeeded, so we can remove it and continue.
  87. _commandQueue.RemoveAt(0);
  88. break;
  89. case CommandOutcome.Error:
  90. Debug.LogError($"[CommandExecutor] Command '{commandData.commandName}' failed. Clearing remaining command queue.");
  91. ClearQueue();
  92. break;
  93. case CommandOutcome.AwaitingNextTurn:
  94. {
  95. // The command has gathered context and is waiting for the next API call.
  96. // The queue is paused. The command remains at the top of the queue.
  97. Debug.Log("[CommandExecutor] Pausing queue. Awaiting next turn with LLM.");
  98. // Check if the command produced detailed context to send back.
  99. if (_currentContext.CurrentSubject is string detailedContextJson)
  100. {
  101. OnContextReadyForNextTurn?.Invoke(detailedContextJson);
  102. }
  103. break;
  104. }
  105. }
  106. }
  107. else
  108. {
  109. Debug.LogError($"[CommandExecutor] Could not create instance for command: {commandData.commandName}");
  110. ClearQueue(); // Clear queue on critical error
  111. }
  112. }
  113. catch(Exception e)
  114. {
  115. Debug.LogError($"[CommandExecutor] Failed to execute command '{commandData.commandName}'");
  116. Debug.LogException(e);
  117. ClearQueue();
  118. }
  119. // Save the modified queue
  120. SessionManager.SaveCommandQueue(_commandQueue);
  121. OnQueueUpdated?.Invoke();
  122. }
  123. private static ICommand CreateCommandInstance(CommandData data)
  124. {
  125. // Use reflection to find the command class in the Commands namespace
  126. // This makes the system extensible without needing a giant switch statement.
  127. var commandClassName = data.commandName.EndsWith("Command") ? data.commandName : $"{data.commandName}Command";
  128. var type = Assembly.GetExecutingAssembly().GetTypes()
  129. .FirstOrDefault(t => t.Namespace == "LLM.Editor.Commands" && t.Name == commandClassName);
  130. if (type != null)
  131. {
  132. // Assumes commands have a constructor that takes a single string (the JSON parameters)
  133. var jsonString = data.jsonData?.ToString() ?? "{}";
  134. return (ICommand)Activator.CreateInstance(type, jsonString);
  135. }
  136. Debug.LogError($"[CommandExecutor] Command type '{commandClassName}' not found.");
  137. return null;
  138. }
  139. }
  140. }