diff --git a/ArchTests/Contracts/CoreGenericSeparationContracts.cs b/ArchTests/Contracts/CoreGenericSeparationContracts.cs new file mode 100644 index 00000000..57b295f1 --- /dev/null +++ b/ArchTests/Contracts/CoreGenericSeparationContracts.cs @@ -0,0 +1,145 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using RimMind.Testing; +using Xunit; + +namespace RimMind.Core.ArchTests.Contracts +{ + /// + /// Architecture guardrails locking in generic-vs-specific separation inside RimMind-Core: + /// no vendor hardcoding outside concrete client adapters, no submodule prompt/tool literals + /// in generic Core infrastructure, and declarative mechanism/provider extension seams. + /// + public sealed class CoreGenericSeparationContracts + { + [Fact] + public void Core_source_maintains_generic_vs_specific_separation_invariants() + { + string sourceRoot = ArchTestExtensions.FindSourceDirectory(); + Assert.True(Directory.Exists(sourceRoot), "RimMind-Core/Source must be discoverable."); + + ContractCaseRunner.Run( + ("no vendor literals outside concrete client adapters and dev harnesses", () => + { + string[] forbiddenVendors = + { + "\"opencode\"", + "\"oc_sk_\"", + "opencode.ai", + "deepseek.com", + "deepseek-flash", + "deepseek-v4", + "siliconflow.cn", + "moonshot.cn", + "grok-" + }; + + var violations = new List(); + foreach (string file in EnumerateCoreSourceFiles(sourceRoot)) + { + string rel = Path.GetRelativePath(sourceRoot, file).Replace('\\', '/'); + if (IsAllowedVendorAdapterPath(rel)) + continue; + + string code = StripComments(File.ReadAllText(file)); + foreach (string literal in forbiddenVendors) + { + if (code.IndexOf(literal, StringComparison.OrdinalIgnoreCase) >= 0) + { + violations.Add($"{rel} contains forbidden vendor literal '{literal}'"); + } + } + } + + Assert.True( + violations.Count == 0, + $"Generic Core code must not hardcode vendor literals:{Environment.NewLine}{string.Join(Environment.NewLine, violations)}"); + }), + ("HttpTransport has zero vendor sniffing and delegates to IHttpRequestDecorator", () => + { + string transportPath = Path.Combine(sourceRoot, "Infrastructure", "Services", "Clients", "HttpTransport.cs"); + string code = StripComments(File.ReadAllText(transportPath)); + Assert.DoesNotContain("opencode", code, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("oc_sk_", code, StringComparison.OrdinalIgnoreCase); + Assert.Contains("IHttpRequestDecorator", code, StringComparison.Ordinal); + }), + ("CoreContextProviders contains zero Storyteller prompt literals", () => + { + string providersPath = Path.Combine(sourceRoot, "Presentation", "Context", "CoreContextProviders.cs"); + string code = StripComments(File.ReadAllText(providersPath)); + Assert.DoesNotContain("You are the RimWorld storyteller AI", code, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Storyteller rules:", code, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("IncidentOutput schema", code, StringComparison.OrdinalIgnoreCase); + }), + ("MechanismToolHandler uses declarative IMechanismAutonomyMetadata instead of hardcoding pawn.work", () => + { + string handlerPath = Path.Combine(sourceRoot, "Infrastructure", "Mechanisms", "MechanismToolHandler.cs"); + string code = StripComments(File.ReadAllText(handlerPath)); + Assert.DoesNotContain("\"pawn.work\"", code, StringComparison.OrdinalIgnoreCase); + Assert.Contains("IMechanismAutonomyMetadata", code, StringComparison.Ordinal); + }), + ("Core lookup and map context builders contain zero hardcoded Actions tool prefixes", () => + { + string[] filesToCheck = + { + Path.Combine(sourceRoot, "Presentation", "Common", "RimMindPawnLookup.cs"), + Path.Combine(sourceRoot, "Presentation", "Agent", "MapContextBuilder.cs"), + Path.Combine(sourceRoot, "Presentation", "Context", "CoreContextProviders.cs") + }; + + var violations = new List(); + foreach (string path in filesToCheck) + { + string code = StripComments(File.ReadAllText(path)); + if (code.IndexOf("actions_", StringComparison.OrdinalIgnoreCase) >= 0) + { + violations.Add(Path.GetRelativePath(sourceRoot, path)); + } + } + + Assert.True( + violations.Count == 0, + $"Core must not hardcode RimMind-Actions tool IDs or prefixes:{Environment.NewLine}{string.Join(Environment.NewLine, violations)}"); + }), + ("RimMindRuntimeGameComponent.NotifyGameStopped uses pure IGameScopedService dispatch without Player2 hardcoding", () => + { + string compPath = Path.Combine(sourceRoot, "Presentation", "Runtime", "RimMindRuntimeGameComponent.cs"); + string code = StripComments(File.ReadAllText(compPath)); + int start = code.IndexOf("internal static void NotifyGameStopped", StringComparison.Ordinal); + Assert.True(start >= 0, "NotifyGameStopped method must exist"); + int nextMethod = code.IndexOf("private static IExtensionRegistry", start, StringComparison.Ordinal); + Assert.True(nextMethod > start, "NotifyGameStopped method boundary must be discoverable"); + string methodBody = code.Substring(start, nextMethod - start); + Assert.DoesNotContain("Player2GameLifecycleService", methodBody, StringComparison.Ordinal); + })); + } + + private static bool IsAllowedVendorAdapterPath(string relativeSlashPath) + { + return relativeSlashPath.StartsWith("Infrastructure/Services/Clients/OpenAI/", StringComparison.OrdinalIgnoreCase) + || relativeSlashPath.StartsWith("Infrastructure/Services/Clients/Player2/", StringComparison.OrdinalIgnoreCase) + || relativeSlashPath.StartsWith("Infrastructure/UI/DebugActions/", StringComparison.OrdinalIgnoreCase); + } + + private static IEnumerable EnumerateCoreSourceFiles(string sourceRoot) + { + return Directory.EnumerateFiles(sourceRoot, "*.cs", SearchOption.AllDirectories) + .Where(path => !path.Split(Path.DirectorySeparatorChar).Any(part => + part.Equals("bin", StringComparison.OrdinalIgnoreCase) || + part.Equals("obj", StringComparison.OrdinalIgnoreCase) || + part.Equals("backup", StringComparison.OrdinalIgnoreCase))); + } + + private static string StripComments(string source) + { + return Regex.Replace( + source, + @"//[^\r\n]*|/\*.*?\*/", + " ", + RegexOptions.Singleline | RegexOptions.CultureInvariant); + } + } +} diff --git a/ArchTests/Contracts/CrossModBoundaryContracts.cs b/ArchTests/Contracts/CrossModBoundaryContracts.cs index 7987f00f..90a28a5c 100644 --- a/ArchTests/Contracts/CrossModBoundaryContracts.cs +++ b/ArchTests/Contracts/CrossModBoundaryContracts.cs @@ -129,6 +129,89 @@ public void Core_production_code_does_not_hardcode_submod_package_ids() .ToArray()); } + [Fact] + public void Downstream_submodules_maintain_generic_vs_specific_separation_boundaries() + { + string root = RepositoryRoot(); + string[] allDependentMods = + { + "RimMind-Actions", + "RimMind-Advisor", + "RimMind-Dialogue", + "RimMind-Memory", + "RimMind-Personality", + "RimMind-Storyteller", + "RimMind-Bridge-RimTalk", + "RimMind-Bridge-RimChat", + "RimMind-Extension-ModelService" + }; + + ContractCaseRunner.Run( + ("no dependent submodule imports RimMind.Infrastructure", () => + { + var pattern = new Regex( + @"^\s*using\s+RimMind\.Infrastructure(?:\.|;)", + RegexOptions.Multiline | RegexOptions.CultureInvariant); + + var violations = allDependentMods + .Select(mod => Path.Combine(root, mod, "Source")) + .Where(Directory.Exists) + .SelectMany(SourceFiles) + .Where(file => pattern.IsMatch(StripCommentsAndStrings(File.ReadAllText(file)))) + .Select(file => Path.GetRelativePath(root, file)) + .OrderBy(path => path, StringComparer.Ordinal) + .ToArray(); + + Assert.True( + violations.Length == 0, + $"Dependent submodules must not import RimMind.Infrastructure:{Environment.NewLine}{string.Join(Environment.NewLine, violations)}"); + }), + ("RimMind-Advisor Perception layer contains zero hardcoded actions_ tool literals", () => + { + string perceptionDir = Path.Combine(root, "RimMind-Advisor", "Source", "Perception"); + if (!Directory.Exists(perceptionDir)) + return; + + var violations = SourceFiles(perceptionDir) + .Where(file => StripCommentsOnly(File.ReadAllText(file)).IndexOf("actions_", StringComparison.OrdinalIgnoreCase) >= 0) + .Select(file => Path.GetRelativePath(root, file)) + .OrderBy(path => path, StringComparer.Ordinal) + .ToArray(); + + Assert.True( + violations.Length == 0, + $"RimMind-Advisor/Source/Perception must not hardcode concrete actions_ tool names:{Environment.NewLine}{string.Join(Environment.NewLine, violations)}"); + }), + ("no dependent submodule bypasses RimMindAPI.Json by importing RimMind.Application.Features.Json", () => + { + var pattern = new Regex( + @"^\s*using\s+RimMind\.Application\.Features\.Json(?:\.|;)", + RegexOptions.Multiline | RegexOptions.CultureInvariant); + + var violations = allDependentMods + .Select(mod => Path.Combine(root, mod, "Source")) + .Where(Directory.Exists) + .SelectMany(SourceFiles) + .Where(file => pattern.IsMatch(StripCommentsAndStrings(File.ReadAllText(file)))) + .Select(file => Path.GetRelativePath(root, file)) + .OrderBy(path => path, StringComparer.Ordinal) + .ToArray(); + + Assert.True( + violations.Length == 0, + $"Dependent submodules must use RimMindAPI.Json instead of importing RimMind.Application.Features.Json directly:{Environment.NewLine}{string.Join(Environment.NewLine, violations)}"); + })); + } + + private static string StripCommentsOnly(string source) + { + return Regex.Replace( + source, + @"//[^\r\n]*|/\*.*?\*/", + " ", + RegexOptions.Singleline | RegexOptions.CultureInvariant); + } + private static void AssertDependentSourceAbsent(string forbiddenPattern) { var pattern = new Regex(forbiddenPattern, RegexOptions.CultureInvariant); diff --git a/IntegrationTests/RimMindCore.Integration.Tests.csproj b/IntegrationTests/RimMindCore.Integration.Tests.csproj index 50361d55..fbf37d40 100644 --- a/IntegrationTests/RimMindCore.Integration.Tests.csproj +++ b/IntegrationTests/RimMindCore.Integration.Tests.csproj @@ -28,6 +28,8 @@ + + diff --git a/Languages/ChineseSimplified/Keyed/RimMind_Core.xml b/Languages/ChineseSimplified/Keyed/RimMind_Core.xml index a36f2c16..b5894424 100644 --- a/Languages/ChineseSimplified/Keyed/RimMind_Core.xml +++ b/Languages/ChineseSimplified/Keyed/RimMind_Core.xml @@ -39,7 +39,7 @@ 按顺序排列的备用 API 节点列表。当主 API 节点请求失败(如 HTTP 503/502/429、超时或空响应)时,RimMind 会在单次请求内自动平滑切换至列表中的下一个可用备用节点,并对故障节点执行 60 秒临时隔离。 + OpenCode Go 备用 + 自定义备用 - 暂未配置备用节点。点击「+ OpenCode Go 备用」或「+ 自定义备用」添加自动容灾保护。 + 暂未配置备用节点。点击「+ 自定义备用」添加自动容灾保护。 强制 JSON 模式(response_format) 向 API 追加 response_format=json_object,强制模型返回 JSON。不支持该参数的本地模型请关闭。 最大 Token 数 diff --git a/Languages/English/Keyed/RimMind_Core.xml b/Languages/English/Keyed/RimMind_Core.xml index baa7a83d..93c8e859 100644 --- a/Languages/English/Keyed/RimMind_Core.xml +++ b/Languages/English/Keyed/RimMind_Core.xml @@ -39,7 +39,7 @@ Ordered failover list of backup API endpoints. When the primary endpoint fails (HTTP 503/502/429, timeout, or empty response), RimMind automatically switches to the next healthy backup node and isolates the failing node for 60s. + OpenCode Go Backup + Custom Backup - No backup nodes configured. Click "+ OpenCode Go Backup" or "+ Custom Backup" to add automatic failover protection. + No backup nodes configured. Click "+ Custom Backup" to add automatic failover protection. Force JSON Mode (response_format) Append response_format=json_object to the API request, forcing the model to return JSON. Disable this for local models that don't support this parameter. Max Tokens diff --git a/Source/Application/Common/Helpers/AIProviderRegistry.cs b/Source/Application/Common/Helpers/AIProviderRegistry.cs index 3db7cbcb..310d4d24 100644 --- a/Source/Application/Common/Helpers/AIProviderRegistry.cs +++ b/Source/Application/Common/Helpers/AIProviderRegistry.cs @@ -8,12 +8,24 @@ namespace RimMind.Application.Common.Helpers { + public sealed record AIProviderPreset( + string Id, + string ProviderId, + string Endpoint, + string ModelName, + string? DisplayLabelKey = null, + string? FallbackLabel = null, + string? HostMatchSubstring = null, + string OwnerModId = RimMindOwnerConsts.CoreModId); + public sealed record AIProviderDescriptor( string ProviderId, bool RequiresApiKey = true, string? SettingsTabId = null, string? DisplayLabelKey = null, - string OwnerModId = RimMindOwnerConsts.CoreModId); + string OwnerModId = RimMindOwnerConsts.CoreModId, + string? DefaultEndpoint = null, + string? DefaultModelName = null); public static class AIProviderRegistry { @@ -21,6 +33,7 @@ public static class AIProviderRegistry private static readonly object SyncRoot = new(); private static readonly Dictionary Descriptors = new(StringComparer.OrdinalIgnoreCase); + private static readonly List Presets = new(); static AIProviderRegistry() { @@ -32,12 +45,15 @@ public static void ResetToDefaults() lock (SyncRoot) { Descriptors.Clear(); + Presets.Clear(); RegisterCoreUnlocked(new AIProviderDescriptor( AIProviders.OpenAI, RequiresApiKey: true, SettingsTabId: null, DisplayLabelKey: "RimMind.Settings.Provider.OpenAI", - OwnerModId: RimMindOwnerConsts.CoreModId)); + OwnerModId: RimMindOwnerConsts.CoreModId, + DefaultEndpoint: "https://api.openai.com/v1", + DefaultModelName: "gpt-4o-mini")); RegisterCoreUnlocked(new AIProviderDescriptor( AIProviders.Player2, RequiresApiKey: false, @@ -47,6 +63,63 @@ public static void ResetToDefaults() } } + public static void RegisterPreset(AIProviderPreset preset) + { + if (preset == null) throw new ArgumentNullException(nameof(preset)); + if (string.IsNullOrWhiteSpace(preset.Id)) + throw new ArgumentException("Preset Id cannot be null or whitespace.", nameof(preset)); + + var normalized = string.IsNullOrWhiteSpace(preset.OwnerModId) + ? preset with { OwnerModId = RimMindOwnerConsts.CoreModId } + : preset; + + lock (SyncRoot) + { + int idx = Presets.FindIndex(p => string.Equals(p.Id, normalized.Id, StringComparison.OrdinalIgnoreCase)); + if (idx >= 0) Presets[idx] = normalized; + else Presets.Add(normalized); + } + } + + public static IReadOnlyList GetPresets(string? providerId = null) + { + lock (SyncRoot) + { + if (string.IsNullOrWhiteSpace(providerId)) + return Presets.ToList(); + return Presets + .Where(p => string.Equals(p.ProviderId, providerId, StringComparison.OrdinalIgnoreCase)) + .ToList(); + } + } + + public static AIProviderPreset? MatchPresetByEndpoint(string? endpoint) + { + if (string.IsNullOrWhiteSpace(endpoint)) return null; + lock (SyncRoot) + { + for (int i = 0; i < Presets.Count; i++) + { + var p = Presets[i]; + if (!string.IsNullOrWhiteSpace(p.HostMatchSubstring) && + endpoint!.IndexOf(p.HostMatchSubstring!, StringComparison.OrdinalIgnoreCase) >= 0) + { + return p; + } + } + return null; + } + } + + public static AIProviderDescriptor? GetDescriptor(string? providerId) + { + if (string.IsNullOrWhiteSpace(providerId)) return null; + lock (SyncRoot) + { + return Descriptors.TryGetValue(providerId!.Trim(), out var descriptor) ? descriptor : null; + } + } + public static void Register(AIProviderDescriptor descriptor) { if (descriptor == null) @@ -98,6 +171,7 @@ public static int UnregisterByOwner(string ownerModId) .ToList(); foreach (var key in keys) Descriptors.Remove(key); + Presets.RemoveAll(p => string.Equals(p.OwnerModId, ownerModId, StringComparison.Ordinal)); return keys.Count; } } diff --git a/Source/Application/Common/Helpers/UnboundedCompletionFence.cs b/Source/Application/Common/Helpers/UnboundedCompletionFence.cs new file mode 100644 index 00000000..84d5ae6f --- /dev/null +++ b/Source/Application/Common/Helpers/UnboundedCompletionFence.cs @@ -0,0 +1,20 @@ +using System.Threading; +using RimMind.Application.Common.Interfaces.Async; + +namespace RimMind.Application.Common.Helpers +{ + /// + /// Shared default completion fence that never cancels and always accepts completions. + /// Replaces duplicated private copies across RequestQueue and ProactiveBehaviorOrchestrator. + /// + public sealed class UnboundedCompletionFence : ICompletionFence + { + public static readonly UnboundedCompletionFence Instance = new UnboundedCompletionFence(); + + private UnboundedCompletionFence() { } + + public CancellationToken CancellationToken => CancellationToken.None; + + public bool TryAcceptCompletion() => true; + } +} diff --git a/Source/Application/Common/Interfaces/Mechanisms/IMechanismMetadata.cs b/Source/Application/Common/Interfaces/Mechanisms/IMechanismMetadata.cs index 2473a2ce..b033da13 100644 --- a/Source/Application/Common/Interfaces/Mechanisms/IMechanismMetadata.cs +++ b/Source/Application/Common/Interfaces/Mechanisms/IMechanismMetadata.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using RimMind.Application.Common.Interfaces.Extension; using RimMind.Application.Common.Models.Mechanisms; +using RimMind.Domain.Agent.Policies; using RimMind.Domain.Enums; namespace RimMind.Application.Common.Interfaces.Mechanisms @@ -15,4 +16,14 @@ public interface IMechanismMetadata : IExtension IReadOnlyList? GetWriteActions(); MechanismRisk GetRiskForOperation(MechanismOperationType operation); } + + /// + /// Optional additive interface allowing mechanisms to declaratively announce the + /// governed by each operation instead of hardcoding mechanism IDs + /// in MechanismToolHandler. + /// + public interface IMechanismAutonomyMetadata : IMechanismMetadata + { + AutonomyDomain? GetAutonomyDomainForOperation(MechanismOperationType operation); + } } diff --git a/Source/Application/Common/Interfaces/Tools/IToolRegistry.cs b/Source/Application/Common/Interfaces/Tools/IToolRegistry.cs index b7c16682..4362f4c5 100644 --- a/Source/Application/Common/Interfaces/Tools/IToolRegistry.cs +++ b/Source/Application/Common/Interfaces/Tools/IToolRegistry.cs @@ -1,6 +1,8 @@ using System.Collections.Generic; +using System.Linq; using RimMind.Application.Common.Models.Agent; using RimMind.Application.Common.Models.Tools; +using RimMind.Application.Features.Tools; namespace RimMind.Application.Common.Interfaces.Tools { @@ -14,4 +16,29 @@ public interface IToolRegistry IReadOnlyList GetHandlersForScope(AgentScopeKind scopeKind); IReadOnlyList GetDefinitionsForScope(AgentScopeKind scopeKind); } + + public static class ToolRegistryScopeExtensions + { + /// + /// Projects tool definitions matching the requested bitmask, + /// optionally applying compact schema projection to cut LLM prompt token bloat. + /// + public static IReadOnlyList GetDefinitionsForScope( + this IToolRegistry? registry, + ToolScope scope, + bool compactSchema = false) + { + if (registry == null || scope == ToolScope.None) + return System.Array.Empty(); + + if (registry is ToolRegistry concrete) + return concrete.GetDefinitionsForScope(scope, compactSchema); + + var matched = registry.GetAllDefinitions() + .Where(d => ToolScopeProjection.MatchesScope(d, scope)); + return compactSchema + ? matched.Select(ToolScopeProjection.CompactDefinition).ToList() + : matched.ToList(); + } + } } diff --git a/Source/Application/Common/Models/Context/ScenarioIds.cs b/Source/Application/Common/Models/Context/ScenarioIds.cs index 839908a2..0d3dc7e3 100644 --- a/Source/Application/Common/Models/Context/ScenarioIds.cs +++ b/Source/Application/Common/Models/Context/ScenarioIds.cs @@ -1,12 +1,25 @@ +using System; + namespace RimMind.Application.Common.Models.Context { public static class ScenarioIds { public const string Dialogue = "Dialogue"; public const string Decision = "Decision"; + public const string AgentDecision = "agent_decision"; + public const string AdvisorDecision = "advisor_decision"; public const string Personality = "Personality"; public const string Storyteller = "Storyteller"; public const string Memory = "Memory"; public const string CrisisDialogue = "CrisisDialogue"; + + /// + /// Returns true for any autonomous/advisor decision scenario whose mutation tool calls + /// must be executed by a main-thread coordinator rather than auto-dispatched on background threads. + /// + public static bool IsDecisionScenario(string? scenarioId) + => string.Equals(scenarioId, Decision, StringComparison.OrdinalIgnoreCase) + || string.Equals(scenarioId, AgentDecision, StringComparison.OrdinalIgnoreCase) + || string.Equals(scenarioId, AdvisorDecision, StringComparison.OrdinalIgnoreCase); } } diff --git a/Source/Application/Common/Models/Debug/AgentRolloutModelBuilder.cs b/Source/Application/Common/Models/Debug/AgentRolloutModelBuilder.cs index 7425b1fe..e5838180 100644 --- a/Source/Application/Common/Models/Debug/AgentRolloutModelBuilder.cs +++ b/Source/Application/Common/Models/Debug/AgentRolloutModelBuilder.cs @@ -278,7 +278,7 @@ private static bool IsRolloutEntry(AIRequestTraceEntry entry) return true; string scenario = ResolveScenarioId(entry); string mod = ResolveModId(entry); - return string.Equals(scenario, "Decision", StringComparison.OrdinalIgnoreCase) + return Context.ScenarioIds.IsDecisionScenario(scenario) || string.Equals(mod, "RimMind.Agent", StringComparison.OrdinalIgnoreCase); } diff --git a/Source/Application/Common/Models/Tools/ToolManifest.cs b/Source/Application/Common/Models/Tools/ToolManifest.cs index d1b4a27d..955b1d81 100644 --- a/Source/Application/Common/Models/Tools/ToolManifest.cs +++ b/Source/Application/Common/Models/Tools/ToolManifest.cs @@ -12,12 +12,26 @@ public enum ToolKind Query = 1 } + [Flags] + public enum ToolScope + { + None = 0, + ColonistSelf = 1 << 0, + ColonyBuild = 1 << 1, + ColonyManage = 1 << 2, + Social = 1 << 3, + WorldAdmin = 1 << 4, + MetaQuery = 1 << 5, + All = ColonistSelf | ColonyBuild | ColonyManage | Social | WorldAdmin | MetaQuery + } + public sealed record ToolManifest { public string OwnerModId { get; init; } = "RimMind.Core"; public IReadOnlyList AllowedScopes { get; init; } = Array.AsReadOnly((AgentScopeKind[])Enum.GetValues(typeof(AgentScopeKind))); public ToolKind Kind { get; init; } = ToolKind.Mutation; + public ToolScope? Scopes { get; init; } public AutonomyDomain? DefaultDomain { get; init; } public string? AutonomyDomainId { get; init; } public RiskLevel RiskLevel { get; init; } = RiskLevel.Medium; diff --git a/Source/Application/Features/Agent/Modes/ProactiveAgentMode.cs b/Source/Application/Features/Agent/Modes/ProactiveAgentMode.cs index 01d40bcb..d0f4049b 100644 --- a/Source/Application/Features/Agent/Modes/ProactiveAgentMode.cs +++ b/Source/Application/Features/Agent/Modes/ProactiveAgentMode.cs @@ -90,14 +90,16 @@ public bool ShouldThink(IAgentInfo agent, IReadOnlyList p public IThinkStrategy GetThinkStrategy() => SharedStrategy; public IReadOnlyList AllowedToolIds(IToolRegistry registry) - => registry.GetAllDefinitions().Select(d => d.Id).ToList(); + => registry.GetDefinitionsForScope(RimMind.Application.Features.Tools.ToolScopeProjection.ColonistAgentDefaultScope) + .Select(d => d.Id) + .ToList(); } internal sealed class ProactiveThinkStrategy : IThinkStrategy { private static readonly List CachedExamples = ThinkStrategyHelper.BuildDecisionExamples(); - public string ScenarioId => ScenarioIds.Decision; + public string ScenarioId => ScenarioIds.AgentDecision; public LlmRequestEnvelope BuildEnvelope(IAgentInfo agent, IReadOnlyList perceptions, diff --git a/Source/Application/Features/Agent/Modes/ReactiveAgentMode.cs b/Source/Application/Features/Agent/Modes/ReactiveAgentMode.cs index e5e00efc..af3a42ba 100644 --- a/Source/Application/Features/Agent/Modes/ReactiveAgentMode.cs +++ b/Source/Application/Features/Agent/Modes/ReactiveAgentMode.cs @@ -38,7 +38,7 @@ public bool ShouldThink(IAgentInfo agent, IReadOnlyList p private static readonly string[] ExcludedToolPrefixes = { "planning.", "dream.", "reflect.", "trait_evolution." }; public IReadOnlyList AllowedToolIds(IToolRegistry registry) - => registry.GetAllDefinitions() + => registry.GetDefinitionsForScope(RimMind.Application.Features.Tools.ToolScopeProjection.ColonistAgentDefaultScope) .Where(d => !ExcludedToolPrefixes.Any(p => d.Id.StartsWith(p))) .Select(d => d.Id) .ToList(); @@ -48,7 +48,7 @@ internal sealed class ReactiveThinkStrategy : IThinkStrategy { private static readonly List CachedExamples = ThinkStrategyHelper.BuildDecisionExamples(); - public string ScenarioId => ScenarioIds.Decision; + public string ScenarioId => ScenarioIds.AgentDecision; public LlmRequestEnvelope BuildEnvelope(IAgentInfo agent, IReadOnlyList perceptions, diff --git a/Source/Application/Features/Agent/Modes/ThinkStrategyHelper.cs b/Source/Application/Features/Agent/Modes/ThinkStrategyHelper.cs index a48fb950..6f9af72d 100644 --- a/Source/Application/Features/Agent/Modes/ThinkStrategyHelper.cs +++ b/Source/Application/Features/Agent/Modes/ThinkStrategyHelper.cs @@ -433,20 +433,12 @@ private static (string? Id, string? Name, string? ArgsJson, string? Reason) TryE if (argsToken.Type == Newtonsoft.Json.Linq.JTokenType.String) { argsJson = argsToken.ToString(); - if (!string.IsNullOrWhiteSpace(argsJson)) - { - try - { - if (Newtonsoft.Json.Linq.JToken.Parse(argsJson!) is Newtonsoft.Json.Linq.JObject parsedArgs) - reason = parsedArgs.Value("reason"); - } - catch { } - } + reason = LlmPayloadParser.ExtractReasonFromArgumentsJson(argsJson); } else if (argsToken is Newtonsoft.Json.Linq.JObject argsObj) { argsJson = argsObj.ToString(Newtonsoft.Json.Formatting.None); - reason = argsObj.Value("reason"); + reason = LlmPayloadParser.ExtractReasonFromObject(argsObj); } } diff --git a/Source/Application/Features/Agent/ProactiveBehaviorOrchestrator.cs b/Source/Application/Features/Agent/ProactiveBehaviorOrchestrator.cs index 09ea3549..1408abe4 100644 --- a/Source/Application/Features/Agent/ProactiveBehaviorOrchestrator.cs +++ b/Source/Application/Features/Agent/ProactiveBehaviorOrchestrator.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using RimMind.Application.Common.Helpers; using RimMind.Application.Common.Interfaces.Async; using RimMind.Application.Common.Interfaces; using RimMind.Application.Common.Interfaces.Abstractions; @@ -231,14 +232,5 @@ public void ExecuteAll(IAgentInfo agent, int currentTick = 0) ExecuteTraitEvolution(agent); ExecuteRegisteredBehaviors(agent, currentTick); } - - private sealed class UnboundedCompletionFence : ICompletionFence - { - public static readonly UnboundedCompletionFence Instance = new UnboundedCompletionFence(); - - public CancellationToken CancellationToken => CancellationToken.None; - - public bool TryAcceptCompletion() => true; - } } } diff --git a/Source/Application/Features/Context/RelevanceTableImpl.cs b/Source/Application/Features/Context/RelevanceTableImpl.cs index ceefca5e..988ddc7e 100644 --- a/Source/Application/Features/Context/RelevanceTableImpl.cs +++ b/Source/Application/Features/Context/RelevanceTableImpl.cs @@ -64,16 +64,21 @@ public void RegisterCoreRelevance() if (_coreRegistered) return; _coreRegistered = true; - RegisterCoreDefaultBatch(ScenarioIds.Decision, new Dictionary + var decisionWeights = new Dictionary { - {"health", 0.9f}, {"mood", 0.8f}, {"current_job", 0.9f}, + {"health", 0.9f}, {"mood", 0.8f}, {"mood_thoughts", 0.7f}, {"current_job", 0.9f}, {"combat_status", 0.95f}, {"target_info", 0.9f}, {"task_progress", 0.85f}, - {"nearby_pawns", 0.7f}, {"colony_status", 0.6f}, {"current_area", 0.5f}, - {"weather", 0.2f}, {"time_of_day", 0.3f}, {"season", 0.1f}, - {"map_structure", 0.3f}, {"pawn_base_info", 0.4f}, {"fixed_relations", 0.5f}, + {"nearby_pawns", 0.7f}, {"colony_status", 0.7f}, {"colony_resources", 0.75f}, {"current_area", 0.5f}, + {"weather", 0.25f}, {"time_of_day", 0.3f}, {"season", 0.15f}, + {"map_structure", 0.45f}, {"pawn_base_info", 0.4f}, {"fixed_relations", 0.5f}, {"ideology", 0.3f}, {"skills_summary", 0.7f}, {"memory_pawn", 0.6f}, - {"working_memory", 0.8f}, {"memory_narrator", 0.2f} - }); + {"working_memory", 0.8f}, {"memory_narrator", 0.2f}, + {"personality_profile", 0.65f}, {"personality_state", 0.65f}, {"personality_shaping", 0.55f}, + {"dialogue_state", 0.55f}, {"dialogue_relation", 0.55f} + }; + RegisterCoreDefaultBatch(ScenarioIds.Decision, decisionWeights); + RegisterCoreDefaultBatch(ScenarioIds.AgentDecision, decisionWeights); + RegisterCoreDefaultBatch(ScenarioIds.AdvisorDecision, decisionWeights); RegisterCoreDefaultBatch(ScenarioIds.Dialogue, new Dictionary { @@ -112,7 +117,7 @@ public void RegisterCoreRelevance() { {"health", 0.3f}, {"mood", 0.4f}, {"current_job", 0.2f}, {"combat_status", 0.8f}, {"target_info", 0.7f}, {"task_progress", 0.3f}, - {"nearby_pawns", 0.5f}, {"colony_status", 0.9f}, {"current_area", 0.4f}, + {"nearby_pawns", 0.5f}, {"colony_status", 0.9f}, {"colony_resources", 0.85f}, {"current_area", 0.4f}, {"weather", 0.6f}, {"time_of_day", 0.5f}, {"season", 0.7f}, {"map_structure", 0.8f}, {"pawn_base_info", 0.3f}, {"fixed_relations", 0.3f}, {"ideology", 0.4f}, {"skills_summary", 0.2f}, {"memory_pawn", 0.3f}, diff --git a/Source/Application/Features/Context/ScenarioRegistry.cs b/Source/Application/Features/Context/ScenarioRegistry.cs index 42590c9d..ed5eb5cd 100644 --- a/Source/Application/Features/Context/ScenarioRegistry.cs +++ b/Source/Application/Features/Context/ScenarioRegistry.cs @@ -240,6 +240,12 @@ public static void RegisterCoreScenarios(ITranslationService? translationService RegisterCoreFallback(ScenarioIds.Decision, 0, Translate(translationService, "RimMind.Application.Scenario.Decision"), defaultBudget: 0.5f, l4Mode: L4Mode.None, defaultExcludeKeys: new string[0], logSink: logSink); + RegisterCoreFallback(ScenarioIds.AgentDecision, 0, Translate(translationService, "RimMind.Application.Scenario.Decision"), + defaultBudget: 0.55f, l4Mode: L4Mode.None, + defaultExcludeKeys: new string[0], logSink: logSink); + RegisterCoreFallback(ScenarioIds.AdvisorDecision, 0, Translate(translationService, "RimMind.Application.Scenario.Decision"), + defaultBudget: 0.6f, l4Mode: L4Mode.None, + defaultExcludeKeys: new string[0], logSink: logSink); RegisterCoreFallback(ScenarioIds.Personality, 3, Translate(translationService, "RimMind.Application.Scenario.Personality"), defaultBudget: 0.4f, l4Mode: L4Mode.MemoryOnly, defaultExcludeKeys: new[] { "combat_status" }, logSink: logSink); diff --git a/Source/Application/Features/Json/LlmPayloadParser.cs b/Source/Application/Features/Json/LlmPayloadParser.cs new file mode 100644 index 00000000..68ca6b08 --- /dev/null +++ b/Source/Application/Features/Json/LlmPayloadParser.cs @@ -0,0 +1,464 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace RimMind.Application.Features.Json +{ + public sealed class ParsedPseudoFunctionCall + { + public string? Id { get; init; } + public string Name { get; init; } = string.Empty; + public string ArgumentsJson { get; init; } = "{}"; + public string? Reason { get; init; } + } + + /// + /// Unified, Verse-free LLM output scrubber, JSON payload extractor/repairer, and pseudo-function-call parser. + /// Shared across Core and all LLM-consuming submodules via RimMindAPI.Json. + /// + public static class LlmPayloadParser + { + private static readonly TimeSpan RegexTimeout = TimeSpan.FromMilliseconds(50); + + private static readonly Regex ThinkingBlockRegex = new Regex( + @"<(?:think|thinking|thought|reasoning)\b[^>]*>[\s\S]*?", + RegexOptions.IgnoreCase | RegexOptions.Compiled, + RegexTimeout); + + private static readonly Regex UnclosedThinkingRegex = new Regex( + @"<(?:think|thinking|thought|reasoning)\b[^>]*>[\s\S]*$", + RegexOptions.IgnoreCase | RegexOptions.Compiled, + RegexTimeout); + + private static readonly Regex CodeFenceRegex = new Regex( + @"```(?:[a-zA-Z0-9_+-]+)?\s*([\s\S]*?)\s*```", + RegexOptions.Compiled, + RegexTimeout); + + private static readonly Regex PseudoFunctionCallRegex = new Regex( + @"\b(?[a-z_][a-z0-9_.]*)\((?[\s\S]+?)\)", + RegexOptions.IgnoreCase | RegexOptions.Compiled, + RegexTimeout); + + private static readonly Regex PseudoFunctionKeyRegex = new Regex( + @"(?:^|,\s*)(?[a-z_][a-z0-9_]*)\)?\s*[:=]\s*", + RegexOptions.IgnoreCase | RegexOptions.Compiled, + RegexTimeout); + + private static readonly Regex ToToolCommentaryRegex = new Regex( + @"\bto=(?:functions\.|tools\.)?(?[a-z_][a-z0-9_.]*)", + RegexOptions.IgnoreCase | RegexOptions.Compiled, + RegexTimeout); + + /// + /// Strips reasoning/thinking tags (<think>...</think>, <thinking>...</thinking>) + /// and unwraps markdown code fences (```` ```json ... ``` ````). + /// + public static string StripThinkingAndCodeFences(string? raw) + { + if (string.IsNullOrWhiteSpace(raw)) + return string.Empty; + + string text = raw!.Trim(); + try + { + text = ThinkingBlockRegex.Replace(text, string.Empty); + text = UnclosedThinkingRegex.Replace(text, string.Empty); + text = text.Trim(); + + var fenceMatch = CodeFenceRegex.Match(text); + if (fenceMatch.Success) + { + text = fenceMatch.Groups[1].Value.Trim(); + } + else + { + if (text.StartsWith("```", StringComparison.Ordinal)) + { + int nl = text.IndexOf('\n'); + text = nl >= 0 ? text.Substring(nl + 1).Trim() : text.Substring(3).Trim(); + } + if (text.EndsWith("```", StringComparison.Ordinal)) + { + text = text.Substring(0, text.Length - 3).Trim(); + } + } + } + catch (RegexMatchTimeoutException) + { + // Return best-effort trimmed input on catastrophic regex timeout. + } + + return text.Trim(); + } + + /// + /// Extracts the first balanced JSON object ({...}) or array ([...]) from raw LLM output, + /// respecting quoted strings and escape sequences. If the payload is truncated before closing, + /// returns the substring from the first opener to the end so callers can repair it. + /// + public static string? ExtractJsonPayload(string? raw) + { + string cleaned = StripThinkingAndCodeFences(raw); + if (string.IsNullOrEmpty(cleaned)) + return null; + + int objStart = cleaned.IndexOf('{'); + int arrStart = cleaned.IndexOf('['); + int start; + char openChar; + char closeChar; + + if (objStart >= 0 && (arrStart < 0 || objStart < arrStart)) + { + start = objStart; + openChar = '{'; + closeChar = '}'; + } + else if (arrStart >= 0) + { + start = arrStart; + openChar = '['; + closeChar = ']'; + } + else + { + return null; + } + + int depth = 0; + bool inString = false; + bool escaped = false; + + for (int i = start; i < cleaned.Length; i++) + { + char c = cleaned[i]; + if (inString) + { + if (escaped) + escaped = false; + else if (c == '\\') + escaped = true; + else if (c == '"') + inString = false; + continue; + } + + if (c == '"') + { + inString = true; + } + else if (c == openChar) + { + depth++; + } + else if (c == closeChar) + { + depth--; + if (depth == 0) + { + return cleaned.Substring(start, i - start + 1); + } + } + } + + // Truncated payload: return from start so JsonRepairer can balance it + return cleaned.Substring(start); + } + + /// + /// Extracts and parses a JSON object from raw LLM output, applying on malformed/truncated JSON. + /// + public static bool TryParseJObjectWithRepair(string? raw, out JObject? obj) + { + obj = null; + string? candidate = ExtractJsonPayload(raw); + if (string.IsNullOrWhiteSpace(candidate)) + return false; + + if (TryParseJObject(candidate!, out obj)) + return true; + + string repaired = JsonRepairer.Repair(candidate!); + return TryParseJObject(repaired, out obj); + } + + /// + /// Extracts and deserializes from raw LLM output, automatically stripping + /// thinking tags/code fences and attempting truncation/trailing-comma repair if direct parsing fails. + /// + public static bool TryDeserializeWithRepair(string? raw, out T? result) where T : class + { + result = null; + string? candidate = ExtractJsonPayload(raw); + if (string.IsNullOrWhiteSpace(candidate)) + return false; + + if (JsonExtractorUtils.TryDeserialize(candidate!, out result) && result != null) + return true; + + string repaired = JsonRepairer.Repair(candidate!); + if (JsonExtractorUtils.TryDeserialize(repaired, out result) && result != null) + return true; + + result = null; + return false; + } + + /// + /// Extracts structured pseudo-function-calls emitted in plain text by LLMs that drop out of + /// native tool calling: raw JSON tool objects ({"name":..., "parameters":...}), + /// tool_name(key=val, ...), and commentary syntax (to=functions.tool_name {...}). + /// + public static IReadOnlyList ParsePseudoFunctionCalls(string? raw) + { + var results = new List(); + if (string.IsNullOrWhiteSpace(raw)) + return results; + + string cleaned = StripThinkingAndCodeFences(raw); + if (string.IsNullOrWhiteSpace(cleaned)) + return results; + + // 1. Raw JSON tool-call object + if (TryParseJObjectWithRepair(cleaned, out var rawObj) && rawObj != null) + { + var fromJson = TryBuildCallFromJObject(rawObj); + if (fromJson != null) + { + results.Add(fromJson); + return results; + } + } + + // 2. Pseudo-function syntax: tool_name(key=val, ...) + try + { + var matches = PseudoFunctionCallRegex.Matches(cleaned); + foreach (Match match in matches) + { + if (!match.Success) continue; + string fnName = match.Groups["fn"].Value; + if (!IsValidToolIdentifier(fnName)) continue; + + string inner = match.Groups["inner"].Value.Trim(); + var jObj = ParseKeyValueInner(inner); + if (jObj != null && jObj.HasValues) + { + results.Add(new ParsedPseudoFunctionCall + { + Name = fnName, + ArgumentsJson = jObj.ToString(Formatting.None), + Reason = ExtractReasonFromObject(jObj) + }); + } + } + } + catch (RegexMatchTimeoutException) + { + // Ignore timeout + } + + if (results.Count > 0) + return results; + + // 3. Commentary syntax: to=functions.tool_name {...} + try + { + var toMatch = ToToolCommentaryRegex.Match(cleaned); + if (toMatch.Success) + { + string fnName = toMatch.Groups["fn"].Value; + if (IsValidToolIdentifier(fnName)) + { + string afterMatch = cleaned.Substring(toMatch.Index + toMatch.Length).Trim(); + string argsJson = "{}"; + string? reason = null; + if (TryParseJObjectWithRepair(afterMatch, out var argObj) && argObj != null) + { + argsJson = argObj.ToString(Formatting.None); + reason = ExtractReasonFromObject(argObj); + } + results.Add(new ParsedPseudoFunctionCall + { + Name = fnName, + ArgumentsJson = argsJson, + Reason = reason + }); + } + } + } + catch (RegexMatchTimeoutException) + { + // Ignore timeout + } + + return results; + } + + /// + /// Extracts a non-empty reason string from a tool arguments JSON object, inspecting top-level + /// reason, nested params.reason, and nested JSON inside value (e.g., + /// {"action":"force_rest","value":"{\"reason\":\"...\"}"}). + /// + public static string? ExtractReasonFromArgumentsJson(string? argumentsJson) + { + if (string.IsNullOrWhiteSpace(argumentsJson)) + return null; + + if (!TryParseJObjectWithRepair(argumentsJson, out var obj) || obj == null) + return null; + + return ExtractReasonFromObject(obj); + } + + internal static string? ExtractReasonFromObject(JObject obj) + { + if (obj == null) return null; + + string? direct = obj.Value("reason"); + if (!string.IsNullOrWhiteSpace(direct)) + return direct!.Trim(); + + if (obj["params"] is JObject paramsObj) + { + string? nested = paramsObj.Value("reason"); + if (!string.IsNullOrWhiteSpace(nested)) + return nested!.Trim(); + } + + var valueTok = obj["value"]; + if (valueTok is JObject valueObj) + { + string? valReason = valueObj.Value("reason"); + if (!string.IsNullOrWhiteSpace(valReason)) + return valReason!.Trim(); + } + else if (valueTok != null && valueTok.Type == JTokenType.String) + { + string valStr = valueTok.Value() ?? string.Empty; + if (valStr.IndexOf('{') >= 0 && TryParseJObjectWithRepair(valStr, out var parsedVal) && parsedVal != null) + { + string? innerReason = parsedVal.Value("reason"); + if (!string.IsNullOrWhiteSpace(innerReason)) + return innerReason!.Trim(); + } + } + + return null; + } + + private static ParsedPseudoFunctionCall? TryBuildCallFromJObject(JObject rawObj) + { + string? rawToolName = rawObj.Value("name") + ?? rawObj.Value("tool") + ?? (rawObj["function"] as JObject)?.Value("name"); + if (string.IsNullOrWhiteSpace(rawToolName) || !IsValidToolIdentifier(rawToolName)) + return null; + + var paramsToken = rawObj["parameters"] + ?? rawObj["arguments"] + ?? rawObj["args"] + ?? rawObj["param"] + ?? (rawObj["function"] as JObject)?["arguments"]; + + string? argsJson = null; + string? reason = ExtractReasonFromObject(rawObj); + + if (paramsToken is JObject paramsObj) + { + argsJson = paramsObj.ToString(Formatting.None); + reason ??= ExtractReasonFromObject(paramsObj); + } + else if (paramsToken != null && paramsToken.Type == JTokenType.String) + { + argsJson = paramsToken.ToString(); + reason ??= ExtractReasonFromArgumentsJson(argsJson); + } + else + { + var copyObj = (JObject)rawObj.DeepClone(); + copyObj.Remove("name"); + copyObj.Remove("tool"); + copyObj.Remove("function"); + copyObj.Remove("id"); + copyObj.Remove("type"); + if (copyObj.HasValues) + argsJson = copyObj.ToString(Formatting.None); + } + + return new ParsedPseudoFunctionCall + { + Id = rawObj.Value("id"), + Name = rawToolName!, + ArgumentsJson = string.IsNullOrWhiteSpace(argsJson) ? "{}" : argsJson!, + Reason = reason + }; + } + + private static JObject? ParseKeyValueInner(string inner) + { + if (string.IsNullOrWhiteSpace(inner)) return null; + var keyMatches = PseudoFunctionKeyRegex.Matches(inner); + if (keyMatches.Count == 0) return null; + + var jObj = new JObject(); + for (int i = 0; i < keyMatches.Count; i++) + { + string key = keyMatches[i].Groups["key"].Value; + int valStart = keyMatches[i].Index + keyMatches[i].Length; + int valEnd = (i + 1 < keyMatches.Count) ? keyMatches[i + 1].Index : inner.Length; + string rawVal = inner.Substring(valStart, valEnd - valStart).Trim(); + if ((rawVal.StartsWith("\"") && rawVal.EndsWith("\"") && rawVal.Length >= 2) || + (rawVal.StartsWith("'") && rawVal.EndsWith("'") && rawVal.Length >= 2) || + (rawVal.StartsWith("\u201C") && rawVal.EndsWith("\u201D") && rawVal.Length >= 2) || + (rawVal.StartsWith("(") && rawVal.EndsWith(")") && rawVal.Length >= 2)) + { + rawVal = rawVal.Substring(1, rawVal.Length - 2).Replace("\\\"", "\""); + } + else if (rawVal.StartsWith("(") && keyMatches[i].Value.IndexOf(')') >= 0) + { + rawVal = rawVal.Substring(1).TrimEnd(')').Trim(); + } + + if (int.TryParse(rawVal, out int intVal)) + jObj[key] = intVal; + else if (bool.TryParse(rawVal, out bool boolVal)) + jObj[key] = boolVal; + else + jObj[key] = rawVal; + } + return jObj; + } + + internal static bool IsValidToolIdentifier(string? fnName) + { + if (string.IsNullOrWhiteSpace(fnName)) return false; + if (fnName!.IndexOf('_') < 0 && fnName.IndexOf('.') < 0) return false; + if (fnName[0] == '.' || fnName[fnName.Length - 1] == '.') return false; + foreach (char c in fnName) + { + if (!(char.IsLetterOrDigit(c) || c == '_' || c == '.')) + return false; + } + return true; + } + + private static bool TryParseJObject(string json, out JObject? obj) + { + obj = null; + try + { + obj = JToken.Parse(json) as JObject; + return obj != null; + } + catch + { + return false; + } + } + } +} diff --git a/Source/Application/Features/Llm/EndpointFailoverPolicy.cs b/Source/Application/Features/Llm/EndpointFailoverPolicy.cs new file mode 100644 index 00000000..e8342126 --- /dev/null +++ b/Source/Application/Features/Llm/EndpointFailoverPolicy.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using RimMind.Domain.ValueObjects; + +namespace RimMind.Application.Features.Llm +{ + /// + /// Reusable thread-safe multi-endpoint failover and circuit-isolation policy. + /// Shared by Core's built-in client and extension model services. + /// + public sealed class EndpointFailoverPolicy + { + public const long DefaultIsolationMs = 180_000L; + public const long DefaultTransientRateLimitIsolationMs = 2_000L; + public const long DefaultPermanentIsolationMs = 1_800_000L; + + private readonly ConcurrentDictionary _isolatedUntilMs = new(StringComparer.OrdinalIgnoreCase); + private readonly ConcurrentDictionary _exhaustedUntilMs = new(StringComparer.OrdinalIgnoreCase); + private readonly Func _clockMs; + private readonly long _defaultIsolationMs; + private readonly long _transientRateLimitIsolationMs; + private readonly long _permanentIsolationMs; + + public EndpointFailoverPolicy( + Func? clockMs = null, + long defaultIsolationMs = DefaultIsolationMs, + long transientRateLimitIsolationMs = DefaultTransientRateLimitIsolationMs, + long permanentIsolationMs = DefaultPermanentIsolationMs) + { + _clockMs = clockMs ?? (() => DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); + _defaultIsolationMs = defaultIsolationMs; + _transientRateLimitIsolationMs = transientRateLimitIsolationMs; + _permanentIsolationMs = permanentIsolationMs; + } + + public bool IsIsolated(string nodeKey, long? nowMs = null) + { + if (string.IsNullOrEmpty(nodeKey)) return false; + long now = nowMs ?? _clockMs(); + return _isolatedUntilMs.TryGetValue(nodeKey, out long untilMs) && now < untilMs; + } + + public bool IsPermanentlyExhausted(string nodeKey, long? nowMs = null) + { + if (string.IsNullOrEmpty(nodeKey)) return false; + long now = nowMs ?? _clockMs(); + return _exhaustedUntilMs.TryGetValue(nodeKey, out long untilMs) && now < untilMs; + } + + public void RecordSuccess(string nodeKey) + { + if (string.IsNullOrEmpty(nodeKey)) return; + _isolatedUntilMs.TryRemove(nodeKey, out _); + _exhaustedUntilMs.TryRemove(nodeKey, out _); + } + + public void RecordFailure(string nodeKey, long cooldownMs, bool isPermanentQuotaOrAuth = false, long? nowMs = null) + { + if (string.IsNullOrEmpty(nodeKey)) return; + long now = nowMs ?? _clockMs(); + _isolatedUntilMs[nodeKey] = now + cooldownMs; + if (isPermanentQuotaOrAuth) + { + _exhaustedUntilMs[nodeKey] = now + cooldownMs; + } + } + + public void RecordFailure(string nodeKey, RimMindError error, bool isRateLimited = false, long? nowMs = null) + { + if (string.IsNullOrEmpty(nodeKey)) return; + // Content moderation and permanent request schema errors must NOT isolate endpoints + if (error.Code == RimMindErrorCode.ContentFiltered || error.Code == RimMindErrorCode.Cancelled) + return; + + if (error.Code == RimMindErrorCode.ClientQuotaOrAuthFailure) + { + RecordFailure(nodeKey, _permanentIsolationMs, isPermanentQuotaOrAuth: true, nowMs: nowMs); + } + else if (isRateLimited) + { + RecordFailure(nodeKey, _transientRateLimitIsolationMs, isPermanentQuotaOrAuth: false, nowMs: nowMs); + } + else + { + RecordFailure(nodeKey, _defaultIsolationMs, isPermanentQuotaOrAuth: false, nowMs: nowMs); + } + } + + public List OrderCandidates(IReadOnlyList candidates, Func keySelector, long? nowMs = null) + { + if (candidates == null || candidates.Count == 0) + return new List(); + if (candidates.Count == 1) + return new List { candidates[0] }; + + long now = nowMs ?? _clockMs(); + var nonExhausted = candidates.Where(n => !IsPermanentlyExhausted(keySelector(n), now)).ToList(); + var pool = nonExhausted.Count > 0 ? nonExhausted : candidates.ToList(); + + var healthy = new List(pool.Count); + var isolated = new List<(T Node, long UntilMs)>(); + + for (int i = 0; i < pool.Count; i++) + { + var node = pool[i]; + string key = keySelector(node); + if (_isolatedUntilMs.TryGetValue(key, out long untilMs) && now < untilMs) + { + isolated.Add((node, untilMs)); + } + else + { + healthy.Add(node); + } + } + + foreach (var item in isolated.OrderBy(x => x.UntilMs)) + { + healthy.Add(item.Node); + } + + return healthy; + } + + public void Reset() + { + _isolatedUntilMs.Clear(); + _exhaustedUntilMs.Clear(); + } + } +} diff --git a/Source/Application/Features/Llm/HttpErrorClassifier.cs b/Source/Application/Features/Llm/HttpErrorClassifier.cs new file mode 100644 index 00000000..ce2b2035 --- /dev/null +++ b/Source/Application/Features/Llm/HttpErrorClassifier.cs @@ -0,0 +1,96 @@ +using System; +using RimMind.Domain.ValueObjects; + +namespace RimMind.Application.Features.Llm +{ + /// + /// Unified HTTP status & response-body classifier shared by Core clients and extension model services. + /// Separates content moderation (non-retryable, no failover), node-level quota/auth failures + /// (isolate node & fail over), transient rate-limit/5xx errors (short cooldown & fail over), + /// and permanent client errors. + /// + public static class HttpErrorClassifier + { + public static bool IsContentModerationResponse(int statusCode, string? responseBody) + { + return statusCode == 400 && + !string.IsNullOrEmpty(responseBody) && + (responseBody!.IndexOf("Content Exists Risk", StringComparison.OrdinalIgnoreCase) >= 0 || + responseBody.IndexOf("content_filter", StringComparison.OrdinalIgnoreCase) >= 0); + } + + public static bool IsQuotaOrAuthError(int statusCode, string? responseBody) + { + if (statusCode == 401 || statusCode == 402 || statusCode == 403 || statusCode == 410) + return true; + + if (string.IsNullOrEmpty(responseBody)) + return false; + + string msg = responseBody!; + return msg.IndexOf("Insufficient Balance", StringComparison.OrdinalIgnoreCase) >= 0 || + msg.IndexOf("Insufficient account funds", StringComparison.OrdinalIgnoreCase) >= 0 || + msg.IndexOf("insufficient_quota", StringComparison.OrdinalIgnoreCase) >= 0 || + msg.IndexOf("account_deactivated", StringComparison.OrdinalIgnoreCase) >= 0 || + msg.IndexOf("invalid_api_key", StringComparison.OrdinalIgnoreCase) >= 0 || + msg.IndexOf("billing_not_active", StringComparison.OrdinalIgnoreCase) >= 0 || + msg.IndexOf("model_not_found", StringComparison.OrdinalIgnoreCase) >= 0 || + msg.IndexOf("ModelDeprecated", StringComparison.OrdinalIgnoreCase) >= 0 || + msg.IndexOf("has been deprecated", StringComparison.OrdinalIgnoreCase) >= 0 || + msg.IndexOf("Model is unavailable", StringComparison.OrdinalIgnoreCase) >= 0 || + msg.IndexOf("is not supported by any configured account", StringComparison.OrdinalIgnoreCase) >= 0; + } + + public static bool IsTransientRateLimitOrQueueError(int statusCode, string? responseBody) + { + if (IsQuotaOrAuthError(statusCode, responseBody)) + return false; + + if (statusCode == 429) + return true; + + if (string.IsNullOrEmpty(responseBody)) + return false; + + string msg = responseBody!; + return msg.IndexOf("rate_limit", StringComparison.OrdinalIgnoreCase) >= 0 || + msg.IndexOf("gateway_concurrency_limit", StringComparison.OrdinalIgnoreCase) >= 0 || + msg.IndexOf("gateway_queue_full", StringComparison.OrdinalIgnoreCase) >= 0 || + msg.IndexOf("concurrency_limit", StringComparison.OrdinalIgnoreCase) >= 0 || + msg.IndexOf("Concurrency limit exceeded", StringComparison.OrdinalIgnoreCase) >= 0 || + msg.IndexOf("queue_full", StringComparison.OrdinalIgnoreCase) >= 0 || + msg.IndexOf("Too many pending requests", StringComparison.OrdinalIgnoreCase) >= 0 || + msg.IndexOf("server_overloaded", StringComparison.OrdinalIgnoreCase) >= 0; + } + + public static bool IsTransientHttpFailure(int statusCode, string? responseBody) + { + if (IsContentModerationResponse(statusCode, responseBody) || IsQuotaOrAuthError(statusCode, responseBody)) + return false; + + return statusCode == 408 || + statusCode == 429 || + statusCode >= 500 || + IsTransientRateLimitOrQueueError(statusCode, responseBody); + } + + public static RimMindError Classify(int statusCode, string? sanitizedBody, string? sourceLabel = null) + { + string safeBody = LogSecretRedactor.ForMessage(sanitizedBody); + string errMsg = string.IsNullOrWhiteSpace(sourceLabel) + ? $"HTTP {statusCode}: {safeBody}".TrimEnd(' ', ':') + : $"Node '{sourceLabel}' HTTP {statusCode}: {safeBody}".TrimEnd(' ', ':'); + + if (IsContentModerationResponse(statusCode, sanitizedBody)) + return RimMindErrors.ContentFiltered(errMsg); + + if (IsQuotaOrAuthError(statusCode, sanitizedBody)) + return RimMindErrors.ClientQuotaOrAuth(errMsg); + + if (IsTransientHttpFailure(statusCode, sanitizedBody)) + return RimMindErrors.ClientTransient(errMsg); + + return RimMindErrors.ClientPermanent(errMsg); + } + } +} diff --git a/Source/Application/Features/Llm/LlmRequestEnvelopeBuilder.cs b/Source/Application/Features/Llm/LlmRequestEnvelopeBuilder.cs index 2295cb73..b946e061 100644 --- a/Source/Application/Features/Llm/LlmRequestEnvelopeBuilder.cs +++ b/Source/Application/Features/Llm/LlmRequestEnvelopeBuilder.cs @@ -27,6 +27,11 @@ public sealed class LlmRequestEnvelopeBuilder private ReasoningEffort _reasoningEffort = ReasoningEffort.Auto; private int? _expireAtTicks; private int? _maxRetryCount; + private string? _coalesceKey; + private int? _maxQueueWaitTicks; + private DateTime? _expiresAtUtc; + private bool? _requireAliveColonist; + private LlmRequestOptions? _options; private Dictionary? _hints; public static LlmRequestEnvelopeBuilder ForScenario(string scenarioId) @@ -165,6 +170,36 @@ public LlmRequestEnvelopeBuilder WithMaxRetryCount(int? count) return this; } + public LlmRequestEnvelopeBuilder WithCoalesceKey(string? coalesceKey) + { + _coalesceKey = string.IsNullOrWhiteSpace(coalesceKey) ? null : coalesceKey!.Trim(); + return this; + } + + public LlmRequestEnvelopeBuilder WithMaxQueueWaitTicks(int? maxQueueWaitTicks) + { + _maxQueueWaitTicks = maxQueueWaitTicks; + return this; + } + + public LlmRequestEnvelopeBuilder WithExpiresAtUtc(DateTime? expiresAtUtc) + { + _expiresAtUtc = expiresAtUtc; + return this; + } + + public LlmRequestEnvelopeBuilder WithRequireAliveColonist(bool? requireAliveColonist) + { + _requireAliveColonist = requireAliveColonist; + return this; + } + + public LlmRequestEnvelopeBuilder WithOptions(LlmRequestOptions? options) + { + _options = options; + return this; + } + public LlmRequestEnvelopeBuilder WithHint(string key, string? value) { if (string.IsNullOrEmpty(key)) return this; @@ -219,6 +254,11 @@ public LlmRequestEnvelope Build() Priority = _priority, ExpireAtTicks = _expireAtTicks, MaxRetryCount = _maxRetryCount, + CoalesceKey = _coalesceKey, + MaxQueueWaitTicks = _maxQueueWaitTicks, + ExpiresAtUtc = _expiresAtUtc, + RequireAliveColonist = _requireAliveColonist, + Options = _options, IsStreaming = _isStreaming, OnStreamChunk = _onStreamChunk, Ct = _ct, diff --git a/Source/Application/Features/Llm/LogSecretRedactor.cs b/Source/Application/Features/Llm/LogSecretRedactor.cs new file mode 100644 index 00000000..3cedccc2 --- /dev/null +++ b/Source/Application/Features/Llm/LogSecretRedactor.cs @@ -0,0 +1,62 @@ +using System; +using System.Text.RegularExpressions; + +namespace RimMind.Application.Features.Llm +{ + /// + /// Engine-free credential redaction and log-payload truncation helper. + /// Shared across Core and extension modules (e.g. ModelService) without touching Infrastructure. + /// + public static class LogSecretRedactor + { + /// Default cap for provider error bodies embedded in messages and logs. + public const int DefaultMaxChars = 500; + + /// Cap for request/response JSON echoed when DebugLogging is enabled. + public const int DebugPayloadMaxChars = 2000; + + private const string Mask = "***"; + + private static readonly Regex BearerPattern = new Regex( + @"(?i)\b(Bearer|Basic)\s+[A-Za-z0-9\-\._~\+\/=:]{4,}", + RegexOptions.Compiled); + + private static readonly Regex KeyValuePattern = new Regex( + @"(?i)(""?(? m.Groups[1].Value + " " + Mask); + result = KeyValuePattern.Replace(result, m => m.Groups[1].Value + Mask); + result = KeyPrefixPattern.Replace(result, Mask); + return result; + } + + public static string Truncate(string? text, int maxChars = DefaultMaxChars) + { + if (string.IsNullOrEmpty(text)) return text ?? string.Empty; + if (maxChars <= 0 || text!.Length <= maxChars) return text!; + return text.Substring(0, maxChars) + $"…[truncated {text.Length - maxChars} chars]"; + } + + public static string ForLog(string? text, int maxChars = DefaultMaxChars) + => Truncate(Redact(text), maxChars); + + public static string ForMessage(string? text, int maxChars = DefaultMaxChars) + => ForLog(text, maxChars); + + public static string ForMessageWithSecret(string? text, string? literalSecret, int maxLength = 320) + { + string value = text ?? string.Empty; + if (!string.IsNullOrEmpty(literalSecret) && literalSecret!.Length >= 4) + value = value.Replace(literalSecret, Mask); + return ForLog(value, maxLength); + } + } +} diff --git a/Source/Application/Features/Llm/OpenAIWireCodec.cs b/Source/Application/Features/Llm/OpenAIWireCodec.cs new file mode 100644 index 00000000..71e8fec4 --- /dev/null +++ b/Source/Application/Features/Llm/OpenAIWireCodec.cs @@ -0,0 +1,527 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using RimMind.Domain.Common; +using RimMind.Domain.Llm; +using RimMind.Domain.ValueObjects; + +namespace RimMind.Application.Features.Llm +{ + /// + /// Engine-free, public wire serializer and response parser for OpenAI-compatible chat-completions endpoints. + /// Supports an optional customizePayload hook so protocol dialect adapters + /// (e.g. DeepSeek thinking/safety_check) can mutate the payload in a single pass without JSON double-parsing. + /// + public static class OpenAIWireCodec + { + private static readonly JsonSerializerSettings WireSettings = + new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; + + private static readonly JsonSerializer WireSerializer = + JsonSerializer.Create(WireSettings); + + public static string BuildRequestJson( + LlmRequestEnvelope envelope, + string modelName, + int defaultMaxTokens, + bool stream = false, + bool forceJsonMode = false, + bool omitZeroMaxTokens = false, + Action? customizePayload = null) + { + if (envelope == null) throw new ArgumentNullException(nameof(envelope)); + + int effectiveMaxTokens = envelope.MaxTokens > 0 + ? (defaultMaxTokens > envelope.MaxTokens && envelope.ScenarioId != "RimMind.Test" + ? defaultMaxTokens + : envelope.MaxTokens) + : defaultMaxTokens; + + var messages = BuildMessages(envelope); + var responseFormat = BuildResponseFormat(envelope, forceJsonMode, messages); + var (tools, toolChoice) = BuildTools(envelope); + + object payload; + if (omitZeroMaxTokens && effectiveMaxTokens <= 0) + { + payload = new WireRequestOmitMaxTokensDto + { + model = modelName, + messages = messages, + max_tokens = null, + temperature = envelope.Temperature, + stream = stream, + stream_options = stream ? new WireStreamOptionsDto() : null, + response_format = responseFormat, + tools = tools, + tool_choice = toolChoice, + }; + } + else + { + payload = new WireRequestDto + { + model = modelName, + messages = messages, + max_tokens = effectiveMaxTokens, + temperature = envelope.Temperature, + stream = stream, + stream_options = stream ? new WireStreamOptionsDto() : null, + response_format = responseFormat, + tools = tools, + tool_choice = toolChoice, + }; + } + + if (customizePayload != null) + { + var root = JObject.FromObject(payload, WireSerializer); + customizePayload(root); + return root.ToString(Formatting.None); + } + + return JsonConvert.SerializeObject(payload, Formatting.None, WireSettings); + } + + public static Result ParseResponse( + string responseBody, + LlmRequestEnvelope? envelope = null) + { + if (string.IsNullOrWhiteSpace(responseBody)) + return Result.Err( + RimMindErrors.ClientTransient("Empty response body from model server.")); + + try + { + var token = JToken.Parse(responseBody.Trim()); + + if (token["error"] != null && token["error"]!.Type != JTokenType.Null) + { + string errMsg = AsString(token["error"]?["message"]) ?? "Unknown API error"; + string errType = AsString(token["error"]?["type"]) ?? string.Empty; + string errCode = AsString(token["error"]?["code"]) ?? string.Empty; + string safeErr = LogSecretRedactor.ForLog(errMsg); + + if (errMsg.IndexOf("Content Exists Risk", StringComparison.OrdinalIgnoreCase) >= 0 || + errCode.IndexOf("content_filter", StringComparison.OrdinalIgnoreCase) >= 0 || + errType.IndexOf("content_filter", StringComparison.OrdinalIgnoreCase) >= 0) + { + return Result.Err(RimMindErrors.ContentFiltered(safeErr)); + } + + if (string.Equals(errType, "server_error", StringComparison.OrdinalIgnoreCase) || + string.Equals(errType, "api_error", StringComparison.OrdinalIgnoreCase) || + string.Equals(errCode, "server_error", StringComparison.OrdinalIgnoreCase)) + { + return Result.Err(RimMindErrors.ClientTransient(safeErr)); + } + + return Result.Err(RimMindErrors.ClientPermanent(safeErr)); + } + + var choices = token["choices"] as JArray; + if (choices == null || choices.Count == 0) + { + return Result.Err( + RimMindErrors.ClientPermanent("Response choices array is missing or empty.")); + } + + var message = choices[0]["message"]; + if (message == null || message.Type == JTokenType.Null) + { + return Result.Err( + RimMindErrors.ClientPermanent("First choice message is null.")); + } + + string content = AsString(message["content"]) ?? string.Empty; + string? reasoningContent = AsString(message["reasoning_content"]); + string? finishReason = AsString(choices[0]["finish_reason"]); + string? refusal = AsString(message["refusal"]); + + if (string.Equals(finishReason, "content_filter", StringComparison.OrdinalIgnoreCase) || + !string.IsNullOrWhiteSpace(refusal)) + { + string refusalDetail = !string.IsNullOrWhiteSpace(refusal) + ? LogSecretRedactor.ForLog(refusal!) + : "Response blocked by upstream content filter (finish_reason=content_filter)."; + return Result.Err(RimMindErrors.ContentFiltered(refusalDetail)); + } + + if (string.Equals(finishReason, "insufficient_system_resource", StringComparison.OrdinalIgnoreCase) || + string.Equals(finishReason, "aborted", StringComparison.OrdinalIgnoreCase)) + { + return Result.Err( + RimMindErrors.ClientTransient($"Upstream generation interrupted (finish_reason={finishReason}).")); + } + + string? toolCallsJson = null; + var toolCalls = message["tool_calls"] as JArray; + if (toolCalls != null && toolCalls.Count > 0) + { + var wireList = new List(toolCalls.Count); + foreach (var tc in toolCalls) + { + string? rawId = AsString(tc["id"]); + string id = !string.IsNullOrEmpty(rawId) ? rawId! : Guid.NewGuid().ToString("N"); + string? rawType = AsString(tc["type"]); + string type = !string.IsNullOrEmpty(rawType) ? rawType! : "function"; + string name = AsString(tc["function"]?["name"]) ?? ""; + var argsToken = tc["function"]?["arguments"]; + string arguments = argsToken == null || argsToken.Type == JTokenType.Null + ? "{}" + : argsToken.Type == JTokenType.String + ? argsToken.ToString() + : argsToken.ToString(Formatting.None); + wireList.Add(new + { + id = id, + type = type, + function = new + { + name = name, + arguments = arguments + } + }); + } + toolCallsJson = JsonConvert.SerializeObject(wireList); + } + + bool expectsTools = envelope?.Tools != null && envelope.Tools.Count > 0; + if (!expectsTools && + !string.Equals(finishReason, "length", StringComparison.OrdinalIgnoreCase) && + string.IsNullOrWhiteSpace(content) && + toolCallsJson == null && + !string.IsNullOrWhiteSpace(reasoningContent)) + { + content = reasoningContent!; + } + + if (toolCallsJson == null && + content.Length > 0 && + string.IsNullOrWhiteSpace(content) && + string.IsNullOrWhiteSpace(reasoningContent)) + { + return Result.Err( + RimMindErrors.ClientTransient("Upstream returned whitespace-only content.")); + } + + var usage = token["usage"]; + int promptTokens = AsInt(usage?["prompt_tokens"]) ?? 0; + int completionTokens = AsInt(usage?["completion_tokens"]) ?? 0; + int totalTokens = AsInt(usage?["total_tokens"]) ?? (promptTokens + completionTokens); + int cachedTokens = AsInt(usage?["prompt_tokens_details"]?["cached_tokens"]) + ?? AsInt(usage?["prompt_cache_hit_tokens"]) + ?? 0; + + var llmResponse = new LlmResponse + { + RequestId = AsString(token["id"]) ?? Guid.NewGuid().ToString("N"), + Content = content, + ReasoningContent = reasoningContent, + ToolCallsJson = toolCallsJson, + PromptTokens = promptTokens, + CompletionTokens = completionTokens, + CachedTokens = cachedTokens, + TokensUsed = totalTokens + }; + + return Result.Ok(llmResponse); + } + catch (Exception ex) + { + return Result.Err( + RimMindErrors.ClientPermanent($"Failed to parse OpenAI response: {LogSecretRedactor.ForLog(ex.Message)}")); + } + } + + /// + /// Ensures at least one message in a serialized messages JArray contains the keyword + /// "json", appending a system instruction if absent (required by OpenAI/DeepSeek json_object mode). + /// + public static void EnsureJsonKeyword(JArray messages) + { + if (messages == null) return; + for (int i = 0; i < messages.Count; i++) + { + if (messages[i] is JObject msgObj) + { + string? content = msgObj["content"]?.ToString(); + if (!string.IsNullOrEmpty(content) && + content!.IndexOf("json", StringComparison.OrdinalIgnoreCase) >= 0) + { + return; + } + } + } + + for (int i = messages.Count - 1; i >= 0; i--) + { + if (messages[i] is JObject msgObj && + string.Equals(msgObj["role"]?.ToString(), "system", StringComparison.OrdinalIgnoreCase)) + { + string existing = msgObj["content"]?.ToString() ?? string.Empty; + msgObj["content"] = existing + "\n\nPlease respond in JSON format."; + return; + } + } + + messages.Insert(0, new JObject + { + ["role"] = "system", + ["content"] = "Please respond in JSON format." + }); + } + + public static bool TryParseJson(string? value, out object? parsed) + { + parsed = null; + if (string.IsNullOrWhiteSpace(value)) return false; + string trimmed = value!.TrimStart(); + if (trimmed.Length == 0 || (trimmed[0] != '{' && trimmed[0] != '[')) return false; + try + { + parsed = JsonConvert.DeserializeObject(value!); + return parsed != null; + } + catch (JsonException) + { + return false; + } + } + + private static WireResponseFormatDto? BuildResponseFormat( + LlmRequestEnvelope envelope, + bool forceJsonMode, + List messages) + { + if (TryParseJson(envelope.JsonSchema, out var parsedSchema)) + { + return new WireResponseFormatDto + { + type = "json_schema", + json_schema = new { name = "response", schema = parsedSchema }, + }; + } + + if (forceJsonMode) + { + EnsureJsonKeyword(messages); + return new WireResponseFormatDto { type = "json_object" }; + } + + return null; + } + + private static (List? tools, object? toolChoice) BuildTools(LlmRequestEnvelope envelope) + { + if (envelope.Tools == null || envelope.Tools.Count == 0) + return (null, null); + + var tools = new List(); + foreach (var t in envelope.Tools.OrderBy(t => t.Name, StringComparer.Ordinal)) + { + tools.Add(new WireToolDto + { + Function = new WireToolFunctionDto + { + Name = t.Name?.Replace('.', '_') ?? "", + Description = t.Description, + Parameters = ParseParameters(t.Parameters), + }, + }); + } + + object toolChoice = envelope.Tools.Any(t => t.ToolChoice == "required") ? "required" : "auto"; + return (tools, toolChoice); + } + + private static object? ParseParameters(string? parameters) + { + if (parameters == null) + return new { type = "object", properties = new { } }; + try + { + return JsonConvert.DeserializeObject(parameters); + } + catch (JsonException) + { + return new { type = "object", properties = new { } }; + } + } + + private static void EnsureJsonKeyword(List messages) + { + foreach (var m in messages) + { + if (m.content != null && m.content.IndexOf("json", StringComparison.OrdinalIgnoreCase) >= 0) + return; + } + int lastSys = -1; + for (int i = messages.Count - 1; i >= 0; i--) + { + if (messages[i].role == "system") + { + lastSys = i; + break; + } + } + if (lastSys >= 0) + messages[lastSys].content = (messages[lastSys].content ?? "") + "\n\nPlease respond in JSON format."; + else + messages.Insert(0, new WireMessageDto { role = "system", content = "Please respond in JSON format." }); + } + + private static List BuildMessages(LlmRequestEnvelope envelope) + { + var converted = new List(); + if (envelope.Messages != null && envelope.Messages.Count > 0) + { + foreach (var m in envelope.Messages) + { + if (m == null) continue; + var dto = new WireMessageDto { role = m.Role, content = m.Content }; + if (m.Role == "assistant" && !string.IsNullOrEmpty(m.ReasoningContent)) + dto.reasoning_content = m.ReasoningContent; + if (!string.IsNullOrEmpty(m.ToolCallId)) + dto.tool_call_id = m.ToolCallId; + if (m.ToolCalls != null && m.ToolCalls.Count > 0) + { + dto.tool_calls = m.ToolCalls.Select(tc => new WireToolCallDto + { + Id = tc.Id, + Type = "function", + Function = new WireToolCallFunctionDto + { + Name = tc.Name, + Arguments = tc.Arguments, + }, + }).ToList(); + } + converted.Add(dto); + } + } + + int firstNonSystem = converted.FindIndex(d => d.role != "system"); + int splitAt = firstNonSystem < 0 ? converted.Count : firstNonSystem; + + var messages = new List(); + for (int i = 0; i < splitAt; i++) messages.Add(converted[i]); + if (envelope.Examples != null && envelope.Examples.Count > 0) + { + foreach (var ex in envelope.Examples) + { + if (ex == null) continue; + messages.Add(new WireMessageDto { role = ex.Role, content = ex.Content }); + } + } + for (int i = splitAt; i < converted.Count; i++) messages.Add(converted[i]); + return messages; + } + + private static string? AsString(JToken? token) + { + if (token == null || token.Type == JTokenType.Null || token.Type == JTokenType.Undefined) return null; + return token.ToString(); + } + + private static int? AsInt(JToken? token) + { + if (token == null || token.Type == JTokenType.Null || token.Type == JTokenType.Undefined) return null; + try { return token.Value(); } + catch (FormatException) { return null; } + catch (InvalidCastException) { return null; } + } + +#pragma warning disable IDE1006 +#pragma warning disable CS0649 + private sealed class WireRequestDto + { + public string model = ""; + public List? messages; + public int max_tokens; + public float temperature; + public bool stream; + public WireStreamOptionsDto? stream_options; + public WireResponseFormatDto? response_format; + public List? tools; + public object? tool_choice; + } + + private sealed class WireRequestOmitMaxTokensDto + { + public string model = ""; + public List? messages; + public int? max_tokens; + public float temperature; + public bool stream; + public WireStreamOptionsDto? stream_options; + public WireResponseFormatDto? response_format; + public List? tools; + public object? tool_choice; + } + + private sealed class WireStreamOptionsDto + { + [JsonProperty("include_usage")] + public bool include_usage = true; + } + + private sealed class WireResponseFormatDto + { + public string type = ""; + public object? json_schema; + } + + private sealed class WireToolDto + { + public string type = "function"; + [JsonProperty("function")] + public WireToolFunctionDto? Function; + } + + private sealed class WireToolFunctionDto + { + [JsonProperty("name")] + public string Name = ""; + [JsonProperty("description")] + public string Description = ""; + [JsonProperty("parameters")] + public object? Parameters; + } + + private sealed class WireMessageDto + { + public string role = ""; + public string? content; + public string? reasoning_content; + public string? name; + public string? tool_call_id; + public List? tool_calls; + [JsonProperty("function_call")] + public object? function_call; + } + + private sealed class WireToolCallDto + { + [JsonProperty("index", NullValueHandling = NullValueHandling.Ignore)] + public int? Index; + [JsonProperty("id")] + public string Id = ""; + [JsonProperty("type")] + public string Type = "function"; + [JsonProperty("function")] + public WireToolCallFunctionDto? Function; + } + + private sealed class WireToolCallFunctionDto + { + [JsonProperty("name")] + public string Name = ""; + [JsonProperty("arguments")] + public string Arguments = ""; + } +#pragma warning restore IDE1006 + } +} diff --git a/Source/Application/Features/Llm/PromptZonePartitioner.cs b/Source/Application/Features/Llm/PromptZonePartitioner.cs new file mode 100644 index 00000000..bdaaadf7 --- /dev/null +++ b/Source/Application/Features/Llm/PromptZonePartitioner.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RimMind.Domain.Llm; + +namespace RimMind.Application.Features.Llm +{ + public sealed class PromptZonePartition + { + public IReadOnlyList StaticSystemPrompts { get; init; } = Array.Empty(); + public IReadOnlyList VolatileObservations { get; init; } = Array.Empty(); + public IReadOnlyList Examples { get; init; } = Array.Empty(); + public IReadOnlyList LiveNonSystemMessages { get; init; } = Array.Empty(); + public ChatMessage? LastUserMessage { get; init; } + + public string? CombinedStaticSystemPrompt => + StaticSystemPrompts.Count > 0 ? string.Join("\n\n", StaticSystemPrompts) : null; + + public string? CombinedVolatileObservation => + VolatileObservations.Count > 0 ? string.Join("\n\n", VolatileObservations) : null; + } + + /// + /// Deterministic 4-Zone KV-cache partitioner separating byte-stable L0/L1 system prefixes + /// from volatile L2/L3/L5 real-time observations and live conversation turns. + /// Shared across OpenAI, Anthropic, and DeepSeek protocol serializers. + /// + public static class PromptZonePartitioner + { + public static bool IsVolatileLayerTag(string? layerTag) + { + return string.Equals(layerTag, "L2", StringComparison.OrdinalIgnoreCase) + || string.Equals(layerTag, "L3", StringComparison.OrdinalIgnoreCase) + || string.Equals(layerTag, "L5", StringComparison.OrdinalIgnoreCase); + } + + public static PromptZonePartition Partition(LlmRequestEnvelope? envelope) + { + if (envelope == null) + return new PromptZonePartition(); + + var staticSystem = new List(); + var volatileObs = new List(); + var liveNonSystem = new List(); + + if (envelope.Messages != null) + { + for (int i = 0; i < envelope.Messages.Count; i++) + { + var m = envelope.Messages[i]; + if (m == null) continue; + + if (string.Equals(m.Role, "system", StringComparison.OrdinalIgnoreCase)) + { + if (string.IsNullOrWhiteSpace(m.Content)) + continue; + + if (IsVolatileLayerTag(m.LayerTag)) + volatileObs.Add(m.Content); + else + staticSystem.Add(m.Content); + } + else + { + liveNonSystem.Add(m); + } + } + } + + var examples = envelope.Examples != null + ? envelope.Examples.Where(ex => ex != null && !string.Equals(ex.Role, "system", StringComparison.OrdinalIgnoreCase)).ToList() + : new List(); + + var lastUser = liveNonSystem.LastOrDefault(m => string.Equals(m.Role, "user", StringComparison.OrdinalIgnoreCase)); + + return new PromptZonePartition + { + StaticSystemPrompts = staticSystem, + VolatileObservations = volatileObs, + Examples = examples, + LiveNonSystemMessages = liveNonSystem, + LastUserMessage = lastUser + }; + } + } +} diff --git a/Source/Application/Features/Llm/RimMindHttpClientPool.cs b/Source/Application/Features/Llm/RimMindHttpClientPool.cs new file mode 100644 index 00000000..6ccc6e46 --- /dev/null +++ b/Source/Application/Features/Llm/RimMindHttpClientPool.cs @@ -0,0 +1,39 @@ +using System; +using System.Net.Http; +using System.Threading; + +namespace RimMind.Application.Features.Llm +{ + /// + /// Process-wide shared pool and endpoint helpers. + /// Prevents socket exhaustion and eliminates duplicate static HttpClient instances across Core and ModelService. + /// + public static class RimMindHttpClientPool + { + /// Shared HttpClient with infinite timeout (per-request CancellationToken controls timeout). + public static HttpClient Shared { get; } = new HttpClient + { + Timeout = Timeout.InfiniteTimeSpan + }; + + /// Shared HttpClient with automatic redirects disabled (for credential-safe endpoint & gateway calls). + public static HttpClient NoRedirect { get; } = new HttpClient(new HttpClientHandler + { + AllowAutoRedirect = false + }) + { + Timeout = Timeout.InfiniteTimeSpan + }; + + /// Returns true if the given URL targets localhost / loopback / Docker host. + public static bool IsLoopbackEndpoint(string? endpoint) + { + if (string.IsNullOrWhiteSpace(endpoint)) return false; + if (!Uri.TryCreate(endpoint!.Trim(), UriKind.Absolute, out var uri)) return false; + if (uri.IsLoopback) return true; + string host = uri.Host; + return string.Equals(host, "localhost", StringComparison.OrdinalIgnoreCase) + || string.Equals(host, "host.docker.internal", StringComparison.OrdinalIgnoreCase); + } + } +} diff --git a/Source/Application/Features/Pipeline/Unified/ToolCallDispatchMiddleware.cs b/Source/Application/Features/Pipeline/Unified/ToolCallDispatchMiddleware.cs index 49f099f2..099a6edf 100644 --- a/Source/Application/Features/Pipeline/Unified/ToolCallDispatchMiddleware.cs +++ b/Source/Application/Features/Pipeline/Unified/ToolCallDispatchMiddleware.cs @@ -55,7 +55,7 @@ public async Task InvokeAsync(LlmRequestContext context, MiddlewareDelegate RimMind.Application.Features.Agent.Modes.ThinkStrategyHelper.IsQueryToolName(tc.FunctionName, _toolRegistry)) diff --git a/Source/Application/Features/Prompt/MoteTextFormatter.cs b/Source/Application/Features/Prompt/MoteTextFormatter.cs new file mode 100644 index 00000000..5360ea29 --- /dev/null +++ b/Source/Application/Features/Prompt/MoteTextFormatter.cs @@ -0,0 +1,102 @@ +using System; +using System.Text; + +namespace RimMind.Application.Features.Prompt +{ + /// + /// CJK-aware and word-boundary-aware text wrapper for overhead speech bubbles / motes. + /// + public static class MoteTextFormatter + { + public const int DefaultMaxCharsPerLine = 26; + + public static string WrapForMote(string? text, int maxCharsPerLine = DefaultMaxCharsPerLine) + { + if (string.IsNullOrWhiteSpace(text)) + return string.Empty; + + if (maxCharsPerLine < 4) + maxCharsPerLine = 4; + + string normalized = text!.Replace("\r\n", "\n").Replace('\r', '\n').Trim(); + var sb = new StringBuilder(normalized.Length + 16); + string[] paragraphs = normalized.Split('\n'); + + for (int p = 0; p < paragraphs.Length; p++) + { + if (p > 0) sb.Append('\n'); + WrapParagraph(paragraphs[p].Trim(), maxCharsPerLine, sb); + } + + return sb.ToString(); + } + + private static void WrapParagraph(string line, int maxUnits, StringBuilder sb) + { + if (string.IsNullOrEmpty(line)) + return; + + int lineStart = 0; + int currentUnits = 0; + int lastBreakIndex = -1; + + for (int i = 0; i < line.Length; i++) + { + char ch = line[i]; + int charUnits = IsWideCjkChar(ch) ? 2 : 1; + + if (currentUnits + charUnits > maxUnits && i > lineStart) + { + int cut = lastBreakIndex > lineStart ? lastBreakIndex : i; + string segment = line.Substring(lineStart, cut - lineStart).TrimEnd(); + if (segment.Length > 0) + { + sb.Append(segment); + sb.Append('\n'); + } + + lineStart = cut; + while (lineStart < line.Length && line[lineStart] == ' ') + lineStart++; + + i = lineStart - 1; + currentUnits = 0; + lastBreakIndex = -1; + continue; + } + + currentUnits += charUnits; + if (IsPreferredBreakAfter(ch)) + { + lastBreakIndex = i + 1; + } + else if (ch == ' ') + { + lastBreakIndex = i; + } + } + + if (lineStart < line.Length) + { + string tail = line.Substring(lineStart).Trim(); + if (tail.Length > 0) + sb.Append(tail); + } + } + + private static bool IsWideCjkChar(char ch) + { + return (ch >= '\u2E80' && ch <= '\u9FFF') + || (ch >= '\uF900' && ch <= '\uFAFF') + || (ch >= '\uFF00' && ch <= '\uFFEF') + || (ch >= '\u3000' && ch <= '\u303F'); + } + + private static bool IsPreferredBreakAfter(char ch) + { + return ch == ',' || ch == '。' || ch == '!' || ch == '?' || ch == '、' || ch == ';' + || ch == ',' || ch == '.' || ch == '!' || ch == '?' || ch == ';' + || IsWideCjkChar(ch); + } + } +} diff --git a/Source/Application/Features/Requests/Queue/IRequestQueue.cs b/Source/Application/Features/Requests/Queue/IRequestQueue.cs index e278ec90..8f3f126f 100644 --- a/Source/Application/Features/Requests/Queue/IRequestQueue.cs +++ b/Source/Application/Features/Requests/Queue/IRequestQueue.cs @@ -24,6 +24,7 @@ void Enqueue( bool isLocalEndpoint = false); void EnqueueImmediate(LlmRequestEnvelope envelope, Action> callback, IAIClient client); bool CancelRequest(string requestId); + int CancelByNpcId(string npcId, string? reason = null); void CancelAllRequests(); void PauseQueue(); void ResumeQueue(); diff --git a/Source/Application/Features/Requests/Queue/RequestQueue.cs b/Source/Application/Features/Requests/Queue/RequestQueue.cs index 9abdb19c..2bc74eec 100644 --- a/Source/Application/Features/Requests/Queue/RequestQueue.cs +++ b/Source/Application/Features/Requests/Queue/RequestQueue.cs @@ -49,6 +49,13 @@ private readonly ConcurrentDictionary _requestIdToActive public int CurrentTick { get; set; } public Action? LogHandler { get; set; } + /// + /// Optional pre-dispatch colonist liveness predicate injected by the Composition Root. + /// When set, requests targeting an NPC-* colonist (or with RequireAliveColonist=true) + /// are cancelled before dispatch if this returns false. + /// + public Func? PawnLivenessChecker { get; set; } + public Func? UtcClock { get; set; } public IExtensionRegistry? ModCooldowns { get => _circuitBreaker.ModCooldowns; @@ -137,6 +144,27 @@ public void Enqueue( { string modId = !string.IsNullOrEmpty(envelope.ModId) ? envelope.ModId : "Unknown"; if (!_modQueues.TryGetValue(modId, out var queue)) { queue = new List(); _modQueues[modId] = queue; } + + // Per-key request coalescing: supersede older pending (not-yet-dispatched) entries with the same CoalesceKey + string? coalesceKey = envelope.EffectiveCoalesceKey; + if (!string.IsNullOrWhiteSpace(coalesceKey)) + { + var superseded = Result.Err( + new RimMindError(RimMindErrorCode.Cancelled, $"Superseded by newer request ({coalesceKey})")); + for (int i = queue.Count - 1; i >= 0; i--) + { + if (string.Equals(queue[i].Envelope.EffectiveCoalesceKey, coalesceKey, StringComparison.Ordinal)) + { + var stale = queue[i]; + queue.RemoveAt(i); + stale.State = AIRequestState.Cancelled; + Complete(stale, superseded); + if (Settings.DebugLogging) + EnqueueLog($"[RimMind-Core] Coalesced stale pending request {stale.Envelope.RequestId} for key '{coalesceKey}'"); + } + } + } + int trackingId = _nextTrackingId++; var tracked = new TrackedRequest { @@ -156,6 +184,18 @@ public void EnqueueImmediate(LlmRequestEnvelope envelope, Action.Err( + new RimMindError(RimMindErrorCode.Cancelled, livenessReason))); + return; + } if (client.IsLocalEndpoint && _isProcessingLocalRequest) { if (Settings.DebugLogging) EnqueueLog($"[RimMind-Core] Immediate request {envelope.RequestId} deferred: local model busy"); @@ -168,7 +208,7 @@ public void EnqueueImmediate(LlmRequestEnvelope envelope, Action client.SendAsync(CloneWithCancellationToken(envelope, ct)), Client = client, IsLocalEndpointSnapshot = client.IsLocalEndpoint, State = AIRequestState.Processing, - EnqueuedAtTick = CurrentTick, StartedProcessingAtTick = CurrentTick, StartedProcessingAtUtc = DateTime.UtcNow, AttemptCount = 1, MaxAttempts = 1, + EnqueuedAtTick = CurrentTick, StartedProcessingAtTick = CurrentTick, StartedProcessingAtUtc = NowUtc(), AttemptCount = 1, MaxAttempts = 1, }; _activeRequests[trackingId] = tracked; _requestIdToActive[envelope.RequestId] = tracked; @@ -186,26 +226,18 @@ private void ProcessAllQueues(int now) { var cooldownSnapshot = _circuitBreaker.GetCooldownSnapshot(); var readyRequests = new List<(string modId, TrackedRequest tracked)>(); + DateTime nowUtc = NowUtc(); foreach (var kvp in _modQueues) { string modId = kvp.Key; var queue = kvp.Value; if (queue.Count == 0) continue; + + // Always prune expired or dead-pawn pending entries even while mod is on cooldown + PruneExpiredAndIneligibleHead(queue, now, nowUtc); + if (queue.Count == 0) continue; + if (cooldownSnapshot.TryGetValue(modId, out int nextAllowed) && now < nextAllowed) continue; - while (queue.Count > 0) - { - var t = queue[0]; - if (t.Envelope.ExpireAtTicks.HasValue && t.Envelope.ExpireAtTicks.Value > 0 && now > t.Envelope.ExpireAtTicks.Value) - { - queue.RemoveAt(0); - Complete(t, Result.Err( - RimMindErrors.Timeout($"Request {t.Envelope.RequestId} expired in queue at tick {now}"))); - if (Settings.DebugLogging) - EnqueueLog($"[RimMind-Core] Expired request {t.Envelope.RequestId} completed with timeout"); - continue; - } - break; - } - if (queue.Count > 0) readyRequests.Add((modId, queue[0])); + readyRequests.Add((modId, queue[0])); } readyRequests.Sort((a, b) => { int p = (int)a.tracked.Envelope.Priority - (int)b.tracked.Envelope.Priority; if (p != 0) return p; return a.tracked.EnqueuedAtTick - b.tracked.EnqueuedAtTick; }); int maxConcurrent = Settings.MaxConcurrentRequests; @@ -217,7 +249,7 @@ private void ProcessAllQueues(int now) queue.RemoveAt(0); int cooldownTicks = _circuitBreaker.GetModCooldownTicks(modId); _circuitBreaker.SetCooldown(modId, now + cooldownTicks); - tracked.State = AIRequestState.Processing; tracked.StartedProcessingAtTick = now; tracked.StartedProcessingAtUtc = DateTime.UtcNow; + tracked.State = AIRequestState.Processing; tracked.StartedProcessingAtTick = now; tracked.StartedProcessingAtUtc = nowUtc; _activeRequests[tracked.TrackingId] = tracked; _requestIdToActive[tracked.Envelope.RequestId] = tracked; if (tracked.IsLocalEndpointSnapshot) _isProcessingLocalRequest = true; if (Settings.DebugLogging) @@ -227,6 +259,92 @@ private void ProcessAllQueues(int now) } } + private void PruneExpiredAndIneligibleHead(List queue, int now, DateTime nowUtc) + { + while (queue.Count > 0) + { + var t = queue[0]; + if (IsExpired(t, now, nowUtc, out string expireReason)) + { + queue.RemoveAt(0); + Complete(t, Result.Err(RimMindErrors.Timeout(expireReason))); + if (Settings.DebugLogging) + EnqueueLog($"[RimMind-Core] Expired request {t.Envelope.RequestId}: {expireReason}"); + continue; + } + + if (!PassesPreDispatchLivenessGate(t.Envelope, out string livenessReason)) + { + queue.RemoveAt(0); + t.State = AIRequestState.Cancelled; + Complete(t, Result.Err( + new RimMindError(RimMindErrorCode.Cancelled, livenessReason))); + if (Settings.DebugLogging) + EnqueueLog($"[RimMind-Core] Dropped request {t.Envelope.RequestId} at pre-dispatch liveness gate: {livenessReason}"); + continue; + } + + break; + } + } + + private bool IsExpired(TrackedRequest tracked, int now, DateTime nowUtc, out string reason) + { + var env = tracked.Envelope; + if (env.ExpireAtTicks.HasValue && env.ExpireAtTicks.Value > 0 && now > env.ExpireAtTicks.Value) + { + reason = $"Request {env.RequestId} expired in queue at tick {now}"; + return true; + } + + int? maxWait = env.EffectiveMaxQueueWaitTicks; + if (maxWait.HasValue && maxWait.Value > 0 && now >= tracked.EnqueuedAtTick && (now - tracked.EnqueuedAtTick) > maxWait.Value) + { + reason = $"Request {env.RequestId} exceeded MaxQueueWaitTicks ({maxWait.Value}) in queue"; + return true; + } + + DateTime? deadlineUtc = env.EffectiveExpiresAtUtc; + if (deadlineUtc.HasValue && nowUtc > deadlineUtc.Value) + { + reason = $"Request {env.RequestId} exceeded UTC queue deadline"; + return true; + } + + reason = string.Empty; + return false; + } + + private bool PassesPreDispatchLivenessGate(LlmRequestEnvelope envelope, out string reason) + { + reason = string.Empty; + var checker = PawnLivenessChecker; + if (checker == null) + return true; + + string? npcId = envelope.NpcId; + if (string.IsNullOrWhiteSpace(npcId)) + return true; + + bool? explicitFlag = envelope.EffectiveRequireAliveColonist; + bool shouldCheck = explicitFlag.HasValue + ? explicitFlag.Value + : npcId!.StartsWith("NPC-", StringComparison.OrdinalIgnoreCase); + + if (!shouldCheck) + return true; + + if (!checker(npcId!)) + { + reason = $"Pawn '{npcId}' is no longer an active living colonist"; + return false; + } + + return true; + } + + private DateTime NowUtc() => UtcClock?.Invoke() ?? DateTime.UtcNow; + private void TryProcessModQueue(string modId, int now) { if (_isPaused) return; @@ -339,6 +457,56 @@ public bool CancelRequest(string requestId) } } + public int CancelByNpcId(string npcId, string? reason = null) + { + if (string.IsNullOrWhiteSpace(npcId)) + return 0; + + string message = string.IsNullOrWhiteSpace(reason) + ? $"Request cancelled for {npcId}" + : reason!; + var errResult = Result.Err( + new RimMindError(RimMindErrorCode.Cancelled, message)); + + int cancelledCount = 0; + lock (_queueLock) + { + foreach (var active in _activeRequests.Values.ToList()) + { + if (string.Equals(active.Envelope.NpcId, npcId, StringComparison.OrdinalIgnoreCase)) + { + active.State = AIRequestState.Cancelled; + active.CancellationSource?.Cancel(); + Complete(active, errResult); + cancelledCount++; + } + } + + foreach (var kvp in _modQueues) + { + var queue = kvp.Value; + for (int i = queue.Count - 1; i >= 0; i--) + { + if (string.Equals(queue[i].Envelope.NpcId, npcId, StringComparison.OrdinalIgnoreCase)) + { + var tracked = queue[i]; + queue.RemoveAt(i); + tracked.State = AIRequestState.Cancelled; + Complete(tracked, errResult); + cancelledCount++; + } + } + } + } + + if (cancelledCount > 0 && Settings.DebugLogging) + { + EnqueueLog($"[RimMind-Core] Cancelled {cancelledCount} request(s) for npcId={npcId} ({message})"); + } + + return cancelledCount; + } + public void PauseQueue() => _isPaused = true; public void ResumeQueue() => _isPaused = false; public bool IsPaused => _isPaused; @@ -364,14 +532,5 @@ private static LlmRequestEnvelope CloneWithCancellationToken( LlmRequestEnvelope envelope, CancellationToken cancellationToken) => envelope.WithCancellationToken(cancellationToken); - - private sealed class UnboundedCompletionFence : ICompletionFence - { - public static readonly UnboundedCompletionFence Instance = new UnboundedCompletionFence(); - - public CancellationToken CancellationToken => CancellationToken.None; - - public bool TryAcceptCompletion() => true; - } } } diff --git a/Source/Application/Features/Requests/RequestSubmissionService.cs b/Source/Application/Features/Requests/RequestSubmissionService.cs index 311b22b3..34e0ce29 100644 --- a/Source/Application/Features/Requests/RequestSubmissionService.cs +++ b/Source/Application/Features/Requests/RequestSubmissionService.cs @@ -152,7 +152,7 @@ private void StartTrace(LlmRequestEnvelope envelope) } bool isAgentRollout = !string.IsNullOrWhiteSpace(rolloutId) - || string.Equals(envelope.ScenarioId, ScenarioIds.Decision, StringComparison.OrdinalIgnoreCase) + || ScenarioIds.IsDecisionScenario(envelope.ScenarioId) || string.Equals(envelope.ModId, "RimMind.Agent", StringComparison.OrdinalIgnoreCase); if (isAgentRollout && string.IsNullOrWhiteSpace(rolloutId)) diff --git a/Source/Application/Features/Tools/AutonomyDomainRiskMapper.cs b/Source/Application/Features/Tools/AutonomyDomainRiskMapper.cs new file mode 100644 index 00000000..643316d3 --- /dev/null +++ b/Source/Application/Features/Tools/AutonomyDomainRiskMapper.cs @@ -0,0 +1,32 @@ +using RimMind.Application.Common.Models.Tools; +using RimMind.Domain.Agent.Policies; +using RimMind.Domain.Enums; + +namespace RimMind.Application.Features.Tools +{ + /// + /// Canonical single-source mapping from to . + /// Shared across Core, Actions, Advisor, and custom tool authors. + /// + public static class AutonomyDomainRiskMapper + { + public static RiskLevel MapToRisk(AutonomyDomain? domain, ToolKind kind = ToolKind.Mutation) + { + if (!domain.HasValue) + { + return kind == ToolKind.Query ? RiskLevel.Low : RiskLevel.Medium; + } + + return domain.Value switch + { + AutonomyDomain.EmergencySurvival => RiskLevel.Low, + AutonomyDomain.ResourceMarking => RiskLevel.Low, + AutonomyDomain.WorktableBills => RiskLevel.Medium, + AutonomyDomain.BlueprintPlacement => RiskLevel.Medium, + AutonomyDomain.WorkPriorityModification => RiskLevel.Medium, + AutonomyDomain.HighRiskOperations => RiskLevel.High, + _ => RiskLevel.Medium + }; + } + } +} diff --git a/Source/Application/Features/Tools/ToolRegistry.cs b/Source/Application/Features/Tools/ToolRegistry.cs index 0d3f4b56..c34b8188 100644 --- a/Source/Application/Features/Tools/ToolRegistry.cs +++ b/Source/Application/Features/Tools/ToolRegistry.cs @@ -170,5 +170,19 @@ public IReadOnlyList GetDefinitionsForScope(AgentScopeKind scope .Select(h => h.Definition) .ToList(); } + + public IReadOnlyList GetDefinitionsForScope(ToolScope scope, bool compactSchema = false) + { + if (scope == ToolScope.None) + return Array.Empty(); + + var matched = _handlers.Values + .Select(h => h.Definition) + .Where(d => ToolScopeProjection.MatchesScope(d, scope)); + + return compactSchema + ? matched.Select(ToolScopeProjection.CompactDefinition).ToList() + : matched.ToList(); + } } } diff --git a/Source/Application/Features/Tools/ToolScopeProjection.cs b/Source/Application/Features/Tools/ToolScopeProjection.cs new file mode 100644 index 00000000..96e944e1 --- /dev/null +++ b/Source/Application/Features/Tools/ToolScopeProjection.cs @@ -0,0 +1,220 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using RimMind.Application.Common.Models.Tools; +using RimMind.Domain.Agent.Policies; + +namespace RimMind.Application.Features.Tools +{ + /// + /// Resolves effective flags from declarative + /// metadata and produces compact JSON schema projections to eliminate prompt token bloat. + /// + public static class ToolScopeProjection + { + public const ToolScope ColonistAgentDefaultScope = + ToolScope.ColonistSelf | ToolScope.ColonyBuild | ToolScope.ColonyManage | ToolScope.Social; + + public const ToolScope AdvisorDefaultScope = + ToolScope.ColonistSelf | ToolScope.ColonyBuild | ToolScope.ColonyManage | ToolScope.Social; + + private const int MaxCompactDescriptionChars = 120; + private const int MaxCompactParamDescChars = 72; + + public static ToolScope ResolveScopes(ToolDefinition? definition) + { + if (definition == null) + return ToolScope.None; + + var manifest = definition.Manifest; + if (manifest?.Scopes is ToolScope declared && declared != ToolScope.None) + return declared; + + string id = (definition.Id ?? string.Empty).Trim(); + string category = (definition.Category ?? string.Empty).Trim(); + + // Meta / listing / help queries + if (id.EndsWith(".list", StringComparison.OrdinalIgnoreCase) || + id.EndsWith("_list", StringComparison.OrdinalIgnoreCase) || + string.Equals(id, "query_tool_help", StringComparison.OrdinalIgnoreCase)) + { + return ToolScope.MetaQuery; + } + + // World-level admin mechanisms/tools + if (string.Equals(category, "world", StringComparison.OrdinalIgnoreCase) || + id.StartsWith("world.", StringComparison.OrdinalIgnoreCase) || + id.StartsWith("world_", StringComparison.OrdinalIgnoreCase)) + { + return ToolScope.WorldAdmin; + } + + // Mechanism read queries (already represented in L1/L2/L3 context) + if (manifest?.Kind == ToolKind.Query && + (id.EndsWith(".query", StringComparison.OrdinalIgnoreCase) || + id.EndsWith("_query", StringComparison.OrdinalIgnoreCase))) + { + return ToolScope.MetaQuery; + } + + ToolScope inferred = ToolScope.None; + + if (manifest?.DefaultDomain is AutonomyDomain domain) + { + switch (domain) + { + case AutonomyDomain.EmergencySurvival: + inferred |= ToolScope.ColonistSelf; + break; + case AutonomyDomain.BlueprintPlacement: + case AutonomyDomain.WorktableBills: + inferred |= ToolScope.ColonyBuild; + break; + case AutonomyDomain.ResourceMarking: + case AutonomyDomain.WorkPriorityModification: + inferred |= ToolScope.ColonyManage; + break; + case AutonomyDomain.HighRiskOperations: + inferred |= ToolScope.ColonyManage | ToolScope.ColonistSelf; + break; + } + } + + if (id.IndexOf("social", StringComparison.OrdinalIgnoreCase) >= 0 || + id.IndexOf("interaction", StringComparison.OrdinalIgnoreCase) >= 0 || + id.IndexOf("dialogue", StringComparison.OrdinalIgnoreCase) >= 0 || + string.Equals(category, "social", StringComparison.OrdinalIgnoreCase)) + { + inferred |= ToolScope.Social; + } + + if (manifest?.IsSelfTargeted == true || + string.Equals(category, "pawn", StringComparison.OrdinalIgnoreCase) || + id.StartsWith("pawn.", StringComparison.OrdinalIgnoreCase) || + id.StartsWith("pawn_", StringComparison.OrdinalIgnoreCase)) + { + inferred |= ToolScope.ColonistSelf; + } + + if (string.Equals(category, "colony", StringComparison.OrdinalIgnoreCase) || + string.Equals(category, "map", StringComparison.OrdinalIgnoreCase)) + { + inferred |= ToolScope.ColonyBuild | ToolScope.ColonyManage; + } + + if (inferred != ToolScope.None) + return inferred; + + // Default fallback for custom module tools without explicit scope or domain: + // treat as colony/self actionable unless explicitly tagged as world/meta. + return manifest?.Kind == ToolKind.Query + ? ToolScope.ColonyManage | ToolScope.ColonyBuild + : ToolScope.ColonistSelf | ToolScope.ColonyManage; + } + + public static bool MatchesScope(ToolDefinition? definition, ToolScope requestedScope) + { + if (definition == null || requestedScope == ToolScope.None) + return false; + if (requestedScope == ToolScope.All) + return true; + + ToolScope resolved = ResolveScopes(definition); + return (resolved & requestedScope) != ToolScope.None; + } + + /// + /// Projects a to a compact form that strips boilerplate + /// schema prose and optional multi-map noise while preserving tool id, types, enums, and required keys. + /// + public static ToolDefinition CompactDefinition(ToolDefinition definition) + { + if (definition == null) throw new ArgumentNullException(nameof(definition)); + + string compactDesc = CompactText(definition.Description, MaxCompactDescriptionChars); + string compactSchema = CompactParametersSchema(definition.ParametersSchema); + + return definition with + { + Description = compactDesc, + ParametersSchema = compactSchema + }; + } + + private static string CompactParametersSchema(string? rawSchema) + { + if (string.IsNullOrWhiteSpace(rawSchema)) + return "{}"; + + try + { + if (!(JToken.Parse(rawSchema!) is JObject root)) + return rawSchema!; + + var requiredSet = new HashSet(StringComparer.OrdinalIgnoreCase); + if (root["required"] is JArray reqArr) + { + foreach (var tok in reqArr) + { + var reqKey = tok?.Value(); + if (!string.IsNullOrWhiteSpace(reqKey)) + requiredSet.Add(reqKey!); + } + if (reqArr.Count == 0) + root.Remove("required"); + } + + if (root["properties"] is JObject props) + { + // Drop optional multi-map boilerplate key from compact projections + if (props.ContainsKey("map_id") && !requiredSet.Contains("map_id")) + props.Remove("map_id"); + + foreach (var prop in props.Properties().ToList()) + { + if (prop.Value is JObject propObj && propObj["description"] is JValue descVal) + { + string desc = descVal.Value() ?? string.Empty; + if (IsBoilerplateParamDesc(desc)) + { + propObj.Remove("description"); + } + else if (desc.Length > MaxCompactParamDescChars) + { + propObj["description"] = CompactText(desc, MaxCompactParamDescChars); + } + } + } + } + + return root.ToString(Formatting.None); + } + catch + { + return rawSchema!; + } + } + + private static bool IsBoilerplateParamDesc(string desc) + { + if (string.IsNullOrWhiteSpace(desc)) return true; + return desc.StartsWith("Parameter for ", StringComparison.OrdinalIgnoreCase) + || desc.Equals("Action to perform", StringComparison.OrdinalIgnoreCase) + || desc.Equals("Pawn thing ID", StringComparison.OrdinalIgnoreCase) + || desc.Equals("Pawn thing ID (optional)", StringComparison.OrdinalIgnoreCase); + } + + private static string CompactText(string? text, int maxChars) + { + if (string.IsNullOrWhiteSpace(text)) return string.Empty; + string normalized = text!.Replace("\r\n", " ").Replace('\n', ' ').Trim(); + while (normalized.Contains(" ")) + normalized = normalized.Replace(" ", " "); + return normalized.Length <= maxChars + ? normalized + : normalized.Substring(0, maxChars - 1).TrimEnd() + "…"; + } + } +} diff --git a/Source/Application/RimMindCore.Application.csproj b/Source/Application/RimMindCore.Application.csproj index 27cbe420..efc76817 100644 --- a/Source/Application/RimMindCore.Application.csproj +++ b/Source/Application/RimMindCore.Application.csproj @@ -20,6 +20,7 @@ + diff --git a/Source/Domain/Llm/LlmRequestEnvelope.cs b/Source/Domain/Llm/LlmRequestEnvelope.cs index 4e8195d1..e2f3cb4a 100644 --- a/Source/Domain/Llm/LlmRequestEnvelope.cs +++ b/Source/Domain/Llm/LlmRequestEnvelope.cs @@ -27,6 +27,16 @@ public class LlmRequestEnvelope public AIRequestPriority Priority { get; init; } = AIRequestPriority.Normal; public int? ExpireAtTicks { get; init; } public int? MaxRetryCount { get; init; } + public string? CoalesceKey { get; init; } + public int? MaxQueueWaitTicks { get; init; } + public DateTime? ExpiresAtUtc { get; init; } + public bool? RequireAliveColonist { get; init; } + public LlmRequestOptions? Options { get; init; } + + public string? EffectiveCoalesceKey => !string.IsNullOrWhiteSpace(CoalesceKey) ? CoalesceKey : Options?.CoalesceKey; + public int? EffectiveMaxQueueWaitTicks => MaxQueueWaitTicks ?? Options?.MaxQueueWaitTicks; + public DateTime? EffectiveExpiresAtUtc => ExpiresAtUtc ?? Options?.ExpiresAtUtc; + public bool? EffectiveRequireAliveColonist => RequireAliveColonist ?? Options?.RequireAliveColonist; // === Streaming === public bool IsStreaming { get; init; } @@ -83,6 +93,11 @@ public LlmRequestEnvelope WithTraceAndHints( Priority = Priority, ExpireAtTicks = ExpireAtTicks, MaxRetryCount = MaxRetryCount, + CoalesceKey = CoalesceKey, + MaxQueueWaitTicks = MaxQueueWaitTicks, + ExpiresAtUtc = ExpiresAtUtc, + RequireAliveColonist = RequireAliveColonist, + Options = Options, IsStreaming = IsStreaming, OnStreamChunk = OnStreamChunk, Ct = Ct, @@ -111,6 +126,11 @@ public LlmRequestEnvelope Clone(CancellationToken? cancellationToken = null) Priority = Priority, ExpireAtTicks = ExpireAtTicks, MaxRetryCount = MaxRetryCount, + CoalesceKey = CoalesceKey, + MaxQueueWaitTicks = MaxQueueWaitTicks, + ExpiresAtUtc = ExpiresAtUtc, + RequireAliveColonist = RequireAliveColonist, + Options = Options, IsStreaming = IsStreaming, OnStreamChunk = OnStreamChunk, Ct = cancellationToken ?? Ct, diff --git a/Source/Domain/Llm/LlmRequestOptions.cs b/Source/Domain/Llm/LlmRequestOptions.cs new file mode 100644 index 00000000..ff65f3ec --- /dev/null +++ b/Source/Domain/Llm/LlmRequestOptions.cs @@ -0,0 +1,33 @@ +using System; + +namespace RimMind.Domain.Llm +{ + /// + /// Optional per-request scheduling, coalescing, TTL, and liveness policies applied by the request queue. + /// + public sealed class LlmRequestOptions + { + /// + /// When set, any pending (not-yet-dispatched) queued request in the same mod queue with the same + /// key is cancelled and superseded by this newer request. + /// + public string? CoalesceKey { get; init; } + + /// + /// Maximum in-game ticks the request may wait in the queue before being dropped prior to dispatch. + /// + public int? MaxQueueWaitTicks { get; init; } + + /// + /// Optional wall-clock UTC deadline after which a still-queued request is dropped prior to dispatch. + /// + public DateTime? ExpiresAtUtc { get; init; } + + /// + /// Controls pre-dispatch colonist liveness verification for pawn-scoped requests (NPC-*). + /// When null, colonist requests (NpcId starting with NPC-) automatically require + /// an active living colonist unless explicitly opted out via false. + /// + public bool? RequireAliveColonist { get; init; } + } +} diff --git a/Source/Infrastructure/Mechanisms/GameMechanismBaseNoDef.cs b/Source/Infrastructure/Mechanisms/GameMechanismBaseNoDef.cs index b8dca38e..f5ec96c9 100644 --- a/Source/Infrastructure/Mechanisms/GameMechanismBaseNoDef.cs +++ b/Source/Infrastructure/Mechanisms/GameMechanismBaseNoDef.cs @@ -6,6 +6,7 @@ using RimMind.Application.Common.Interfaces.Extension; using RimMind.Application.Common.Interfaces.Mechanisms; using RimMind.Application.Common.Models.Mechanisms; +using RimMind.Domain.Agent.Policies; using RimMind.Domain.Enums; using RimMind.Domain.ValueObjects; using Verse; @@ -14,7 +15,7 @@ namespace RimMind.Infrastructure.Mechanisms { - public abstract class GameMechanismBaseNoDef : IGameMechanism + public abstract class GameMechanismBaseNoDef : IGameMechanism, IMechanismAutonomyMetadata { private readonly string? _ownerModId; @@ -34,6 +35,7 @@ protected GameMechanismBaseNoDef(string? ownerModId = null) public abstract MechanismDocs Docs { get; } public virtual IReadOnlyList? GetWriteActions() => null; public virtual MechanismRisk GetRiskForOperation(MechanismOperationType operation) => Risk; + public virtual AutonomyDomain? GetAutonomyDomainForOperation(MechanismOperationType operation) => null; public virtual Task> ExecuteQueryAsync(MechanismReadArgs args, CancellationToken ct) => Task.FromResult(Result.Err(RimMindErrors.MechanismOperationNotSupported(MechanismId, "query"))); diff --git a/Source/Infrastructure/Mechanisms/MechanismToolHandler.cs b/Source/Infrastructure/Mechanisms/MechanismToolHandler.cs index 0ebac963..bfab7842 100644 --- a/Source/Infrastructure/Mechanisms/MechanismToolHandler.cs +++ b/Source/Infrastructure/Mechanisms/MechanismToolHandler.cs @@ -143,6 +143,12 @@ public async Task> ExecuteAsync(ToolCallArgs ar case MechanismOperationType.Trigger: case MechanismOperationType.Watch: { + var isMainThread = IsMainThreadPredicate; + if (isMainThread != null && !isMainThread()) + { + return Result.Err( + RimMindErrors.ToolExecution(Id, $"Mutation tool '{Id}' cannot execute off the Unity main thread")); + } var writeArgs = BuildWriteArgs(root, args, target.PawnId); var r = _operation switch { @@ -247,6 +253,7 @@ private MechanismWriteArgs BuildWriteArgs(JObject? root, ToolCallArgs args, int } internal static Func? PawnExistsPredicate { get; set; } + internal static Func? IsMainThreadPredicate { get; set; } internal static int ResolvePawnId(JObject? root, ToolCallArgs args, string key = "pawn_id") => ResolveTargetPawn(root, args, key).PawnId; @@ -593,6 +600,10 @@ private static ToolDefinition BuildDefinition(IMechanismMetadata metadata, Mecha var description = BuildDescription(metadata, operation); var schema = BuildParameterSchema(metadata, operation); var mechanismRisk = metadata.GetRiskForOperation(operation); + var defaultDomain = (metadata as IMechanismAutonomyMetadata)?.GetAutonomyDomainForOperation(operation); + var kind = operation == MechanismOperationType.Query || operation == MechanismOperationType.List + ? ToolKind.Query + : ToolKind.Mutation; return new ToolDefinition { @@ -602,16 +613,52 @@ private static ToolDefinition BuildDefinition(IMechanismMetadata metadata, Mecha Category = metadata.Scope.ToString().ToLowerInvariant(), Manifest = new ToolManifest { + Kind = kind, RiskLevel = MapRisk(mechanismRisk), RequiresApproval = mechanismRisk >= MechanismRisk.Dangerous, - DefaultDomain = string.Equals(metadata.MechanismId, "pawn.work", StringComparison.OrdinalIgnoreCase) - && operation == MechanismOperationType.Set - ? RimMind.Domain.Agent.Policies.AutonomyDomain.WorkPriorityModification - : (RimMind.Domain.Agent.Policies.AutonomyDomain?)null + DefaultDomain = defaultDomain, + AutonomyDomainId = defaultDomain?.ToString(), + Scopes = ResolveMechanismScopes(metadata, operation, defaultDomain) } }; } + private static ToolScope ResolveMechanismScopes( + IMechanismMetadata metadata, + MechanismOperationType operation, + RimMind.Domain.Agent.Policies.AutonomyDomain? defaultDomain) + { + if (operation == MechanismOperationType.List) + return ToolScope.MetaQuery; + + if (metadata.Scope == MechanismScope.World) + return ToolScope.WorldAdmin; + + if (operation == MechanismOperationType.Query) + return ToolScope.MetaQuery; + + if (defaultDomain == RimMind.Domain.Agent.Policies.AutonomyDomain.WorkPriorityModification) + return ToolScope.ColonyManage | ToolScope.ColonistSelf; + + if (metadata.Scope == MechanismScope.Map) + return ToolScope.ColonyBuild | ToolScope.ColonyManage; + + if (metadata.Scope == MechanismScope.Pawn) + { + string id = metadata.MechanismId ?? string.Empty; + if (id.IndexOf("interaction", StringComparison.OrdinalIgnoreCase) >= 0 || + id.IndexOf("relation", StringComparison.OrdinalIgnoreCase) >= 0 || + id.IndexOf("recruit", StringComparison.OrdinalIgnoreCase) >= 0) + { + return ToolScope.Social | ToolScope.ColonistSelf; + } + + return ToolScope.ColonistSelf; + } + + return ToolScope.ColonistSelf | ToolScope.ColonyManage; + } + private static RiskLevel MapRisk(MechanismRisk risk) => ToolManifestRiskResolver.MapMechanismRisk(risk); private static string BuildDescription(IMechanismMetadata metadata, MechanismOperationType operation) diff --git a/Source/Infrastructure/Mechanisms/Pawn/Work/WorkMechanism.cs b/Source/Infrastructure/Mechanisms/Pawn/Work/WorkMechanism.cs index 2bd476ab..32ca1f01 100644 --- a/Source/Infrastructure/Mechanisms/Pawn/Work/WorkMechanism.cs +++ b/Source/Infrastructure/Mechanisms/Pawn/Work/WorkMechanism.cs @@ -45,6 +45,9 @@ public sealed class WorkMechanism : GameMechanismBase public override IReadOnlyList? GetWriteActions() => _writeActions; + public override AutonomyDomain? GetAutonomyDomainForOperation(MechanismOperationType operation) + => operation == MechanismOperationType.Set ? AutonomyDomain.WorkPriorityModification : null; + public override Task> ExecuteQueryAsync(MechanismReadArgs args, CancellationToken ct) { var pawn = FindPawn(args.PawnId); diff --git a/Source/Infrastructure/Patches/CharacterCardUtility_BioTabBadgePatch.cs b/Source/Infrastructure/Patches/CharacterCardUtility_BioTabBadgePatch.cs new file mode 100644 index 00000000..dd2350e5 --- /dev/null +++ b/Source/Infrastructure/Patches/CharacterCardUtility_BioTabBadgePatch.cs @@ -0,0 +1,125 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Reflection.Emit; +using HarmonyLib; +using RimMind.Presentation.UI; +using RimWorld; +using UnityEngine; +using Verse; + +namespace RimMind.Infrastructure.Patches +{ + /// + /// Single unified Harmony transpiler on that renders all + /// registered badges using a cached lookup. + /// Replaces duplicate per-submodule transpilers in Personality and Memory. + /// + [HarmonyPatch(typeof(CharacterCardUtility), "DoTopStack")] + internal static class CharacterCardUtility_BioTabBadgePatch + { + private static readonly FieldInfo? TmpStackElementsField = + AccessTools.Field(typeof(CharacterCardUtility), "tmpStackElements"); + + private static void AppendRegisteredBadges(Pawn? pawn) + { + if (pawn == null || TmpStackElementsField == null) + return; + + var providers = BioTabBadgeRegistry.GetAll(); + if (providers.Count == 0) + return; + + var tmpStackElements = TmpStackElementsField.GetValue(null) as List; + if (tmpStackElements == null) + return; + + for (int i = 0; i < providers.Count; i++) + { + var provider = providers[i]; + if (provider == null) continue; + + BioTabBadgeDescriptor? badge; + try + { + badge = provider.TryGetBadge(pawn); + } + catch (Exception ex) + { + Log.Warning($"[RimMind-Core] BioTab badge provider '{provider.Id}' threw in TryGetBadge: {ex.Message}"); + continue; + } + + if (badge == null || string.IsNullOrEmpty(badge.Label)) + continue; + + var capturedBadge = badge; + string label = capturedBadge.Label; + float totalW = Text.CalcSize(label).x + Math.Max(4f, capturedBadge.ExtraWidth); + + tmpStackElements.Add(new GenUI.AnonymousStackElement + { + width = totalW, + drawer = rect => + { + Widgets.DrawOptionBackground(rect, false); + Widgets.DrawHighlightIfMouseover(rect); + + if (capturedBadge.TooltipProvider != null) + { + try + { + string tip = capturedBadge.TooltipProvider(); + if (!string.IsNullOrEmpty(tip)) + TooltipHandler.TipRegion(rect, tip); + } + catch + { + // Never disrupt Bio tab rendering if tooltip provider throws. + } + } + + TextAnchor prevAnchor = Text.Anchor; + Text.Anchor = TextAnchor.MiddleCenter; + Widgets.Label(rect, label); + Text.Anchor = prevAnchor; + + if (capturedBadge.OnClick != null && Widgets.ButtonInvisible(rect)) + { + try + { + capturedBadge.OnClick(); + } + catch (Exception ex) + { + Log.Error($"[RimMind-Core] BioTab badge click handler failed: {ex}"); + } + } + } + }); + } + } + + public static IEnumerable Transpiler(IEnumerable instructions) + { + MethodInfo? anchor = AccessTools.Method( + typeof(QuestUtility), + nameof(QuestUtility.AppendInspectStringsFromQuestParts), + new[] { typeof(Action), typeof(ISelectable), typeof(int).MakeByRefType() }); + + MethodInfo appendMethod = AccessTools.Method( + typeof(CharacterCardUtility_BioTabBadgePatch), + nameof(AppendRegisteredBadges)); + + foreach (var instr in instructions) + { + yield return instr; + if (anchor != null && instr.Calls(anchor)) + { + yield return new CodeInstruction(OpCodes.Ldarg_0); + yield return new CodeInstruction(OpCodes.Call, appendMethod); + } + } + } + } +} diff --git a/Source/Infrastructure/Services/Clients/HttpTransport.cs b/Source/Infrastructure/Services/Clients/HttpTransport.cs index 757550de..57e8a60b 100644 --- a/Source/Infrastructure/Services/Clients/HttpTransport.cs +++ b/Source/Infrastructure/Services/Clients/HttpTransport.cs @@ -5,17 +5,15 @@ using System.Text; using System.Threading; using System.Threading.Tasks; +using RimMind.Application.Features.Llm; using RimMind.Infrastructure.Services.Clients.Shared; namespace RimMind.Infrastructure.Services.Clients { internal static class HttpTransport { - // One process-wide client for every Core LLM call (buffered and streaming). - // HttpClient.Timeout is disabled: each request carries its own linked CancellationTokenSource - // so the configured per-request timeout (e.g. 300s for local endpoints) is honoured instead of - // the 100s HttpClient default, and timeouts stay distinguishable from caller cancellation. - private static readonly HttpClient _http = new HttpClient { Timeout = Timeout.InfiniteTimeSpan }; + // Shared process-wide client from RimMindHttpClientPool (infinite timeout; per-request CTS bounds wait). + private static HttpClient _http => RimMindHttpClientPool.Shared; /// Upper bound for the redacted body kept on for classification. private const int ClassificationBodyMaxChars = 4096; @@ -55,19 +53,11 @@ public static HttpException FromResponse(int statusCode, string? body, string? r public string ClassificationText => ResponseBody ?? Message ?? string.Empty; } - public static void EnsureOpenCodeSessionHeader(HttpRequestMessage request, string? url, string? authHeader, string? customSessionId = null) - { - if (!string.IsNullOrEmpty(url) && (url.IndexOf("opencode", StringComparison.OrdinalIgnoreCase) >= 0 || (authHeader != null && authHeader.IndexOf("oc_sk_", StringComparison.OrdinalIgnoreCase) >= 0))) - { - if (!request.Headers.Contains("x-opencode-session")) - { - string sessionId = !string.IsNullOrEmpty(customSessionId) - ? customSessionId! - : "rimmind-" + Guid.NewGuid().ToString("N").Substring(0, 12); - request.Headers.TryAddWithoutValidation("x-opencode-session", sessionId); - } - } - } + public static void RegisterDecorator(IHttpRequestDecorator decorator) + => HttpRequestDecorators.Register(decorator); + + public static void ApplyDecorators(HttpRequestMessage request, string? url, string? authHeader, string? customSessionId = null) + => HttpRequestDecorators.ApplyAll(request, url, authHeader, customSessionId); public static async Task<(string body, long statusCode)> PostAsync( string url, string jsonBody, string? authHeader = null, @@ -88,7 +78,7 @@ public static void EnsureOpenCodeSessionHeader(HttpRequestMessage request, strin if (headerName != null && headerValue != null) request.Headers.TryAddWithoutValidation(headerName, headerValue); - EnsureOpenCodeSessionHeader(request, url, authHeader, headerName == "x-opencode-session" ? headerValue : null); + ApplyDecorators(request, url, authHeader, headerValue); using var response = await _http.SendAsync(request, effectiveToken).ConfigureAwait(false); string body = await response.Content.ReadAsStringAsync().ConfigureAwait(false); @@ -118,7 +108,7 @@ public static void EnsureOpenCodeSessionHeader(HttpRequestMessage request, strin if (headerName != null && headerValue != null) request.Headers.TryAddWithoutValidation(headerName, headerValue); - EnsureOpenCodeSessionHeader(request, url, authHeader, headerName == "x-opencode-session" ? headerValue : null); + ApplyDecorators(request, url, authHeader, headerValue); using var response = await _http.SendAsync(request, effectiveToken).ConfigureAwait(false); string body = await response.Content.ReadAsStringAsync().ConfigureAwait(false); diff --git a/Source/Infrastructure/Services/Clients/IHttpRequestDecorator.cs b/Source/Infrastructure/Services/Clients/IHttpRequestDecorator.cs new file mode 100644 index 00000000..afad197e --- /dev/null +++ b/Source/Infrastructure/Services/Clients/IHttpRequestDecorator.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; + +namespace RimMind.Infrastructure.Services.Clients +{ + /// + /// Extensible request decorator invoked by prior to sending HTTP requests. + /// Allows concrete provider adapters (e.g. OpenCode session routing) to attach custom headers without + /// embedding vendor literals inside generic transport code. + /// + public interface IHttpRequestDecorator + { + string Id { get; } + void Decorate(HttpRequestMessage request, string? url, string? authHeader, string? customSessionId = null); + } + + internal static class HttpRequestDecorators + { + private static readonly object SyncRoot = new object(); + private static readonly List Registered = new List(); + + public static void Register(IHttpRequestDecorator decorator) + { + if (decorator == null) throw new ArgumentNullException(nameof(decorator)); + lock (SyncRoot) + { + int idx = Registered.FindIndex(d => string.Equals(d.Id, decorator.Id, StringComparison.OrdinalIgnoreCase)); + if (idx >= 0) Registered[idx] = decorator; + else Registered.Add(decorator); + } + } + + public static void ApplyAll(HttpRequestMessage request, string? url, string? authHeader, string? customSessionId = null) + { + if (request == null) return; + IHttpRequestDecorator[] snapshot; + lock (SyncRoot) + { + if (Registered.Count == 0) return; + snapshot = Registered.ToArray(); + } + + for (int i = 0; i < snapshot.Length; i++) + { + snapshot[i].Decorate(request, url, authHeader, customSessionId); + } + } + } +} diff --git a/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClient.RequestBuilding.cs b/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClient.RequestBuilding.cs index 6bdc0fd5..3e28d1ba 100644 --- a/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClient.RequestBuilding.cs +++ b/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClient.RequestBuilding.cs @@ -33,6 +33,11 @@ private static RimMind.Domain.Llm.LlmRequestEnvelope StripJsonSchema(RimMind.Dom Priority = envelope.Priority, ExpireAtTicks = envelope.ExpireAtTicks, MaxRetryCount = envelope.MaxRetryCount, + CoalesceKey = envelope.CoalesceKey, + MaxQueueWaitTicks = envelope.MaxQueueWaitTicks, + ExpiresAtUtc = envelope.ExpiresAtUtc, + RequireAliveColonist = envelope.RequireAliveColonist, + Options = envelope.Options, IsStreaming = envelope.IsStreaming, OnStreamChunk = envelope.OnStreamChunk, Ct = envelope.Ct, diff --git a/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClient.cs b/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClient.cs index 6d44ec3d..e657b63d 100644 --- a/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClient.cs +++ b/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClient.cs @@ -10,6 +10,7 @@ using RimMind.Application.Common.Interfaces.Client; using RimMind.Application.Common.Models.Client; using RimMind.Application.Common.Models.Npc; +using RimMind.Application.Features.Llm; using RimMind.Domain.Common; using RimMind.Domain.ValueObjects; using RimMind.Infrastructure.Services.Clients.Shared; @@ -20,6 +21,11 @@ namespace RimMind.Infrastructure.Services.Clients.OpenAI { public partial class OpenAIClient : IAIClient { + static OpenAIClient() + { + HttpTransport.RegisterDecorator(OpenCodeHeaderDecorator.Instance); + } + public delegate Task<(string body, long statusCode)> HttpPostDelegate( string url, string jsonBody, @@ -29,19 +35,17 @@ public partial class OpenAIClient : IAIClient float connectTimeout = 60f, CancellationToken cancellationToken = default); - private const long DefaultNodeIsolationMs = 180_000L; - private const long TransientRateLimitIsolationMs = 2_000L; - private const long PermanentNodeIsolationMs = 1_800_000L; + private const long DefaultNodeIsolationMs = EndpointFailoverPolicy.DefaultIsolationMs; + private const long TransientRateLimitIsolationMs = EndpointFailoverPolicy.DefaultTransientRateLimitIsolationMs; + private const long PermanentNodeIsolationMs = EndpointFailoverPolicy.DefaultPermanentIsolationMs; private static readonly ConcurrentDictionary _formatCapabilityCache = new(StringComparer.OrdinalIgnoreCase); - private static readonly ConcurrentDictionary _endpointIsolatedUntilMs = new(StringComparer.OrdinalIgnoreCase); - private static readonly ConcurrentDictionary _endpointExhaustedUntilMs = new(StringComparer.OrdinalIgnoreCase); + private static readonly EndpointFailoverPolicy FailoverPolicy = new EndpointFailoverPolicy(); internal static void InvalidateFormatCache() { _formatCapabilityCache.Clear(); - _endpointIsolatedUntilMs.Clear(); - _endpointExhaustedUntilMs.Clear(); + FailoverPolicy.Reset(); } internal static string? GetCachedFormatCapability(string? endpoint, string? model) @@ -57,33 +61,16 @@ private static string BuildNodeKey(BackupEndpointNode node) => $"{(node.ApiEndpoint ?? string.Empty).Trim().TrimEnd('/')}|{(node.ModelName ?? string.Empty).Trim()}|{(string.IsNullOrEmpty(node.ApiKey) ? string.Empty : (node.ApiKey.Length > 8 ? node.ApiKey.Substring(node.ApiKey.Length - 8) : node.ApiKey))}"; internal static bool IsNodeIsolated(BackupEndpointNode node, long nowMs) - { - string key = BuildNodeKey(node); - return _endpointIsolatedUntilMs.TryGetValue(key, out long untilMs) && nowMs < untilMs; - } + => FailoverPolicy.IsIsolated(BuildNodeKey(node), nowMs); internal static bool IsNodePermanentlyExhausted(BackupEndpointNode node, long nowMs) - { - string key = BuildNodeKey(node); - return _endpointExhaustedUntilMs.TryGetValue(key, out long untilMs) && nowMs < untilMs; - } + => FailoverPolicy.IsPermanentlyExhausted(BuildNodeKey(node), nowMs); internal static void RecordNodeSuccess(BackupEndpointNode node) - { - string key = BuildNodeKey(node); - _endpointIsolatedUntilMs.TryRemove(key, out _); - _endpointExhaustedUntilMs.TryRemove(key, out _); - } + => FailoverPolicy.RecordSuccess(BuildNodeKey(node)); internal static void RecordNodeFailure(BackupEndpointNode node, long nowMs, long cooldownMs = DefaultNodeIsolationMs, bool isPermanentQuotaOrAuth = false) - { - string key = BuildNodeKey(node); - _endpointIsolatedUntilMs[key] = nowMs + cooldownMs; - if (isPermanentQuotaOrAuth) - { - _endpointExhaustedUntilMs[key] = nowMs + cooldownMs; - } - } + => FailoverPolicy.RecordFailure(BuildNodeKey(node), cooldownMs, isPermanentQuotaOrAuth, nowMs); private static string ClassificationText(Exception ex) => ex is HttpTransport.HttpException httpEx ? httpEx.ClassificationText : (ex.Message ?? string.Empty); @@ -91,37 +78,15 @@ private static string ClassificationText(Exception ex) => internal static bool IsPermanentNodeQuotaOrAuthError(Exception? ex) { if (ex == null) return false; - if (ex is HttpTransport.HttpException httpEx && - (httpEx.StatusCode == 401 || httpEx.StatusCode == 402 || httpEx.StatusCode == 403 || httpEx.StatusCode == 410)) - { - return true; - } - - string msg = ClassificationText(ex); - return msg.IndexOf("Insufficient account funds", StringComparison.OrdinalIgnoreCase) >= 0 || - msg.IndexOf("insufficient_quota", StringComparison.OrdinalIgnoreCase) >= 0 || - msg.IndexOf("account_deactivated", StringComparison.OrdinalIgnoreCase) >= 0 || - msg.IndexOf("invalid_api_key", StringComparison.OrdinalIgnoreCase) >= 0 || - msg.IndexOf("billing_not_active", StringComparison.OrdinalIgnoreCase) >= 0 || - msg.IndexOf("model_not_found", StringComparison.OrdinalIgnoreCase) >= 0 || - msg.IndexOf("ModelDeprecated", StringComparison.OrdinalIgnoreCase) >= 0 || - msg.IndexOf("has been deprecated", StringComparison.OrdinalIgnoreCase) >= 0 || - msg.IndexOf("Model is unavailable", StringComparison.OrdinalIgnoreCase) >= 0 || - msg.IndexOf("is not supported by any configured account", StringComparison.OrdinalIgnoreCase) >= 0; + int statusCode = ex is HttpTransport.HttpException httpEx ? httpEx.StatusCode : 0; + return HttpErrorClassifier.IsQuotaOrAuthError(statusCode, ClassificationText(ex)); } internal static bool IsTransientConcurrencyOrRateLimitError(Exception? ex) { - if (ex == null || IsPermanentNodeQuotaOrAuthError(ex)) return false; - if (ex is HttpTransport.HttpException httpEx && httpEx.StatusCode == 429) - return true; - - string msg = ClassificationText(ex); - return msg.IndexOf("gateway_concurrency_limit", StringComparison.OrdinalIgnoreCase) >= 0 || - msg.IndexOf("gateway_queue_full", StringComparison.OrdinalIgnoreCase) >= 0 || - msg.IndexOf("Concurrency limit exceeded", StringComparison.OrdinalIgnoreCase) >= 0 || - msg.IndexOf("Too many pending requests", StringComparison.OrdinalIgnoreCase) >= 0 || - msg.IndexOf("rate_limit_error", StringComparison.OrdinalIgnoreCase) >= 0; + if (ex == null) return false; + int statusCode = ex is HttpTransport.HttpException httpEx ? httpEx.StatusCode : 0; + return HttpErrorClassifier.IsTransientRateLimitOrQueueError(statusCode, ClassificationText(ex)); } private static long ResolveNodeIsolationCooldownMs(Exception ex, out bool isPermanentQuotaOrAuth) @@ -160,15 +125,7 @@ public void Dispose() } private static bool IsLoopbackEndpoint(string endpoint) - { - if (string.IsNullOrEmpty(endpoint)) return false; - if (!Uri.TryCreate(endpoint.Trim(), UriKind.Absolute, out var uri)) return false; - if (uri.IsLoopback) return true; - string host = uri.Host; - if (string.Equals(host, "localhost", StringComparison.OrdinalIgnoreCase)) return true; - if (string.Equals(host, "host.docker.internal", StringComparison.OrdinalIgnoreCase)) return true; - return false; - } + => RimMindHttpClientPool.IsLoopbackEndpoint(endpoint); public bool SupportsStreaming => true; @@ -219,35 +176,7 @@ internal List ResolveOrderedCandidateNodes(long nowMs) } } - if (allConfigured.Count <= 1) - return allConfigured; - - var nonExhausted = allConfigured.Where(n => !IsNodePermanentlyExhausted(n, nowMs)).ToList(); - var pool = nonExhausted.Count > 0 ? nonExhausted : allConfigured; - - var healthy = new List(); - var isolated = new List<(BackupEndpointNode node, long untilMs)>(); - - for (int i = 0; i < pool.Count; i++) - { - var node = pool[i]; - string key = BuildNodeKey(node); - if (_endpointIsolatedUntilMs.TryGetValue(key, out long untilMs) && nowMs < untilMs) - { - isolated.Add((node, untilMs)); - } - else - { - healthy.Add(node); - } - } - - foreach (var item in isolated.OrderBy(x => x.untilMs)) - { - healthy.Add(item.node); - } - - return healthy; + return FailoverPolicy.OrderCandidates(allConfigured, BuildNodeKey, nowMs); } private async Task<(string responseText, long httpStatusCode)> PostWithFormatFallbackAsync( @@ -353,14 +282,17 @@ internal List ResolveOrderedCandidateNodes(long nowMs) if (logSuccessDetails) { + string cacheSuffix = val.PromptTokens > 0 + ? $", cached={val.CachedTokens}/{val.PromptTokens}" + : string.Empty; if (attempt > 0 || !string.Equals(node.Name, "Primary", StringComparison.OrdinalIgnoreCase)) { _logSink?.LogFromBackground( - $"[RimMind-Core] Request {envelope.RequestId} served by node '{node.Name}' ({node.ApiEndpoint}, model={effectiveModel}, {val.TokensUsed} tok, {sw.ElapsedMilliseconds}ms)."); + $"[RimMind-Core] Request {envelope.RequestId} served by node '{node.Name}' ({node.ApiEndpoint}, model={effectiveModel}, {val.TokensUsed} tok{cacheSuffix}, {sw.ElapsedMilliseconds}ms)."); } else if (_settings.DebugLogging) { - _logSink?.LogFromBackground($"[RimMind-Core] << {envelope.RequestId} ({val.TokensUsed} tok)\n{LogSanitizer.ForLog(val.Content, LogSanitizer.DebugPayloadMaxChars)}"); + _logSink?.LogFromBackground($"[RimMind-Core] << {envelope.RequestId} ({val.TokensUsed} tok{cacheSuffix})\n{LogSanitizer.ForLog(val.Content, LogSanitizer.DebugPayloadMaxChars)}"); } } @@ -593,7 +525,7 @@ internal List ResolveOrderedCandidateNodes(long nowMs) using var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, endpoint); request.Content = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json"); request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {node.ApiKey}"); - HttpTransport.EnsureOpenCodeSessionHeader(request, endpoint, $"Bearer {node.ApiKey}", ResolveSessionId(envelope)); + HttpTransport.ApplyDecorators(request, endpoint, $"Bearer {node.ApiKey}", ResolveSessionId(envelope)); using var session = StreamSendOverride != null ? await HttpTransport.OpenStreamAsync(request, connectTimeout, effectiveCt, StreamSendOverride).ConfigureAwait(false) diff --git a/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClientFactory.cs b/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClientFactory.cs index 0f9e11d0..240d99d5 100644 --- a/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClientFactory.cs +++ b/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClientFactory.cs @@ -1,4 +1,5 @@ using RimMind.Application.Common.Constants; +using RimMind.Application.Common.Helpers; using RimMind.Application.Common.Interfaces.Abstractions; using RimMind.Application.Common.Interfaces.Client; using RimMind.Application.Common.Interfaces.Internal; @@ -11,6 +12,40 @@ public class OpenAIClientFactory : IAIClientFactory private readonly IOpenAISettings? _openAISettings; private readonly ILogSink? _logSink; + static OpenAIClientFactory() + { + HttpTransport.RegisterDecorator(OpenCodeHeaderDecorator.Instance); + RegisterDefaultPresets(); + } + + public static void RegisterDefaultPresets() + { + AIProviderRegistry.RegisterPreset(new AIProviderPreset( + Id: "openai_official", + ProviderId: AIProviders.OpenAI, + Endpoint: "https://api.openai.com/v1", + ModelName: "gpt-4o-mini", + DisplayLabelKey: "RimMind.Settings.Provider.OpenAIOfficial", + FallbackLabel: "OpenAI", + HostMatchSubstring: "api.openai.com")); + AIProviderRegistry.RegisterPreset(new AIProviderPreset( + Id: "openai_deepseek", + ProviderId: AIProviders.OpenAI, + Endpoint: "https://api.deepseek.com/v1", + ModelName: "deepseek-flash", + DisplayLabelKey: "RimMind.Settings.Provider.DeepSeek", + FallbackLabel: "DeepSeek", + HostMatchSubstring: "deepseek.com")); + AIProviderRegistry.RegisterPreset(new AIProviderPreset( + Id: "openai_ollama", + ProviderId: AIProviders.OpenAI, + Endpoint: "http://localhost:11434/v1", + ModelName: "llama3.1", + DisplayLabelKey: null, + FallbackLabel: "Ollama", + HostMatchSubstring: ":11434")); + } + public OpenAIClientFactory(IOpenAISettings? openAISettings = null, ILogSink? logSink = null) { _openAISettings = openAISettings; diff --git a/Source/Infrastructure/Services/Clients/OpenAI/OpenAIRequestSerializer.cs b/Source/Infrastructure/Services/Clients/OpenAI/OpenAIRequestSerializer.cs index ea5f72c5..a208f47a 100644 --- a/Source/Infrastructure/Services/Clients/OpenAI/OpenAIRequestSerializer.cs +++ b/Source/Infrastructure/Services/Clients/OpenAI/OpenAIRequestSerializer.cs @@ -3,6 +3,7 @@ using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; +using RimMind.Application.Features.Llm; using RimMind.Domain.Common; using RimMind.Domain.Llm; using RimMind.Domain.ValueObjects; @@ -11,21 +12,18 @@ namespace RimMind.Infrastructure.Services.Clients.OpenAI { /// - /// Pure (Verse-free, stateless) wire serializer and response parser for OpenAI-compatible - /// chat-completions endpoints. Shared by Core's built-in client and extension model services. + /// Backwards-compatible forwarding wrapper around . + /// Extension modules should call in RimMind.Application.Features.Llm. /// public static class OpenAIRequestSerializer { - private static readonly JsonSerializerSettings WireSettings = - new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; - public static string BuildRequestJson( LlmRequestEnvelope envelope, string modelName, int defaultMaxTokens, bool stream = false, bool forceJsonMode = false) - => BuildRequestJson(envelope, modelName, defaultMaxTokens, stream, forceJsonMode, omitZeroMaxTokens: false); + => OpenAIWireCodec.BuildRequestJson(envelope, modelName, defaultMaxTokens, stream, forceJsonMode, omitZeroMaxTokens: false); public static string BuildRequestJson( LlmRequestEnvelope envelope, @@ -34,211 +32,12 @@ public static string BuildRequestJson( bool stream, bool forceJsonMode, bool omitZeroMaxTokens) - { - if (envelope == null) throw new ArgumentNullException(nameof(envelope)); - - int effectiveMaxTokens = envelope.MaxTokens > 0 - ? (defaultMaxTokens > envelope.MaxTokens && envelope.ScenarioId != "RimMind.Test" - ? defaultMaxTokens - : envelope.MaxTokens) - : defaultMaxTokens; + => OpenAIWireCodec.BuildRequestJson(envelope, modelName, defaultMaxTokens, stream, forceJsonMode, omitZeroMaxTokens); - var messages = BuildMessages(envelope); - var responseFormat = BuildResponseFormat(envelope, forceJsonMode, messages); - var (tools, toolChoice) = BuildTools(envelope); - - if (omitZeroMaxTokens && effectiveMaxTokens <= 0) - { - var omitBody = new WireRequestDto - { - model = modelName, - messages = messages, - max_tokens = null, - temperature = envelope.Temperature, - stream = stream, - stream_options = stream ? new StreamOptionsDto() : null, - response_format = responseFormat, - tools = tools, - tool_choice = toolChoice, - }; - - return JsonConvert.SerializeObject(omitBody, Formatting.None, WireSettings); - } - - var body = new OpenAIRequestDto - { - model = modelName, - messages = messages, - max_tokens = effectiveMaxTokens, - temperature = envelope.Temperature, - stream = stream, - stream_options = stream ? new StreamOptionsDto() : null, - response_format = responseFormat, - tools = tools, - tool_choice = toolChoice, - }; - - return JsonConvert.SerializeObject(body, Formatting.None, WireSettings); - } - - /// - /// Parses an OpenAI chat-completions JSON response into an . - /// Tool-call names are returned in wire (underscore) form for ToolRegistry to resolve, - /// is null when there are no tool calls, cached - /// prompt tokens are surfaced, and reasoning-only replies fall back to reasoning text - /// when the request did not expect tool calls. - /// public static Result ParseResponse( string responseBody, LlmRequestEnvelope? envelope = null) - { - if (string.IsNullOrWhiteSpace(responseBody)) - return Result.Err( - RimMindErrors.ClientTransient("Empty response body from model server.")); - - try - { - var token = JToken.Parse(responseBody); - - if (token["error"] != null && token["error"]!.Type != JTokenType.Null) - { - string errMsg = AsString(token["error"]?["message"]) ?? "Unknown API error"; - string errType = AsString(token["error"]?["type"]) ?? string.Empty; - string errCode = AsString(token["error"]?["code"]) ?? string.Empty; - string safeErr = LogSanitizer.ForLog(errMsg); - - if (errMsg.IndexOf("Content Exists Risk", StringComparison.OrdinalIgnoreCase) >= 0 || - errCode.IndexOf("content_filter", StringComparison.OrdinalIgnoreCase) >= 0 || - errType.IndexOf("content_filter", StringComparison.OrdinalIgnoreCase) >= 0) - { - return Result.Err(RimMindErrors.ContentFiltered(safeErr)); - } - - if (string.Equals(errType, "server_error", StringComparison.OrdinalIgnoreCase) || - string.Equals(errType, "api_error", StringComparison.OrdinalIgnoreCase) || - string.Equals(errCode, "server_error", StringComparison.OrdinalIgnoreCase)) - { - return Result.Err(RimMindErrors.ClientTransient(safeErr)); - } - - return Result.Err(RimMindErrors.ClientPermanent(safeErr)); - } - - var choices = token["choices"] as JArray; - if (choices == null || choices.Count == 0) - { - return Result.Err( - RimMindErrors.ClientPermanent("Response choices array is missing or empty.")); - } - - var message = choices[0]["message"]; - if (message == null || message.Type == JTokenType.Null) - { - return Result.Err( - RimMindErrors.ClientPermanent("First choice message is null.")); - } - - string content = AsString(message["content"]) ?? string.Empty; - string? reasoningContent = AsString(message["reasoning_content"]); - string? finishReason = AsString(choices[0]["finish_reason"]); - string? refusal = AsString(message["refusal"]); - - if (string.Equals(finishReason, "content_filter", StringComparison.OrdinalIgnoreCase) || - !string.IsNullOrWhiteSpace(refusal)) - { - string refusalDetail = !string.IsNullOrWhiteSpace(refusal) - ? LogSanitizer.ForLog(refusal!) - : "Response blocked by upstream content filter (finish_reason=content_filter)."; - return Result.Err(RimMindErrors.ContentFiltered(refusalDetail)); - } - - if (string.Equals(finishReason, "insufficient_system_resource", StringComparison.OrdinalIgnoreCase) || - string.Equals(finishReason, "aborted", StringComparison.OrdinalIgnoreCase)) - { - return Result.Err( - RimMindErrors.ClientTransient($"Upstream generation interrupted (finish_reason={finishReason}).")); - } - - string? toolCallsJson = null; - var toolCalls = message["tool_calls"] as JArray; - if (toolCalls != null && toolCalls.Count > 0) - { - var wireList = new List(toolCalls.Count); - foreach (var tc in toolCalls) - { - string? rawId = AsString(tc["id"]); - string id = !string.IsNullOrEmpty(rawId) ? rawId! : Guid.NewGuid().ToString("N"); - string? rawType = AsString(tc["type"]); - string type = !string.IsNullOrEmpty(rawType) ? rawType! : "function"; - string name = AsString(tc["function"]?["name"]) ?? ""; - var argsToken = tc["function"]?["arguments"]; - string arguments = argsToken == null || argsToken.Type == JTokenType.Null - ? "{}" - : argsToken.Type == JTokenType.String - ? argsToken.ToString() - : argsToken.ToString(Formatting.None); - wireList.Add(new - { - id = id, - type = type, - function = new - { - name = name, - arguments = arguments - } - }); - } - toolCallsJson = JsonConvert.SerializeObject(wireList); - } - - bool expectsTools = envelope?.Tools != null && envelope.Tools.Count > 0; - if (!expectsTools && - !string.Equals(finishReason, "length", StringComparison.OrdinalIgnoreCase) && - string.IsNullOrWhiteSpace(content) && - toolCallsJson == null && - !string.IsNullOrWhiteSpace(reasoningContent)) - { - content = reasoningContent!; - } - - // Some providers (e.g. json_object validation failure) replace non-JSON output with spaces (U+0020) - if (toolCallsJson == null && - content.Length > 0 && - string.IsNullOrWhiteSpace(content) && - string.IsNullOrWhiteSpace(reasoningContent)) - { - return Result.Err( - RimMindErrors.ClientTransient("Upstream returned whitespace-only content.")); - } - - var usage = token["usage"]; - int promptTokens = AsInt(usage?["prompt_tokens"]) ?? 0; - int completionTokens = AsInt(usage?["completion_tokens"]) ?? 0; - int totalTokens = AsInt(usage?["total_tokens"]) ?? (promptTokens + completionTokens); - int cachedTokens = AsInt(usage?["prompt_tokens_details"]?["cached_tokens"]) - ?? AsInt(usage?["prompt_cache_hit_tokens"]) - ?? 0; - - var llmResponse = new LlmResponse - { - RequestId = AsString(token["id"]) ?? Guid.NewGuid().ToString("N"), - Content = content, - ReasoningContent = reasoningContent, - ToolCallsJson = toolCallsJson, - PromptTokens = promptTokens, - CompletionTokens = completionTokens, - CachedTokens = cachedTokens, - TokensUsed = totalTokens - }; - - return Result.Ok(llmResponse); - } - catch (Exception ex) - { - return Result.Err( - RimMindErrors.ClientPermanent($"Failed to parse OpenAI response: {LogSanitizer.ForLog(ex.Message)}")); - } - } + => OpenAIWireCodec.ParseResponse(responseBody, envelope); internal static ResponseFormatDto? BuildResponseFormat( LlmRequestEnvelope envelope, @@ -454,20 +253,5 @@ public static bool TryParseJson(string? value, out object? parsed) return null; } } - -#pragma warning disable IDE1006 - private sealed class WireRequestDto - { - public string model = ""; - public List? messages; - public int? max_tokens; - public float temperature; - public bool stream; - public StreamOptionsDto? stream_options; - public ResponseFormatDto? response_format; - public List? tools; - public object? tool_choice; - } -#pragma warning restore IDE1006 } } diff --git a/Source/Infrastructure/Services/Clients/OpenAI/OpenCodeHeaderDecorator.cs b/Source/Infrastructure/Services/Clients/OpenAI/OpenCodeHeaderDecorator.cs new file mode 100644 index 00000000..c72a007d --- /dev/null +++ b/Source/Infrastructure/Services/Clients/OpenAI/OpenCodeHeaderDecorator.cs @@ -0,0 +1,40 @@ +using System; +using System.Net.Http; + +namespace RimMind.Infrastructure.Services.Clients.OpenAI +{ + /// + /// Concrete OpenCode Go gateway header decorator (attaches x-opencode-session + /// when targeting OpenCode endpoints or oc_sk_ keys). Kept strictly inside the + /// concrete OpenAI client adapter directory so generic transport stays vendor-free. + /// + internal sealed class OpenCodeHeaderDecorator : IHttpRequestDecorator + { + public static readonly OpenCodeHeaderDecorator Instance = new OpenCodeHeaderDecorator(); + + public string Id => "core.opencode_session_header"; + + public static bool Matches(string? url, string? authOrKey) + { + if (!string.IsNullOrEmpty(url) && url!.IndexOf("opencode", StringComparison.OrdinalIgnoreCase) >= 0) + return true; + if (!string.IsNullOrEmpty(authOrKey) && authOrKey!.IndexOf("oc_sk_", StringComparison.OrdinalIgnoreCase) >= 0) + return true; + return false; + } + + public void Decorate(HttpRequestMessage request, string? url, string? authHeader, string? customSessionId = null) + { + if (request == null) return; + if (!Matches(url, authHeader)) return; + + if (!request.Headers.Contains("x-opencode-session")) + { + string sessionId = !string.IsNullOrEmpty(customSessionId) + ? customSessionId! + : "rimmind-" + Guid.NewGuid().ToString("N").Substring(0, 12); + request.Headers.TryAddWithoutValidation("x-opencode-session", sessionId); + } + } + } +} diff --git a/Source/Infrastructure/Services/Clients/Shared/ClientExceptionMapper.cs b/Source/Infrastructure/Services/Clients/Shared/ClientExceptionMapper.cs index 06e1d6d4..e5775d25 100644 --- a/Source/Infrastructure/Services/Clients/Shared/ClientExceptionMapper.cs +++ b/Source/Infrastructure/Services/Clients/Shared/ClientExceptionMapper.cs @@ -4,6 +4,7 @@ using System.Threading; using System.Threading.Tasks; using RimMind.Application.Common.Interfaces.Abstractions; +using RimMind.Application.Features.Llm; using RimMind.Domain.Llm; using RimMind.Domain.ValueObjects; @@ -88,34 +89,13 @@ public static Result MapException( /// 401/402/403 and quota/auth keywords are permanent; 408/429/5xx and rate-limit/queue keywords are transient. /// internal static bool IsTransientHttpFailure(HttpTransport.HttpException httpEx) - { - string msg = httpEx.ClassificationText; - bool isRateLimitOrQueue = - msg.IndexOf("rate_limit", StringComparison.OrdinalIgnoreCase) >= 0 || - msg.IndexOf("concurrency_limit", StringComparison.OrdinalIgnoreCase) >= 0 || - msg.IndexOf("queue_full", StringComparison.OrdinalIgnoreCase) >= 0 || - msg.IndexOf("Too many pending requests", StringComparison.OrdinalIgnoreCase) >= 0; - bool isPermanentQuotaOrAuth = - httpEx.StatusCode == 401 || - httpEx.StatusCode == 402 || - httpEx.StatusCode == 403 || - msg.IndexOf("Insufficient account funds", StringComparison.OrdinalIgnoreCase) >= 0 || - msg.IndexOf("insufficient_quota", StringComparison.OrdinalIgnoreCase) >= 0 || - msg.IndexOf("invalid_api_key", StringComparison.OrdinalIgnoreCase) >= 0; - return !isPermanentQuotaOrAuth && - (httpEx.StatusCode == 408 || httpEx.StatusCode == 429 || httpEx.StatusCode >= 500 || isRateLimitOrQueue); - } + => HttpErrorClassifier.IsTransientHttpFailure(httpEx.StatusCode, httpEx.ClassificationText); internal static bool IsContentModerationResponse(int statusCode, string? responseBody) - { - return statusCode == 400 && - !string.IsNullOrEmpty(responseBody) && - (responseBody!.IndexOf("Content Exists Risk", StringComparison.OrdinalIgnoreCase) >= 0 || - responseBody.IndexOf("content_filter", StringComparison.OrdinalIgnoreCase) >= 0); - } + => HttpErrorClassifier.IsContentModerationResponse(statusCode, responseBody); internal static bool IsContentFilteredHttpFailure(Exception? ex) => ex is HttpTransport.HttpException httpEx && - IsContentModerationResponse(httpEx.StatusCode, httpEx.ClassificationText); + HttpErrorClassifier.IsContentModerationResponse(httpEx.StatusCode, httpEx.ClassificationText); } } diff --git a/Source/Infrastructure/Services/Clients/Shared/LogSanitizer.cs b/Source/Infrastructure/Services/Clients/Shared/LogSanitizer.cs index a9c0a0a7..ff90c592 100644 --- a/Source/Infrastructure/Services/Clients/Shared/LogSanitizer.cs +++ b/Source/Infrastructure/Services/Clients/Shared/LogSanitizer.cs @@ -1,75 +1,21 @@ -using System; -using System.Text.RegularExpressions; +using RimMind.Application.Features.Llm; namespace RimMind.Infrastructure.Services.Clients.Shared { /// - /// Log hygiene for transport diagnostics: truncates provider payloads and - /// redacts anything that looks like a credential before it reaches a log sink - /// or an exception message. + /// Backwards-compatible forwarding facade delegating to . + /// Extension modules should call or RimMindAPI.Diagnostics. /// public static class LogSanitizer { - /// Default cap for provider error bodies embedded in messages and logs. - public const int DefaultMaxChars = 500; + public const int DefaultMaxChars = LogSecretRedactor.DefaultMaxChars; + public const int DebugPayloadMaxChars = LogSecretRedactor.DebugPayloadMaxChars; - /// Cap for request/response JSON echoed when DebugLogging is enabled. - public const int DebugPayloadMaxChars = 2000; - - private const string Mask = "***"; - - private static readonly Regex BearerPattern = new Regex( - @"(?i)\b(Bearer|Basic)\s+[A-Za-z0-9\-\._~\+\/=:]{4,}", - RegexOptions.Compiled); - - private static readonly Regex KeyValuePattern = new Regex( - @"(?i)(""?(?Redacts bearer tokens, key/value secrets and well-known API-key shapes. - public static string Redact(string? text) - { - if (string.IsNullOrEmpty(text)) return text ?? string.Empty; - string result = BearerPattern.Replace(text, m => m.Groups[1].Value + " " + Mask); - result = KeyValuePattern.Replace(result, m => m.Groups[1].Value + Mask); - result = KeyPrefixPattern.Replace(result, Mask); - return result; - } - - /// Truncates to characters, appending a marker with the original length. - public static string Truncate(string? text, int maxChars = DefaultMaxChars) - { - if (string.IsNullOrEmpty(text)) return text ?? string.Empty; - if (maxChars <= 0 || text!.Length <= maxChars) return text!; - return text.Substring(0, maxChars) + $"…[truncated {text.Length - maxChars} chars]"; - } - - /// Redacts then truncates; the standard treatment for anything that may be logged. - public static string ForLog(string? text, int maxChars = DefaultMaxChars) - { - return Truncate(Redact(text), maxChars); - } - - /// Redacts then truncates; alias for used for diagnostic/error messages. - public static string ForMessage(string? text, int maxChars = DefaultMaxChars) - { - return ForLog(text, maxChars); - } - - /// - /// Redacts and additionally masks a literal configured secret - /// (when at least 4 characters long) that may not match any generic key shape. - /// + public static string Redact(string? text) => LogSecretRedactor.Redact(text); + public static string Truncate(string? text, int maxChars = DefaultMaxChars) => LogSecretRedactor.Truncate(text, maxChars); + public static string ForLog(string? text, int maxChars = DefaultMaxChars) => LogSecretRedactor.ForLog(text, maxChars); + public static string ForMessage(string? text, int maxChars = DefaultMaxChars) => LogSecretRedactor.ForMessage(text, maxChars); public static string ForMessageWithSecret(string? text, string? literalSecret, int maxLength = 320) - { - string value = text ?? string.Empty; - if (!string.IsNullOrEmpty(literalSecret) && literalSecret!.Length >= 4) - value = value.Replace(literalSecret, Mask); - return ForLog(value, maxLength); - } + => LogSecretRedactor.ForMessageWithSecret(text, literalSecret, maxLength); } } diff --git a/Source/Infrastructure/UI/AgentsPage/AgentDetailPanelDrawer.cs b/Source/Infrastructure/UI/AgentsPage/AgentDetailPanelDrawer.cs index 8c6715e8..0f7a0faf 100644 --- a/Source/Infrastructure/UI/AgentsPage/AgentDetailPanelDrawer.cs +++ b/Source/Infrastructure/UI/AgentsPage/AgentDetailPanelDrawer.cs @@ -383,6 +383,6 @@ private static string DomainTooltip(RimMind.Domain.Agent.Policies.AutonomyDomain }; private static string SafeTranslate(string key, string fallback) - => key.CanTranslate() ? key.Translate().ToString() : fallback; + => RimMind.Presentation.Api.RimMindText.TrOr(key, fallback); } } diff --git a/Source/Infrastructure/UI/DebugActions/TenDayPlaythroughRunner.cs b/Source/Infrastructure/UI/DebugActions/TenDayPlaythroughRunner.cs index 598e29f2..aefd9bd7 100644 --- a/Source/Infrastructure/UI/DebugActions/TenDayPlaythroughRunner.cs +++ b/Source/Infrastructure/UI/DebugActions/TenDayPlaythroughRunner.cs @@ -220,8 +220,6 @@ private sealed class PlaythroughCoroutineHost : MonoBehaviour private SettingsOverrideScope? _settingsScope; private readonly HashSet _processedTraceRequestIds = new(StringComparer.Ordinal); - private readonly HashSet _seenTraceSources = new(StringComparer.OrdinalIgnoreCase); - private readonly Dictionary _lastSystemPromptBySource = new(StringComparer.OrdinalIgnoreCase); private readonly List _approvedOverlayItems = new(); private int _totalLlmCalls; private int _successfulLlmCalls; @@ -962,46 +960,16 @@ private void CollectTraceLogMetrics(PlaythroughDayReport dayReport) _report.LlmCallsBySource.TryGetValue(sourceKey, out int totalSrcCount); _report.LlmCallsBySource[sourceKey] = totalSrcCount + 1; - if (tokens > 0) + int promptTokens = Math.Max(0, entry.PromptTokens); + int cachedTokens = Math.Max(0, entry.CachedTokens); + if (promptTokens > 0) { - int sysChars = entry.SystemPrompt?.Length ?? 0; - int userChars = (entry.UserPrompt?.Length ?? 0) + (entry.AssistantPrompt?.Length ?? 0); - int respChars = entry.Response?.Length ?? 0; - int totalPromptChars = sysChars + userChars; - - int promptTokens = (totalPromptChars + respChars) > 0 - ? Math.Max(1, (int)Math.Round(tokens * ((double)totalPromptChars / Math.Max(1, totalPromptChars + respChars)))) - : Math.Max(1, (int)Math.Round(tokens * 0.78)); - + if (cachedTokens > promptTokens) + cachedTokens = promptTokens; dayPromptTokens += promptTokens; _totalPromptTokens += promptTokens; - - string curSysPrompt = entry.SystemPrompt ?? string.Empty; - bool isSubsequentInSource = !_seenTraceSources.Add(sourceKey); - if (isSubsequentInSource) - { - double prefixRatio = 0.60; - if (!string.IsNullOrEmpty(curSysPrompt) && - _lastSystemPromptBySource.TryGetValue(sourceKey, out string? prevSysPrompt) && - !string.IsNullOrEmpty(prevSysPrompt)) - { - int commonLen = ComputeCommonPrefixLength(prevSysPrompt!, curSysPrompt); - if (commonLen > 0 && totalPromptChars > 0) - { - double sysShare = (double)commonLen / totalPromptChars; - prefixRatio = Math.Clamp(Math.Max(0.60, sysShare), 0.60, 0.85); - } - } - - int entryPrefixTokens = (int)Math.Round(promptTokens * prefixRatio); - dayPrefixTokens += entryPrefixTokens; - _totalPrefixTokens += entryPrefixTokens; - } - - if (!string.IsNullOrEmpty(curSysPrompt)) - { - _lastSystemPromptBySource[sourceKey] = curSysPrompt; - } + dayPrefixTokens += cachedTokens; + _totalPrefixTokens += cachedTokens; } } @@ -1016,17 +984,6 @@ private void CollectTraceLogMetrics(PlaythroughDayReport dayReport) } } - private static int ComputeCommonPrefixLength(string a, string b) - { - int minLen = Math.Min(a.Length, b.Length); - int i = 0; - while (i < minLen && a[i] == b[i]) - { - i++; - } - return i; - } - private static void CollectRealAgentActions( List colonists, int dayStartTick, @@ -1036,13 +993,18 @@ private static void CollectRealAgentActions( try { var actionsToday = new List<(string PawnName, BehaviorRecord Record)>(); - foreach (var pawn in colonists) + var visitedPawnIds = new HashSet(); + + void CollectFromPawn(Pawn? pawn) { + if (pawn == null || pawn.thingIDNumber <= 0 || !visitedPawnIds.Add(pawn.thingIDNumber)) + return; + var agent = CompPawnAgent.GetComp(pawn)?.Agent; - if (agent == null) continue; + if (agent == null) return; var history = agent.GetRecentHistory(50); - if (history == null) continue; + if (history == null) return; string pawnName = pawn.Name?.ToStringShort ?? "Colonist"; for (int i = 0; i < history.Count; i++) @@ -1055,6 +1017,30 @@ private static void CollectRealAgentActions( } } + foreach (var pawn in colonists) + { + CollectFromPawn(pawn); + } + + // Also include colonists who died later during the day (corpses on loaded maps) + // so their executed actions are never dropped from the daily audit. + var maps = Find.Maps; + if (maps != null) + { + for (int m = 0; m < maps.Count; m++) + { + var corpses = maps[m]?.listerThings?.ThingsInGroup(ThingRequestGroup.Corpse); + if (corpses == null) continue; + for (int c = 0; c < corpses.Count; c++) + { + if (corpses[c] is Corpse corpse && corpse.InnerPawn is Pawn inner && inner.IsColonist) + { + CollectFromPawn(inner); + } + } + } + } + actionsToday.Sort((a, b) => a.Record.Timestamp.CompareTo(b.Record.Timestamp)); dayReport.AgentActionsExecutedCount = actionsToday.Count; @@ -1463,45 +1449,12 @@ private void ExportDailyStateJson(int day, PlaythroughDayReport report, Map? map { try { - int woodCount = map?.resourceCounter?.GetCount(ThingDefOf.WoodLog) ?? 0; - int steelCount = map?.resourceCounter?.GetCount(ThingDefOf.Steel) ?? 0; - int mealsCount = (map?.resourceCounter?.GetCount(ThingDefOf.MealSimple) ?? 0) - + (map?.resourceCounter?.GetCount(ThingDefOf.MealFine) ?? 0) - + (map?.resourceCounter?.GetCount(ThingDefOf.MealSurvivalPack) ?? 0); - float totalNutrition = map?.resourceCounter?.TotalHumanEdibleNutrition ?? 0f; - if (map?.listerThings != null && (mealsCount == 0 || totalNutrition <= 0.01f)) - { - var edibles = map.listerThings.ThingsInGroup(ThingRequestGroup.FoodSourceNotPlantOrTree); - if (edibles != null) - { - int mapMeals = 0; - float mapNut = 0f; - for (int i = 0; i < edibles.Count; i++) - { - var item = edibles[i]; - if (item == null || item.Destroyed || !item.Spawned || item is Corpse || item is Pawn) - continue; - if (item.Position.Fogged(map) || item.IsForbidden(Faction.OfPlayer)) - continue; - if (item.def?.ingestible == null || !item.def.IsNutritionGivingIngestible || !item.def.ingestible.HumanEdible) - continue; - if (item.def.ingestible.drugCategory != DrugCategory.None || item.def.ingestible.preferability < FoodPreferability.RawBad) - continue; - - float nutPerUnit = item.GetStatValue(StatDefOf.Nutrition); - if (nutPerUnit > 0f) - { - mapNut += nutPerUnit * Math.Max(1, item.stackCount); - } - if (item.def == ThingDefOf.MealSimple || item.def == ThingDefOf.MealFine || item.def == ThingDefOf.MealSurvivalPack) - { - mapMeals += Math.Max(1, item.stackCount); - } - } - if (mapMeals > mealsCount) mealsCount = mapMeals; - if (mapNut > totalNutrition) totalNutrition = mapNut; - } - } + int woodCount = MapResourceCounter.GetAvailableCount(map, ThingDefOf.WoodLog); + int steelCount = MapResourceCounter.GetAvailableCount(map, ThingDefOf.Steel); + int mealsCount = MapResourceCounter.GetAvailableCount(map, ThingDefOf.MealSimple) + + MapResourceCounter.GetAvailableCount(map, ThingDefOf.MealFine) + + MapResourceCounter.GetAvailableCount(map, ThingDefOf.MealSurvivalPack); + float totalNutrition = MapResourceCounter.GetAvailableFoodNutrition(map); int blueprintsCount = map?.listerThings?.ThingsInGroup(ThingRequestGroup.Blueprint)?.Count ?? 0; int framesCount = map?.listerThings?.ThingsInGroup(ThingRequestGroup.BuildingFrame)?.Count ?? 0; int buildingsCount = map?.listerBuildings?.allBuildingsColonist?.Count ?? 0; diff --git a/Source/Infrastructure/UI/DebugCenter/Pages/AIRequestsDebugCenterPageDrawer.cs b/Source/Infrastructure/UI/DebugCenter/Pages/AIRequestsDebugCenterPageDrawer.cs index 78ecd879..121fb05d 100644 --- a/Source/Infrastructure/UI/DebugCenter/Pages/AIRequestsDebugCenterPageDrawer.cs +++ b/Source/Infrastructure/UI/DebugCenter/Pages/AIRequestsDebugCenterPageDrawer.cs @@ -899,7 +899,7 @@ private static string StateLabelFor(AIRequestTraceState state) }; private static string SafeTranslate(string key, string fallback) - => key.CanTranslate() ? key.Translate().ToString() : fallback; + => RimMindText.TrOr(key, fallback); private sealed record DetailBlock( string Key, diff --git a/Source/Infrastructure/UI/DebugCenter/Pages/CapabilitiesDebugCenterPageDrawer.cs b/Source/Infrastructure/UI/DebugCenter/Pages/CapabilitiesDebugCenterPageDrawer.cs index f0e9e4d2..808ac973 100644 --- a/Source/Infrastructure/UI/DebugCenter/Pages/CapabilitiesDebugCenterPageDrawer.cs +++ b/Source/Infrastructure/UI/DebugCenter/Pages/CapabilitiesDebugCenterPageDrawer.cs @@ -297,7 +297,7 @@ private void DrawToolDetail(Rect rect, ToolDefinition def) } private static string SafeTranslate(string key, string fallback) - => key.CanTranslate() ? key.Translate().ToString() : fallback; + => RimMindText.TrOr(key, fallback); private sealed class CompositeDisposable : IDisposable { diff --git a/Source/Infrastructure/UI/DebugTables/DebugTableModels.cs b/Source/Infrastructure/UI/DebugTables/DebugTableModels.cs index 87e296c8..318f3a4c 100644 --- a/Source/Infrastructure/UI/DebugTables/DebugTableModels.cs +++ b/Source/Infrastructure/UI/DebugTables/DebugTableModels.cs @@ -142,10 +142,10 @@ public static DebugTableModel MixedRequests() "AI Requests", new[] { - DebugTableRow.Create("req-001", DebugTableStatus.Waiting, "10:00", "Pawn", "Nickie", "chat", "deepseek-flash", "Queued for context build", "0ms"), + DebugTableRow.Create("req-001", DebugTableStatus.Waiting, "10:00", "Pawn", "Nickie", "chat", "gpt-4o-mini", "Queued for context build", "0ms"), DebugTableRow.Create("req-002", DebugTableStatus.Streaming, "10:01", "Pawn", "Tynan", "advisor", "gpt-4.1-mini", "Streaming 3 chunks", "1.2s"), - DebugTableRow.Create("req-003", DebugTableStatus.Completed, "10:02", "Colony", "Workbench", "memory", "deepseek-flash", "Completed ToolCall summary: choose_repair_target", "2.4s"), - DebugTableRow.Create("req-004", DebugTableStatus.Failed, "10:03", "Pawn", "Maya", "chat", "deepseek-flash", "HTTP timeout after retry", "5s") + DebugTableRow.Create("req-003", DebugTableStatus.Completed, "10:02", "Colony", "Workbench", "memory", "gpt-4o-mini", "Completed ToolCall summary: choose_repair_target", "2.4s"), + DebugTableRow.Create("req-004", DebugTableStatus.Failed, "10:03", "Pawn", "Maya", "chat", "gpt-4o-mini", "HTTP timeout after retry", "5s") }); } diff --git a/Source/Infrastructure/UI/RequestOverlay.cs b/Source/Infrastructure/UI/RequestOverlay.cs index e1908e5c..8d98dc25 100644 --- a/Source/Infrastructure/UI/RequestOverlay.cs +++ b/Source/Infrastructure/UI/RequestOverlay.cs @@ -42,7 +42,7 @@ public static class RequestOverlay private static readonly List CachedHeights = new List(); private static string Tr(string key, string fallback) - => key.CanTranslate() ? key.Translate().ToString() : fallback; + => RimMind.Presentation.Api.RimMindText.TrOr(key, fallback); private static string PendingCount0Label => _cachedPendingCount0 ??= "RimMind.UI.RequestOverlay.PendingCount".CanTranslate() @@ -177,6 +177,16 @@ public static void OnGUI() bool isCollapsed = !_isExpanded; + if (RequestOverlayLayoutEvaluator.ShouldHideCompletely( + pending.Count, + autoHide, + _isExpanded, + _isDragging, + _isResizing)) + { + return; + } + if (!isCollapsed) { float maxAllowedWidth = Mathf.Max(MinWidth, global::Verse.UI.screenWidth - AlertsMargin); diff --git a/Source/Infrastructure/UI/Window_ContextKeyDebug.cs b/Source/Infrastructure/UI/Window_ContextKeyDebug.cs index 13756e84..bde0bc28 100644 --- a/Source/Infrastructure/UI/Window_ContextKeyDebug.cs +++ b/Source/Infrastructure/UI/Window_ContextKeyDebug.cs @@ -331,13 +331,15 @@ private void DrawKeyDetail(Rect rect, IReadOnlyList keys, RimMindLayout { string[] scenarios = { RimMindAPI.Context.ScenarioDecision, + RimMind.Application.Common.Models.Context.ScenarioIds.AgentDecision, + RimMind.Application.Common.Models.Context.ScenarioIds.AdvisorDecision, RimMindAPI.Context.ScenarioDialogue, RimMindAPI.Context.ScenarioPersonality, RimMindAPI.Context.ScenarioStoryteller, RimMindAPI.Context.ScenarioMemory }; string[] scenarioLabels = { - "Decision", "Dialogue", "Personality", "Storyteller", "Memory" + "Decision", "AgentDecision", "AdvisorDecision", "Dialogue", "Personality", "Storyteller", "Memory" }; var relevanceParts = new List(); diff --git a/Source/Infrastructure/UI/Window_ContextPayloadInspector.cs b/Source/Infrastructure/UI/Window_ContextPayloadInspector.cs index f308a312..bd8e9114 100644 --- a/Source/Infrastructure/UI/Window_ContextPayloadInspector.cs +++ b/Source/Infrastructure/UI/Window_ContextPayloadInspector.cs @@ -12,6 +12,7 @@ using RimMind.Application.Common.Models.Pipeline; using RimMind.Application.Common.Models.Tools; using RimMind.Application.Features.Agent.Modes; +using RimMind.Application.Features.Context; using RimMind.Domain.Common; using RimMind.Domain.Enums; using RimMind.Domain.Llm; @@ -40,23 +41,54 @@ public class Window_ContextPayloadInspector : RimMindWindowBase private Vector2 _pawnListScroll = Vector2.zero; private Vector2 _contentScroll = Vector2.zero; - private static readonly string[] Scenarios = new[] + private List<(string Id, string Label)> _scenarios = new(); + + private IReadOnlyList<(string Id, string Label)> GetScenarios() { - ScenarioIds.Decision, - ScenarioIds.Dialogue, - ScenarioIds.CrisisDialogue, - ScenarioIds.Personality, - ScenarioIds.Memory - }; + if (_scenarios.Count == 0) + { + RefreshScenarios(); + } + return _scenarios; + } - private static readonly string[] ScenarioLabels = new[] + private void RefreshScenarios() { - "Decision", - "Dialogue", - "CrisisDialogue", - "Personality", - "DarkMemory" - }; + _scenarios.Clear(); + var registered = ScenarioRegistry.GetAll(); + if (registered != null && registered.Count > 0) + { + foreach (var entry in registered.OrderBy(e => e.Id, StringComparer.OrdinalIgnoreCase)) + { + if (entry == null || string.IsNullOrWhiteSpace(entry.Id)) continue; + string label = string.IsNullOrWhiteSpace(entry.Description) + ? entry.Id + : $"{entry.Id} ({entry.Description})"; + _scenarios.Add((entry.Id, label)); + } + } + + if (_scenarios.Count == 0) + { + _scenarios.Add((ScenarioIds.AgentDecision, "Agent Decision")); + _scenarios.Add((ScenarioIds.Decision, "Decision")); + } + + if (_selectedScenarioIndex < 0 || _selectedScenarioIndex >= _scenarios.Count) + { + _selectedScenarioIndex = 0; + } + } + + private (string Id, string Label) CurrentScenario + { + get + { + var list = GetScenarios(); + int idx = Math.Clamp(_selectedScenarioIndex, 0, list.Count - 1); + return list[idx]; + } + } private static readonly string[] Tabs = new[] { @@ -167,13 +199,16 @@ private void DrawHeader(Rect rect) Widgets.Label(scenLabelRect, "RimMind.Inspector.ScenarioLabel".Translate()); Rect scenBtnRect = new Rect(selX + 80f, rect.y + 6f, 250f, 26f); - if (Widgets.ButtonText(scenBtnRect, ScenarioLabels[_selectedScenarioIndex])) + var scenarios = GetScenarios(); + if (Widgets.ButtonText(scenBtnRect, CurrentScenario.Label)) { + RefreshScenarios(); + scenarios = GetScenarios(); var options = new List(); - for (int i = 0; i < ScenarioLabels.Length; i++) + for (int i = 0; i < scenarios.Count; i++) { int index = i; - options.Add(new FloatMenuOption(ScenarioLabels[index], () => + options.Add(new FloatMenuOption(scenarios[index].Label, () => { _selectedScenarioIndex = index; RebuildEnvelope(); @@ -409,7 +444,7 @@ private void DrawBottomBar(Rect rect) private void CopyFullPayloadToClipboard() { StringBuilder sb = new StringBuilder(); - sb.AppendLine($"# RimMind LLM Request Envelope (Pawn: {_selectedPawn?.LabelCap}, Scenario: {ScenarioLabels[_selectedScenarioIndex]})"); + sb.AppendLine($"# RimMind LLM Request Envelope (Pawn: {_selectedPawn?.LabelCap}, Scenario: {CurrentScenario.Label})"); sb.AppendLine(); sb.AppendLine("## 1. System Prompt"); sb.AppendLine("```"); @@ -467,7 +502,7 @@ private void RebuildEnvelope() _cachedScenarioIndex = _selectedScenarioIndex; if (_selectedPawn == null) return; - string scenario = Scenarios[_selectedScenarioIndex]; + string scenario = CurrentScenario.Id; var tools = RimMindAPI.Tools.GetAllDefinitions().ToList(); // 1. Build System Prompt & Rules diff --git a/Source/Presentation/Agent/GameContextBuilder.cs b/Source/Presentation/Agent/GameContextBuilder.cs index 3e13d84e..972d1afa 100644 --- a/Source/Presentation/Agent/GameContextBuilder.cs +++ b/Source/Presentation/Agent/GameContextBuilder.cs @@ -62,6 +62,10 @@ public string CollectBasicGameState(string npcId) public string BuildMapContextInstance(object map, bool brief = false) => map is Map m ? _mapBuilder.BuildMapContext(m, brief) : ""; + public string BuildStaticMapTopology(Map map) => _mapBuilder.BuildStaticMapTopology(map); + + public string BuildVolatileColonyResources(Map map) => _mapBuilder.BuildVolatileColonyResources(map); + // --- IContextKeyProvider --- public List BuildMapContextEntries(object map) diff --git a/Source/Presentation/Agent/MapContextBuilder.cs b/Source/Presentation/Agent/MapContextBuilder.cs index 909591f8..2abd6f0a 100644 --- a/Source/Presentation/Agent/MapContextBuilder.cs +++ b/Source/Presentation/Agent/MapContextBuilder.cs @@ -5,7 +5,10 @@ using System.Linq; using System.Runtime.CompilerServices; using System.Text; +using RimMind.Application.Common.Constants; +using RimMind.Application.Common.Interfaces.Extension; using RimMind.Application.Common.Interfaces.Internal; +using RimMind.Application.Common.Models; using RimMind.Application.Common.Models.Context; using RimMind.Application.Common.Models.Prompt; using RimMind.Application.Features.Context; @@ -29,9 +32,6 @@ public sealed class MapContextBuilder private const long TicksPerDay = 60000L; private const int CacheStalenessTicks = 60; private const long WarningCooldownSeconds = 30L; - private const float ThreatThresholdHigh = 200000f; - private const float ThreatThresholdMedium = 100000f; - private const float ThreatThresholdLow = 50000f; private static readonly ConcurrentDictionary<(int settingsHash, int mapId, bool brief), (int tick, List entries)> _snapshotCache = new ConcurrentDictionary<(int settingsHash, int mapId, bool brief), (int tick, List entries)>(); @@ -49,6 +49,16 @@ public MapContextBuilder(IContextSettings? contextSettings = null) _contextSettings = contextSettings ?? new ContextSettings(); } + /// + /// Clears all static map snapshot caches (invoked on game start/stop via ). + /// + public static void ClearCaches() + { + _snapshotCache.Clear(); + _lastMainThreadSnapshot.Clear(); + _lastWarningTimestamp.Clear(); + } + private IMapIncludeSettings MapSettings => _contextSettings; private IColonyIncludeSettings ColonySettings => _contextSettings; @@ -72,15 +82,112 @@ private static void WarnRateLimited(string area, Exception ex) } } - private static string Tr(string key, params object[] args) + /// + /// Builds strictly static / semi-static map topology suitable for L1_Baseline (KV-Cache prefix-stable). + /// Contains ONLY biome/size, colony room layout, and static worktable roster — NO time, season, weather, + /// wealth, food storage, or volatile resource counts. + /// + public string BuildStaticMapTopology(Map? map) { + if (map == null || !UnityData.IsInMainThread) + return string.Empty; + + var sb = new StringBuilder(); try { - if (string.IsNullOrEmpty(key)) return string.Empty; - string template = key.CanTranslate() ? key.TranslateSimple() : key; - return (args == null || args.Length == 0) ? template : string.Format(template, args); + string biomeLabel = map.Biome?.label ?? map.Biome?.defName ?? "Unknown"; + sb.AppendLine($"Map Topology: Biome={biomeLabel}, Size={map.Size.x}x{map.Size.z}"); + } + catch (Exception ex) { WarnRateLimited("StaticTopologyHeader", ex); } + + if (map.listerBuildings != null) + { + AppendColonyRoomsSummary(map, sb); + try + { + var buildings = map.listerBuildings.allBuildingsColonist; + if (buildings != null && buildings.Count > 0) + { + var worktables = new List(); + for (int i = 0; i < buildings.Count; i++) + { + var b = buildings[i]; + if (b is Building_WorkTable wt && wt.def != null && !wt.Destroyed) + { + var recipes = wt.def.AllRecipes? + .Take(3) + .Select(r => r.defName) + .ToList(); + string recipeStr = (recipes != null && recipes.Count > 0) ? string.Join("/", recipes) : "None"; + string tableName = wt.def.label ?? wt.def.defName; + worktables.Add($"{tableName}(id={wt.thingIDNumber}, recipes=[{recipeStr}])"); + if (worktables.Count >= 4) break; + } + } + + if (worktables.Count > 0) + { + sb.AppendLine($"WorktableRoster: [{string.Join("; ", worktables)}]"); + } + } + } + catch (Exception ex) { WarnRateLimited("StaticWorktableRoster", ex); } } - catch { return key ?? string.Empty; } + + return sb.ToString().TrimEnd(); + } + + /// + /// Builds volatile colony resource and operational status suitable for L2_Environment. + /// Keeps dynamic wealth, food, key resources, pending construction, worktable bill/fuel status, + /// and stored apparel out of L1_Baseline so KV-Cache prefixes remain stable. + /// + public string BuildVolatileColonyResources(Map? map) + { + if (map == null || !UnityData.IsInMainThread) + return string.Empty; + + var colony = ColonySettings; + var sb = new StringBuilder(); + + if (colony.IncludeWealth) + { + try + { + float wealth = map.wealthWatcher?.WealthTotal ?? 0f; + string threat = ThreatLabel(wealth); + sb.AppendLine(RimMindText.Tr("RimMind.Prompt.WealthWithThreat", $"{wealth:F0}", threat)); + } + catch (Exception ex) { WarnRateLimited("VolatileWealth", ex); } + } + + if (colony.IncludeFood) + { + float foodNutrition = MapResourceCounter.GetAvailableFoodNutrition(map); + sb.AppendLine(RimMindText.Tr("RimMind.Prompt.FoodStorage", $"{foodNutrition:F0}")); + + int wood = MapResourceCounter.GetAvailableCount(map, ThingDefOf.WoodLog); + int steel = MapResourceCounter.GetAvailableCount(map, ThingDefOf.Steel); + int med = CountAvailableMedicine(map); + sb.AppendLine(RimMindText.TrOr( + "RimMind.Prompt.KeyResources", + "Key Resources: Wood {0}, Steel {1}, Medicine {2}", + wood, steel, med)); + + int totalPending = CountPendingConstruction(map); + if (totalPending > 0) + { + sb.AppendLine(RimMindText.TrOr( + "RimMind.Prompt.PendingConstruction", + "Pending Construction: {0} blueprints/frames", + totalPending)); + } + + AppendWorktableStatus(map, sb); + AppendStoredApparelSummary(map, sb); + } + + return sb.ToString().TrimEnd(); } public string BuildMapContext(Map map, bool brief = false) @@ -128,7 +235,7 @@ public List BuildMapContextEntries(Map map, bool brief = false) var ctx = MapSettings; var colony = ColonySettings; - entries.Add(new ContextEntry(Tr("RimMind.Prompt.MapStatusHeader"))); + entries.Add(new ContextEntry(RimMindText.Tr("RimMind.Prompt.MapStatusHeader"))); if (ctx.IncludeGameTime) { @@ -138,7 +245,7 @@ public List BuildMapContextEntries(Map map, bool brief = false) string dateStr = GenDate.DateFullStringAt(ticks, longLat); int day = (int)(ticks / TicksPerDay); entries.Add(new ContextEntry( - Tr("RimMind.Prompt.TimeFormat", dateStr, $"{hour:D2}")) + RimMindText.Tr("RimMind.Prompt.TimeFormat", dateStr, $"{hour:D2}")) { Metadata = new Dictionary { @@ -158,11 +265,11 @@ public List BuildMapContextEntries(Map map, bool brief = false) { var names = colonists.Select(p => p.Name.ToStringShort); string nameList = string.Join(", ", names); - content = Tr("RimMind.Prompt.ColonistCount", count, nameList); + content = RimMindText.Tr("RimMind.Prompt.ColonistCount", count, nameList); } else { - content = Tr("RimMind.Prompt.ColonistCountBrief", count); + content = RimMindText.Tr("RimMind.Prompt.ColonistCountBrief", count); } entries.Add(new ContextEntry(content) { @@ -183,7 +290,7 @@ public List BuildMapContextEntries(Map map, bool brief = false) { var names = prisoners.Select(p => p.Name.ToStringShort); string nameList = string.Join(", ", names); - otherSb.AppendLine(Tr("RimMind.Prompt.PrisonerCount", prisoners.Count, nameList)); + otherSb.AppendLine(RimMindText.Tr("RimMind.Prompt.PrisonerCount", prisoners.Count, nameList)); } } @@ -193,7 +300,7 @@ public List BuildMapContextEntries(Map map, bool brief = false) { float wealth = map.wealthWatcher?.WealthTotal ?? 0f; string threat = ThreatLabel(wealth); - otherSb.AppendLine(Tr("RimMind.Prompt.WealthWithThreat", $"{wealth:F0}", threat)); + otherSb.AppendLine(RimMindText.Tr("RimMind.Prompt.WealthWithThreat", $"{wealth:F0}", threat)); } catch (Exception ex) { WarnRateLimited("Wealth", ex); } } @@ -204,190 +311,54 @@ public List BuildMapContextEntries(Map map, bool brief = false) { float wealth = map.wealthWatcher?.WealthTotal ?? 0f; string threat = ThreatLabel(wealth); - otherSb.AppendLine(Tr("RimMind.Prompt.ThreatLevel", threat)); + otherSb.AppendLine(RimMindText.Tr("RimMind.Prompt.ThreatLevel", threat)); } catch (Exception ex) { WarnRateLimited("Threats", ex); } } if (colony.IncludeFood) { - float foodNutrition = 0f; - try - { - foodNutrition = CountAvailableMapFoodNutrition(map); - } - catch (Exception ex) { WarnRateLimited("FoodNutrition", ex); } - otherSb.AppendLine(Tr("RimMind.Prompt.FoodStorage", $"{foodNutrition:F0}")); - - int wood = CountAvailableMapResource(map, ThingDefOf.WoodLog); - int steel = CountAvailableMapResource(map, ThingDefOf.Steel); - int med = 0; - try - { - var medThings = map.listerThings?.ThingsInGroup(ThingRequestGroup.Medicine); - if (medThings != null) - { - for (int i = 0; i < medThings.Count; i++) - { - var t = medThings[i]; - if (t != null && t.Spawned && !t.IsForbidden(Faction.OfPlayer)) - med += t.stackCount; - } - } - } - catch (Exception ex) { WarnRateLimited("Medicine", ex); } - string resKey = "RimMind.Prompt.KeyResources"; - otherSb.AppendLine(resKey.CanTranslate() - ? Tr(resKey, wood, steel, med) - : $"Key Resources: Wood {wood}, Steel {steel}, Medicine {med}"); - - int totalPending = 0; - try - { - int pendingBlueprints = map.listerThings?.ThingsInGroup(ThingRequestGroup.Blueprint)?.Count ?? 0; - int pendingFrames = map.listerThings?.ThingsInGroup(ThingRequestGroup.BuildingFrame)?.Count ?? 0; - totalPending = pendingBlueprints + pendingFrames; - } - catch (Exception ex) { WarnRateLimited("PendingConstruction", ex); } + float foodNutrition = MapResourceCounter.GetAvailableFoodNutrition(map); + otherSb.AppendLine(RimMindText.Tr("RimMind.Prompt.FoodStorage", $"{foodNutrition:F0}")); + + int wood = MapResourceCounter.GetAvailableCount(map, ThingDefOf.WoodLog); + int steel = MapResourceCounter.GetAvailableCount(map, ThingDefOf.Steel); + int med = CountAvailableMedicine(map); + otherSb.AppendLine(RimMindText.TrOr( + "RimMind.Prompt.KeyResources", + "Key Resources: Wood {0}, Steel {1}, Medicine {2}", + wood, steel, med)); + + int totalPending = CountPendingConstruction(map); if (totalPending > 0) { - string pendingKey = "RimMind.Prompt.PendingConstruction"; - otherSb.AppendLine(pendingKey.CanTranslate() - ? Tr(pendingKey, totalPending) - : $"Pending Construction: {totalPending} blueprints/frames (Shortage Notice: gather wood/minerals if materials are low)"); + otherSb.AppendLine(RimMindText.TrOr( + "RimMind.Prompt.PendingConstruction", + "Pending Construction: {0} blueprints/frames", + totalPending)); } if (!brief && map.listerBuildings != null) { AppendColonyRoomsSummary(map, otherSb); - var worktables = new List(); - try - { - var buildings = map.listerBuildings.allBuildingsColonist; - if (buildings != null) - { - for (int i = 0; i < buildings.Count; i++) - { - var b = buildings[i]; - if (b is Building_WorkTable wt && wt.def != null && !wt.Destroyed) - { - int billCount = wt.billStack?.Count ?? 0; - string activeBillsStr = ""; - if (billCount > 0 && wt.billStack?.Bills != null) - { - var activeBillNames = wt.billStack.Bills - .Where(bill => bill?.recipe != null && !bill.suspended) - .Select(bill => bill.recipe.defName) - .Distinct() - .ToList(); - if (activeBillNames.Count > 0) - activeBillsStr = $"[{string.Join("/", activeBillNames)}]"; - } - var recipes = wt.def.AllRecipes? - .Take(3) - .Select(r => r.defName) - .ToList(); - string recipeStr = (recipes != null && recipes.Count > 0) ? string.Join("/", recipes) : "None"; - string tableName = wt.def.label ?? wt.def.defName; - var blockReasons = new List(); - var refuelable = wt.GetComp(); - if (refuelable != null && !refuelable.HasFuel) - { - blockReasons.Add("0 WoodLog fuel — harvest trees/haul wood instead of adding bills"); - } - var powerComp = wt.GetComp(); - if (powerComp != null && !powerComp.PowerOn) - { - blockReasons.Add("unpowered"); - } - if (billCount > 0 && (wt.def.defName.Contains("Stove") || wt.def.defName.Contains("Campfire"))) - { - var rawCat = DefDatabase.GetNamedSilentFail("FoodRaw"); - var rawNutrition = (rawCat != null && map.resourceCounter != null) ? map.resourceCounter.GetCountIn(rawCat) : 0; - if (rawNutrition <= 0 && map.listerThings != null) - { - var foods = map.listerThings.ThingsInGroup(ThingRequestGroup.FoodSourceNotPlantOrTree); - if (foods != null) - { - for (int f = 0; f < foods.Count; f++) - { - var ft = foods[f]; - if (ft != null && ft.Spawned && !ft.IsForbidden(Faction.OfPlayer) - && ft.def?.thingCategories != null && rawCat != null - && ft.def.thingCategories.Any(c => c == rawCat || (c.Parents != null && c.Parents.Contains(rawCat)))) - { - rawNutrition += ft.stackCount; - } - } - } - } - if (rawNutrition <= 0) - { - blockReasons.Add("0 raw food available, harvest/hunt needed"); - } - } - string blockNotice = blockReasons.Count > 0 - ? $" [BLOCKED: {string.Join("; ", blockReasons)}]" - : ""; - worktables.Add($"{tableName}(id={wt.thingIDNumber}, bills={billCount}{activeBillsStr}{blockNotice}, recipes=[{recipeStr}])"); - if (worktables.Count >= 4) break; - } - } - } - } - catch (Exception ex) { WarnRateLimited("Worktables", ex); } - if (worktables.Count > 0) - { - string wtKey = "RimMind.Prompt.ColonyWorktables"; - string tableList = string.Join("; ", worktables); - otherSb.AppendLine(wtKey.CanTranslate() - ? Tr(wtKey, tableList) - : $"Worktables: [{tableList}] (Queue bills via actions_add_worktable_bill)"); - } + AppendWorktableStatus(map, otherSb); } if (!brief) { - try - { - var storageApparel = map.listerThings?.ThingsInGroup(ThingRequestGroup.Apparel); - if (storageApparel != null && storageApparel.Count > 0) - { - var apparelEntries = new List(); - for (int i = 0; i < storageApparel.Count; i++) - { - var a = storageApparel[i]; - if (a != null && a.Spawned && !a.IsForbidden(Faction.OfPlayer) && a.IsInAnyStorage() && a.def != null) - { - string itemLabel = a.def.label ?? a.def.defName; - int hpPct = a.MaxHitPoints > 0 ? Mathf.RoundToInt((float)a.HitPoints / a.MaxHitPoints * 100f) : 100; - apparelEntries.Add($"{itemLabel}(id={a.thingIDNumber}, hp={hpPct}%)"); - if (apparelEntries.Count >= 5) break; - } - } - if (apparelEntries.Count > 0) - { - string apKey = "RimMind.Prompt.StoredApparel"; - string apList = string.Join(", ", apparelEntries); - otherSb.AppendLine(apKey.CanTranslate() - ? Tr(apKey, apList) - : $"AvailableApparel: [{apList}] (Equip protective/thermal gear via actions_manage_equipment)"); - } - } - } - catch (Exception ex) { WarnRateLimited("StoredApparel", ex); } + AppendStoredApparelSummary(map, otherSb); } } if (ctx.IncludeSeason) { string seasonStr = GenLocalDate.Season(map).Label(); - otherSb.Append(Tr("RimMind.Prompt.Season", seasonStr)); + otherSb.AppendLine(RimMindText.Tr("RimMind.Prompt.Season", seasonStr)); } if (ctx.IncludeWeather) - otherSb.AppendLine(Tr("RimMind.Prompt.Weather", map.weatherManager.curWeather.label)); - else if (ctx.IncludeSeason) - otherSb.AppendLine(); + { + otherSb.AppendLine(RimMindText.Tr("RimMind.Prompt.Weather", map.weatherManager.curWeather.label)); + } string otherContent = otherSb.ToString().TrimEnd(); if (!string.IsNullOrEmpty(otherContent)) @@ -433,9 +404,9 @@ private static string CompressRenderedMapContext(string? raw) private string ThreatLabel(float wealth) { - float high = EnvSettings?.ThreatThresholdHigh ?? ThreatThresholdHigh; - float medium = EnvSettings?.ThreatThresholdMedium ?? ThreatThresholdMedium; - float low = EnvSettings?.ThreatThresholdLow ?? ThreatThresholdLow; + float high = EnvSettings?.ThreatThresholdHigh ?? RimMindDefaults.DefaultThreatThresholdHigh; + float medium = EnvSettings?.ThreatThresholdMedium ?? RimMindDefaults.DefaultThreatThresholdMedium; + float low = EnvSettings?.ThreatThresholdLow ?? RimMindDefaults.DefaultThreatThresholdLow; float threatScale = 1f; try { threatScale = Find.Storyteller?.difficulty?.threatScale ?? 1f; } catch (System.Exception) { /* Storyteller may be null during early init */ } @@ -444,49 +415,170 @@ private string ThreatLabel(float wealth) string tier = ThreatClassifier.ClassifyThreatTier(wealth, high, medium, low, threatScale); return tier switch { - "Extreme" => Tr("RimMind.Prompt.Threat.Extreme"), - "High" => Tr("RimMind.Prompt.Threat.High"), - "Medium" => Tr("RimMind.Prompt.Threat.Medium"), - _ => Tr("RimMind.Prompt.Threat.Low") + "Extreme" => RimMindText.Tr("RimMind.Prompt.Threat.Extreme"), + "High" => RimMindText.Tr("RimMind.Prompt.Threat.High"), + "Medium" => RimMindText.Tr("RimMind.Prompt.Threat.Medium"), + _ => RimMindText.Tr("RimMind.Prompt.Threat.Low") }; } - private static float CountAvailableMapFoodNutrition(Map? map) + private static int CountAvailableMedicine(Map map) { - if (map == null) return 0f; - float counted = 0f; + int med = 0; try { - counted = map.resourceCounter?.TotalHumanEdibleNutrition ?? 0f; - var foodThings = map.listerThings?.ThingsInGroup(ThingRequestGroup.FoodSourceNotPlantOrTree); - if (foodThings != null && foodThings.Count > 0) + var medThings = map.listerThings?.ThingsInGroup(ThingRequestGroup.Medicine); + if (medThings != null) { - float unforbiddenTotal = 0f; - for (int i = 0; i < foodThings.Count; i++) + for (int i = 0; i < medThings.Count; i++) { - var t = foodThings[i]; - if (t == null || !t.Spawned || t.Destroyed || t is Corpse || t is Pawn) - continue; - if (t.Position.Fogged(map) || t.IsForbidden(Faction.OfPlayer)) - continue; - var ingestible = t.def?.ingestible; - if (ingestible == null || !t.def!.IsNutritionGivingIngestible || !ingestible.HumanEdible) - continue; - if (ingestible.drugCategory != DrugCategory.None || ingestible.preferability < FoodPreferability.RawBad) - continue; - - float nut = t.GetStatValue(StatDefOf.Nutrition); - if (nut > 0f) + var t = medThings[i]; + if (t != null && t.Spawned && !t.IsForbidden(Faction.OfPlayer)) + med += t.stackCount; + } + } + } + catch (Exception ex) { WarnRateLimited("Medicine", ex); } + return med; + } + + private static int CountPendingConstruction(Map map) + { + try + { + int pendingBlueprints = map.listerThings?.ThingsInGroup(ThingRequestGroup.Blueprint)?.Count ?? 0; + int pendingFrames = map.listerThings?.ThingsInGroup(ThingRequestGroup.BuildingFrame)?.Count ?? 0; + return pendingBlueprints + pendingFrames; + } + catch (Exception ex) + { + WarnRateLimited("PendingConstruction", ex); + return 0; + } + } + + private static void AppendWorktableStatus(Map map, StringBuilder sb) + { + if (map.listerBuildings == null) return; + + var worktables = new List(); + try + { + var buildings = map.listerBuildings.allBuildingsColonist; + if (buildings != null) + { + for (int i = 0; i < buildings.Count; i++) + { + var b = buildings[i]; + if (b is Building_WorkTable wt && wt.def != null && !wt.Destroyed) { - unforbiddenTotal += nut * Math.Max(1, t.stackCount); + int billCount = wt.billStack?.Count ?? 0; + string activeBillsStr = ""; + if (billCount > 0 && wt.billStack?.Bills != null) + { + var activeBillNames = wt.billStack.Bills + .Where(bill => bill?.recipe != null && !bill.suspended) + .Select(bill => bill.recipe.defName) + .Distinct() + .ToList(); + if (activeBillNames.Count > 0) + activeBillsStr = $"[{string.Join("/", activeBillNames)}]"; + } + var recipes = wt.def.AllRecipes? + .Take(3) + .Select(r => r.defName) + .ToList(); + string recipeStr = (recipes != null && recipes.Count > 0) ? string.Join("/", recipes) : "None"; + string tableName = wt.def.label ?? wt.def.defName; + var blockReasons = new List(); + var refuelable = wt.GetComp(); + if (refuelable != null && !refuelable.HasFuel) + { + blockReasons.Add("0 WoodLog fuel — harvest trees/haul wood instead of adding bills"); + } + var powerComp = wt.GetComp(); + if (powerComp != null && !powerComp.PowerOn) + { + blockReasons.Add("unpowered"); + } + if (billCount > 0 && (wt.def.defName.Contains("Stove") || wt.def.defName.Contains("Campfire"))) + { + var rawCat = DefDatabase.GetNamedSilentFail("FoodRaw"); + var rawNutrition = (rawCat != null && map.resourceCounter != null) ? map.resourceCounter.GetCountIn(rawCat) : 0; + if (rawNutrition <= 0 && map.listerThings != null) + { + var foods = map.listerThings.ThingsInGroup(ThingRequestGroup.FoodSourceNotPlantOrTree); + if (foods != null) + { + for (int f = 0; f < foods.Count; f++) + { + var ft = foods[f]; + if (ft != null && ft.Spawned && !ft.IsForbidden(Faction.OfPlayer) + && ft.def?.thingCategories != null && rawCat != null + && ft.def.thingCategories.Any(c => c == rawCat || (c.Parents != null && c.Parents.Contains(rawCat)))) + { + rawNutrition += ft.stackCount; + } + } + } + } + if (rawNutrition <= 0) + { + blockReasons.Add("0 raw food available, harvest/hunt needed"); + } + } + string blockNotice = blockReasons.Count > 0 + ? $" [BLOCKED: {string.Join("; ", blockReasons)}]" + : ""; + worktables.Add($"{tableName}(id={wt.thingIDNumber}, bills={billCount}{activeBillsStr}{blockNotice}, recipes=[{recipeStr}])"); + if (worktables.Count >= 4) break; } } - if (unforbiddenTotal > counted) - counted = unforbiddenTotal; } } - catch (Exception ex) { WarnRateLimited("CountAvailableMapFoodNutrition", ex); } - return counted; + catch (Exception ex) { WarnRateLimited("Worktables", ex); } + + if (worktables.Count > 0) + { + string tableList = string.Join("; ", worktables); + sb.AppendLine(RimMindText.TrOr( + "RimMind.Prompt.ColonyWorktables", + "Worktables: [{0}]", + tableList)); + } + } + + private static void AppendStoredApparelSummary(Map map, StringBuilder sb) + { + try + { + var storageApparel = map.listerThings?.ThingsInGroup(ThingRequestGroup.Apparel); + if (storageApparel == null || storageApparel.Count == 0) + return; + + var apparelEntries = new List(); + for (int i = 0; i < storageApparel.Count; i++) + { + var a = storageApparel[i]; + if (a != null && a.Spawned && !a.IsForbidden(Faction.OfPlayer) && a.IsInAnyStorage() && a.def != null) + { + string itemLabel = a.def.label ?? a.def.defName; + int hpPct = a.MaxHitPoints > 0 ? Mathf.RoundToInt((float)a.HitPoints / a.MaxHitPoints * 100f) : 100; + apparelEntries.Add($"{itemLabel}(id={a.thingIDNumber}, hp={hpPct}%)"); + if (apparelEntries.Count >= 5) break; + } + } + + if (apparelEntries.Count > 0) + { + string apList = string.Join(", ", apparelEntries); + sb.AppendLine(RimMindText.TrOr( + "RimMind.Prompt.StoredApparel", + "AvailableApparel: [{0}]", + apList)); + } + } + catch (Exception ex) { WarnRateLimited("StoredApparel", ex); } } private static void AppendColonyRoomsSummary(Map map, StringBuilder sb) @@ -565,39 +657,25 @@ private static void AppendColonyRoomsSummary(Map map, StringBuilder sb) .ToList(); string summaryList = string.Join("; ", ordered); - string key = "RimMind.Prompt.ColonyRooms"; - sb.AppendLine(key.CanTranslate() - ? Tr(key, summaryList) - : $"ColonyRooms: [{summaryList}]"); + sb.AppendLine(RimMindText.TrOr( + "RimMind.Prompt.ColonyRooms", + "ColonyRooms: [{0}]", + summaryList)); } catch (Exception ex) { WarnRateLimited("AppendColonyRoomsSummary", ex); } } + } - private static int CountAvailableMapResource(Map? map, ThingDef? def) - { - if (map == null || def == null) return 0; - int counted = 0; - try - { - counted = map.resourceCounter?.GetCount(def) ?? 0; - var spawnedList = map.listerThings?.ThingsOfDef(def); - if (spawnedList != null && spawnedList.Count > 0) - { - int unforbiddenTotal = 0; - for (int i = 0; i < spawnedList.Count; i++) - { - var t = spawnedList[i]; - if (t != null && t.Spawned && !t.Destroyed && !t.Position.Fogged(map) && !t.IsForbidden(Faction.OfPlayer)) - { - unforbiddenTotal += t.stackCount; - } - } - if (unforbiddenTotal > counted) - counted = unforbiddenTotal; - } - } - catch (Exception ex) { WarnRateLimited("CountAvailableMapResource", ex); } - return counted; - } + internal sealed class MapContextBuilderCacheLifecycleService : IGameScopedService + { + public static readonly MapContextBuilderCacheLifecycleService Instance = new MapContextBuilderCacheLifecycleService(); + + public string Id => "core.map_context_builder.cache_lifecycle"; + + public string OwnerModId => RimMindOwnerConsts.CoreModId; + + public void OnGameStarted() => MapContextBuilder.ClearCaches(); + + public void OnGameStopped() => MapContextBuilder.ClearCaches(); } } diff --git a/Source/Presentation/Agent/PawnContextBuilder.cs b/Source/Presentation/Agent/PawnContextBuilder.cs index a8f4ebc2..a3eb85bc 100644 --- a/Source/Presentation/Agent/PawnContextBuilder.cs +++ b/Source/Presentation/Agent/PawnContextBuilder.cs @@ -43,15 +43,7 @@ public PawnContextBuilder(IContextSettings? contextSettings = null, ILogSink? lo private IPawnIncludeSettings PawnSettings => _contextSettings ?? DefaultFallbackSettings; private static string Tr(string key, params object[] args) - { - try - { - if (string.IsNullOrEmpty(key)) return string.Empty; - string template = key.CanTranslate() ? key.TranslateSimple() : key; - return (args == null || args.Length == 0) ? template : string.Format(template, args); - } - catch { return key ?? string.Empty; } - } + => RimMind.Presentation.Api.RimMindText.Tr(key, args); public string BuildPawnContext(Pawn pawn) { diff --git a/Source/Presentation/Agent/PawnThinker.cs b/Source/Presentation/Agent/PawnThinker.cs index 9aa72416..f7e37a36 100644 --- a/Source/Presentation/Agent/PawnThinker.cs +++ b/Source/Presentation/Agent/PawnThinker.cs @@ -11,6 +11,7 @@ using RimMind.Application.Common.Interfaces.Agent.Psychology; using RimMind.Application.Common.Interfaces.Agent.Social; using RimMind.Application.Common.Interfaces.Internal; +using RimMind.Application.Common.Interfaces.Tools; using RimMind.Application.Common.Models; using RimMind.Application.Common.Models.Pipeline; using RimMind.Application.Common.Models.Tools; @@ -178,7 +179,7 @@ private void Think() _proactiveExecutor.ExecuteProactiveExtensions(_agent, mode, pawnId); var strategy = mode.GetThinkStrategy(); var allowedToolIds = mode.AllowedToolIds(RimMindAPI.Tools); - var availableTools = RimMindAPI.Tools.GetAllDefinitions() + var availableTools = RimMindAPI.Tools.GetDefinitionsForScope(ToolScope.All, compactSchema: true) .Where(d => allowedToolIds.Contains(d.Id)) .Where(d => !IsToolDisabledForPawn(pawn, d)) .ToList(); diff --git a/Source/Presentation/Agent/ScopedThinkStrategy.cs b/Source/Presentation/Agent/ScopedThinkStrategy.cs index a73ab047..27c67580 100644 --- a/Source/Presentation/Agent/ScopedThinkStrategy.cs +++ b/Source/Presentation/Agent/ScopedThinkStrategy.cs @@ -20,7 +20,7 @@ public sealed class ScopedThinkStrategy : IThinkStrategy public string ScenarioId => _scopeType switch { "Storyteller" => ScenarioIds.Storyteller, - _ => ScenarioIds.Decision + _ => ScenarioIds.AgentDecision }; public ScopedThinkStrategy(string scopeType) diff --git a/Source/Presentation/Api/ActorMapResolver.cs b/Source/Presentation/Api/ActorMapResolver.cs new file mode 100644 index 00000000..c52babf4 --- /dev/null +++ b/Source/Presentation/Api/ActorMapResolver.cs @@ -0,0 +1,114 @@ +using RimMind.Domain.ValueObjects; +using Verse; + +namespace RimMind.Presentation.Api +{ + /// + /// Resolves a target and active colonist from optional pawn/map IDs, + /// enforcing RimMind's pawn liveness policy. + /// + public static class ActorMapResolver + { + /// + /// Resolves a map by explicit , otherwise by 's current map, + /// otherwise Find.AnyPlayerHomeMap / Find.CurrentMap. + /// + public static Map? ResolveMap(int? pawnId, int? mapId = null) + { + if (mapId.HasValue) + { + var maps = Find.Maps; + if (maps != null) + { + for (int i = 0; i < maps.Count; i++) + { + if (maps[i]?.uniqueID == mapId.Value) + return maps[i]; + } + } + return null; + } + + if (pawnId.HasValue && pawnId.Value > 0) + { + var pawn = RimMindPawnLookup.FindPawnByNumber(pawnId.Value); + if (pawn?.Map != null) + return pawn.Map; + } + + return Find.AnyPlayerHomeMap ?? Find.CurrentMap; + } + + /// + /// Resolves an active spawned player colonist and its map. When is false, + /// downed or mentally broken colonists are rejected with a descriptive . + /// + public static bool ResolveColonistAndMap( + int pawnId, + bool allowDowned, + out Pawn? pawn, + out Map? map, + out RimMindError? error, + string? traceId = null) + { + pawn = RimMindPawnLookup.FindPawnByNumber(pawnId); + if (pawn == null) + { + map = null; + error = RimMindErrors.PawnNotFound(pawnId) with { TraceId = traceId }; + return false; + } + + if (!RimMindPawnLookup.IsActiveSpawnedColonist(pawn)) + { + map = null; + error = RimMindErrors.PawnNotFound(pawnId) with + { + Message = $"Pawn with ID {pawnId} is not an active spawned player colonist", + TraceId = traceId + }; + pawn = null; + return false; + } + + if (!allowDowned && pawn.Downed) + { + map = null; + error = RimMindErrors.PawnNotFound(pawnId) with + { + Message = $"Pawn with ID {pawnId} is downed and cannot perform this action", + TraceId = traceId + }; + pawn = null; + return false; + } + + if (!allowDowned && pawn.InMentalState) + { + map = null; + error = RimMindErrors.PawnNotFound(pawnId) with + { + Message = $"Pawn with ID {pawnId} is in a mental state ({pawn.MentalStateDef?.label}) and cannot be controlled", + TraceId = traceId + }; + pawn = null; + return false; + } + + map = pawn.Map; + if (map == null) + { + error = RimMindErrors.PawnNotFound(pawnId) with + { + Message = $"Pawn with ID {pawnId} is not on an active map", + TraceId = traceId + }; + pawn = null; + return false; + } + + error = null; + return true; + } + } +} diff --git a/Source/Presentation/Api/CompositeToolCallBase.cs b/Source/Presentation/Api/CompositeToolCallBase.cs new file mode 100644 index 00000000..5f1b1127 --- /dev/null +++ b/Source/Presentation/Api/CompositeToolCallBase.cs @@ -0,0 +1,376 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using RimMind.Application.Common.Constants; +using RimMind.Application.Common.Interfaces.Tools; +using RimMind.Application.Common.Models.Tools; +using RimMind.Application.Features.Tools; +using RimMind.Domain.Agent.Policies; +using RimMind.Domain.Common; +using RimMind.Domain.Enums; +using RimMind.Domain.ValueObjects; + +namespace RimMind.Presentation.Api +{ + /// + /// Generic base class for composite ToolCalls that orchestrate atomic tools or game mutations. + /// Provides single-pass JSON argument parsing, autonomy risk mapping, colonist target liveness guards, + /// and atomic sub-tool execution helpers. + /// + public abstract class CompositeToolCallBase : ICompositeToolCall, IToolPolicyClassifier + { + private ToolDefinition? _cachedDefinition; + + public abstract string Id { get; } + + public virtual string OwnerModId => RimMindOwnerConsts.CoreModId; + + protected virtual ToolKind ToolKind => ToolKind.Mutation; + + protected virtual AutonomyDomain? DefaultAutonomyDomain => null; + + protected virtual RiskLevel DefaultRiskLevel => AutonomyDomainRiskMapper.MapToRisk(DefaultAutonomyDomain, ToolKind); + + protected virtual bool DefaultRequiresApproval => false; + + protected virtual ToolScope? ToolScopes => null; + + protected virtual IReadOnlyList ToolAliases => Array.Empty(); + + protected virtual bool IsSelfTargetedTool => false; + + protected virtual string? DisplayName => null; + + protected virtual IReadOnlyList SummaryArgKeys => Array.Empty(); + + public virtual ToolManifest Manifest => new ToolManifest + { + OwnerModId = OwnerModId, + Kind = ToolKind, + DefaultDomain = DefaultAutonomyDomain, + AutonomyDomainId = DefaultAutonomyDomain?.ToString(), + RiskLevel = DefaultRiskLevel, + RequiresApproval = DefaultRequiresApproval, + Aliases = ToolAliases, + IsSelfTargeted = IsSelfTargetedTool, + DisplayName = DisplayName, + SummaryArgKeys = SummaryArgKeys, + Scopes = ToolScopes + }; + + public virtual ToolDefinition Definition => _cachedDefinition ??= BuildDefinition() with + { + Manifest = Manifest + }; + + protected virtual ToolDefinition BuildDefinition() => new ToolDefinition + { + Id = Id, + Manifest = Manifest + }; + + public abstract IReadOnlyList RequiredToolIds { get; } + + public abstract Task> ExecuteAsync(ToolCallArgs args, CancellationToken ct); + + protected virtual AutonomyDomain? ResolveAutonomyDomain(JObject? root, ToolCallArgs args) + => DefaultAutonomyDomain; + + public virtual ToolPolicyDecision Classify(ToolCallArgs args) + { + var effectiveArgs = args ?? new ToolCallArgs + { + ToolName = Id, + ArgumentsJson = "{}" + }; + var root = TryParseArgumentsObject(effectiveArgs.ArgumentsJson); + var domain = ResolveAutonomyDomain(root, effectiveArgs); + return new ToolPolicyDecision + { + Domain = domain, + DomainId = domain?.ToString() ?? Manifest.AutonomyDomainId, + Risk = AutonomyDomainRiskMapper.MapToRisk(domain, ToolKind), + RequiresApproval = Manifest.RequiresApproval + }; + } + + protected static JObject? TryParseArgumentsObject(string? argumentsJson) + { + if (string.IsNullOrWhiteSpace(argumentsJson)) + return null; + try + { + return JToken.Parse(argumentsJson!) as JObject; + } + catch + { + return null; + } + } + + protected virtual IToolHandler? FindTool(string toolId) => RimMindAPI.Tools.FindById(toolId); + + protected virtual bool AreRequiredToolsRegistered() + { + foreach (var toolId in RequiredToolIds) + { + if (FindTool(toolId) == null) + return false; + } + return true; + } + + protected async Task ExecuteAtomicAsync( + string toolId, + string argumentsJson, + ToolCallArgs parentArgs, + CancellationToken ct) + { + var childCallId = $"{parentArgs.ToolCallId}:{toolId}"; + var handler = FindTool(toolId); + if (handler == null) + { + return ToolResult.Fail($"Required tool not registered: {toolId}", childCallId, toolId); + } + + var childArgs = new ToolCallArgs + { + ToolCallId = childCallId, + ToolName = toolId, + ArgumentsJson = argumentsJson, + PawnId = parentArgs.PawnId, + NpcId = parentArgs.NpcId, + TraceId = parentArgs.TraceId, + Ct = ct, + IsPlayerApproved = parentArgs.IsPlayerApproved + }; + + var result = await handler.ExecuteAsync(childArgs, ct); + return result.IsOk + ? result.Value with { ToolCallId = childCallId, ToolName = toolId } + : ToolResult.Fail($"[{result.Error.Code}] {result.Error.Message}", childCallId, toolId); + } + + protected static bool TryParsePawnIdString(string? raw, out int parsedId) + => PawnIdParser.TryParse(raw, out parsedId); + + /// + /// Checks whether trusted host code approved this call. + /// Approval is read only from . + /// + public static bool IsPreApproved(ToolCallArgs? args) => args != null && args.IsPlayerApproved; + + /// + /// Fails fast with a structured if invoked off the Unity main thread + /// before touching Verse / RimWorld map or pawn state. + /// + protected Result EnsureMainThread(ToolCallArgs? args = null) + { + if (!Verse.UnityData.IsInMainThread) + { + return Result.Err( + new RimMindError( + RimMindErrorCode.ToolExecutionFailed, + $"Tool '{Id}' cannot execute off the Unity main thread") + { + TraceId = args?.TraceId + }); + } + + return Result.Ok(Unit.Value); + } + + /// + /// Verifies that is an active spawned player colonist and passes autonomy checks. + /// + protected virtual Result GuardColonistTarget( + int pawnId, + AutonomyDomain domain, + ToolCallArgs args, + string argumentKey = "pawn_id") + { + var threadGuard = EnsureMainThread(args); + if (threadGuard.IsErr) + return threadGuard; + + var pawn = RimMindPawnLookup.FindPawnByNumber(pawnId); + if (pawn == null || !RimMindPawnLookup.IsActiveSpawnedColonist(pawn)) + { + return Result.Err( + new RimMindError( + RimMindErrorCode.MechanismInvalidAction, + $"{argumentKey} {pawnId} is not an active spawned colonist") + { + TraceId = args?.TraceId + }); + } + + return CheckPermission(pawn, domain, args); + } + + /// + /// Checks autonomy permissions against the colonist and autonomy domain, honoring player pre-approvals. + /// Submodules may override to attach custom notifications or approval-queue routing. + /// + protected virtual Result CheckPermission( + Verse.Pawn? pawn, + AutonomyDomain domain, + ToolCallArgs? args) + { + if (IsPreApproved(args)) + return Result.Ok(Unit.Value); + + var level = RimMindAPI.Autonomy.GetLevel(pawn, domain); + if (level == AutonomyLevel.Disabled) + { + return Result.Err( + new RimMindError( + RimMindErrorCode.MechanismInvalidAction, + $"Action '{Id}' in domain '{domain}' is disabled by player autonomy policy") + { + TraceId = args?.TraceId + }); + } + + if (level == AutonomyLevel.RequireApproval) + { + return Result.Err( + new RimMindError( + RimMindErrorCode.ToolPolicyDenied, + $"Action '{Id}' in domain '{domain}' requires player approval") + { + TraceId = args?.TraceId + }); + } + + return Result.Ok(Unit.Value); + } + + /// + /// Reads a typed argument from a pre-parsed (zero re-parsing). + /// + protected static bool TryGetArgument(JObject? root, string key, out T value) + { + value = default!; + if (root == null || string.IsNullOrEmpty(key)) + return false; + + try + { + var token = root[key]; + if (token == null || token.Type == JTokenType.Null) + return false; + + if (typeof(T) == typeof(int) && token.Type == JTokenType.String) + { + if (PawnIdParser.TryParse(token.ToString(), out int parsedInt)) + { + value = (T)(object)parsedInt; + return true; + } + return false; + } + + var converted = token.Value(); + if (converted == null) + return false; + + value = converted; + return true; + } + catch (Exception ex) when (ex is JsonException or FormatException or OverflowException or InvalidCastException or ArgumentException) + { + return false; + } + } + + /// + /// Reads a typed argument from raw JSON arguments. Prefer the overload when reading multiple keys. + /// + protected static bool TryGetArgument(string? argumentsJson, string key, out T value) + { + var root = TryParseArgumentsObject(argumentsJson); + return TryGetArgument(root, key, out value); + } + + protected static Result TryGetArgumentOrError( + JObject? root, string key, string? traceId) + { + if (TryGetArgument(root, key, out T value)) + return Result.Ok(value); + + return Result.Err( + new RimMindError(RimMindErrorCode.MechanismInvalidAction, $"Missing or invalid {key}") + { + TraceId = traceId + }); + } + + protected static Result TryGetArgumentOrError( + string? argumentsJson, string key, string? traceId) + { + if (TryGetArgument(argumentsJson, key, out T value)) + return Result.Ok(value); + + return Result.Err( + new RimMindError(RimMindErrorCode.MechanismInvalidAction, $"Missing or invalid {key}") + { + TraceId = traceId + }); + } + + protected static Result TryGetPawnIdOrError( + JObject? root, ToolCallArgs args, string key = "pawn_id") + { + int contextFallbackId = (args.PawnId.HasValue && args.PawnId.Value > 0) + ? args.PawnId.Value + : (PawnIdParser.TryParse(args.NpcId, out int parsedNpcId) && parsedNpcId > 0 ? parsedNpcId : 0); + + if (TryGetArgument(root, key, out int id) && id > 0) + return Result.Ok(id); + + if (key != "pawn_id" && TryGetArgument(root, "pawn_id", out int fallbackId) && fallbackId > 0) + return Result.Ok(fallbackId); + + if (contextFallbackId > 0) + return Result.Ok(contextFallbackId); + + return Result.Err( + new RimMindError(RimMindErrorCode.MechanismInvalidAction, $"Missing or invalid {key}") + { + TraceId = args.TraceId + }); + } + + protected static Result TryGetPawnIdOrError( + ToolCallArgs args, string key = "pawn_id") + => TryGetPawnIdOrError(TryParseArgumentsObject(args?.ArgumentsJson), args!, key); + + protected static string BuildArgumentsJson(params (string Key, object? Value)[] pairs) + { + var obj = new JObject(); + foreach (var (key, val) in pairs) + { + obj[key] = val == null ? JValue.CreateNull() : JToken.FromObject(val); + } + return obj.ToString(Formatting.None); + } + + protected static string BuildStepSummary(params (string Name, ToolResult Result)[] steps) + { + var obj = new JObject(); + foreach (var (name, result) in steps) + { + obj[name] = new JObject + { + ["ok"] = !result.IsError, + ["content"] = result.Content + }; + } + return obj.ToString(Formatting.None); + } + } +} diff --git a/Source/Presentation/Api/MapResourceCounter.cs b/Source/Presentation/Api/MapResourceCounter.cs new file mode 100644 index 00000000..d91bd24d --- /dev/null +++ b/Source/Presentation/Api/MapResourceCounter.cs @@ -0,0 +1,100 @@ +using System; +using RimWorld; +using Verse; + +namespace RimMind.Presentation.Api +{ + /// + /// Counts map-wide available (unforbidden, unfogged) resources and human-edible food nutrition, + /// combining stockpile counts (map.resourceCounter) with loose spawned unforbidden items on the ground. + /// + public static class MapResourceCounter + { + /// + /// Returns the maximum of stockpile count and spawned unforbidden, unfogged items of on . + /// + public static int GetAvailableCount(Map? map, ThingDef? def) + { + if (map == null || def == null) + return 0; + + int counted = 0; + try + { + counted = map.resourceCounter?.GetCount(def) ?? 0; + var spawnedList = map.listerThings?.ThingsOfDef(def); + if (spawnedList != null && spawnedList.Count > 0) + { + int unforbiddenTotal = 0; + for (int i = 0; i < spawnedList.Count; i++) + { + var t = spawnedList[i]; + if (t != null && t.Spawned && !t.Destroyed && !t.Position.Fogged(map) && !t.IsForbidden(Faction.OfPlayer)) + { + unforbiddenTotal += t.stackCount; + } + } + + if (unforbiddenTotal > counted) + counted = unforbiddenTotal; + } + } + catch + { + // Best-effort count when map state is partially initialized. + } + + return counted; + } + + /// + /// Returns the maximum of map.resourceCounter.TotalHumanEdibleNutrition and loose spawned unforbidden, + /// unfogged human-edible food items (excluding corpses, pawns, and drugs) on . + /// + public static float GetAvailableFoodNutrition(Map? map) + { + if (map == null) + return 0f; + + float counted = 0f; + try + { + counted = map.resourceCounter?.TotalHumanEdibleNutrition ?? 0f; + var foodThings = map.listerThings?.ThingsInGroup(ThingRequestGroup.FoodSourceNotPlantOrTree); + if (foodThings != null && foodThings.Count > 0) + { + float unforbiddenTotal = 0f; + for (int i = 0; i < foodThings.Count; i++) + { + var t = foodThings[i]; + if (t == null || !t.Spawned || t.Destroyed || t is Corpse || t is Pawn) + continue; + if (t.Position.Fogged(map) || t.IsForbidden(Faction.OfPlayer)) + continue; + + var ingestible = t.def?.ingestible; + if (ingestible == null || !t.def!.IsNutritionGivingIngestible || !ingestible.HumanEdible) + continue; + if (ingestible.drugCategory != DrugCategory.None || ingestible.preferability < FoodPreferability.RawBad) + continue; + + float nut = t.GetStatValue(StatDefOf.Nutrition); + if (nut > 0f) + { + unforbiddenTotal += nut * Math.Max(1, t.stackCount); + } + } + + if (unforbiddenTotal > counted) + counted = unforbiddenTotal; + } + } + catch + { + // Best-effort count when map state is partially initialized. + } + + return counted; + } + } +} diff --git a/Source/Presentation/Api/RimMindAPI.Diagnostics.cs b/Source/Presentation/Api/RimMindAPI.Diagnostics.cs index 96027684..c8137bd2 100644 --- a/Source/Presentation/Api/RimMindAPI.Diagnostics.cs +++ b/Source/Presentation/Api/RimMindAPI.Diagnostics.cs @@ -1,4 +1,4 @@ -using RimMind.Infrastructure.Services.Clients.Shared; +using RimMind.Application.Features.Llm; namespace RimMind.Presentation.Api { @@ -10,11 +10,11 @@ public static partial class RimMindAPI /// public static class Diagnostics { - public static string SanitizeForLog(string? text, int maxLength = LogSanitizer.DefaultMaxChars) - => LogSanitizer.ForLog(text, maxLength); + public static string SanitizeForLog(string? text, int maxLength = LogSecretRedactor.DefaultMaxChars) + => LogSecretRedactor.ForLog(text, maxLength); public static string SanitizeMessage(string? text, string? literalSecret = null, int maxLength = 320) - => LogSanitizer.ForMessageWithSecret(text, literalSecret, maxLength); + => LogSecretRedactor.ForMessageWithSecret(text, literalSecret, maxLength); } } } diff --git a/Source/Presentation/Api/RimMindAPI.Prompt.cs b/Source/Presentation/Api/RimMindAPI.Prompt.cs index 8e7b59ab..59fa6dae 100644 --- a/Source/Presentation/Api/RimMindAPI.Prompt.cs +++ b/Source/Presentation/Api/RimMindAPI.Prompt.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using Newtonsoft.Json.Linq; using RimMind.Application.Common.Interfaces.Abstractions; using RimMind.Application.Features.Json; using RimMind.Application.Features.Prompt; @@ -89,6 +90,26 @@ public static List ExtractAllTags(string text, string tagName) where T : c public static List ExtractAllTagRaw(string text, string tagName) => JsonTagExtractor.ExtractAllRaw(text, tagName); + + // ── LlmPayloadParser (Unified LLM output cleaning, JSON extraction/repair, pseudo-tool parsing) ── + + public static string StripThinkingAndCodeFences(string? raw) + => LlmPayloadParser.StripThinkingAndCodeFences(raw); + + public static string? ExtractJsonPayload(string? raw) + => LlmPayloadParser.ExtractJsonPayload(raw); + + public static bool TryParseJObjectWithRepair(string? raw, out JObject? obj) + => LlmPayloadParser.TryParseJObjectWithRepair(raw, out obj); + + public static bool TryDeserializeWithRepair(string? raw, out T? value) where T : class + => LlmPayloadParser.TryDeserializeWithRepair(raw, out value); + + public static IReadOnlyList ParsePseudoFunctionCalls(string? raw) + => LlmPayloadParser.ParsePseudoFunctionCalls(raw); + + public static string? ExtractReasonFromArgumentsJson(string? argumentsJson) + => LlmPayloadParser.ExtractReasonFromArgumentsJson(argumentsJson); } } } diff --git a/Source/Presentation/Api/RimMindAPI.Request.cs b/Source/Presentation/Api/RimMindAPI.Request.cs index 687cdc5e..64039d63 100644 --- a/Source/Presentation/Api/RimMindAPI.Request.cs +++ b/Source/Presentation/Api/RimMindAPI.Request.cs @@ -34,6 +34,14 @@ public static class Request public static int GetModCooldownTicksLeft(string modId) => Queues.ValueOrDefault?.GetCooldownTicksLeft(modId) ?? 0; + /// Cancels all queued and in-flight requests associated with . + public static int CancelByNpcId(string npcId, string? reason = null) + => Queues.ValueOrDefault?.CancelByNpcId(npcId, reason) ?? 0; + + /// Cancels a single queued or active request by its request ID. + public static bool CancelRequest(string requestId) + => Queues.ValueOrDefault?.CancelRequest(requestId) == true; + /// Unified async request entry (callback style) public static void Send(LlmRequestEnvelope envelope, Action> onComplete) { diff --git a/Source/Presentation/Api/RimMindAPI.Text.cs b/Source/Presentation/Api/RimMindAPI.Text.cs index 88ab5266..c4c2bc4a 100644 --- a/Source/Presentation/Api/RimMindAPI.Text.cs +++ b/Source/Presentation/Api/RimMindAPI.Text.cs @@ -1,3 +1,5 @@ +using RimMind.Application.Features.Prompt; + namespace RimMind.Presentation.Api { public static partial class RimMindAPI @@ -9,6 +11,9 @@ public static string TrOr(string key, string fallback, params object[] args) public static string Tr(string key, params object[] args) => RimMindText.Tr(key, args); + + public static string WrapForMote(string? text, int maxCharsPerLine = MoteTextFormatter.DefaultMaxCharsPerLine) + => MoteTextFormatter.WrapForMote(text, maxCharsPerLine); } } } diff --git a/Source/Presentation/Api/RimMindAPI.Tools.cs b/Source/Presentation/Api/RimMindAPI.Tools.cs index 2ca69622..0592617d 100644 --- a/Source/Presentation/Api/RimMindAPI.Tools.cs +++ b/Source/Presentation/Api/RimMindAPI.Tools.cs @@ -1,8 +1,12 @@ using System; +using System.Collections.Generic; using RimMind.Application.Common.Interfaces.Internal; using RimMind.Application.Common.Interfaces.Mechanisms; using RimMind.Application.Common.Interfaces.Tools; using RimMind.Application.Common.Models.Tools; +using RimMind.Application.Features.Tools; +using RimMind.Domain.Agent.Policies; +using RimMind.Domain.Enums; using RimMind.Presentation.Runtime; using RimMind.Presentation.Runtime.Services; @@ -22,6 +26,18 @@ public static class ToolSet public static IToolRegistry Registry => ToolRegistries.Value; public static IGameMechanismRegistry Mechanisms => MechanismRegistries.Value; + /// + /// Projects registered tool definitions filtered by , optionally compacting parameter schemas. + /// + public static IReadOnlyList GetDefinitionsForScope(ToolScope scope, bool compactSchema = false) + => Registry.GetDefinitionsForScope(scope, compactSchema); + + /// + /// Canonical mapping from + to . + /// + public static RiskLevel MapAutonomyDomainRisk(AutonomyDomain? domain, ToolKind kind = ToolKind.Mutation) + => AutonomyDomainRiskMapper.MapToRisk(domain, kind); + public static ToolPolicyDecision? ClassifyPolicy(string? toolId, ToolCallArgs? args = null) { try diff --git a/Source/Presentation/Api/RimMindAPI.UI.cs b/Source/Presentation/Api/RimMindAPI.UI.cs index 32120399..7f971ae4 100644 --- a/Source/Presentation/Api/RimMindAPI.UI.cs +++ b/Source/Presentation/Api/RimMindAPI.UI.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using RimMind.Application.Common.Models.UI; using RimMind.Infrastructure.UI.DebugCenter; +using RimMind.Presentation.UI; namespace RimMind.Presentation.Api { @@ -53,6 +54,20 @@ public static void ResetDebugPagesToDefaults() public static IReadOnlyList GetDebugPages() => DebugCenterPageRegistry.GetAll(); + + // ── Bio-tab badge providers (unified CharacterCardUtility.DoTopStack host) ── + + public static void RegisterBioTabBadge(IBioTabBadgeProvider provider) + => BioTabBadgeRegistry.Register(provider); + + public static bool UnregisterBioTabBadge(string id) + => BioTabBadgeRegistry.Unregister(id); + + public static int UnregisterBioTabBadgesByOwner(string ownerModId) + => BioTabBadgeRegistry.UnregisterByOwner(ownerModId); + + public static IReadOnlyList GetBioTabBadges() + => BioTabBadgeRegistry.GetAll(); } } } diff --git a/Source/Presentation/Api/RimMindPawnLookup.ColonyRetention.cs b/Source/Presentation/Api/RimMindPawnLookup.ColonyRetention.cs new file mode 100644 index 00000000..d69123cd --- /dev/null +++ b/Source/Presentation/Api/RimMindPawnLookup.ColonyRetention.cs @@ -0,0 +1,114 @@ +using System; +using System.Collections.Generic; +using RimWorld; +using Verse; + +namespace RimMind.Presentation.Api +{ + public static partial class RimMindPawnLookup + { + /// + /// Collects the numeric thingIDNumber of every colony-relevant pawn whose persistent data + /// (memory, personality, etc.) should be retained across pruning passes: + /// alive colonists (across maps, caravans, and travelling transporters), prisoners/slaves on maps, + /// colony/prisoner/slave corpses on maps, and pawns held in any faction's kidnapped list. + /// Must be called on the main thread. + /// + public static HashSet CollectRetainedColonyPawnIds() + { + var retained = new HashSet(); + if (!UnityData.IsInMainThread) + return retained; + + try + { + var aliveColonists = PawnsFinder.AllMapsCaravansAndTravellingTransporters_Alive_Colonists; + if (aliveColonists != null) + { + for (int i = 0; i < aliveColonists.Count; i++) + { + var p = aliveColonists[i]; + if (p != null && p.thingIDNumber > 0 && !p.Destroyed) + retained.Add(p.thingIDNumber); + } + } + } + catch + { + // Ignore if PawnsFinder is unavailable during early init/shutdown. + } + + try + { + var maps = Find.Maps; + if (maps != null) + { + for (int m = 0; m < maps.Count; m++) + { + var map = maps[m]; + if (map == null) continue; + + var mapPawns = map.mapPawns?.AllPawns; + if (mapPawns != null) + { + for (int i = 0; i < mapPawns.Count; i++) + { + var p = mapPawns[i]; + if (p != null && p.thingIDNumber > 0 && !p.Destroyed && + (p.IsColonist || p.IsPrisonerOfColony || p.IsSlaveOfColony)) + { + retained.Add(p.thingIDNumber); + } + } + } + + var corpses = map.listerThings?.ThingsInGroup(ThingRequestGroup.Corpse); + if (corpses != null) + { + for (int i = 0; i < corpses.Count; i++) + { + if (corpses[i] is Corpse corpse && + corpse.InnerPawn is Pawn inner && + inner.thingIDNumber > 0 && + !inner.Destroyed && + (inner.IsColonist || inner.IsPrisonerOfColony || inner.IsSlaveOfColony)) + { + retained.Add(inner.thingIDNumber); + } + } + } + } + } + } + catch + { + // Ignore transient map state errors. + } + + try + { + var factions = Find.FactionManager?.AllFactionsListForReading; + if (factions != null) + { + for (int i = 0; i < factions.Count; i++) + { + var kidnapped = factions[i]?.kidnapped?.KidnappedPawnsListForReading; + if (kidnapped == null) continue; + for (int k = 0; k < kidnapped.Count; k++) + { + var p = kidnapped[k]; + if (p != null && p.thingIDNumber > 0 && !p.Destroyed) + retained.Add(p.thingIDNumber); + } + } + } + } + catch + { + // Ignore if FactionManager is unavailable. + } + + return retained; + } + } +} diff --git a/Source/Presentation/Api/WorldScopedComponentCache.cs b/Source/Presentation/Api/WorldScopedComponentCache.cs new file mode 100644 index 00000000..92182835 --- /dev/null +++ b/Source/Presentation/Api/WorldScopedComponentCache.cs @@ -0,0 +1,45 @@ +using RimWorld.Planet; +using Verse; + +namespace RimMind.Presentation.Api +{ + /// + /// Thread-safe, world-scoped cache for a RimWorld . + /// Automatically re-resolves when the active changes across save reloads or new games. + /// + public sealed class WorldScopedComponentCache where T : WorldComponent + { + private T? _cached; + + /// + /// Gets the active for Current.Game.World, or null if no world is loaded. + /// + public T? Get() + { + var world = Current.Game?.World; + if (world == null) + { + _cached = null; + return null; + } + + var current = _cached; + if (current != null && ReferenceEquals(current.world, world)) + { + return current; + } + + current = world.GetComponent(); + _cached = current; + return current; + } + + /// + /// Clears the cached component reference (e.g., on explicit reset or shutdown). + /// + public void Reset() + { + _cached = null; + } + } +} diff --git a/Source/Presentation/Common/RimMindPawnLookup.cs b/Source/Presentation/Common/RimMindPawnLookup.cs index f27e4feb..fa5bbd7d 100644 --- a/Source/Presentation/Common/RimMindPawnLookup.cs +++ b/Source/Presentation/Common/RimMindPawnLookup.cs @@ -3,6 +3,9 @@ using System.Collections.Generic; using System.Linq; using RimMind.Application.Common.Helpers; +using RimMind.Application.Common.Interfaces.Tools; +using RimMind.Application.Features.Tools; +using RimMind.Presentation.Runtime.Services; using RimWorld; using Verse; @@ -10,10 +13,9 @@ namespace RimMind.Presentation.Api { /// /// Centralized lookup and eligibility policy for Pawns across Core and submodules. - /// Unifies pawn resolution logic and colonist validity checks. /// Unifies pawn resolution logic, thread-safe caching, and colonist validity checks. /// - public static class RimMindPawnLookup + public static partial class RimMindPawnLookup { private static readonly ConcurrentDictionary PawnByNumberCache = new(); private static readonly ConcurrentDictionary PawnByIdCache = new(); @@ -274,15 +276,18 @@ public static void ClearCache() if (mp == null) return null; var allPawns = mp.AllPawns; - if (allPawns != null) + if (allPawns != null && allPawns.Count > 0) { for (int j = 0; j < allPawns.Count; j++) { var p = allPawns[j]; if (p != null && !p.Dead && !p.DestroyedOrNull() && match(p)) return p; } + // In RimWorld, AllPawns is a strict superset of FreeColonists / AllPawnsSpawned / SpawnedColonyAnimals. + return null; } + // Fallback when running under unit-test stubs that populate only subset lists directly. var freeColonists = mp.FreeColonists; if (freeColonists != null) { @@ -471,8 +476,23 @@ public static List GetFreeColonistsSafe(Map? map) } /// - /// Formats a raw tool/action identifier (e.g. "actions_place_blueprint", "pawn.job.take_job") - /// into a clean human-readable title ("Place Blueprint", "Take Job") for UI overlays, motes, and approval cards. + /// Checks whether an NPC identifier (e.g. "NPC-123" or "Pawn_123") resolves to an active spawned player colonist. + /// Used by RequestQueue's pre-dispatch pawn liveness gate. + /// + public static bool IsNpcActiveColonist(string? npcId) + { + if (string.IsNullOrWhiteSpace(npcId)) return false; + if (!PawnIdParser.TryParse(npcId, out int thingId) || thingId <= 0) + return false; + + var pawn = FindPawnByNumber(thingId); + return IsActiveSpawnedColonist(pawn); + } + + /// + /// Formats a raw tool/action identifier (e.g. "pawn.job.take_job") into a clean human-readable title + /// for UI overlays, motes, and approval cards. Prefers + /// when the tool is registered. /// public static string FormatHumanReadableActionName(string? rawName) { @@ -480,7 +500,19 @@ public static string FormatHumanReadableActionName(string? rawName) return "Action"; var trimmed = rawName!.Trim(); - string[] prefixes = { "actions_", "pawn_", "rimmind_", "pawn.job.", "pawn.", "map." }; + try + { + var registry = RuntimeServiceHub.Shared.Capture().GetOptional(); + var displayName = registry?.FindById(trimmed)?.Definition?.Manifest?.DisplayName; + if (!string.IsNullOrWhiteSpace(displayName)) + return displayName!; + } + catch + { + // Safe fallback when runtime is not booted (e.g. unit tests). + } + + string[] prefixes = { "pawn.job.", "pawn.", "map.", "world.", "pawn_", "rimmind_" }; foreach (var prefix in prefixes) { if (trimmed.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && diff --git a/Source/Presentation/Context/CoreContextProviders.cs b/Source/Presentation/Context/CoreContextProviders.cs index ae743804..fc997875 100644 --- a/Source/Presentation/Context/CoreContextProviders.cs +++ b/Source/Presentation/Context/CoreContextProviders.cs @@ -3,12 +3,14 @@ using System.Text; using System.Threading; using System.Threading.Tasks; +using RimMind.Application.Common.Constants; using RimMind.Application.Common.Interfaces.Abstractions; using RimMind.Application.Common.Interfaces.Context; using RimMind.Application.Common.Interfaces.Internal; using RimMind.Application.Common.Interfaces.Npc; using RimMind.Application.Common.Models.Context; using RimMind.Domain.ValueObjects; +using RimMind.Presentation.Agent; using RimMind.Presentation.Api; using Verse; @@ -43,6 +45,14 @@ public static class CoreContextProviders }, null, ct: ct); } + private static bool IsAdvisorOwnedScenario(string? scenario) + => string.Equals(scenario, ScenarioIds.Decision, StringComparison.Ordinal) + || string.Equals(scenario, ScenarioIds.AdvisorDecision, StringComparison.Ordinal); + + private static bool IsDialogueOwnedScenario(string? scenario) + => string.Equals(scenario, ScenarioIds.Dialogue, StringComparison.Ordinal) + || string.Equals(scenario, ScenarioIds.CrisisDialogue, StringComparison.Ordinal); + public static void RegisterAll(IContextKeyRegistry registry, ITranslationService? translationService = null, IContextKeyProvider? contextKeyProvider = null, @@ -66,14 +76,31 @@ public static void RegisterAll(IContextKeyRegistry registry, priority: 1.0f, provider: async (pctx, ct) => { - if (pctx.Scenario == ScenarioIds.Storyteller) - return "You are the RimWorld storyteller AI. Based on the colony's current situation, select the most appropriate incident event. " + - "Consider colony wealth, threat level, food supply, colonist count, and recent events. " + - "Output must be valid JSON matching the IncidentOutput schema."; - if (pctx.Scenario == ScenarioIds.Decision) + // Submodule-owned scenarios supply their own system instructions. + if (IsAdvisorOwnedScenario(pctx.Scenario) || IsDialogueOwnedScenario(pctx.Scenario)) return null; - if (pctx.Scenario == ScenarioIds.Dialogue || pctx.Scenario == ScenarioIds.CrisisDialogue) + if (pctx.Scenario == ScenarioIds.Storyteller) return null; + if (pctx.Scenario == ScenarioIds.AgentDecision) + { + string? pawnPrompt = null; + if (pctx.PawnId > 0) + { + pawnPrompt = await RimMindAPI.MainThreadSnapshot.GetAsync(() => + { + var pawn = ResolvePawn(pctx.PawnId); + if (pawn == null) return null; + var profile = npcManagers?.Current?.GetNpc($"NPC-{pawn.thingIDNumber}"); + return NullIfEmpty(profile?.SystemPrompt); + }, null, ct: ct).ConfigureAwait(false); + } + + const string agentRole = + "You are the autonomous mind of this RimWorld colonist. " + + "Evaluate your immediate survival needs, colony priorities, and current environment, " + + "then choose the best concrete tool call to execute (or wait if no action is needed)."; + return string.IsNullOrWhiteSpace(pawnPrompt) ? agentRole : $"{agentRole}\n{pawnPrompt}"; + } if (pctx.PawnId <= 0) return null; return await RimMindAPI.MainThreadSnapshot.GetAsync(() => { @@ -83,7 +110,7 @@ public static void RegisterAll(IContextKeyRegistry registry, return NullIfEmpty(profile?.SystemPrompt); }, null, ct: ct).ConfigureAwait(false); }, - ownerMod: "Core", + ownerMod: RimMindOwnerConsts.CoreModId, stalenessTicks: 0, cacheScope: CacheScope.Static)); @@ -93,9 +120,7 @@ public static void RegisterAll(IContextKeyRegistry registry, priority: 1.0f, provider: async (pctx, ct) => { - if (pctx.Scenario == ScenarioIds.Decision) - return null; - if (pctx.Scenario == ScenarioIds.Dialogue || pctx.Scenario == ScenarioIds.CrisisDialogue) + if (IsAdvisorOwnedScenario(pctx.Scenario) || IsDialogueOwnedScenario(pctx.Scenario)) return null; if (pctx.PawnId <= 0) return null; return await RimMindAPI.MainThreadSnapshot.GetAsync(() => @@ -113,7 +138,7 @@ public static void RegisterAll(IContextKeyRegistry registry, return NullIfEmpty(sb.ToString().TrimEnd()); }, null, ct: ct).ConfigureAwait(false); }, - ownerMod: "Core", + ownerMod: RimMindOwnerConsts.CoreModId, stalenessTicks: 0, cacheScope: CacheScope.Pawn)); @@ -123,8 +148,8 @@ public static void RegisterAll(IContextKeyRegistry registry, priority: 1.0f, provider: async (pctx, ct) => { - if (pctx.Scenario == ScenarioIds.Decision) return null; - if (pctx.Scenario == ScenarioIds.Dialogue || pctx.Scenario == ScenarioIds.CrisisDialogue) return null; + if (IsAdvisorOwnedScenario(pctx.Scenario) || IsDialogueOwnedScenario(pctx.Scenario)) + return null; if (pctx.PawnId <= 0) return null; return await RimMindAPI.MainThreadSnapshot.GetAsync(() => { @@ -139,7 +164,7 @@ public static void RegisterAll(IContextKeyRegistry registry, return NullIfEmpty(sb.ToString().TrimEnd()); }, null, ct: ct).ConfigureAwait(false); }, - ownerMod: "Core", + ownerMod: RimMindOwnerConsts.CoreModId, stalenessTicks: 0, cacheScope: CacheScope.Pawn)); @@ -150,16 +175,7 @@ public static void RegisterAll(IContextKeyRegistry registry, provider: async (pctx, ct) => { if (pctx.Scenario == ScenarioIds.Storyteller) - { - var sb = new StringBuilder(); - sb.AppendLine("Storyteller rules:"); - sb.AppendLine("- Only select from available RimWorld incident definitions"); - sb.AppendLine("- Consider threat level relative to colony wealth"); - sb.AppendLine("- Balance positive and negative events"); - sb.AppendLine("- Food shortages should trigger related events"); - sb.AppendLine("- Low mood colonists may need positive events"); - return sb.ToString().TrimEnd(); - } + return null; return await RimMindAPI.MainThreadSnapshot.GetAsync(() => { var sb2 = new StringBuilder(); @@ -172,7 +188,7 @@ public static void RegisterAll(IContextKeyRegistry registry, return NullIfEmpty(sb2.ToString().TrimEnd()); }, null, ct: ct).ConfigureAwait(false); }, - ownerMod: "Core", + ownerMod: RimMindOwnerConsts.CoreModId, stalenessTicks: 0, cacheScope: CacheScope.Static)); @@ -183,21 +199,19 @@ public static void RegisterAll(IContextKeyRegistry registry, provider: async (pctx, ct) => { if (pctx.Scenario == ScenarioIds.Storyteller) - return "Select the most fitting incident for the colony's current state. Return structured JSON with defName, reason, and optional params."; + return null; return await RimMindAPI.MainThreadSnapshot.GetAsync(() => { - if (pctx.Scenario == ScenarioIds.Decision) - return NullIfEmpty(Translate("RimMind.Prompt.TaskInstruction.WorldOnly")); - if (pctx.Scenario == ScenarioIds.Dialogue || pctx.Scenario == ScenarioIds.CrisisDialogue) + if (IsAdvisorOwnedScenario(pctx.Scenario) || IsDialogueOwnedScenario(pctx.Scenario)) return NullIfEmpty(Translate("RimMind.Prompt.TaskInstruction.WorldOnly")); return NullIfEmpty(Translate("RimMind.Prompt.TaskInstruction.Base")); }, null, ct: ct).ConfigureAwait(false); }, - ownerMod: "Core", + ownerMod: RimMindOwnerConsts.CoreModId, stalenessTicks: 0, cacheScope: CacheScope.Static)); - // ── L1_Baseline (stalenessTicks: 3000 ~50s) ── + // ── L1_Baseline (stalenessTicks: 3000 ~50s — strictly KV-Cache prefix-stable) ── if (ctx == null) return; @@ -208,11 +222,15 @@ public static void RegisterAll(IContextKeyRegistry registry, provider: (pctx, ct) => ReadPawnContextAsync(pctx.PawnId, pawn => { if (pawn.Map == null) return null; + if (ctx is GameContextBuilder gcb) + { + return NullIfEmpty(gcb.BuildStaticMapTopology(pawn.Map)); + } var entries = ctx.BuildMapContextEntries(pawn.Map); if (entries == null || entries.Count == 0) return null; return string.Join("\n", entries.Select(e => e.Content)); }, ct), - ownerMod: "Core", + ownerMod: RimMindOwnerConsts.CoreModId, stalenessTicks: 3000, cacheScope: CacheScope.Map)); @@ -221,7 +239,7 @@ public static void RegisterAll(IContextKeyRegistry registry, layer: ContextLayer.L1_Baseline, priority: 0.95f, provider: (pctx, ct) => ReadPawnContextAsync(pctx.PawnId, ctx.ExtractPawnBaseInfo, ct), - ownerMod: "Core", + ownerMod: RimMindOwnerConsts.CoreModId, stalenessTicks: 3000, cacheScope: CacheScope.Pawn)); @@ -230,7 +248,7 @@ public static void RegisterAll(IContextKeyRegistry registry, layer: ContextLayer.L1_Baseline, priority: 0.9f, provider: (pctx, ct) => ReadPawnContextAsync(pctx.PawnId, ctx.ExtractFixedRelations, ct), - ownerMod: "Core", + ownerMod: RimMindOwnerConsts.CoreModId, stalenessTicks: 3000, cacheScope: CacheScope.Pawn)); @@ -239,7 +257,7 @@ public static void RegisterAll(IContextKeyRegistry registry, layer: ContextLayer.L1_Baseline, priority: 0.9f, provider: (pctx, ct) => ReadPawnContextAsync(pctx.PawnId, ctx.ExtractIdeology, ct), - ownerMod: "Core", + ownerMod: RimMindOwnerConsts.CoreModId, stalenessTicks: 3000, cacheScope: CacheScope.Pawn)); @@ -248,18 +266,35 @@ public static void RegisterAll(IContextKeyRegistry registry, layer: ContextLayer.L1_Baseline, priority: 0.85f, provider: (pctx, ct) => ReadPawnContextAsync(pctx.PawnId, ctx.ExtractSkillsSummary, ct), - ownerMod: "Core", + ownerMod: RimMindOwnerConsts.CoreModId, stalenessTicks: 3000, cacheScope: CacheScope.Pawn)); - // ── L2_Environment (stalenessTicks: 1500 ~25s) ── + // ── L2_Environment (stalenessTicks: 1500 ~25s — volatile map/environment context) ── + + registry.Register(new ContextProviderDef( + key: "colony_resources", + layer: ContextLayer.L2_Environment, + priority: 0.72f, + provider: (pctx, ct) => ReadPawnContextAsync(pctx.PawnId, pawn => + { + if (pawn.Map == null) return null; + if (ctx is GameContextBuilder gcb) + { + return NullIfEmpty(gcb.BuildVolatileColonyResources(pawn.Map)); + } + return null; + }, ct), + ownerMod: RimMindOwnerConsts.CoreModId, + stalenessTicks: 1500, + cacheScope: CacheScope.Map)); registry.Register(new ContextProviderDef( key: "current_area", layer: ContextLayer.L2_Environment, priority: 0.7f, provider: (pctx, ct) => ReadPawnContextAsync(pctx.PawnId, ctx.ExtractCurrentArea, ct), - ownerMod: "Core", + ownerMod: RimMindOwnerConsts.CoreModId, stalenessTicks: 1500, cacheScope: CacheScope.Pawn)); @@ -268,7 +303,7 @@ public static void RegisterAll(IContextKeyRegistry registry, layer: ContextLayer.L2_Environment, priority: 0.6f, provider: (pctx, ct) => ReadPawnContextAsync(pctx.PawnId, ctx.ExtractWeather, ct), - ownerMod: "Core", + ownerMod: RimMindOwnerConsts.CoreModId, stalenessTicks: 1500, cacheScope: CacheScope.Map)); @@ -277,7 +312,7 @@ public static void RegisterAll(IContextKeyRegistry registry, layer: ContextLayer.L2_Environment, priority: 0.65f, provider: (pctx, ct) => ReadPawnContextAsync(pctx.PawnId, ctx.ExtractTimeOfDay, ct), - ownerMod: "Core", + ownerMod: RimMindOwnerConsts.CoreModId, stalenessTicks: 1500, cacheScope: CacheScope.Map)); @@ -286,7 +321,7 @@ public static void RegisterAll(IContextKeyRegistry registry, layer: ContextLayer.L2_Environment, priority: 0.7f, provider: (pctx, ct) => ReadPawnContextAsync(pctx.PawnId, ctx.ExtractNearbyPawns, ct), - ownerMod: "Core", + ownerMod: RimMindOwnerConsts.CoreModId, stalenessTicks: 1500, cacheScope: CacheScope.Pawn)); @@ -295,7 +330,7 @@ public static void RegisterAll(IContextKeyRegistry registry, layer: ContextLayer.L2_Environment, priority: 0.5f, provider: (pctx, ct) => ReadPawnContextAsync(pctx.PawnId, ctx.ExtractSeason, ct), - ownerMod: "Core", + ownerMod: RimMindOwnerConsts.CoreModId, stalenessTicks: 1500, cacheScope: CacheScope.Map)); @@ -304,7 +339,7 @@ public static void RegisterAll(IContextKeyRegistry registry, layer: ContextLayer.L2_Environment, priority: 0.6f, provider: (pctx, ct) => ReadPawnContextAsync(pctx.PawnId, ctx.ExtractColonyStatus, ct), - ownerMod: "Core", + ownerMod: RimMindOwnerConsts.CoreModId, stalenessTicks: 1500, cacheScope: CacheScope.Map)); @@ -315,7 +350,7 @@ public static void RegisterAll(IContextKeyRegistry registry, layer: ContextLayer.L3_State, priority: 0.3f, provider: (pctx, ct) => ReadPawnContextAsync(pctx.PawnId, ctx.ExtractHealth, ct), - ownerMod: "Core", + ownerMod: RimMindOwnerConsts.CoreModId, stalenessTicks: 750, cacheScope: CacheScope.Pawn)); @@ -324,7 +359,7 @@ public static void RegisterAll(IContextKeyRegistry registry, layer: ContextLayer.L3_State, priority: 0.3f, provider: (pctx, ct) => ReadPawnContextAsync(pctx.PawnId, ctx.ExtractMood, ct), - ownerMod: "Core", + ownerMod: RimMindOwnerConsts.CoreModId, stalenessTicks: 750, cacheScope: CacheScope.Pawn)); @@ -333,7 +368,7 @@ public static void RegisterAll(IContextKeyRegistry registry, layer: ContextLayer.L3_State, priority: 0.28f, provider: (pctx, ct) => ReadPawnContextAsync(pctx.PawnId, ctx.ExtractMoodThoughts, ct), - ownerMod: "Core", + ownerMod: RimMindOwnerConsts.CoreModId, stalenessTicks: 750, cacheScope: CacheScope.Pawn)); @@ -342,7 +377,7 @@ public static void RegisterAll(IContextKeyRegistry registry, layer: ContextLayer.L3_State, priority: 0.25f, provider: (pctx, ct) => ReadPawnContextAsync(pctx.PawnId, ctx.ExtractCurrentJob, ct), - ownerMod: "Core", + ownerMod: RimMindOwnerConsts.CoreModId, stalenessTicks: 750, cacheScope: CacheScope.Pawn)); @@ -351,7 +386,7 @@ public static void RegisterAll(IContextKeyRegistry registry, layer: ContextLayer.L3_State, priority: 0.2f, provider: (pctx, ct) => ReadPawnContextAsync(pctx.PawnId, ctx.ExtractCombatStatus, ct), - ownerMod: "Core", + ownerMod: RimMindOwnerConsts.CoreModId, stalenessTicks: 750, cacheScope: CacheScope.Pawn)); @@ -360,7 +395,7 @@ public static void RegisterAll(IContextKeyRegistry registry, layer: ContextLayer.L3_State, priority: 0.15f, provider: (pctx, ct) => ReadPawnContextAsync(pctx.PawnId, ctx.ExtractTargetInfo, ct), - ownerMod: "Core", + ownerMod: RimMindOwnerConsts.CoreModId, stalenessTicks: 750, cacheScope: CacheScope.Pawn)); @@ -369,7 +404,7 @@ public static void RegisterAll(IContextKeyRegistry registry, layer: ContextLayer.L3_State, priority: 0.2f, provider: (pctx, ct) => ReadPawnContextAsync(pctx.PawnId, ctx.ExtractTaskProgress, ct), - ownerMod: "Core", + ownerMod: RimMindOwnerConsts.CoreModId, stalenessTicks: 750, cacheScope: CacheScope.Pawn)); } diff --git a/Source/Presentation/Runtime/Composition/ClientComposition.cs b/Source/Presentation/Runtime/Composition/ClientComposition.cs index 72002ce2..7f6fafdb 100644 --- a/Source/Presentation/Runtime/Composition/ClientComposition.cs +++ b/Source/Presentation/Runtime/Composition/ClientComposition.cs @@ -38,6 +38,7 @@ public static ClientCompositionServices ComposeClientManager( var gameScopedServices = extensions.GetExtensionRegistry(); gameScopedServices.Register(Player2GameLifecycleService.Instance); + gameScopedServices.Register(RimMind.Presentation.Agent.MapContextBuilderCacheLifecycleService.Instance); services.Bind(gameScopedServices); return new ClientCompositionServices diff --git a/Source/Presentation/Runtime/RimMindCompositionRoot.cs b/Source/Presentation/Runtime/RimMindCompositionRoot.cs index 7ab2cf36..983a8b47 100644 --- a/Source/Presentation/Runtime/RimMindCompositionRoot.cs +++ b/Source/Presentation/Runtime/RimMindCompositionRoot.cs @@ -149,6 +149,8 @@ public RuntimeComposition Compose( SettingsComposition.ComposeInfrastructureServices(services, infraBag); Infrastructure.Mechanisms.MechanismToolHandler.PawnExistsPredicate = id => Api.RimMindPawnLookup.FindPawnByNumber(id) != null; + Infrastructure.Mechanisms.MechanismToolHandler.IsMainThreadPredicate = + () => global::Verse.UnityData.IsInMainThread; var logSink = infraBag.LogSink; var tickProvider = infraBag.TickProvider; @@ -184,12 +186,18 @@ public RuntimeComposition Compose( (string.Equals(evt.NewState, "Dead", StringComparison.OrdinalIgnoreCase) || string.Equals(evt.NewState, "Removed", StringComparison.OrdinalIgnoreCase) || string.Equals(evt.NewState, "Despawned", StringComparison.OrdinalIgnoreCase) || + string.Equals(evt.NewState, "Kidnapped", StringComparison.OrdinalIgnoreCase) || string.Equals(evt.NewState, "Terminated", StringComparison.OrdinalIgnoreCase))) { contextServices.ContextEngine.InvalidateNpc(evt.NpcId); + appBag.Queue.CancelByNpcId(evt.NpcId, $"Agent lifecycle: {evt.NewState}"); } }); owned.Add(new ActionLease(() => agentBus.Unsubscribe(lifecycleCleanupKey))); + if (appBag.Queue is RequestQueue concreteQueue) + { + concreteQueue.PawnLivenessChecker = Api.RimMindPawnLookup.IsNpcActiveColonist; + } var busMiddleware = extensions.GetExtensionRegistry>(); services.Bind(busMiddleware); diff --git a/Source/Presentation/Runtime/RimMindRuntimeGameComponent.cs b/Source/Presentation/Runtime/RimMindRuntimeGameComponent.cs index 72482025..befe87fe 100644 --- a/Source/Presentation/Runtime/RimMindRuntimeGameComponent.cs +++ b/Source/Presentation/Runtime/RimMindRuntimeGameComponent.cs @@ -164,24 +164,11 @@ internal static void NotifyGameStopped(IExtensionRegistry? r { var resolved = ResolveGameScopedServices(registry); if (resolved == null) - { - try - { - Player2GameLifecycleService.Instance.OnGameStopped(); - } - catch (Exception ex) - { - Log.Error($"[RimMind-Core] Default Player2 game-scoped service failed in OnGameStopped: {ex}"); - } return; - } - var notifiedPlayer2 = false; foreach (var service in resolved.All) { if (service == null) continue; - if (service is Player2GameLifecycleService) - notifiedPlayer2 = true; try { service.OnGameStopped(); @@ -191,18 +178,6 @@ internal static void NotifyGameStopped(IExtensionRegistry? r Log.Error($"[RimMind-Core] Game-scoped service '{service.Id}' failed in OnGameStopped: {ex}"); } } - - if (!notifiedPlayer2 && registry == null) - { - try - { - Player2GameLifecycleService.Instance.OnGameStopped(); - } - catch (Exception ex) - { - Log.Error($"[RimMind-Core] Default Player2 game-scoped service failed in OnGameStopped: {ex}"); - } - } } private static IExtensionRegistry? ResolveGameScopedServices( diff --git a/Source/Presentation/Settings/BackupEndpointEntry.cs b/Source/Presentation/Settings/BackupEndpointEntry.cs index a87fb21b..413bbbd4 100644 --- a/Source/Presentation/Settings/BackupEndpointEntry.cs +++ b/Source/Presentation/Settings/BackupEndpointEntry.cs @@ -1,4 +1,5 @@ using RimMind.Application.Common.Models.Client; +using RimMind.Domain.Common; using Verse; namespace RimMind.Presentation.Settings @@ -9,19 +10,19 @@ namespace RimMind.Presentation.Settings /// public class BackupEndpointEntry : IExposable { - public string name = "OpenCode Go (Backup)"; - public string provider = "opencode"; - public string apiEndpoint = "https://opencode.ai/zen/go/v1"; - public string modelName = "deepseek-v4.1-flash"; + public string name = "Backup Node"; + public string provider = AIProviders.OpenAI; + public string apiEndpoint = string.Empty; + public string modelName = string.Empty; public string apiKey = string.Empty; public bool enabled = true; public void ExposeData() { - Scribe_Values.Look(ref name, "name", "OpenCode Go (Backup)"); - Scribe_Values.Look(ref provider, "provider", "opencode"); - Scribe_Values.Look(ref apiEndpoint, "apiEndpoint", "https://opencode.ai/zen/go/v1"); - Scribe_Values.Look(ref modelName, "modelName", "deepseek-v4.1-flash"); + Scribe_Values.Look(ref name, "name", "Backup Node"); + Scribe_Values.Look(ref provider, "provider", AIProviders.OpenAI); + Scribe_Values.Look(ref apiEndpoint, "apiEndpoint", string.Empty); + Scribe_Values.Look(ref modelName, "modelName", string.Empty); string storedKey = ApiKeyObfuscator.Obfuscate(apiKey); Scribe_Values.Look(ref storedKey, "apiKey", string.Empty); apiKey = ApiKeyObfuscator.Deobfuscate(storedKey); @@ -31,7 +32,7 @@ public void ExposeData() public BackupEndpointNode ToNode() => new BackupEndpointNode { Name = name ?? string.Empty, - Provider = provider ?? "openai", + Provider = string.IsNullOrWhiteSpace(provider) ? AIProviders.OpenAI : provider, ApiEndpoint = apiEndpoint ?? string.Empty, ModelName = modelName ?? string.Empty, ApiKey = apiKey ?? string.Empty, diff --git a/Source/Presentation/Settings/RimMindCoreSettings.cs b/Source/Presentation/Settings/RimMindCoreSettings.cs index 1b6c36c5..fdf2b3af 100644 --- a/Source/Presentation/Settings/RimMindCoreSettings.cs +++ b/Source/Presentation/Settings/RimMindCoreSettings.cs @@ -13,8 +13,8 @@ namespace RimMind.Presentation.Settings { public class RimMindCoreSettings : ModSettings, IOpenAISettings { - public const string DefaultApiEndpoint = "https://api.deepseek.com/v1"; - public const string DefaultModelName = "deepseek-flash"; + public const string DefaultApiEndpoint = "https://api.openai.com/v1"; + public const string DefaultModelName = "gpt-4o-mini"; public string? SavedModVersion; diff --git a/Source/Presentation/UI/ApiTabDrawer.TestConnection.cs b/Source/Presentation/UI/ApiTabDrawer.TestConnection.cs index ffff2ab6..6897823e 100644 --- a/Source/Presentation/UI/ApiTabDrawer.TestConnection.cs +++ b/Source/Presentation/UI/ApiTabDrawer.TestConnection.cs @@ -64,7 +64,7 @@ private static void RunConnectionTest( if (!s.IsOpenAIConfigured()) { Log.Message(BuildConnectionDebugLine("openai-settings-not-configured", s, providerRegistry, null, null)); - _testStatus = "RimMind.Settings.Status.NotConfigured".Translate(); + _testStatus = UiText.Get("RimMind.Settings.Status.NotConfigured", "Not configured"); _testStatusColor = Color.yellow; return; } @@ -90,14 +90,14 @@ private static void RunConnectionProbe( ConnectionTestOperation operation = BeginConnectionTest(token); // Translate on the main thread: Verse's LanguageDatabase is not thread-safe. - string testMessage = "RimMind.Settings.TestMessage".Translate(); - string notConfiguredText = notConfiguredKey.Translate(); + string testMessage = UiText.Get("RimMind.Settings.TestMessage", "Say hi in 3 words."); + string notConfiguredText = UiText.Get(notConfiguredKey, "Not configured"); Color notConfiguredColor = requireConfiguredClient || notConfiguredKey == "RimMind.Settings.Status.NotConfigured" ? Color.yellow : new Color(0.9f, 0.4f, 0.4f); - string okFormat = TranslateOrFallback("RimMind.Settings.TestResult.Ok", "OK ({0}ms) {1} ({2} tok)"); - string failFormat = TranslateOrFallback("RimMind.Settings.TestResult.Fail", "FAIL ({0}ms) {1}"); - string exceptionFormat = TranslateOrFallback("RimMind.Settings.TestResult.Exception", "FAIL {0}"); + string okFormat = UiText.Get("RimMind.Settings.TestResult.Ok", "OK ({0}ms) {1} ({2} tok)"); + string failFormat = UiText.Get("RimMind.Settings.TestResult.Fail", "FAIL ({0}ms) {1}"); + string exceptionFormat = UiText.Get("RimMind.Settings.TestResult.Exception", "FAIL {0}"); var okColor = new Color(0.4f, 0.9f, 0.4f); var failColor = new Color(0.9f, 0.4f, 0.4f); @@ -145,11 +145,6 @@ private static void RunConnectionProbe( }); } - private static string TranslateOrFallback(string key, string fallback) - { - return key.CanTranslate() ? (string)key.Translate() : fallback; - } - private static string SafeFormat(string format, params object[] args) { try @@ -167,7 +162,7 @@ private static ConnectionTestOperation BeginConnectionTest(RuntimeGenerationToke var operation = new ConnectionTestOperation(token); _activeConnectionTest = operation; _testPending = true; - _testStatus = "RimMind.Settings.Status.Testing".Translate(); + _testStatus = UiText.Get("RimMind.Settings.Status.Testing", "Testing..."); _testStatusColor = Color.yellow; return operation; } @@ -254,11 +249,11 @@ internal static float EstimateApiHeight(ISettingsProvider? s = null) internal static string GetProviderLabel(string p) { string? descriptorKey = AIProviderRegistry.GetDisplayLabelKey(p); - if (!string.IsNullOrEmpty(descriptorKey) && descriptorKey!.CanTranslate()) - return (string)descriptorKey.Translate(); + if (!string.IsNullOrEmpty(descriptorKey)) + return UiText.Get(descriptorKey!, p); string key = $"RimMind.Settings.Provider.{NormalizeProviderTranslationSuffix(p)}"; - return key.CanTranslate() ? (string)key.Translate() : p; + return UiText.Get(key, p); } private static string NormalizeProviderTranslationSuffix(string providerId) @@ -275,9 +270,9 @@ private static string GetAutoApplyModeLabel(FlywheelAutoApplyMode mode) { return mode switch { - FlywheelAutoApplyMode.Off => "RimMind.UI.FlywheelAutoApply.Off".Translate(), - FlywheelAutoApplyMode.LogOnly => "RimMind.UI.FlywheelAutoApply.LogOnly".Translate(), - FlywheelAutoApplyMode.ApplyWithLog => "RimMind.UI.FlywheelAutoApply.Apply".Translate(), + FlywheelAutoApplyMode.Off => UiText.Get("RimMind.UI.FlywheelAutoApply.Off", "Off"), + FlywheelAutoApplyMode.LogOnly => UiText.Get("RimMind.UI.FlywheelAutoApply.LogOnly", "Log Only"), + FlywheelAutoApplyMode.ApplyWithLog => UiText.Get("RimMind.UI.FlywheelAutoApply.Apply", "Apply"), _ => mode.ToString() }; } diff --git a/Source/Presentation/UI/ApiTabDrawer.cs b/Source/Presentation/UI/ApiTabDrawer.cs index 4381c2e2..4cb4528e 100644 --- a/Source/Presentation/UI/ApiTabDrawer.cs +++ b/Source/Presentation/UI/ApiTabDrawer.cs @@ -230,36 +230,41 @@ internal static string GetActiveProviderDisplayLabel( ISettingsProvider s, IExtensionRegistry? providerRegistry = null) { - if (s.Provider == "player2") + if (string.Equals(s.Provider, Domain.Common.AIProviders.Player2, StringComparison.OrdinalIgnoreCase)) return UiText.Get("RimMind.Settings.Provider.Player2"); if (providerRegistry != null) { - var factory = providerRegistry.All.FirstOrDefault(f => f.ProviderId == s.Provider); + var factory = providerRegistry.All.FirstOrDefault(f => + string.Equals(f.ProviderId, s.Provider, StringComparison.OrdinalIgnoreCase)); if (factory != null && !string.IsNullOrEmpty(factory.DisplayLabel)) return factory.DisplayLabel; } - if (s.Provider == "openai") + if (string.Equals(s.Provider, Domain.Common.AIProviders.OpenAI, StringComparison.OrdinalIgnoreCase)) { - string ep = (s.ApiEndpoint ?? string.Empty).ToLowerInvariant(); string openAiLabel = UiText.Get("RimMind.Settings.Provider.OpenAI"); - if (ep.Contains("deepseek.com")) - return "DeepSeek (" + openAiLabel + ")"; - if (ep.Contains("siliconflow.cn")) - return "SiliconFlow (" + openAiLabel + ")"; - if (ep.Contains("moonshot.cn")) - return "Moonshot (" + openAiLabel + ")"; - if (ep.Contains("localhost:11434") || ep.Contains("127.0.0.1:11434")) - return "Ollama (" + openAiLabel + ")"; - if (ep.Contains("api.openai.com")) - return UiText.Get("RimMind.Settings.Provider.OpenAIOfficial"); + var matchedPreset = AIProviderRegistry.MatchPresetByEndpoint(s.ApiEndpoint); + if (matchedPreset != null) + { + string presetLabel = ResolvePresetLabel(matchedPreset); + if (!string.IsNullOrWhiteSpace(presetLabel)) + return presetLabel; + } + return openAiLabel + " (" + UiText.Get("RimMind.Settings.Provider.Custom") + ")"; } return GetProviderLabel(s.Provider); } + private static string ResolvePresetLabel(AIProviderPreset preset) + { + if (!string.IsNullOrEmpty(preset.DisplayLabelKey)) + return UiText.Get(preset.DisplayLabelKey!, preset.FallbackLabel ?? preset.Id); + return preset.FallbackLabel ?? preset.Id; + } + private static void OpenProviderSelectionMenu( ISettingsProvider s, IExtensionRegistry? providerRegistry, @@ -267,34 +272,57 @@ private static void OpenProviderSelectionMenu( { var options = new List(); - // 1. OpenAI Compatible (OpenAI / 兼容) - string openAiLabel = UiText.Get("RimMind.Settings.Provider.OpenAI"); - options.Add(new FloatMenuOption(openAiLabel, () => + // 1. OpenAI-compatible presets registered via AIProviderRegistry + var openAiPresets = AIProviderRegistry.GetPresets(Domain.Common.AIProviders.OpenAI); + if (openAiPresets.Count > 0) { - ApplyProviderPreset(s, "openai", "https://api.openai.com/v1", "gpt-4o-mini", UiText.Get("RimMind.Settings.Provider.OpenAI")); - })); - - // 2. DeepSeek (标准 OpenAI 兼容端点) - options.Add(new FloatMenuOption(UiText.Get("RimMind.Settings.Provider.DeepSeek"), () => + foreach (var preset in openAiPresets) + { + var capturedPreset = preset; + string label = ResolvePresetLabel(capturedPreset); + options.Add(new FloatMenuOption(label, () => + { + ApplyProviderPreset( + s, + capturedPreset.ProviderId, + capturedPreset.Endpoint, + capturedPreset.ModelName, + label); + })); + } + } + else { - ApplyProviderPreset(s, "openai", "https://api.deepseek.com/v1", "deepseek-flash", "DeepSeek"); - })); + var openAiDescriptor = AIProviderRegistry.GetDescriptor(Domain.Common.AIProviders.OpenAI); + string openAiLabel = UiText.Get("RimMind.Settings.Provider.OpenAI"); + options.Add(new FloatMenuOption(openAiLabel, () => + { + ApplyProviderPreset( + s, + Domain.Common.AIProviders.OpenAI, + openAiDescriptor?.DefaultEndpoint ?? RimMindCoreSettings.DefaultApiEndpoint, + openAiDescriptor?.DefaultModelName ?? RimMindCoreSettings.DefaultModelName, + openAiLabel); + })); + } - // 3. Player2 (本地/云端) + // 2. Player2 (local/cloud) options.Add(new FloatMenuOption(UiText.Get("RimMind.Settings.Provider.Player2"), () => { - s.Provider = "player2"; + s.Provider = Domain.Common.AIProviders.Player2; s.Persist(); RuntimeServiceScope operationScope = RuntimeServiceHub.Shared.Capture(); var currentClientManager = ClientManager.ResolveOptional(operationScope); currentClientManager?.InvalidateCache(); })); - // 4+. 外部动态注入的服务商工厂 (由 providerRegistry 提供,如 ModelService 注入的 OpenCode Go, Extended Service 等) + // 3+. Dynamically registered provider factories (extensions such as ModelService) if (providerRegistry != null) { var externalFactories = providerRegistry.All - .Where(f => f.VisibleInMenu && f.ProviderId != "openai" && f.ProviderId != "player2") + .Where(f => f.VisibleInMenu + && !string.Equals(f.ProviderId, Domain.Common.AIProviders.OpenAI, StringComparison.OrdinalIgnoreCase) + && !string.Equals(f.ProviderId, Domain.Common.AIProviders.Player2, StringComparison.OrdinalIgnoreCase)) .OrderBy(f => f.OrderWeight); foreach (var factory in externalFactories) @@ -319,7 +347,9 @@ private static void OpenProviderSelectionMenu( var allProviders = AIProviderRegistry.GetAllProviderIds(providerRegistry); foreach (var p in allProviders) { - if (p == "openai" || p == "player2" || (providerRegistry != null && providerRegistry.All.Any(f => f.ProviderId == p))) + if (string.Equals(p, Domain.Common.AIProviders.OpenAI, StringComparison.OrdinalIgnoreCase) + || string.Equals(p, Domain.Common.AIProviders.Player2, StringComparison.OrdinalIgnoreCase) + || (providerRegistry != null && providerRegistry.All.Any(f => string.Equals(f.ProviderId, p, StringComparison.OrdinalIgnoreCase)))) continue; var label = GetProviderLabel(p); options.Add(new FloatMenuOption(label, () => @@ -540,45 +570,14 @@ private static void DrawInterfaceSection(Listing_Standard listing, ISettingsProv private static void DrawApiKeySection(Listing_Standard listing, ISettingsProvider s, RimMindLayoutScope? scope = null) { string apiKeyDesc = UiText.Get("RimMind.Settings.ApiKey.Desc"); - listing.LabelWithTooltip(UiText.Get("RimMind.Settings.ApiKey"), apiKeyDesc); - { - Rect row = listing.GetRect(26f); - float btnW = 52f; - Rect field = new Rect(row.x, row.y, row.width - btnW - 4f, row.height); - Rect toggle = new Rect(field.xMax + 4f, row.y, btnW, row.height); - - Widgets.DrawBoxSolid(field, new Color(0.04f, 0.05f, 0.08f, 0.6f)); - GUI.color = new Color(0.28f, 0.35f, 0.45f, 0.7f); - Widgets.DrawBox(field, 1); - GUI.color = Color.white; - - if (_showApiKey) - { - s.ApiKey = Widgets.TextField(field, s.ApiKey ?? string.Empty); - } - else - { - if (string.IsNullOrEmpty(s.ApiKey)) - { - GUI.color = new Color(0.6f, 0.65f, 0.7f, 0.65f); - Widgets.Label(new Rect(field.x + 8f, field.y + 3f, field.width - 16f, field.height), UiText.Get("RimMind.Settings.ApiKey.EmptyPlaceholder")); - GUI.color = Color.white; - } - else - { - string hiddenLabel = UiText.Format("RimMind.Settings.ApiKey.Saved", s.ApiKey.Length); - Widgets.Label(new Rect(field.x + 8f, field.y + 3f, field.width - 16f, field.height), hiddenLabel); - } - - if (Widgets.ButtonInvisible(field)) - { - _showApiKey = true; - } - } - TooltipHandler.TipRegion(field, apiKeyDesc); - if (Widgets.ButtonText(toggle, _showApiKey ? UiText.Get("RimMind.Settings.Hide") : UiText.Get("RimMind.Settings.Show"))) - _showApiKey = !_showApiKey; - } + string apiKey = s.ApiKey ?? string.Empty; + SettingsUIDrawer.DrawSecretField( + listing, + UiText.Get("RimMind.Settings.ApiKey"), + ref apiKey, + ref _showApiKey, + apiKeyDesc); + s.ApiKey = apiKey; listing.Gap(4f); string endpointDesc = UiText.Get("RimMind.Settings.ApiEndpoint.Desc"); @@ -609,36 +608,20 @@ private static void DrawBackupEndpointsSection(Listing_Standard listing, ISettin Rect headerRow = listing.GetRect(26f); float btnW = 148f; - Rect titleRect = new Rect(headerRow.x, headerRow.y + 2f, headerRow.width - (btnW * 2f + 12f), headerRow.height); - Rect addOpenCodeRect = new Rect(headerRow.xMax - (btnW * 2f + 6f), headerRow.y, btnW, 24f); + Rect titleRect = new Rect(headerRow.x, headerRow.y + 2f, Mathf.Max(0f, headerRow.width - btnW - 8f), headerRow.height); Rect addCustomRect = new Rect(headerRow.xMax - btnW, headerRow.y, btnW, 24f); Widgets.Label(titleRect, headerLabel + $" ({list.Count})"); TooltipHandler.TipRegion(titleRect, headerDesc); - if (Widgets.ButtonText(addOpenCodeRect, UiText.Get("RimMind.Settings.BackupEndpoints.AddOpenCode", "+ OpenCode Go Backup"))) - { - list.Add(new BackupEndpointEntry - { - name = $"OpenCode Go #{list.Count + 1}", - provider = "opencode", - apiEndpoint = "https://opencode.ai/zen/go/v1", - modelName = "deepseek-v4.1-flash", - apiKey = string.Empty, - enabled = true - }); - s.Persist(); - } - TooltipHandler.TipRegion(addOpenCodeRect, headerDesc); - if (Widgets.ButtonText(addCustomRect, UiText.Get("RimMind.Settings.BackupEndpoints.AddCustom", "+ Custom Backup"))) { list.Add(new BackupEndpointEntry { name = $"Backup #{list.Count + 1}", - provider = "openai", - apiEndpoint = "https://api.deepseek.com/v1", - modelName = "deepseek-flash", + provider = Domain.Common.AIProviders.OpenAI, + apiEndpoint = string.Empty, + modelName = string.Empty, apiKey = string.Empty, enabled = true }); @@ -663,6 +646,8 @@ private static void DrawBackupEndpointsSection(Listing_Standard listing, ISettin string endpointDesc = UiText.Get("RimMind.Settings.ApiEndpoint.Desc"); string modelDesc = UiText.Get("RimMind.Settings.ModelName.Desc"); string apiKeyDesc = UiText.Get("RimMind.Settings.ApiKey.Desc"); + string emptyPlaceholder = UiText.Get("RimMind.Settings.ApiKey.EmptyPlaceholder"); + string savedFormat = UiText.Get("RimMind.Settings.ApiKey.Saved", "Saved ({0} chars)"); string hideLabel = UiText.Get("RimMind.Settings.Hide"); string showLabel = UiText.Get("RimMind.Settings.Show"); @@ -690,8 +675,6 @@ private static void DrawBackupEndpointsSection(Listing_Standard listing, ISettin Rect epRect = new Rect(badgeRect.xMax + 4f, cardRow1.y + 1f, endpointW, 22f); entry.apiEndpoint = Widgets.TextField(epRect, entry.apiEndpoint ?? string.Empty); TooltipHandler.TipRegion(epRect, endpointDesc); - if (entry.apiEndpoint.IndexOf("opencode.ai", StringComparison.OrdinalIgnoreCase) >= 0) - entry.provider = "opencode"; Rect modelRect = new Rect(epRect.xMax + fieldGap, cardRow1.y + 1f, modelW, 22f); entry.modelName = Widgets.TextField(modelRect, entry.modelName ?? string.Empty); @@ -706,30 +689,23 @@ private static void DrawBackupEndpointsSection(Listing_Standard listing, ISettin if (Widgets.ButtonText(delBtn, "×")) removeIdx = i; Rect cardRow2 = listing.GetRect(24f); - float showBtnW = 52f; - Rect keyField = new Rect(cardRow2.x + 32f, cardRow2.y + 1f, cardRow2.width - 32f - showBtnW - 4f, 22f); - Rect showToggle = new Rect(keyField.xMax + 4f, cardRow2.y + 1f, showBtnW, 22f); - + Rect keyRow = new Rect(cardRow2.x + 32f, cardRow2.y + 1f, Mathf.Max(0f, cardRow2.width - 32f), 22f); bool showingThisKey = _editingBackupKeyIndex == i; + string entryKey = entry.apiKey ?? string.Empty; + SettingsUIDrawer.DrawSecretField( + keyRow, + ref entryKey, + ref showingThisKey, + emptyPlaceholder, + savedFormat, + showLabel, + hideLabel, + apiKeyDesc); + entry.apiKey = entryKey; if (showingThisKey) - { - entry.apiKey = Widgets.TextField(keyField, entry.apiKey ?? string.Empty); - } - else - { - Widgets.DrawBoxSolid(keyField, new Color(0.04f, 0.05f, 0.08f, 0.6f)); - string keyPreview = string.IsNullOrEmpty(entry.apiKey) - ? UiText.Get("RimMind.Settings.ApiKey.EmptyPlaceholder") - : UiText.Format("RimMind.Settings.ApiKey.Saved", entry.apiKey.Length); - Widgets.Label(new Rect(keyField.x + 6f, keyField.y + 2f, keyField.width - 12f, keyField.height), keyPreview); - if (Widgets.ButtonInvisible(keyField)) - _editingBackupKeyIndex = i; - } - TooltipHandler.TipRegion(keyField, apiKeyDesc); - if (Widgets.ButtonText(showToggle, showingThisKey ? hideLabel : showLabel)) - { - _editingBackupKeyIndex = showingThisKey ? -1 : i; - } + _editingBackupKeyIndex = i; + else if (_editingBackupKeyIndex == i) + _editingBackupKeyIndex = -1; } if (removeIdx >= 0 && removeIdx < list.Count) @@ -764,45 +740,14 @@ private static void DrawPlayer2Section( listing.Gap(4f); string player2ApiKeyDesc = UiText.Get("RimMind.Settings.Player2.ApiKeyDesc"); - listing.LabelWithTooltip(UiText.Get("RimMind.Settings.ApiKey") + " (" + UiText.Get("RimMind.Settings.Player2.ApiKeyOptional") + ")", player2ApiKeyDesc); - { - Rect row = listing.GetRect(26f); - float btnW = 52f; - Rect field = new Rect(row.x, row.y, row.width - btnW - 4f, row.height); - Rect toggle = new Rect(field.xMax + 4f, row.y, btnW, row.height); - - Widgets.DrawBoxSolid(field, new Color(0.04f, 0.05f, 0.08f, 0.6f)); - GUI.color = new Color(0.28f, 0.35f, 0.45f, 0.7f); - Widgets.DrawBox(field, 1); - GUI.color = Color.white; - - if (_showApiKey) - { - s.ApiKey = Widgets.TextField(field, s.ApiKey ?? string.Empty); - } - else - { - if (string.IsNullOrEmpty(s.ApiKey)) - { - GUI.color = new Color(0.6f, 0.65f, 0.7f, 0.65f); - Widgets.Label(new Rect(field.x + 8f, field.y + 3f, field.width - 16f, field.height), UiText.Get("RimMind.Settings.ApiKey.EmptyPlaceholder")); - GUI.color = Color.white; - } - else - { - string hiddenLabel = UiText.Format("RimMind.Settings.ApiKey.Saved", s.ApiKey.Length); - Widgets.Label(new Rect(field.x + 8f, field.y + 3f, field.width - 16f, field.height), hiddenLabel); - } - - if (Widgets.ButtonInvisible(field)) - { - _showApiKey = true; - } - } - TooltipHandler.TipRegion(field, player2ApiKeyDesc); - if (Widgets.ButtonText(toggle, _showApiKey ? UiText.Get("RimMind.Settings.Hide") : UiText.Get("RimMind.Settings.Show"))) - _showApiKey = !_showApiKey; - } + string player2Key = s.ApiKey ?? string.Empty; + SettingsUIDrawer.DrawSecretField( + listing, + UiText.Get("RimMind.Settings.ApiKey") + " (" + UiText.Get("RimMind.Settings.Player2.ApiKeyOptional") + ")", + ref player2Key, + ref _showApiKey, + player2ApiKeyDesc); + s.ApiKey = player2Key; listing.Gap(4f); { diff --git a/Source/Presentation/UI/Framework/RequestOverlayLayoutEvaluator.cs b/Source/Presentation/UI/Framework/RequestOverlayLayoutEvaluator.cs index 8d9f04b7..de62faca 100644 --- a/Source/Presentation/UI/Framework/RequestOverlayLayoutEvaluator.cs +++ b/Source/Presentation/UI/Framework/RequestOverlayLayoutEvaluator.cs @@ -79,6 +79,20 @@ public static bool ShouldCollapse( return true; } + /// + /// Evaluates whether the overlay should hide completely (not even drawing the idle mini-pill) + /// when there are no pending requests and auto-hide is enabled. + /// + public static bool ShouldHideCompletely( + int pendingCount, + bool autoHideWhenEmpty, + bool isExpanded, + bool isDragging, + bool isResizing) + { + return pendingCount <= 0 && autoHideWhenEmpty && !isExpanded && !isDragging && !isResizing; + } + /// /// Returns the bounding rectangle based on collapsed vs expanded state. /// diff --git a/Source/Presentation/UI/IBioTabBadgeProvider.cs b/Source/Presentation/UI/IBioTabBadgeProvider.cs new file mode 100644 index 00000000..f5b50d20 --- /dev/null +++ b/Source/Presentation/UI/IBioTabBadgeProvider.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RimMind.Application.Common.Constants; +using Verse; + +namespace RimMind.Presentation.UI +{ + /// + /// Immutable descriptor for a Bio-tab top-stack badge rendered inside RimWorld's character card. + /// + public sealed record BioTabBadgeDescriptor( + string Label, + Func? TooltipProvider = null, + Action? OnClick = null, + float ExtraWidth = 16f); + + /// + /// Extension interface for submodules that wish to add a badge button to the RimWorld Bio tab + /// (CharacterCardUtility.DoTopStack) without adding their own Harmony transpiler. + /// Implementations MUST keep read-only (no save-state mutations on hover/draw). + /// + public interface IBioTabBadgeProvider + { + string Id { get; } + string OwnerModId { get; } + int Order { get; } + BioTabBadgeDescriptor? TryGetBadge(Pawn pawn); + } + + /// + /// Thread-safe registry for extensions consumed by Core's single + /// CharacterCardUtility.DoTopStack Harmony patch. + /// + public static class BioTabBadgeRegistry + { + private static readonly object SyncRoot = new object(); + private static readonly List Providers = new List(); + + public static void Register(IBioTabBadgeProvider provider) + { + if (provider == null) throw new ArgumentNullException(nameof(provider)); + if (string.IsNullOrWhiteSpace(provider.Id)) + throw new ArgumentException("Provider Id cannot be null or whitespace.", nameof(provider)); + + lock (SyncRoot) + { + int idx = Providers.FindIndex(p => string.Equals(p.Id, provider.Id, StringComparison.OrdinalIgnoreCase)); + if (idx >= 0) Providers[idx] = provider; + else Providers.Add(provider); + Providers.Sort((a, b) => + { + int cmp = a.Order.CompareTo(b.Order); + return cmp != 0 ? cmp : string.Compare(a.Id, b.Id, StringComparison.OrdinalIgnoreCase); + }); + } + } + + public static bool Unregister(string id) + { + if (string.IsNullOrWhiteSpace(id)) return false; + lock (SyncRoot) + { + return Providers.RemoveAll(p => string.Equals(p.Id, id, StringComparison.OrdinalIgnoreCase)) > 0; + } + } + + public static int UnregisterByOwner(string ownerModId) + { + if (string.IsNullOrWhiteSpace(ownerModId)) return 0; + lock (SyncRoot) + { + return Providers.RemoveAll(p => + string.Equals(p.OwnerModId ?? RimMindOwnerConsts.CoreModId, ownerModId, StringComparison.OrdinalIgnoreCase)); + } + } + + public static IReadOnlyList GetAll() + { + lock (SyncRoot) + { + return Providers.Count == 0 + ? Array.Empty() + : Providers.ToArray(); + } + } + + public static void Clear() + { + lock (SyncRoot) + { + Providers.Clear(); + } + } + } +} diff --git a/Source/Presentation/UI/RimMindChatWindowBase.cs b/Source/Presentation/UI/RimMindChatWindowBase.cs new file mode 100644 index 00000000..725ab8d3 --- /dev/null +++ b/Source/Presentation/UI/RimMindChatWindowBase.cs @@ -0,0 +1,296 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Threading; +using RimMind.Infrastructure.UI; +using RimMind.Presentation.UI.Layout; +using UnityEngine; +using Verse; + +namespace RimMind.Presentation.UI +{ + /// + /// Represents one chat message entry rendered inside . + /// + public readonly struct ChatWindowMessage + { + public ChatWindowMessage(string role, string content, string? senderPrefix = null) + { + Role = role ?? string.Empty; + Content = content ?? string.Empty; + SenderPrefix = senderPrefix; + } + + public string Role { get; } + public string Content { get; } + public string? SenderPrefix { get; } + } + + /// + /// Reusable interactive chat window base class built on . + /// Handles layout-scoped rendering, zebra-striped auto-scrolling message history, + /// thread-safe background response marshaling, status bar, Enter-to-send input row, + /// and automatic teardown on . + /// + public abstract class RimMindChatWindowBase : RimMindWindowBase + { + protected const float ChatPadding = 8f; + protected const float ChatInputHeight = 36f; + protected const float ChatSendButtonWidth = 80f; + protected const float ChatHeaderHeight = 28f; + protected const float ChatStatusHeight = 22f; + protected const float ChatScrollbarWidth = 16f; + + private readonly List _messages = new List(); + private readonly ConcurrentQueue _mainThreadUpdates = new ConcurrentQueue(); + private readonly CancellationTokenSource _lifetime = new CancellationTokenSource(); + private Vector2 _scrollPosition = Vector2.zero; + private string _inputText = string.Empty; + private bool _isWaiting; + private bool _autoScroll = true; + private bool _closed; + + protected RimMindChatWindowBase() + { + doCloseButton = false; + doCloseX = true; + closeOnAccept = false; + forcePause = false; + closeOnClickedOutside = false; + absorbInputAroundWindow = false; + draggable = true; + } + + public override Vector2 InitialSize => new Vector2(480f, 540f); + + protected CancellationToken LifetimeToken => _lifetime.Token; + protected bool IsClosed => _closed; + protected bool IsWaiting => _isWaiting; + protected IReadOnlyList Messages => _messages; + + protected virtual Color HeaderColor => new Color(0.8f, 0.95f, 1f); + protected virtual Color UserColor => new Color(0.7f, 0.85f, 1f); + protected virtual Color AssistantColor => new Color(1f, 0.95f, 0.8f); + protected virtual Color SystemColor => new Color(1f, 0.55f, 0.55f); + protected virtual Color ChatBackgroundColor => new Color(0.08f, 0.08f, 0.12f, 0.5f); + protected virtual Color StatusColor => new Color(1f, 1f, 0.5f); + + protected abstract string GetTitle(); + protected abstract string GetWaitingText(); + protected abstract string GetSendButtonLabel(); + protected abstract string GetPrefixForRole(string role); + protected abstract void OnSubmitUserMessage(string trimmedInput); + + /// + /// Optional guard called at the start of every frame. Return false to auto-close the window. + /// + protected virtual bool ValidateCanStayOpen() => true; + + /// + /// Optional hook invoked on the main thread whenever a new message is appended via + /// or . + /// + protected virtual void OnMessageAppended(ChatWindowMessage message) + { + } + + protected virtual Color GetColorForRole(string role) + { + if (string.Equals(role, "user", StringComparison.OrdinalIgnoreCase)) + return UserColor; + if (string.Equals(role, "system", StringComparison.OrdinalIgnoreCase)) + return SystemColor; + return AssistantColor; + } + + /// + /// Appends a message immediately on the main thread. + /// + protected void AppendMessage(string role, string content, string? senderPrefix = null, bool notifyHook = true) + { + if (string.IsNullOrEmpty(content)) + return; + var msg = new ChatWindowMessage(role, content, senderPrefix); + _messages.Add(msg); + _autoScroll = true; + if (notifyHook) + OnMessageAppended(msg); + } + + /// + /// Thread-safe helper for background LLM callbacks to deliver a reply and clear waiting state on the next UI frame. + /// + protected void PostReply(string role, string content, bool clearWaiting = true, string? senderPrefix = null) + { + if (_closed) return; + _mainThreadUpdates.Enqueue(() => + { + if (_closed) return; + if (clearWaiting) + _isWaiting = false; + if (!string.IsNullOrEmpty(content)) + AppendMessage(role, content, senderPrefix); + }); + } + + /// + /// Thread-safe helper to toggle the waiting indicator. + /// + protected void SetWaiting(bool waiting) + { + _isWaiting = waiting; + } + + public override void PostClose() + { + if (!_closed) + { + _closed = true; + _isWaiting = false; + try { _lifetime.Cancel(); } catch (ObjectDisposedException) { } + try { _lifetime.Dispose(); } catch (ObjectDisposedException) { } + } + base.PostClose(); + } + + protected override void DrawContents(Rect inRect, RimMindLayoutScope scope) + { + if (!ValidateCanStayOpen()) + { + Close(); + return; + } + + while (_mainThreadUpdates.TryDequeue(out var update)) + { + update?.Invoke(); + } + + Text.Font = GameFont.Small; + + float statusH = _isWaiting ? ChatStatusHeight + ChatPadding : 0f; + float chatHeight = Mathf.Max(40f, inRect.height - ChatHeaderHeight - statusH - ChatInputHeight - ChatPadding * 3f); + float inputY = inRect.yMax - ChatInputHeight; + + Rect headerRect = new Rect(inRect.x, inRect.y, inRect.width, ChatHeaderHeight); + Rect chatRect = new Rect(inRect.x, inRect.y + ChatHeaderHeight + ChatPadding, inRect.width, chatHeight); + scope.Record(headerRect, "ChatWindow:Header"); + scope.Record(chatRect, "ChatWindow:History"); + + GUI.color = HeaderColor; + Text.Anchor = TextAnchor.MiddleCenter; + Widgets.Label(headerRect, GetTitle()); + Text.Anchor = TextAnchor.UpperLeft; + GUI.color = Color.white; + + Widgets.DrawBoxSolid(chatRect, ChatBackgroundColor); + DrawChatHistory(chatRect); + + if (_isWaiting) + { + Rect statusRect = new Rect(inRect.x, inputY - ChatStatusHeight - ChatPadding, inRect.width, ChatStatusHeight); + scope.Record(statusRect, "ChatWindow:Status"); + GUI.color = StatusColor; + Text.Anchor = TextAnchor.MiddleCenter; + Widgets.Label(statusRect, GetWaitingText()); + Text.Anchor = TextAnchor.UpperLeft; + GUI.color = Color.white; + } + + Rect inputRect = new Rect(inRect.x, inputY, Mathf.Max(40f, inRect.width - ChatSendButtonWidth - ChatPadding), ChatInputHeight); + Rect sendRect = new Rect(inRect.xMax - ChatSendButtonWidth, inputY, ChatSendButtonWidth, ChatInputHeight); + scope.Record(inputRect, "ChatWindow:Input"); + scope.Record(sendRect, "ChatWindow:Send"); + + _inputText = Widgets.TextField(inputRect, _inputText ?? string.Empty); + + bool wasEnabled = GUI.enabled; + GUI.enabled = wasEnabled && !_isWaiting; + bool sendClicked = Widgets.ButtonText(sendRect, GetSendButtonLabel()); + GUI.enabled = wasEnabled; + + if (sendClicked && !_isWaiting) + { + SubmitCurrentInput(); + } + + if (!_isWaiting + && Event.current != null + && Event.current.type == EventType.KeyDown + && (Event.current.keyCode == KeyCode.Return || Event.current.keyCode == KeyCode.KeypadEnter) + && !string.IsNullOrWhiteSpace(_inputText)) + { + SubmitCurrentInput(); + Event.current.Use(); + } + } + + private void SubmitCurrentInput() + { + string trimmed = (_inputText ?? string.Empty).Trim(); + if (string.IsNullOrEmpty(trimmed)) + return; + + _inputText = string.Empty; + OnSubmitUserMessage(trimmed); + } + + private void DrawChatHistory(Rect rect) + { + if (_messages.Count == 0) + return; + + float contentWidth = Mathf.Max(20f, rect.width - ChatScrollbarWidth); + float textWidth = Mathf.Max(20f, contentWidth - ChatPadding * 2f); + float contentHeight = CalcMessagesHeight(textWidth); + Rect viewRect = new Rect(0f, 0f, contentWidth, Mathf.Max(rect.height, contentHeight)); + + float prevScrollY = _scrollPosition.y; + Widgets.BeginScrollView(rect, ref _scrollPosition, viewRect); + + float y = 0f; + for (int i = 0; i < _messages.Count; i++) + { + var msg = _messages[i]; + string prefix = msg.SenderPrefix ?? GetPrefixForRole(msg.Role); + string line = prefix + msg.Content; + float lineH = Text.CalcHeight(line, textWidth) + ChatPadding; + + if (i % 2 == 0) + { + Widgets.DrawBoxSolid(new Rect(0f, y, contentWidth, lineH), new Color(1f, 1f, 1f, 0.03f)); + } + + GUI.color = GetColorForRole(msg.Role); + Widgets.Label(new Rect(ChatPadding, y, textWidth, lineH), line); + GUI.color = Color.white; + + y += lineH; + } + + Widgets.EndScrollView(); + + if (_autoScroll) + { + _scrollPosition.y = Mathf.Max(0f, contentHeight - rect.height); + _autoScroll = false; + } + else if (Mathf.Abs(_scrollPosition.y - prevScrollY) > 0.5f) + { + // User scrolled manually; keep their position. + } + } + + private float CalcMessagesHeight(float textWidth) + { + float total = 0f; + for (int i = 0; i < _messages.Count; i++) + { + var msg = _messages[i]; + string prefix = msg.SenderPrefix ?? GetPrefixForRole(msg.Role); + total += Text.CalcHeight(prefix + msg.Content, textWidth) + ChatPadding; + } + return total; + } + } +} diff --git a/Source/Presentation/UI/SettingsUIDrawer.cs b/Source/Presentation/UI/SettingsUIDrawer.cs index ed0d3835..448ae025 100644 --- a/Source/Presentation/UI/SettingsUIDrawer.cs +++ b/Source/Presentation/UI/SettingsUIDrawer.cs @@ -141,5 +141,161 @@ public static void DrawBottomBar(Rect bottomBar, Action resetAction) resetAction?.Invoke(); } } + + /// + /// Draws a scrollable settings page with automatic height measurement, dirty-only persistence + /// (avoiding per-frame disk writes), and an optional bottom reset bar. + /// + public static void DrawScrollableSettingsPage( + Rect inRect, + ref Vector2 scrollPos, + ref float measuredHeight, + Action drawContent, + Action? onReset = null, + Action? onDirtySave = null) + { + if (drawContent == null) + return; + + Rect contentArea = onReset != null ? SplitContentArea(inRect) : inRect; + float viewHeight = Mathf.Max(measuredHeight, contentArea.height + 1f); + Rect viewRect = new Rect(0f, 0f, Mathf.Max(0f, contentArea.width - 16f), viewHeight); + + bool prevChanged = GUI.changed; + GUI.changed = false; + + Widgets.BeginScrollView(contentArea, ref scrollPos, viewRect); + var listing = new Listing_Standard(); + listing.Begin(viewRect); + try + { + drawContent(listing); + measuredHeight = listing.CurHeight + 24f; + } + finally + { + listing.End(); + Widgets.EndScrollView(); + } + + if (onReset != null) + { + Rect bottomBar = SplitBottomBar(inRect); + DrawBottomBar(bottomBar, () => + { + onReset(); + GUI.changed = true; + }); + } + + bool dirty = GUI.changed; + GUI.changed = prevChanged || dirty; + if (dirty) + { + onDirtySave?.Invoke(); + } + } + + /// + /// Draws a masked secret input field (e.g., API key) with click-to-reveal and Show/Hide toggle. + /// + public static void DrawSecretField( + Rect row, + ref string value, + ref bool isRevealed, + string emptyPlaceholder, + string savedFormat, + string showLabel, + string hideLabel, + string? tooltip = null, + float toggleButtonWidth = 52f) + { + float btnW = Mathf.Max(36f, toggleButtonWidth); + Rect field = new Rect(row.x, row.y, Mathf.Max(0f, row.width - btnW - 4f), row.height); + Rect toggle = new Rect(field.xMax + 4f, row.y, btnW, row.height); + + Widgets.DrawBoxSolid(field, new Color(0.04f, 0.05f, 0.08f, 0.6f)); + GUI.color = new Color(0.28f, 0.35f, 0.45f, 0.7f); + Widgets.DrawBox(field, 1); + GUI.color = Color.white; + + if (isRevealed) + { + value = Widgets.TextField(field, value ?? string.Empty); + } + else + { + if (string.IsNullOrEmpty(value)) + { + GUI.color = new Color(0.6f, 0.65f, 0.7f, 0.65f); + Widgets.Label( + new Rect(field.x + 8f, field.y + 3f, Mathf.Max(0f, field.width - 16f), field.height), + emptyPlaceholder ?? string.Empty); + GUI.color = Color.white; + } + else + { + string hiddenLabel; + try + { + hiddenLabel = string.Format(savedFormat ?? "Saved ({0} chars)", value.Length); + } + catch (FormatException) + { + hiddenLabel = $"{savedFormat} ({value.Length})"; + } + + Widgets.Label( + new Rect(field.x + 8f, field.y + 3f, Mathf.Max(0f, field.width - 16f), field.height), + hiddenLabel); + } + + if (Widgets.ButtonInvisible(field)) + { + isRevealed = true; + } + } + + if (!string.IsNullOrEmpty(tooltip)) + { + TooltipHandler.TipRegion(field, tooltip); + } + + if (Widgets.ButtonText(toggle, isRevealed ? hideLabel : showLabel)) + { + isRevealed = !isRevealed; + } + } + + /// + /// Convenience Listing_Standard wrapper around . + /// + public static void DrawSecretField( + Listing_Standard listing, + string label, + ref string value, + ref bool isRevealed, + string? tooltip = null, + float rowHeight = 26f) + { + if (!string.IsNullOrEmpty(label)) + { + if (!string.IsNullOrEmpty(tooltip)) + listing.LabelWithTooltip(label, tooltip); + else + listing.Label(label); + } + + Rect row = listing.GetRect(rowHeight); + DrawSecretField( + row, + ref value, + ref isRevealed, + UiText.Get("RimMind.Settings.ApiKey.EmptyPlaceholder", "Click to enter API key..."), + UiText.Get("RimMind.Settings.ApiKey.Saved", "Saved ({0} chars)"), + UiText.Get("RimMind.Settings.Show", "Show"), + UiText.Get("RimMind.Settings.Hide", "Hide"), + tooltip); + } } } diff --git a/Tests/Contracts/P0CorePipelineBusContracts.cs b/Tests/Contracts/P0CorePipelineBusContracts.cs index c905b5ae..41ce9345 100644 --- a/Tests/Contracts/P0CorePipelineBusContracts.cs +++ b/Tests/Contracts/P0CorePipelineBusContracts.cs @@ -246,6 +246,17 @@ await breaker.InvokeAsync(failoverCtx, c => Priority = AIRequestPriority.High, ExpireAtTicks = 9999, MaxRetryCount = 4, + CoalesceKey = "coalesce:npc-42", + MaxQueueWaitTicks = 600, + ExpiresAtUtc = new DateTime(2026, 11, 21, 12, 0, 0, DateTimeKind.Utc), + RequireAliveColonist = true, + Options = new LlmRequestOptions + { + CoalesceKey = "coalesce:opt", + MaxQueueWaitTicks = 300, + ExpiresAtUtc = new DateTime(2026, 11, 21, 13, 0, 0, DateTimeKind.Utc), + RequireAliveColonist = true + }, IsStreaming = true, OnStreamChunk = streamCallback, Ct = cts1.Token, diff --git a/Tests/Contracts/Phase2CoreBuildingBlockContracts.cs b/Tests/Contracts/Phase2CoreBuildingBlockContracts.cs new file mode 100644 index 00000000..15dccb43 --- /dev/null +++ b/Tests/Contracts/Phase2CoreBuildingBlockContracts.cs @@ -0,0 +1,603 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Newtonsoft.Json.Linq; +using RimMind.Application.Common.Helpers; +using RimMind.Application.Common.Interfaces.Abstractions; +using RimMind.Application.Common.Interfaces.Agent; +using RimMind.Application.Common.Interfaces.Mechanisms; +using RimMind.Application.Common.Interfaces.Tools; +using RimMind.Application.Common.Models.Agent; +using RimMind.Application.Common.Models.Context; +using RimMind.Application.Common.Models.Mechanisms; +using RimMind.Application.Common.Models.Tools; +using RimMind.Application.Features.Agent.Modes; +using RimMind.Application.Features.Json; +using RimMind.Application.Features.Llm; +using RimMind.Application.Features.Prompt; +using RimMind.Application.Features.Requests.Queue; +using RimMind.Application.Features.Tools; +using RimMind.Domain.Agent.Policies; +using RimMind.Domain.Common; +using RimMind.Domain.Enums; +using RimMind.Domain.Llm; +using RimMind.Domain.ValueObjects; +using RimMind.Infrastructure.Mechanisms; +using RimMind.Presentation.Api; +using RimMind.Presentation.UI; +using RimMind.Presentation.UI.Framework; +using RimMind.Testing; +using Xunit; + +namespace RimMind.Tests.Contracts +{ + public sealed class Phase2CoreBuildingBlockContracts + { + private sealed class FakeToolHandler : IToolHandler + { + public FakeToolHandler(ToolDefinition definition, string ownerModId = "RimMindCore") + { + Definition = definition; + OwnerModId = ownerModId; + } + + public string Id => Definition.Id; + public string OwnerModId { get; } + public ToolDefinition Definition { get; } + + public Task> ExecuteAsync(ToolCallArgs args, CancellationToken ct) + => Task.FromResult(Result.Ok(ToolResult.Ok("ok", args.ToolCallId, Id))); + } + + private sealed class FakeTickProvider : ITickProvider + { + public int TicksGame { get; set; } = 1000; + public long TicksAbs => TicksGame; + } + + private sealed class FakeAgentInfo : IAgentInfo + { + public AgentState State => AgentState.Active; + public string NpcId => "NPC-42"; + public string Label => "Alice"; + public int? LastThinkTick { get; set; } = 0; + public int GoalCount => 0; + public IReadOnlyList GetRecentHistory(int count = 10) => Array.Empty(); + public float GetRecentSuccessRate(int count = 10) => 1f; + } + + private sealed class FakeAutonomyMechanism : IMechanismReader, IMechanismWriter, IMechanismTrigger, IMechanismAutonomyMetadata + { + public string Id => MechanismId; + public string OwnerModId => "TestMod"; + public string MechanismId { get; init; } = "pawn.custom_schedule"; + public MechanismScope Scope { get; init; } = MechanismScope.Pawn; + public MechanismRisk Risk { get; init; } = MechanismRisk.Moderate; + public IReadOnlyList SupportedOperations { get; } = + new[] { MechanismOperationType.Query, MechanismOperationType.Set }; + public MechanismDocs Docs { get; } = new MechanismDocs { Summary = "Custom test mechanism" }; + public IReadOnlyList? GetWriteActions() => null; + public MechanismRisk GetRiskForOperation(MechanismOperationType operation) => Risk; + public AutonomyDomain? GetAutonomyDomainForOperation(MechanismOperationType operation) + => operation == MechanismOperationType.Set ? AutonomyDomain.WorkPriorityModification : null; + + public Task> ExecuteQueryAsync(MechanismReadArgs args, CancellationToken ct) + => Task.FromResult(Result.Ok("{}")); + public Task, RimMindError>> ExecuteListAsync(int? pawnId, CancellationToken ct) + => Task.FromResult(Result, RimMindError>.Ok(Array.Empty())); + public Task> ExecuteSetAsync(MechanismWriteArgs args, CancellationToken ct) + => Task.FromResult(Result.Ok(true)); + public Task> ExecuteAddAsync(MechanismWriteArgs args, CancellationToken ct) + => Task.FromResult(Result.Ok(true)); + public Task> ExecuteRemoveAsync(MechanismWriteArgs args, CancellationToken ct) + => Task.FromResult(Result.Ok(true)); + public Task> ExecuteToggleAsync(MechanismWriteArgs args, CancellationToken ct) + => Task.FromResult(Result.Ok(true)); + public Task> ExecuteTriggerAsync(MechanismWriteArgs args, CancellationToken ct) + => Task.FromResult(Result.Ok(true)); + public Task> ExecuteWatchAsync(MechanismWriteArgs args, CancellationToken ct) + => Task.FromResult(Result.Ok(true)); + } + + private sealed class FakeBioBadgeProvider : IBioTabBadgeProvider + { + public FakeBioBadgeProvider(string id, string ownerModId, int order) + { + Id = id; + OwnerModId = ownerModId; + Order = order; + } + + public string Id { get; } + public string OwnerModId { get; } + public int Order { get; } + public BioTabBadgeDescriptor? TryGetBadge(Verse.Pawn pawn) => new BioTabBadgeDescriptor(Id); + } + + private sealed class SampleDto + { + public string? Action { get; set; } + public int Priority { get; set; } + } + + [Fact] + public void ToolScope_projection_scenario_separation_and_declarative_mechanisms() + { + ContractCaseRunner.Run( + ("AgentDecision and AdvisorDecision scenarios are distinct from Decision and wired into modes", () => + { + Assert.NotEqual(ScenarioIds.AgentDecision, ScenarioIds.AdvisorDecision); + Assert.NotEqual(ScenarioIds.AgentDecision, ScenarioIds.Decision); + + var tickProvider = new FakeTickProvider(); + var agentInfo = new FakeAgentInfo(); + var proactive = new ProactiveAgentMode(tickProvider); + var reactive = new ReactiveAgentMode(); + var proactiveEnv = proactive.GetThinkStrategy().BuildEnvelope(agentInfo, Array.Empty(), Array.Empty()); + var reactiveEnv = reactive.GetThinkStrategy().BuildEnvelope(agentInfo, Array.Empty(), Array.Empty()); + Assert.Equal(ScenarioIds.AgentDecision, proactiveEnv.ScenarioId); + Assert.Equal(ScenarioIds.AgentDecision, reactiveEnv.ScenarioId); + }), + ("GetDefinitionsForScope filters WorldAdmin and MetaQuery and compacts schemas", () => + { + var registry = new ToolRegistry(); + string verboseSchema = "{\"type\":\"object\",\"properties\":{\"pawn_id\":{\"type\":\"integer\",\"description\":\"A very long verbose description explaining pawn_id in extreme detail for humans and models alike beyond 72 chars.\"},\"map_id\":{\"type\":\"integer\",\"description\":\"Optional map ID\"},\"def_name\":{\"type\":\"string\",\"enum\":[\"WoodLog\",\"Steel\"],\"description\":\"Long description\"}},\"required\":[\"pawn_id\"]}"; + + registry.Register(new FakeToolHandler(new ToolDefinition + { + Id = "pawn.job.set", + Description = "Assign a concrete job to the colonist.\nExtra verbose line 2.", + ParametersSchema = verboseSchema, + Category = "pawn" + })); + registry.Register(new FakeToolHandler(new ToolDefinition + { + Id = "world.storyteller.trigger", + Description = "Trigger storyteller incident", + ParametersSchema = verboseSchema, + Category = "world" + })); + registry.Register(new FakeToolHandler(new ToolDefinition + { + Id = "pawn.job.list", + Description = "List all job defs", + ParametersSchema = verboseSchema, + Category = "pawn" + })); + registry.Register(new FakeToolHandler(new ToolDefinition + { + Id = "actions_place_blueprint", + Description = "Place blueprint", + ParametersSchema = verboseSchema, + Category = "actions", + Manifest = new ToolManifest { Scopes = ToolScope.ColonyBuild } + })); + + var scoped = registry.GetDefinitionsForScope(ToolScopeProjection.ColonistAgentDefaultScope, compactSchema: true); + var ids = scoped.Select(d => d.Id).ToHashSet(StringComparer.Ordinal); + Assert.Contains("pawn.job.set", ids); + Assert.Contains("actions_place_blueprint", ids); + Assert.DoesNotContain("world.storyteller.trigger", ids); + Assert.DoesNotContain("pawn.job.list", ids); + + var jobDef = scoped.Single(d => d.Id == "pawn.job.set"); + Assert.True(jobDef.ParametersSchema.Length < verboseSchema.Length); + var schemaObj = JObject.Parse(jobDef.ParametersSchema); + Assert.Equal("integer", schemaObj["properties"]?["pawn_id"]?["type"]?.ToString()); + Assert.NotNull(schemaObj["properties"]?["def_name"]?["enum"]); + string? compactedPawnDesc = schemaObj["properties"]?["pawn_id"]?["description"]?.ToString(); + Assert.True(compactedPawnDesc == null || compactedPawnDesc.Length <= 72); + Assert.Null(schemaObj["properties"]?["map_id"]); + + var proactiveAllowed = new ProactiveAgentMode(new FakeTickProvider()).AllowedToolIds(registry); + Assert.Contains("pawn.job.set", proactiveAllowed); + Assert.DoesNotContain("world.storyteller.trigger", proactiveAllowed); + Assert.DoesNotContain("pawn.job.list", proactiveAllowed); + }), + ("MechanismToolHandler resolves DefaultDomain declaratively via IMechanismAutonomyMetadata and populates Kind/Scopes", () => + { + var mech = new FakeAutonomyMechanism(); + var setHandler = new MechanismToolHandler(mech, mech, mech, mech, MechanismOperationType.Set); + var queryHandler = new MechanismToolHandler(mech, mech, mech, mech, MechanismOperationType.Query); + + Assert.Equal(AutonomyDomain.WorkPriorityModification, setHandler.Definition.Manifest.DefaultDomain); + Assert.Equal(ToolKind.Mutation, setHandler.Definition.Manifest.Kind); + Assert.True((setHandler.Definition.Manifest.Scopes!.Value & ToolScope.ColonyManage) != 0); + + Assert.Null(queryHandler.Definition.Manifest.DefaultDomain); + Assert.Equal(ToolKind.Query, queryHandler.Definition.Manifest.Kind); + Assert.Equal(ToolScope.MetaQuery, queryHandler.Definition.Manifest.Scopes); + }), + ("AutonomyDomainRiskMapper provides canonical risk levels", () => + { + Assert.Equal(RiskLevel.Low, AutonomyDomainRiskMapper.MapToRisk(AutonomyDomain.EmergencySurvival)); + Assert.Equal(RiskLevel.Low, AutonomyDomainRiskMapper.MapToRisk(AutonomyDomain.ResourceMarking)); + Assert.Equal(RiskLevel.Medium, AutonomyDomainRiskMapper.MapToRisk(AutonomyDomain.BlueprintPlacement)); + Assert.Equal(RiskLevel.Medium, AutonomyDomainRiskMapper.MapToRisk(AutonomyDomain.WorkPriorityModification)); + Assert.Equal(RiskLevel.High, AutonomyDomainRiskMapper.MapToRisk(AutonomyDomain.HighRiskOperations)); + Assert.Equal(RiskLevel.Low, AutonomyDomainRiskMapper.MapToRisk(null, ToolKind.Query)); + Assert.Equal(RiskLevel.Medium, AutonomyDomainRiskMapper.MapToRisk(null, ToolKind.Mutation)); + })); + } + + [Fact] + public void RequestQueue_enforces_liveness_gate_npc_cancel_coalescing_and_ttl() + { + ContractCaseRunner.Run( + ("pre-dispatch PawnLivenessChecker blocks dead NPC requests by default and respects opt-out", () => + { + var queue = new RequestQueue(); + queue.PawnLivenessChecker = npcId => npcId == "NPC-10"; + int executedCount = 0; + Result? deadResult = null; + Result? optOutResult = null; + + var deadEnv = new LlmRequestEnvelope + { + RequestId = "req-dead", + ModId = "RimMind.Test", + NpcId = "NPC-99", + Messages = new List { new ChatMessage { Role = "user", Content = "hi" } } + }; + var optOutEnv = new LlmRequestEnvelope + { + RequestId = "req-optout", + ModId = "RimMind.Test", + NpcId = "NPC-99", + RequireAliveColonist = false, + Messages = new List { new ChatMessage { Role = "user", Content = "memorial" } } + }; + + using var optOutDone = new ManualResetEventSlim(false); + + queue.Enqueue(deadEnv, r => deadResult = r, _ => + { + Interlocked.Increment(ref executedCount); + return Task.FromResult(Result.Ok(new LlmResponse { Content = "ok" })); + }); + + queue.Enqueue(optOutEnv, r => + { + optOutResult = r; + }, _ => + { + Interlocked.Increment(ref executedCount); + optOutDone.Set(); + return Task.FromResult(Result.Ok(new LlmResponse { Content = "ok" })); + }); + + queue.CurrentTick = 100; + queue.Tick(); + Assert.True(optOutDone.Wait(TimeSpan.FromSeconds(5)), "Opt-out executor did not run within 5s"); + for (int i = 0; i < 50 && (!optOutResult.HasValue || !deadResult.HasValue); i++) + { + queue.CurrentTick = 101 + i; + queue.Tick(); + if (!optOutResult.HasValue || !deadResult.HasValue) + Thread.Sleep(5); + } + + Assert.Equal(1, executedCount); + Assert.True(deadResult.HasValue && deadResult.Value.IsErr); + Assert.Equal(RimMindErrorCode.Cancelled, deadResult!.Value.Error.Code); + Assert.True(optOutResult.HasValue && optOutResult.Value.IsOk); + }), + ("CoalesceKey supersedes stale pending requests so backlogs cannot accumulate", () => + { + var queue = new RequestQueue(); + queue.PauseQueue(); + Result? firstResult = null; + Result? secondResult = null; + int executedCount = 0; + string? executedId = null; + using var secondDone = new ManualResetEventSlim(false); + + var env1 = new LlmRequestEnvelope + { + RequestId = "mem-1", + ModId = "RimMind.Memory", + CoalesceKey = "mem:NPC-5", + Messages = new List { new ChatMessage { Role = "user", Content = "old" } } + }; + var env2 = new LlmRequestEnvelope + { + RequestId = "mem-2", + ModId = "RimMind.Memory", + CoalesceKey = "mem:NPC-5", + Messages = new List { new ChatMessage { Role = "user", Content = "new" } } + }; + + queue.Enqueue(env1, r => firstResult = r, _ => + { + Interlocked.Increment(ref executedCount); + executedId = env1.RequestId; + return Task.FromResult(Result.Ok(new LlmResponse { Content = "old" })); + }); + + queue.Enqueue(env2, r => secondResult = r, _ => + { + Interlocked.Increment(ref executedCount); + executedId = env2.RequestId; + secondDone.Set(); + return Task.FromResult(Result.Ok(new LlmResponse { Content = "new" })); + }); + + Assert.Equal(1, queue.TotalQueuedCount); + queue.ResumeQueue(); + queue.CurrentTick = 200; + queue.Tick(); + Assert.True(secondDone.Wait(TimeSpan.FromSeconds(5)), "Coalesced request executor did not run within 5s"); + for (int i = 0; i < 50 && (!firstResult.HasValue || !secondResult.HasValue); i++) + { + queue.CurrentTick = 201 + i; + queue.Tick(); + if (!firstResult.HasValue || !secondResult.HasValue) + Thread.Sleep(5); + } + + Assert.Equal(1, executedCount); + Assert.Equal("mem-2", executedId); + Assert.True(firstResult.HasValue && firstResult.Value.IsErr); + Assert.Equal(RimMindErrorCode.Cancelled, firstResult!.Value.Error.Code); + Assert.True(secondResult.HasValue && secondResult.Value.IsOk); + }), + ("CancelByNpcId removes queued entries for that NPC only and TTL drops expired entries", () => + { + var queue = new RequestQueue(); + var fakeNow = new DateTime(2026, 11, 21, 10, 0, 0, DateTimeKind.Utc); + queue.UtcClock = () => fakeNow; + queue.PauseQueue(); + queue.CurrentTick = 1000; + + Result? npc1Result = null; + Result? expiredResult = null; + + queue.Enqueue(new LlmRequestEnvelope + { + RequestId = "npc1-req", + ModId = "ModA", + NpcId = "NPC-1" + }, r => npc1Result = r, _ => Task.FromResult(Result.Ok(new LlmResponse()))); + + queue.Enqueue(new LlmRequestEnvelope + { + RequestId = "ttl-req", + ModId = "ModA", + NpcId = "NPC-2", + MaxQueueWaitTicks = 50, + ExpiresAtUtc = fakeNow.AddSeconds(5) + }, r => expiredResult = r, _ => Task.FromResult(Result.Ok(new LlmResponse()))); + + int cancelled = queue.CancelByNpcId("NPC-1", "Colonist died"); + Assert.Equal(1, cancelled); + Assert.Equal(1, queue.TotalQueuedCount); + + queue.ResumeQueue(); + queue.CurrentTick = 1200; // Exceeds MaxQueueWaitTicks = 50 + queue.Tick(); + queue.Tick(); + + Assert.True(npc1Result.HasValue && npc1Result.Value.IsErr); + Assert.Equal(RimMindErrorCode.Cancelled, npc1Result!.Value.Error.Code); + Assert.True(expiredResult.HasValue && expiredResult.Value.IsErr); + Assert.Equal(RimMindErrorCode.Timeout, expiredResult!.Value.Error.Code); + })); + } + + [Fact] + public void LlmPayloadParser_reason_extraction_and_MoteTextFormatter_contracts() + { + ContractCaseRunner.Run( + ("StripThinkingAndCodeFences and ExtractJsonPayload handle thinking tags, fences, and quoted braces", () => + { + string raw = "let me plan {not json}\n```json\n{\"action\":\"eat\",\"note\":\"a {b} c\"}\n```"; + string cleaned = LlmPayloadParser.StripThinkingAndCodeFences(raw); + Assert.Equal("{\"action\":\"eat\",\"note\":\"a {b} c\"}", cleaned); + + string? extracted = LlmPayloadParser.ExtractJsonPayload("Sure! Here is the result: " + raw + " thanks!"); + Assert.Equal("{\"action\":\"eat\",\"note\":\"a {b} c\"}", extracted); + }), + ("TryDeserializeWithRepair repairs trailing commas and extracts JSON cleanly", () => + { + string raw = "hmm\n```json\n{\"Action\":\"build\",\"Priority\":2,}\n```"; + Assert.True(LlmPayloadParser.TryDeserializeWithRepair(raw, out var dto)); + Assert.NotNull(dto); + Assert.Equal("build", dto!.Action); + Assert.Equal(2, dto.Priority); + }), + ("ExtractReasonFromArgumentsJson finds reason nested inside value JSON string (pawn_job_set fix)", () => + { + string nestedArgs = "{\"pawn_id\":42,\"action\":\"take_job\",\"value\":\"{\\\"job_def\\\":\\\"HaulToCell\\\",\\\"reason\\\":\\\"Hauling wood before rain ruins it\\\"}\"}"; + string? reason = LlmPayloadParser.ExtractReasonFromArgumentsJson(nestedArgs); + Assert.Equal("Hauling wood before rain ruins it", reason); + + var resp = new LlmResponse + { + ToolCallsJson = "[{\"id\":\"call_1\",\"function\":{\"name\":\"pawn.job.set\",\"arguments\":" + + Newtonsoft.Json.JsonConvert.SerializeObject(nestedArgs) + "}}]" + }; + var parsedDecision = ThinkStrategyHelper.ParseDecisionCore(resp); + Assert.True(parsedDecision.IsOk); + Assert.Equal("pawn.job.set", parsedDecision.Value.ActionIntent); + Assert.Equal("Hauling wood before rain ruins it", parsedDecision.Value.Reason); + }), + ("ParsePseudoFunctionCalls parses textual function calls", () => + { + string text = "I will haul now. pawn_job_set(pawn_id=12, action=\"take_job\", reason=\"Keep food dry\")"; + var calls = LlmPayloadParser.ParsePseudoFunctionCalls(text); + Assert.Single(calls); + Assert.Equal("pawn_job_set", calls[0].Name); + Assert.Equal("Keep food dry", calls[0].Reason); + }), + ("MoteTextFormatter wraps English and CJK text without overflowing line budget", () => + { + string en = MoteTextFormatter.WrapForMote("Colonists should haul the harvested rice before the storm arrives", 20); + Assert.Contains("\n", en); + Assert.DoesNotContain(" ", en); + + string zh = MoteTextFormatter.WrapForMote("我们必须赶紧把室外的木材搬回仓库里避免淋雨腐烂", 16); + Assert.Contains("\n", zh); + })); + } + + [Fact] + public void Public_protocol_failover_redactor_and_pool_building_blocks() + { + ContractCaseRunner.Run( + ("HttpErrorClassifier separates moderation, quota/auth, transient, and permanent errors", () => + { + Assert.Equal(RimMindErrorCode.ContentFiltered, HttpErrorClassifier.Classify(400, "Content Exists Risk").Code); + Assert.Equal(RimMindErrorCode.ClientQuotaOrAuthFailure, HttpErrorClassifier.Classify(401, "invalid_api_key").Code); + Assert.Equal(RimMindErrorCode.ClientQuotaOrAuthFailure, HttpErrorClassifier.Classify(400, "Insufficient Balance").Code); + Assert.Equal(RimMindErrorCode.ClientTransientFailure, HttpErrorClassifier.Classify(429, "rate_limit").Code); + Assert.Equal(RimMindErrorCode.ClientTransientFailure, HttpErrorClassifier.Classify(503, "unavailable").Code); + Assert.Equal(RimMindErrorCode.ClientPermanentFailure, HttpErrorClassifier.Classify(400, "bad schema").Code); + }), + ("EndpointFailoverPolicy isolates failing nodes and restores on success or cooldown expiry", () => + { + long now = 10_000L; + var policy = new EndpointFailoverPolicy(() => now, defaultIsolationMs: 60_000L, permanentIsolationMs: 600_000L); + var nodes = new[] { "primary", "backup-1", "backup-2" }; + + policy.RecordFailure("primary", RimMindErrors.ClientTransient("503")); + Assert.True(policy.IsIsolated("primary")); + var ordered = policy.OrderCandidates(nodes, n => n); + Assert.Equal("backup-1", ordered[0]); + + now += 61_000L; + Assert.False(policy.IsIsolated("primary")); + + policy.RecordFailure("primary", RimMindErrors.ClientQuotaOrAuth("402")); + Assert.True(policy.IsPermanentlyExhausted("primary")); + policy.RecordSuccess("primary"); + Assert.False(policy.IsPermanentlyExhausted("primary")); + }), + ("PromptZonePartitioner separates L0/L1 static prefix from L2/L3/L5 volatile observations", () => + { + var env = new LlmRequestEnvelope + { + Messages = new List + { + new ChatMessage { Role = "system", LayerTag = "L0", Content = "Rules" }, + new ChatMessage { Role = "system", LayerTag = "L1", Content = "MapTopology" }, + new ChatMessage { Role = "system", LayerTag = "L2", Content = "WeatherRain" }, + new ChatMessage { Role = "system", LayerTag = "L3", Content = "MoodLow" }, + new ChatMessage { Role = "user", Content = "Decide" } + } + }; + var part = PromptZonePartitioner.Partition(env); + Assert.Equal(2, part.StaticSystemPrompts.Count); + Assert.Equal(2, part.VolatileObservations.Count); + Assert.Single(part.LiveNonSystemMessages); + Assert.Equal("Decide", part.LastUserMessage?.Content); + }), + ("OpenAIWireCodec supports single-pass customizePayload and parses cached tokens", () => + { + var env = new LlmRequestEnvelope + { + Messages = new List + { + new ChatMessage { Role = "system", LayerTag = "L0", Content = "System" }, + new ChatMessage { Role = "user", Content = "Hello" } + }, + MaxTokens = 256 + }; + + string json = OpenAIWireCodec.BuildRequestJson( + env, + "test-model", + defaultMaxTokens: 256, + customizePayload: root => root["custom_dialect_flag"] = true); + + var parsedReq = JObject.Parse(json); + Assert.Equal(true, parsedReq["custom_dialect_flag"]?.Value()); + + string respJson = "{\"choices\":[{\"message\":{\"content\":\"hi\",\"reasoning_content\":\"thought\"}}],\"usage\":{\"total_tokens\":120,\"prompt_tokens\":100,\"completion_tokens\":20,\"prompt_tokens_details\":{\"cached_tokens\":80}}}"; + var parsedResp = OpenAIWireCodec.ParseResponse(respJson, env); + Assert.True(parsedResp.IsOk); + Assert.Equal("hi", parsedResp.Value.Content); + Assert.Equal("thought", parsedResp.Value.ReasoningContent); + Assert.Equal(100, parsedResp.Value.PromptTokens); + Assert.Equal(80, parsedResp.Value.CachedTokens); + }), + ("LogSecretRedactor redacts generic credentials and RimMindHttpClientPool classifies loopback hosts", () => + { + string redacted = LogSecretRedactor.ForMessage("Authorization: Bearer sk-abc123456789012345 api_key=my_sk_9999999999999"); + Assert.DoesNotContain("sk-abc123456789012345", redacted); + Assert.DoesNotContain("my_sk_9999999999999", redacted); + + Assert.True(RimMindHttpClientPool.IsLoopbackEndpoint("http://localhost:11434/v1")); + Assert.True(RimMindHttpClientPool.IsLoopbackEndpoint("http://127.0.0.1:8080/v1")); + Assert.False(RimMindHttpClientPool.IsLoopbackEndpoint("https://api.openai.com/v1")); + })); + } + + [Fact] + public void Generic_ui_overlay_biotab_provider_preset_and_action_formatting_contracts() + { + ContractCaseRunner.Run( + ("RequestOverlayLayoutEvaluator.ShouldHideCompletely hides idle empty overlay when auto-hide enabled", () => + { + Assert.True(RequestOverlayLayoutEvaluator.ShouldHideCompletely(0, autoHideWhenEmpty: true, isExpanded: false, isDragging: false, isResizing: false)); + Assert.False(RequestOverlayLayoutEvaluator.ShouldHideCompletely(1, autoHideWhenEmpty: true, isExpanded: false, isDragging: false, isResizing: false)); + Assert.False(RequestOverlayLayoutEvaluator.ShouldHideCompletely(0, autoHideWhenEmpty: false, isExpanded: false, isDragging: false, isResizing: false)); + Assert.False(RequestOverlayLayoutEvaluator.ShouldHideCompletely(0, autoHideWhenEmpty: true, isExpanded: true, isDragging: false, isResizing: false)); + }), + ("BioTabBadgeRegistry orders providers and cleans up by owner", () => + { + BioTabBadgeRegistry.Clear(); + try + { + BioTabBadgeRegistry.Register(new FakeBioBadgeProvider("b2", "ModB", 20)); + BioTabBadgeRegistry.Register(new FakeBioBadgeProvider("a1", "ModA", 10)); + var all = BioTabBadgeRegistry.GetAll(); + Assert.Equal(2, all.Count); + Assert.Equal("a1", all[0].Id); + Assert.Equal("b2", all[1].Id); + + Assert.Equal(1, BioTabBadgeRegistry.UnregisterByOwner("ModA")); + Assert.Single(BioTabBadgeRegistry.GetAll()); + } + finally + { + BioTabBadgeRegistry.Clear(); + } + }), + ("AIProviderRegistry supports preset registration, endpoint matching, and owner cleanup", () => + { + AIProviderRegistry.ResetToDefaults(); + try + { + AIProviderRegistry.RegisterPreset(new AIProviderPreset( + Id: "test_preset", + ProviderId: AIProviders.OpenAI, + Endpoint: "https://api.example.invalid/v1", + ModelName: "example-model", + FallbackLabel: "Example AI", + HostMatchSubstring: "api.example.invalid", + OwnerModId: "TestMod")); + + var matched = AIProviderRegistry.MatchPresetByEndpoint("https://api.example.invalid/v1/chat/completions"); + Assert.NotNull(matched); + Assert.Equal("test_preset", matched!.Id); + Assert.NotEmpty(AIProviderRegistry.GetPresets(AIProviders.OpenAI)); + + AIProviderRegistry.UnregisterByOwner("TestMod"); + Assert.Null(AIProviderRegistry.MatchPresetByEndpoint("https://api.example.invalid/v1")); + } + finally + { + AIProviderRegistry.ResetToDefaults(); + } + }), + ("RimMindPawnLookup.FormatHumanReadableActionName strips generic prefixes cleanly without module hardcoding", () => + { + Assert.Equal("Take Job", RimMindPawnLookup.FormatHumanReadableActionName("pawn.job.take_job")); + Assert.Equal("Place Blueprint", RimMindPawnLookup.FormatHumanReadableActionName("place_blueprint")); + Assert.Equal("Action", RimMindPawnLookup.FormatHumanReadableActionName("")); + })); + } + } +} diff --git a/Tests/Contracts/ProviderRegistryContracts.cs b/Tests/Contracts/ProviderRegistryContracts.cs index 2df6d581..272242e6 100644 --- a/Tests/Contracts/ProviderRegistryContracts.cs +++ b/Tests/Contracts/ProviderRegistryContracts.cs @@ -139,18 +139,21 @@ private sealed class TestClientFactory : RimMind.Application.Common.Interfaces.C [Fact] public void HttpTransport_attaches_opencode_session_header_when_opencode_url_or_key_used() { + RimMind.Infrastructure.Services.Clients.HttpTransport.RegisterDecorator( + RimMind.Infrastructure.Services.Clients.OpenAI.OpenCodeHeaderDecorator.Instance); + using var req1 = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, "https://opencode.ai/zen/go/v1/chat/completions"); - RimMind.Infrastructure.Services.Clients.HttpTransport.EnsureOpenCodeSessionHeader(req1, "https://opencode.ai/zen/go/v1/chat/completions", null); + RimMind.Infrastructure.Services.Clients.HttpTransport.ApplyDecorators(req1, "https://opencode.ai/zen/go/v1/chat/completions", null); Assert.True(req1.Headers.Contains("x-opencode-session")); Assert.StartsWith("rimmind-", System.Linq.Enumerable.First(req1.Headers.GetValues("x-opencode-session"))); using var req2 = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, "https://api.custom.com/v1"); - RimMind.Infrastructure.Services.Clients.HttpTransport.EnsureOpenCodeSessionHeader(req2, "https://api.custom.com/v1", "Bearer oc_sk_test_key_123", "custom-sess"); + RimMind.Infrastructure.Services.Clients.HttpTransport.ApplyDecorators(req2, "https://api.custom.com/v1", "Bearer oc_sk_test_key_123", "custom-sess"); Assert.True(req2.Headers.Contains("x-opencode-session")); Assert.Equal("custom-sess", System.Linq.Enumerable.First(req2.Headers.GetValues("x-opencode-session"))); using var req3 = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, "https://api.openai.com/v1"); - RimMind.Infrastructure.Services.Clients.HttpTransport.EnsureOpenCodeSessionHeader(req3, "https://api.openai.com/v1", "Bearer sk-standard-key"); + RimMind.Infrastructure.Services.Clients.HttpTransport.ApplyDecorators(req3, "https://api.openai.com/v1", "Bearer sk-standard-key"); Assert.False(req3.Headers.Contains("x-opencode-session")); } diff --git a/Tests/Contracts/ToolCallDispatchMiddlewareContract.cs b/Tests/Contracts/ToolCallDispatchMiddlewareContract.cs index b48aa5ee..7dbaab2b 100644 --- a/Tests/Contracts/ToolCallDispatchMiddlewareContract.cs +++ b/Tests/Contracts/ToolCallDispatchMiddlewareContract.cs @@ -3,14 +3,20 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using RimMind.Application.Common.Interfaces.Mechanisms; using RimMind.Application.Common.Interfaces.Tools; using RimMind.Application.Common.Models; using RimMind.Application.Common.Models.Agent; +using RimMind.Application.Common.Models.Context; +using RimMind.Application.Common.Models.Mechanisms; using RimMind.Application.Common.Models.Pipeline; using RimMind.Application.Common.Models.Tools; using RimMind.Application.Features.Pipeline.Unified; +using RimMind.Domain.Enums; using RimMind.Domain.Llm; using RimMind.Domain.ValueObjects; +using RimMind.Infrastructure.Mechanisms; +using RimMind.Testing; using Xunit; namespace RimMind.Tests.Contracts @@ -54,13 +60,146 @@ public void Dispatch_runs_outside_retry_and_circuit_breaker_scopes() Assert.True(RimMindDefaults.MiddlewareOrder.ToolCallDispatch < RimMindDefaults.MiddlewareOrder.UnifiedRetry); } + [Fact] + public async Task Decision_scenarios_defer_mutation_tools_and_mechanism_writes_reject_off_main_thread() + { + await ContractCaseRunner.RunAsync( + ("Decision, AgentDecision, and AdvisorDecision defer mutation tools while allowing query tools", async () => + { + foreach (string scenarioId in new[] { ScenarioIds.Decision, ScenarioIds.AgentDecision, ScenarioIds.AdvisorDecision }) + { + Assert.True(ScenarioIds.IsDecisionScenario(scenarioId)); + + var mutation = new CountingHandler("pawn.job.set", throwOnExecute: false, ToolKind.Mutation); + var compositeMutation = new CountingHandler("actions_stabilize_rest", throwOnExecute: false, ToolKind.Mutation); + var query = new CountingHandler("pawn.health.query", throwOnExecute: false, ToolKind.Query); + var middleware = new ToolCallDispatchMiddleware(new FakeRegistry(mutation, compositeMutation, query)); + + var context = new LlmRequestContext(new LlmRequestEnvelope + { + RequestId = $"req-{scenarioId}", + ModId = "RimMind.Agent", + ScenarioId = scenarioId, + ToolDispatchMode = ToolCallDispatchMode.Auto + }); + + await middleware.InvokeAsync(context, ctx => + { + ctx.Result = Result.Ok(new LlmResponse + { + ToolCallsJson = + "[{\"id\":\"c1\",\"type\":\"function\",\"function\":{\"name\":\"pawn.job.set\",\"arguments\":\"{}\"}}," + + "{\"id\":\"c2\",\"type\":\"function\",\"function\":{\"name\":\"actions_stabilize_rest\",\"arguments\":\"{}\"}}," + + "{\"id\":\"c3\",\"type\":\"function\",\"function\":{\"name\":\"pawn.health.query\",\"arguments\":\"{}\"}}]" + }); + return Task.CompletedTask; + }); + + Assert.Equal(0, mutation.Calls); + Assert.Equal(0, compositeMutation.Calls); + Assert.Equal(1, query.Calls); + Assert.NotNull(context.ToolCallResults); + Assert.Single(context.ToolCallResults!); + Assert.Equal("pawn.health.query", context.ToolCallResults![0].ToolName); + } + }), + ("Decision scenarios with only mutation tools leave ToolCallResults null and never invoke handlers", async () => + { + foreach (string scenarioId in new[] { ScenarioIds.Decision, ScenarioIds.AgentDecision, ScenarioIds.AdvisorDecision }) + { + var mutation = new CountingHandler("pawn.draft.toggle", throwOnExecute: false, ToolKind.Mutation); + var middleware = new ToolCallDispatchMiddleware(new FakeRegistry(mutation)); + var context = new LlmRequestContext(new LlmRequestEnvelope + { + RequestId = $"req-mut-{scenarioId}", + ModId = "RimMind.Agent", + ScenarioId = scenarioId, + ToolDispatchMode = ToolCallDispatchMode.Auto + }); + + await middleware.InvokeAsync(context, ctx => + { + ctx.Result = Result.Ok(new LlmResponse + { + ToolCallsJson = "[{\"id\":\"c1\",\"type\":\"function\",\"function\":{\"name\":\"pawn.draft.toggle\",\"arguments\":\"{}\"}}]" + }); + return Task.CompletedTask; + }); + + Assert.Equal(0, mutation.Calls); + Assert.Null(context.ToolCallResults); + } + }), + ("MechanismToolHandler fails fast on write operations invoked off the Unity main thread", async () => + { + var prev = MechanismToolHandler.IsMainThreadPredicate; + try + { + MechanismToolHandler.IsMainThreadPredicate = () => false; + var fakeMech = new CountingMechanism(); + var setHandler = new MechanismToolHandler(fakeMech, fakeMech, fakeMech, fakeMech, MechanismOperationType.Set); + var result = await setHandler.ExecuteAsync(new ToolCallArgs + { + ToolCallId = "tc-offthread", + ToolName = setHandler.Id, + ArgumentsJson = "{\"pawn_id\":12}" + }, CancellationToken.None); + + Assert.True(result.IsOk); + Assert.True(result.Value.IsError); + Assert.Contains("main thread", result.Value.Content, StringComparison.OrdinalIgnoreCase); + Assert.Equal(0, fakeMech.WriteCalls); + } + finally + { + MechanismToolHandler.IsMainThreadPredicate = prev; + } + })); + } + + private sealed class CountingMechanism : IMechanismReader, IMechanismWriter, IMechanismTrigger, IMechanismMetadata + { + public int WriteCalls { get; private set; } + public string Id => MechanismId; + public string OwnerModId => "TestMod"; + public string MechanismId => "pawn.job"; + public MechanismScope Scope => MechanismScope.Pawn; + public MechanismRisk Risk => MechanismRisk.Moderate; + public IReadOnlyList SupportedOperations => new[] { MechanismOperationType.Set }; + public MechanismDocs Docs => new MechanismDocs { Summary = "test" }; + public IReadOnlyList? GetWriteActions() => null; + public MechanismRisk GetRiskForOperation(MechanismOperationType operation) => Risk; + public Task> ExecuteQueryAsync(MechanismReadArgs args, CancellationToken ct) + => Task.FromResult(Result.Ok("{}")); + public Task, RimMindError>> ExecuteListAsync(int? pawnId, CancellationToken ct) + => Task.FromResult(Result, RimMindError>.Ok(Array.Empty())); + public Task> ExecuteSetAsync(MechanismWriteArgs args, CancellationToken ct) + { WriteCalls++; return Task.FromResult(Result.Ok(true)); } + public Task> ExecuteAddAsync(MechanismWriteArgs args, CancellationToken ct) + { WriteCalls++; return Task.FromResult(Result.Ok(true)); } + public Task> ExecuteRemoveAsync(MechanismWriteArgs args, CancellationToken ct) + { WriteCalls++; return Task.FromResult(Result.Ok(true)); } + public Task> ExecuteToggleAsync(MechanismWriteArgs args, CancellationToken ct) + { WriteCalls++; return Task.FromResult(Result.Ok(true)); } + public Task> ExecuteTriggerAsync(MechanismWriteArgs args, CancellationToken ct) + { WriteCalls++; return Task.FromResult(Result.Ok(true)); } + public Task> ExecuteWatchAsync(MechanismWriteArgs args, CancellationToken ct) + { WriteCalls++; return Task.FromResult(Result.Ok(true)); } + } + private sealed class CountingHandler : IToolHandler { private readonly bool _throw; - public CountingHandler(string id, bool throwOnExecute) { Id = id; _throw = throwOnExecute; } + private readonly ToolKind _kind; + public CountingHandler(string id, bool throwOnExecute, ToolKind kind = ToolKind.Mutation) + { Id = id; _throw = throwOnExecute; _kind = kind; } public string Id { get; } public string OwnerModId => "TestMod"; - public ToolDefinition Definition => new ToolDefinition { Id = Id }; + public ToolDefinition Definition => new ToolDefinition + { + Id = Id, + Manifest = new ToolManifest { Kind = _kind } + }; public int Calls { get; private set; } public Task> ExecuteAsync(ToolCallArgs args, CancellationToken ct) diff --git a/Tests/RimMindCore.Tests.csproj b/Tests/RimMindCore.Tests.csproj index 5f15169d..2a78a203 100644 --- a/Tests/RimMindCore.Tests.csproj +++ b/Tests/RimMindCore.Tests.csproj @@ -71,6 +71,8 @@ + + @@ -93,6 +95,8 @@ + + diff --git a/Tests/VerseStubs.cs b/Tests/VerseStubs.cs index 84de9f8f..4999a8c0 100644 --- a/Tests/VerseStubs.cs +++ b/Tests/VerseStubs.cs @@ -73,6 +73,7 @@ public static class GUI { public static Color color { get; set; } = Color.white; public static bool enabled { get; set; } = true; + public static bool changed { get; set; } public static void BeginGroup(Rect rect) { } public static void EndGroup() { } } @@ -496,6 +497,7 @@ public sealed record WidgetDraw(string Kind, UnityEngine.Rect Rect, string Label public class Listing_Standard { public float ColumnWidth => 400f; + public float CurHeight { get; set; } public void Begin(UnityEngine.Rect rect) { } public void End() { } public void Gap(float gap = 12f) { } @@ -594,6 +596,7 @@ public static bool NullOrEmpty([System.Diagnostics.CodeAnalysis.NotNullWhen(fals public static class Translator { public static bool CanTranslate(this string key) => true; + public static string TranslateSimple(this string key) => key; public static string Translate(this string key) => key; public static string Resolve(this string s) => s; public static string Translate(this string key, string arg1) => $"{key}:{arg1}";