UpdateWorkingContextCommand.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System.Linq;
  2. using UnityEngine;
  3. using LLM.Editor.Data;
  4. using LLM.Editor.Core;
  5. using LLM.Editor.Helper;
  6. using Newtonsoft.Json.Linq;
  7. using JetBrains.Annotations;
  8. namespace LLM.Editor.Commands
  9. {
  10. /// <summary>
  11. /// A command that allows the LLM to write to, update, or clear its own
  12. /// short-term memory for the current session.
  13. /// </summary>
  14. [UsedImplicitly]
  15. public class UpdateWorkingContextCommand : ICommand
  16. {
  17. [System.Serializable]
  18. private class UpdateWorkingContextParams
  19. {
  20. public JObject updates;
  21. public string[] keysToRemove;
  22. public bool clearAll;
  23. }
  24. private readonly UpdateWorkingContextParams _params;
  25. public UpdateWorkingContextCommand(string jsonParams)
  26. {
  27. _params = jsonParams?.FromJson<UpdateWorkingContextParams>();
  28. }
  29. public CommandOutcome Execute(CommandContext context)
  30. {
  31. if (_params == null)
  32. {
  33. context.ErrorMessage = "Invalid parameters for UpdateWorkingContextCommand.";
  34. return CommandOutcome.Error;
  35. }
  36. var workingContext = SessionManager.LoadWorkingContext();
  37. if (_params.clearAll)
  38. {
  39. workingContext = new JObject();
  40. context.Plan = null;
  41. }
  42. if (_params.keysToRemove != null)
  43. {
  44. foreach (var key in _params.keysToRemove)
  45. {
  46. workingContext.Remove(key);
  47. if (key == "plan") context.Plan = null;
  48. }
  49. }
  50. if (_params.updates != null)
  51. {
  52. if (_params.updates.TryGetValue("plan", out var planToken) && planToken is JArray planArray)
  53. {
  54. context.Plan = planArray.Select(step => step.ToString()).ToList();
  55. Debug.Log($"[UpdateWorkingContextCommand] Extracted plan with {context.Plan.Count} steps.");
  56. }
  57. foreach (var property in _params.updates.Properties())
  58. {
  59. workingContext[property.Name] = property.Value;
  60. }
  61. }
  62. SessionManager.SaveWorkingContext(workingContext);
  63. Debug.Log($"[UpdateWorkingContextCommand] Working context updated.");
  64. return CommandOutcome.Success;
  65. }
  66. }
  67. }