Decompiled source of PummelPartyMcp v1.0.0

BepInEx/plugins/PummelPartyMcp/PummelPartyMcp.Plugin.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.Win32.SafeHandles;
using ModSystem.Logic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PummelPartyMcp.Core;
using PummelPartyMcp.Game;
using PummelPartyMcp.Hooks;
using PummelPartyMcp.Safety;
using PummelPartyMcp.Tools;
using UnityEngine;
using UnityEngine.Rendering.PostProcessing;
using UnityEngine.SceneManagement;
using ZP.Net;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("PummelPartyMcp.Plugin")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+2e8972caea375df6755375b0655b22adff6e5bd2")]
[assembly: AssemblyProduct("PummelPartyMcp.Plugin")]
[assembly: AssemblyTitle("PummelPartyMcp.Plugin")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace PummelPartyMcp
{
	internal sealed class PluginRuntimeInfo
	{
		public string GameVersion;

		public string UnityVersion;

		public string SessionId;
	}
	[BepInPlugin("com.pummelpartymcp.plugin", "PummelPartyMcp", "1.0.0")]
	public sealed class PummelPartyMcpPlugin : BaseUnityPlugin
	{
		private sealed class BepInExPluginLog : IPluginLog
		{
			private readonly ManualLogSource m_source;

			public BepInExPluginLog(ManualLogSource source)
			{
				m_source = source;
			}

			public void Debug(string message)
			{
				m_source.LogDebug((object)message);
			}

			public void Info(string message)
			{
				m_source.LogInfo((object)message);
			}

			public void Warning(string message)
			{
				m_source.LogWarning((object)message);
			}

			public void Error(string message)
			{
				m_source.LogError((object)message);
			}
		}

		private const int MaxWorkItemsPerFrame = 16;

		private const double MaxWorkMillisecondsPerFrame = 8.0;

		private static readonly TimeSpan MainThreadTimeout = TimeSpan.FromSeconds(10.0);

		private PluginConfig m_config;

		private bool m_enabledAtStart;

		private IPluginLog m_log;

		private PluginRuntimeInfo m_info;

		private readonly EditorLifecycle m_lifecycle = new EditorLifecycle();

		private readonly Stopwatch m_clock = Stopwatch.StartNew();

		private bool m_sceneHooked;

		private bool m_shutDown;

		private LogRingBuffer m_logRing;

		private FramePoller m_poller;

		private EditServices m_edit;

		private ToolRegistry m_registry;

		private PublishBlockMonitor m_monitor;

		private MainThreadDispatcher m_dispatcher;

		private RpcHttpServer m_server;

		private volatile ToolAccess m_access;

		private volatile string m_blockMissing;

		private int m_cancelledAtDisarm;

		private bool m_logHooked;

		private static readonly TimeSpan ScanInterval = TimeSpan.FromSeconds(0.5);

		private bool m_scanned;

		private TimeSpan m_lastScanAt;

		private bool m_lastScanResult;

		private TimeSpan Now => m_clock.Elapsed;

		private static string ReadGameVersion()
		{
			try
			{
				return Application.version;
			}
			catch (Exception)
			{
				return null;
			}
		}

		private void Awake()
		{
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			m_config = new PluginConfig(((BaseUnityPlugin)this).Config);
			m_enabledAtStart = m_config.PluginEnabled;
			((Behaviour)this).enabled = false;
			if (!m_enabledAtStart)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)"PummelPartyMcp 1.0.0 is disabled ([General] PluginEnabled = false): no RPC server, no Workshop publish block.");
				return;
			}
			m_log = new BepInExPluginLog(((BaseUnityPlugin)this).Logger);
			GameReflection.Log = m_log;
			if ((Object)(object)((Component)this).transform.parent == (Object)null)
			{
				Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			}
			m_info = new PluginRuntimeInfo
			{
				GameVersion = ReadGameVersion(),
				UnityVersion = Application.unityVersion,
				SessionId = Guid.NewGuid().ToString("N")
			};
			((BaseUnityPlugin)this).Logger.LogInfo((object)(string.Format("{0} {1} (api v{2}); game version {3}, Unity {4}. ", "PummelPartyMcp", "1.0.0", 2, m_info.GameVersion, m_info.UnityVersion) + "Dormant: the plugin starts when the Mod Editor opens and stops when it closes."));
			SceneManager.sceneLoaded += OnSceneLoaded;
			m_sceneHooked = true;
			if (InstanceExistsOr(onError: false))
			{
				Scene activeScene = SceneManager.GetActiveScene();
				OnSceneLoadedCore(((Scene)(ref activeScene)).name);
			}
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			try
			{
				OnSceneLoadedCore(((Scene)(ref scene)).name);
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("scene-loaded handler failed: " + ex.GetType().Name + ": " + ex.Message));
			}
		}

		private void OnSceneLoadedCore(string sceneName)
		{
			if (!m_shutDown)
			{
				bool editorExists = ((m_lifecycle.State == LifecycleState.Dormant) ? InstanceExistsOr(onError: false) : EditorPresent(fresh: true));
				switch (m_lifecycle.OnSceneLoaded(sceneName, editorExists, Now))
				{
				case LifecycleAction.Arm:
					Arm("scene " + sceneName);
					break;
				case LifecycleAction.BeginDisarm:
					BeginDisarm();
					break;
				}
			}
		}

		private void Update()
		{
			if (m_shutDown)
			{
				return;
			}
			LifecycleAction lifecycleAction = LifecycleAction.None;
			try
			{
				bool flag = EditorPresent(fresh: false);
				if (!flag && m_lifecycle.SeenEditor && (m_lifecycle.State == LifecycleState.Active || m_lifecycle.State == LifecycleState.Failed))
				{
					flag = EditorPresent(fresh: true);
				}
				lifecycleAction = m_lifecycle.OnFrame(flag, Now, m_lifecycle.State == LifecycleState.Disarming && WorkIdle());
			}
			catch (Exception ex)
			{
				GameReflection.WarnOnce("lifecycle.frame", "lifecycle check failed: " + ex.GetType().Name + ": " + ex.Message);
			}
			if (lifecycleAction == LifecycleAction.BeginDisarm)
			{
				BeginDisarm();
			}
			if (m_lifecycle.State != LifecycleState.Dormant)
			{
				Pump();
			}
			if (lifecycleAction == LifecycleAction.FinishDisarm)
			{
				FinishDisarm();
			}
		}

		private void Pump()
		{
			m_edit?.Observe();
			m_dispatcher?.Drain(16, 8.0);
			m_poller?.Tick();
			m_registry?.WriteQueue.Pump();
		}

		private bool WorkIdle()
		{
			if (m_poller != null && m_poller.Count > 0)
			{
				return false;
			}
			if (m_registry != null && (m_registry.WriteQueue.IsBusy || m_registry.WriteQueue.PendingCount > 0))
			{
				return false;
			}
			if (m_dispatcher != null)
			{
				if (m_dispatcher.PendingCount == 0)
				{
					return m_dispatcher.RunningCount == 0;
				}
				return false;
			}
			return true;
		}

		private bool InstanceExistsOr(bool onError)
		{
			try
			{
				return ReadInstanceExists();
			}
			catch (Exception ex)
			{
				GameReflection.WarnOnce("lifecycle.editor", "cannot read EditorSystem.Instance (game version changed?): " + ex.GetType().Name + ": " + ex.Message);
				return onError;
			}
		}

		private bool EditorPresent(bool fresh)
		{
			if (InstanceExistsOr(onError: false))
			{
				return true;
			}
			if (!fresh && m_scanned && Now - m_lastScanAt < ScanInterval)
			{
				return m_lastScanResult;
			}
			try
			{
				m_lastScanResult = ScanForEditors();
			}
			catch (Exception ex)
			{
				GameReflection.WarnOnce("lifecycle.scan", "cannot look for EditorSystem objects: " + ex.GetType().Name + ": " + ex.Message);
				m_lastScanResult = true;
			}
			m_scanned = true;
			m_lastScanAt = Now;
			return m_lastScanResult;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static bool ReadInstanceExists()
		{
			return (Object)(object)EditorAccess.EditorOrNull() != (Object)null;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static bool ScanForEditors()
		{
			return Object.FindObjectsOfType<EditorSystem>().Length != 0;
		}

		private static bool InstanceReadable()
		{
			try
			{
				ReadInstanceExists();
				return true;
			}
			catch
			{
				return false;
			}
		}

		private void Arm(string trigger)
		{
			Stopwatch stopwatch = Stopwatch.StartNew();
			bool flag = false;
			bool flag2 = false;
			try
			{
				m_monitor = InstallPublishBlock();
				flag2 = true;
				m_access = ToolAccess.Starting;
				m_blockMissing = null;
				m_scanned = false;
				HookLog();
				m_config.RefreshIfChanged();
				RemoveLeftoverHooks();
				PublishBlockStatus publishBlockStatus = m_monitor.Current();
				if (!publishBlockStatus.Complete)
				{
					m_blockMissing = string.Join("; ", publishBlockStatus.Missing.ToArray());
					ArmError("the Workshop publish block could not be installed completely (missing: " + m_blockMissing + "). The editor and mod tools are off for this Mod Editor session (only ping, get_status, get_log and self_test answer).");
				}
				bool flag3 = InstanceReadable();
				if (!flag3)
				{
					ArmError("cannot read EditorSystem.Instance (game version changed?). The Workshop publish block is installed, but the editor and mod tools are off for this Mod Editor session (only ping, get_status, get_log and self_test answer).");
				}
				bool flag4 = publishBlockStatus.Complete && flag3;
				LogVersionGate();
				if (flag4 && m_config.EnableWrites && m_config.ServerEnabled)
				{
					RecoverImports();
				}
				string arg = "";
				string text;
				bool flag5;
				if (!m_config.ServerEnabled)
				{
					text = "RPC server off ([Server] Enabled = false)";
					flag5 = flag4;
				}
				else if (!StartServer(flag4, out text))
				{
					flag5 = false;
				}
				else
				{
					flag5 = flag4;
					if (flag5)
					{
						arg = ", " + InstallHooks();
					}
				}
				m_access = ((!publishBlockStatus.Complete) ? ToolAccess.BlockIncomplete : (flag3 ? ToolAccess.Enabled : ToolAccess.EditorUnreadable));
				m_lifecycle.Armed(flag5, EditorPresent(fresh: true), Now, DateTime.UtcNow);
				flag = true;
				((Behaviour)this).enabled = true;
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Mod Editor opened (" + trigger + "): Workshop publish block " + (publishBlockStatus.Complete ? $"active ({publishBlockStatus.PatchedCount} methods)" : "INCOMPLETE") + $"{arg}; {text}; armed in {stopwatch.ElapsedMilliseconds} ms."));
			}
			catch (Exception ex)
			{
				if (!flag2)
				{
					m_monitor = InstallPublishBlock();
				}
				ArmError("starting for the Mod Editor failed: " + ex.GetType().Name + ": " + ex.Message + ". The tools are off for this Mod Editor session.");
				StopSessionServer();
				if (!flag)
				{
					m_lifecycle.ArmAborted(EditorPresent(fresh: true), Now, DateTime.UtcNow);
				}
				((Behaviour)this).enabled = true;
			}
		}

		private void ArmError(string message)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)message);
			try
			{
				Debug.LogError((object)("[PummelPartyMcp] " + message));
			}
			catch
			{
			}
		}

		private void HookLog()
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Expected O, but got Unknown
			if (!m_logHooked)
			{
				if (m_logRing == null)
				{
					m_logRing = new LogRingBuffer(2000);
				}
				Application.logMessageReceivedThreaded += new LogCallback(OnUnityLog);
				m_logHooked = true;
			}
		}

		private void UnhookLog()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected O, but got Unknown
			if (m_logHooked)
			{
				Application.logMessageReceivedThreaded -= new LogCallback(OnUnityLog);
				m_logHooked = false;
			}
		}

		private void LogVersionGate()
		{
			GameVersionStatus gameVersionStatus = m_config.CurrentGameVersion(m_info.GameVersion);
			if (gameVersionStatus.WritesAllowed)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)(gameVersionStatus.IsTested ? ("Game version " + m_info.GameVersion + " is in the tested list (" + string.Join(", ", gameVersionStatus.Tested) + ").") : ("Game version " + m_info.GameVersion + " is not in the tested list (" + string.Join(", ", gameVersionStatus.Tested) + ") but is accepted by [Safety] AcceptedGameVersion.")));
			}
			else
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)(GameVersionGate.Refusal(gameVersionStatus).Message + " (this is a warning: read tools keep working)"));
			}
		}

		private void RecoverImports()
		{
			try
			{
				foreach (string item in ImportJournal.RecoverAll(Path.Combine(Application.persistentDataPath, "WorkshopMods")))
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("import recovery: " + item));
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("import recovery skipped: " + ex.Message));
			}
		}

		private void RemoveLeftoverHooks()
		{
			string[] array = new string[3] { "com.pummelpartymcp.plugin.savewatch", "com.pummelpartymcp.plugin.modswitchguard", "com.pummelpartymcp.plugin.playtesthooks" };
			foreach (string text in array)
			{
				PatchRemoval.Result result = PatchRemoval.Remove(text);
				if (result.Removed > 0 || !result.Clean)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)($"Removed {result.Removed} patched methods of {text} left from the last Mod Editor session" + (result.Clean ? "." : ("; still left: " + string.Join(", ", result.Left.Concat(result.Errors).ToArray()) + "."))));
				}
			}
		}

		private PublishBlockMonitor InstallPublishBlock()
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Expected O, but got Unknown
			try
			{
				PublishBlocker.Configure(m_log, delegate(string message)
				{
					Debug.LogWarning((object)message);
				});
				List<BlockTarget> targets = PublishBlockTargets.Build(typeof(EditorSystem).Assembly);
				return new PublishBlockMonitor(PublishBlocker.Apply(new Harmony("com.pummelpartymcp.plugin.publishblock"), targets), targets, "com.pummelpartymcp.plugin.publishblock", m_log);
			}
			catch (Exception ex)
			{
				return new PublishBlockMonitor(new PublishBlockStatus(active: false, complete: false, 0, new string[1] { "installer failed: " + ex.GetType().Name + ": " + ex.Message }), null, "com.pummelpartymcp.plugin.publishblock", m_log);
			}
		}

		private bool StartServer(bool blockComplete, out string text)
		{
			string text2 = Path.Combine(Paths.ConfigPath, "PummelPartyMcp.token");
			string token;
			try
			{
				token = TokenAuth.LoadOrCreate(text2, out var created);
				((BaseUnityPlugin)this).Logger.LogInfo((object)((created ? "Created new token file: " : "Using token file: ") + text2));
			}
			catch (Exception ex)
			{
				ArmError("cannot read or create the token file " + text2 + ": " + ex.Message + ". No RPC server; the tools are off for this Mod Editor session.");
				text = "no RPC server (token file problem)";
				return false;
			}
			int port = m_config.Port;
			try
			{
				EnsureServices();
				ModTools.ResetSession();
				ScreenshotTool.StartSession();
				m_dispatcher = new MainThreadDispatcher();
				RpcHandler rpcHandler = new RpcHandler(m_registry, m_dispatcher, m_log, MainThreadTimeout, (string method) => SessionGate.Check(m_access, method, m_blockMissing));
				m_server = new RpcHttpServer(new RpcHttpServerOptions
				{
					Port = port,
					Token = token
				}, rpcHandler.Handle, m_log);
				m_server.Start();
				text = $"listening on http://127.0.0.1:{m_server.Port}/rpc, " + (blockComplete ? ("writes " + (m_config.EnableWrites ? "enabled" : "disabled")) : "only ping, get_status, get_log and self_test answer");
				return true;
			}
			catch (Exception ex2)
			{
				ArmError($"failed to start the RPC server on 127.0.0.1:{port} (port in use?): {ex2.GetType().Name}: {ex2.Message}. " + "The tools are off for this Mod Editor session; the Workshop publish block stays until the Mod Editor closes.");
				StopSessionServer();
				text = "no RPC server (port problem)";
				return false;
			}
		}

		private void StopSessionServer()
		{
			try
			{
				m_server?.Stop();
			}
			catch
			{
			}
			m_server = null;
			try
			{
				m_dispatcher?.Shutdown();
			}
			catch
			{
			}
			m_dispatcher = null;
		}

		private void EnsureServices()
		{
			if (m_registry == null)
			{
				IPluginLog log = m_log;
				PluginRuntimeInfo info = m_info;
				PluginConfig config = m_config;
				FramePoller poller = new FramePoller(log);
				EditServices editServices = new EditServices(poller, log);
				Func<bool> writesEnabled = delegate
				{
					config.RefreshIfChanged();
					return config.EnableWrites;
				};
				Func<GameVersionStatus> gameVersionPeek = () => config.CurrentGameVersion(info.GameVersion);
				Func<GameVersionStatus> func = delegate
				{
					config.RefreshIfChanged();
					return gameVersionPeek();
				};
				Func<PublishBlockStatus> blockStatus = () => m_monitor?.Current() ?? PublishBlockStatus.NotApplied;
				Func<bool> publishBlockComplete = () => blockStatus().Complete;
				ToolRegistry registry = new ToolRegistry(new WriteSafety(writesEnabled, publishBlockComplete, func, new GameEditorGuardHost(log)), new WriteQueue(log));
				StatusTools.Register(registry, info, writesEnabled, blockStatus, gameVersionPeek, func, editServices, m_lifecycle);
				SelfTestTool.Register(registry, info, func, blockStatus);
				HierarchyTools.Register(registry);
				ObjectTools.Register(registry);
				ActionTools.Register(registry);
				AssetTools.Register(registry);
				AssetImportTools.Register(registry, editServices, delegate
				{
					config.RefreshIfChanged();
					return config.AssetLimits;
				});
				PrefabTools.Register(registry, editServices);
				LogTools.Register(registry, m_logRing, info);
				ScreenshotTool.Register(registry, (MonoBehaviour)(object)this, poller, log);
				ModTools.Register(registry, poller, log, editServices);
				ObjectEditTools.Register(registry, editServices);
				ComponentTools.Register(registry, editServices);
				SettingsTools.Register(registry, editServices);
				ActionEditTools.Register(registry, editServices);
				PlaytestTools.Register(registry, editServices, info);
				BatchTool.Register(registry, poller);
				m_poller = poller;
				m_edit = editServices;
				m_registry = registry;
			}
		}

		private string InstallHooks()
		{
			InstallSaveWatch();
			InstallModSwitchGuard();
			InstallPlaytestHooks();
			return string.Format("playtest hooks {0}, save watch {1}, ", PlaytestHooks.TriggerHooks + PlaytestHooks.ActionHooks, SaveWatch.Installed ? "on" : "OFF") + "mod-switch guard " + (ModSwitchGuard.Installed ? "on" : "OFF");
		}

		private void InstallSaveWatch()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Expected O, but got Unknown
			try
			{
				MethodInfo method = typeof(EditorSystem).GetMethod("SaveCurrentMod", BindingFlags.Instance | BindingFlags.Public, null, new Type[1] { typeof(bool) }, null);
				string text = SaveWatch.Install(new Harmony("com.pummelpartymcp.plugin.savewatch"), method);
				if (text != null)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Save watch not installed (" + text + "); unsaved-edit tracking falls back to the editor's dirty flag."));
					return;
				}
				EditServices edit = m_edit;
				SaveWatch.OnSaved = delegate
				{
					edit.OnSaved();
				};
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Save watch not installed (" + ex.GetType().Name + ": " + ex.Message + "); unsaved-edit tracking falls back to the editor's dirty flag."));
			}
		}

		private void InstallModSwitchGuard()
		{
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Expected O, but got Unknown
			try
			{
				MethodBase method = typeof(EditorSystem).GetMethod("OpenMod", BindingFlags.Instance | BindingFlags.Public, null, new Type[1] { typeof(string) }, null);
				MethodBase method2 = typeof(EditorSystem).GetMethod("CreateNewMod", BindingFlags.Instance | BindingFlags.Public, null, new Type[3]
				{
					typeof(string),
					typeof(PummelModType),
					typeof(string)
				}, null);
				MethodBase methodBase = typeof(NewModPopup).GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic).FirstOrDefault((MethodInfo m) => m.Name == "CreateNewMod" && m.GetParameters().Length == 1);
				MethodBase method3 = typeof(MainMenuWidget).GetMethod("DeleteModResult", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[1] { typeof(int) }, null);
				MethodBase method4 = typeof(LoadModPopup).GetMethod("DeleteModResult", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[1] { typeof(int) }, null);
				MethodBase method5 = typeof(EditorSystem).GetMethod("SetCurrentMod", BindingFlags.Instance | BindingFlags.Public, null, new Type[1] { typeof(PummelMod) }, null);
				MethodBase method6 = typeof(EditorSystem).GetMethod("OnDisable", BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null);
				ModSwitchGuard.Log = m_log;
				ModSwitchGuard.ExtraSink = delegate(string message)
				{
					Debug.LogWarning((object)message);
				};
				string text = ModSwitchGuard.Install(new Harmony("com.pummelpartymcp.plugin.modswitchguard"), new MethodBase[5] { method, methodBase, method2, method3, method4 }, method5, method6);
				if (text != null)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Mod-switch guard not installed (" + text + "); capture_preview_image is disabled."));
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Mod-switch guard not installed (" + ex.GetType().Name + ": " + ex.Message + "); capture_preview_image is disabled."));
			}
		}

		private void InstallPlaytestHooks()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			try
			{
				List<string> list = PlaytestHooks.Install(new Harmony("com.pummelpartymcp.plugin.playtesthooks"));
				if (list.Count > 0)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)(string.Format("Playtest hooks: {0} trigger and {1} action hooks installed; problems: {2}. ", PlaytestHooks.TriggerHooks, PlaytestHooks.ActionHooks, string.Join("; ", list.ToArray())) + "get_playtest_events may lack trigger_fired / action_executed entries."));
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Playtest hooks not installed (" + ex.GetType().Name + ": " + ex.Message + "); get_playtest_events has no trigger_fired / action_executed entries."));
			}
		}

		private void BeginDisarm()
		{
			m_access = ToolAccess.Stopping;
			int num = 0;
			try
			{
				m_server?.Stop();
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("stopping the RPC server: " + ex.Message));
			}
			m_server = null;
			try
			{
				m_dispatcher?.Shutdown(SessionGate.EditorClosed);
			}
			catch (Exception ex2)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("stopping the dispatcher: " + ex2.Message));
			}
			try
			{
				if (m_registry != null)
				{
					num += m_registry.WriteQueue.FailPending(SessionGate.EditorClosed);
				}
				num += ScreenshotTool.BeginStop(SessionGate.EditorClosed);
			}
			catch (Exception ex3)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("failing queued calls: " + ex3.Message));
			}
			m_cancelledAtDisarm = num;
		}

		private void FinishDisarm()
		{
			int num = m_cancelledAtDisarm;
			try
			{
				if (m_registry != null)
				{
					num += m_registry.WriteQueue.Reset(SessionGate.EditorClosed, SessionGate.EditorClosedWhileRunning);
				}
				m_poller?.Clear();
				num += ScreenshotTool.ResetSession(SessionGate.EditorClosedWhileRunning);
				((MonoBehaviour)this).StopAllCoroutines();
				ModTools.ResetSession();
				ModSwitchGuard.Disarm();
				if (m_dispatcher != null)
				{
					num += m_dispatcher.AbandonRunning(SessionGate.EditorClosedWhileRunning);
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("ending the running calls failed: " + ex.GetType().Name + ": " + ex.Message));
			}
			m_dispatcher = null;
			PlaytestHooks.Collecting = false;
			try
			{
				PlaytestLogicRecorder.Reset();
			}
			catch
			{
			}
			int restored = 0;
			List<string> left = new List<string>();
			Take("save watch", SaveWatch.Uninstall);
			Take("mod-switch guard", ModSwitchGuard.Uninstall);
			Take("playtest hooks", PlaytestHooks.Uninstall);
			Take("publish block", PublishBlocker.Remove);
			m_monitor = null;
			m_blockMissing = null;
			if (left.Count > 0)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)(string.Format("Mod Editor closed, but {0} patches could not be removed ({1}). ", left.Count, string.Join("; ", left.ToArray())) + "They stay in the game until the next Mod Editor open and close removes them: a leftover playtest hook still runs (and returns at once) in mod minigames, a leftover Workshop block still blocks the main-menu Workshop delete. Restart the game to be sure."));
			}
			string text = m_lifecycle.DisarmReason ?? "the Mod Editor was closed";
			try
			{
				UnhookLog();
			}
			catch
			{
			}
			((Behaviour)this).enabled = false;
			LifecycleAction lifecycleAction = m_lifecycle.Disarmed(EditorPresent(fresh: true));
			((BaseUnityPlugin)this).Logger.LogInfo((object)$"Dormant again ({text}): server stopped, {num} calls cancelled, {restored} patched methods restored ({left.Count} left).");
			if (lifecycleAction == LifecycleAction.Arm)
			{
				Arm("again, while the plugin was stopping");
			}
			void Take(string what, Func<PatchRemoval.Result> remove)
			{
				try
				{
					PatchRemoval.Result result = remove();
					restored += result.Removed;
					left.AddRange(result.Left.Select((string n) => what + " " + n));
					left.AddRange(result.Errors.Select((string n) => what + " " + n));
				}
				catch (Exception ex2)
				{
					left.Add(what + ": " + ex2.GetType().Name + ": " + ex2.Message);
				}
			}
		}

		private void OnDestroy()
		{
			Shutdown("OnDestroy");
		}

		private void OnApplicationQuit()
		{
			Shutdown("OnApplicationQuit");
		}

		private void Shutdown(string reason)
		{
			if (m_shutDown || !m_enabledAtStart)
			{
				return;
			}
			m_shutDown = true;
			try
			{
				if (m_sceneHooked)
				{
					SceneManager.sceneLoaded -= OnSceneLoaded;
					m_sceneHooked = false;
				}
				m_access = ToolAccess.Stopping;
				StopSessionServer();
				UnhookLog();
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Stopped (" + reason + ")."));
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Error during shutdown: " + ex.Message));
			}
		}

		private void OnUnityLog(string condition, string stackTrace, LogType type)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Invalid comparison between Unknown and I4
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Invalid comparison between Unknown and I4
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				bool flag = (int)type == 0 || (int)type == 4 || (int)type == 1;
				m_logRing?.Add(LogTools.LevelName(type), condition, flag ? stackTrace : null);
			}
			catch
			{
			}
		}
	}
	internal sealed class PluginConfig
	{
		public const int DefaultPort = 38917;

		private readonly ConfigFile m_file;

		private readonly ConfigEntry<bool> m_pluginEnabled;

		private readonly ConfigEntry<bool> m_enableWrites;

		private readonly ConfigEntry<string> m_acceptedGameVersion;

		private readonly ConfigEntry<bool> m_forceUntested;

		private readonly ConfigEntry<int> m_port;

		private readonly ConfigEntry<bool> m_serverEnabled;

		private readonly ConfigEntry<int> m_maxImportFileMB;

		private readonly ConfigEntry<int> m_maxModAssetsMB;

		private readonly ConfigEntry<int> m_maxAudioSeconds;

		private readonly ConfigEntry<int> m_maxCompressedAudioMB;

		private DateTime m_lastWriteUtc;

		public AssetLimits AssetLimits => new AssetLimits((m_maxImportFileMB.Value >= 1 && m_maxImportFileMB.Value <= 1024) ? m_maxImportFileMB.Value : 50, (m_maxModAssetsMB.Value >= 1 && m_maxModAssetsMB.Value <= 8192) ? m_maxModAssetsMB.Value : 500, (m_maxAudioSeconds.Value >= 1 && m_maxAudioSeconds.Value <= 7200) ? m_maxAudioSeconds.Value : 600, (m_maxCompressedAudioMB.Value >= 1 && m_maxCompressedAudioMB.Value <= 1024) ? m_maxCompressedAudioMB.Value : 15);

		public bool PluginEnabled => m_pluginEnabled.Value;

		public bool EnableWrites => m_enableWrites.Value;

		public string AcceptedGameVersion => m_acceptedGameVersion.Value ?? "";

		public bool ForceGameVersionUntested => m_forceUntested.Value;

		public int Port
		{
			get
			{
				int value = m_port.Value;
				if (value < 1024 || value > 65535)
				{
					return 38917;
				}
				return m_port.Value;
			}
		}

		public bool ServerEnabled => m_serverEnabled.Value;

		public PluginConfig(ConfigFile config)
		{
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Expected O, but got Unknown
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Expected O, but got Unknown
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Expected O, but got Unknown
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Expected O, but got Unknown
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Expected O, but got Unknown
			m_file = config;
			m_pluginEnabled = config.Bind<bool>("General", "PluginEnabled", true, "Master switch, read at game start. true = the plugin starts when the Mod Editor opens and stops when it closes. false = the plugin does nothing at all: no RPC server and no Workshop publish block. Set false (and restart the game) to publish a mod to the Workshop by hand.");
			m_enableWrites = config.Bind<bool>("Safety", "EnableWrites", true, "Allow write tools (they still only act on mods named MCP_...). false = every write tool returns WRITES_DISABLED. Does not affect the Workshop publish block, which is on while the Mod Editor is open and the plugin is enabled.");
			m_acceptedGameVersion = config.Bind<string>("Safety", "AcceptedGameVersion", "", "Game version you accept although this plugin was not tested with it (the tested versions are listed in the log at startup and by get_status). Empty = none. After a game update write tools return GAME_VERSION_UNTESTED (read tools keep working); run the self_test tool and, if it reports ok, set this to the exact running version, e.g. 1.14.2. Applies only to that exact version string; the next game update closes the gate again. Re-read from this file on every write call, no restart needed.");
			m_forceUntested = config.Bind<bool>("Safety", "ForceGameVersionUntested", false, "Test switch: true = treat the running game version as untested even if it is in the tested list (write tools then return GAME_VERSION_UNTESTED unless AcceptedGameVersion equals the running version). It can only make the gate stricter; no setting here can accept a version the plugin was not tested with other than AcceptedGameVersion.");
			m_port = config.Bind<int>("Server", "Port", 38917, new ConfigDescription("TCP port of the local RPC server (bound to 127.0.0.1 only, and only while the Mod Editor is open).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1024, 65535), Array.Empty<object>()));
			m_serverEnabled = config.Bind<bool>("Server", "Enabled", true, "Start the local RPC server while the Mod Editor is open. false = no server, but the Workshop publish block still applies while the Mod Editor is open (as long as [General] PluginEnabled = true).");
			m_maxImportFileMB = config.Bind<int>("Assets", "MaxImportFileMB", 50, new ConfigDescription("import_asset: largest source file accepted, in MB. The editor itself has no limit; the game decodes audio on the main thread and waits for it, so keep this moderate. Re-read from this file on every import call, no restart needed.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 1024), Array.Empty<object>()));
			m_maxModAssetsMB = config.Bind<int>("Assets", "MaxModAssetsMB", 500, new ConfigDescription("import_asset: largest total size of the sandbox mod's Assets folder after an import, in MB. Re-read from this file on every import call, no restart needed.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 8192), Array.Empty<object>()));
			m_maxAudioSeconds = config.Bind<int>("Assets", "MaxAudioSeconds", 600, new ConfigDescription("import_asset: longest audio clip accepted, in seconds, read from the WAV/OGG/MP3 header of the copy (the game decodes the whole clip on the main thread and waits for it). Re-read on every import call, no restart needed.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 7200), Array.Empty<object>()));
			m_maxCompressedAudioMB = config.Bind<int>("Assets", "MaxCompressedAudioMB", 15, new ConfigDescription("import_asset: largest OGG/MP3 file accepted when its duration cannot be read from its header (e.g. a VBR MP3 without a Xing/VBRI header), in MB. Re-read on every import call, no restart needed.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 1024), Array.Empty<object>()));
			m_lastWriteUtc = LastWrite();
		}

		private DateTime LastWrite()
		{
			try
			{
				return File.GetLastWriteTimeUtc(m_file.ConfigFilePath);
			}
			catch
			{
				return DateTime.MinValue;
			}
		}

		public void RefreshIfChanged()
		{
			try
			{
				if (!(LastWrite() == m_lastWriteUtc))
				{
					m_file.Reload();
					m_lastWriteUtc = LastWrite();
				}
			}
			catch
			{
				m_lastWriteUtc = LastWrite();
			}
		}

		public GameVersionStatus CurrentGameVersion(string running)
		{
			return GameVersionGate.Evaluate(running, GameVersionGate.TestedVersions, AcceptedGameVersion, ForceGameVersionUntested);
		}
	}
	internal static class PluginInfo
	{
		public const string Guid = "com.pummelpartymcp.plugin";

		public const string Name = "PummelPartyMcp";

		public const string Version = "1.0.0";

		public const int ApiVersion = 2;

		public const string TokenFileName = "PummelPartyMcp.token";
	}
}
namespace PummelPartyMcp.Tools
{
	internal static class ActionEditTools
	{
		private sealed class ActionArgs
		{
			public TriggerAddress Address;

			public string Type;

			public int? Index;

			public int? NewIndex;

			public JObject Parameters;

			public JToken TargetFlags;

			public JToken Targets;
		}

		private sealed class TriggerArgs
		{
			public TriggerAddress Address;

			public string Guid;

			public string Component;

			public string Type;

			public JObject Parameters;
		}

		private sealed class TargetPlan
		{
			public int? Flags;

			public Component[] Targets;

			public bool IsEmpty
			{
				get
				{
					if (!Flags.HasValue)
					{
						return Targets == null;
					}
					return false;
				}
			}
		}

		private sealed class Ctx
		{
			public EditorSystem Ed;

			public PummelMod Mod;

			public ResolvedTrigger First;
		}

		public const int MaxParameters = 64;

		public static void Register(ToolRegistry registry, EditServices services)
		{
			registry.Register(ToolDefinition.Write("add_action", WriteGuard.OpenMod(), delegate(ToolContext ctx)
			{
				ActionArgs actionArgs = ParseActionArgs(ctx, needIndex: false);
				actionArgs.Type = ctx.GetString("type", required: true);
				actionArgs.Index = OptIndex(ctx, "index");
				return actionArgs;
			}, delegate(WriteInvocation inv)
			{
				AddAction(inv, services);
			}, EditCommon.EditTimeout));
			registry.Register(ToolDefinition.Write("remove_action", WriteGuard.OpenMod(), (ToolContext ctx) => ParseActionArgs(ctx, needIndex: true, allowValues: false), delegate(WriteInvocation inv)
			{
				RemoveAction(inv, services);
			}, EditCommon.EditTimeout));
			registry.Register(ToolDefinition.Write("move_action", WriteGuard.OpenMod(), delegate(ToolContext ctx)
			{
				ActionArgs actionArgs = ParseActionArgs(ctx, needIndex: true, allowValues: false);
				actionArgs.NewIndex = OptIndex(ctx, "newIndex") ?? throw RpcException.InvalidParams("'newIndex' is required");
				return actionArgs;
			}, delegate(WriteInvocation inv)
			{
				MoveAction(inv, services);
			}, EditCommon.EditTimeout));
			registry.Register(ToolDefinition.Write("set_action", WriteGuard.OpenMod(), delegate(ToolContext ctx)
			{
				ActionArgs actionArgs = ParseActionArgs(ctx, needIndex: true);
				if ((actionArgs.Parameters == null || ((JContainer)actionArgs.Parameters).Count == 0) && actionArgs.TargetFlags == null && actionArgs.Targets == null)
				{
					throw RpcException.InvalidParams("give at least one of 'parameters', 'targetFlags', 'targets'");
				}
				return actionArgs;
			}, delegate(WriteInvocation inv)
			{
				SetAction(inv, services);
			}, EditCommon.EditTimeout));
			registry.Register(ToolDefinition.Write("add_trigger", WriteGuard.OpenMod(), delegate(ToolContext ctx)
			{
				if (ctx.Params["trigger"] != null || ctx.Params["scope"] != null || ctx.Params["path"] != null)
				{
					throw RpcException.InvalidParams("add_trigger takes guid (+ component), type and parameters; triggers can only be added to a Logic component");
				}
				return new TriggerArgs
				{
					Guid = EditCommon.Guid(ctx, "guid", required: true),
					Component = ctx.GetString("component"),
					Type = (ctx.GetString("type") ?? "Start"),
					Parameters = OptParameters(ctx)
				};
			}, delegate(WriteInvocation inv)
			{
				AddTrigger(inv, services);
			}, EditCommon.EditTimeout));
			registry.Register(ToolDefinition.Write("remove_trigger", WriteGuard.OpenMod(), delegate(ToolContext ctx)
			{
				TriggerArgs result = new TriggerArgs
				{
					Address = TriggerAddress.Parse(ctx.Params, EditorAccess.NormalizeGuid)
				};
				RejectExtra(ctx, "type", "parameters", "index");
				return result;
			}, delegate(WriteInvocation inv)
			{
				RemoveTrigger(inv, services);
			}, EditCommon.EditTimeout));
			registry.Register(ToolDefinition.Write("set_trigger", WriteGuard.OpenMod(), delegate(ToolContext ctx)
			{
				TriggerArgs triggerArgs = new TriggerArgs
				{
					Address = TriggerAddress.Parse(ctx.Params, EditorAccess.NormalizeGuid),
					Type = ctx.GetString("type"),
					Parameters = OptParameters(ctx)
				};
				if (triggerArgs.Type == null && (triggerArgs.Parameters == null || ((JContainer)triggerArgs.Parameters).Count == 0))
				{
					throw RpcException.InvalidParams("give 'type' and/or 'parameters'");
				}
				return triggerArgs;
			}, delegate(WriteInvocation inv)
			{
				SetTrigger(inv, services);
			}, EditCommon.EditTimeout));
		}

		private static ActionArgs ParseActionArgs(ToolContext ctx, bool needIndex, bool allowValues = true)
		{
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Invalid comparison between Unknown and I4
			ActionArgs actionArgs = new ActionArgs
			{
				Address = TriggerAddress.Parse(ctx.Params, EditorAccess.NormalizeGuid)
			};
			if (needIndex)
			{
				actionArgs.Index = OptIndex(ctx, "index") ?? throw RpcException.InvalidParams("'index' (action index in the list) is required");
			}
			if (allowValues)
			{
				actionArgs.Parameters = OptParameters(ctx);
				actionArgs.TargetFlags = NullToNone(ctx.Params["targetFlags"]);
				actionArgs.Targets = NullToNone(ctx.Params["targets"]);
				if (actionArgs.Targets != null && (int)actionArgs.Targets.Type != 2)
				{
					throw RpcException.InvalidParams("'targets' must be an array of object references (guid strings, {\"guid\": ...} or null)");
				}
			}
			else
			{
				RejectExtra(ctx, "parameters", "targetFlags", "targets", "type");
			}
			return actionArgs;
		}

		private static JToken NullToNone(JToken t)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Invalid comparison between Unknown and I4
			if (t != null && (int)t.Type != 10)
			{
				return t;
			}
			return null;
		}

		private static void RejectExtra(ToolContext ctx, params string[] names)
		{
			foreach (string text in names)
			{
				if (ctx.Params[text] != null)
				{
					throw RpcException.InvalidParams("'" + text + "' is not a parameter of " + ctx.Method);
				}
			}
		}

		private static int? OptIndex(ToolContext ctx, string name)
		{
			long? num = ctx.GetLong(name, 0L, 100000L);
			if (!num.HasValue)
			{
				return null;
			}
			return (int)num.Value;
		}

		private static JObject OptParameters(ToolContext ctx)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Invalid comparison between Unknown and I4
			JToken val = ctx.Params["parameters"];
			if (val == null || (int)val.Type == 10)
			{
				return null;
			}
			JToken obj = ((val is JObject) ? val : null) ?? throw RpcException.InvalidParams("'parameters' must be an object {name: value, ...}");
			if (((JContainer)obj).Count > 64)
			{
				throw RpcException.InvalidParams($"at most {64} parameters per call");
			}
			return (JObject)(object)obj;
		}

		private static Ctx Begin(TriggerAddress address)
		{
			EditorSystem val = EditorAccess.RequireEditor();
			EditContext.RequireEditReady(val);
			PummelMod currentMod = val.CurrentMod;
			ResolvedTrigger resolvedTrigger = ActionModel.Resolve(val, currentMod, address, forWrite: true);
			if (resolvedTrigger.NotEditable != null)
			{
				throw RpcException.InvalidParams("'" + address.Describe() + "': " + resolvedTrigger.NotEditable);
			}
			return new Ctx
			{
				Ed = val,
				Mod = currentMod,
				First = resolvedTrigger
			};
		}

		private static ResolvedTrigger Fresh(Ctx c)
		{
			ResolvedTrigger resolvedTrigger = ActionModel.Resolve(c.Ed, c.Mod, c.First.Address, forWrite: true);
			if (resolvedTrigger.NotEditable != null)
			{
				throw RpcException.InvalidParams("'" + resolvedTrigger.Name + "': " + resolvedTrigger.NotEditable + "; nothing was changed");
			}
			return resolvedTrigger;
		}

		private static void Run(WriteInvocation inv, EditServices services, Ctx c, string what, Func<ResolvedTrigger, Func<JObject>> apply)
		{
			bool settings = c.First.Address.IsPlayerSettings;
			EditHost host = new EditHost(c.Ed, settings ? null : ((Component)c.First.Object).gameObject);
			EditCommon.Run(services, inv, host, !settings, delegate
			{
				ResolvedTrigger resolvedTrigger = Fresh(c);
				ValueConverter valueConverter = new ValueConverter(c.Mod, summarizeTriggers: false, 12);
				JToken val = (settings ? valueConverter.Trigger(resolvedTrigger.Trigger, 0) : null);
				services.Observe();
				Func<JObject> build = apply(resolvedTrigger);
				bool changed = (settings ? (!JToken.DeepEquals(val, new ValueConverter(c.Mod, summarizeTriggers: false, 12).Trigger(resolvedTrigger.Trigger, 0))) : EditCommon.SnapshotChanged(host));
				services.MarkEditIfChanged(c.Mod, what, changed);
				return new EditOutcome
				{
					Changed = changed,
					Then = ((!settings) ? PostEditWait.AwaitPush : PostEditWait.None),
					BuildResult = delegate(EditReport report)
					{
						JObject val2 = build();
						bool undoable = !settings && EditCommon.Undoable(report);
						EditCommon.WithEditFields(val2, c.Ed, report, undoable);
						if (settings && report.Changed)
						{
							val2["note"] = JToken.op_Implicit("player-settings triggers are not undoable (the editor has no undo for mod settings); save_mod writes them to ModSettings.json");
						}
						return val2;
					}
				};
			});
		}

		private static void ApplyInModel(ParamPlan plan, EditServices services, Ctx c, string what, Action then)
		{
			List<string> list = new List<string>();
			bool flag = false;
			try
			{
				foreach (ParamWrite write in plan.Writes)
				{
					write.Apply();
					list.Add(write.Name);
				}
				if (then != null)
				{
					flag = true;
					then();
				}
			}
			catch (Exception innerException)
			{
				while (innerException is TargetInvocationException && innerException.InnerException != null)
				{
					innerException = innerException.InnerException;
				}
				bool flag2 = list.Count > 0 || flag;
				services.MarkEditIfChanged(c.Mod, what, flag2);
				string text = ((innerException is RpcException ex) ? ex.Message : (innerException.GetType().Name + ": " + innerException.Message));
				string code = ((innerException is RpcException ex2) ? ex2.Code : "INTERNAL");
				if (!flag2)
				{
					throw new RpcException(code, text);
				}
				string text2 = (c.First.Address.IsPlayerSettings ? "player-settings triggers have no undo" : "one undo reverts them");
				List<string> list2 = new List<string>();
				if (list.Count > 0)
				{
					list2.Add("already applied in this call: " + string.Join(", ", list.ToArray()));
				}
				if (flag)
				{
					list2.Add("the targets may be partly applied");
				}
				throw new RpcException(code, text + "; " + string.Join("; ", list2.ToArray()) + " (" + text2 + ")");
			}
		}

		private static JObject AddressJson(ResolvedTrigger r)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Expected O, but got Unknown
			JObject val = new JObject();
			if (r.Address.IsPlayerSettings)
			{
				val["scope"] = JToken.op_Implicit("playerSettings");
			}
			else
			{
				val["guid"] = JToken.op_Implicit(r.Address.Guid);
				val["component"] = JToken.op_Implicit(r.Slot.Reflected.name);
				val["componentGuid"] = JToken.op_Implicit(EditorAccess.GuidOf(r.Slot.Component));
			}
			val["trigger"] = JToken.op_Implicit(r.Address.Trigger);
			if (r.IsNested)
			{
				val["path"] = (JToken)new JArray((object)((IEnumerable<TriggerPathStep>)r.Address.Path).Select((Func<TriggerPathStep, JObject>)((TriggerPathStep s) => new JObject
				{
					["action"] = JToken.op_Implicit(s.Action),
					["choice"] = JToken.op_Implicit(s.Choice)
				})));
			}
			return val;
		}

		private static ModAction[] ActionsOf(ResolvedTrigger r)
		{
			return (ModAction[])(((object)r.Trigger.Actions) ?? ((object)new ModAction[0]));
		}

		private static ModAction RequireSameAction(ResolvedTrigger r, int index, ModAction expected)
		{
			ModAction[] array = ActionsOf(r);
			if (index >= array.Length || array[index] != expected)
			{
				throw new RpcException("INVALID_STATE", "the action list changed while the edit was waiting for the editor; nothing was changed (read get_action_graph again)");
			}
			return expected;
		}

		private static ReferenceResolver Refs(Ctx c, ResolvedTrigger r)
		{
			return new ReferenceResolver(c.Ed, r.ReferenceOwner);
		}

		private static TargetPlan PrepareTargets(ModAction action, PummelPartyMcp.Core.CallSite site, JToken flagsTok, JToken targetsTok, int? currentFlags, ReferenceResolver refs)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Expected O, but got Unknown
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Expected O, but got Unknown
			TargetPlan targetPlan = new TargetPlan();
			if (flagsTok == null && targetsTok == null)
			{
				return targetPlan;
			}
			TargetAction val = (TargetAction)(object)((action is TargetAction) ? action : null);
			if (val == null)
			{
				throw RpcException.InvalidParams($"{action.Type} has no targets ('targetFlags'/'targets' do not apply)");
			}
			bool[] hidden = TargetFlagRules.Hidden(ActionModel.HideFlags(val), site.HideSource);
			int num = currentFlags ?? ((int)val.TargetFlags);
			int num2 = num;
			if (flagsTok != null)
			{
				num2 = TargetFlagRules.Parse(flagsTok, "targetFlags");
				string text = TargetFlagRules.Check(hidden, num, num2);
				if (text != null)
				{
					throw RpcException.InvalidParams("'targetFlags': " + text);
				}
				targetPlan.Flags = num2;
			}
			if (targetsTok != null)
			{
				if ((num2 & 4) == 0)
				{
					throw RpcException.InvalidParams("'targets': the explicit target list is shown (and used) only while the Advanced target flag is set; pass targetFlags including Advanced");
				}
				Type type = ActionModel.AcceptedTargetType(val);
				JArray val2 = (JArray)targetsTok;
				if (((JContainer)val2).Count > 1024)
				{
					throw RpcException.InvalidParams($"'targets': more than {1024} elements");
				}
				Component[] array = (Component[])(object)new Component[((JContainer)val2).Count];
				for (int i = 0; i < ((JContainer)val2).Count; i++)
				{
					PRef pRef = (PRef)ValueParser.Parse(val2[i], ValueTypeDesc.Reference(type.Name), $"targets[{i}]");
					array[i] = (Component)ActionParams.ResolveRegistered(pRef.Guid, type, refs, $"targets[{i}]");
				}
				targetPlan.Targets = array;
			}
			return targetPlan;
		}

		private static void ApplyTargets(ModAction action, TargetPlan plan)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			if (!plan.IsEmpty)
			{
				TargetAction val = (TargetAction)action;
				if (plan.Flags.HasValue)
				{
					val.TargetFlags = (ModActionTargets)plan.Flags.Value;
				}
				if (plan.Targets != null)
				{
					val.Targets = plan.Targets;
				}
			}
		}

		private static JObject ActionJson(PummelMod mod, ModAction action, int index)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			return (JObject)new ValueConverter(mod, summarizeTriggers: false, 12).Action(action, index, 0);
		}

		private static void AddAction(WriteInvocation inv, EditServices services)
		{
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Expected O, but got Unknown
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			ActionArgs actionArgs = inv.ArgsAs<ActionArgs>();
			Ctx c = Begin(actionArgs.Address);
			ActionTypeInfo actionTypeInfo = ActionModel.FindActionType(actionArgs.Type) ?? throw RpcException.InvalidParams("unknown action type '" + actionArgs.Type + "' (a ModActionType name like ChangeHealth, a class name or a UI name; see list_action_types)");
			string text = ActionModel.WhyNotUsable(actionTypeInfo, c.Mod, c.First.Site);
			if (text != null)
			{
				throw RpcException.InvalidParams(text);
			}
			int count = ActionsOf(c.First).Length;
			bool append;
			int index = ActionListOps.ResolveInsertIndex(actionArgs.Index, count, out append);
			ModAction action = (ModAction)Activator.CreateInstance(actionTypeInfo.ClassType);
			bool defaultsApplied = false;
			if (append && actionTypeInfo.ClassType.IsSubclassOf(typeof(TargetAction)) && c.First.Site.DefaultTargets != 0)
			{
				((TargetAction)action).TargetFlags = (ModActionTargets)c.First.Site.DefaultTargets;
				defaultsApplied = true;
			}
			ReferenceResolver refs = Refs(c, c.First);
			ParamPlan plan = ActionParams.Prepare(action, actionArgs.Parameters, refs, actionTypeInfo.UiName);
			TargetPlan plan2 = PrepareTargets(action, c.First.Site, actionArgs.TargetFlags, actionArgs.Targets, null, refs);
			plan.ApplyAll();
			ApplyTargets(action, plan2);
			Run(inv, services, c, "add_action", delegate(ResolvedTrigger r)
			{
				if (ActionsOf(r).Length != count)
				{
					throw new RpcException("INVALID_STATE", "the action list changed while the edit was waiting for the editor; nothing was changed (read get_action_graph again)");
				}
				if (append)
				{
					ModAction[] array = (ModAction[])Extensions.AddElement((Array)ActionsOf(r), typeof(ModAction));
					array.SetValue(action, array.Length - 1);
					r.Trigger.Actions = array;
				}
				else
				{
					r.Trigger.Actions = ActionListOps.Insert(ActionsOf(r), index, action);
				}
				return delegate
				{
					//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
					//IL_00c0: Expected O, but got Unknown
					JObject obj = AddressJson(r);
					obj["index"] = JToken.op_Implicit(index);
					obj["mode"] = JToken.op_Implicit(append ? "append" : "insert");
					obj["defaultTargetsApplied"] = JToken.op_Implicit(defaultsApplied);
					obj["action"] = (JToken)(object)ActionJson(c.Mod, action, index);
					obj["clamped"] = (JToken)new JArray((object)plan.Clamped);
					AddNoTargetWarning(obj, action, c.First.Site);
					obj["actionCount"] = JToken.op_Implicit(ActionsOf(r).Length);
					return obj;
				};
			});
		}

		private static void RemoveAction(WriteInvocation inv, EditServices services)
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			ActionArgs actionArgs = inv.ArgsAs<ActionArgs>();
			Ctx ctx = Begin(actionArgs.Address);
			ModAction[] array = ActionsOf(ctx.First);
			int index = actionArgs.Index.Value;
			ActionListOps.CheckIndex(index, array.Length, "index");
			ModAction target = array[index];
			ModAction obj = target;
			string removedType = ((obj != null) ? ((object)obj.Type/*cast due to .constrained prefix*/).ToString() : null);
			Run(inv, services, ctx, "remove_action", delegate(ResolvedTrigger r)
			{
				RequireSameAction(r, index, target);
				r.Trigger.Actions = (ModAction[])Extensions.DeleteElement((Array)ActionsOf(r), index, typeof(ModAction));
				return delegate
				{
					//IL_002c: Unknown result type (might be due to invalid IL or missing references)
					//IL_0031: Unknown result type (might be due to invalid IL or missing references)
					//IL_004c: Unknown result type (might be due to invalid IL or missing references)
					//IL_007d: Expected O, but got Unknown
					JObject obj2 = AddressJson(r);
					obj2["index"] = JToken.op_Implicit(index);
					obj2["removed"] = (JToken)new JObject
					{
						["type"] = JToken.op_Implicit(removedType),
						["className"] = JToken.op_Implicit(((object)target)?.GetType().Name)
					};
					obj2["actionCount"] = JToken.op_Implicit(ActionsOf(r).Length);
					return obj2;
				};
			});
		}

		private static void MoveAction(WriteInvocation inv, EditServices services)
		{
			ActionArgs actionArgs = inv.ArgsAs<ActionArgs>();
			Ctx ctx = Begin(actionArgs.Address);
			ModAction[] array = ActionsOf(ctx.First);
			int from = actionArgs.Index.Value;
			int to = actionArgs.NewIndex.Value;
			ActionListOps.CheckIndex(from, array.Length, "index");
			ActionListOps.CheckIndex(to, array.Length, "newIndex");
			ModAction target = array[from];
			Run(inv, services, ctx, "move_action", delegate(ResolvedTrigger r)
			{
				RequireSameAction(r, from, target);
				if (from != to)
				{
					r.Trigger.Actions = ActionListOps.Move(ActionsOf(r), from, to);
				}
				return delegate
				{
					//IL_0076: Unknown result type (might be due to invalid IL or missing references)
					//IL_0080: Expected O, but got Unknown
					JObject obj = AddressJson(r);
					obj["index"] = JToken.op_Implicit(from);
					obj["newIndex"] = JToken.op_Implicit(to);
					obj["order"] = (JToken)new JArray((object)(from x in ActionsOf(r)
						select (x == null) ? null : ((object)x.Type/*cast due to .constrained prefix*/).ToString()));
					return obj;
				};
			});
		}

		private static void SetAction(WriteInvocation inv, EditServices services)
		{
			ActionArgs actionArgs = inv.ArgsAs<ActionArgs>();
			Ctx c = Begin(actionArgs.Address);
			ModAction[] array = ActionsOf(c.First);
			int index = actionArgs.Index.Value;
			ActionListOps.CheckIndex(index, array.Length, "index");
			ModAction action = array[index] ?? throw new RpcException("INVALID_STATE", $"action {index} is null in the model");
			ActionTypeInfo actionTypeInfo = ActionModel.InfoFor(((object)action).GetType());
			ReferenceResolver refs = Refs(c, c.First);
			ParamPlan plan = ActionParams.Prepare(action, actionArgs.Parameters, refs, actionTypeInfo?.UiName ?? ((object)action).GetType().Name);
			TargetPlan targets = PrepareTargets(action, c.First.Site, actionArgs.TargetFlags, actionArgs.Targets, null, refs);
			Run(inv, services, c, "set_action", delegate(ResolvedTrigger r)
			{
				RequireSameAction(r, index, action);
				ApplyInModel(plan, services, c, "set_action", delegate
				{
					ApplyTargets(action, targets);
				});
				return delegate
				{
					//IL_0072: Unknown result type (might be due to invalid IL or missing references)
					//IL_007c: Expected O, but got Unknown
					JObject obj = AddressJson(r);
					obj["index"] = JToken.op_Implicit(index);
					obj["action"] = (JToken)(object)ActionJson(c.Mod, action, index);
					obj["clamped"] = (JToken)new JArray((object)plan.Clamped);
					AddNoTargetWarning(obj, action, c.First.Site);
					return obj;
				};
			});
		}

		private static void AddNoTargetWarning(JObject res, ModAction action, PummelPartyMcp.Core.CallSite site)
		{
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Expected I4, but got Unknown
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Expected O, but got Unknown
			try
			{
				TargetAction val = (TargetAction)(object)((action is TargetAction) ? action : null);
				if (val != null)
				{
					bool? spawnAtPosition = null;
					if (action is SpawnPrefabAction)
					{
						FieldInfo fieldInfo = GameReflection.FindField(((object)action).GetType(), "m_spawnAtPosition");
						spawnAtPosition = ((fieldInfo == null) ? ((bool?)null) : new bool?((bool)fieldInfo.GetValue(action)));
					}
					int? messageTarget = null;
					if (action is ShowMessageAction)
					{
						FieldInfo fieldInfo2 = GameReflection.FindField(((object)action).GetType(), "m_messageTarget");
						messageTarget = ((fieldInfo2 == null) ? ((int?)null) : new int?(Convert.ToInt32(fieldInfo2.GetValue(action))));
					}
					int resolvedTargetCount = val.TargetReferences?.Count((ModAssetReference<Component> t) => t != null && (Object)(object)t.Asset != (Object)null) ?? 0;
					string text = TargetActionNotes.NoTargetWarning(((object)action).GetType().Name, (int)val.TargetFlags, resolvedTargetCount, spawnAtPosition, messageTarget, site?.SourceName, site?.ReceiverName);
					if (text != null)
					{
						res["warnings"] = (JToken)new JArray((object)text);
					}
				}
			}
			catch (Exception)
			{
			}
		}

		private static Type TriggerClass(string typeName, string modType, out ModTriggerType tt)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected I4, but got Unknown
			tt = (ModTriggerType)0;
			string b = typeName.Trim();
			bool flag = false;
			foreach (ModTriggerType value in Enum.GetValues(typeof(ModTriggerType)))
			{
				Type triggerClassType = ModLogicTrigger.GetTriggerClassType(value);
				if (string.Equals(((object)value/*cast due to .constrained prefix*/).ToString(), b, StringComparison.OrdinalIgnoreCase) || (triggerClassType != null && string.Equals(triggerClassType.Name, b, StringComparison.OrdinalIgnoreCase)))
				{
					tt = (ModTriggerType)(int)value;
					flag = true;
					break;
				}
			}
			if (!flag)
			{
				throw RpcException.InvalidParams("unknown trigger type '" + typeName + "' (see list_trigger_types)");
			}
			string text = LogicTriggerTypes.WhyNotOffered(((object)Unsafe.As<ModTriggerType, ModTriggerType>(ref tt)/*cast due to .constrained prefix*/).ToString(), modType);
			if (text != null)
			{
				throw RpcException.InvalidParams(text);
			}
			return ModLogicTrigger.GetTriggerClassType(tt);
		}

		private static void AddTrigger(WriteInvocation inv, EditServices services)
		{
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Invalid comparison between Unknown and I4
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			TriggerArgs a = inv.ArgsAs<TriggerArgs>();
			EditorSystem ed = EditorAccess.RequireEditor();
			EditContext.RequireEditReady(ed);
			PummelMod mod = ed.CurrentMod;
			ModTransform val = EditContext.RequireEditable(ed, a.Guid);
			List<ModLogic> list = (from l in EditorAccess.ModComponents(((Component)val).gameObject).OfType<ModLogic>()
				where ActionModel.MatchesComponent((ModBehaviour)(object)l, a.Component)
				select l).ToList();
			if (list.Count == 0)
			{
				throw RpcException.NotFound("'" + ((Object)val).name + "' has no Logic component" + ((a.Component != null) ? (" matching '" + a.Component + "'") : "") + "; triggers can only be added to a Logic component (add one with add_component type Logic)");
			}
			if (list.Count > 1)
			{
				throw RpcException.InvalidParams("'" + ((Object)val).name + "' has several Logic components; pass 'component' (" + string.Join(", ", list.Select(EditorAccess.GuidOf).ToArray()) + ")");
			}
			ModLogic logic = list[0];
			if ((Object)(object)((Component)val).GetComponent<ModPrefabInstance>() != (Object)null)
			{
				throw RpcException.InvalidParams("the inspector shows only Transform and Prefab Instance on a prefab instance; edit the prefab instead");
			}
			TriggerClass(a.Type, ((object)mod.ModType/*cast due to .constrained prefix*/).ToString(), out var tt);
			ModLogicTrigger trigger = (ModLogicTrigger)(((int)tt != 32) ? ((object)((ModLogicTrigger)new StartTrigger()).CreateInstance(tt)) : ((object)new StartTrigger()));
			ReferenceResolver refs = new ReferenceResolver(ed, (Component)(object)logic);
			ParamPlan plan = ActionParams.Prepare(trigger, a.Parameters, refs, $"{tt} trigger");
			plan.ApplyAll();
			int count = logic.Triggers.Length;
			TriggerAddress address = new TriggerAddress
			{
				Guid = a.Guid,
				Component = EditorAccess.GuidOf((ModBehaviour)(object)logic),
				Trigger = $"Triggers[{count}]"
			};
			SlotName.TryParse(address.Trigger, out address.Slot);
			EditHost host = new EditHost(ed, ((Component)val).gameObject);
			EditCommon.Run(services, inv, host, selectFirst: true, delegate
			{
				if ((Object)(object)logic == (Object)null)
				{
					throw RpcException.NotFound("the Logic component was removed meanwhile");
				}
				ModLogicTrigger[] triggers = logic.Triggers;
				if (triggers.Length != count)
				{
					throw new RpcException("INVALID_STATE", "the trigger list changed while the edit was waiting for the editor; nothing was changed");
				}
				services.Observe();
				List<ModLogicTrigger> list2 = new List<ModLogicTrigger>(triggers) { trigger };
				logic.Triggers = list2.ToArray();
				bool changed = EditCommon.SnapshotChanged(host);
				services.MarkEditIfChanged(mod, "add_trigger", changed);
				return new EditOutcome
				{
					Changed = changed,
					Then = PostEditWait.AwaitPush,
					BuildResult = delegate(EditReport report)
					{
						//IL_0059: Unknown result type (might be due to invalid IL or missing references)
						//IL_0063: Expected O, but got Unknown
						ResolvedTrigger r = ActionModel.Resolve(ed, mod, address, forWrite: false);
						JObject obj = ActionTools.Entry(new ValueConverter(mod, summarizeTriggers: false, 12), r);
						obj["guid"] = JToken.op_Implicit(a.Guid);
						obj["clamped"] = (JToken)new JArray((object)plan.Clamped);
						return EditCommon.WithEditFields(obj, ed, report, EditCommon.Undoable(report));
					}
				};
			});
		}

		private static void RemoveTrigger(WriteInvocation inv, EditServices services)
		{
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			TriggerArgs triggerArgs = inv.ArgsAs<TriggerArgs>();
			Ctx ctx = Begin(triggerArgs.Address);
			if (ctx.First.IsNested || ctx.First.Slot == null || !ctx.First.Slot.IsLogicList)
			{
				throw RpcException.InvalidParams("'" + triggerArgs.Address.Describe() + "' is a fixed trigger slot; only the triggers of a Logic component (Triggers[i]) can be removed (remove its actions with remove_action)");
			}
			ModLogicTrigger target = ctx.First.Trigger;
			int index = ctx.First.Slot.Index;
			string type = ((object)target.TriggerType/*cast due to .constrained prefix*/).ToString();
			int actionCount = ActionsOf(ctx.First).Length;
			Run(inv, services, ctx, "remove_trigger", delegate(ResolvedTrigger r)
			{
				//IL_0047: Unknown result type (might be due to invalid IL or missing references)
				//IL_0051: Expected O, but got Unknown
				if (r.Trigger != target)
				{
					throw new RpcException("INVALID_STATE", "the trigger list changed while the edit was waiting for the editor; nothing was changed");
				}
				ModLogic logic = (ModLogic)r.Slot.Component;
				List<ModLogicTrigger> list = new List<ModLogicTrigger>(logic.Triggers);
				list.Remove(target);
				logic.Triggers = list.ToArray();
				return delegate
				{
					//IL_0011: Unknown result type (might be due to invalid IL or missing references)
					//IL_0016: Unknown result type (might be due to invalid IL or missing references)
					//IL_0031: Unknown result type (might be due to invalid IL or missing references)
					//IL_0051: Expected O, but got Unknown
					JObject obj = AddressJson(r);
					obj["removed"] = (JToken)new JObject
					{
						["triggerType"] = JToken.op_Implicit(type),
						["actionCount"] = JToken.op_Implicit(actionCount)
					};
					obj["triggerCount"] = JToken.op_Implicit(logic.Triggers.Length);
					obj["indexNote"] = JToken.op_Implicit($"the following triggers moved up by one (Triggers[{index + 1}] is now Triggers[{index}], ...)");
					return obj;
				};
			});
		}

		private static void SetTrigger(WriteInvocation inv, EditServices services)
		{
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			TriggerArgs triggerArgs = inv.ArgsAs<TriggerArgs>();
			Ctx c = Begin(triggerArgs.Address);
			ModLogicTrigger original = c.First.Trigger;
			ModLogicTrigger subject = original;
			bool typeChange = false;
			if (triggerArgs.Type != null)
			{
				if (c.First.IsNested || c.First.Slot == null || !c.First.Slot.IsLogicList)
				{
					throw RpcException.InvalidParams("'" + triggerArgs.Address.Describe() + "' is a fixed trigger slot; its type cannot be changed (only Logic component triggers have an Event dropdown)");
				}
				TriggerClass(triggerArgs.Type, ((object)c.Mod.ModType/*cast due to .constrained prefix*/).ToString(), out var tt);
				if (tt != original.TriggerType)
				{
					subject = original.CreateInstance(tt);
					subject.Actions = original.Actions;
					typeChange = true;
				}
			}
			ReferenceResolver refs = Refs(c, c.First);
			ParamPlan plan = ActionParams.Prepare(subject, triggerArgs.Parameters, refs, $"{subject.TriggerType} trigger");
			if (typeChange)
			{
				plan.ApplyAll();
			}
			string oldType = ((object)original.TriggerType/*cast due to .constrained prefix*/).ToString();
			Run(inv, services, c, "set_trigger", delegate(ResolvedTrigger r)
			{
				if (r.Trigger != original)
				{
					throw new RpcException("INVALID_STATE", "the trigger changed while the edit was waiting for the editor; nothing was changed");
				}
				if (typeChange)
				{
					subject.Actions = original.Actions;
					ActionModel.ReplaceLogicTrigger(r, subject);
				}
				else
				{
					ApplyInModel(plan, services, c, "set_trigger", null);
				}
				return delegate
				{
					//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
					//IL_00b3: Expected O, but got Unknown
					JObject val = ActionTools.Entry(new ValueConverter(c.Mod, summarizeTriggers: false, 12), r);
					if (!r.Address.IsPlayerSettings)
					{
						val["guid"] = JToken.op_Implicit(r.Address.Guid);
					}
					if (typeChange)
					{
						val["previousTriggerType"] = JToken.op_Implicit(oldType);
						val["note"] = JToken.op_Implicit("changing the type keeps the actions and resets the trigger parameters to the new type's defaults, as the Logic inspector does");
					}
					val["clamped"] = (JToken)new JArray((object)plan.Clamped);
					return val;
				};
			});
		}
	}
	internal static class ActionTools
	{
		public static void Register(ToolRegistry registry)
		{
			registry.Register(ToolDefinition.Read("get_action_graph", delegate(ToolContext ctx)
			{
				TriggerAddress scope = ParseScopeOnly(ctx);
				return ctx.OnMainThread(() => GetActionGraph(scope));
			}));
			registry.Register(ToolDefinition.Read("list_action_types", delegate(ToolContext ctx)
			{
				TriggerAddress addr = null;
				if (ctx.Params["guid"] != null || ctx.Params["trigger"] != null || ctx.Params["scope"] != null || ctx.Params["component"] != null || ctx.Params["path"] != null)
				{
					addr = TriggerAddress.Parse(ctx.Params, EditorAccess.NormalizeGuid);
				}
				return ctx.OnMainThread(() => ListActionTypes(addr));
			}));
			registry.Register(ToolDefinition.Read("list_trigger_types", (ToolContext ctx) => ctx.OnMainThread(ListTriggerTypes)));
		}

		private static TriggerAddress ParseScopeOnly(ToolContext ctx)
		{
			if (ctx.Params["trigger"] != null || ctx.Params["path"] != null)
			{
				throw RpcException.InvalidParams("get_action_graph takes guid (+ component) or scope \"playerSettings\"; it lists all triggers");
			}
			return TriggerAddress.Parse(ctx.Params, EditorAccess.NormalizeGuid, requireTrigger: false);
		}

		private static JArray GetActionGraph(TriggerAddress scope)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			EditorSystem ed = EditorAccess.RequireEditor();
			PummelMod mod = EditorAccess.RequireLoadedMod(ed);
			PlaytestAccess.RequireEditMode(ed, "get_action_graph");
			ValueConverter conv = new ValueConverter(mod, summarizeTriggers: false, 12);
			JArray val = new JArray();
			if (scope.IsPlayerSettings)
			{
				string[] playerSettingTriggers = CallSites.PlayerSettingTriggers;
				foreach (string text in playerSettingTriggers)
				{
					TriggerAddress triggerAddress = new TriggerAddress
					{
						Scope = "playerSettings",
						Trigger = text
					};
					SlotName.TryParse(text, out triggerAddress.Slot);
					ResolvedTrigger r = ActionModel.Resolve(ed, mod, triggerAddress, forWrite: false);
					val.Add((JToken)(object)Entry(conv, r));
				}
				return val;
			}
			Transform foundUnderRoot;
			ModTransform obj = EditorAccess.FindByGuid(ed, scope.Guid, out foundUnderRoot) ?? throw RpcException.NotFound("no object with guid " + scope.Guid);
			bool flag = scope.Component == null;
			foreach (ModBehaviour item in EditorAccess.ModComponents(((Component)obj).gameObject))
			{
				if (!ActionModel.MatchesComponent(item, scope.Component))
				{
					continue;
				}
				flag = true;
				foreach (TriggerSlot item2 in ActionModel.Slots(item))
				{
					val.Add((JToken)(object)SlotEntry(conv, item2));
				}
			}
			if (!flag)
			{
				throw RpcException.NotFound("object " + scope.Guid + " has no component matching '" + scope.Component + "'");
			}
			return val;
		}

		internal static JObject SlotEntry(ValueConverter conv, TriggerSlot slot)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			JObject val = new JObject
			{
				["component"] = JToken.op_Implicit(slot.Reflected.name),
				["componentGuid"] = JToken.op_Implicit(EditorAccess.GuidOf(slot.Component)),
				["triggerName"] = JToken.op_Implicit(slot.Name)
			};
			AddTrigger(conv, val, slot.Trigger);
			string text = ActionModel.WhySlotHidden(slot);
			val["callSite"] = (JToken)(object)ActionModel.SiteFor(slot).ToJson();
			val["editable"] = JToken.op_Implicit(text == null);
			if (text != null)
			{
				val["reason"] = JToken.op_Implicit(text);
			}
			return val;
		}

		internal static JObject Entry(ValueConverter conv, ResolvedTrigger r)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Expected O, but got Unknown
			if (r.Slot != null && !r.IsNested)
			{
				return SlotEntry(conv, r.Slot);
			}
			JObject val = new JObject();
			if (r.Address.IsPlayerSettings)
			{
				val["scope"] = JToken.op_Implicit("playerSettings");
				val["component"] = null;
				val["componentGuid"] = null;
			}
			else
			{
				val["component"] = JToken.op_Implicit(r.Slot.Reflected.name);
				val["componentGuid"] = JToken.op_Implicit(EditorAccess.GuidOf(r.Slot.Component));
			}
			val["triggerName"] = JToken.op_Implicit(r.Address.Trigger);
			if (r.IsNested)
			{
				val["path"] = (JToken)new JArray((object)((IEnumerable<TriggerPathStep>)r.Address.Path).Select((Func<TriggerPathStep, JObject>)((TriggerPathStep s) => new JObject
				{
					["action"] = JToken.op_Implicit(s.Action),
					["choice"] = JToken.op_Implicit(s.Choice)
				})));
			}
			AddTrigger(conv, val, r.Trigger);
			val["callSite"] = (JToken)(object)r.Site.ToJson();
			val["editable"] = JToken.op_Implicit(r.NotEditable == null);
			if (r.NotEditable != null)
			{
				val["reason"] = JToken.op_Implicit(r.NotEditable);
			}
			return val;
		}

		private static void AddTrigger(ValueConverter conv, JObject entry, ModLogicTrigger trigger)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			if (trigger == null)
			{
				entry["triggerType"] = null;
				entry["actions"] = (JToken)new JArray();
				return;
			}
			JObject val = (JObject)conv.Trigger(trigger, 0);
			entry["triggerType"] = val["triggerType"];
			entry["triggerClass"] = val["triggerClass"];
			entry["triggerParameters"] = val["triggerParameters"];
			entry["actions"] = val["actions"];
		}

		private static JObject ListActionTypes(TriggerAddress addr)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Expected O, but got Unknown
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Expected I4, but got Unknown
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Expected O, but got Unknown
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Invalid comparison between Unknown and I4
			//IL_0162: Expected O, but got Unknown
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Expected O, but got Unknown
			//IL_0402: Unknown result type (might be due to invalid IL or missing references)
			//IL_0407: Unknown result type (might be due to invalid IL or missing references)
			//IL_040e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0413: Unknown result type (might be due to invalid IL or missing references)
			//IL_042e: Expected O, but got Unknown
			//IL_0454: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Expected I4, but got Unknown
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			//IL_025a: Expected O, but got Unknown
			//IL_02e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02eb: Expected O, but got Unknown
			//IL_033e: Unknown result type (might be due to invalid IL or missing references)
			EditorSystem val = EditorAccess.RequireEditor();
			PummelMod val2 = EditorAccess.RequireLoadedMod(val);
			if (addr != null)
			{
				PlaytestAccess.RequireEditMode(val, "list_action_types with a trigger address");
			}
			ResolvedTrigger resolvedTrigger = ((addr != null) ? ActionModel.Resolve(val, val2, addr, forWrite: false) : null);
			PummelPartyMcp.Core.CallSite callSite = resolvedTrigger?.Site;
			ValueConverter conv = new ValueConverter(val2, summarizeTriggers: false, 12);
			JArray val3 = new JArray();
			foreach (ActionTypeInfo item in ActionModel.ActionTypes())
			{
				ModAction val4 = (ModAction)Activator.CreateInstance(item.ClassType);
				JObject val5 = new JObject
				{
					["type"] = JToken.op_Implicit(item.EnumName),
					["value"] = JToken.op_Implicit(item.EnumValue),
					["className"] = JToken.op_Implicit(item.ClassType.Name),
					["uiName"] = JToken.op_Implicit(item.UiName),
					["category"] = JToken.op_Implicit(ActionModel.CategoryName(item.Meta.Category)),
					["helpText"] = JToken.op_Implicit(item.Meta.HelpText)
				};
				object[] array = PaletteGates.ModTypeNames((int)item.Meta.ModTypes);
				val5["modTypes"] = (JToken)new JArray(array);
				val5["boardSpaceOnly"] = JToken.op_Implicit((item.Meta.UsageFlags & 2) > 0);
				JObject val6 = val5;
				JArray val7 = new JArray();
				FieldInfo[] array2 = ActionParams.Fields(item.ClassType);
				foreach (FieldInfo f in array2)
				{
					val7.Add((JToken)(object)ActionParams.Describe(item.ClassType, f, val4, conv));
				}
				val6["parameters"] = (JToken)(object)val7;
				TargetAction val8 = (TargetAction)(object)((val4 is TargetAction) ? val4 : null);
				if (val8 != null)
				{
					bool[] hideAction = ActionModel.HideFlags(val8);
					val6["supportsTargets"] = JToken.op_Implicit(true);
					val6["defaultTargetFlags"] = JToken.op_Implicit(TargetBits.Format((int)val8.TargetFlags));
					val6["hiddenTargetFlags"] = (JToken)new JArray((object)(from num in Enumerable.Range(0, 3)
						where hideAction.Length > num && hideAction[num]
						select TargetBits.Names[num]));
					val6["targetType"] = JToken.op_Implicit(ActionModel.AcceptedTargetType(val8).Name);
					if (callSite != null)
					{
						bool[] hidden = TargetFlagRules.Hidden(hideAction, callSite.HideSource);
						val6["availableTargetFlags"] = (JToken)new JArray((object)(from num in Enumerable.Range(0, 3)
							where !hidden[num]
							select TargetBits.Names[num]));
						val6["targetFlagsLocked"] = JToken.op_Implicit(hidden.Count((bool b) => b) >= 2);
						val6["appendTargetFlags"] = JToken.op_Implicit(TargetBits.Format((callSite.DefaultTargets != 0) ? callSite.DefaultTargets : ((int)val8.TargetFlags)));
					}
				}
				else
				{
					val6["supportsTargets"] = JToken.op_Implicit(false);
					val6["defaultTargetFlags"] = null;
				}
				string text = TargetActionNotes.RowNote(item.ClassType.Name);
				if (text != null)
				{
					val6["note"] = JToken.op_Implicit(text);
				}
				string text2 = ActionModel.WhyNotUsable(item, val2, callSite);
				val6["usableHere"] = JToken.op_Implicit(text2 == null);
				if (text2 != null)
				{
					val6["reason"] = JToken.op_Implicit(text2);
				}
				val3.Add((JToken)(object)val6);
			}
			JObject val9 = new JObject { ["modType"] = JToken.op_Implicit(((object)val2.ModType/*cast due to .constrained prefix*/).ToString()) };
			if (resolvedTrigger != null)
			{
				val9["trigger"] = (JToken)(object)Entry(conv, resolvedTrigger);
			}
			val9["actionTypes"] = (JToken)(object)val3;
			if ((int)val.State != 0)
			{
				val9["playMode"] = JToken.op_Implicit(true);
			}
			return val9;
		}

		private static JObject ListTriggerTypes()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Expected O, but got Unknown
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Expected O, but got Unknown
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Expected I4, but got Unknown
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Invalid comparison between Unknown and I4
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Invalid comparison between Unknown and I4
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Expected O, but got Unknown
			EditorSystem val = EditorAccess.RequireEditor();
			PummelMod obj = EditorAccess.RequireLoadedMod(val);
			string text = ((object)obj.ModType/*cast due to .constrained prefix*/).ToString();
			ValueConverter conv = new ValueConverter(obj, summarizeTriggers: false, 12);
			JArray val2 = new JArray();
			foreach (ModTriggerType value in Enum.GetValues(typeof(ModTriggerType)))
			{
				Type triggerClassType = ModLogicTrigger.GetTriggerClassType(value);
				if (!(triggerClassType == null))
				{
					object fresh = Activator.CreateInstance(triggerClassType);
					JArray val4 = new JArray();
					FieldInfo[] array = ActionParams.Fields(triggerClassType);
					foreach (FieldInfo f in array)
					{
						val4.Add((JToken)(object)ActionParams.Describe(triggerClassType, f, fresh, conv));
					}
					string text2 = LogicTriggerTypes.WhyNotOffered(((object)value/*cast due to .constrained prefix*/).ToString(), text);
					JObject val5 = new JObject
					{
						["type"] = JToken.op_Implicit(((object)value/*cast due to .constrained prefix*/).ToString()),
						["value"] = JToken.op_Implicit((int)value),
						["className"] = JToken.op_Implicit(triggerClassType.Name),
						["parameters"] = (JToken)(object)val4,
						["sourceTargetAvailable"] = JToken.op_Implicit((int)value == 64 || (int)value == 80),
						["addable"] = JToken.op_Implicit(text2 == null)
					};
					if (text2 != null)
					{
						val5["reason"] = JToken.op_Implicit(text2);
					}
					val2.Add((JToken)(object)val5);
				}
			}
			JObject val6 = new JObject
			{
				["modType"] = JToken.op_Implicit(text),
				["triggerTypes"] = (JToken)(object)val2
			};
			if ((int)val.State != 0)
			{
				val6["playMode"] = JToken.op_Implicit(true);
			}
			return val6;
		}
	}
	internal static class AssetImportTools
	{
		private sealed class ImportArgs
		{
			public string Path;

			public string Name;

			public AssetImportKind? Type;

			public string TypeText;
		}

		private sealed class SettingsArgs
		{
			public string Guid;

			public JObject Values;
		}

		private sealed class CreateMaterialArgs
		{
			public string Name;

			public string Shader;

			public JObject Properties;
		}

		private sealed class SetMaterialArgs
		{
			public string Guid;

			public string Shader;

			public JObject Properties;
		}

		private sealed class RemoveArgs
		{
			public string Guid;

			public bool Force;
		}

		private sealed class Ready
		{
			public EditorSystem Ed;

			public PummelMod Mod;

			public string AssetsFull;

			public string Root => AssetImportRules.ModRootOf(AssetsFull);
		}

		public static readonly TimeSpan ImportTimeout = CommitBudgets.ImportTimeout;

		public static readonly TimeSpan EditTimeout = CommitBudgets.AssetEditTimeout;

		public static void Register(ToolRegistry registry, EditServices services, Func<AssetLimits> limits)
		{
			registry.Register(ToolDefinition.Read("get_asset", delegate(ToolContext ctx)
			{
				string guid = EditorAccess.NormalizeGuid(ctx.GetString("guid", required: true), "guid");
				return ctx.OnMainThread(() => GetAsset(guid, limits()));
			}));
			registry.Register(ToolDefinition.Read("list_asset_rules", (ToolContext ctx) => ctx.OnMainThread(() => ListRules(limits()))));
			registry.Register(ToolDefinition.Write("import_asset", WriteGuard.OpenMod(), ParseImport, delegate(WriteInvocation inv)
			{
				Import(inv, services, limits);
			}, ImportTimeout));
			registry.Register(ToolDefinition.Write("set_import_settings", WriteGuard.OpenMod(), ParseSettings, delegate(WriteInvocation inv)
			{
				SetImportSettings(inv, services);
			}, EditTimeout));
			registry.Register(ToolDefinition.Write("create_material", WriteGuard.OpenMod(), ParseCreateMaterial, delegate(WriteInvocation inv)
			{
				CreateMaterial(inv, services);
			}, EditTimeout));
			registry.Register(ToolDefinition.Write("set_material", WriteGuard.OpenMod(), ParseSetMaterial, delegate(WriteInvocation inv)
			{
				SetMaterial(inv, services);
			}, EditTimeout));
			registry.Register(ToolDefinition.Write("remove_asset", WriteGuard.OpenMod(), ParseRemove, delegate(WriteInvocation inv)
			{
				Remove(inv, services);
			}, EditTimeout));
		}

		private static ImportArgs ParseImport(ToolContext ctx)
		{
			string text = ctx.GetString("path", required: true);
			string text2 = AssetImportRules.CheckSourcePathText(text);
			if (text2 != null)
			{
				throw RpcException.InvalidParams(text2);
			}
			string text3 = ctx.GetString("name");
			if (text3 != null)
			{
				string text4 = AssetImportRules.ValidateName(text3);
				if (text4 != null)
				{
					throw RpcException.InvalidParams("'name' " + text4);
				}
			}
			AssetImportKind? type = null;
			string text5 = ctx.GetString("type");
			if (text5 != null)
			{
				switch (text5.ToLowerInvariant())
				{
				case "texture":
					type = AssetImportKind.Texture;
					break;
				case "prop":
				case "mesh":
					type = AssetImportKind.Mesh;
					break;
				case "audio":
				case "audioclip":
					type = AssetImportKind.Audio;
					break;
				default:
					throw RpcException.InvalidParams("'type' must be Texture, Prop (Mesh) or AudioClip (Audio); it is optional and only checked against the file");
				}
			}
			return new ImportArgs
			{
				Path = text,
				Name = text3,
				Type = type,
				TypeText = text5
			};
		}

		private static SettingsArgs ParseSettings(ToolContext ctx)
		{
			string guid = EditorAccess.NormalizeGuid(ctx.GetString("guid", required: true), "guid");
			JToken obj = ctx.Params["values"];
			JObject val = (JObject)(object)((obj is JObject) ? obj : null);
			if (val == null || ((JContainer)val).Count == 0)
			{
				throw RpcException.InvalidParams("'values' must be an object {field: value, ...} with at least one field (list_asset_rules / get_asset show the fields)");
			}
			return new SettingsArgs
			{
				Guid = guid,
				Values = val
			};
		}

		private static string OptionalNameCheck(string name)
		{
			if (name == null)
			{
				return null;
			}
			string text = AssetImportRules.ValidateName(name);
			if (text != null)
			{
				throw RpcException.InvalidParams("'name' " + text);
			}
			return name;
		}

		private static JObject OptionalProperties(ToolContext ctx)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Invalid comparison between Unknown and I4
			JToken val = ctx.Params["properties"];
			if (val == null || (int)val.Type == 10)
			{
				return null;
			}
			JObject val2 = (JObject)(object)((val is JObject) ? val : null);
			if (val2 == null || ((JContainer)val2).Count == 0)
			{
				throw RpcException.InvalidParams("'properties' must be an object {property: value, ...} (list_asset_rules shows the properties per shader)");
			}
			return val2;
		}

		private static CreateMaterialArgs ParseCreateMaterial(ToolContext ctx)
		{
			return new CreateMaterialArgs
			{
				Name = OptionalNameCheck(ctx.GetString("name")),
				Shader = ctx.GetString("shader"),
				Properties = OptionalProperties(ctx)
			};
		}

		private static SetMaterialArgs ParseSetMaterial(ToolContext ctx)
		{
			SetMaterialArgs setMaterialArgs = new SetMaterialArgs
			{
				Guid = EditorAccess.NormalizeGuid(ctx.GetString("guid", required: true), "guid"),
				Shader = ctx.GetString("shader"),
				Properties = OptionalProperties(ctx)
			};
			if (setMaterialArgs.Shader == null && setMaterialArgs.Properties == null)
			{
				throw RpcException.InvalidParams("give 'shader' and/or 'properties'");
			}
			return setMaterialArgs;
		}

		private static RemoveArgs ParseRemove(ToolContext ctx)
		{
			return new RemoveArgs
			{
				Guid = EditorAccess.NormalizeGuid(ctx.GetString("guid", required: true), "guid"),
				Force = ctx.GetBool("force", defaultValue: false)
			};
		}

		private static Ready RequireReady(bool noPrefab)
		{
			EditorSystem val = EditorAccess.RequireEditor();
			PummelMod mod = EditorAccess.RequireLoadedMod(val);
			EditContext.RequireEditReady(val);
			if (noPrefab && val.CurrentPrefab != null)
			{
				throw new RpcException("INVALID_STATE", "a prefab ('" + ((ModAsset)val.CurrentPrefab).name + "') is being edited; call close_prefab first (or use Return to Hierarchy in the editor)");
			}
			return new Ready
			{
				Ed = val,
				Mod = mod,
				AssetsFull = AssetAccess.AssetsFolderOf(mod)
			};
		}

		private static ModAssetExternal RequireOwnAsset(Ready r, string guid, string tool)
		{
			ModAsset val = AssetAccess.Find(r.Ed, guid);
			if (val == null)
			{
				throw RpcException.NotFound("no asset with guid " + guid);
			}
			ModAssetExternal val2 = (ModAssetExternal)(object)((val is ModAssetExternal) ? val : null);
			if (val2 == null || ValueConverter.LocationName(val) != "external" || !AssetAccess.InModList(r.Mod, val))
			{
				throw RpcException.InvalidParams("'" + val.name + "' is a " + ValueConverter.LocationName(val) + " asset; " + tool + " only acts on the open sandbox mod's own custom assets (list_assets location external)");
			}
			if (!AssetImportRules.IsStrictlyUnder(r.AssetsFull, val2.filePath))
			{
				throw RpcException.InvalidParams("'" + val.name + "' is external but its file is not inside the open mod's Assets folder; " + tool + " does not act on it");
			}
			return val2;
		}

		private static string RelOf(Ready r, ModAssetExternal a)
		{
			return AssetAccess.RelativePath(r.AssetsFull, a.filePath);
		}

		private static JObject GetAsset(string guid, AssetLimits limits)
		{
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Expected O, but got Unknown
			//IL_02ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0309: Expected O, but got Unknown
			//IL_0234: Unknown result type (might be due to invalid IL or missing references)
			//IL_0239: Unknown result type (might be due to invalid IL or missing references)
			//IL_0266: Expected O, but got Unknown
			EditorSystem val = EditorAccess.RequireEditor();
			PummelMod mod = EditorAccess.RequireLoadedMod(val);
			PlaytestAccess.RequireEditMode(val, "get_asset");
			ModAsset val2 = AssetAccess.Find(val, guid);
			if (val2 == null || ValueConverter.LocationName(val2) == "runtime")
			{
				throw RpcException.NotFound("no asset with guid " + guid);
			}
			string text = SafeAssetsFolder(mod);
			JObject val3 = AssetAccess.Row(val2, text);
			bool flag = text != null && AssetAccess.IsOwnCustom(mod, val2, text);
			val3["ownCustomAsset"] = JToken.op_Implicit(flag);
			AssetAccess.Kind(val2);
			PummelTexture val4 = (PummelTexture)(object)((val2 is PummelTexture) ? val2 : null);
			if (val4 != null && flag)
			{
				Texture2D unityTexture = val4.UnityTexture;
				if ((Object)(object)unityTexture != (Object)null)
				{
					val3["width"] = JToken.op_Implicit(((Texture)unityTexture).width);
					val3["height"] = JToken.op_Implicit(((Texture)unityTexture).height);
				}
				val3["importSettings"] = (JToken)new JObject
				{
					["compression"] = JToken.op_Implicit(((object)val4.GetCompression()/*cast due to .constrained prefix*/).ToString()),
					["filterMode"] = JToken.op_Implicit(((object)val4.GetFilterMode()/*cast due to .constrained prefix*/).ToString()),
					["wrapMode"] = JToken.op_Implicit(((object)val4.GetWrapMode()/*cast due to .constrained prefix*/).ToString())
				};
				val3["importSettingFields"] = (JToken)(object)ImportSettingRules.ToJson("Texture");
			}
			else
			{
				PummelProp val5 = (PummelProp)(object)((val2 is PummelProp) ? val2 : null);
				if (val5 != null && flag)
				{
					object obj = val5.PropInstance?.mesh;
					if (obj == null)
					{
						PummelMesh meshAsset = val5.MeshAsset;
						obj = ((meshAsset != null) ? meshAsset.Mesh : null);
					}
					Mesh val6 = (Mesh)obj;
					if ((Object)(object)val6 != (Object)null)
					{
						int num = 0;
						for (int i = 0; i < val6.subMeshCount; i++)
						{
							num += (int)(val6.GetIndexCount(i) / 3);
						}
						val3["vertices"] = JToken.op_Implicit(val6.vertexCount);
						val3["triangles"] = JToken.op_Implicit(num);
						val3["subMeshes"] = JToken.op_Implicit(val6.subMeshCount);
					}
					val3["importSettings"] = (JToken)new JObject { ["recalculateNormals"] = JToken.op_Implicit(val5.MeshAsset != null && val5.MeshAsset.RecalculateNormals) };
					val3["importSettingFields"] = (JToken)(object)ImportSettingRules.ToJson("Prop");
				}
				else
				{
					PummelAudioClip val7 = (PummelAudioClip)(object)((val2 is PummelAudioClip) ? val2 : null);
					if (val7 != null && flag)
					{
						AudioClip unityAudioClip = val7.UnityAudioClip;
						if ((Object)(object)unityAudioClip != (Object)null)
						{
							val3["lengthSeconds"] = JToken.op_Implicit(Math.Round(unityAudioClip.length, 3));
							val3["frequency"] = JToken.op_Implicit(unityAudioClip.frequency);
							val3["channels"] = JToken.op_Implicit(unityAudioClip.channels);
						}
						val3["importSettings"] = (JToken)new JObject();
						val3["importSettingsNote"] = JToken.op_Implicit("audio clips have no import settings in the editor");
					}
					else
					{
						PummelMaterial val8 = (PummelMaterial)(object)((val2 is PummelMaterial) ? val2 : null);
						if (val8 != null && flag)
						{
							Material unityMaterial = val8.UnityMaterial;
							if ((Object)(object)unityMaterial != (Object)null && (Object)(object)unityMaterial.shader != (Object)null)
							{
								val3["shader"] = JToken.op_Implicit(((Object)unityMaterial.shader).name);
								ShaderRule shaderRule = MaterialRules.ForShader(((Object)unityMaterial.shader).name);
								val3["knownShader"] = JToken.op_Implicit(shaderRule != null);
								if (shaderRule != null)
								{
									MaterialAccess materialAccess = new MaterialAccess(val, unityMaterial, unityMaterial.shader);
									val3["properties"] = (JToken)(object)materialAccess.Describe();
									JToken obj2 = MaterialRules.RulesJson()[string.Join(" | ", shaderRule.ShaderNames)];
									val3["propertyFields"] = ((obj2 != null) ? obj2[(object)"properties"] : null);
								}
								else
								{
									val3["propertiesNote"] = JToken.op_Implicit("this shader has no known inspector in this plugin; its properties are not exposed (see list_asset_rules)");
								}
							}
						}
						else
						{
							PummelPrefab val9 = (PummelPrefab)(object)((val2 is PummelPrefab) ? val2 : null);
							if (val9 != null && flag)
							{
								val3["isOpen"] = JToken.op_Implicit(val.CurrentPrefab != null && val.CurrentPrefab == val9);
								JObject val10 = PrefabAccess.TreeOf(val9);
								if (val10 != null)
								{
									int num2 = 0;
									Stack<JToken> stack = new Stack<JToken>();
									stack.Push((JToken)(object)val10);
									while (stack.Count > 0)
									{
										JToken obj3 = stack.Pop();
										num2++;
										JObject val11 = (JObject)(object)((obj3 is JObject) ? obj3 : null);
										if (val11 == null)
										{
											continue;
										}
										JToken obj4 = val11["children"];
										JArray val12 = (JArray)(object)((obj4 is JArray) ? obj4 : null);
										if (val12 == null)
										{
											continue;
										}
										foreach (JToken item in val12)
										{
											stack.Push(item);
										}
									}
									val3["objectCount"] = JToken.op_Implicit(num2);
									val3["objects"] = (JToken)(object)val10;
								}
								List<ModPrefabInstance> list = PrefabAccess.SceneInstances(val, val9);
								val3["instanceCount"] = JToken.op_Implicit(list.Count);
								val3["instances"] = (JToken)(object)PrefabAccess.InstancesJson(list);
								val3["note"] = JToken.op_Implicit("objects = the prefab's object tree (guids work with get_object; edit it with open_prefab + the edit tools); instances = Prefab Instance objects in the scene; references (below) also lists spawners, items and actions that use it");
							}
						}
					}
				}
			}
			if (flag)
			{
				string text2 = AssetRemovalRules.Check(Facts(val, val2, text));
				val3["removable"] = JToken.op_Implicit(text2 == null);
				if (text2 != null)
				{
					val3["removableReason"] = JToken.op_Implicit(text2);
				}
			}
			val3["references"] = (JToken)(object)AssetAccess.RefsJson(AssetAccess.FindReferences(val, mod, val2));
			val3["limits"] = (JToken)(object)LimitsJson(limits);
			return val3;
		}

		private static string SafeAssetsFolder(PummelMod mod)
		{
			try
			{
				return AssetAccess.AssetsFolderOf(mod);
			}
			catch (RpcException)
			{
				return null;
			}
		}

		private static JObject LimitsJson(AssetLimits l)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to i