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]*?(?:think|thinking|thought|reasoning)>",
+ 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