diff --git a/.claude/plugins/local/rimworld-mod-dev/skills/rimworld-mod-dev/SKILL.md b/.claude/plugins/local/rimworld-mod-dev/skills/rimworld-mod-dev/SKILL.md deleted file mode 100644 index 1b3829a7..00000000 --- a/.claude/plugins/local/rimworld-mod-dev/skills/rimworld-mod-dev/SKILL.md +++ /dev/null @@ -1,616 +0,0 @@ ---- -name: rimworld-mod-dev -description: This skill should be used when developing RimWorld mods, including creating C# Harmony patches, writing XML Defs, implementing AI integration for pawns or events, setting up mod structure, or debugging RimWorld mod issues. Activates for "rimworld mod", "harmony patch", "pawncomp", "incidentdef", "thinkTree", "storyteller", "jobgiver", "hediff", "defmodextension" topics. -version: 1.0.0 ---- - -# RimWorld Mod Development Skill - -This skill provides guidance for developing RimWorld mods, with a focus on C#/Harmony-based behavior modification and AI integration patterns. - ---- - -## Project Context - -- **Game version**: 1.5 / 1.6 -- **Target framework**: .NET Framework 4.8 (net48) -- **Required dependency**: Harmony (brrainz.harmony) - ---- - -## Mod Folder Structure - -``` -MyMod/ -├── About/ -│ ├── About.xml # Required: mod metadata, dependencies, supported versions -│ └── Preview.png # Required: 640x360 or 1280x720, < 1MB -├── Assemblies/ # Compiled DLL files -├── Defs/ # XML definitions (ThingDef, IncidentDef, etc.) -├── Patches/ # PatchOperations XML (safe cross-mod patching) -├── Languages/ # Localization files -│ └── English/ -│ └── Keyed/ -│ └── Keys.xml # Translation keys -├── Sounds/ # .ogg audio files -├── Textures/ # .png texture files (must be PoT: 32x32, 64x64, etc.) -├── Source/ # C# source code (not loaded by game) -│ └── MyMod/ -│ ├── MyModMain.cs -│ └── ... -└── LoadFolders.xml # Optional: conditional folder loading per version -``` - ---- - -## Core Technology Stack - -| Tech | Purpose | Notes | -|------|---------|-------| -| **Harmony** | Runtime method patching | Use PostFix over Prefix to reduce conflicts | -| **C# async/await** | AI API calls | Never block game main thread | -| **ConcurrentQueue** | Thread-safe result passing | Main thread consumes on next Tick | -| **ThingComp** | Per-pawn state storage | Serialized via ExposeData | -| **DefModExtension** | Extend XML Def fields | No C# subclassing needed | -| **Newtonsoft.Json** | JSON parsing | Already bundled in RimWorld | - ---- - -## AI Integration Pattern - -```csharp -// 1. Harmony patch on TickManager - runs every game tick -[HarmonyPatch(typeof(TickManager), "DoSingleTick")] -public static class TickManagerPatch -{ - static void Postfix() - { - // Consume AI results from queue (main thread safe) - while (AIRequestQueue.Results.TryDequeue(out var result)) - result.Apply(); - - // Enqueue new requests (triggers async AI call) - if (ShouldQueryAI()) - AIRequestQueue.Enqueue(new AIRequest(BuildContext())); - } -} - -// 2. Async AI call (runs on background thread) -public static async Task QueryAI(AIRequest request) -{ - var response = await httpClient.PostAsync(endpoint, content); - var result = ParseResponse(await response.Content.ReadAsStringAsync()); - AIRequestQueue.Results.Enqueue(result); -} -``` - ---- - -## Key Game Systems & How to Hook Them - -### Pawn Behavior (Jobs / ThinkTree) - -```csharp -// Force a pawn to do a specific job -pawn.jobs.StartJob(new Job(JobDefOf.GotoWander, targetCell), JobCondition.InterruptForced); - -// Hook into job giving (Harmony prefix on JobGiver_Work) -[HarmonyPatch(typeof(JobGiver_Work), "TryGiveJob")] -static void Postfix(Pawn pawn, ref Job __result) -{ - if (AIController.ShouldOverride(pawn)) - __result = AIController.GetAIJob(pawn); -} -``` - -### Incidents / Storyteller - -```csharp -// Custom StorytellerComp - AI selects which incident to fire -public class StorytellerComp_AIDirector : StorytellerComp -{ - public override IEnumerable MakeIntervalIncidents(IIncidentTarget target) - { - var chosen = AIDirector.GetNextIncident(target); // reads from result queue - if (chosen != null) - yield return new FiringIncident(chosen, this); - } -} -``` - -XML registration: -```xml - - AIDirectorStoryteller - -
  • - - -``` - -### Thoughts / Mood - -```csharp -// Add a thought (affects mood) -pawn.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.SomeThought); - -// Remove a thought -pawn.needs.mood.thoughts.memories.RemoveMemoriesOfDef(thoughtDef); -``` - -### Mental States - -```csharp -// Trigger mental break -pawn.mindState.mentalStateHandler.TryStartMentalState( - MentalStateDefOf.Berserk, forceWake: true); -``` - -### Faction Relations - -```csharp -Faction.OfPlayer.TryAffectGoodwillWith(otherFaction, delta: 15, - lookTarget: pawn, reason: HistoryEventDefOf.GiftsGiven); -``` - ---- - -## ThingComp Pattern (Per-Pawn State) - -```csharp -// 1. Properties class -public class CompProperties_AIController : CompProperties -{ - public CompProperties_AIController() => compClass = typeof(CompAIController); -} - -// 2. Comp class with save/load -public class CompAIController : ThingComp -{ - public bool AIEnabled = false; - public string LastAIDecision = ""; - - public override void ExposeData() - { - base.ExposeData(); - Scribe_Values.Look(ref AIEnabled, "aiEnabled", false); - Scribe_Values.Look(ref LastAIDecision, "lastAIDecision", ""); - } -} - -// 3. XML patch to add comp to all Pawns -// Patches/AddAIComp.xml -``` - -```xml - - - /Defs/ThingDef[thingClass="Pawn"]/comps - -
  • - - - -``` - ---- - -## Harmony Patch Patterns - -```csharp -// PostFix: runs after original method, can modify result -[HarmonyPatch(typeof(TargetClass), "MethodName")] -public static class MyPatch -{ - static void Postfix(ref ReturnType __result, Pawn __instance, OtherParam param) - { - // __result = modified return value - // __instance = the object the method was called on - } -} - -// Prefix: runs before original, can skip original with return false -[HarmonyPatch(typeof(TargetClass), "MethodName")] -public static class MyPatch -{ - static bool Prefix(ref ReturnType __result, Pawn __instance) - { - if (ShouldSkip(__instance)) - { - __result = myResult; - return false; // skip original - } - return true; // run original - } -} -``` - ---- - -## About.xml Template - -```xml - - - My Mod - YourName - YourName.MyMod - -
  • 1.5
  • -
  • 1.6
  • - - My awesome mod. - -
  • - brrainz.harmony - Harmony - steam://url/CommunityFilePage/2009463077 -
  • -
    - -
  • brrainz.harmony
  • -
    - -``` - ---- - -## Mod Entry Point Pattern - -```csharp -using HarmonyLib; -using Verse; - -namespace MyMod -{ - public class MyModMain : Mod - { - public static MyModSettings Settings; - - public MyModMain(ModContentPack content) : base(content) - { - Settings = GetSettings(); - new Harmony("YourName.MyMod").PatchAll(); - } - - public override string SettingsCategory() => "My Mod"; - public override void DoSettingsWindowContents(Rect rect) - => Settings.DoWindowContents(rect); - } - - public class MyModSettings : ModSettings - { - public string ApiKey = ""; - public string Model = "gpt-4o-mini"; - public int CooldownTicks = 2500; // ~1 game hour - - public override void ExposeData() - { - Scribe_Values.Look(ref ApiKey, "apiKey", ""); - Scribe_Values.Look(ref Model, "model", "gpt-4o-mini"); - Scribe_Values.Look(ref CooldownTicks, "cooldownTicks", 2500); - } - } -} -``` - ---- - -## AI Context Building (Game State → Prompt) - -Key game state to include in AI prompts: - -```csharp -public static string BuildGameContext(Map map) -{ - var sb = new StringBuilder(); - // Colony stats - sb.AppendLine($"Colonists: {map.mapPawns.FreeColonists.Count}"); - sb.AppendLine($"Food: {map.resourceCounter.GetCount(ThingDefOf.MealSimple)}"); - sb.AppendLine($"Threat: {StorytellerUtility.GetThreatBiggestGoodwill(Faction.OfPlayer)}"); - // Recent events (from WorldComponent history) - // Current threats - foreach (var raid in map.attackTargetsCache.TargetsHostileToColony) - sb.AppendLine($"Threat: {raid.Thing.Label}"); - return sb.ToString(); -} -``` - ---- - -## Common XML Def Types - -| Def | Purpose | -|-----|---------| -| `ThingDef` (thingClass=Pawn) | Pawn/creature definition | -| `IncidentDef` | Events (raids, traders, etc.) | -| `StorytellerDef` | Storyteller configuration | -| `ThoughtDef` | Mood thoughts | -| `MentalStateDef` | Mental breaks | -| `JobDef` | Work job types | -| `HediffDef` | Health conditions/implants | -| `TraitDef` | Pawn traits | -| `InteractionDef` | Social interactions | -| `ThinkTreeDef` | AI behavior tree | -| `DutyDef` | Temporary behavior duties | - -## Performance Guidelines - -- AI calls: minimum 2500 ticks (~1 game hour) cooldown between calls per pawn -- Use `ConcurrentQueue` for all cross-thread data transfer -- Cache game state reads (don't traverse all pawns every tick) -- Use `ModsConfig.IsActive("packageId")` for conditional compatibility patches -- Limit AI context to ~500 tokens for routine decisions - ---- - -## Debugging - -```csharp -// Log to RimWorld debug log -Log.Message("[MyMod] Debug info here"); -Log.Warning("[MyMod] Something unexpected"); -Log.Error("[MyMod] Something broke"); - -// Dev mode actions (shows in debug menu) -[DebugAction("MyMod", "Trigger AI Event")] -static void TriggerAIEvent() { /* ... */ } -``` - -Enable dev mode in game: Options → Development Mode - ---- - -## Pitfalls & Lessons Learned - -### 1. UnityWebRequest 只能在主线程调用 - -**症状**:`UnityWebRequest.SendWebRequest()` 在 `Task.Run` 内调用时返回 HTTP 0,无任何错误日志。 - -**原因**:Unity 的 `UnityWebRequest` 不是线程安全的,必须在主线程发起。 - -**修复**:后台线程 HTTP 调用改用 `System.Net.Http.HttpClient`(net48 支持,线程安全): - -```csharp -private static readonly HttpClient _httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(30) }; - -// 可在 Task.Run 内安全调用 -using var req = new HttpRequestMessage(HttpMethod.Post, endpoint) { Content = content }; -req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey); -using var res = await _httpClient.SendAsync(req); -``` - ---- - -### 2. OpenAI 兼容 API 的 FormatEndpoint 三段式逻辑 - -用户填写的 endpoint 格式不一,需统一处理: - -```csharp -private static string FormatEndpoint(string baseUrl) -{ - if (string.IsNullOrEmpty(baseUrl)) return string.Empty; - string trimmed = baseUrl.Trim().TrimEnd('/'); - // 已是完整 endpoint → 不变 - if (trimmed.EndsWith("/chat/completions", StringComparison.OrdinalIgnoreCase)) - return trimmed; - var uri = new Uri(trimmed); - string path = uri.AbsolutePath.Trim('/'); - // 有版本路径(如 /v1)→ 只追加 /chat/completions - if (!string.IsNullOrEmpty(path)) - return trimmed + "/chat/completions"; - // 裸域名 → 追加 /v1/chat/completions - return trimmed + "/v1/chat/completions"; -} -``` - -| 输入 | 输出 | -|------|------| -| `https://api.deepseek.com` | `https://api.deepseek.com/v1/chat/completions` | -| `https://api.deepseek.com/v1` | `https://api.deepseek.com/v1/chat/completions` | -| `https://api.deepseek.com/v1/chat/completions` | 原样返回 | - ---- - -### 3. net48 中禁止使用 `dynamic` 类型 - -**症状**:编译报错,缺少 `Microsoft.CSharp` 引用。 - -**替代方案**:用 Newtonsoft.Json 的 `JObject`: - -```csharp -// 不要用 dynamic -// dynamic obj = JsonConvert.DeserializeObject(text); // 编译失败 - -// 改用 JObject -var jobj = JObject.Parse(text); -string reply = jobj["choices"]?[0]?["message"]?["content"]?.ToString() ?? ""; -int tokens = jobj["usage"]?["total_tokens"]?.Value() ?? 0; -``` - ---- - -### 4. RimWorld 纹理必须是 2 的幂次方(PoT) - -**症状**:`Texture X.png is being reloaded with reduced mipmap count (clamped to 2) due to non-power-of-two dimensions: (24x24)` - -**原因**:RimWorld(Unity)要求 UI 纹理尺寸为 2 的幂次方(16、32、64…)。 - -**规则**: -- 不要用游戏内置的非 PoT 纹理(如 `UI/Buttons/Info` 是 24×24) -- 自己提供纹理放在 `Textures/UI/MyMod/Icon.png`,使用 32×32 或 64×64 - -```csharp -// 错误:复用游戏内置 24×24 纹理 -ContentFinder.Get("UI/Buttons/Info", reportFailure: false) - -// 正确:使用自己的 32×32 纹理 -ContentFinder.Get("UI/MyMod/Icon", reportFailure: false) -``` - ---- - -### 5. `[DebugAction]` Dev 菜单搜索按动作名,不按分类名 - -Dev 菜单搜索框只匹配**动作名称**,不匹配 category 参数。 - -```csharp -// category="MyMod", name="Test API Connection" -[DebugAction("MyMod", "Test API Connection", actionType = DebugActionType.Action)] -``` - -- 搜索 `"MyMod"` → **找不到** -- 搜索 `"Test API"` → **可以找到** -- 或者在 Actions 列表滚动到 "MyMod" 分类下查看 - ---- - -### 6. Keyed XML 不会产生翻译错误 - -"Translation data has X errors" 这条日志**只来自 `DefInjected/` 翻译文件**(key 与 Def 不匹配时触发)。 - -`Languages/*/Keyed/*.xml` 无论多余还是缺失 key 都**不会**触发该错误: -- 多余的 key → 静默忽略 -- 缺失的 key → 代码中显示 key 原文字符串 - -如果看到翻译错误,首先检查其他 mod 的 DefInjected 目录,而非自己的 Keyed 文件。 - ---- - -### 7. WorkGiver 三模式扫描:用 `wg.def.scanCells` 区分,而非类型判断 - -**背景**:枚举某 WorkType 可执行目标时,WorkGiver 有三种工作模式。 - -**错误做法**:`if (scanner is WorkGiver_Grower)` — 只覆盖 Growing,漏掉 SmoothWall、BuildRoof、RemoveRoof、ClearSnow、PaintFloor 等 8 个格子类 WorkGiver。 - -**正确做法**:用 `wg.def.scanCells` 属性区分,与具体类型无关: - -```csharp -foreach (var wg in workType.workGiversByPriority) -{ - if (wg.Worker is not WorkGiver_Scanner scanner) continue; - - if (wg.scanCells) - { - // 格子类:Growing / SmoothWall / BuildRoof / RemoveRoof / - // ClearSnow / PaintFloor / ClearPollution 等 - var cells = scanner.PotentialWorkCellsGlobal(pawn); - foreach (var cell in cells) - { - if (scanner.HasJobOnCell(pawn, cell, false)) - // 处理 cell 目标 - } - } - else - { - // 物体类(默认):Mining / Hauling / Tend / Hunt 等 - // DoBill 工作台(Cooking / Crafting / Smithing)也在此分支, - // 额外通过 IBillGiver.BillStack.FirstShouldDoNow 获取账单名称 - var things = scanner.PotentialWorkThingsGlobal(pawn); - foreach (var thing in things) - { - if (scanner.HasJobOnThing(pawn, thing, false)) - // 处理 thing 目标 - } - } -} -``` - -`IBillGiver` 账单名称: -```csharp -if (thing is IBillGiver billGiver) -{ - var bill = billGiver.BillStack?.FirstShouldDoNow; - label = bill != null ? $"{thing.LabelShort} → {bill.LabelCap}" : thing.LabelShort; -} -``` - -所有 WorkGiver 调用包在 `try-catch` 内,部分 WorkGiver 在特定地图状态下会抛异常。 - ---- - -### 8. 插件 API 可扩展分类:C# 8 接口默认方法代替硬编码 HashSet - -**问题**:`ExecuteBatch` 需要知道哪些动作是 Job 类(需要 `requestQueueing`),原实现用硬编码 HashSet: -```csharp -// 脆弱:外部 mod 注册的 Job 类动作不在此集合中 -private static readonly HashSet _jobBasedIntents = new() { "force_rest", "assign_work", ... }; -``` - -**修复**:用 C# 8 接口默认方法声明扩展点: -```csharp -public interface IActionRule -{ - bool IsJobBased => false; // 默认非 Job 类;Job 类实现覆盖为 true - bool Execute(Pawn actor, Pawn? target, string? param, bool requestQueueing = false); -} - -// 内置 Job 类动作 -public class ForceRestAction : IActionRule -{ - public bool IsJobBased => true; - // ... -} - -// ExecuteBatch 直接读属性,无需查 HashSet -bool isJobAction = rule.IsJobBased; -``` - -**优点**:外部 mod 注册自定义 Job 类动作时,只需在自己的类中声明 `public bool IsJobBased => true;`,框架代码无需改动。 - ---- - -### 9. RimWorld AI 空闲判断:GotoWander ≠ 游戏空闲,但 = AI 可接管 - -**问题**:`pawn.jobs.curJob == null` 不足以判断"AI 是否可以重定向小人"。 - -- `GotoWander`:小人在漫步,`curJob != null`,游戏认为不空闲 -- `playerForced = true`:玩家手动命令的 Job,AI 不应打断 - -**正确的 AI 可接管判断**: - -```csharp -public static bool IsAdvisorIdle(Pawn pawn) -{ - var job = pawn.jobs?.curJob; - if (job == null) return true; - if (job.playerForced) return false; // 玩家命令优先 - - // 这些 Job 类型 AI 可安全打断 - var def = job.def; - return def == JobDefOf.Wait - || def == JobDefOf.Wait_Wander - || def == JobDefOf.GotoWander - || def == JobDefOf.Wait_MaintainPosture; -} -``` - -调试输出应明确区分:`"是否空闲(AI 可接管)"` 而非 `"游戏空闲"`,避免概念混淆。 - ---- - -### 10. ModSettings 孤儿条目:warn 但不删除,保留以备 mod 重启恢复 - -**场景**:玩家禁用了某外部 mod 的某动作(存入 `DisabledIntents`),然后卸载该外部 mod。 -下次加载时该 intentId 不再注册,但 `DisabledIntents` 仍保存着它。 - -**策略**:`[StaticConstructorOnStartup]`(所有 Mod 构造器完成后运行,此时所有动作已注册)中验证并 **warn 但不删除**: - -```csharp -[StaticConstructorOnStartup] -internal static class ActionsSettingsValidator -{ - static ActionsSettingsValidator() - { - if (MyModMain.Settings == null) return; - var registered = new HashSet(MyModAPI.GetSupportedIntents()); - foreach (var id in MyModMain.Settings.DisabledIntents) - { - if (!registered.Contains(id)) - Log.Warning($"[MyMod] 设置中有未注册的动作 '{id}'(对应 mod 未加载?),已保留以备恢复。"); - } - } -} -``` - -**为什么不删除**:若玩家重新启用该外部 mod,孤儿条目会自动重新生效,无需玩家重新配置。 diff --git a/AGENTS.md b/AGENTS.md index 1339f40b..7f4d1c0c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,9 +9,9 @@ RimMind 的运行时与公共 API 前置。Core 负责 LLM 请求、上下文、 - AI 请求:`Source/Application/Features/Requests/README.md` - 上下文:`Source/Presentation/Context/README.md` - Agent:`Source/Presentation/Agent/PawnAgent.cs` -- 自治分级治理:`Source/Application/Features/Agent/AgentAutonomyPolicyService.cs`(`AutonomyDomain` / `AutonomyLevel`) +- 自治分级治理:`Source/Domain/Agent/Policies/AgentAutonomyPolicy.cs`(`AutonomyDomain` / `AutonomyLevel`) - ToolCall 与渐进式帮助:`Source/Application/Features/Pipeline/Unified/ToolCallDispatchMiddleware.cs`、`Source/Application/Features/Tools/QueryToolHelpTool.cs` -- 主备端点容灾:`Source/Domain/Settings/BackupEndpointNode.cs`、`Source/Infrastructure/Services/Clients/OpenAI/OpenAIClient.cs` +- 主备端点容灾:`Source/Application/Common/Models/Client/BackupEndpointNode.cs`、`Source/Infrastructure/Services/Clients/OpenAI/OpenAIClient.cs` - 组合与生命周期:`Source/Presentation/Runtime/RimMindCompositionRoot.cs` - 游戏内调试:`Source/Infrastructure/UI/DebugActions/README.md` - Agent 流程实验室:`Source/Infrastructure/UI/AgentFlow/README.md` diff --git a/ArchTests/ArchTestExtensions.cs b/ArchTests/ArchTestExtensions.cs index 73297a83..c1a57d5e 100644 --- a/ArchTests/ArchTestExtensions.cs +++ b/ArchTests/ArchTestExtensions.cs @@ -2,38 +2,14 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Reflection; -using System.Reflection.Metadata; -using System.Reflection.PortableExecutable; +using System.Text.RegularExpressions; using System.Xml.Linq; -using NetArchTest.Rules; +using Xunit; namespace RimMind.Core.ArchTests { public static class ArchTestExtensions { - public static string FormatFailingTypes(this TestResult result) - { - if (result.IsSuccessful) - return string.Empty; - - var names = result.FailingTypes? - .Select(t => t.FullName ?? t.Name) - .OrderBy(n => n) - ?? Enumerable.Empty(); - - return string.Join("\n ", names); - } - - public static string FormatFailingTypes(this IEnumerable types) - { - var names = types - .Select(t => t.FullName ?? t.Name) - .OrderBy(n => n); - - return string.Join("\n ", names); - } - public static string FindSourceDirectory() { var dir = Path.GetDirectoryName(typeof(ArchTestExtensions).Assembly.Location); @@ -50,63 +26,74 @@ public static string FindSourceDirectory() return ""; } - public static string LocateAssembly(string fileName) + public static string RequireSourceDirectory() { - var sourceDir = FindSourceDirectory(); - var gameVersion = "1.6"; - - var candidates = new List(); - - if (!string.IsNullOrEmpty(sourceDir)) - { - candidates.Add(Path.Combine(sourceDir, "..", gameVersion, "Assemblies", fileName)); - candidates.Add(Path.Combine(sourceDir, "..", "Assemblies", fileName)); - } - - candidates.Add(Path.Combine(AppContext.BaseDirectory, fileName)); - - foreach (var candidate in candidates) - { - var full = Path.GetFullPath(candidate); - if (File.Exists(full)) - return full; - } + string source = FindSourceDirectory(); + Assert.True(Directory.Exists(source), "RimMind-Core/Source must be discoverable."); + return source; + } - throw new FileNotFoundException( - $"R-D: 找不到 {fileName}。搜索路径:\n {string.Join("\n ", candidates.Select(Path.GetFullPath))}\n" + - "请先构建三个源码项目: dotnet build RimMind-Core/Source/Domain/RimMindCore.Domain.csproj 等"); + public static string RepositoryRoot() + { + string source = RequireSourceDirectory(); + DirectoryInfo? core = Directory.GetParent(source); + Assert.NotNull(core); + DirectoryInfo? root = core!.Parent; + Assert.NotNull(root); + return root!.FullName; } - public static bool TryLocateAssembly(string fileName, out string? path) + public static IEnumerable SourceFiles(string directory) { - path = null; - try - { - path = LocateAssembly(fileName); - return true; - } - catch (FileNotFoundException) - { - return false; - } + Assert.True(Directory.Exists(directory), $"Source directory must exist: {directory}"); + return Directory.EnumerateFiles(directory, "*.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))); } - public static HashSet GetAssemblyReferences(string assemblyPath) + public static string StripComments(string source) { - var refs = new HashSet(StringComparer.OrdinalIgnoreCase); + return Regex.Replace( + source, + @"//[^\r\n]*|/\*.*?\*/", + " ", + RegexOptions.Singleline | RegexOptions.CultureInvariant); + } - using var stream = File.OpenRead(assemblyPath); - using var peReader = new PEReader(stream); - var metadataReader = peReader.GetMetadataReader(); + public static string StripCommentsAndStrings(string source) + { + return Regex.Replace( + source, + @"@""(?:""""|[^""])*""|""(?:\\.|[^""\\])*""|'(?:\\.|[^'\\])'|//[^\r\n]*|/\*.*?\*/", + " ", + RegexOptions.Singleline | RegexOptions.CultureInvariant); + } - foreach (var handle in metadataReader.AssemblyReferences) + public static string ExtractBraceBalancedBlock(string code, int startIndex) + { + int openBrace = code.IndexOf('{', startIndex); + Assert.True(openBrace >= startIndex, "Method opening brace must be discoverable."); + int depth = 0; + for (int i = openBrace; i < code.Length; i++) { - var asmRef = metadataReader.GetAssemblyReference(handle); - var name = metadataReader.GetString(asmRef.Name); - refs.Add(name); + if (code[i] == '{') + { + depth++; + } + else if (code[i] == '}') + { + depth--; + if (depth == 0) + { + return code.Substring(startIndex, i - startIndex + 1); + } + } } - return refs; + Assert.Fail("Unbalanced braces when extracting method block."); + return string.Empty; } public static CsprojAnalysis AnalyzeCsproj(string csprojPath) @@ -134,6 +121,7 @@ public static CsprojAnalysis AnalyzeCsproj(string csprojPath) .FirstOrDefault() ?? Path.GetFileNameWithoutExtension(csprojPath); var targetFramework = doc.Descendants(ns + "TargetFramework") + .Concat(doc.Descendants(ns + "TargetFrameworks")) .Select(el => el.Value) .FirstOrDefault() ?? ""; diff --git a/ArchTests/Contracts/CoreGenericSeparationContracts.cs b/ArchTests/Contracts/CoreGenericSeparationContracts.cs index 57b295f1..bdc74042 100644 --- a/ArchTests/Contracts/CoreGenericSeparationContracts.cs +++ b/ArchTests/Contracts/CoreGenericSeparationContracts.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text.RegularExpressions; using RimMind.Testing; using Xunit; @@ -18,8 +17,7 @@ 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."); + string sourceRoot = ArchTestExtensions.RequireSourceDirectory(); ContractCaseRunner.Run( ("no vendor literals outside concrete client adapters and dev harnesses", () => @@ -38,13 +36,13 @@ public void Core_source_maintains_generic_vs_specific_separation_invariants() }; var violations = new List(); - foreach (string file in EnumerateCoreSourceFiles(sourceRoot)) + foreach (string file in ArchTestExtensions.SourceFiles(sourceRoot)) { string rel = Path.GetRelativePath(sourceRoot, file).Replace('\\', '/'); if (IsAllowedVendorAdapterPath(rel)) continue; - string code = StripComments(File.ReadAllText(file)); + string code = ArchTestExtensions.StripComments(File.ReadAllText(file)); foreach (string literal in forbiddenVendors) { if (code.IndexOf(literal, StringComparison.OrdinalIgnoreCase) >= 0) @@ -61,7 +59,7 @@ public void Core_source_maintains_generic_vs_specific_separation_invariants() ("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)); + string code = ArchTestExtensions.StripComments(File.ReadAllText(transportPath)); Assert.DoesNotContain("opencode", code, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("oc_sk_", code, StringComparison.OrdinalIgnoreCase); Assert.Contains("IHttpRequestDecorator", code, StringComparison.Ordinal); @@ -69,7 +67,7 @@ public void Core_source_maintains_generic_vs_specific_separation_invariants() ("CoreContextProviders contains zero Storyteller prompt literals", () => { string providersPath = Path.Combine(sourceRoot, "Presentation", "Context", "CoreContextProviders.cs"); - string code = StripComments(File.ReadAllText(providersPath)); + string code = ArchTestExtensions.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); @@ -77,26 +75,23 @@ public void Core_source_maintains_generic_vs_specific_separation_invariants() ("MechanismToolHandler uses declarative IMechanismAutonomyMetadata instead of hardcoding pawn.work", () => { string handlerPath = Path.Combine(sourceRoot, "Infrastructure", "Mechanisms", "MechanismToolHandler.cs"); - string code = StripComments(File.ReadAllText(handlerPath)); + string code = ArchTestExtensions.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", () => + ("Core production code contains zero hardcoded Actions tool prefixes outside dev debug harnesses", () => { - 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) + foreach (string path in ArchTestExtensions.SourceFiles(sourceRoot)) { - string code = StripComments(File.ReadAllText(path)); + string rel = Path.GetRelativePath(sourceRoot, path).Replace('\\', '/'); + if (rel.StartsWith("Infrastructure/UI/DebugActions/", StringComparison.OrdinalIgnoreCase)) + continue; + + string code = ArchTestExtensions.StripComments(File.ReadAllText(path)); if (code.IndexOf("actions_", StringComparison.OrdinalIgnoreCase) >= 0) { - violations.Add(Path.GetRelativePath(sourceRoot, path)); + violations.Add(rel); } } @@ -107,13 +102,72 @@ public void Core_source_maintains_generic_vs_specific_separation_invariants() ("RimMindRuntimeGameComponent.NotifyGameStopped uses pure IGameScopedService dispatch without Player2 hardcoding", () => { string compPath = Path.Combine(sourceRoot, "Presentation", "Runtime", "RimMindRuntimeGameComponent.cs"); - string code = StripComments(File.ReadAllText(compPath)); + string code = ArchTestExtensions.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); + string methodBody = ArchTestExtensions.ExtractBraceBalancedBlock(code, start); Assert.DoesNotContain("Player2GameLifecycleService", methodBody, StringComparison.Ordinal); + }), + ("Application layer contains zero Infrastructure/Verse adapter string leaks", () => + { + string appDir = Path.Combine(sourceRoot, "Application"); + var violations = new List(); + foreach (string file in ArchTestExtensions.SourceFiles(appDir)) + { + string code = ArchTestExtensions.StripComments(File.ReadAllText(file)); + if (code.IndexOf("VerseLogSink", StringComparison.Ordinal) >= 0 + || code.IndexOf("LongEventHandler", StringComparison.Ordinal) >= 0) + { + violations.Add(Path.GetRelativePath(sourceRoot, file)); + } + } + + Assert.True( + violations.Count == 0, + $"Application must not reference Infrastructure/Verse adapter names:{Environment.NewLine}{string.Join(Environment.NewLine, violations)}"); + }), + ("Application generic seams stay free of hardcoded submodule/vendor/test leaks", () => + { + string schemaCode = ArchTestExtensions.StripComments(File.ReadAllText( + Path.Combine(sourceRoot, "Application", "Features", "Context", "SchemaRegistry.cs"))); + Assert.DoesNotContain("PersonalityOutput", schemaCode, StringComparison.Ordinal); + Assert.DoesNotContain("IncidentOutput", schemaCode, StringComparison.Ordinal); + Assert.DoesNotContain("DarkMemoryOutput", schemaCode, StringComparison.Ordinal); + + string credCode = ArchTestExtensions.StripComments(File.ReadAllText( + Path.Combine(sourceRoot, "Application", "Common", "Interfaces", "Internal", "IApiCredentialSettings.cs"))); + Assert.DoesNotContain("Player2RemoteUrl", credCode, StringComparison.Ordinal); + Assert.DoesNotContain("IsOpenAIConfigured", credCode, StringComparison.Ordinal); + + string clientMgrCode = ArchTestExtensions.StripComments(File.ReadAllText( + Path.Combine(sourceRoot, "Application", "Common", "Interfaces", "Internal", "IClientManager.cs"))); + Assert.DoesNotContain("GetPlayer2Client", clientMgrCode, StringComparison.Ordinal); + + string codecCode = ArchTestExtensions.StripComments(File.ReadAllText( + Path.Combine(sourceRoot, "Application", "Features", "Llm", "OpenAIWireCodec.cs"))); + Assert.DoesNotContain("\"RimMind.Test\"", codecCode, StringComparison.Ordinal); + + string registryCode = ArchTestExtensions.StripComments(File.ReadAllText( + Path.Combine(sourceRoot, "Application", "Features", "Tools", "ToolRegistry.cs"))); + Assert.DoesNotContain("IToolRegistry? Current", registryCode, StringComparison.Ordinal); + + string orchestratorCode = ArchTestExtensions.StripComments(File.ReadAllText( + Path.Combine(sourceRoot, "Application", "Features", "Agent", "ProactiveBehaviorOrchestrator.cs"))); + Assert.DoesNotContain("TaskScheduler.Current", orchestratorCode, StringComparison.Ordinal); + + string redactorCode = ArchTestExtensions.StripComments(File.ReadAllText( + Path.Combine(sourceRoot, "Application", "Features", "Llm", "LogSecretRedactor.cs"))); + Assert.Contains("AIza[A-Za-z0-9", redactorCode, StringComparison.Ordinal); + + string reactiveCode = ArchTestExtensions.StripComments(File.ReadAllText( + Path.Combine(sourceRoot, "Application", "Features", "Agent", "Modes", "ReactiveAgentMode.cs"))); + Assert.DoesNotContain("ExcludedToolPrefixes", reactiveCode, StringComparison.Ordinal); + Assert.Contains("RequiresProactiveMode", reactiveCode, StringComparison.Ordinal); + + string taskBuilderCode = ArchTestExtensions.StripComments(File.ReadAllText( + Path.Combine(sourceRoot, "Application", "Features", "Prompt", "TaskInstructionBuilder.cs"))); + Assert.DoesNotContain("StripDiacritics", taskBuilderCode, StringComparison.Ordinal); + Assert.Contains("CanTranslate", taskBuilderCode, StringComparison.Ordinal); })); } @@ -123,23 +177,5 @@ private static bool IsAllowedVendorAdapterPath(string relativeSlashPath) || 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 90a28a5c..59457d8a 100644 --- a/ArchTests/Contracts/CrossModBoundaryContracts.cs +++ b/ArchTests/Contracts/CrossModBoundaryContracts.cs @@ -19,7 +19,9 @@ public void Dependent_mods_use_capabilities_instead_of_runtime_hub_access() ("generic service lookup is not consumed", () => AssertDependentSourceAbsent(@"\bGetService\s*<")), ("generic try lookup is not consumed", () => AssertDependentSourceAbsent(@"\bTryGetService\s*<")), ("runtime service hub is not consumed", () => AssertDependentSourceAbsent(@"\bRuntimeServiceHub\b")), - ("runtime snapshots are not consumed", () => AssertDependentSourceAbsent(@"\bRuntimeServiceSnapshot\b"))); + ("runtime snapshots are not consumed", () => AssertDependentSourceAbsent(@"\bRuntimeServiceSnapshot\b")), + ("settings singleton is not consumed", () => AssertDependentSourceAbsent(@"RimMindCoreMod\s*\.\s*Settings")), + ("internal core namespace is not consumed", () => AssertDependentSourceAbsent(@"\bRimMind\.Core\.Internal\b"))); } [Fact] @@ -37,7 +39,9 @@ public void Feature_mod_dependencies_remain_directional() ("dialogue does not depend on peer feature mods", () => AssertNoUsing("RimMind-Dialogue", "Actions", "Advisor", "Memory", "Personality", "Storyteller", "Bridge")), ("storyteller does not depend on peer feature mods", () => - AssertNoUsing("RimMind-Storyteller", "Actions", "Advisor", "Memory", "Personality", "Dialogue", "Bridge"))); + AssertNoUsing("RimMind-Storyteller", "Actions", "Advisor", "Memory", "Personality", "Dialogue", "Bridge")), + ("extension model service does not depend on peer feature mods", () => + AssertNoUsing("RimMind-Extension-ModelService", "Actions", "Advisor", "Memory", "Personality", "Dialogue", "Storyteller", "Bridge"))); } [Fact] @@ -106,10 +110,13 @@ public void Core_production_code_does_not_hardcode_submod_package_ids() "mcocdaa.RimMindActions", "mcocdaa.RimMindDialogue", "mcocdaa.RimMindPersonality", - "mcocdaa.RimMindStoryteller" + "mcocdaa.RimMindStoryteller", + "mcocdaa.RimMindModelService", + "mcocdaa.RimMindBridgeRimTalk", + "mcocdaa.RimMindBridgeRimChat" }; - var productionFiles = SourceFiles(coreSourceDir).ToArray(); + var productionFiles = ArchTestExtensions.SourceFiles(coreSourceDir).ToArray(); ContractCaseRunner.Run( forbiddenPackageIds @@ -132,7 +139,7 @@ public void Core_production_code_does_not_hardcode_submod_package_ids() [Fact] public void Downstream_submodules_maintain_generic_vs_specific_separation_boundaries() { - string root = RepositoryRoot(); + string root = ArchTestExtensions.RepositoryRoot(); string[] allDependentMods = { "RimMind-Actions", @@ -156,8 +163,8 @@ public void Downstream_submodules_maintain_generic_vs_specific_separation_bounda var violations = allDependentMods .Select(mod => Path.Combine(root, mod, "Source")) .Where(Directory.Exists) - .SelectMany(SourceFiles) - .Where(file => pattern.IsMatch(StripCommentsAndStrings(File.ReadAllText(file)))) + .SelectMany(ArchTestExtensions.SourceFiles) + .Where(file => pattern.IsMatch(ArchTestExtensions.StripCommentsAndStrings(File.ReadAllText(file)))) .Select(file => Path.GetRelativePath(root, file)) .OrderBy(path => path, StringComparer.Ordinal) .ToArray(); @@ -172,8 +179,8 @@ public void Downstream_submodules_maintain_generic_vs_specific_separation_bounda if (!Directory.Exists(perceptionDir)) return; - var violations = SourceFiles(perceptionDir) - .Where(file => StripCommentsOnly(File.ReadAllText(file)).IndexOf("actions_", StringComparison.OrdinalIgnoreCase) >= 0) + var violations = ArchTestExtensions.SourceFiles(perceptionDir) + .Where(file => ArchTestExtensions.StripComments(File.ReadAllText(file)).IndexOf("actions_", StringComparison.OrdinalIgnoreCase) >= 0) .Select(file => Path.GetRelativePath(root, file)) .OrderBy(path => path, StringComparer.Ordinal) .ToArray(); @@ -191,8 +198,8 @@ public void Downstream_submodules_maintain_generic_vs_specific_separation_bounda var violations = allDependentMods .Select(mod => Path.Combine(root, mod, "Source")) .Where(Directory.Exists) - .SelectMany(SourceFiles) - .Where(file => pattern.IsMatch(StripCommentsAndStrings(File.ReadAllText(file)))) + .SelectMany(ArchTestExtensions.SourceFiles) + .Where(file => pattern.IsMatch(ArchTestExtensions.StripCommentsAndStrings(File.ReadAllText(file)))) .Select(file => Path.GetRelativePath(root, file)) .OrderBy(path => path, StringComparer.Ordinal) .ToArray(); @@ -203,22 +210,13 @@ public void Downstream_submodules_maintain_generic_vs_specific_separation_bounda })); } - 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); - string root = RepositoryRoot(); + string root = ArchTestExtensions.RepositoryRoot(); IReadOnlyList violations = DiscoverDependentMods() - .SelectMany(mod => SourceFiles(Path.Combine(root, mod, "Source"))) - .Where(file => pattern.IsMatch(StripCommentsAndStrings(File.ReadAllText(file)))) + .SelectMany(mod => ArchTestExtensions.SourceFiles(Path.Combine(root, mod, "Source"))) + .Where(file => pattern.IsMatch(ArchTestExtensions.StripCommentsAndStrings(File.ReadAllText(file)))) .Select(file => Path.GetRelativePath(root, file)) .OrderBy(path => path, StringComparer.Ordinal) .ToArray(); @@ -235,7 +233,7 @@ private static void AssertNoUsing(string mod, params string[] forbiddenModules) private static void AssertNoPattern(string mod, string forbiddenPattern) { - string root = RepositoryRoot(); + string root = ArchTestExtensions.RepositoryRoot(); string modSourceDir = Path.Combine(root, mod, "Source"); if (!Directory.Exists(modSourceDir) && DiscoverDependentMods().Count == 0) { @@ -245,8 +243,8 @@ private static void AssertNoPattern(string mod, string forbiddenPattern) var pattern = new Regex( forbiddenPattern, RegexOptions.Multiline | RegexOptions.CultureInvariant); - IReadOnlyList violations = SourceFiles(modSourceDir) - .Where(file => pattern.IsMatch(StripCommentsAndStrings(File.ReadAllText(file)))) + IReadOnlyList violations = ArchTestExtensions.SourceFiles(modSourceDir) + .Where(file => pattern.IsMatch(ArchTestExtensions.StripCommentsAndStrings(File.ReadAllText(file)))) .Select(file => Path.GetRelativePath(root, file)) .OrderBy(path => path, StringComparer.Ordinal) .ToArray(); @@ -257,7 +255,7 @@ private static void AssertNoPattern(string mod, string forbiddenPattern) private static IReadOnlyList DiscoverDependentMods() { - string root = RepositoryRoot(); + string root = ArchTestExtensions.RepositoryRoot(); return Directory.EnumerateDirectories(root, "RimMind-*", SearchOption.TopDirectoryOnly) .Where(directory => !Path.GetFileName(directory).Equals("RimMind-Core", StringComparison.OrdinalIgnoreCase)) .Where(directory => Directory.Exists(Path.Combine(directory, "Source"))) @@ -267,35 +265,5 @@ private static IReadOnlyList DiscoverDependentMods() .OrderBy(name => name, StringComparer.Ordinal) .ToArray(); } - - private static string StripCommentsAndStrings(string source) - { - return Regex.Replace( - source, - @"@""(?:""""|[^""])*""|""(?:\\.|[^""\\])*""|'(?:\\.|[^'\\])'|//[^\r\n]*|/\*.*?\*/", - " ", - RegexOptions.Singleline | RegexOptions.CultureInvariant); - } - - private static IEnumerable SourceFiles(string directory) - { - Assert.True(Directory.Exists(directory), $"Source directory must exist: {directory}"); - return Directory.EnumerateFiles(directory, "*.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 RepositoryRoot() - { - string source = ArchTestExtensions.FindSourceDirectory(); - Assert.True(Directory.Exists(source), "RimMind-Core/Source must be discoverable."); - DirectoryInfo? core = Directory.GetParent(source); - Assert.NotNull(core); - DirectoryInfo? root = core!.Parent; - Assert.NotNull(root); - return root!.FullName; - } } } diff --git a/ArchTests/Contracts/LayeringContracts.cs b/ArchTests/Contracts/LayeringContracts.cs index 629c6403..7efee19e 100644 --- a/ArchTests/Contracts/LayeringContracts.cs +++ b/ArchTests/Contracts/LayeringContracts.cs @@ -19,7 +19,8 @@ public void Domain_remains_independent_of_outer_layers_and_game_frameworks() ("domain does not depend on infrastructure", () => AssertNoUsing("Domain", "RimMind.Infrastructure")), ("domain does not depend on Verse", () => AssertNoUsing("Domain", "Verse")), ("domain does not depend on Harmony", () => AssertNoUsing("Domain", "HarmonyLib")), - ("domain does not depend on Unity", () => AssertNoUsing("Domain", "UnityEngine"))); + ("domain does not depend on Unity", () => AssertNoUsing("Domain", "UnityEngine")), + ("domain does not depend on RimWorld", () => AssertNoUsing("Domain", "RimWorld"))); } [Fact] @@ -62,19 +63,19 @@ public void Project_references_follow_the_clean_architecture_direction() private static CsprojAnalysis Project(string directory, string projectName) { - string source = RequireSourceDirectory(); + string source = ArchTestExtensions.RequireSourceDirectory(); return ArchTestExtensions.AnalyzeCsproj(Path.GetFullPath(Path.Combine(source, directory, projectName))); } private static void AssertNoUsing(string relativeLayer, string forbiddenNamespace) { - string source = RequireSourceDirectory(); + string source = ArchTestExtensions.RequireSourceDirectory(); string layer = Path.Combine(source, relativeLayer); var pattern = new Regex( $@"^\s*using\s+(?:global::)?{Regex.Escape(forbiddenNamespace)}(?:\.|;)", RegexOptions.Multiline | RegexOptions.CultureInvariant); - IReadOnlyList violations = SourceFiles(layer) - .Where(file => pattern.IsMatch(StripCommentsAndStrings(File.ReadAllText(file)))) + IReadOnlyList violations = ArchTestExtensions.SourceFiles(layer) + .Where(file => pattern.IsMatch(ArchTestExtensions.StripCommentsAndStrings(File.ReadAllText(file)))) .Select(file => Path.GetRelativePath(source, file)) .OrderBy(path => path, StringComparer.Ordinal) .ToArray(); @@ -83,30 +84,5 @@ private static void AssertNoUsing(string relativeLayer, string forbiddenNamespac violations.Count == 0, $"{relativeLayer} must not reference {forbiddenNamespace}:{Environment.NewLine}{string.Join(Environment.NewLine, violations)}"); } - - private static string StripCommentsAndStrings(string source) - { - return Regex.Replace( - source, - @"@""(?:""""|[^""])*""|""(?:\\.|[^""\\])*""|'(?:\\.|[^'\\])'|//[^\r\n]*|/\*.*?\*/", - " ", - RegexOptions.Singleline | RegexOptions.CultureInvariant); - } - - private static IEnumerable SourceFiles(string directory) - { - return Directory.EnumerateFiles(directory, "*.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 RequireSourceDirectory() - { - string source = ArchTestExtensions.FindSourceDirectory(); - Assert.True(Directory.Exists(source), "RimMind-Core/Source must be discoverable."); - return source; - } } } diff --git a/ArchTests/Contracts/PublicApiSurfaceContracts.cs b/ArchTests/Contracts/PublicApiSurfaceContracts.cs index da4acad5..d4dd24cb 100644 --- a/ArchTests/Contracts/PublicApiSurfaceContracts.cs +++ b/ArchTests/Contracts/PublicApiSurfaceContracts.cs @@ -12,7 +12,6 @@ namespace RimMind.Core.ArchTests.Contracts { - [Trait("Phase", "N")] public sealed class PublicApiSurfaceContracts { private static readonly string[] CanonicalNestedGroups = @@ -50,7 +49,7 @@ public sealed class PublicApiSurfaceContracts "RimMindAPI.Settings.get_Telemetry" }; - private static readonly string[] ExpectedObsoleteFlatAliases = + private static readonly string[] RetiredFlatAliases = { "PauseQueue", "ResumeQueue", @@ -117,31 +116,30 @@ public void RimMindAPI_exposes_ApiVersion_2_and_all_canonical_nested_groups() missing.Length == 0, $"Missing or non-static canonical RimMindAPI nested groups: {string.Join(", ", missing)}"); }), - ("deprecated flat aliases on RimMindAPI carry [Obsolete]", () => + ("retired flat aliases on RimMindAPI remain absent (hard-cut to nested groups)", () => { - var missingObsolete = new List(); - foreach (string memberName in ExpectedObsoleteFlatAliases) + var stillPresent = new List(); + foreach (string memberName in RetiredFlatAliases) { MemberInfo[] members = apiType.GetMember( memberName, BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly); - if (members.Length == 0 - || members.Any(m => m.GetCustomAttribute() == null)) + if (members.Length > 0) { - missingObsolete.Add(memberName); + stillPresent.Add(memberName); } } Assert.True( - missingObsolete.Count == 0, - $"Flat RimMindAPI aliases missing [Obsolete]: {string.Join(", ", missingObsolete)}"); + stillPresent.Count == 0, + $"Retired flat RimMindAPI aliases must remain absent: {string.Join(", ", stillPresent)}"); })); } [Fact] public void Nested_RimMindAPI_groups_do_not_expose_internal_interfaces_outside_allowlist() { - string sourceRoot = RequireSourceDirectory(); + string sourceRoot = ArchTestExtensions.RequireSourceDirectory(); string internalInterfacesDir = Path.Combine( sourceRoot, "Application", @@ -149,7 +147,7 @@ public void Nested_RimMindAPI_groups_do_not_expose_internal_interfaces_outside_a "Interfaces", "Internal"); - var internalTypeNames = SourceFiles(internalInterfacesDir) + var internalTypeNames = ArchTestExtensions.SourceFiles(internalInterfacesDir) .Select(Path.GetFileNameWithoutExtension) .Where(name => !string.IsNullOrWhiteSpace(name)) .Cast() @@ -250,19 +248,44 @@ public void Nested_RimMindAPI_groups_do_not_expose_internal_interfaces_outside_a continue; } - Match match = internalTypePattern.Match(trimmed); + int startLine = i + 1; + var signature = new System.Text.StringBuilder(trimmed); + while (!trimmed.Contains("=>", StringComparison.Ordinal) + && !trimmed.Contains("{", StringComparison.Ordinal) + && !trimmed.Contains(";", StringComparison.Ordinal) + && i + 1 < lines.Length) + { + i++; + trimmed = lines[i].Trim(); + signature.Append(' ').Append(trimmed); + } + + string fullSignature = signature.ToString(); + int bodyStart = fullSignature.IndexOf("=>", StringComparison.Ordinal); + int braceStart = fullSignature.IndexOf('{'); + int semiStart = fullSignature.IndexOf(';'); + int cut = fullSignature.Length; + if (bodyStart >= 0) cut = Math.Min(cut, bodyStart); + if (braceStart >= 0) cut = Math.Min(cut, braceStart); + if (semiStart >= 0) cut = Math.Min(cut, semiStart); + string headerOnly = fullSignature.Substring(0, cut); + + Match match = internalTypePattern.Match(headerOnly); if (!match.Success) continue; + string expectedPrefix = $"RimMindAPI.{groupName}."; bool isAllowlisted = AllowlistedInternalSurfaceMembers.Any(allowed => { - string shortMember = allowed.Split('.').Last(); - return trimmed.Contains($" {shortMember}", StringComparison.Ordinal); + if (!allowed.StartsWith(expectedPrefix, StringComparison.Ordinal)) + return false; + string shortMember = allowed.Substring(expectedPrefix.Length); + return Regex.IsMatch(headerOnly, $@"\b{Regex.Escape(shortMember)}\b", RegexOptions.CultureInvariant); }); if (!isAllowlisted) { - publicSignatureViolations.Add($"{Path.GetFileName(file)}:{i + 1} ({groupName}): {trimmed}"); + publicSignatureViolations.Add($"{Path.GetFileName(file)}:{startLine} ({groupName}): {headerOnly.Trim()}"); } } } @@ -276,7 +299,7 @@ public void Nested_RimMindAPI_groups_do_not_expose_internal_interfaces_outside_a [Fact] public void Domain_and_Application_do_not_contain_hardcoded_provider_literals() { - string sourceRoot = RequireSourceDirectory(); + string sourceRoot = ArchTestExtensions.RequireSourceDirectory(); string[] layers = { "Domain", "Application" }; string[] forbiddenLiterals = { "\"opencode\"", "\"oc_sk_\"", "\"deepseek.com\"" }; HashSet allowedFiles = new(StringComparer.OrdinalIgnoreCase) @@ -292,9 +315,9 @@ public void Domain_and_Application_do_not_contain_hardcoded_provider_literals() () => { var violations = layers - .SelectMany(layer => SourceFiles(Path.Combine(sourceRoot, layer))) + .SelectMany(layer => ArchTestExtensions.SourceFiles(Path.Combine(sourceRoot, layer))) .Where(file => !allowedFiles.Contains(Path.GetFileName(file))) - .Where(file => StripComments(File.ReadAllText(file)).Contains(literal, StringComparison.OrdinalIgnoreCase)) + .Where(file => ArchTestExtensions.StripComments(File.ReadAllText(file)).Contains(literal, StringComparison.OrdinalIgnoreCase)) .Select(file => Path.GetRelativePath(sourceRoot, file)) .OrderBy(path => path, StringComparer.Ordinal) .ToArray(); @@ -309,15 +332,16 @@ public void Domain_and_Application_do_not_contain_hardcoded_provider_literals() [Fact] public void Owner_ids_and_Harmony_patches_obey_building_block_architecture_rules() { - string repoRoot = RepositoryRoot(); - string sourceRoot = RequireSourceDirectory(); + string repoRoot = ArchTestExtensions.RepositoryRoot(); + string sourceRoot = ArchTestExtensions.RequireSourceDirectory(); ContractCaseRunner.Run( - ("RimMindOwnerConsts defines all 9 canonical module owner IDs as distinct non-empty constants", () => + ("RimMindOwnerConsts defines all 10 canonical module owner IDs and AgentModId as distinct non-empty constants", () => { string[] ids = { RimMindOwnerConsts.CoreModId, + RimMindOwnerConsts.AgentModId, RimMindOwnerConsts.ActionsModId, RimMindOwnerConsts.AdvisorModId, RimMindOwnerConsts.DialogueModId, @@ -325,7 +349,8 @@ public void Owner_ids_and_Harmony_patches_obey_building_block_architecture_rules RimMindOwnerConsts.PersonalityModId, RimMindOwnerConsts.StorytellerModId, RimMindOwnerConsts.BridgeRimTalkModId, - RimMindOwnerConsts.BridgeRimChatModId + RimMindOwnerConsts.BridgeRimChatModId, + RimMindOwnerConsts.ExtensionModelServiceModId }; Assert.All(ids, id => Assert.False(string.IsNullOrWhiteSpace(id))); @@ -345,8 +370,8 @@ public void Owner_ids_and_Harmony_patches_obey_building_block_architecture_rules .Distinct(StringComparer.OrdinalIgnoreCase); var violations = sourceDirs - .SelectMany(SourceFiles) - .Where(file => emptyOwnerPattern.IsMatch(StripComments(File.ReadAllText(file)))) + .SelectMany(ArchTestExtensions.SourceFiles) + .Where(file => emptyOwnerPattern.IsMatch(ArchTestExtensions.StripComments(File.ReadAllText(file)))) .Select(file => Path.GetRelativePath(repoRoot, file)) .OrderBy(path => path, StringComparer.Ordinal) .ToArray(); @@ -365,7 +390,7 @@ public void Owner_ids_and_Harmony_patches_obey_building_block_architecture_rules "Patch_PersonalityIncident.cs"); if (File.Exists(personalityPatchPath)) { - string personalityIncidentPatch = StripComments(File.ReadAllText(personalityPatchPath)); + string personalityIncidentPatch = ArchTestExtensions.StripComments(File.ReadAllText(personalityPatchPath)); Assert.Contains("IncidentWorker.TryExecute", personalityIncidentPatch, StringComparison.Ordinal); Assert.DoesNotContain("TryExecuteWorker", personalityIncidentPatch, StringComparison.Ordinal); } @@ -385,8 +410,8 @@ public void Owner_ids_and_Harmony_patches_obey_building_block_architecture_rules var patchViolations = nonPatchSubmods .Select(mod => Path.Combine(repoRoot, mod, "Source")) .Where(Directory.Exists) - .SelectMany(SourceFiles) - .Where(file => forbiddenGameEventPatchPattern.IsMatch(StripComments(File.ReadAllText(file)))) + .SelectMany(ArchTestExtensions.SourceFiles) + .Where(file => forbiddenGameEventPatchPattern.IsMatch(ArchTestExtensions.StripComments(File.ReadAllText(file)))) .Select(file => Path.GetRelativePath(repoRoot, file)) .OrderBy(path => path, StringComparer.Ordinal) .ToArray(); @@ -438,41 +463,5 @@ private static bool IsInternalInterfaceType(Type type, HashSet internalT return internalTypeNames.Contains(type.Name); } - - private static string StripComments(string source) - { - return Regex.Replace( - source, - @"//[^\r\n]*|/\*.*?\*/", - " ", - RegexOptions.Singleline | RegexOptions.CultureInvariant); - } - - private static IEnumerable SourceFiles(string directory) - { - Assert.True(Directory.Exists(directory), $"Source directory must exist: {directory}"); - return Directory.EnumerateFiles(directory, "*.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 RequireSourceDirectory() - { - string source = ArchTestExtensions.FindSourceDirectory(); - Assert.True(Directory.Exists(source), "RimMind-Core/Source must be discoverable."); - return source; - } - - private static string RepositoryRoot() - { - string source = RequireSourceDirectory(); - DirectoryInfo? core = Directory.GetParent(source); - Assert.NotNull(core); - DirectoryInfo? root = core!.Parent; - Assert.NotNull(root); - return root!.FullName; - } } } diff --git a/ArchTests/Contracts/RuntimeBoundaryContracts.cs b/ArchTests/Contracts/RuntimeBoundaryContracts.cs index 20333e43..781d9305 100644 --- a/ArchTests/Contracts/RuntimeBoundaryContracts.cs +++ b/ArchTests/Contracts/RuntimeBoundaryContracts.cs @@ -53,13 +53,14 @@ public void Runtime_container_types_remain_in_outer_adapters() private static void AssertSourceAbsent(string forbiddenPattern) { - AssertAbsent(SourceFiles(RequireSourceDirectory()), RequireSourceDirectory(), forbiddenPattern); + string source = ArchTestExtensions.RequireSourceDirectory(); + AssertAbsent(ArchTestExtensions.SourceFiles(source), source, forbiddenPattern); } private static void AssertLayerAbsent(string layer, string forbiddenPattern) { - string source = RequireSourceDirectory(); - AssertAbsent(SourceFiles(Path.Combine(source, layer)), source, forbiddenPattern); + string source = ArchTestExtensions.RequireSourceDirectory(); + AssertAbsent(ArchTestExtensions.SourceFiles(Path.Combine(source, layer)), source, forbiddenPattern); } private static void AssertAbsent( @@ -69,7 +70,7 @@ private static void AssertAbsent( { var pattern = new Regex(forbiddenPattern, RegexOptions.CultureInvariant); IReadOnlyList violations = files - .Where(file => pattern.IsMatch(StripCommentsAndStrings(File.ReadAllText(file)))) + .Where(file => pattern.IsMatch(ArchTestExtensions.StripCommentsAndStrings(File.ReadAllText(file)))) .Select(file => Path.GetRelativePath(source, file)) .OrderBy(path => path, StringComparer.Ordinal) .ToArray(); @@ -80,12 +81,12 @@ private static void AssertAbsent( private static void AssertDeclarationUnder(string typeName, string expectedRelativeDirectory) { - string source = RequireSourceDirectory(); + string source = ArchTestExtensions.RequireSourceDirectory(); var declaration = new Regex( $@"\b(?:class|interface|struct|record)\s+{Regex.Escape(typeName)}\b", RegexOptions.CultureInvariant); - string[] matches = SourceFiles(source) - .Where(file => declaration.IsMatch(StripCommentsAndStrings(File.ReadAllText(file)))) + string[] matches = ArchTestExtensions.SourceFiles(source) + .Where(file => declaration.IsMatch(ArchTestExtensions.StripCommentsAndStrings(File.ReadAllText(file)))) .ToArray(); string expected = Path.GetFullPath(Path.Combine(source, expectedRelativeDirectory)) .TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; @@ -93,30 +94,5 @@ private static void AssertDeclarationUnder(string typeName, string expectedRelat Assert.NotEmpty(matches); Assert.All(matches, file => Assert.StartsWith(expected, Path.GetFullPath(file), StringComparison.OrdinalIgnoreCase)); } - - private static string StripCommentsAndStrings(string source) - { - return Regex.Replace( - source, - @"@""(?:""""|[^""])*""|""(?:\\.|[^""\\])*""|'(?:\\.|[^'\\])'|//[^\r\n]*|/\*.*?\*/", - " ", - RegexOptions.Singleline | RegexOptions.CultureInvariant); - } - - private static IEnumerable SourceFiles(string directory) - { - return Directory.EnumerateFiles(directory, "*.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 RequireSourceDirectory() - { - string source = ArchTestExtensions.FindSourceDirectory(); - Assert.True(Directory.Exists(source), "RimMind-Core/Source must be discoverable."); - return source; - } } } diff --git a/ArchTests/RimMindCore.ArchTests.csproj b/ArchTests/RimMindCore.ArchTests.csproj index 88ef41b2..546a1e25 100644 --- a/ArchTests/RimMindCore.ArchTests.csproj +++ b/ArchTests/RimMindCore.ArchTests.csproj @@ -15,12 +15,9 @@ - - - diff --git a/INTRODUCTION.txt b/INTRODUCTION.txt deleted file mode 100644 index de3b3bc5..00000000 --- a/INTRODUCTION.txt +++ /dev/null @@ -1,134 +0,0 @@ -═══════════════════════════════════════════════ - RimMind — 你的小人有了真正的灵魂 -═══════════════════════════════════════════════ -[h1]RimMind - Core (核心引擎)[/h1] - -想象这个场景: -[i]赋予殖民者真正的认知与灵魂——RimMind 系列模组的基础运行时与核心引擎。[/i] -[i]Bring true cognition and souls to your colonists — The foundation runtime and core AI engine for the RimMind suite.[/i] - - 袭击刚结束。Alice 蹲在废墟旁,她的爱人倒在血泊中。 - 你点开她的思维面板——她在想: - "我受够了。我要离开这个鬼地方。" -[hr] -[h2]📖 中文介绍 / Chinese Overview[/h2] - - 另一边,Bob 刚被救回来。他看到 Alice 独自发抖, - 决定走过去安慰她。不是你下的命令——是他自己想的。 -[b]RimMind-Core[/b] 是整个 RimMind 智能体套件的心脏与基础设施。它将大型语言模型(LLM)无缝嵌入 RimWorld 1.6 的游戏循环中,通过高效的上下文编排、异步队列与原生 ToolCall 机制,让殖民地的小人获得真正的思考、记忆与行动能力。 - - 这不是脚本。不是随机事件表。这是 AI 在那一刻, - 为这两个有性格、有记忆、有情感的小人做出的真实决定。 -[h3]🌟 核心特性[/h3] -[list] -[*] [b]4-Zone KV-Cache 深度缓存架构[/b]:创新将系统提示词、角色背景、长期记忆与易变环境(天气/心情/时间)分层解耦,实现高达 [b]80%~90% 的缓存命中率[/b],大幅降低 API Token 消耗并提升响应速度! -[*] [b]全能模型服务适配[/b]:开箱即用支持 [b]OpenAI (GPT-4o/mini)[/b]、[b]DeepSeek (Chat/Reasoner)[/b]、[b]本地 Ollama / LM Studio / vLLM[/b] 以及 [b]OpenCode Go[/b] 订阅直连。 -[*] [b]原生 ToolCall 工具调用体系[/b]:支持复杂嵌套函数调用(Function Calling),AI 不仅能输出台词,更能精准执行游戏内动作。 -[*] [b]直观的 F8 智能体调试与控制中心[/b]:按 [b]F8[/b] 随时唤出总控中心,提供实时连通性测试、队列状态、Token 消耗统计、报文检查器与殖民者智能体监控。 -[*] [b]统一频率调节滑块[/b]:在设置中提供动态活动频率滑块(0.33x ~ 3.33x),支持从“每3天1次”到“每天10次”的平滑调谐,彻底告别死板定时打卡。 -[*] [b]极致性能保护[/b]:网络请求与高开销纯计算全部运行在后台线程,游戏主线程 0 掉帧、0 阻断。 -[/list] - -━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ -[hr] -[h2]🌐 English Overview[/h2] - - 这 Mod 到底好玩在哪? - ──────────────────── -[b]RimMind-Core[/b] is the foundational AI runtime engine for the entire RimMind mod suite in RimWorld 1.6. It bridges large language models (LLMs) with RimWorld's simulation loop, providing intelligent context management, async queue scheduling, and structured tool execution. - - ▸ 小人真的会"想" - 每个 Pawn 都有独立的认知循环:感知→思考→行动→记忆。 - 它们会注意到同伴的心情、殖民地的食物短缺、窗外的威胁。 - 然后做出自己的判断,甚至形成长期目标。 -[h3]🌟 Key Highlights[/h3] -[list] -[*] [b]4-Zone Prompt Caching (KV-Cache)[/b]: Isolates static definitions and pawn profiles from volatile environmental states (time/weather/mood), achieving [b]80%~90% prefix cache hit rate[/b] for massive token cost reduction and lightning-fast responses! -[*] [b]Universal Model Compatibility[/b]: Out-of-the-box support for [b]OpenAI[/b], [b]DeepSeek[/b], local [b]Ollama / LM Studio[/b], and high-speed [b]OpenCode Go[/b]. -[*] [b]Unified Native ToolCall Architecture[/b]: Enables structured function calling, allowing LLMs to directly read game states and invoke game mechanics without brittle text parsing. -[*] [b]F8 RimMind Debug Hub & Inspector[/b]: Press [b]F8[/b] in-game to view live AI connectivity, test API ping, inspect token payloads, and monitor colonist agents. -[*] [b]Dynamic Frequency Slider[/b]: Seamlessly scale AI interaction frequency from eco-mode (1 event per 3 days) to active-mode (10+ events per day). -[*] [b]Lag-Free Threading[/b]: All network and compute workloads run on background threads; your RimWorld main thread stays completely butter-smooth. -[/list] - - ▸ 上下文引擎——AI 真正"懂"你的殖民地 - 不是把一堆数据丢给 LLM,而是用五层架构精准筛选: - 只给 AI 此刻最相关的信息。BudgetScheduler 控制每次请求 - 都在 token 预算内。所以小人不会"失忆"或"胡说八道"。 - - ▸ 飞轮自动调优——越用越聪明 - 不需要手动调参数。Flywheel 持续监控 AI 响应质量, - 自动调整温度、预算、权重。用得越久,小人越"对味"。 - - ▸ 感知桥接——小人不是木头人 - 5 个 Patch 把 RimWorld 的原生事件翻译成 AI 能理解的信号。 - 受伤、心情崩溃、社交冲突、袭击警报——小人会主动感知, - 不是等你点按钮才反应。 - -━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ - - 推荐怎么玩? - ──────────── - - 第一步:装 RimMind-Core - 这是引擎。装好,填入你的 API Key,就能跑了。 - 支持任何 OpenAI 兼容的 API(OpenAI / 本地 Ollama / 其他)。 - - 第二步:加 RimMind-Dialogue - 和小人自由对话。这是最直观的体验——直接跟你的殖民者聊天, - 问它们在想什么,听它们抱怨食物难吃。 - - 第三步:加 RimMind-Personality - 给每个小人分配大五人格特质。内向的科学家、外向的社交达人、 - 神经质的艺术家——性格不同,反应完全不同。 - - 第四步:加 RimMind-Memory - 小人开始记住事情了。三个月前那次袭击,它还记得谁救了它。 - 暗记忆系统让 AI 在不知不觉中被过去的经历影响。 - - 进阶:RimMind-Actions + RimMind-Storyteller - Actions 让小人自主行动——工作、社交、逃跑,全凭自己判断。 - Storyteller 让 AI 当叙事者,动态生成故事线和事件。 - 这两个会让游戏难度和不可预测性大幅上升,建议熟悉基础后再加。 - - 还有:RimMind-Advisor - AI 顾问模式。不改变小人行为,而是帮你分析殖民地状况、 - 给出建议。适合想用 AI 辅助决策但不想让小人"失控"的玩家。 - -━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ - - 常见问题 - ──────── - - Q: 贵不贵? - A: 默认每 500 秒思考一次,token 用量可控。 - 用本地 Ollama 的话完全免费。Flywheel 会自动优化避免浪费。 - - Q: 和其他 Mod 冲突吗? - A: 不冲突。RimMind 通过 Harmony Patch 桥接,不修改游戏原生逻辑。 - - Q: 可以只装 Core 吗? - A: 可以跑,但小人只会"想"不会"做"。 - 建议至少搭配 Dialogue,体验最完整。 - - Q: Player2 模式是什么? - A: 你自己扮演 NPC 的 AI。适合想亲自"演"角色的玩家。 - -━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ - - 给 Mod 开发者 - - - 公共 API: RimMindAPI 静态类 - - 注册上下文: ContextKeyRegistry.Register(key, layer, priority, provider, modId) - - 上下文架构: L0(静态)→L1(基线+Diff)→L2(环境)→L3(状态)→L4(历史)→L5(感知) - - 请求队列: AIRequestQueue,支持优先级、冷却、取消 - - 详细规范: 见 AGENTS.md - -═══════════════════════════════════════════════ -[hr] -[h2]⚙️ 安装与依赖 / Requirements & Setup[/h2] -[list] -[*] [b]必需前置 (Required)[/b]: [url=https://steamcommunity.com/sharedfiles/filedetails/?id=2009463077]Harmony[/url] -[*] [b]加载顺序 (Load Order)[/b]: Harmony -> RimWorld Core -> [b]RimMind-Core[/b] -> (其他 RimMind 子模组) -[*] [b]配置指南[/b]: 进入游戏主菜单或选项 -> Mod 设置 -> [b]RimMind-Core[/b],选择你的 AI 服务商并填入 API Key 与端点即可! -[/list] diff --git a/IntegrationTests/Contracts/MechanismContracts.cs b/IntegrationTests/Contracts/MechanismContracts.cs index 5e6ba706..358e0dd0 100644 --- a/IntegrationTests/Contracts/MechanismContracts.cs +++ b/IntegrationTests/Contracts/MechanismContracts.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.Application.Common.Models.Tools; using RimMind.Domain.Common; using RimMind.Domain.Enums; using RimMind.Domain.ValueObjects; @@ -94,49 +95,68 @@ public void Mechanism_registry_retires_only_the_selected_owner() } [Fact] - public async Task Mechanism_operation_boundary_preserves_results_and_risk() + public async Task Mechanism_tool_handlers_dispatch_operations_risk_and_declared_scopes() { await ContractCaseRunner.RunAsync( - ("query returns the mechanism value", async () => + ("query handler dispatches through MechanismToolHandler and returns mechanism payload", async () => { var mechanism = new StubMechanism("pawn.work", "Core", "priorities"); - Result result = await mechanism.ExecuteQueryAsync( - new MechanismReadArgs { MechanismId = "pawn.work" }, + var handler = new MechanismToolHandler(mechanism, mechanism, mechanism, mechanism, MechanismOperationType.Query); + var result = await handler.ExecuteAsync( + new ToolCallArgs { ToolCallId = "q-1", ToolName = handler.Id, ArgumentsJson = "{\"pawn_id\":7}" }, CancellationToken.None); Assert.True(result.IsOk); - Assert.Equal("priorities", result.Value); + Assert.False(result.Value.IsError); + Assert.Equal("priorities", result.Value.Content); + Assert.Equal(ToolScope.MetaQuery, handler.Definition.Manifest!.Scopes); }), - ("supported write returns success", async () => + ("write handler forwards parsed arguments and exposes manifest risk and approval", async () => { - var mechanism = new StubMechanism("pawn.work", "Core", "priorities"); - Result result = await mechanism.ExecuteSetAsync( - new MechanismWriteArgs { MechanismId = "pawn.work", Action = "set_priority" }, + var mechanism = new StubMechanism("pawn.social", "Core", "priorities", MechanismRisk.Dangerous, ToolScope.Social | ToolScope.ColonistSelf); + var handler = new MechanismToolHandler(mechanism, mechanism, mechanism, mechanism, MechanismOperationType.Set); + Assert.Equal(RiskLevel.High, handler.Definition.Manifest!.RiskLevel); + Assert.True(handler.Definition.Manifest.RequiresApproval); + Assert.Equal(ToolScope.Social | ToolScope.ColonistSelf, handler.Definition.Manifest.Scopes); + + var result = await handler.ExecuteAsync( + new ToolCallArgs { ToolCallId = "s-1", ToolName = handler.Id, ArgumentsJson = "{\"pawn_id\":7,\"action\":\"set_priority\"}" }, CancellationToken.None); Assert.True(result.IsOk); - Assert.True(result.Value); + Assert.False(result.Value.IsError); + Assert.Equal(7, mechanism.LastWriteArgs?.PawnId); + Assert.Equal("set_priority", mechanism.LastWriteArgs?.Action); }), - ("unsupported operation returns a typed error", async () => + ("unsupported operation wraps typed error as tool error result", async () => { var mechanism = new StubMechanism("pawn.work", "Core", "priorities"); - Result result = await mechanism.ExecuteAddAsync( - new MechanismWriteArgs { MechanismId = "pawn.work", Action = "add" }, + var handler = new MechanismToolHandler(mechanism, mechanism, mechanism, mechanism, MechanismOperationType.Add); + var result = await handler.ExecuteAsync( + new ToolCallArgs { ToolCallId = "a-1", ToolName = handler.Id, ArgumentsJson = "{\"pawn_id\":7}" }, CancellationToken.None); - Assert.True(result.IsErr); - Assert.Equal(RimMindErrorCode.MechanismOperationNotSupported, result.Error.Code); - }), - ("list returns a stable read-only option set", async () => - { - var mechanism = new StubMechanism("pawn.work", "Core", "priorities"); - Result, RimMindError> result = - await mechanism.ExecuteListAsync(7, CancellationToken.None); Assert.True(result.IsOk); - Assert.Collection(result.Value, item => Assert.Equal("option", item.DefName)); + Assert.True(result.Value.IsError); }), - ("operation risk is exposed through the public boundary", () => + ("list handler serializes mechanism options and MechanismListToolHandler filters by category", async () => { - var mechanism = new StubMechanism("pawn.work", "Core", "priorities", MechanismRisk.Dangerous); - Assert.Equal(MechanismRisk.Dangerous, mechanism.GetRiskForOperation(MechanismOperationType.Set)); - return Task.CompletedTask; + var mechanism = new StubMechanism("pawn.work", "Core", "priorities"); + var listHandler = new MechanismToolHandler(mechanism, mechanism, mechanism, mechanism, MechanismOperationType.List); + var listResult = await listHandler.ExecuteAsync( + new ToolCallArgs { ToolCallId = "l-1", ToolName = listHandler.Id, ArgumentsJson = "{\"pawn_id\":7}" }, + CancellationToken.None); + Assert.True(listResult.IsOk); + Assert.False(listResult.Value.IsError); + Assert.Contains("option", listResult.Value.Content, StringComparison.Ordinal); + + var listToolHandler = new MechanismListToolHandler( + mechanism, + mechanism, + new MechanismToolHelper.FallbackJsonExtractor()); + var catalogResult = await listToolHandler.ExecuteAsync( + new ToolCallArgs { ToolCallId = "cat-1", ToolName = listToolHandler.Id, ArgumentsJson = "{\"category\":\"opt\"}" }, + CancellationToken.None); + Assert.True(catalogResult.IsOk); + Assert.False(catalogResult.Value.IsError); + Assert.Contains("option", catalogResult.Value.Content, StringComparison.Ordinal); })); } @@ -149,21 +169,24 @@ private static GameMechanismRegistry RegistryWithOwners() return registry; } - private sealed class StubMechanism : IGameMechanism + private sealed class StubMechanism : IGameMechanism, IMechanismScopeMetadata { private readonly string _ownerModId; private readonly string _queryValue; + private readonly ToolScope? _declaredWriteScope; public StubMechanism( string mechanismId, string ownerModId, string queryValue, - MechanismRisk risk = MechanismRisk.Safe) + MechanismRisk risk = MechanismRisk.Safe, + ToolScope? declaredWriteScope = null) { MechanismId = mechanismId; _ownerModId = ownerModId; _queryValue = queryValue; Risk = risk; + _declaredWriteScope = declaredWriteScope; SupportedOperations = new[] { MechanismOperationType.Query, @@ -172,6 +195,7 @@ public StubMechanism( }; } + public MechanismWriteArgs? LastWriteArgs { get; private set; } string IExtension.Id => MechanismId; string IExtension.OwnerModId => _ownerModId; public string MechanismId { get; } @@ -180,6 +204,11 @@ public StubMechanism( public IReadOnlyList SupportedOperations { get; } public MechanismDocs Docs { get; } = new() { Summary = "contract mechanism" }; + public ToolScope? GetToolScopeForOperation(MechanismOperationType operation) + => operation is MechanismOperationType.Query or MechanismOperationType.List + ? ToolScope.MetaQuery + : _declaredWriteScope; + public Task> ExecuteQueryAsync( MechanismReadArgs args, CancellationToken ct) => @@ -187,8 +216,11 @@ public Task> ExecuteQueryAsync( public Task> ExecuteSetAsync( MechanismWriteArgs args, - CancellationToken ct) => - Task.FromResult(Result.Ok(true)); + CancellationToken ct) + { + LastWriteArgs = args; + return Task.FromResult(Result.Ok(true)); + } public Task> ExecuteAddAsync( MechanismWriteArgs args, diff --git a/IntegrationTests/RimMindCore.Integration.Tests.csproj b/IntegrationTests/RimMindCore.Integration.Tests.csproj index fbf37d40..63c6cba2 100644 --- a/IntegrationTests/RimMindCore.Integration.Tests.csproj +++ b/IntegrationTests/RimMindCore.Integration.Tests.csproj @@ -17,7 +17,7 @@ - + @@ -28,8 +28,6 @@ - - diff --git a/Languages/ChineseSimplified/Keyed/RimMind_Core.xml b/Languages/ChineseSimplified/Keyed/RimMind_Core.xml index b5894424..ab3e7bd6 100644 --- a/Languages/ChineseSimplified/Keyed/RimMind_Core.xml +++ b/Languages/ChineseSimplified/Keyed/RimMind_Core.xml @@ -37,7 +37,6 @@ 要使用的模型 ID,如 deepseek-flash、deepseek-v4-pro、gpt-4o-mini 等。 备用 API 容灾节点列表 (Failover List) 按顺序排列的备用 API 节点列表。当主 API 节点请求失败(如 HTTP 503/502/429、超时或空响应)时,RimMind 会在单次请求内自动平滑切换至列表中的下一个可用备用节点,并对故障节点执行 60 秒临时隔离。 - + OpenCode Go 备用 + 自定义备用 暂未配置备用节点。点击「+ 自定义备用」添加自动容灾保护。 强制 JSON 模式(response_format) @@ -434,9 +433,14 @@ 无法创建 Agent:工厂不可用 状态 模式 + 工作流阶段 + 自主权 目标 + (无) 策略权重 + (暂无数据) 行为历史 + (暂无记录) RimMind 调试中心 概览 @@ -448,16 +452,10 @@ 设置 已选择小人 未选择小人 - 运行时 Agent 状态 待处理 AI 请求 Agent 运行循环 最近循环 Tick - 循环故障数 - 小人 - 作用域 - 尚未运行 队列:尚未初始化 - 队列状态 快捷操作 设置 设置 @@ -787,7 +785,6 @@ 恢复默认 ⚙️ 快捷配置预设 - 已应用预设:{0} ⚡ 响应优先 快速交互:MaxTokens=600,并发=3,超时=25秒,冷却=15秒。适合即时对话与快节奏智能体。 ⚖️ 均衡标准 @@ -806,7 +803,6 @@ 打开实时报文检查器,可查看组装后的上下文、测试发送或复制完整 JSON 报文。 待审批: {0} RimMind 待审批悬浮窗(已收起)。悬停展开完整视图。 - 系统概况与运行状态 快速操作 请求队列 进行中 @@ -905,4 +901,22 @@ 工作优先级表 修改殖民者工作面板的数字优先级(1-4)。默认禁止,防止 AI 覆盖玩家手动配置的工作表。 殖民地房间拓扑: [{0}] + + “再吃靴子味的营养膏,本小姐就要去弹药库打保龄球了!” + 傲娇女仆贝拉的绝食抗议 + “本小姐已经连续吃了3天靴子味的营养膏了!如果晚餐再没有炙烤牛排,我就去弹药库把迫击炮弹当保龄球打!” + 批准:烹饪精致牛排 + 驳回:老实吃营养膏 + “终于端上热气腾腾的烤肉排了,今晚总算不用啃皮靴营养膏啦!” + “敬大厨一杯!+6 社交好感度 ❤️ [THOUGHT: GRATEFUL]” + 终于端上热气腾腾的烤肉排了,今晚总算不用啃皮靴营养膏啦! + 敬大厨一杯!木屋里点上火把暖和多了,明天我们把北边的稻田也收割入库吧。 + 因果律的制裁:狂怒鼠群的复仇 + AI 叙事者已编排戏剧性事件:\n昨天贝拉击退松鼠并在屁股上留下牙印的事件引发了连锁因果反扑!\n\n根据地底啮齿类动物情报网的报告,附近的松鼠家族认为此举严重侵犯了森林主权。一支由 18 只狂暴嗜血松鼠组成的远征军正向殖民地奔袭而来……\n\n“它们目光如炬,誓要为昨天的屁股咬痕讨回公道!” + 破晓心境自白 + 观察日出麦浪 + “初升的朝阳照在木屋与麦浪上,虽然昨天屁股被松鼠咬得很痛,但有热饭和伙伴在身边,生活依旧充满希望。” + 自主建造决策 + {"tool":"place_blueprint","building_def":"Bed","stuff_def":"WoodLog","reason":"为同伴补充温暖的木床"} + 食堂晚宴交谈 diff --git a/Languages/English/Keyed/RimMind_Core.xml b/Languages/English/Keyed/RimMind_Core.xml index 93c8e859..c6210db4 100644 --- a/Languages/English/Keyed/RimMind_Core.xml +++ b/Languages/English/Keyed/RimMind_Core.xml @@ -37,7 +37,6 @@ The model ID to use, e.g. deepseek-flash, deepseek-v4-pro, or gpt-4o-mini. Backup API Failover Nodes 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 "+ Custom Backup" to add automatic failover protection. Force JSON Mode (response_format) @@ -434,9 +433,14 @@ Cannot create agent: factory not available Status Mode + Workflow Phase + Autonomy Goals + (none) Strategy Weights + (no data) Behavior History + (no history) RimMind Debug Center Overview @@ -448,16 +452,10 @@ Settings Selected pawn No pawn selected - Runtime agent states Pending AI requests Agent runtime loop Last loop tick - Loop faults - pawn - scoped - Not run Queue: not initialized - Queue State Quick Actions Settings Settings @@ -787,7 +785,6 @@ Reset to Defaults ⚙️ Quick Configuration Presets - Preset applied: {0} ⚡ Responsive Fast interaction: MaxTokens=600, Concurrency=3, Timeout=25s, Cooldown=15s. Ideal for real-time dialogue and responsive agents. ⚖️ Balanced @@ -806,7 +803,6 @@ Open the real-time Payload Inspector to view assembled context, test AI connectivity, or copy full request JSON. Pending: {0} RimMind Approval HUD (Collapsed). Hover to expand full view. - System Status Summary Quick Actions Request Queue active @@ -905,4 +901,22 @@ Work Priorities Modifying colonist Work Tab numeric priorities (1-4). Off by default so AI does not overwrite player Work Tab settings. ColonyRooms: [{0}] + + "One more boot-flavored nutrient paste meal and I'm bowling in the mortar shell depot!" + Bella's Hunger Strike Protest + "I have eaten boot-flavored nutrient paste for 3 days straight! If dinner isn't seared steak, I'm taking the mortar shells bowling!" + Approve: Cook Fine Steak + Reject: Stick to Paste + "Finally, sizzling grilled steak! No more chewing boot-flavored paste tonight!" + "Cheers to the chef! +6 Social Opinion [THOUGHT: GRATEFUL]" + Finally, sizzling grilled steak! No more chewing boot-flavored paste tonight! + Cheers to the chef! The torches keep the lodge cozy — tomorrow let's harvest the northern rice fields. + Causal Retribution: Revenge of the Mad Squirrel Swarm + AI Storyteller orchestrated a dramatic event:\nYesterday's squirrel skirmish triggered a causal retaliation!\n\nAccording to underground rodent intelligence, the local squirrel clans consider the act a grave violation of forest sovereignty. An expedition of 18 maddened squirrels is charging toward the colony...\n\n"Eyes blazing, they have come to settle yesterday's score!" + Dawn Reflection + Watching sunrise over the wheat field + "Morning sunlight warms the wooden lodge and wheat fields. Yesterday's squirrel bite still stings, yet with hot meals and friends nearby, life remains full of hope." + Autonomous Build Decision + {"tool":"place_blueprint","building_def":"Bed","stuff_def":"WoodLog","reason":"Build a warm wooden bed for companions"} + Dining Hall Banter diff --git a/README.md b/README.md index b215a606..30d86ca0 100644 --- a/README.md +++ b/README.md @@ -104,11 +104,11 @@ Configurable via **Options -> Mod Settings -> RimMind-Core**: | Setting | Default | Description | |---|---|---| | **AI Provider** | `openai` | Supports OpenAI-compatible endpoints, DeepSeek, Player2, and extended gateways | -| **API Endpoint & Backup Nodes** | `https://api.deepseek.com/v1` | Primary OpenAI Chat Completions URL plus optional `BackupEndpointNode` failover list | -| **Model Name** | `deepseek-flash` | Target LLM model identifier (`deepseek-flash`, `deepseek-v4-pro`, `gpt-4o-mini`, etc.) | +| **API Endpoint & Backup Nodes** | `https://api.openai.com/v1` | Primary OpenAI Chat Completions URL plus optional `BackupEndpointNode` failover list | +| **Model Name** | `gpt-4o-mini` | Target LLM model identifier (`gpt-4o-mini`, `deepseek-chat`, local Ollama models, etc.) | | **Agent Autonomy Policies** | Domain-specific | Per-domain (`Survival`, `Work`, `Social`, `Colony`, `Governance`) level (`Auto`, `AutoWithNotify`, `RecommendOnly`) | | **Max Concurrent Requests** | `3` | Maximum simultaneous requests sent to the LLM (1~10) | -| **Request Timeout** | `60s` | Maximum wait time for LLM response before timeout (10s~180s) | +| **Request Timeout** | `120s` | Maximum wait time for LLM response before timeout (10s~300s) | | **Request Overlay** | `Enabled` | Floating status widget in the lower right showing active requests | | **Verbose Logging** | `Disabled` | Outputs detailed payload traces to `Player.log` | diff --git a/README_zh.md b/README_zh.md index 9140e691..bb4e6c07 100644 --- a/README_zh.md +++ b/README_zh.md @@ -104,11 +104,11 @@ flowchart TD | 设置项 | 默认值 | 说明 | |---|---|---| | **AI Provider** | `openai` | 支持 OpenAI 兼容端点、DeepSeek、Player2 与扩展网关 | -| **API 端点与备用节点** | `https://api.deepseek.com/v1` | 主 OpenAI Chat Completions URL 及 `BackupEndpointNode` 自动故障转移列表 | -| **模型名称** | `deepseek-flash` | 目标大语言模型标识符(如 `deepseek-flash`、`deepseek-v4-pro`、`gpt-4o-mini`) | +| **API 端点与备用节点** | `https://api.openai.com/v1` | 主 OpenAI Chat Completions URL 及 `BackupEndpointNode` 自动故障转移列表 | +| **模型名称** | `gpt-4o-mini` | 目标大语言模型标识符(如 `gpt-4o-mini`、`deepseek-chat`、本地 Ollama 模型等) | | **智能体自治策略** | 按领域分级 | 独立配置五大领域(`Survival`/`Work`/`Social`/`Colony`/`Governance`)的自治级别(`Auto`/`AutoWithNotify`/`RecommendOnly`) | | **最大并发请求数** | `3` | 同时发送给大模型的请求上限(1~10) | -| **请求超时** | `60秒` | 等待 AI 响应的最大超时时限(10~180秒) | +| **请求超时** | `120秒` | 等待 AI 响应的最大超时时限(10~300秒) | | **请求悬浮窗** | `开启` | 屏幕右下角实时显示请求处理状态与迷你胶囊 | | **详细调试日志** | `关闭` | 输出完整报文跟踪日志至 `Player.log` | diff --git a/Source/Application/Common/Behaviours/ConcurrentRegistryBase.cs b/Source/Application/Common/Behaviours/ConcurrentRegistryBase.cs deleted file mode 100644 index b108dc2c..00000000 --- a/Source/Application/Common/Behaviours/ConcurrentRegistryBase.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using RimMind.Application.Common.Interfaces.Registry; - -namespace RimMind.Application.Common.Behaviours -{ - /// - /// Base class for concurrent registries. Provides Register/Unregister/FindById/All/UnregisterByOwner. - /// Subclasses provide key extractor and owner extractor via constructor. - /// - public abstract class ConcurrentRegistryBase : IOwnedRegistry - where TKey : notnull - where TValue : class - { - protected readonly ConcurrentDictionary _items = new ConcurrentDictionary(); - private readonly Func _keyExtractor; - private readonly Func? _ownerExtractor; - - protected ConcurrentRegistryBase(Func keyExtractor, Func? ownerExtractor = null) - { - _keyExtractor = keyExtractor ?? throw new ArgumentNullException(nameof(keyExtractor)); - _ownerExtractor = ownerExtractor; - } - - public void Register(TValue item) - { - if (item == null) return; - var key = _keyExtractor(item); - _items.AddOrUpdate(key, item, (_, __) => item); - } - - public bool Unregister(TKey key) => _items.TryRemove(key, out _); - - public TValue? FindById(TKey key) => _items.TryGetValue(key, out var v) ? v : null; - - public IReadOnlyList All => new List(_items.Values); - - /// - public int UnregisterByOwner(string ownerModId) - { - if (ownerModId == null) throw new ArgumentNullException(nameof(ownerModId)); - if (_ownerExtractor == null) return 0; - var toRemove = new List(); - foreach (var kvp in _items) - { - if (_ownerExtractor(kvp.Value) == ownerModId) - toRemove.Add(kvp.Key); - } - foreach (var k in toRemove) _items.TryRemove(k, out _); - return toRemove.Count; - } - } -} diff --git a/Source/Application/Common/Behaviours/MiddlewareBase.cs b/Source/Application/Common/Behaviours/MiddlewareBase.cs deleted file mode 100644 index 02f2a539..00000000 --- a/Source/Application/Common/Behaviours/MiddlewareBase.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.Threading.Tasks; -using RimMind.Application.Common.Constants; -using RimMind.Application.Common.Interfaces.Abstractions; -using RimMind.Application.Common.Interfaces.Pipeline; -using RimMind.Application.Common.Models.Pipeline; - -namespace RimMind.Application.Common.Behaviours -{ - /// - /// Base class for IMiddleware implementations. Provides default Id, OwnerModId, and Log property. - /// Subclasses only need to override Name, Order, and InvokeAsync. - /// - public abstract class MiddlewareBase : IMiddleware where TContext : IPipelineContext - { - public abstract string Name { get; } - public abstract int Order { get; } - public virtual string Id => Name; - public virtual string OwnerModId => RimMindOwnerConsts.CoreModId; - - protected readonly ILogSink? Log; - - protected MiddlewareBase(ILogSink? log = null) - { - Log = log; - } - - public abstract Task InvokeAsync(TContext context, MiddlewareDelegate next); - } -} diff --git a/Source/Application/Common/Constants/RimMindOwnerConsts.cs b/Source/Application/Common/Constants/RimMindOwnerConsts.cs index e629c9df..7fbfe1f4 100644 --- a/Source/Application/Common/Constants/RimMindOwnerConsts.cs +++ b/Source/Application/Common/Constants/RimMindOwnerConsts.cs @@ -4,18 +4,14 @@ namespace RimMind.Application.Common.Constants /// OwnerModId 统一常量。所有 Core 内置 IExtension 实现应引用此类, /// 避免散落的字符串字面量导致 UnregisterByOwner 查询不一致。 /// - /// - /// 已知不一致(待后续统一): - /// - "RimMind.Core":用于 ScopedAgent.cs、ToolManifest.cs(2 处) - /// - "Core":用于 OutputGuardrailMiddleware.cs、CoreContextProviders.cs 的 ownerMod 参数(~21 处) - /// 这两种写法暂不修改,避免破坏存档序列化或潜在的 UnregisterByOwner 查询。 - /// 后续应统一为 。 - /// public static class RimMindOwnerConsts { /// Core 模组的 OwnerModId 标识。 public const string CoreModId = "RimMindCore"; + /// Core Agent 请求来源 ModId 标识。 + public const string AgentModId = "RimMind.Agent"; + /// Actions 模组的 OwnerModId 标识。 public const string ActionsModId = "RimMindActions"; @@ -39,5 +35,8 @@ public static class RimMindOwnerConsts /// Bridge-RimChat 模组的 OwnerModId 标识。 public const string BridgeRimChatModId = "RimMindBridgeRimChat"; + + /// Extension-ModelService 模组的 OwnerModId 标识。 + public const string ExtensionModelServiceModId = "RimMindExtensionModelService"; } } diff --git a/Source/Application/Common/Defaults/AgentBusCoreSubscriber.cs b/Source/Application/Common/Defaults/AgentBusCoreSubscriber.cs index 8bcc7929..b86ac804 100644 --- a/Source/Application/Common/Defaults/AgentBusCoreSubscriber.cs +++ b/Source/Application/Common/Defaults/AgentBusCoreSubscriber.cs @@ -9,7 +9,8 @@ namespace RimMind.Application.Common.Defaults; public sealed class AgentBusCoreSubscriber : IDisposable { private readonly IAgentBus _eventBus; - private readonly ILogSink _logSink; + private readonly ILogSink? _logSink; + private readonly bool _logPerceptions; private readonly string _perceptionKey; private readonly string _actionKey; private readonly string _modeChangedKey; @@ -18,10 +19,11 @@ public sealed class AgentBusCoreSubscriber : IDisposable private readonly string _goalKey; private int _disposed; - public AgentBusCoreSubscriber(IAgentBus eventBus, ILogSink logSink) + public AgentBusCoreSubscriber(IAgentBus eventBus, ILogSink? logSink, bool logPerceptions = false) { _eventBus = eventBus ?? throw new ArgumentNullException(nameof(eventBus)); _logSink = logSink; + _logPerceptions = logPerceptions; _perceptionKey = eventBus.Subscribe(OnPerception); _actionKey = eventBus.Subscribe(OnAction); _modeChangedKey = eventBus.Subscribe(OnModeChanged); @@ -45,33 +47,33 @@ public void Dispose() private void OnPerception(PerceptionEvent e) { - if (_logSink.GetType().Name == "VerseLogSink") + if (!_logPerceptions) return; - _logSink.Message($"[AgentBus] Perception: NpcId={e.NpcId}, PawnId={e.PawnId}, Type={e.PerceptionType}"); + _logSink?.Message($"[AgentBus] Perception: NpcId={e.NpcId}, PawnId={e.PawnId}, Type={e.PerceptionType}"); } private void OnAction(ActionEvent e) { - _logSink.Message($"[AgentBus] Action: NpcId={e.NpcId}, PawnId={e.PawnId}, Name={e.ActionName}, Success={e.Success}"); + _logSink?.Message($"[AgentBus] Action: NpcId={e.NpcId}, PawnId={e.PawnId}, Name={e.ActionName}, Success={e.Success}"); } private void OnModeChanged(AgentModeChangedEvent e) { - _logSink.Message($"[AgentBus] ModeChanged: NpcId={e.NpcId}, PawnId={e.PawnId}, {e.OldMode}->{e.NewMode}"); + _logSink?.Message($"[AgentBus] ModeChanged: NpcId={e.NpcId}, PawnId={e.PawnId}, {e.OldMode}->{e.NewMode}"); } private void OnLifecycle(AgentLifecycleEvent e) { - _logSink.Message($"[AgentBus] Lifecycle: NpcId={e.NpcId}, PawnId={e.PawnId}, {e.PreviousState}->{e.NewState}"); + _logSink?.Message($"[AgentBus] Lifecycle: NpcId={e.NpcId}, PawnId={e.PawnId}, {e.PreviousState}->{e.NewState}"); } private void OnDecision(DecisionEvent e) { - _logSink.Message($"[AgentBus] Decision: NpcId={e.NpcId}, PawnId={e.PawnId}, Type={e.DecisionType}"); + _logSink?.Message($"[AgentBus] Decision: NpcId={e.NpcId}, PawnId={e.PawnId}, Type={e.DecisionType}"); } private void OnGoal(GoalEvent e) { - _logSink.Message($"[AgentBus] Goal: NpcId={e.NpcId}, PawnId={e.PawnId}, Status={e.Status}, Desc={e.GoalDescription}"); + _logSink?.Message($"[AgentBus] Goal: NpcId={e.NpcId}, PawnId={e.PawnId}, Status={e.Status}, Desc={e.GoalDescription}"); } } diff --git a/Source/Application/Common/Extensions/KeyMetaExtensions.cs b/Source/Application/Common/Extensions/KeyMetaExtensions.cs index 4f2e7073..229b64d2 100644 --- a/Source/Application/Common/Extensions/KeyMetaExtensions.cs +++ b/Source/Application/Common/Extensions/KeyMetaExtensions.cs @@ -5,9 +5,6 @@ namespace RimMind.Application.Common.Extensions { public static class KeyMetaExtensions { - public static ContextProviderDef? GetProviderDef(this KeyMeta meta) - => meta.Def as ContextProviderDef; - public static bool HasAsyncProvider(this KeyMeta meta) => meta.Def is ContextProviderDef; } diff --git a/Source/Application/Common/Helpers/AIProviderRegistry.cs b/Source/Application/Common/Helpers/AIProviderRegistry.cs index 310d4d24..63931c50 100644 --- a/Source/Application/Common/Helpers/AIProviderRegistry.cs +++ b/Source/Application/Common/Helpers/AIProviderRegistry.cs @@ -147,6 +147,22 @@ public static void Register( Register(new AIProviderDescriptor(providerId, requiresApiKey, settingsTabId, displayLabelKey, ownerModId)); } + public static void RegisterFromFactory( + IAIClientFactory factory, + string? settingsTabId = null, + string? displayLabelKey = null) + { + if (factory == null) throw new ArgumentNullException(nameof(factory)); + Register(new AIProviderDescriptor( + factory.ProviderId, + RequiresApiKey: factory.RequiresApiKey, + SettingsTabId: settingsTabId, + DisplayLabelKey: displayLabelKey, + OwnerModId: factory.OwnerModId, + DefaultEndpoint: factory.DefaultEndpoint, + DefaultModelName: factory.DefaultModelName)); + } + public static bool Unregister(string providerId) { if (string.IsNullOrWhiteSpace(providerId)) @@ -154,7 +170,7 @@ public static bool Unregister(string providerId) lock (SyncRoot) { - return Descriptors.Remove(providerId); + return Descriptors.Remove(providerId.Trim()); } } @@ -177,15 +193,7 @@ public static int UnregisterByOwner(string ownerModId) } public static AIProviderDescriptor? FindDescriptor(string? providerId) - { - if (string.IsNullOrWhiteSpace(providerId)) - return null; - - lock (SyncRoot) - { - return Descriptors.TryGetValue(providerId!, out var descriptor) ? descriptor : null; - } - } + => GetDescriptor(providerId); public static IReadOnlyList GetAllDescriptors() { @@ -236,12 +244,12 @@ public static bool RequiresApiKey(string providerId, IExtensionRegistry? registry = null) + public static string? GetSettingsTabId(string? providerId) { if (string.IsNullOrWhiteSpace(providerId)) return null; - var descriptor = FindDescriptor(providerId); + var descriptor = GetDescriptor(providerId); if (!string.IsNullOrWhiteSpace(descriptor?.SettingsTabId)) return descriptor!.SettingsTabId; diff --git a/Source/Application/Common/Interfaces/Abstractions/IPathProvider.cs b/Source/Application/Common/Interfaces/Abstractions/IPathProvider.cs deleted file mode 100644 index fe8b5721..00000000 --- a/Source/Application/Common/Interfaces/Abstractions/IPathProvider.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace RimMind.Application.Common.Interfaces.Abstractions -{ - public interface IPathProvider - { - string SaveDataFolderPath { get; } - } -} diff --git a/Source/Application/Common/Interfaces/Abstractions/ITranslationService.cs b/Source/Application/Common/Interfaces/Abstractions/ITranslationService.cs index 9217d323..7709067f 100644 --- a/Source/Application/Common/Interfaces/Abstractions/ITranslationService.cs +++ b/Source/Application/Common/Interfaces/Abstractions/ITranslationService.cs @@ -2,6 +2,7 @@ namespace RimMind.Application.Common.Interfaces.Abstractions { public interface ITranslationService { + bool CanTranslate(string key); string Translate(string key); string Translate(string key, object arg0); string Translate(string key, object arg0, object arg1); diff --git a/Source/Application/Common/Interfaces/Agent/IAgentIdentity.cs b/Source/Application/Common/Interfaces/Agent/IAgentIdentity.cs deleted file mode 100644 index ef6f913a..00000000 --- a/Source/Application/Common/Interfaces/Agent/IAgentIdentity.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace RimMind.Application.Common.Interfaces.Agent -{ - /// - /// Agent identity interface located in Application/Common/Interfaces so sub-mods can reference it - /// via 1_RimMindApplication.dll without depending on the Presentation layer or Verse. - /// The IExposable implementation lives in the Presentation layer. - /// - public interface IAgentIdentity - { - string NpcId { get; } - int PawnId { get; } - string DisplayName { get; } - System.Collections.Generic.List Motivations { get; } - System.Collections.Generic.List PersonalityTraits { get; } - System.Collections.Generic.List CoreValues { get; } - } -} diff --git a/Source/Application/Common/Interfaces/Agent/IEnvelopeEnricher.cs b/Source/Application/Common/Interfaces/Agent/IEnvelopeEnricher.cs deleted file mode 100644 index 353b76a7..00000000 --- a/Source/Application/Common/Interfaces/Agent/IEnvelopeEnricher.cs +++ /dev/null @@ -1,10 +0,0 @@ -using RimMind.Domain.Llm; - -namespace RimMind.Application.Common.Interfaces.Agent -{ - public interface IEnvelopeEnricher - { - int Order { get; } - void Enrich(LlmRequestEnvelope envelope, IAgentInfo agent); - } -} diff --git a/Source/Application/Common/Interfaces/Agent/IHumanApprovalGate.cs b/Source/Application/Common/Interfaces/Agent/IHumanApprovalGate.cs deleted file mode 100644 index 71edca06..00000000 --- a/Source/Application/Common/Interfaces/Agent/IHumanApprovalGate.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using RimMind.Domain.Agent.Modes; -using RimMind.Domain.Enums; - -namespace RimMind.Application.Common.Interfaces.Agent -{ - public interface IHumanApprovalGate - { - bool RequiresApproval(AgentDecision decision, RiskLevel riskLevel); - void RequestApproval(AgentDecision decision, Action callback); - } -} diff --git a/Source/Application/Common/Interfaces/Agent/IProactiveBehaviorOrchestrator.cs b/Source/Application/Common/Interfaces/Agent/IProactiveBehaviorOrchestrator.cs deleted file mode 100644 index 94aecf0f..00000000 --- a/Source/Application/Common/Interfaces/Agent/IProactiveBehaviorOrchestrator.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace RimMind.Application.Common.Interfaces.Agent -{ - public interface IProactiveBehaviorOrchestrator - { - void ExecuteReflection(IAgentInfo agent); - void ExecutePlanning(IAgentInfo agent); - void ExecuteDream(IAgentInfo agent); - void ExecuteTraitEvolution(IAgentInfo agent); - void ExecuteRegisteredBehaviors(IAgentInfo agent, int currentTick = 0); - void ExecuteAll(IAgentInfo agent, int currentTick = 0); - } -} diff --git a/Source/Application/Common/Interfaces/Agent/Perception/IPerceptionSourceRegistry.cs b/Source/Application/Common/Interfaces/Agent/Perception/IPerceptionSourceRegistry.cs deleted file mode 100644 index a8d3df66..00000000 --- a/Source/Application/Common/Interfaces/Agent/Perception/IPerceptionSourceRegistry.cs +++ /dev/null @@ -1,11 +0,0 @@ -using RimMind.Application.Common.Interfaces.Extension; - -namespace RimMind.Application.Common.Interfaces.Agent.Perception -{ - /// - /// Registry for perception sources. Extends IExtensionRegistry with perception-specific queries. - /// - public interface IPerceptionSourceRegistry : IExtensionRegistry - { - } -} diff --git a/Source/Application/Common/Interfaces/Agent/Psychology/IPawnPsychologyDataProvider.cs b/Source/Application/Common/Interfaces/Agent/Psychology/IPawnPsychologyDataProvider.cs deleted file mode 100644 index b26cc8f6..00000000 --- a/Source/Application/Common/Interfaces/Agent/Psychology/IPawnPsychologyDataProvider.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Collections.Generic; -using RimMind.Domain.Agent.Psychology; - -namespace RimMind.Application.Common.Interfaces.Agent.Psychology; - -/// -/// 小人心理数据提供者——提供心情/需求/精神状态数据,避免 Application 层直接依赖 Verse -/// -public interface IPawnPsychologyDataProvider -{ - /// 获取心情水平 (0-1) - float GetMoodLevel(int pawnId); - - /// 获取所有需求水平 - IReadOnlyList GetNeedLevels(int pawnId); - - /// 获取精神崩溃阈值 - float GetMentalBreakThreshold(int pawnId); - - /// 当前是否处于精神崩溃状态 - bool IsInMentalState(int pawnId); -} diff --git a/Source/Application/Common/Interfaces/Agent/Social/ISleepDetector.cs b/Source/Application/Common/Interfaces/Agent/Social/ISleepDetector.cs deleted file mode 100644 index 236f035a..00000000 --- a/Source/Application/Common/Interfaces/Agent/Social/ISleepDetector.cs +++ /dev/null @@ -1,8 +0,0 @@ -using RimMind.Application.Common.Interfaces.Agent; - -namespace RimMind.Application.Common.Interfaces.Agent.Social; - -public interface ISleepDetector -{ - bool IsSleeping(IAgentInfo agent); -} diff --git a/Source/Application/Common/Interfaces/Client/IHttpRequestDecorator.cs b/Source/Application/Common/Interfaces/Client/IHttpRequestDecorator.cs new file mode 100644 index 00000000..665c6044 --- /dev/null +++ b/Source/Application/Common/Interfaces/Client/IHttpRequestDecorator.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; + +namespace RimMind.Application.Common.Interfaces.Client +{ + /// + /// Typed context passed to instances prior to sending an HTTP request. + /// Carries provider, request, NPC, and session metadata so provider-specific header decorators do not + /// need vendor checks inside shared transport or OpenAI client code. + /// + public sealed record HttpRequestDecorationContext( + string? Url, + string? AuthHeader, + string? CustomSessionId = null, + string? RequestId = null, + string? NpcId = null, + string? Provider = null); + + /// + /// Extensible request decorator invoked by HTTP transports prior to sending requests. + /// Allows concrete provider adapters (e.g. OpenCode session routing) to attach custom headers without + /// embedding vendor literals inside generic transport or client code. + /// + public interface IHttpRequestDecorator + { + string Id { get; } + void Decorate(HttpRequestMessage request, HttpRequestDecorationContext context); + } + + /// + /// Thread-safe registry of extensions applied to outbound HTTP requests. + /// + public static class HttpRequestDecoratorRegistry + { + 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)); + if (string.IsNullOrWhiteSpace(decorator.Id)) + throw new ArgumentException("Decorator Id cannot be null or whitespace.", 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 bool Unregister(string id) + { + if (string.IsNullOrWhiteSpace(id)) return false; + lock (SyncRoot) + { + int removed = Registered.RemoveAll(d => string.Equals(d.Id, id, StringComparison.OrdinalIgnoreCase)); + return removed > 0; + } + } + + public static void ApplyAll(HttpRequestMessage request, HttpRequestDecorationContext context) + { + if (request == null || context == 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, context); + } + } + + public static void Clear() + { + lock (SyncRoot) + { + Registered.Clear(); + } + } + } +} diff --git a/Source/Application/Common/Interfaces/Context/IAsyncContextProvider.cs b/Source/Application/Common/Interfaces/Context/IAsyncContextProvider.cs deleted file mode 100644 index 7a9237f5..00000000 --- a/Source/Application/Common/Interfaces/Context/IAsyncContextProvider.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace RimMind.Application.Common.Interfaces.Context -{ - /// - /// Optional interface for class-style async context providers. - /// Sub-mods can either implement this interface or pass a Provider delegate in ContextProviderDef. - /// - public interface IAsyncContextProvider - { - ContextProviderDef Definition { get; } - Task ProvideAsync(ProviderContext ctx, CancellationToken ct); - } -} diff --git a/Source/Application/Common/Interfaces/Diagnostics/IRequestTraceSummarizer.cs b/Source/Application/Common/Interfaces/Diagnostics/IRequestTraceSummarizer.cs new file mode 100644 index 00000000..9f863db0 --- /dev/null +++ b/Source/Application/Common/Interfaces/Diagnostics/IRequestTraceSummarizer.cs @@ -0,0 +1,125 @@ +using System; +using System.Collections.Generic; +using RimMind.Application.Common.Interfaces.Extension; +using RimMind.Application.Common.Models.Debug; + +namespace RimMind.Application.Common.Interfaces.Diagnostics +{ + /// + /// Summary produced by a submodule for an AI request trace row. + /// + public sealed record RequestTraceSummary( + string ContentSummary, + IReadOnlyList? SuppressToolNames = null); + + /// + /// Extensible trace-summarization seam allowing submodules (e.g. Dialogue) to format their own + /// tool responses, prompts, and tool-badge suppressions in Core's trace UI without Core hardcoding + /// submodule tool names or translation keys. + /// + public interface IRequestTraceSummarizer : IExtension + { + int Order { get; } + bool TrySummarizeResponse(AIRequestTraceEntry entry, out RequestTraceSummary? summary); + bool TrySummarizePrompt(string rawPrompt, out string? summary); + bool ShouldSuppressToolCall(string toolName); + } + + /// + /// Thread-safe registry of extensions queried by trace UI builders. + /// + public static class RequestTraceSummarizerRegistry + { + private static readonly object SyncRoot = new object(); + private static readonly List Registered = new List(); + + public static void Register(IRequestTraceSummarizer summarizer) + { + if (summarizer == null) throw new ArgumentNullException(nameof(summarizer)); + if (string.IsNullOrWhiteSpace(summarizer.Id)) + throw new ArgumentException("Summarizer Id cannot be null or whitespace.", nameof(summarizer)); + + lock (SyncRoot) + { + int idx = Registered.FindIndex(s => string.Equals(s.Id, summarizer.Id, StringComparison.OrdinalIgnoreCase)); + if (idx >= 0) Registered[idx] = summarizer; + else Registered.Add(summarizer); + Registered.Sort((a, b) => a.Order.CompareTo(b.Order)); + } + } + + public static bool Unregister(string id) + { + if (string.IsNullOrWhiteSpace(id)) return false; + lock (SyncRoot) + { + return Registered.RemoveAll(s => string.Equals(s.Id, id, StringComparison.OrdinalIgnoreCase)) > 0; + } + } + + public static int UnregisterByOwner(string ownerModId) + { + if (ownerModId == null) throw new ArgumentNullException(nameof(ownerModId)); + lock (SyncRoot) + { + return Registered.RemoveAll(s => string.Equals(s.OwnerModId, ownerModId, StringComparison.Ordinal)); + } + } + + public static bool TrySummarizeResponse(AIRequestTraceEntry entry, out RequestTraceSummary? summary) + { + summary = null; + if (entry == null) return false; + var snapshot = Snapshot(); + for (int i = 0; i < snapshot.Length; i++) + { + if (snapshot[i].TrySummarizeResponse(entry, out summary) && summary != null) + return true; + } + return false; + } + + public static bool TrySummarizePrompt(string rawPrompt, out string? summary) + { + summary = null; + if (string.IsNullOrWhiteSpace(rawPrompt)) return false; + var snapshot = Snapshot(); + for (int i = 0; i < snapshot.Length; i++) + { + if (snapshot[i].TrySummarizePrompt(rawPrompt, out summary) && !string.IsNullOrWhiteSpace(summary)) + return true; + } + return false; + } + + public static bool ShouldSuppressToolCall(string toolName) + { + if (string.IsNullOrWhiteSpace(toolName)) return false; + var snapshot = Snapshot(); + for (int i = 0; i < snapshot.Length; i++) + { + if (snapshot[i].ShouldSuppressToolCall(toolName)) + return true; + } + return false; + } + + public static IReadOnlyList All => Snapshot(); + + public static void Clear() + { + lock (SyncRoot) + { + Registered.Clear(); + } + } + + private static IRequestTraceSummarizer[] Snapshot() + { + lock (SyncRoot) + { + return Registered.Count == 0 ? Array.Empty() : Registered.ToArray(); + } + } + } +} diff --git a/Source/Application/Common/Interfaces/Diagnostics/ISpan.cs b/Source/Application/Common/Interfaces/Diagnostics/ISpan.cs deleted file mode 100644 index d2a45809..00000000 --- a/Source/Application/Common/Interfaces/Diagnostics/ISpan.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; - -namespace RimMind.Application.Common.Interfaces.Diagnostics -{ - public interface ISpan : IDisposable - { - string SpanId { get; } - string Name { get; } - void SetAttribute(string key, object value); - void RecordException(Exception ex); - } -} diff --git a/Source/Application/Common/Interfaces/Diagnostics/ISpanTracer.cs b/Source/Application/Common/Interfaces/Diagnostics/ISpanTracer.cs deleted file mode 100644 index 1c6e76ec..00000000 --- a/Source/Application/Common/Interfaces/Diagnostics/ISpanTracer.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace RimMind.Application.Common.Interfaces.Diagnostics -{ - public interface ISpanTracer - { - ISpan BeginSpan(string name, string? parentId = null); - } -} diff --git a/Source/Application/Common/Interfaces/Extension/IExtension.cs b/Source/Application/Common/Interfaces/Extension/IExtension.cs index 7a063bc4..258bd5e1 100644 --- a/Source/Application/Common/Interfaces/Extension/IExtension.cs +++ b/Source/Application/Common/Interfaces/Extension/IExtension.cs @@ -1,7 +1,8 @@ -namespace RimMind.Application.Common.Interfaces.Extension; - -public interface IExtension +namespace RimMind.Application.Common.Interfaces.Extension { - string Id { get; } - string OwnerModId { get; } + public interface IExtension + { + string Id { get; } + string OwnerModId { get; } + } } diff --git a/Source/Application/Common/Interfaces/IEventSubscriber.cs b/Source/Application/Common/Interfaces/IEventSubscriber.cs index a46e4f09..3fed2c8e 100644 --- a/Source/Application/Common/Interfaces/IEventSubscriber.cs +++ b/Source/Application/Common/Interfaces/IEventSubscriber.cs @@ -9,8 +9,6 @@ public interface IEventSubscriber void Subscribe(string key, Action handler) where T : AgentBusEvent; void Unsubscribe(string key) where T : AgentBusEvent; void Unsubscribe(string key); - [Obsolete("Use Unsubscribe(string key) instead. Action-based unsubscribe is unreliable due to lambda wrapping.")] - void Unsubscribe(Action handler) where T : AgentBusEvent; string SubscribeByName(string eventTypeName, Action handler); } } diff --git a/Source/Application/Common/Interfaces/Internal/IApiCredentialSettings.cs b/Source/Application/Common/Interfaces/Internal/IApiCredentialSettings.cs index 24977c88..9a95d6d0 100644 --- a/Source/Application/Common/Interfaces/Internal/IApiCredentialSettings.cs +++ b/Source/Application/Common/Interfaces/Internal/IApiCredentialSettings.cs @@ -8,9 +8,9 @@ public interface IApiCredentialSettings string Provider { get; set; } string ApiKey { get; set; } string ApiEndpoint { get; set; } - string Player2RemoteUrl { get; set; } IReadOnlyList? BackupEndpoints { get; } bool IsConfigured { get; } - bool IsOpenAIConfigured(); + string GetProviderOption(string key); + void SetProviderOption(string key, string value); } } diff --git a/Source/Application/Common/Interfaces/Internal/IClientManager.cs b/Source/Application/Common/Interfaces/Internal/IClientManager.cs index 722546ac..51288d03 100644 --- a/Source/Application/Common/Interfaces/Internal/IClientManager.cs +++ b/Source/Application/Common/Interfaces/Internal/IClientManager.cs @@ -6,6 +6,5 @@ public interface IClientManager { IAIClient? GetClient(); void InvalidateCache(); - IAIClient? GetPlayer2Client(); } } diff --git a/Source/Application/Common/Interfaces/Internal/RimMindServiceLocator.cs b/Source/Application/Common/Interfaces/Internal/RimMindServiceLocator.cs deleted file mode 100644 index 9e4f995f..00000000 --- a/Source/Application/Common/Interfaces/Internal/RimMindServiceLocator.cs +++ /dev/null @@ -1,2 +0,0 @@ -// Legacy global service lookup removed by the lifecycle service hard cut. -// File retained pending explicit owner approval for deletion. diff --git a/Source/Application/Common/Interfaces/Mechanisms/IMechanismMetadata.cs b/Source/Application/Common/Interfaces/Mechanisms/IMechanismMetadata.cs index b033da13..ec5815d9 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.Application.Common.Models.Tools; using RimMind.Domain.Agent.Policies; using RimMind.Domain.Enums; @@ -26,4 +27,14 @@ public interface IMechanismAutonomyMetadata : IMechanismMetadata { AutonomyDomain? GetAutonomyDomainForOperation(MechanismOperationType operation); } + + /// + /// Optional additive interface allowing mechanisms to declaratively announce the + /// for each operation instead of relying on name heuristics + /// in MechanismToolHandler or ToolScopeProjection. + /// + public interface IMechanismScopeMetadata : IMechanismMetadata + { + ToolScope? GetToolScopeForOperation(MechanismOperationType operation); + } } diff --git a/Source/Application/Common/Models/Agent/AgentGoalStack.cs b/Source/Application/Common/Models/Agent/AgentGoalStack.cs index 832730a2..275aea5a 100644 --- a/Source/Application/Common/Models/Agent/AgentGoalStack.cs +++ b/Source/Application/Common/Models/Agent/AgentGoalStack.cs @@ -54,10 +54,13 @@ public bool TryAdd(AgentGoal goal, int pawnId) { var removable = _goals.FirstOrDefault(g => g.Status == GoalStatus.Proposed); if (removable == null) return false; - if (removable.Status == GoalStatus.Active) _activeCount--; _goals.Remove(removable); } - if (ActiveCount < MaxActiveGoals && goal.Status == GoalStatus.Proposed) + if (goal.Status == GoalStatus.Active) + { + _activeCount++; + } + else if (ActiveCount < MaxActiveGoals && goal.Status == GoalStatus.Proposed) { goal.Status = GoalStatus.Active; _activeCount++; @@ -118,6 +121,7 @@ public void Clear() { _goals.Clear(); _activeCount = 0; + BumpVersion(); } private void BumpVersion() => _version++; diff --git a/Source/Application/Common/Models/Agent/AgentIdentity.cs b/Source/Application/Common/Models/Agent/AgentIdentity.cs index 95d87acd..22df5177 100644 --- a/Source/Application/Common/Models/Agent/AgentIdentity.cs +++ b/Source/Application/Common/Models/Agent/AgentIdentity.cs @@ -1,7 +1,5 @@ using System.Collections.Generic; -using RimMind.Application.Common.Interfaces.Agent; - namespace RimMind.Application.Common.Models.Agent { /// @@ -11,7 +9,7 @@ namespace RimMind.Application.Common.Models.Agent /// IExposable serialization is handled by the Presentation-layer subclass /// . /// - public class AgentIdentity : IAgentIdentity + public class AgentIdentity { public string NpcId = ""; public int PawnId; @@ -20,13 +18,6 @@ public class AgentIdentity : IAgentIdentity public List PersonalityTraits = new List(); public List CoreValues = new List(); - string IAgentIdentity.NpcId => NpcId; - int IAgentIdentity.PawnId => PawnId; - string IAgentIdentity.DisplayName => DisplayName; - List IAgentIdentity.Motivations => Motivations; - List IAgentIdentity.PersonalityTraits => PersonalityTraits; - List IAgentIdentity.CoreValues => CoreValues; - public AgentIdentity() { } public AgentIdentity(string npcId, int pawnId, string displayName) diff --git a/Source/Application/Common/Models/Client/BackupEndpointNode.cs b/Source/Application/Common/Models/Client/BackupEndpointNode.cs index 20d30624..ad13cf82 100644 --- a/Source/Application/Common/Models/Client/BackupEndpointNode.cs +++ b/Source/Application/Common/Models/Client/BackupEndpointNode.cs @@ -1,3 +1,6 @@ +using RimMind.Application.Common.Helpers; +using RimMind.Application.Features.Llm; + namespace RimMind.Application.Common.Models.Client { /// @@ -15,7 +18,9 @@ public sealed class BackupEndpointNode public bool IsConfigured => Enabled && !string.IsNullOrWhiteSpace(ApiEndpoint) && - !string.IsNullOrWhiteSpace(ApiKey) && - !string.IsNullOrWhiteSpace(ModelName); + !string.IsNullOrWhiteSpace(ModelName) && + (!string.IsNullOrWhiteSpace(ApiKey) || + RimMindHttpClientPool.IsLoopbackEndpoint(ApiEndpoint) || + !AIProviderRegistry.RequiresApiKey(Provider)); } } diff --git a/Source/Application/Common/Models/Debug/AgentRolloutModelBuilder.cs b/Source/Application/Common/Models/Debug/AgentRolloutModelBuilder.cs index e5838180..b6d85a9c 100644 --- a/Source/Application/Common/Models/Debug/AgentRolloutModelBuilder.cs +++ b/Source/Application/Common/Models/Debug/AgentRolloutModelBuilder.cs @@ -278,8 +278,8 @@ private static bool IsRolloutEntry(AIRequestTraceEntry entry) return true; string scenario = ResolveScenarioId(entry); string mod = ResolveModId(entry); - return Context.ScenarioIds.IsDecisionScenario(scenario) - || string.Equals(mod, "RimMind.Agent", StringComparison.OrdinalIgnoreCase); + return Features.Context.ScenarioRegistry.IsDecisionScenario(scenario) + || string.Equals(mod, Constants.RimMindOwnerConsts.AgentModId, StringComparison.OrdinalIgnoreCase); } private static double ComputePrefixReuseRatio(IReadOnlyList turns) diff --git a/Source/Application/Common/Models/Diagnostics/InMemorySpanTracer.cs b/Source/Application/Common/Models/Diagnostics/InMemorySpanTracer.cs deleted file mode 100644 index b31febfa..00000000 --- a/Source/Application/Common/Models/Diagnostics/InMemorySpanTracer.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using RimMind.Application.Common.Interfaces.Diagnostics; - -namespace RimMind.Application.Common.Models.Diagnostics -{ - public sealed class InMemorySpanTracer : ISpanTracer - { - private readonly ConcurrentBag _spans = new(); - private const int MaxSpans = 1000; - - public IReadOnlyList GetSpans() => _spans.ToList(); - public IReadOnlyList GetSpans(string traceId) => _spans.Where(s => s.ParentId == traceId || s.SpanId == traceId).ToList(); - public void Clear() { while (_spans.TryTake(out _)) { } } - - public ISpan BeginSpan(string name, string? parentId = null) - { - var record = new SpanRecord { Name = name, ParentId = parentId }; - if (_spans.Count >= MaxSpans) - { - var oldest = _spans.OrderBy(s => s.StartTime).FirstOrDefault(); - if (oldest != null) _spans.Take(1); - } - _spans.Add(record); - return new InMemorySpan(record, this); - } - - private void EndSpan(SpanRecord record) => record.EndTime = DateTime.UtcNow; - - private sealed class InMemorySpan : ISpan - { - private readonly SpanRecord _record; - private readonly InMemorySpanTracer _tracer; - private bool _disposed; - - public string SpanId => _record.SpanId; - public string Name => _record.Name; - - public InMemorySpan(SpanRecord record, InMemorySpanTracer tracer) - { - _record = record; - _tracer = tracer; - } - - public void SetAttribute(string key, object value) => _record.Attributes[key] = value; - public void RecordException(Exception ex) => _record.Exception = ex; - - public void Dispose() - { - if (_disposed) return; - _disposed = true; - _tracer.EndSpan(_record); - } - } - } -} diff --git a/Source/Application/Common/Models/Diagnostics/SpanRecord.cs b/Source/Application/Common/Models/Diagnostics/SpanRecord.cs deleted file mode 100644 index 8d14c154..00000000 --- a/Source/Application/Common/Models/Diagnostics/SpanRecord.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace RimMind.Application.Common.Models.Diagnostics -{ - public sealed class SpanRecord - { - public string SpanId { get; init; } = Guid.NewGuid().ToString("N").Substring(0, 8); - public string Name { get; init; } = ""; - public string? ParentId { get; init; } - public DateTime StartTime { get; init; } = DateTime.UtcNow; - public DateTime? EndTime { get; set; } - public Dictionary Attributes { get; init; } = new(); - public Exception? Exception { get; set; } - public long DurationMs => EndTime.HasValue ? (long)(EndTime.Value - StartTime).TotalMilliseconds : -1; - } -} diff --git a/Source/Application/Common/Models/Npc/StorageDriverDependencies.cs b/Source/Application/Common/Models/Npc/StorageDriverDependencies.cs deleted file mode 100644 index f7c27f6d..00000000 --- a/Source/Application/Common/Models/Npc/StorageDriverDependencies.cs +++ /dev/null @@ -1,38 +0,0 @@ -using RimMind.Application.Common.Interfaces; -using RimMind.Application.Common.Interfaces.Abstractions; -using RimMind.Application.Common.Interfaces.Context; -using RimMind.Application.Common.Interfaces.Internal; -using RimMind.Application.Common.Interfaces.Npc; - -namespace RimMind.Application.Common.Models.Npc -{ - /// - /// Parameter object grouping common storage driver dependencies. - /// Reduces constructor parameter count for StorageDriver implementations. - /// - public sealed class StorageDriverDependencies - { - public INpcManager NpcManager { get; } - public ILogSink LogSink { get; } - public IContextBuilder ContextBuilder { get; } - public ISettingsProvider SettingsProvider { get; } - public IGameContextBuilder GameContextBuilder { get; } - public IResponseDispatcher ResponseDispatcher { get; } - - public StorageDriverDependencies( - INpcManager npcManager, - ILogSink logSink, - IContextBuilder contextBuilder, - ISettingsProvider settingsProvider, - IGameContextBuilder gameContextBuilder, - IResponseDispatcher responseDispatcher) - { - NpcManager = npcManager; - LogSink = logSink; - ContextBuilder = contextBuilder; - SettingsProvider = settingsProvider; - GameContextBuilder = gameContextBuilder; - ResponseDispatcher = responseDispatcher; - } - } -} diff --git a/Source/Application/Common/Models/Pipeline/PipelineContextKeys.cs b/Source/Application/Common/Models/Pipeline/PipelineContextKeys.cs new file mode 100644 index 00000000..3cca505a --- /dev/null +++ b/Source/Application/Common/Models/Pipeline/PipelineContextKeys.cs @@ -0,0 +1,12 @@ +namespace RimMind.Application.Common.Models.Pipeline +{ + /// + /// Canonical keys used in for cross-middleware communication. + /// + public static class PipelineContextKeys + { + public const string NpcProfile = "NpcProfile"; + public const string FallbackContent = "fallback_content"; + public const string RecentActionIntents = "recent_action_intents"; + } +} diff --git a/Source/Application/Common/Models/Pipeline/PromptAugmentation.cs b/Source/Application/Common/Models/Pipeline/PromptAugmentation.cs deleted file mode 100644 index b0a2c490..00000000 --- a/Source/Application/Common/Models/Pipeline/PromptAugmentation.cs +++ /dev/null @@ -1 +0,0 @@ -// PromptAugmentation is Domain-owned at Source/Domain/Llm/PromptAugmentation.cs. diff --git a/Source/Application/Common/Models/RimMindDefaults.cs b/Source/Application/Common/Models/RimMindDefaults.cs index 99945b74..bcf86327 100644 --- a/Source/Application/Common/Models/RimMindDefaults.cs +++ b/Source/Application/Common/Models/RimMindDefaults.cs @@ -103,9 +103,6 @@ public static class RimMindDefaults public const float ReserveBudgetWeight = 0.4f; // Queue settings - /// Game ticks per millisecond (for tick-to-ms conversion). - public const int TicksPerMillisecond = 16; - /// Number of failures before circuit breaker opens. public const int CircuitBreakerFailureThreshold = 5; diff --git a/Source/Application/Common/Models/Tools/ToolManifest.cs b/Source/Application/Common/Models/Tools/ToolManifest.cs index 955b1d81..05971d8f 100644 --- a/Source/Application/Common/Models/Tools/ToolManifest.cs +++ b/Source/Application/Common/Models/Tools/ToolManifest.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using RimMind.Application.Common.Constants; using RimMind.Application.Common.Models.Agent; using RimMind.Domain.Agent.Policies; using RimMind.Domain.Enums; @@ -27,7 +28,7 @@ public enum ToolScope public sealed record ToolManifest { - public string OwnerModId { get; init; } = "RimMind.Core"; + public string OwnerModId { get; init; } = RimMindOwnerConsts.CoreModId; public IReadOnlyList AllowedScopes { get; init; } = Array.AsReadOnly((AgentScopeKind[])Enum.GetValues(typeof(AgentScopeKind))); public ToolKind Kind { get; init; } = ToolKind.Mutation; @@ -36,12 +37,18 @@ public sealed record ToolManifest public string? AutonomyDomainId { get; init; } public RiskLevel RiskLevel { get; init; } = RiskLevel.Medium; public bool RequiresApproval { get; init; } + public bool RequiresProactiveMode { get; init; } public IReadOnlyList Aliases { get; init; } = Array.Empty(); public bool IsSelfTargeted { get; init; } public string? DisplayName { get; init; } public IReadOnlyList SummaryArgKeys { get; init; } = Array.Empty(); public string SchemaVersion { get; init; } = "1"; + public string? ResolveDomainId() + => !string.IsNullOrWhiteSpace(AutonomyDomainId) + ? AutonomyDomainId!.Trim() + : DefaultDomain?.ToString(); + public static ToolManifest Default { get; } = new ToolManifest(); } } diff --git a/Source/Application/Common/Threading/MainThreadReader.cs b/Source/Application/Common/Threading/MainThreadReader.cs index c022e11f..239d19d1 100644 --- a/Source/Application/Common/Threading/MainThreadReader.cs +++ b/Source/Application/Common/Threading/MainThreadReader.cs @@ -118,6 +118,7 @@ private async Task PostAndAwaitAsync(Func read, T fallback, TimeSpan ti if (!abandoned && completion.Task.IsCompleted) return await completion.Task.ConfigureAwait(false); + SynchronousTaskGate.ObserveFault(completion.Task); ct.ThrowIfCancellationRequested(); Interlocked.Increment(ref _timeoutCount); return fallback; diff --git a/Source/Application/DependencyInjection.cs b/Source/Application/DependencyInjection.cs index ce3d1421..205a5bd1 100644 --- a/Source/Application/DependencyInjection.cs +++ b/Source/Application/DependencyInjection.cs @@ -1,19 +1,15 @@ using RimMind.Application.Common.Interfaces; using RimMind.Application.Common.Interfaces.Abstractions; -using RimMind.Application.Common.Interfaces.Context; -using RimMind.Application.Common.Interfaces.Extension; +using RimMind.Application.Common.Interfaces.Async; using RimMind.Application.Common.Interfaces.Flywheel; using RimMind.Application.Common.Interfaces.Internal; using RimMind.Application.Common.Interfaces.Json; -using RimMind.Application.Common.Interfaces.Pipeline; -using RimMind.Application.Common.Interfaces.Sensor; using RimMind.Application.Common.Interfaces.Tools; using RimMind.Application.Features.AgentBus; using RimMind.Application.Features.Flywheel; using RimMind.Application.Features.Json; using RimMind.Application.Features.Requests.Queue; using RimMind.Application.Features.Tools; -using RimMind.Application.Common.Interfaces.Async; namespace RimMind.Application { diff --git a/Source/Application/Features/Agent/AgenticLoopService.cs b/Source/Application/Features/Agent/AgenticLoopService.cs index dfca0835..766dd893 100644 --- a/Source/Application/Features/Agent/AgenticLoopService.cs +++ b/Source/Application/Features/Agent/AgenticLoopService.cs @@ -3,7 +3,13 @@ namespace RimMind.Application.Features.Agent { - public class AgenticLoopService : IAgenticLoopService + public sealed record LoopResult(bool ShouldContinue, AgentDecision? FinalDecision = null, string? Reason = null) + { + public static LoopResult Continue(string reason) => new(true, Reason: reason); + public static LoopResult Stop(AgentDecision decision, string? reason = null) => new(false, decision, reason); + } + + public class AgenticLoopService { public AgenticLoopService(int maxDepth = RimMindDefaults.DefaultMaxToolCallDepth) { diff --git a/Source/Application/Features/Agent/BehaviorHistoryEnricher.cs b/Source/Application/Features/Agent/BehaviorHistoryEnricher.cs deleted file mode 100644 index 1fe3348c..00000000 --- a/Source/Application/Features/Agent/BehaviorHistoryEnricher.cs +++ /dev/null @@ -1,75 +0,0 @@ -using System; -using System.Text; -using RimMind.Application.Common.Interfaces.Agent; -using RimMind.Domain.Llm; - -namespace RimMind.Application.Features.Agent -{ - internal sealed class BehaviorHistoryEnricher : IEnvelopeEnricher - { - public int Order => 20; - - public void Enrich(LlmRequestEnvelope envelope, IAgentInfo agent) - { - if (envelope?.GameStateInfo == null || agent == null) return; - var history = FormatBehaviorHistory(agent); - if (!string.IsNullOrEmpty(history)) - envelope.GameStateInfo.AddSection("behavior_history", history); - } - - private string FormatBehaviorHistory(IAgentInfo agent) - { - var recentHistory = agent.GetRecentHistory(10); - var successRate = agent.GetRecentSuccessRate(10); - - if (recentHistory == null || recentHistory.Count == 0) return ""; - - var sb = new StringBuilder(); - sb.AppendLine(""); - string? lastRawLine = null; - string? lastNormalizedKey = null; - int repeatCount = 0; - - void FlushPendingLine() - { - if (lastRawLine == null) return; - sb.AppendLine(repeatCount > 1 - ? $"{lastRawLine.TrimEnd()} (x{repeatCount})" - : lastRawLine); - lastRawLine = null; - lastNormalizedKey = null; - repeatCount = 0; - } - - foreach (var record in recentHistory) - { - var status = record.Success - ? "Success" - : (!string.IsNullOrWhiteSpace(record.ResultReason) ? $"Fail ({record.ResultReason})" : "Fail"); - string line = $"- {record.Action} → {status}: {record.Reason}"; - string normalizedKey = line.TrimEnd(); - - if (string.Equals(normalizedKey, lastNormalizedKey, StringComparison.OrdinalIgnoreCase)) - { - repeatCount++; - } - else - { - FlushPendingLine(); - lastRawLine = line; - lastNormalizedKey = normalizedKey; - repeatCount = 1; - } - } - FlushPendingLine(); - - if (successRate < 0.4f) - { - sb.AppendLine("[Warning: Recent behavior success rate is low. Consider more cautious decisions.]"); - } - - sb.AppendLine(""); - return sb.ToString(); - } - } -} diff --git a/Source/Application/Features/Agent/DecisionMapper.cs b/Source/Application/Features/Agent/DecisionMapper.cs index e9c811e1..abe4a9eb 100644 --- a/Source/Application/Features/Agent/DecisionMapper.cs +++ b/Source/Application/Features/Agent/DecisionMapper.cs @@ -1,3 +1,5 @@ +using System; +using System.Collections.Concurrent; using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -13,6 +15,25 @@ namespace RimMind.Application.Features.Agent /// public static class DecisionMapper { + private static readonly ConcurrentDictionary ActionAliases = + new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase) + { + ["prioritize_work"] = ("pawn.work", "set_priority"), + ["set_work_priority"] = ("pawn.work", "set_priority"), + ["take_job"] = ("pawn.job", "assign_work") + }; + + /// + /// Registers or overrides an action intent alias mapping to a target mechanism and action. + /// Allows submodules to register shorthand intents without modifying Core. + /// + public static void RegisterActionAlias(string alias, string mechanismId, string action) + { + if (string.IsNullOrWhiteSpace(alias) || string.IsNullOrWhiteSpace(mechanismId)) + return; + ActionAliases[alias.Trim()] = (mechanismId.Trim(), action ?? string.Empty); + } + /// /// Map an AgentDecision to a MechanismWriteArgs for the given pawn. /// ActionIntent format: "mechanismId.action" (e.g., "pawn.job.force_rest") @@ -40,7 +61,8 @@ public static MechanismWriteArgs ToWriteArgs(AgentDecision decision, int pawnId) else if (paramsDict.TryGetValue("job_type", out var jt) && !string.IsNullOrEmpty(jt)) defName = jt; - if (mechanismId == "pawn.work") + if (string.Equals(action, "set_priority", StringComparison.OrdinalIgnoreCase) + || string.Equals(mechanismId, "pawn.work", StringComparison.OrdinalIgnoreCase)) { if (paramsDict.TryGetValue("priority", out var prio) && !string.IsNullOrEmpty(prio)) valueJson = prio; @@ -94,12 +116,8 @@ public static (string mechanismId, string action) ParseActionIntent(string actio if (string.IsNullOrEmpty(actionIntent)) return ("pawn.job", ""); - if (string.Equals(actionIntent, "prioritize_work", System.StringComparison.OrdinalIgnoreCase) - || string.Equals(actionIntent, "set_work_priority", System.StringComparison.OrdinalIgnoreCase)) - return ("pawn.work", "set_priority"); - - if (string.Equals(actionIntent, "take_job", System.StringComparison.OrdinalIgnoreCase)) - return ("pawn.job", "assign_work"); + if (ActionAliases.TryGetValue(actionIntent, out var aliased)) + return aliased; var lastDot = actionIntent.LastIndexOf('.'); if (lastDot <= 0) diff --git a/Source/Application/Features/Agent/DecisionProcessor.cs b/Source/Application/Features/Agent/DecisionProcessor.cs index 79dee8d0..a3787345 100644 --- a/Source/Application/Features/Agent/DecisionProcessor.cs +++ b/Source/Application/Features/Agent/DecisionProcessor.cs @@ -4,7 +4,6 @@ using RimMind.Application.Common.Interfaces.Abstractions; using RimMind.Application.Common.Interfaces.Agent; using RimMind.Application.Common.Interfaces.Agent.Modes; -using RimMind.Application.Common.Models; using RimMind.Application.Common.Models.Agent; using RimMind.Application.Common.Models.Pipeline; using RimMind.Application.Common.Models.Tools; @@ -23,7 +22,7 @@ namespace RimMind.Application.Features.Agent /// executes decisions, records behavior, and publishes events. /// Extracted from PawnThinker.ProcessPendingCallback for single-responsibility. /// - public class DecisionProcessor : IDecisionProcessor + public class DecisionProcessor { private readonly IAgentControl _agent; private readonly IAgentBus _agentBus; @@ -34,9 +33,9 @@ public class DecisionProcessor : IDecisionProcessor private readonly Action _transitionWorkflow; private readonly Func> _executeDecision; private readonly Func _getPawnId; - private readonly IDecisionValidator _validator; + private readonly DecisionValidator _validator; private readonly IToolRegistry? _toolRegistry; - private readonly IAgenticLoopService _loopService; + private readonly AgenticLoopService _loopService; private readonly Action? _recordTraceOutcome; public DecisionProcessor( @@ -49,9 +48,9 @@ public DecisionProcessor( Func> executeDecision, Func getPawnId, ILogSink? log = null, - IDecisionValidator? validator = null, + DecisionValidator? validator = null, IToolRegistry? toolRegistry = null, - IAgenticLoopService? loopService = null, + AgenticLoopService? loopService = null, Action? recordTraceOutcome = null) { _agent = agent ?? throw new ArgumentNullException(nameof(agent)); diff --git a/Source/Application/Features/Agent/DecisionValidator.cs b/Source/Application/Features/Agent/DecisionValidator.cs index 27fcab11..0a52b0aa 100644 --- a/Source/Application/Features/Agent/DecisionValidator.cs +++ b/Source/Application/Features/Agent/DecisionValidator.cs @@ -1,3 +1,4 @@ +using System; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -6,7 +7,13 @@ namespace RimMind.Application.Features.Agent { - public class DecisionValidator : IDecisionValidator + public sealed record ValidationResult(bool IsValid, string Reason = "") + { + public static ValidationResult Ok() => new(true); + public static ValidationResult Fail(string reason) => new(false, reason); + } + + public class DecisionValidator { public ValidationResult Validate(AgentDecision decision, IToolRegistry toolRegistry) { @@ -19,23 +26,25 @@ public ValidationResult Validate(AgentDecision decision, IToolRegistry toolRegis if (decision.ActionIntent == "dialogue.free") return ValidationResult.Ok(); - var dotIndex = decision.ActionIntent.IndexOf('.'); - if (dotIndex < 0 || dotIndex >= decision.ActionIntent.Length - 1) - return ValidationResult.Fail($"ActionIntent '{decision.ActionIntent}' does not follow mechanism.action format"); - - var mechanismId = decision.ActionIntent.Substring(0, dotIndex); - var actionSuffix = decision.ActionIntent.Substring(dotIndex + 1); - var handler = toolRegistry.FindById(decision.ActionIntent); if (handler == null) { - var mechanismExists = toolRegistry.All.Any(h => h.Id.StartsWith(mechanismId + ".")); - if (!mechanismExists) + var dotIndex = decision.ActionIntent.LastIndexOf('.'); + if (dotIndex <= 0 || dotIndex >= decision.ActionIntent.Length - 1) + return ValidationResult.Fail($"Unknown tool or ActionIntent '{decision.ActionIntent}'"); + + var mechanismId = decision.ActionIntent.Substring(0, dotIndex); + var actionSuffix = decision.ActionIntent.Substring(dotIndex + 1); + string prefix = mechanismId + "."; + + var matchingHandlers = toolRegistry.All + .Where(h => h.Id.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + .ToList(); + if (matchingHandlers.Count == 0) return ValidationResult.Fail($"No mechanism found for '{mechanismId}' in ActionIntent '{decision.ActionIntent}'"); - var supportedSuffixes = toolRegistry.All - .Where(h => h.Id.StartsWith(mechanismId + ".")) - .Select(h => h.Id.Substring(mechanismId.Length + 1)) + var supportedSuffixes = matchingHandlers + .Select(h => h.Id.Substring(prefix.Length)) .ToList(); return ValidationResult.Fail($"Operation '{actionSuffix}' not supported by mechanism '{mechanismId}'. Supported: {string.Join(", ", supportedSuffixes)}"); } diff --git a/Source/Application/Features/Agent/EnvelopeEnrichmentCoordinator.cs b/Source/Application/Features/Agent/EnvelopeEnrichmentCoordinator.cs deleted file mode 100644 index 91b9258a..00000000 --- a/Source/Application/Features/Agent/EnvelopeEnrichmentCoordinator.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using RimMind.Application.Common.Interfaces.Agent; -using RimMind.Domain.Llm; - -namespace RimMind.Application.Features.Agent -{ - internal class EnvelopeEnrichmentCoordinator - { - private readonly List _enrichers; - - public EnvelopeEnrichmentCoordinator(IEnumerable enrichers) - { - _enrichers = (enrichers ?? Enumerable.Empty()) - .OrderBy(e => e.Order).ToList(); - } - - public void EnrichAll(LlmRequestEnvelope envelope, IAgentInfo agent) - { - if (envelope == null || agent == null) return; - foreach (var enricher in _enrichers) - enricher.Enrich(envelope, agent); - } - } -} diff --git a/Source/Application/Features/Agent/IAgenticLoopService.cs b/Source/Application/Features/Agent/IAgenticLoopService.cs deleted file mode 100644 index 86524a67..00000000 --- a/Source/Application/Features/Agent/IAgenticLoopService.cs +++ /dev/null @@ -1,17 +0,0 @@ -using RimMind.Domain.Agent.Modes; - -namespace RimMind.Application.Features.Agent -{ - public interface IAgenticLoopService - { - int MaxDepth { get; } - bool ShouldContinue(AgentDecision decision, int currentDepth); - LoopResult Evaluate(AgentDecision decision, int currentDepth); - } - - public sealed record LoopResult(bool ShouldContinue, AgentDecision? FinalDecision = null, string? Reason = null) - { - public static LoopResult Continue(string reason) => new(true, Reason: reason); - public static LoopResult Stop(AgentDecision decision, string? reason = null) => new(false, decision, reason); - } -} diff --git a/Source/Application/Features/Agent/IDecisionProcessor.cs b/Source/Application/Features/Agent/IDecisionProcessor.cs deleted file mode 100644 index e0c7b4e7..00000000 --- a/Source/Application/Features/Agent/IDecisionProcessor.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Collections.Generic; -using RimMind.Application.Common.Interfaces.Agent.Modes; -using RimMind.Application.Common.Models.Pipeline; -using RimMind.Application.Common.Models.Tools; -using RimMind.Domain.Common; -using RimMind.Domain.ValueObjects; -using RimMind.Domain.Llm; - -namespace RimMind.Application.Features.Agent -{ - /// - /// Processes AI callback results: validates, handles agentic loop continuation, - /// executes decisions, records behavior, and publishes events. - /// Extracted from PawnThinker.ProcessPendingCallback for single-responsibility. - /// - public interface IDecisionProcessor - { - /// - /// Process the result of an AI think request. - /// Returns true if the think cycle is complete (decision executed or failed), - /// false if the agentic loop continues (more tool calls needed). - /// - bool ProcessResult( - Result result, - LlmRequestContext? context, - IThinkStrategy strategy, - IReadOnlyList availableTools, - int toolCallRound); - } -} diff --git a/Source/Application/Features/Agent/IDecisionValidator.cs b/Source/Application/Features/Agent/IDecisionValidator.cs deleted file mode 100644 index 47c71e66..00000000 --- a/Source/Application/Features/Agent/IDecisionValidator.cs +++ /dev/null @@ -1,16 +0,0 @@ -using RimMind.Domain.Agent.Modes; -using RimMind.Application.Common.Interfaces.Tools; - -namespace RimMind.Application.Features.Agent -{ - public sealed record ValidationResult(bool IsValid, string Reason = "") - { - public static ValidationResult Ok() => new(true); - public static ValidationResult Fail(string reason) => new(false, reason); - } - - public interface IDecisionValidator - { - ValidationResult Validate(AgentDecision decision, IToolRegistry toolRegistry); - } -} diff --git a/Source/Application/Features/Agent/InnerVoice/InnerVoiceHandler.cs b/Source/Application/Features/Agent/InnerVoice/InnerVoiceHandler.cs index 5a872a70..7653010d 100644 --- a/Source/Application/Features/Agent/InnerVoice/InnerVoiceHandler.cs +++ b/Source/Application/Features/Agent/InnerVoice/InnerVoiceHandler.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Concurrent; -using System.Collections.Generic; using RimMind.Application.Common.Interfaces; using RimMind.Application.Common.Interfaces.Abstractions; using RimMind.Domain.Events; @@ -25,6 +24,11 @@ public InnerVoiceHandler(IAgentBus agentBus, ITickProvider tickProvider, ILogSin public void StartListening() { + if (_subscriptionKey != null) + { + _agentBus.Unsubscribe(_subscriptionKey); + _subscriptionKey = null; + } _subscriptionKey = _agentBus.Subscribe(OnInnerVoiceEvent); } @@ -35,6 +39,7 @@ public void StopListening() _agentBus.Unsubscribe(_subscriptionKey); _subscriptionKey = null; } + _pendingVoices.Clear(); } private void OnInnerVoiceEvent(InnerVoiceEvent evt) diff --git a/Source/Application/Features/Agent/Modes/DefaultModeTransitionPolicy.cs b/Source/Application/Features/Agent/Modes/DefaultModeTransitionPolicy.cs index 8b76bf09..9244db19 100644 --- a/Source/Application/Features/Agent/Modes/DefaultModeTransitionPolicy.cs +++ b/Source/Application/Features/Agent/Modes/DefaultModeTransitionPolicy.cs @@ -1,8 +1,6 @@ using RimMind.Application.Common.Constants; -using RimMind.Application.Common.Interfaces; using RimMind.Application.Common.Interfaces.Agent; using RimMind.Application.Common.Interfaces.Agent.Modes; -using RimMind.Application.Common.Interfaces.Extension; using RimMind.Domain.Agent.Modes; namespace RimMind.Application.Features.Agent.Modes diff --git a/Source/Application/Features/Agent/Modes/ProactiveAgentMode.cs b/Source/Application/Features/Agent/Modes/ProactiveAgentMode.cs index d0f4049b..7d6f2807 100644 --- a/Source/Application/Features/Agent/Modes/ProactiveAgentMode.cs +++ b/Source/Application/Features/Agent/Modes/ProactiveAgentMode.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using RimMind.Application.Common.Constants; @@ -97,7 +96,7 @@ public IReadOnlyList AllowedToolIds(IToolRegistry registry) internal sealed class ProactiveThinkStrategy : IThinkStrategy { - private static readonly List CachedExamples = ThinkStrategyHelper.BuildDecisionExamples(); + private static readonly IReadOnlyList CachedExamples = ThinkStrategyHelper.BuildDecisionExamples(); public string ScenarioId => ScenarioIds.AgentDecision; @@ -113,7 +112,7 @@ public LlmRequestEnvelope BuildEnvelope(IAgentInfo agent, var examples = CachedExamples; return LlmRequestEnvelopeBuilder .ForScenario(ScenarioId) - .WithModId("RimMind.Agent") + .WithModId(RimMindOwnerConsts.AgentModId) .WithNpcId(agent.NpcId) .WithGameStateInfo(new GameStateInfo().AddSection("perceptions", query)) .WithSchema("...") diff --git a/Source/Application/Features/Agent/Modes/ReactiveAgentMode.cs b/Source/Application/Features/Agent/Modes/ReactiveAgentMode.cs index af3a42ba..7ef74df0 100644 --- a/Source/Application/Features/Agent/Modes/ReactiveAgentMode.cs +++ b/Source/Application/Features/Agent/Modes/ReactiveAgentMode.cs @@ -1,11 +1,9 @@ -using System; using System.Collections.Generic; using System.Linq; using RimMind.Application.Common.Constants; using RimMind.Application.Common.Interfaces.Agent; using RimMind.Application.Common.Interfaces.Agent.Modes; using RimMind.Application.Common.Interfaces.Tools; -using RimMind.Application.Common.Models; using RimMind.Application.Common.Models.Context; using RimMind.Application.Common.Models.Pipeline; using RimMind.Application.Common.Models.Tools; @@ -20,10 +18,10 @@ namespace RimMind.Application.Features.Agent.Modes; public sealed class ReactiveAgentMode : IAgentMode { public AgentModeId ModeId => AgentModeId.Reactive; - public string DisplayName => "Reactive"; - public string Description => "Responds to perception events only"; - public string Id => ModeId.Value; - public string OwnerModId => RimMindOwnerConsts.CoreModId; + public string DisplayName => "Reactive"; + public string Description => "Responds to perception events only"; + public string Id => ModeId.Value; + public string OwnerModId => RimMindOwnerConsts.CoreModId; public bool IsApplicable(IAgentInfo agent) => agent.State == AgentState.Active; @@ -35,18 +33,16 @@ public bool ShouldThink(IAgentInfo agent, IReadOnlyList p public IThinkStrategy GetThinkStrategy() => SharedStrategy; - private static readonly string[] ExcludedToolPrefixes = { "planning.", "dream.", "reflect.", "trait_evolution." }; - public IReadOnlyList AllowedToolIds(IToolRegistry registry) => registry.GetDefinitionsForScope(RimMind.Application.Features.Tools.ToolScopeProjection.ColonistAgentDefaultScope) - .Where(d => !ExcludedToolPrefixes.Any(p => d.Id.StartsWith(p))) + .Where(d => d.Manifest?.RequiresProactiveMode != true) .Select(d => d.Id) .ToList(); } internal sealed class ReactiveThinkStrategy : IThinkStrategy { - private static readonly List CachedExamples = ThinkStrategyHelper.BuildDecisionExamples(); + private static readonly IReadOnlyList CachedExamples = ThinkStrategyHelper.BuildDecisionExamples(); public string ScenarioId => ScenarioIds.AgentDecision; @@ -59,7 +55,7 @@ public LlmRequestEnvelope BuildEnvelope(IAgentInfo agent, var examples = CachedExamples; return LlmRequestEnvelopeBuilder .ForScenario(ScenarioId) - .WithModId("RimMind.Agent") + .WithModId(RimMindOwnerConsts.AgentModId) .WithNpcId(agent.NpcId) .WithGameStateInfo(new GameStateInfo().AddSection("perceptions", query)) .WithSchema("...") diff --git a/Source/Application/Features/Agent/Modes/ThinkStrategyHelper.cs b/Source/Application/Features/Agent/Modes/ThinkStrategyHelper.cs index 6f9af72d..d7bf50b6 100644 --- a/Source/Application/Features/Agent/Modes/ThinkStrategyHelper.cs +++ b/Source/Application/Features/Agent/Modes/ThinkStrategyHelper.cs @@ -2,15 +2,11 @@ using System.Collections.Generic; using System.Linq; using System.Text; -using System.Text.RegularExpressions; -using RimMind.Application.Common.Interfaces.Agent.Modes; using RimMind.Application.Common.Interfaces.Tools; using RimMind.Application.Common.Models.Pipeline; using RimMind.Application.Common.Models.Tools; using RimMind.Application.Features.Json; -using RimMind.Application.Features.Tools; using RimMind.Domain.Agent.Modes; -using RimMind.Domain.Common; using RimMind.Domain.Llm; using RimMind.Domain.ValueObjects; @@ -40,8 +36,7 @@ public static string FormatPerceptions(IReadOnlyList perc sb.AppendLine(""); // Prioritize the most recent entries and highest importance so the prompt stays well within BudgetOverflowGuardrail (8000 chars) - int startIndex = System.Math.Max(0, perceptions.Count - MaxFormattedPerceptions); - int count = 0; + int startIndex = Math.Max(0, perceptions.Count - MaxFormattedPerceptions); for (int i = perceptions.Count - 1; i >= startIndex; i--) { var p = perceptions[i]; @@ -50,38 +45,19 @@ public static string FormatPerceptions(IReadOnlyList perc if (sb.Length + line.Length + 32 > MaxFormattedPerceptionChars) break; sb.AppendLine(line); - count++; } sb.AppendLine(""); return sb.ToString(); } - private static readonly TimeSpan RegexTimeout = TimeSpan.FromMilliseconds(50); - - private static readonly Regex PseudoFunctionCallRegex = new Regex( - @"\b(?[a-z_][a-z0-9_.]*)\((?[\s\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); - - private static readonly List CachedDecisionExamples = CreateDecisionExamples(); + private static readonly IReadOnlyList CachedDecisionExamples = CreateDecisionExamples().AsReadOnly(); public static bool IsQueryToolName(string? toolName, IToolRegistry? toolRegistry = null) { if (string.IsNullOrWhiteSpace(toolName)) return false; - var registry = toolRegistry ?? ToolRegistry.Current; - var handler = registry?.FindById(toolName!); + var handler = toolRegistry?.FindById(toolName!); if (handler?.Definition?.Manifest != null) { return handler.Definition.Manifest.Kind == ToolKind.Query; @@ -213,196 +189,12 @@ internal static bool IsMeaningfulActionName(string? action) internal static (string? Id, string? Name, string? ArgsJson, string? Reason) TryExtractToolCallFromContent(string? content) { - if (string.IsNullOrWhiteSpace(content)) return (null, null, null, null); - string trimmed = content!.Trim(); - - // 0. Check raw JSON tool call object: {"name": "actions_eat_and_recreation", "parameters": {...}} or {"tool": "...", "arguments": {...}} - int firstBrace = trimmed.IndexOf('{'); - if (firstBrace >= 0) - { - int lastBrace = trimmed.LastIndexOf('}'); - string jsonCandidate = lastBrace > firstBrace - ? trimmed.Substring(firstBrace, lastBrace - firstBrace + 1) - : trimmed.Substring(firstBrace); - - Newtonsoft.Json.Linq.JObject? rawObj = null; - try - { - rawObj = Newtonsoft.Json.Linq.JToken.Parse(jsonCandidate) as Newtonsoft.Json.Linq.JObject; - } - catch - { - try - { - string repaired = JsonRepairer.Repair(trimmed.Substring(firstBrace)); - rawObj = Newtonsoft.Json.Linq.JToken.Parse(repaired) as Newtonsoft.Json.Linq.JObject; - } - catch { } - } - - if (rawObj != null) - { - string? rawToolName = rawObj.Value("name") - ?? rawObj.Value("tool") - ?? (rawObj["function"] as Newtonsoft.Json.Linq.JObject)?.Value("name"); - if (!string.IsNullOrWhiteSpace(rawToolName) && IsValidFallbackToolIdentifier(rawToolName)) - { - var paramsToken = rawObj["parameters"] - ?? rawObj["arguments"] - ?? rawObj["args"] - ?? rawObj["param"] - ?? (rawObj["function"] as Newtonsoft.Json.Linq.JObject)?["arguments"]; - string? argsJson = null; - string? reason = rawObj.Value("reason"); - if (paramsToken is Newtonsoft.Json.Linq.JObject paramsObj) - { - argsJson = paramsObj.ToString(Newtonsoft.Json.Formatting.None); - reason ??= paramsObj.Value("reason"); - } - else if (paramsToken != null && paramsToken.Type == Newtonsoft.Json.Linq.JTokenType.String) - { - argsJson = paramsToken.ToString(); - if (!string.IsNullOrWhiteSpace(argsJson)) - { - try - { - if (Newtonsoft.Json.Linq.JToken.Parse(argsJson!) is Newtonsoft.Json.Linq.JObject parsedParams) - reason ??= parsedParams.Value("reason"); - } - catch { } - } - } - else - { - var copyObj = (Newtonsoft.Json.Linq.JObject)rawObj.DeepClone(); - copyObj.Remove("name"); - copyObj.Remove("tool"); - copyObj.Remove("function"); - copyObj.Remove("id"); - copyObj.Remove("type"); - if (copyObj.HasValues) - argsJson = copyObj.ToString(Newtonsoft.Json.Formatting.None); - } - - return (rawObj.Value("id"), rawToolName, argsJson ?? "{}", reason); - } - } - } - - // 1. Check pseudo-function call syntax: tool_name(key=val, ...) - // Require a structured tool identifier (containing '_' or '.') immediately followed by '(' - // so ordinary parenthetical prose like "I'm tired (reason: no sleep)" is never treated as a tool call. - Match match; - try - { - match = PseudoFunctionCallRegex.Match(trimmed); - } - catch (RegexMatchTimeoutException) - { - return (null, null, null, null); - } - - if (match.Success) - { - string fnName = match.Groups["fn"].Value; - if (!IsValidFallbackToolIdentifier(fnName)) - return (null, null, null, null); - - string inner = match.Groups["inner"].Value.Trim(); - MatchCollection keyMatches; - try - { - keyMatches = PseudoFunctionKeyRegex.Matches(inner); - } - catch (RegexMatchTimeoutException) - { - return (null, null, null, null); - } - if (keyMatches.Count > 0) - { - var jObj = new Newtonsoft.Json.Linq.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("“") && rawVal.EndsWith("”") && 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 - jObj[key] = rawVal; - } - string argsJson = jObj.ToString(Newtonsoft.Json.Formatting.None); - string? reason = jObj.Value("reason"); - return (null, fnName, argsJson, reason); - } - } - - // 2. Check commentary syntax: to=tool_name or to=functions.tool_name [optional {...}] - Match toMatch; - try - { - toMatch = ToToolCommentaryRegex.Match(trimmed); - } - catch (RegexMatchTimeoutException) - { + var parsed = LlmPayloadParser.ParsePseudoFunctionCalls(content); + if (parsed.Count == 0) return (null, null, null, null); - } - - if (toMatch.Success) - { - string fnName = toMatch.Groups["fn"].Value; - if (IsValidFallbackToolIdentifier(fnName)) - { - string afterMatch = trimmed.Substring(toMatch.Index + toMatch.Length).Trim(); - string? argsJson = "{}"; - string? reason = null; - int braceStart = afterMatch.IndexOf('{'); - int braceEnd = afterMatch.LastIndexOf('}'); - if (braceStart >= 0 && braceEnd > braceStart) - { - string candidate = afterMatch.Substring(braceStart, braceEnd - braceStart + 1); - try - { - if (Newtonsoft.Json.Linq.JToken.Parse(candidate) is Newtonsoft.Json.Linq.JObject argObj) - { - argsJson = argObj.ToString(Newtonsoft.Json.Formatting.None); - reason = argObj.Value("reason"); - } - } - catch { } - } - else if (braceStart >= 0) - { - string candidate = afterMatch.Substring(braceStart); - try - { - string repaired = JsonRepairer.Repair(candidate); - if (Newtonsoft.Json.Linq.JToken.Parse(repaired) is Newtonsoft.Json.Linq.JObject argObj) - { - argsJson = argObj.ToString(Newtonsoft.Json.Formatting.None); - reason = argObj.Value("reason"); - } - } - catch { } - } - return (null, fnName, argsJson, reason); - } - } - - return (null, null, null, null); + var first = parsed[0]; + return (first.Id, first.Name, first.ArgumentsJson, first.Reason); } private static (string? Id, string? Name, string? ArgsJson, string? Reason) TryExtractFirstToolCall(string? toolCallsJson) @@ -450,20 +242,7 @@ private static (string? Id, string? Name, string? ArgsJson, string? Reason) TryE } } - private static bool IsValidFallbackToolIdentifier(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; - } - - public static List BuildDecisionExamples() => CachedDecisionExamples; + public static IReadOnlyList BuildDecisionExamples() => CachedDecisionExamples; private static List CreateDecisionExamples() { diff --git a/Source/Application/Features/Agent/ProactiveBehaviorOrchestrator.cs b/Source/Application/Features/Agent/ProactiveBehaviorOrchestrator.cs index 1408abe4..ce07b9e3 100644 --- a/Source/Application/Features/Agent/ProactiveBehaviorOrchestrator.cs +++ b/Source/Application/Features/Agent/ProactiveBehaviorOrchestrator.cs @@ -4,7 +4,6 @@ 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; using RimMind.Application.Common.Interfaces.Agent; @@ -12,6 +11,7 @@ using RimMind.Application.Common.Interfaces.Agent.Planning; using RimMind.Application.Common.Interfaces.Agent.Reflection; using RimMind.Application.Common.Interfaces.Agent.Social; +using RimMind.Application.Common.Interfaces.Async; using RimMind.Application.Common.Interfaces.Extension; using RimMind.Domain.Agent.Social; using RimMind.Domain.Events; @@ -19,7 +19,13 @@ namespace RimMind.Application.Features.Agent { - public class ProactiveBehaviorOrchestrator : IProactiveBehaviorOrchestrator + /// + /// Orchestrates proactive agent extensions (registered extensions + /// plus optional reflection, planning, dream, and trait-evolution strategy hooks). + /// Async completions are marshaled back to the Unity main thread via mainThreadDispatch + /// before mutating Verse state or publishing to . + /// + public class ProactiveBehaviorOrchestrator { private const float TraitConfidenceThreshold = 0.7f; @@ -34,14 +40,16 @@ public class ProactiveBehaviorOrchestrator : IProactiveBehaviorOrchestrator private readonly ILogSink? _log; private readonly ICompletionFence _completionFence; private readonly IExtensionRegistry? _behaviorRegistry; + private readonly Action? _mainThreadDispatch; public ProactiveBehaviorOrchestrator( IAgentBus agentBus, int pawnId, IExtensionRegistry? behaviorRegistry, ILogSink? log = null, - ICompletionFence? completionFence = null) - : this(null, null, null, null, null, null, agentBus, pawnId, log, completionFence, behaviorRegistry) + ICompletionFence? completionFence = null, + Action? mainThreadDispatch = null) + : this(null, null, null, null, null, null, agentBus, pawnId, log, completionFence, behaviorRegistry, mainThreadDispatch) { } @@ -56,7 +64,8 @@ public ProactiveBehaviorOrchestrator( int pawnId, ILogSink? log = null, ICompletionFence? completionFence = null, - IExtensionRegistry? behaviorRegistry = null) + IExtensionRegistry? behaviorRegistry = null, + Action? mainThreadDispatch = null) { _reflectionStrategy = reflectionStrategy; _dailyPlanner = dailyPlanner; @@ -69,13 +78,15 @@ public ProactiveBehaviorOrchestrator( _log = log; _completionFence = completionFence ?? UnboundedCompletionFence.Instance; _behaviorRegistry = behaviorRegistry; + _mainThreadDispatch = mainThreadDispatch; } public void ExecuteReflection(IAgentInfo agent) { if (_reflectionStrategy?.ShouldReflect(agent) != true) return; if (_completionFence.CancellationToken.IsCancellationRequested) return; - _reflectionStrategy.ReflectAsync(agent, _completionFence.CancellationToken).ContinueWith(t => + var task = _reflectionStrategy.ReflectAsync(agent, _completionFence.CancellationToken); + ObserveCompletion(task, t => { if (!_completionFence.TryAcceptCompletion()) return; if (t.IsFaulted) @@ -85,14 +96,15 @@ public void ExecuteReflection(IAgentInfo agent) } if (t.Status == TaskStatus.RanToCompletion && t.Result.IsOk && t.Result.Value.Count > 0) _log?.Message($"[RimMind.Orchestrator] action=ReflectionCompleted npcId={agent.NpcId} insightCount={t.Result.Value.Count}"); - }, TaskScheduler.Current); + }); } public void ExecutePlanning(IAgentInfo agent) { if (_dailyPlanner?.ShouldPlan(agent) != true) return; if (_completionFence.CancellationToken.IsCancellationRequested) return; - _dailyPlanner.PlanAsync(agent, _completionFence.CancellationToken).ContinueWith(t => + var task = _dailyPlanner.PlanAsync(agent, _completionFence.CancellationToken); + ObserveCompletion(task, t => { if (!_completionFence.TryAcceptCompletion()) return; if (t.IsFaulted) @@ -102,14 +114,15 @@ public void ExecutePlanning(IAgentInfo agent) } if (t.Status == TaskStatus.RanToCompletion && t.Result.IsOk && t.Result.Value.Count > 0) _log?.Message($"[RimMind.Orchestrator] action=PlanningCompleted npcId={agent.NpcId} blockCount={t.Result.Value.Count}"); - }, TaskScheduler.Current); + }); } public void ExecuteDream(IAgentInfo agent) { if (_dreamGenerator?.ShouldDream(agent) != true) return; if (_completionFence.CancellationToken.IsCancellationRequested) return; - _dreamGenerator.GenerateDreamAsync(agent, _completionFence.CancellationToken).ContinueWith(t => + var task = _dreamGenerator.GenerateDreamAsync(agent, _completionFence.CancellationToken); + ObserveCompletion(task, t => { if (!_completionFence.TryAcceptCompletion()) return; if (t.IsFaulted) @@ -126,7 +139,7 @@ public void ExecuteDream(IAgentInfo agent) agent.NpcId, _pawnId, t.Result.Value.DreamContent, t.Result.Value.DreamType, t.Result.Value.MoodImpact)); } - }, TaskScheduler.Current); + }); } public void ExecuteTraitEvolution(IAgentInfo agent) @@ -134,12 +147,7 @@ public void ExecuteTraitEvolution(IAgentInfo agent) if (_traitEvolutionEngine?.ShouldEvolve(agent) != true) return; if (_completionFence.CancellationToken.IsCancellationRequested) return; var task = _traitEvolutionEngine.EvaluateEvolutionAsync(agent, _completionFence.CancellationToken); - if (task.IsCompleted) - { - ProcessTraitEvolutionResult(task, agent); - return; - } - task.ContinueWith(t => ProcessTraitEvolutionResult(t, agent), TaskScheduler.Current); + ObserveCompletion(task, t => ProcessTraitEvolutionResult(t, agent)); } private void ProcessTraitEvolutionResult(Task, RimMindError>> t, IAgentInfo agent) @@ -203,24 +211,14 @@ public void ExecuteRegisteredBehaviors(IAgentInfo agent, int currentTick = 0) if (task == null) continue; var behaviorId = behavior.BehaviorId; - if (task.IsCompleted) - { - if (!_completionFence.TryAcceptCompletion()) return; - if (task.IsFaulted) - { - _log?.Warning($"[RimMind.Orchestrator] action=ProactiveBehaviorFailed behaviorId={behaviorId} npcId={agent.NpcId} error={task.Exception?.InnerException?.Message}"); - } - continue; - } - - task.ContinueWith(t => + ObserveCompletion(task, t => { if (!_completionFence.TryAcceptCompletion()) return; if (t.IsFaulted) { _log?.Warning($"[RimMind.Orchestrator] action=ProactiveBehaviorFailed behaviorId={behaviorId} npcId={agent.NpcId} error={t.Exception?.InnerException?.Message}"); } - }, TaskScheduler.Current); + }); } } @@ -232,5 +230,33 @@ public void ExecuteAll(IAgentInfo agent, int currentTick = 0) ExecuteTraitEvolution(agent); ExecuteRegisteredBehaviors(agent, currentTick); } + + private void ObserveCompletion(TTask task, Action onMainThread) + where TTask : Task + { + if (task.IsCompleted) + { + onMainThread(task); + return; + } + + task.ContinueWith( + completed => + { + var typed = (TTask)completed; + if (_mainThreadDispatch != null) + { + _mainThreadDispatch(() => onMainThread(typed)); + } + else + { + // No main-thread dispatcher supplied (e.g. headless tests); run fenced callback directly. + onMainThread(typed); + } + }, + CancellationToken.None, + TaskContinuationOptions.None, + TaskScheduler.Default); + } } } diff --git a/Source/Application/Features/Agent/Psychology/DefaultPsychologyWatcher.cs b/Source/Application/Features/Agent/Psychology/DefaultPsychologyWatcher.cs deleted file mode 100644 index 5f4c2ef8..00000000 --- a/Source/Application/Features/Agent/Psychology/DefaultPsychologyWatcher.cs +++ /dev/null @@ -1,167 +0,0 @@ -using System; -using System.Collections.Generic; -using RimMind.Application.Common.Interfaces; -using RimMind.Application.Common.Interfaces.Abstractions; -using RimMind.Application.Common.Interfaces.Agent; -using RimMind.Application.Common.Interfaces.Agent.Psychology; -using RimMind.Domain.Agent.Psychology; -using RimMind.Domain.Enums; -using RimMind.Domain.Events; - -namespace RimMind.Application.Features.Agent.Psychology; - -internal sealed class DefaultPsychologyWatcher : IPsychologyWatcher -{ - private readonly ITickProvider _tickProvider; - private readonly IAgentBus _agentBus; - private readonly IPawnPsychologyDataProvider _psychologyDataProvider; - - private const int CheckIntervalTicks = 1500; - private const float MoodNormalThreshold = 0.6f; - private const float MoodLowThreshold = 0.3f; - private const float NeedHighThreshold = 0.3f; - private const float NeedCriticalThreshold = 0.1f; - private const float MentalBreakApproachFactor = 1.2f; - - private readonly Dictionary _lastCheckTick = new(); - private readonly Dictionary _lastMoodLevel = new(); - private readonly Dictionary> _lastNeedLevels = new(); - private readonly HashSet _urgentEvents = new(); - - public DefaultPsychologyWatcher( - ITickProvider tickProvider, - IAgentBus agentBus, - IPawnPsychologyDataProvider psychologyDataProvider) - { - _tickProvider = tickProvider ?? throw new ArgumentNullException(nameof(tickProvider)); - _agentBus = agentBus ?? throw new ArgumentNullException(nameof(agentBus)); - _psychologyDataProvider = psychologyDataProvider ?? throw new ArgumentNullException(nameof(psychologyDataProvider)); - } - - public void CheckAndPublish(IAgentInfo agent, int pawnId) - { - var npcId = agent.NpcId; - var currentTick = _tickProvider.TicksGame; - - if (_lastCheckTick.TryGetValue(npcId, out var lastTick) - && currentTick - lastTick < CheckIntervalTicks) - { - return; - } - _lastCheckTick[npcId] = currentTick; - - CheckMood(npcId, pawnId); - CheckNeeds(npcId, pawnId); - CheckMentalState(npcId, pawnId); - } - - public bool HasUrgentEvent(string npcId) - { - return _urgentEvents.Contains(npcId); - } - - private void CheckMood(string npcId, int pawnId) - { - var currentMood = _psychologyDataProvider.GetMoodLevel(pawnId); - - if (_lastMoodLevel.TryGetValue(npcId, out var lastMood)) - { - var previousThreshold = ClassifyMoodThreshold(lastMood); - var currentThreshold = ClassifyMoodThreshold(currentMood); - - if (previousThreshold != currentThreshold - && (previousThreshold == MoodThreshold.Normal && currentThreshold == MoodThreshold.Low - || previousThreshold == MoodThreshold.Low && currentThreshold == MoodThreshold.Critical)) - { - _agentBus.Publish(new MoodThresholdCrossedEvent( - npcId, pawnId, lastMood, currentMood, currentThreshold)); - } - } - - _lastMoodLevel[npcId] = currentMood; - } - - private void CheckNeeds(string npcId, int pawnId) - { - var currentNeeds = _psychologyDataProvider.GetNeedLevels(pawnId); - var hasCriticalNeed = false; - - foreach (var need in currentNeeds) - { - var urgency = ClassifyNeedUrgency(need.CurrentLevel); - - if (urgency == NeedUrgency.High || urgency == NeedUrgency.Critical) - { - if (_lastNeedLevels.TryGetValue(npcId, out var lastNeeds) - && lastNeeds.TryGetValue(need.NeedId, out var lastLevel)) - { - var lastUrgency = ClassifyNeedUrgency(lastLevel); - if (urgency != lastUrgency) - { - _agentBus.Publish(new NeedCriticalEvent( - npcId, pawnId, need.NeedId, need.CurrentLevel, urgency)); - } - } - else - { - _agentBus.Publish(new NeedCriticalEvent( - npcId, pawnId, need.NeedId, need.CurrentLevel, urgency)); - } - } - - if (urgency == NeedUrgency.Critical) - { - hasCriticalNeed = true; - } - } - - if (hasCriticalNeed) - { - _urgentEvents.Add(npcId); - } - else - { - _urgentEvents.Remove(npcId); - } - - var needsDict = new Dictionary(); - foreach (var need in currentNeeds) - { - needsDict[need.NeedId] = need.CurrentLevel; - } - _lastNeedLevels[npcId] = needsDict; - } - - private void CheckMentalState(string npcId, int pawnId) - { - var currentMood = _psychologyDataProvider.GetMoodLevel(pawnId); - var breakThreshold = _psychologyDataProvider.GetMentalBreakThreshold(pawnId); - var approachThreshold = breakThreshold * MentalBreakApproachFactor; - - if (currentMood <= breakThreshold) - { - _agentBus.Publish(new MentalStateWarningEvent( - npcId, pawnId, breakThreshold, currentMood, "imminent")); - _urgentEvents.Add(npcId); - } - else if (currentMood <= approachThreshold) - { - _agentBus.Publish(new MentalStateWarningEvent( - npcId, pawnId, breakThreshold, currentMood, "approaching")); - } - } - - private static MoodThreshold ClassifyMoodThreshold(float moodLevel) - { - if (moodLevel >= MoodNormalThreshold) return MoodThreshold.Normal; - if (moodLevel >= MoodLowThreshold) return MoodThreshold.Low; - return MoodThreshold.Critical; - } - - private static NeedUrgency ClassifyNeedUrgency(float level) - { - if (level < NeedCriticalThreshold) return NeedUrgency.Critical; - if (level < NeedHighThreshold) return NeedUrgency.High; - return NeedUrgency.Low; - } -} diff --git a/Source/Application/Features/Agent/Social/DefaultInformationDiffuser.cs b/Source/Application/Features/Agent/Social/DefaultInformationDiffuser.cs index b23c87be..3d12d48f 100644 --- a/Source/Application/Features/Agent/Social/DefaultInformationDiffuser.cs +++ b/Source/Application/Features/Agent/Social/DefaultInformationDiffuser.cs @@ -4,6 +4,7 @@ using RimMind.Application.Common.Interfaces.Abstractions; using RimMind.Application.Common.Interfaces.Agent; using RimMind.Application.Common.Interfaces.Agent.Social; +using RimMind.Application.Features.Tools; using RimMind.Domain.Agent.Social; using RimMind.Domain.Events; using RimMind.Domain.ValueObjects; @@ -12,8 +13,11 @@ namespace RimMind.Application.Features.Agent.Social; public sealed class DefaultInformationDiffuser : IInformationDiffuser { + private const int MaxRumorsPerNpc = 32; + private readonly IAgentBus _agentBus; private readonly ITickProvider _tickProvider; + private readonly object _syncLock = new object(); private readonly Dictionary> _knownRumors = new(); private readonly Random _random = new(); @@ -26,7 +30,12 @@ public DefaultInformationDiffuser(IAgentBus agentBus, ITickProvider tickProvider public bool ShouldDiffuse(IAgentInfo source, IAgentInfo target, RumorEntry rumor) { var probability = rumor.Importance * 0.7f * 0.5f; - return _random.NextDouble() < probability; + double sample; + lock (_syncLock) + { + sample = _random.NextDouble(); + } + return sample < probability; } public Result Diffuse(IAgentInfo source, IAgentInfo target, RumorEntry original) @@ -37,23 +46,56 @@ public Result Diffuse(IAgentInfo source, IAgentInfo ta SourceNpcId = source.NpcId, }; AddRumor(target.NpcId, diffused); + PawnIdParser.TryParse(target.NpcId, out int targetPawnId); _agentBus.Publish(new InformationDiffusionEvent( - target.NpcId, 0, diffused.RumorId, diffused.Content, + target.NpcId, targetPawnId, diffused.RumorId, diffused.Content, diffused.SourceNpcId, diffused.Importance, diffused.DistortionLevel, _tickProvider.TicksGame)); return Result.Ok(diffused); } public IReadOnlyList GetKnownRumors(string npcId) - => _knownRumors.TryGetValue(npcId, out var list) ? list : Array.Empty(); + { + lock (_syncLock) + { + return _knownRumors.TryGetValue(npcId, out var list) + ? list.ToArray() + : Array.Empty(); + } + } public void AddRumor(string npcId, RumorEntry rumor) { - if (!_knownRumors.TryGetValue(npcId, out var list)) + if (string.IsNullOrEmpty(npcId) || rumor == null) return; + lock (_syncLock) + { + if (!_knownRumors.TryGetValue(npcId, out var list)) + { + list = new List(); + _knownRumors[npcId] = list; + } + list.Add(rumor); + if (list.Count > MaxRumorsPerNpc) + { + list.RemoveRange(0, list.Count - MaxRumorsPerNpc); + } + } + } + + public void ClearNpc(string npcId) + { + if (string.IsNullOrEmpty(npcId)) return; + lock (_syncLock) + { + _knownRumors.Remove(npcId); + } + } + + public void Clear() + { + lock (_syncLock) { - list = new List(); - _knownRumors[npcId] = list; + _knownRumors.Clear(); } - list.Add(rumor); } } diff --git a/Source/Application/Features/Agent/ThinkContextEnricher.cs b/Source/Application/Features/Agent/ThinkContextEnricher.cs index 0996f0a1..d976ef5c 100644 --- a/Source/Application/Features/Agent/ThinkContextEnricher.cs +++ b/Source/Application/Features/Agent/ThinkContextEnricher.cs @@ -15,7 +15,7 @@ namespace RimMind.Application.Features.Agent { - public sealed class ThinkContextEnricher : IEnvelopeEnricher + public sealed class ThinkContextEnricher { private readonly InnerVoiceHandler? _innerVoiceHandler; private readonly IPsychologyWatcher? _psychologyWatcher; diff --git a/Source/Application/Features/AgentBus/AgentBusImpl.cs b/Source/Application/Features/AgentBus/AgentBusImpl.cs index 4cadd7b7..7cedc984 100644 --- a/Source/Application/Features/AgentBus/AgentBusImpl.cs +++ b/Source/Application/Features/AgentBus/AgentBusImpl.cs @@ -21,7 +21,6 @@ private readonly ConcurrentDictionary> _handlers private readonly ConcurrentQueue _backgroundQueue = new ConcurrentQueue(); private ILogSink? _log; - private readonly IThreadChecker? _threadChecker; private readonly Action _dispatchAction; private IPipeline? _pipeline; private int _handlerIdCounter; @@ -72,7 +71,6 @@ private readonly ConcurrentDictionary _warnedUnknownNames public AgentBusImpl(ILogSink? log = null, IThreadChecker? threadChecker = null) { _log = log; - _threadChecker = threadChecker; _dispatchAction = DispatchToHandlers; } @@ -92,9 +90,13 @@ internal void DispatchToHandlers(AgentBusEvent evt) { if (evt == null) return; BindPendingSubscriptions(); - if (!_handlers.TryGetValue(evt.GetType(), out var list) || list.Count == 0) return; + if (!_handlers.TryGetValue(evt.GetType(), out var list)) return; HandlerEntry[] snapshot; - lock (list) { snapshot = list.ToArray(); } + lock (list) + { + if (list.Count == 0) return; + snapshot = list.ToArray(); + } foreach (var entry in snapshot) { try { entry.Action(evt); } @@ -214,18 +216,6 @@ public void Unsubscribe(string key) } } - /// - /// Obsolete: action-based unsubscribe is unreliable because subscriptions wrap the original handler in a lambda. - /// Use with the key returned from . - /// - [Obsolete("Use Unsubscribe(string key) instead. Action-based unsubscribe is unreliable due to lambda wrapping.")] - public void Unsubscribe(Action handler) where T : AgentBusEvent - { - throw new NotSupportedException( - "Unsubscribe by Action is unreliable due to lambda wrapping. " + - "Use Unsubscribe(string key) with the key returned from Subscribe(Action)."); - } - [ThreadAffinity(ThreadAffinityKind.MainOnly)] public void Publish(T evt) where T : AgentBusEvent { @@ -245,7 +235,11 @@ public void PublishFromBackground(T evt) where T : AgentBusEvent { if (evt == null) return; BindPendingSubscriptions(); - if (!_handlers.TryGetValue(evt.GetType(), out var list) || list.Count == 0) return; + if (!_handlers.TryGetValue(evt.GetType(), out var list)) return; + lock (list) + { + if (list.Count == 0) return; + } _backgroundQueue.Enqueue(new DeferredPublish(evt.GetType(), evt)); } diff --git a/Source/Application/Features/Bridges/ReflectionAccessor.cs b/Source/Application/Features/Bridges/ReflectionAccessor.cs index e281fafd..4e5ff02f 100644 --- a/Source/Application/Features/Bridges/ReflectionAccessor.cs +++ b/Source/Application/Features/Bridges/ReflectionAccessor.cs @@ -176,19 +176,19 @@ public void SetCachedType(string typeName, Type? type) { if (type == null) { - _warnCallback?.Invoke(FormatMessage("GetStaticPropertyValue: type is null.")); + WarnOnce("static-prop:null-type", FormatMessage("GetStaticPropertyValue: type is null.")); return null; } try { - var prop = GetCachedProperty(type, propertyName, BindingFlags.Public | BindingFlags.Static); + var prop = GetCachedProperty(type, propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); if (prop == null) return null; return prop.GetValue(null); } catch (Exception ex) { - _warnCallback?.Invoke(FormatMessage($"GetStaticPropertyValue({type.Name}.{propertyName}) failed: {ex.Message}")); + WarnOnce($"static-prop-ex:{type.FullName}:{propertyName}", FormatMessage($"GetStaticPropertyValue({type.Name}.{propertyName}) failed: {ex.Message}")); return null; } } @@ -200,7 +200,7 @@ public void SetCachedType(string typeName, Type? type) { if (instance == null) { - _warnCallback?.Invoke(FormatMessage("GetInstanceFieldValue: instance is null.")); + WarnOnce($"inst-field:null-instance:{fieldName}", FormatMessage("GetInstanceFieldValue: instance is null.")); return null; } @@ -212,27 +212,61 @@ public void SetCachedType(string typeName, Type? type) } catch (Exception ex) { - _warnCallback?.Invoke(FormatMessage($"GetInstanceFieldValue({instance.GetType().Name}.{fieldName}) failed: {ex.Message}")); + WarnOnce($"inst-field-ex:{instance.GetType().FullName}:{fieldName}", FormatMessage($"GetInstanceFieldValue({instance.GetType().Name}.{fieldName}) failed: {ex.Message}")); return null; } } - public object? TryGetSingletonInstance(Type? managerType, string instancePropertyName = "Instance") + /// + /// Resolves a singleton instance from a static property or static field (public or non-public). + /// Missing members and invocation errors are deduplicated via . + /// + public object? TryGetSingletonInstance(Type? managerType, string instanceMemberName = "Instance") { if (managerType == null) { - _warnCallback?.Invoke(FormatMessage("TryGetManagerInstance: managerType is null.")); + WarnOnce("singleton:null-type", FormatMessage("TryGetSingletonInstance: managerType is null.")); return null; } - var instance = GetStaticPropertyValue(managerType, instancePropertyName); - if (instance == null) + const BindingFlags staticFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static; + try { - _warnCallback?.Invoke(FormatMessage($"TryGetManagerInstance: instance is null on {managerType.Name}.")); + var prop = GetCachedProperty(managerType, instanceMemberName, staticFlags, warnIfMissing: false); + if (prop != null) + { + var val = prop.GetValue(null); + if (val != null) return val; + } + else + { + var field = GetCachedField(managerType, instanceMemberName, staticFlags, warnIfMissing: false); + if (field != null) + { + var val = field.GetValue(null); + if (val != null) return val; + } + else + { + WarnOnce( + $"singleton-missing:{managerType.FullName}:{instanceMemberName}", + FormatMessage($"TryGetSingletonInstance: static property/field '{instanceMemberName}' not found on {managerType.Name}.")); + return null; + } + } + } + catch (Exception ex) + { + WarnOnce( + $"singleton-ex:{managerType.FullName}:{instanceMemberName}", + FormatMessage($"TryGetSingletonInstance({managerType.Name}.{instanceMemberName}) failed: {ex.Message}")); return null; } - return instance; + WarnOnce( + $"singleton-null:{managerType.FullName}:{instanceMemberName}", + FormatMessage($"TryGetSingletonInstance: instance is null on {managerType.Name}.")); + return null; } public void ResetForTesting() diff --git a/Source/Application/Features/Context/AIResponseAnalyzer.cs b/Source/Application/Features/Context/AIResponseAnalyzer.cs index a3194015..0adf03e9 100644 --- a/Source/Application/Features/Context/AIResponseAnalyzer.cs +++ b/Source/Application/Features/Context/AIResponseAnalyzer.cs @@ -6,9 +6,9 @@ namespace RimMind.Application.Features.Context { /// - /// Heuristic analyzer: checks if AI response content contains substrings - /// from context messages, indicating the AI actually used that context. - /// Returns the LayerTag values of messages whose content was referenced. + /// Heuristic analyzer: checks if AI response content references text from + /// context entries, returning the context key names (matching + /// ) that appear to have been used. /// public sealed class AIResponseAnalyzer { diff --git a/Source/Application/Features/Context/BudgetScheduler.cs b/Source/Application/Features/Context/BudgetScheduler.cs index 7b09ad67..48a7df81 100644 --- a/Source/Application/Features/Context/BudgetScheduler.cs +++ b/Source/Application/Features/Context/BudgetScheduler.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; -using System.Linq; using RimMind.Application.Common.Interfaces.Abstractions; using RimMind.Application.Common.Interfaces.Context; using RimMind.Application.Common.Models; @@ -228,11 +227,6 @@ private static float CosineSimilarity(float[] a, float[] b) return denom > 0 ? dot / denom : 0f; } - private static ContextLayer ChooseLayer(ContextLayer declared, float cumulative) - { - return declared; - } - private static void AddToAllocation(BudgetAllocation alloc, ContextLayer layer, KeyMeta key) { switch (layer) diff --git a/Source/Application/Features/Context/ContextCacheManager.cs b/Source/Application/Features/Context/ContextCacheManager.cs index 0e3f8797..3a70cec0 100644 --- a/Source/Application/Features/Context/ContextCacheManager.cs +++ b/Source/Application/Features/Context/ContextCacheManager.cs @@ -25,13 +25,11 @@ private readonly ConcurrentDictionary> _l1KeyVer = new ConcurrentDictionary>(); private readonly ConcurrentDictionary _pendingCacheEvents = new ConcurrentDictionary(); - private readonly IEmbedCache _embedCache; - private readonly ILogSink? _log; + private readonly IEmbedCache? _embedCache; public ContextCacheManager(ILogSink? log = null, IEmbedCache? embedCache = null) { - _log = log; - _embedCache = embedCache!; + _embedCache = embedCache; } public IReadOnlyDictionary L0Cache => _l0Cache; @@ -39,7 +37,7 @@ public ContextCacheManager(ILogSink? log = null, IEmbedCache? embedCache = null) public IReadOnlyDictionary L1Version => _l1Version; public IReadOnlyDictionary> L1KeyVersions => _l1KeyVersions; public IReadOnlyDictionary PendingCacheEvents => _pendingCacheEvents; - public IEmbedCache EmbedCache => _embedCache; + public IEmbedCache EmbedCache => _embedCache!; public void TouchCache(string cacheKey) { /* Intentionally empty: reserved for future LRU cache eviction */ } public void RemoveL0CacheForNpc(string npcId) @@ -51,8 +49,19 @@ public void RemoveL0CacheForNpc(string npcId) } public void InvalidateLayer(string npcId, ContextLayer layer) { - _l1BlockCache.TryRemove(npcId, out _); - _l1Version.AddOrUpdate(npcId, 0, (_, __) => 0); + if (layer == ContextLayer.L0_Static) + { + RemoveL0CacheForNpc(npcId); + return; + } + if (layer == ContextLayer.L1_Baseline) + { + lock (_l1BlockCacheLock) + { + _l1BlockCache.TryRemove(npcId, out _); + } + _l1Version.AddOrUpdate(npcId, 0, (_, __) => 0); + } } public void InvalidateKey(string npcId, string key) { @@ -65,18 +74,28 @@ public void InvalidateKey(string npcId, string key) public void InvalidateNpc(string npcId) { RemoveL0CacheForNpc(npcId); - _l1BlockCache.TryRemove(npcId, out _); + lock (_l1BlockCacheLock) + { + _l1BlockCache.TryRemove(npcId, out _); + } _l1Version.TryRemove(npcId, out _); _l1KeyVersions.TryRemove(npcId, out _); } public void Reset() { - _l0Cache.Clear(); _l1BlockCache.Clear(); _l1Version.Clear(); - _l1KeyVersions.Clear(); _pendingCacheEvents.Clear(); _embedCache.Clear(); + _l0Cache.Clear(); + lock (_l1BlockCacheLock) + { + _l1BlockCache.Clear(); + } + _l1Version.Clear(); + _l1KeyVersions.Clear(); + _pendingCacheEvents.Clear(); + _embedCache?.Clear(); } public int GetL0CacheCount() => _l0Cache.Count; public int GetL1BlockCacheCount() => _l1BlockCache.Count; - public int GetEmbedCacheCount() => _embedCache.Count; + public int GetEmbedCacheCount() => _embedCache?.Count ?? 0; public void ClearPendingCacheEvents() => _pendingCacheEvents.Clear(); public bool TryGetL0CacheItem(string key, out ChatMessage msg) => _l0Cache.TryGetValue(key, out msg!); diff --git a/Source/Application/Features/Context/ContextDiffTracker.cs b/Source/Application/Features/Context/ContextDiffTracker.cs index fe9af4ce..579902d7 100644 --- a/Source/Application/Features/Context/ContextDiffTracker.cs +++ b/Source/Application/Features/Context/ContextDiffTracker.cs @@ -11,11 +11,9 @@ public sealed class ContextDiffTracker : IContextDiffTracker private readonly DiffComputer _computer = new(); private readonly DiffRecorder _recorder; private readonly DiffMerger _merger = new(); - private readonly ILogSink? _log; public ContextDiffTracker(ILogSink? log = null) { - _log = log; _recorder = new DiffRecorder(); } @@ -31,7 +29,7 @@ public void AddDiff(string npcId, string key, string oldValue, string newValue, public void MergeExpiredDiffs(string npcId, IContextCacheManager cacheManager) { - if (_recorder.TryGetDiffStore(npcId, out var diffs)) + if (_recorder.TryTakeDiffStore(npcId, out var diffs)) _merger.MergeExpired(npcId, diffs, cacheManager); } @@ -40,24 +38,36 @@ public void UpdateKeyValues(string npcId, List keys, object? pawn, { if (keys == null || keys.Count == 0) return; - // Get current values from L1 block cache + // Get current values from L1 block cache and map each key to its declared layer var newValues = new Dictionary(); + var keyLayers = new Dictionary(); if (cacheManager.TryGetL1BlockCache(npcId, out var cachedBlocks)) { foreach (var key in keys) { + keyLayers[key.Key] = key.Layer; if (cachedBlocks.TryGetValue(key.Key, out var value)) newValues[key.Key] = value; } } + else + { + foreach (var key in keys) + keyLayers[key.Key] = key.Layer; + } // Get old values from recorder if (!_recorder.TryGetKeyLastValues(npcId, out var oldValues)) oldValues = new Dictionary(); - // Compute diffs - var layer = keys[0].Layer; - var diffs = _computer.Compute(oldValues, newValues, layer); + // Compute diffs and preserve each key's declared ContextLayer + var fallbackLayer = keys[0].Layer; + var diffs = _computer.Compute(oldValues, newValues, fallbackLayer); + for (int i = 0; i < diffs.Count; i++) + { + if (keyLayers.TryGetValue(diffs[i].Key, out var keyLayer)) + diffs[i].Layer = keyLayer; + } // Record diffs and update last values if (diffs.Count > 0) diff --git a/Source/Application/Features/Context/Diff/DiffRecorder.cs b/Source/Application/Features/Context/Diff/DiffRecorder.cs index e85b1c2d..a6b1c129 100644 --- a/Source/Application/Features/Context/Diff/DiffRecorder.cs +++ b/Source/Application/Features/Context/Diff/DiffRecorder.cs @@ -47,12 +47,50 @@ public void SetKeyLastValues(string npcId, Dictionary values) public bool TryGetDiffStore(string npcId, out List diffs) { - return _diffStore.TryGetValue(npcId, out diffs!); + if (_diffStore.TryGetValue(npcId, out var list)) + { + lock (list) + { + diffs = new List(list); + } + return true; + } + diffs = null!; + return false; + } + + public bool TryTakeDiffStore(string npcId, out List diffs) + { + if (_diffStore.TryGetValue(npcId, out var list)) + { + lock (list) + { + if (list.Count == 0) + { + diffs = new List(); + return false; + } + diffs = new List(list); + list.Clear(); + } + return true; + } + diffs = null!; + return false; } public bool TryGetKeyLastValues(string npcId, out Dictionary values) { - return _keyLastValues.TryGetValue(npcId, out values!); + if (_keyLastValues.TryGetValue(npcId, out var dict)) + { + lock (dict) + { + values = new Dictionary(dict); + } + return true; + } + values = null!; + return false; } public void ClearNpcDiffs(string npcId) => _diffStore.TryRemove(npcId, out _); diff --git a/Source/Application/Features/Context/ProviderCache.cs b/Source/Application/Features/Context/ProviderCache.cs index 1dcff1f5..a315782b 100644 --- a/Source/Application/Features/Context/ProviderCache.cs +++ b/Source/Application/Features/Context/ProviderCache.cs @@ -130,7 +130,7 @@ internal async Task GetOrComputeWithOutcomeAsync( // StalenessTicks > 0 means "cache for this many ticks" — return cached if within window. if (cacheable && _entries.TryGetValue(cacheKey, out var entry)) { - if (currentTicks - entry.ComputedAtTicks < def.StalenessTicks) + if (currentTicks >= entry.ComputedAtTicks && currentTicks - entry.ComputedAtTicks < def.StalenessTicks) { return ProviderCacheResult.Succeeded(entry.Value); } @@ -197,12 +197,14 @@ private void MaybeSweepExpired(int currentTicks) { if (currentTicks <= 0) return; int last = _lastSweepTicks; - if (currentTicks - last < SweepIntervalTicks) return; + if (currentTicks >= last && currentTicks - last < SweepIntervalTicks) return; if (Interlocked.CompareExchange(ref _lastSweepTicks, currentTicks, last) != last) return; foreach (var kvp in _entries) { - if (kvp.Value.StalenessTicks > 0 && currentTicks - kvp.Value.ComputedAtTicks >= kvp.Value.StalenessTicks) + if (kvp.Value.StalenessTicks > 0 + && (currentTicks < kvp.Value.ComputedAtTicks + || currentTicks - kvp.Value.ComputedAtTicks >= kvp.Value.StalenessTicks)) { _entries.TryRemove(kvp.Key, out _); } @@ -219,6 +221,7 @@ private static bool IsCacheableScope(CacheScope scope, ProviderContext ctx) public void Clear() { _entries.Clear(); + Interlocked.Exchange(ref _lastSweepTicks, 0); lock (_subscriptionSync) { if (_bus == null) diff --git a/Source/Application/Features/Context/RelevanceLearner.cs b/Source/Application/Features/Context/RelevanceLearner.cs index ce642069..5f536b46 100644 --- a/Source/Application/Features/Context/RelevanceLearner.cs +++ b/Source/Application/Features/Context/RelevanceLearner.cs @@ -17,6 +17,7 @@ public sealed class RelevanceLearner : IRelevanceLearner private int _lastCleanupTick = 0; private const int CleanupIntervalTicks = 600; // ~10 seconds private const int TraceTimeoutTicks = 36000; // ~10 minutes + private const int MaxPendingTraces = 1024; public RelevanceLearner(ITickProvider? tickProvider = null) { @@ -27,6 +28,10 @@ public void RecordInclusion(string traceId, string scenario, IReadOnlyList= MaxPendingTraces) + { + _pendingTraces.Clear(); + } var nowTick = _tickProvider?.TicksGame ?? 0; _pendingTraces[traceId] = (scenario, includedKeys, nowTick); } @@ -65,11 +70,11 @@ private void MaybeCleanup() { var now = _tickProvider?.TicksGame ?? 0; if (now == 0) return; // no tick provider, can't determine age - if (now - _lastCleanupTick < CleanupIntervalTicks) return; + if (now >= _lastCleanupTick && now - _lastCleanupTick < CleanupIntervalTicks) return; _lastCleanupTick = now; var expired = _pendingTraces - .Where(kvp => now - kvp.Value.TimestampTick > TraceTimeoutTicks) + .Where(kvp => now < kvp.Value.TimestampTick || now - kvp.Value.TimestampTick > TraceTimeoutTicks) .Select(kvp => kvp.Key) .ToList(); foreach (var id in expired) diff --git a/Source/Application/Features/Context/ScenarioRegistry.cs b/Source/Application/Features/Context/ScenarioRegistry.cs index ed5eb5cd..83a9de7c 100644 --- a/Source/Application/Features/Context/ScenarioRegistry.cs +++ b/Source/Application/Features/Context/ScenarioRegistry.cs @@ -2,8 +2,8 @@ using System.Collections.Concurrent; using System.Collections.Generic; using RimMind.Application.Common.Interfaces.Abstractions; -using RimMind.Application.Common.Interfaces.Internal; using RimMind.Application.Common.Models.Context; +using RimMind.Domain.Llm; namespace RimMind.Application.Features.Context { @@ -26,6 +26,8 @@ public sealed class ScenarioDescriptor public string[] DefaultExcludeKeys { get; init; } = new string[0]; public IReadOnlyDictionary? RelevanceWeights { get; init; } public string? OwnerModId { get; init; } + public bool IsDecisionScenario { get; init; } + public ToolCallDispatchMode? DefaultToolDispatchMode { get; init; } } public class ScenarioMeta @@ -39,6 +41,8 @@ public class ScenarioMeta public string[] DefaultExcludeKeys = new string[0]; public IReadOnlyDictionary? RelevanceWeights; public string? OwnerModId; + public bool IsDecisionScenario; + public ToolCallDispatchMode? DefaultToolDispatchMode; internal bool IsCoreFallback; } @@ -143,6 +147,8 @@ private static void RegisterInternal(ScenarioDescriptor descriptor, ILogSink? lo DefaultExcludeKeys = descriptor.DefaultExcludeKeys ?? new string[0], RelevanceWeights = copiedWeights, OwnerModId = descriptor.OwnerModId, + IsDecisionScenario = descriptor.IsDecisionScenario, + DefaultToolDispatchMode = descriptor.DefaultToolDispatchMode, IsCoreFallback = isCoreFallback }; } @@ -227,41 +233,59 @@ public static List GetAll() return new List(_scenarios.Values); } + public static bool IsDecisionScenario(string? scenarioId) + { + if (string.IsNullOrWhiteSpace(scenarioId)) + return false; + var meta = Get(scenarioId!); + if (meta != null) + return meta.IsDecisionScenario || ScenarioIds.IsDecisionScenario(scenarioId); + return ScenarioIds.IsDecisionScenario(scenarioId); + } + + public static ToolCallDispatchMode? GetDefaultToolDispatchMode(string? scenarioId) + { + if (string.IsNullOrWhiteSpace(scenarioId)) + return null; + return Get(scenarioId!)?.DefaultToolDispatchMode; + } + public static void RegisterCoreScenarios(ITranslationService? translationService = null, ILogSink? logSink = null) { if (_coreRegistered) return; _coreRegistered = true; - RegisterCoreFallback(ScenarioIds.Dialogue, 10, Translate(translationService, "RimMind.Application.Scenario.Dialogue"), + RegisterCoreFallback(ScenarioIds.Dialogue, 10, Translate(translationService, "RimMind.Application.Scenario.Dialogue", "Dialogue"), defaultBudget: 0.6f, l4Mode: L4Mode.BudgetControlled, defaultExcludeKeys: new[] { "combat_status", "task_progress" }, logSink: logSink); - RegisterCoreFallback(ScenarioIds.CrisisDialogue, 8, Translate(translationService, "RimMind.Application.Scenario.CrisisDialogue"), + RegisterCoreFallback(ScenarioIds.CrisisDialogue, 8, Translate(translationService, "RimMind.Application.Scenario.CrisisDialogue", "Crisis Dialogue"), defaultBudget: 0.7f, l4Mode: L4Mode.BudgetControlled, defaultExcludeKeys: new[] { "task_progress" }, logSink: logSink); - RegisterCoreFallback(ScenarioIds.Decision, 0, Translate(translationService, "RimMind.Application.Scenario.Decision"), + RegisterCoreFallback(ScenarioIds.Decision, 0, Translate(translationService, "RimMind.Application.Scenario.Decision", "Decision"), defaultBudget: 0.5f, l4Mode: L4Mode.None, - defaultExcludeKeys: new string[0], logSink: logSink); - RegisterCoreFallback(ScenarioIds.AgentDecision, 0, Translate(translationService, "RimMind.Application.Scenario.Decision"), + defaultExcludeKeys: new string[0], logSink: logSink, isDecisionScenario: true); + RegisterCoreFallback(ScenarioIds.AgentDecision, 0, Translate(translationService, "RimMind.Application.Scenario.Decision", "Decision"), defaultBudget: 0.55f, l4Mode: L4Mode.None, - defaultExcludeKeys: new string[0], logSink: logSink); - RegisterCoreFallback(ScenarioIds.AdvisorDecision, 0, Translate(translationService, "RimMind.Application.Scenario.Decision"), + defaultExcludeKeys: new string[0], logSink: logSink, isDecisionScenario: true); + RegisterCoreFallback(ScenarioIds.AdvisorDecision, 0, Translate(translationService, "RimMind.Application.Scenario.Decision", "Decision"), defaultBudget: 0.6f, l4Mode: L4Mode.None, - defaultExcludeKeys: new string[0], logSink: logSink); - RegisterCoreFallback(ScenarioIds.Personality, 3, Translate(translationService, "RimMind.Application.Scenario.Personality"), + defaultExcludeKeys: new string[0], logSink: logSink, isDecisionScenario: true); + RegisterCoreFallback(ScenarioIds.Personality, 3, Translate(translationService, "RimMind.Application.Scenario.Personality", "Personality"), defaultBudget: 0.4f, l4Mode: L4Mode.MemoryOnly, defaultExcludeKeys: new[] { "combat_status" }, logSink: logSink); - RegisterCoreFallback(ScenarioIds.Storyteller, 8, Translate(translationService, "RimMind.Application.Scenario.Storyteller"), + RegisterCoreFallback(ScenarioIds.Storyteller, 8, Translate(translationService, "RimMind.Application.Scenario.Storyteller", "Storyteller"), defaultBudget: 0.7f, l4Mode: L4Mode.NarrativeMemory, defaultExcludeKeys: new[] { "npc_identity", "pawn_base_info", "fixed_relations", "ideology", "skills_summary", "health", "mood", "current_job", "combat_status", "target_info", "task_progress", "npc_commands" }, logSink: logSink); - RegisterCoreFallback(ScenarioIds.Memory, 0, Translate(translationService, "RimMind.Application.Scenario.Memory"), + RegisterCoreFallback(ScenarioIds.Memory, 0, Translate(translationService, "RimMind.Application.Scenario.Memory", "Memory"), defaultBudget: 0.4f, l4Mode: L4Mode.None, defaultExcludeKeys: new[] { "combat_status", "current_job", "mood", "task_progress", "npc_commands", "target_info" }, logSink: logSink); } private static void RegisterCoreFallback(string scenarioId, int defaultBaseRounds, string description, - float defaultBudget, L4Mode l4Mode, string[] defaultExcludeKeys, ILogSink? logSink) + float defaultBudget, L4Mode l4Mode, string[] defaultExcludeKeys, ILogSink? logSink, + bool isDecisionScenario = false) { RegisterInternal( new ScenarioDescriptor @@ -271,15 +295,20 @@ private static void RegisterCoreFallback(string scenarioId, int defaultBaseRound Description = description, DefaultBudget = defaultBudget, L4Mode = l4Mode, - DefaultExcludeKeys = defaultExcludeKeys + DefaultExcludeKeys = defaultExcludeKeys, + IsDecisionScenario = isDecisionScenario }, logSink, isCoreFallback: true); } - private static string Translate(ITranslationService? translationService, string key) + private static string Translate(ITranslationService? translationService, string key, string fallback) { - return translationService?.Translate(key) ?? key; + if (translationService == null) + return key; + return translationService.CanTranslate(key) + ? translationService.Translate(key) + : fallback; } public static int GetBaseRounds(string scenarioId) diff --git a/Source/Application/Features/Context/SchemaRegistry.cs b/Source/Application/Features/Context/SchemaRegistry.cs index fa0b5afe..2b439d9e 100644 --- a/Source/Application/Features/Context/SchemaRegistry.cs +++ b/Source/Application/Features/Context/SchemaRegistry.cs @@ -1,7 +1,6 @@ using System.Collections.Concurrent; using System.Collections.Generic; using RimMind.Application.Common.Interfaces.Abstractions; -using RimMind.Domain.ValueObjects; namespace RimMind.Application.Features.Context { @@ -9,17 +8,12 @@ public sealed class SchemaRegistry { private readonly ConcurrentDictionary _schemas = new ConcurrentDictionary(); - private readonly ILogSink? _log; - public SchemaRegistry(ILogSink? log = null) { _log = log; } + public SchemaRegistry(ILogSink? log = null) { } public void Register(string key, string schema) => _schemas[key] = schema; public string? Find(string key) => _schemas.TryGetValue(key, out var s) ? s : null; public IReadOnlyDictionary All => _schemas; public void Reset() => _schemas.Clear(); - - public string PersonalityOutput => Find("PersonalityOutput") ?? ""; - public string IncidentOutput => Find("IncidentOutput") ?? ""; - public string DarkMemoryOutput => Find("DarkMemoryOutput") ?? ""; } } diff --git a/Source/Application/Features/Context/ThreatClassifier.cs b/Source/Application/Features/Context/ThreatClassifier.cs index c64e41df..8322c2be 100644 --- a/Source/Application/Features/Context/ThreatClassifier.cs +++ b/Source/Application/Features/Context/ThreatClassifier.cs @@ -1,5 +1,3 @@ -using System; - namespace RimMind.Application.Features.Context { public static class ThreatClassifier diff --git a/Source/Application/Features/Flywheel/FlywheelBuiltinTuner.cs b/Source/Application/Features/Flywheel/FlywheelBuiltinTuner.cs index 93855754..bbad24a6 100644 --- a/Source/Application/Features/Flywheel/FlywheelBuiltinTuner.cs +++ b/Source/Application/Features/Flywheel/FlywheelBuiltinTuner.cs @@ -1,4 +1,3 @@ -using System; using RimMind.Application.Common.Constants; using RimMind.Application.Common.Interfaces.Extension; diff --git a/Source/Application/Features/Flywheel/FlywheelRuleEngine.cs b/Source/Application/Features/Flywheel/FlywheelRuleEngine.cs index afbafb07..9f06e753 100644 --- a/Source/Application/Features/Flywheel/FlywheelRuleEngine.cs +++ b/Source/Application/Features/Flywheel/FlywheelRuleEngine.cs @@ -3,7 +3,6 @@ using RimMind.Application.Common.Interfaces.Abstractions; using RimMind.Application.Common.Interfaces.Flywheel; using RimMind.Application.Common.Models.Flywheel; -using RimMind.Application.Common.Models.Context; using RimMind.Application.Common.Models; namespace RimMind.Application.Features.Flywheel @@ -26,13 +25,24 @@ public void Analyze(List records) _log?.Message($"Analyzing {records.Count} telemetry records"); float totalTokens = 0f; + int tokenSampleCount = 0; foreach (var record in records) { - totalTokens += record.Value; + if (record == null) continue; + if (string.Equals(record.Metric, "unified_tokens_used", StringComparison.OrdinalIgnoreCase) + || string.Equals(record.Metric, "tokens_used", StringComparison.OrdinalIgnoreCase)) + { + totalTokens += record.Value; + tokenSampleCount++; + } } - float avgTokens = totalTokens / records.Count; + if (tokenSampleCount == 0) return; + float budget = _store.Get("ContextBudget"); + if (budget <= 0f) return; + + float avgTokens = totalTokens / tokenSampleCount; float ratio = avgTokens / (budget * RimMindDefaults.MaxTokens); if (ratio > 0.9f) @@ -50,9 +60,13 @@ public List Evaluate(Dictionary metrics) var recommendations = new List(); if (metrics == null) return recommendations; - if (metrics.TryGetValue("avg_tokens_used", out var avgTokens) && avgTokens > 0) + bool hasTokens = metrics.TryGetValue("unified_tokens_used_avg", out var avgTokens) + || metrics.TryGetValue("avg_tokens_used", out avgTokens); + if (hasTokens && avgTokens > 0f) { float budget = _store.Get("ContextBudget"); + if (budget <= 0f) return recommendations; + float ratio = avgTokens / (budget * RimMindDefaults.MaxTokens); if (ratio > 0.9f) { diff --git a/Source/Application/Features/Flywheel/FlywheelTelemetryCollector.cs b/Source/Application/Features/Flywheel/FlywheelTelemetryCollector.cs index 8bac51eb..88869d7a 100644 --- a/Source/Application/Features/Flywheel/FlywheelTelemetryCollector.cs +++ b/Source/Application/Features/Flywheel/FlywheelTelemetryCollector.cs @@ -12,10 +12,9 @@ public sealed class FlywheelTelemetryCollector : ITelemetryCollector, IDisposabl { private readonly ConcurrentQueue _records = new ConcurrentQueue(); - private readonly ILogSink? _log; private const int MaxRecords = RimMindDefaults.TelemetryMaxRecords; - public FlywheelTelemetryCollector(ILogSink? log = null) { _log = log; } + public FlywheelTelemetryCollector(ILogSink? log = null) { } public void Record(string metric, float value, Dictionary? tags = null) { @@ -33,11 +32,13 @@ public void Record(string metric, float value, Dictionary? tags public List GetRecent(int count = RimMindDefaults.TelemetryRecordLimit) { - var result = new List(); - foreach (var r in _records) + if (count <= 0) return new List(); + var snapshot = _records.ToArray(); + int start = Math.Max(0, snapshot.Length - count); + var result = new List(snapshot.Length - start); + for (int i = start; i < snapshot.Length; i++) { - result.Add(r); - if (result.Count >= count) break; + result.Add(snapshot[i]); } return result; } diff --git a/Source/Application/Features/Json/JsonExtractorUtils.cs b/Source/Application/Features/Json/JsonExtractorUtils.cs index f44c9513..15a2d2a4 100644 --- a/Source/Application/Features/Json/JsonExtractorUtils.cs +++ b/Source/Application/Features/Json/JsonExtractorUtils.cs @@ -1,4 +1,3 @@ -using System; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; @@ -64,19 +63,28 @@ public static bool TryDeserialize(string json, out T? result) where T : class } } - public static string? SafeGetString(JObject obj, string key) + public static string? SafeGetString(JObject? obj, string key) { - return obj.TryGetValue(key, out var token) ? token.Value() : null; + if (obj == null || !obj.TryGetValue(key, out var token) || token == null || token.Type == JTokenType.Null || token.Type == JTokenType.Undefined) + return null; + try { return token.Type == JTokenType.String ? token.Value() : token.ToString(); } + catch { return null; } } - public static int SafeGetInt(JObject obj, string key, int defaultValue = 0) + public static int SafeGetInt(JObject? obj, string key, int defaultValue = 0) { - return obj.TryGetValue(key, out var token) ? token.Value() : defaultValue; + if (obj == null || !obj.TryGetValue(key, out var token) || token == null || token.Type == JTokenType.Null || token.Type == JTokenType.Undefined) + return defaultValue; + try { return token.Value(); } + catch { return defaultValue; } } - public static bool SafeGetBool(JObject obj, string key, bool defaultValue = false) + public static bool SafeGetBool(JObject? obj, string key, bool defaultValue = false) { - return obj.TryGetValue(key, out var token) ? token.Value() : defaultValue; + if (obj == null || !obj.TryGetValue(key, out var token) || token == null || token.Type == JTokenType.Null || token.Type == JTokenType.Undefined) + return defaultValue; + try { return token.Value(); } + catch { return defaultValue; } } public static string? ExtractString(string json, string propertyName) diff --git a/Source/Application/Features/Json/LlmPayloadParser.cs b/Source/Application/Features/Json/LlmPayloadParser.cs index 68ca6b08..919e46c4 100644 --- a/Source/Application/Features/Json/LlmPayloadParser.cs +++ b/Source/Application/Features/Json/LlmPayloadParser.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -43,6 +42,11 @@ public static class LlmPayloadParser RegexOptions.IgnoreCase | RegexOptions.Compiled, RegexTimeout); + private static readonly Regex MalformedTailPseudoCallRegex = new Regex( + @"\b(?[a-z_][a-z0-9_.]*)\((?[\s\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, @@ -256,6 +260,29 @@ public static IReadOnlyList ParsePseudoFunctionCalls(s }); } } + + if (results.Count == 0) + { + var tailMatch = MalformedTailPseudoCallRegex.Match(cleaned); + if (tailMatch.Success) + { + string fnName = tailMatch.Groups["fn"].Value; + if (IsValidToolIdentifier(fnName)) + { + string inner = tailMatch.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) { diff --git a/Source/Application/Features/Llm/ChunkAggregator.cs b/Source/Application/Features/Llm/ChunkAggregator.cs index 866012f1..2a06e334 100644 --- a/Source/Application/Features/Llm/ChunkAggregator.cs +++ b/Source/Application/Features/Llm/ChunkAggregator.cs @@ -13,7 +13,7 @@ internal sealed class ChunkAggregator private readonly string _requestId; private readonly StringBuilder _contentBuilder = new(); private readonly StringBuilder _toolCallsBuilder = new(); - private string? _reasoningContent; + private readonly StringBuilder _reasoningBuilder = new(); private int _promptTokens; private int _completionTokens; private int _cachedTokens; @@ -38,7 +38,7 @@ public void Append(LlmChunk chunk) if (chunk.DeltaToolCallsJson != null) _toolCallsBuilder.Append(chunk.DeltaToolCallsJson); if (chunk.DeltaReasoningContent != null) - _reasoningContent += chunk.DeltaReasoningContent; + _reasoningBuilder.Append(chunk.DeltaReasoningContent); if (chunk.DeltaPromptTokens.HasValue) _promptTokens = chunk.DeltaPromptTokens.Value; if (chunk.DeltaCompletionTokens.HasValue) @@ -59,7 +59,7 @@ public Result BuildFinalResponse() RequestId = _requestId, Content = _contentBuilder.ToString(), ToolCallsJson = _toolCallsBuilder.Length > 0 ? _toolCallsBuilder.ToString() : null, - ReasoningContent = _reasoningContent, + ReasoningContent = _reasoningBuilder.Length > 0 ? _reasoningBuilder.ToString() : null, TokensUsed = _promptTokens + _completionTokens, PromptTokens = _promptTokens, CompletionTokens = _completionTokens, diff --git a/Source/Application/Features/Llm/EndpointFailoverPolicy.cs b/Source/Application/Features/Llm/EndpointFailoverPolicy.cs index e8342126..1ae30d47 100644 --- a/Source/Application/Features/Llm/EndpointFailoverPolicy.cs +++ b/Source/Application/Features/Llm/EndpointFailoverPolicy.cs @@ -70,8 +70,10 @@ public void RecordFailure(string nodeKey, long cooldownMs, bool isPermanentQuota 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) + // Content moderation, cancellation, and permanent request schema errors must NOT isolate endpoints + if (error.Code == RimMindErrorCode.ContentFiltered || + error.Code == RimMindErrorCode.Cancelled || + error.Code == RimMindErrorCode.ClientPermanentFailure) return; if (error.Code == RimMindErrorCode.ClientQuotaOrAuthFailure) diff --git a/Source/Application/Features/Llm/EnvelopePromptFormatter.cs b/Source/Application/Features/Llm/EnvelopePromptFormatter.cs new file mode 100644 index 00000000..e5248bf8 --- /dev/null +++ b/Source/Application/Features/Llm/EnvelopePromptFormatter.cs @@ -0,0 +1,36 @@ +using System; +using System.Text; +using RimMind.Domain.Llm; + +namespace RimMind.Application.Features.Llm +{ + /// + /// Formats envelope chat messages by role for trace logging without duplicating role-filtering logic. + /// + internal static class EnvelopePromptFormatter + { + public static string FormatRolePrompt(LlmRequestEnvelope? envelope, string role) + { + var messages = envelope?.Messages; + if (messages == null || messages.Count == 0) + return string.Empty; + + var text = new StringBuilder(); + foreach (var message in messages) + { + if (message == null + || !string.Equals(message.Role, role, StringComparison.OrdinalIgnoreCase) + || string.IsNullOrWhiteSpace(message.Content)) + continue; + + if (text.Length > 0) + text.AppendLine().AppendLine(); + if (!string.IsNullOrWhiteSpace(message.LayerTag)) + text.Append('[').Append(message.LayerTag).Append("] "); + text.Append(message.Content); + } + + return text.ToString(); + } + } +} diff --git a/Source/Application/Features/Llm/LogSecretRedactor.cs b/Source/Application/Features/Llm/LogSecretRedactor.cs index 3cedccc2..4a16834d 100644 --- a/Source/Application/Features/Llm/LogSecretRedactor.cs +++ b/Source/Application/Features/Llm/LogSecretRedactor.cs @@ -26,7 +26,7 @@ public static class LogSecretRedactor RegexOptions.Compiled); private static readonly Regex KeyPrefixPattern = new Regex( - @"\b(?:[a-z]{2,4}_sk|sk-ant|sk-proj|sk|pk|rk|xai|gsk|AIza)[\-_][A-Za-z0-9\-_]{8,}", + @"\b(?:(?:[a-z]{2,4}_sk|sk-ant|sk-proj|sk|pk|rk|xai|gsk)[\-_][A-Za-z0-9\-_]{8,}|AIza[A-Za-z0-9\-_]{16,})", RegexOptions.Compiled); public static string Redact(string? text) diff --git a/Source/Application/Features/Llm/OpenAIWireCodec.cs b/Source/Application/Features/Llm/OpenAIWireCodec.cs index 71e8fec4..0d671853 100644 --- a/Source/Application/Features/Llm/OpenAIWireCodec.cs +++ b/Source/Application/Features/Llm/OpenAIWireCodec.cs @@ -3,7 +3,6 @@ using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; -using RimMind.Domain.Common; using RimMind.Domain.Llm; using RimMind.Domain.ValueObjects; @@ -34,46 +33,25 @@ public static string BuildRequestJson( if (envelope == null) throw new ArgumentNullException(nameof(envelope)); int effectiveMaxTokens = envelope.MaxTokens > 0 - ? (defaultMaxTokens > envelope.MaxTokens && envelope.ScenarioId != "RimMind.Test" - ? defaultMaxTokens - : envelope.MaxTokens) + ? envelope.MaxTokens : defaultMaxTokens; var messages = BuildMessages(envelope); var responseFormat = BuildResponseFormat(envelope, forceJsonMode, messages); var (tools, toolChoice) = BuildTools(envelope); - object payload; - if (omitZeroMaxTokens && effectiveMaxTokens <= 0) + var payload = new WireRequestDto { - 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, - }; - } + model = modelName, + messages = messages, + max_tokens = (omitZeroMaxTokens && effectiveMaxTokens <= 0) ? (int?)null : effectiveMaxTokens, + temperature = envelope.Temperature, + stream = stream, + stream_options = stream ? new WireStreamOptionsDto() : null, + response_format = responseFormat, + tools = tools, + tool_choice = toolChoice, + }; if (customizePayload != null) { @@ -102,16 +80,25 @@ public static Result ParseResponse( 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; + int embeddedStatus = AsInt(token["error"]?["status"]) ?? 0; string safeErr = LogSecretRedactor.ForLog(errMsg); + string combined = $"{errCode} {errType} {errMsg}"; - if (errMsg.IndexOf("Content Exists Risk", StringComparison.OrdinalIgnoreCase) >= 0 || + if (HttpErrorClassifier.IsContentModerationResponse(400, combined) || 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) || + if (HttpErrorClassifier.IsQuotaOrAuthError(embeddedStatus, combined)) + { + return Result.Err(RimMindErrors.ClientQuotaOrAuth(safeErr)); + } + + if (HttpErrorClassifier.IsTransientRateLimitOrQueueError(embeddedStatus, combined) || + HttpErrorClassifier.IsTransientHttpFailure(embeddedStatus, combined) || + string.Equals(errType, "server_error", StringComparison.OrdinalIgnoreCase) || string.Equals(errType, "api_error", StringComparison.OrdinalIgnoreCase) || string.Equals(errCode, "server_error", StringComparison.OrdinalIgnoreCase)) { @@ -437,19 +424,6 @@ private static List BuildMessages(LlmRequestEnvelope envelope) #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; @@ -496,17 +470,12 @@ 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")] @@ -522,6 +491,7 @@ private sealed class WireToolCallFunctionDto [JsonProperty("arguments")] public string Arguments = ""; } +#pragma warning restore CS0649 #pragma warning restore IDE1006 } } diff --git a/Source/Application/Features/Pipeline/Bus/BusPublishPipelineFactory.cs b/Source/Application/Features/Pipeline/Bus/BusPublishPipelineFactory.cs index 275dc041..73e588ba 100644 --- a/Source/Application/Features/Pipeline/Bus/BusPublishPipelineFactory.cs +++ b/Source/Application/Features/Pipeline/Bus/BusPublishPipelineFactory.cs @@ -1,6 +1,5 @@ using System; using RimMind.Application.Common.Behaviours; -using RimMind.Application.Common.Interfaces; using RimMind.Application.Common.Interfaces.Abstractions; using RimMind.Application.Common.Interfaces.Extension; using RimMind.Application.Common.Interfaces.Pipeline; diff --git a/Source/Application/Features/Pipeline/Bus/BusPublishTelemetryMiddleware.cs b/Source/Application/Features/Pipeline/Bus/BusPublishTelemetryMiddleware.cs index 5fad8da8..305b0ae5 100644 --- a/Source/Application/Features/Pipeline/Bus/BusPublishTelemetryMiddleware.cs +++ b/Source/Application/Features/Pipeline/Bus/BusPublishTelemetryMiddleware.cs @@ -15,8 +15,13 @@ internal sealed class BusPublishTelemetryMiddleware : IMiddleware RimMindOwnerConsts.CoreModId; private readonly ILogSink? _log; + private readonly bool _verboseLogging; - public BusPublishTelemetryMiddleware(ILogSink? log = null) { _log = log; } + public BusPublishTelemetryMiddleware(ILogSink? log = null, bool verboseLogging = false) + { + _log = log; + _verboseLogging = verboseLogging; + } public async Task InvokeAsync(BusPublishContext context, MiddlewareDelegate next) { @@ -27,7 +32,7 @@ public async Task InvokeAsync(BusPublishContext context, MiddlewareDelegate public string OwnerModId => RimMindOwnerConsts.CoreModId; private readonly Action _dispatch; - private readonly ILogSink? _log; public DispatchMiddleware(Action dispatch, ILogSink? log = null) { _dispatch = dispatch; - _log = log; } public Task InvokeAsync(BusPublishContext context, MiddlewareDelegate next) diff --git a/Source/Application/Features/Pipeline/Bus/ThreadAffinityCheckMiddleware.cs b/Source/Application/Features/Pipeline/Bus/ThreadAffinityCheckMiddleware.cs index c3ea2f2c..6452b5f3 100644 --- a/Source/Application/Features/Pipeline/Bus/ThreadAffinityCheckMiddleware.cs +++ b/Source/Application/Features/Pipeline/Bus/ThreadAffinityCheckMiddleware.cs @@ -4,7 +4,6 @@ using RimMind.Application.Common.Interfaces.Abstractions; using RimMind.Application.Common.Interfaces.Pipeline; using RimMind.Application.Common.Models.Pipeline; -using RimMind.Domain.Common; namespace RimMind.Application.Features.Pipeline.Bus { @@ -28,10 +27,10 @@ public Task InvokeAsync(BusPublishContext context, MiddlewareDelegate - { - public string Name => "UnifiedCache"; - public int Order => RimMindDefaults.MiddlewareOrder.Cache; - public string Id => "UnifiedCache"; - public string OwnerModId => RimMindOwnerConsts.CoreModId; - - private readonly ILogSink? _log; - - public CacheMiddleware(ILogSink? log = null) - { - _log = log; - } - - public Task InvokeAsync(LlmRequestContext context, MiddlewareDelegate next) - { - // Streaming requests are not cacheable - if (context.Envelope != null && context.Envelope.IsStreaming) - { - _log?.Message($"[UnifiedCache] Streaming request {context.Envelope.RequestId}, skipping cache"); - return next(context); - } - - if (context.CacheHit) - { - _log?.Message($"[UnifiedCache] Cache hit for {context.Envelope?.RequestId}"); - context.ShortCircuit("CacheHit"); - return Task.CompletedTask; - } - - return next(context); - } - } -} diff --git a/Source/Application/Features/Pipeline/Unified/CircuitBreakerMiddleware.cs b/Source/Application/Features/Pipeline/Unified/CircuitBreakerMiddleware.cs index 7e6b6d56..5c2217b9 100644 --- a/Source/Application/Features/Pipeline/Unified/CircuitBreakerMiddleware.cs +++ b/Source/Application/Features/Pipeline/Unified/CircuitBreakerMiddleware.cs @@ -44,7 +44,9 @@ private sealed class CircuitBucket public bool CanaryInProgress; } - private readonly Dictionary _buckets = new Dictionary(StringComparer.Ordinal); + private readonly Dictionary _providerBuckets = new Dictionary(StringComparer.Ordinal); + private readonly ConditionalWeakTable _clientBuckets = new ConditionalWeakTable(); + private readonly CircuitBucket _defaultBucket = new CircuitBucket(); private CircuitBucket _lastBucket = new CircuitBucket(); internal string CurrentStateName { get { lock (_syncRoot) return _lastBucket.State.ToString(); } } @@ -55,7 +57,7 @@ internal string GetStateName(IAIClient client) { lock (_syncRoot) { - return _buckets.TryGetValue(ResolveClientKey(client), out var bucket) + return client != null && _clientBuckets.TryGetValue(client, out var bucket) ? bucket.State.ToString() : CircuitState.Closed.ToString(); } @@ -65,7 +67,7 @@ internal int GetConsecutiveFailuresCount(IAIClient client) { lock (_syncRoot) { - return _buckets.TryGetValue(ResolveClientKey(client), out var bucket) + return client != null && _clientBuckets.TryGetValue(client, out var bucket) ? bucket.ConsecutiveFailures : 0; } @@ -148,45 +150,44 @@ public async Task InvokeAsync(LlmRequestContext context, MiddlewareDelegate $"client:{client.GetType().FullName}:{RuntimeHelpers.GetHashCode(client)}"; - private void ShortCircuitOpen(LlmRequestContext context) { _log?.Warning("[UnifiedCircuitBreaker] Circuit open, short-circuiting request"); diff --git a/Source/Application/Features/Pipeline/Unified/ClientInvokeMiddleware.cs b/Source/Application/Features/Pipeline/Unified/ClientInvokeMiddleware.cs index 98a912ed..99b99081 100644 --- a/Source/Application/Features/Pipeline/Unified/ClientInvokeMiddleware.cs +++ b/Source/Application/Features/Pipeline/Unified/ClientInvokeMiddleware.cs @@ -65,7 +65,7 @@ private async Task InvokeNonStreamingAsync(LlmRequestContext context, IAIClient } else { - if (result.Error.Code != RimMindErrorCode.Cancelled) _log?.Warning($"[UnifiedClientInvoke] Error: {result.Error.Message}"); + if (result.Error.Code != RimMindErrorCode.Cancelled) _log?.Warning($"[UnifiedClientInvoke] Error: {LogSecretRedactor.ForLog(result.Error.Message)}"); context.Result = result; } } @@ -75,14 +75,16 @@ private async Task InvokeStreamingAsync(LlmRequestContext context, IAIClient cli RecordFinalPrompts(context.Envelope); // Streaming: use SendStreamAsync with callback; the Result now carries the final LlmResponse var aggregator = new ChunkAggregator(context.Envelope.RequestId); + var onChunk = context.Envelope.OnStreamChunk; var result = await client.SendStreamAsync(context.Envelope, chunk => { aggregator.Append(chunk); + onChunk?.Invoke(chunk); }, context.Ct); if (result.IsErr) { - if (result.Error.Code != RimMindErrorCode.Cancelled) _log?.Warning($"[UnifiedClientInvoke] Stream error: {result.Error.Message}"); + if (result.Error.Code != RimMindErrorCode.Cancelled) _log?.Warning($"[UnifiedClientInvoke] Stream error: {LogSecretRedactor.ForLog(result.Error.Message)}"); aggregator.SetError(result.Error); var errorResult = aggregator.BuildFinalResponse(); context.Result = errorResult; @@ -120,37 +122,15 @@ private void RecordFinalPrompts(LlmRequestEnvelope envelope) _traceLog.UpdateRequestPrompts( envelope.RequestId, - BuildPrompt(envelope, "system"), - BuildPrompt(envelope, "user"), - BuildPrompt(envelope, "assistant")); + EnvelopePromptFormatter.FormatRolePrompt(envelope, "system"), + EnvelopePromptFormatter.FormatRolePrompt(envelope, "user"), + EnvelopePromptFormatter.FormatRolePrompt(envelope, "assistant")); var layers = AIRequestTraceEntry.ExtractLayerTraces(envelope.Messages); if (layers.Count > 0) _traceLog.UpdateRequestLayers(envelope.RequestId, layers); } - private static string BuildPrompt(LlmRequestEnvelope envelope, string role) - { - var messages = envelope.Messages; - if (messages == null || messages.Count == 0) - return string.Empty; - - var text = new System.Text.StringBuilder(); - foreach (var message in messages) - { - if (!string.Equals(message.Role, role, StringComparison.OrdinalIgnoreCase) - || string.IsNullOrWhiteSpace(message.Content)) - continue; - - if (text.Length > 0) - text.AppendLine().AppendLine(); - if (!string.IsNullOrWhiteSpace(message.LayerTag)) - text.Append('[').Append(message.LayerTag).Append("] "); - text.Append(message.Content); - } - return text.ToString(); - } - private static LlmRequestEnvelope CloneWithCancellationToken( LlmRequestEnvelope envelope, System.Threading.CancellationToken cancellationToken) diff --git a/Source/Application/Features/Pipeline/Unified/ContextBuildMiddleware.cs b/Source/Application/Features/Pipeline/Unified/ContextBuildMiddleware.cs index 050e0bf8..f6aafac6 100644 --- a/Source/Application/Features/Pipeline/Unified/ContextBuildMiddleware.cs +++ b/Source/Application/Features/Pipeline/Unified/ContextBuildMiddleware.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; -using System.Linq; using System.Threading.Tasks; using RimMind.Application.Common.Constants; using RimMind.Application.Common.Interfaces.Abstractions; diff --git a/Source/Application/Features/Pipeline/Unified/ContextFeedbackMiddleware.cs b/Source/Application/Features/Pipeline/Unified/ContextFeedbackMiddleware.cs index 627a8112..ba44de5d 100644 --- a/Source/Application/Features/Pipeline/Unified/ContextFeedbackMiddleware.cs +++ b/Source/Application/Features/Pipeline/Unified/ContextFeedbackMiddleware.cs @@ -20,22 +20,23 @@ internal sealed class ContextFeedbackMiddleware : IMiddleware private readonly IRelevanceLearner _learner; private readonly AIResponseAnalyzer _analyzer; - private readonly ILogSink? _log; public ContextFeedbackMiddleware(IRelevanceLearner learner, AIResponseAnalyzer analyzer, ILogSink? log = null) { _learner = learner; _analyzer = analyzer; - _log = log; } public async Task InvokeAsync(LlmRequestContext ctx, MiddlewareDelegate next) { + var envelope = ctx.Envelope; + string? traceId = envelope?.TraceId; + // Before downstream: record which keys were included in the prompt - if (ctx.Snapshot != null && ctx.Snapshot.IncludedKeys != null && ctx.Snapshot.IncludedKeys.Length > 0) + if (ctx.Snapshot != null && ctx.Snapshot.IncludedKeys != null && ctx.Snapshot.IncludedKeys.Length > 0 && !string.IsNullOrEmpty(traceId)) { var keys = ctx.Snapshot.IncludedKeys.ToList(); - _learner.RecordInclusion(ctx.Envelope.TraceId, ctx.Envelope.ScenarioId, keys); + _learner.RecordInclusion(traceId!, envelope?.ScenarioId ?? string.Empty, keys); } try @@ -43,21 +44,25 @@ public async Task InvokeAsync(LlmRequestContext ctx, MiddlewareDelegate()); + if (ctx.Result != null && ctx.Result.Value.IsOk && ctx.Snapshot != null) + { + var used = _analyzer.ExtractUsedKeys(ctx.Snapshot, ctx.Result.Value.Value); + _learner.RecordUsage(traceId!, used); + } + else if (ctx.Result != null && ctx.Result.Value.IsErr) + { + // Request failed: clean up pending trace with empty usage + _learner.RecordUsage(traceId!, Array.Empty()); + } } } catch { // Exception: clean up pending trace with empty usage - _learner.RecordUsage(ctx.Envelope.TraceId, Array.Empty()); + if (!string.IsNullOrEmpty(traceId)) + _learner.RecordUsage(traceId!, Array.Empty()); throw; } } diff --git a/Source/Application/Features/Pipeline/Unified/NpcEnrichMiddleware.cs b/Source/Application/Features/Pipeline/Unified/NpcEnrichMiddleware.cs index c77de01b..459a642a 100644 --- a/Source/Application/Features/Pipeline/Unified/NpcEnrichMiddleware.cs +++ b/Source/Application/Features/Pipeline/Unified/NpcEnrichMiddleware.cs @@ -45,7 +45,7 @@ public async Task InvokeAsync(LlmRequestContext context, MiddlewareDelegate public string OwnerModId => RimMindOwnerConsts.CoreModId; private const int MaxRepetitiveCount = 3; + private static readonly TimeSpan RegexTimeout = TimeSpan.FromMilliseconds(50); + + private static readonly Regex ThinkingTagBlockRegex = new Regex( + @"[\s\S]*?", + RegexOptions.IgnoreCase | RegexOptions.Compiled, + RegexTimeout); + + private static readonly Regex ResidualXmlTagRegex = new Regex( + @"]*>", + RegexOptions.IgnoreCase | RegexOptions.Compiled, + RegexTimeout); public async Task InvokeAsync(LlmRequestContext context, MiddlewareDelegate next) { @@ -33,7 +48,7 @@ public async Task InvokeAsync(LlmRequestContext context, MiddlewareDelegate.Ok(response.With(content: fallbackStr)); return; @@ -52,22 +67,23 @@ public async Task InvokeAsync(LlmRequestContext context, MiddlewareDelegate 0) { - var (_, extractedToolName, extractedArgsJson, _) = - RimMind.Application.Features.Agent.Modes.ThinkStrategyHelper.TryExtractToolCallFromContent(response.Content); - if (!string.IsNullOrWhiteSpace(extractedToolName) - && !string.IsNullOrWhiteSpace(extractedArgsJson) - && declaredTools.Any(t => string.Equals(t.Name, extractedToolName, StringComparison.OrdinalIgnoreCase))) + var parsedCalls = LlmPayloadParser.ParsePseudoFunctionCalls(response.Content); + var firstCall = parsedCalls.Count > 0 ? parsedCalls[0] : null; + if (firstCall != null + && !string.IsNullOrWhiteSpace(firstCall.Name) + && !string.IsNullOrWhiteSpace(firstCall.ArgumentsJson) + && declaredTools.Any(t => string.Equals(t.Name, firstCall.Name, StringComparison.OrdinalIgnoreCase))) { - string synthesizedToolCallsJson = Newtonsoft.Json.JsonConvert.SerializeObject(new[] + string synthesizedToolCallsJson = JsonConvert.SerializeObject(new[] { new { - id = "call_pseudo_0", + id = string.IsNullOrWhiteSpace(firstCall.Id) ? "call_pseudo_0" : firstCall.Id, type = "function", function = new { - name = extractedToolName, - arguments = extractedArgsJson + name = firstCall.Name, + arguments = firstCall.ArgumentsJson } } }); @@ -84,7 +100,7 @@ public async Task InvokeAsync(LlmRequestContext context, MiddlewareDelegate.Err( @@ -99,35 +115,33 @@ internal static string StripResidualModelXmlTags(string content) return string.Empty; string result = content; - if (result.IndexOf("", StringComparison.OrdinalIgnoreCase) >= 0) + try { - result = System.Text.RegularExpressions.Regex.Replace( - result, - @"[\s\S]*?", - string.Empty, - System.Text.RegularExpressions.RegexOptions.IgnoreCase); - } + if (result.IndexOf("", StringComparison.OrdinalIgnoreCase) >= 0) + { + result = ThinkingTagBlockRegex.Replace(result, string.Empty); + } - if (result.IndexOf('<') >= 0 && result.IndexOf('>') >= 0) + if (result.IndexOf('<') >= 0 && result.IndexOf('>') >= 0) + { + result = ResidualXmlTagRegex.Replace(result, string.Empty); + } + } + catch (RegexMatchTimeoutException) { - result = System.Text.RegularExpressions.Regex.Replace( - result, - @"]*>", - string.Empty, - System.Text.RegularExpressions.RegexOptions.IgnoreCase); } result = result.Trim(); if (result.IndexOf('(') > 0) { - var (_, _, argsJson, _) = - RimMind.Application.Features.Agent.Modes.ThinkStrategyHelper.TryExtractToolCallFromContent(result); + var parsed = LlmPayloadParser.ParsePseudoFunctionCalls(result); + string? argsJson = parsed.Count > 0 ? parsed[0].ArgumentsJson : null; if (!string.IsNullOrWhiteSpace(argsJson)) { try { - var obj = Newtonsoft.Json.Linq.JObject.Parse(argsJson!); + var obj = JObject.Parse(argsJson!); string? innerText = obj["speech"]?.ToString() ?? obj["thought"]?.ToString() ?? obj["reply"]?.ToString() @@ -148,10 +162,12 @@ internal static string StripResidualModelXmlTags(string content) return result.Trim(); } - private bool IsRepetitiveAction(LlmRequestContext context) + private static bool IsRepetitiveAction(LlmRequestContext context, LlmResponse response) { - if (context.ToolCallResults == null || context.ToolCallResults.Count == 0) return false; - if (!context.Items.TryGetValue("recent_action_intents", out var obj)) return false; + bool hasToolCalls = !string.IsNullOrWhiteSpace(response.ToolCallsJson) + || (context.ToolCallResults != null && context.ToolCallResults.Count > 0); + if (!hasToolCalls) return false; + if (!context.Items.TryGetValue(PipelineContextKeys.RecentActionIntents, out var obj)) return false; if (obj is not List recentIntents) return false; if (recentIntents.Count < MaxRepetitiveCount) return false; diff --git a/Source/Application/Features/Pipeline/Unified/RetryMiddleware.cs b/Source/Application/Features/Pipeline/Unified/RetryMiddleware.cs index f8fdd1d9..0f650aee 100644 --- a/Source/Application/Features/Pipeline/Unified/RetryMiddleware.cs +++ b/Source/Application/Features/Pipeline/Unified/RetryMiddleware.cs @@ -3,9 +3,11 @@ using System.Threading.Tasks; using RimMind.Application.Common.Constants; using RimMind.Application.Common.Interfaces.Abstractions; +using RimMind.Application.Common.Interfaces.Internal; using RimMind.Application.Common.Interfaces.Pipeline; using RimMind.Application.Common.Models; using RimMind.Application.Common.Models.Pipeline; +using RimMind.Application.Features.Llm; using RimMind.Domain.Llm; using RimMind.Domain.ValueObjects; @@ -21,23 +23,30 @@ internal sealed class RetryMiddleware : IMiddleware private readonly int _maxRetries; private readonly TimeSpan _delay; private readonly ILogSink? _log; + private readonly IQueueSettings? _queueSettings; - public RetryMiddleware(int maxRetries = RimMindDefaults.DefaultMaxRetryCount, TimeSpan? delay = null, ILogSink? log = null) + public RetryMiddleware( + int maxRetries = RimMindDefaults.DefaultMaxRetryCount, + TimeSpan? delay = null, + ILogSink? log = null, + IQueueSettings? queueSettings = null) { _maxRetries = maxRetries; _delay = delay ?? TimeSpan.FromSeconds(2); _log = log; + _queueSettings = queueSettings; } public async Task InvokeAsync(LlmRequestContext context, MiddlewareDelegate next) { - int maxAttempts = context.Envelope?.MaxRetryCount ?? _maxRetries; + int configuredRetries = _queueSettings != null ? Math.Max(0, _queueSettings.MaxRetryCount) : _maxRetries; + int maxAttempts = context.Envelope?.MaxRetryCount ?? configuredRetries; Result? lastResult = null; for (int attempt = 0; attempt <= maxAttempts; attempt++) { try { - await next(context); + await next(context).ConfigureAwait(false); if (context.Result.HasValue) lastResult = context.Result; if (context.Result?.IsOk == true) @@ -63,7 +72,7 @@ public async Task InvokeAsync(LlmRequestContext context, MiddlewareDelegate.Err( new RimMindError(RimMindErrorCode.ClientTransientFailure, ex.Message) { InnerException = ex }); - _log?.Warning($"[UnifiedRetry] Attempt {attempt + 1}/{maxAttempts + 1} failed: {ex.Message}"); + _log?.Warning($"[UnifiedRetry] Attempt {attempt + 1}/{maxAttempts + 1} failed: {LogSecretRedactor.ForLog(ex.Message)}"); } if (attempt < maxAttempts) @@ -72,7 +81,7 @@ public async Task InvokeAsync(LlmRequestContext context, MiddlewareDelegate + var tags = new Dictionary { { "scenario", context.Envelope?.ScenarioId ?? "unknown" }, { "is_streaming", (context.Envelope?.IsStreaming ?? false).ToString() }, { "npc_id", context.Envelope?.NpcId ?? "none" }, { "mode_id", context.AgentModeId.Value }, { "trace_id", context.TraceId ?? "none" }, - { "tool_call_count", (context.ToolCallResults?.Count ?? 0).ToString() } + { "tool_call_count", toolCallCount.ToString() } }; // Record timing @@ -64,7 +67,8 @@ public async Task InvokeAsync(LlmRequestContext context, MiddlewareDelegate 0) + return context.ToolCallResults.Count; + + string? toolCallsJson = context.Result?.IsOk == true ? context.Result.Value.Value?.ToolCallsJson : null; + if (string.IsNullOrWhiteSpace(toolCallsJson)) + return 0; + + try + { + return JArray.Parse(toolCallsJson!).Count; + } + catch + { + return 0; + } + } } } diff --git a/Source/Application/Features/Pipeline/Unified/ToolCallDispatchMiddleware.cs b/Source/Application/Features/Pipeline/Unified/ToolCallDispatchMiddleware.cs index 099a6edf..4202975f 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/Pipeline/Unified/UnifiedRequestPipelineFactory.cs b/Source/Application/Features/Pipeline/Unified/UnifiedRequestPipelineFactory.cs index c4da51be..e930cf52 100644 --- a/Source/Application/Features/Pipeline/Unified/UnifiedRequestPipelineFactory.cs +++ b/Source/Application/Features/Pipeline/Unified/UnifiedRequestPipelineFactory.cs @@ -1,13 +1,13 @@ using System.Collections.Generic; using RimMind.Application.Common.Behaviours; using RimMind.Application.Common.Interfaces.Abstractions; -using RimMind.Application.Common.Interfaces.Client; using RimMind.Application.Common.Interfaces.Context; using RimMind.Application.Common.Interfaces.Extension; using RimMind.Application.Common.Interfaces.Flywheel; using RimMind.Application.Common.Interfaces.Internal; using RimMind.Application.Common.Interfaces.Npc; using RimMind.Application.Common.Interfaces.Pipeline; +using RimMind.Application.Common.Interfaces.Runtime; using RimMind.Application.Common.Interfaces.Tools; using RimMind.Application.Common.Models.Pipeline; using RimMind.Application.Features.Context; @@ -26,12 +26,14 @@ public static MutablePipeline Build( IExtensionRegistry>? extensions = null, IRelevanceLearner? relevanceLearner = null, AIResponseAnalyzer? responseAnalyzer = null, - IAIRequestTraceLog? requestTraceLog = null) + IAIRequestTraceLog? requestTraceLog = null, + IRimMindRuntime? runtime = null, + IQueueSettings? queueSettings = null) { var analyzer = responseAnalyzer ?? new AIResponseAnalyzer(); var middlewares = new List> { - new ShortCircuitMiddleware(log), + new ShortCircuitMiddleware(log, runtime), new TraceContextMiddleware(log), new NpcEnrichMiddleware(npcManagers, log), new InputGuardrailMiddleware(new IInputGuardrail[] @@ -43,10 +45,9 @@ public static MutablePipeline Build( new ContextBuildMiddleware(contextEngine, log), new ContextFeedbackMiddleware(relevanceLearner ?? new RelevanceLearner(), analyzer, log), new RequestSanitizeMiddleware(log), - new CacheMiddleware(log), new TelemetryMiddleware(telemetry, log), new CircuitBreakerMiddleware(circuitBreakerSettings, log), - new RetryMiddleware(log: log), + new RetryMiddleware(log: log, queueSettings: queueSettings), new ClientInvokeMiddleware(log, requestTraceLog), new ToolCallDispatchMiddleware(toolRegistry, log, requestTraceLog), new OutputGuardrailMiddleware() diff --git a/Source/Application/Features/Prompt/MoteTextFormatter.cs b/Source/Application/Features/Prompt/MoteTextFormatter.cs index 5360ea29..53fe2c85 100644 --- a/Source/Application/Features/Prompt/MoteTextFormatter.cs +++ b/Source/Application/Features/Prompt/MoteTextFormatter.cs @@ -1,4 +1,3 @@ -using System; using System.Text; namespace RimMind.Application.Features.Prompt diff --git a/Source/Application/Features/Prompt/PromptSanitizer.cs b/Source/Application/Features/Prompt/PromptSanitizer.cs index d9ad83df..d7c2c9a7 100644 --- a/Source/Application/Features/Prompt/PromptSanitizer.cs +++ b/Source/Application/Features/Prompt/PromptSanitizer.cs @@ -73,6 +73,7 @@ private static string RemoveFormatCharacters(string input) public static string Truncate(string input, int maxLength) { + if (maxLength < 0) return string.Empty; if (string.IsNullOrEmpty(input) || input.Length <= maxLength) return input; return input.Substring(0, maxLength) + "..."; } @@ -80,9 +81,10 @@ public static string Truncate(string input, int maxLength) public static string RemoveDuplicateLines(string input) { if (string.IsNullOrEmpty(input)) return input; + var normalized = input.Replace("\r\n", "\n").Replace('\r', '\n'); var seen = new HashSet(); var sb = new StringBuilder(); - foreach (var line in input.Split('\n')) + foreach (var line in normalized.Split('\n')) { if (seen.Add(line)) { diff --git a/Source/Application/Features/Prompt/TaskInstructionBuilder.cs b/Source/Application/Features/Prompt/TaskInstructionBuilder.cs index a0bc528d..253f6cc8 100644 --- a/Source/Application/Features/Prompt/TaskInstructionBuilder.cs +++ b/Source/Application/Features/Prompt/TaskInstructionBuilder.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Globalization; using System.Text; using RimMind.Application.Common.Interfaces.Abstractions; @@ -49,51 +47,22 @@ public string Build() public static string Build(string keyPrefix, ITranslationService? translationService, params string[] subKeys) { + if (translationService == null || subKeys == null || subKeys.Length == 0) + return string.Empty; + var parts = new List(); foreach (var subKey in subKeys) { + if (string.IsNullOrEmpty(subKey)) continue; string fullKey = $"{keyPrefix}.{subKey}"; - string translated = translationService?.Translate(fullKey) ?? fullKey; - if (string.IsNullOrEmpty(translated)) continue; - if (IsMissingTranslation(translated, fullKey)) + if (!translationService.CanTranslate(fullKey)) + continue; + string translated = translationService.Translate(fullKey); + if (string.IsNullOrEmpty(translated) || translated == fullKey) continue; parts.Add(translated); } - return parts.Count > 0 ? string.Join("\n\n", parts) : ""; - } - - private static bool IsMissingTranslation(string translated, string originalKey) - { - if (translated == originalKey) return true; - string stripped = StripDiacritics(translated); - return string.Equals(stripped, originalKey, StringComparison.OrdinalIgnoreCase); - } - - private static string StripDiacritics(string text) - { - if (string.IsNullOrEmpty(text)) return text; - var sbPre = new StringBuilder(text.Length); - foreach (char c in text) - { - switch (c) - { - case 'ð': case 'Ð': sbPre.Append('d'); break; - case 'þ': case 'Þ': sbPre.Append('t'); break; - case 'Ƒ': case 'ƒ': sbPre.Append('f'); break; - case 'к': case 'К': sbPre.Append('k'); break; - case 'ſ': sbPre.Append('s'); break; - case 'ƞ': case 'Ƞ': sbPre.Append('n'); break; - default: sbPre.Append(c); break; - } - } - string normalized = sbPre.ToString().Normalize(NormalizationForm.FormD); - var sb = new StringBuilder(normalized.Length); - foreach (char c in normalized) - { - if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark) - sb.Append(c); - } - return sb.ToString().Normalize(); + return parts.Count > 0 ? string.Join("\n\n", parts) : string.Empty; } } } diff --git a/Source/Application/Features/Registry/ExtensionRegistry.cs b/Source/Application/Features/Registry/ExtensionRegistry.cs index 3b741da4..0e1238eb 100644 --- a/Source/Application/Features/Registry/ExtensionRegistry.cs +++ b/Source/Application/Features/Registry/ExtensionRegistry.cs @@ -22,7 +22,7 @@ public void Register(T extension) // We overwrite with the new extension, but log a warning for diagnostics. if (!_extensions.TryAdd(extension.Id, extension)) { - _log?.Message($"[ExtensionRegistry] Duplicate ID '{extension.Id}' for {typeof(T).Name}, overwriting previous registration"); + _log?.Warning($"[ExtensionRegistry] Duplicate ID '{extension.Id}' for {typeof(T).Name}, overwriting previous registration"); _extensions[extension.Id] = extension; } else diff --git a/Source/Application/Features/Requests/Queue/AgentBusQueueTickCoordinator.cs b/Source/Application/Features/Requests/Queue/AgentBusQueueTickCoordinator.cs index b3c20b21..2bf75b24 100644 --- a/Source/Application/Features/Requests/Queue/AgentBusQueueTickCoordinator.cs +++ b/Source/Application/Features/Requests/Queue/AgentBusQueueTickCoordinator.cs @@ -1,6 +1,5 @@ using System; using RimMind.Application.Common.Interfaces; -using RimMind.Application.Common.Interfaces.Internal; namespace RimMind.Application.Features.Requests.Queue { diff --git a/Source/Application/Features/Requests/Queue/CooldownTable.cs b/Source/Application/Features/Requests/Queue/CooldownTable.cs index 3767ecd5..be030bf6 100644 --- a/Source/Application/Features/Requests/Queue/CooldownTable.cs +++ b/Source/Application/Features/Requests/Queue/CooldownTable.cs @@ -9,13 +9,12 @@ public sealed class CooldownTable { private readonly ConcurrentDictionary _table = new ConcurrentDictionary(); - private readonly ILogSink? _log; - public CooldownTable(ILogSink? log = null) { _log = log; } + public CooldownTable(ILogSink? log = null) { } - public void Set(string modId, int ticksRemaining) + public void Set(string modId, int nextAllowedTick) { - _table[modId] = ticksRemaining; + _table[modId] = nextAllowedTick; } public int Get(string modId) @@ -23,16 +22,6 @@ public int Get(string modId) return _table.TryGetValue(modId, out var ticks) ? ticks : 0; } - public void Tick() - { - foreach (var key in _table.Keys) - { - _table.AddOrUpdate(key, 0, (_, v) => Math.Max(0, v - 1)); - if (_table.TryGetValue(key, out var v) && v <= 0) - _table.TryRemove(key, out _); - } - } - public void Clear(string modId) => _table.TryRemove(modId, out _); public void ClearAll() => _table.Clear(); @@ -41,11 +30,6 @@ public IReadOnlyDictionary GetSnapshot() return new Dictionary(_table); } - public int GetModCooldownTicks(string modId) - { - return Get(modId); - } - public bool IsOnCooldown(string modId, int currentTick) { if (!_table.TryGetValue(modId, out var nextAllowed)) return false; @@ -58,9 +42,6 @@ public int GetCooldownTicksLeft(string modId, int currentTick) return Math.Max(0, nextAllowed - currentTick); } - public IReadOnlyDictionary GetAll() - { - return new Dictionary(_table); - } + public IReadOnlyDictionary GetAll() => GetSnapshot(); } } diff --git a/Source/Application/Features/Requests/Queue/QueueCircuitBreaker.cs b/Source/Application/Features/Requests/Queue/QueueCircuitBreaker.cs index cd30c47d..13be9968 100644 --- a/Source/Application/Features/Requests/Queue/QueueCircuitBreaker.cs +++ b/Source/Application/Features/Requests/Queue/QueueCircuitBreaker.cs @@ -12,18 +12,14 @@ namespace RimMind.Application.Features.Requests.Queue internal sealed class QueueCircuitBreaker { private readonly CooldownTable _cooldowns; - private readonly ISettingsProvider _settings; public IExtensionRegistry? ModCooldowns { get; set; } - public QueueCircuitBreaker(ISettingsProvider settings, ILogSink? logSink = null, IExtensionRegistry? modCooldowns = null) + public QueueCircuitBreaker(ISettingsProvider? settings = null, ILogSink? logSink = null, IExtensionRegistry? modCooldowns = null) { - _settings = settings; _cooldowns = new CooldownTable(logSink); ModCooldowns = modCooldowns; } - public CooldownTable Cooldowns => _cooldowns; - public bool IsOnCooldown(string modId, int currentTick) => _cooldowns.IsOnCooldown(modId, currentTick); @@ -79,11 +75,5 @@ public void ClearCooldown(string modId) public void ClearAllCooldowns() => _cooldowns.ClearAll(); - - public void TickCooldowns() - => _cooldowns.Tick(); - - public int FailureThreshold => _settings.CircuitBreakerFailureThreshold; - public int OpenDurationSec => _settings.CircuitBreakerOpenDurationSec; } } diff --git a/Source/Application/Features/Requests/Queue/QueueDefaultSettings.cs b/Source/Application/Features/Requests/Queue/QueueDefaultSettings.cs index a42f9165..ddbfdf9e 100644 --- a/Source/Application/Features/Requests/Queue/QueueDefaultSettings.cs +++ b/Source/Application/Features/Requests/Queue/QueueDefaultSettings.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using RimMind.Application.Common.Helpers; -using RimMind.Application.Common.Interfaces.Abstractions; using RimMind.Application.Common.Interfaces.Internal; using RimMind.Application.Common.Models; using RimMind.Application.Common.Models.Client; @@ -10,11 +9,9 @@ namespace RimMind.Application.Features.Requests.Queue { internal sealed class DefaultSettingsProvider : ISettingsProvider { + private static readonly IContextSettings SharedDefaultContext = new DefaultContextSettings(); private const int kCircuitBreakerFailureThreshold = RimMindDefaults.CircuitBreakerFailureThreshold; private const int kCircuitBreakerOpenDurationSec = RimMindDefaults.CircuitBreakerOpenDurationSec; - private const int kMaxCacheEntries = RimMindDefaults.MaxCacheEntries; - private const float kMoodDiffThreshold = RimMindDefaults.DefaultMoodDiffThreshold; - private const float kTemperatureDiffThreshold = RimMindDefaults.DefaultTemperatureDiffThreshold; public int QueueProcessInterval { get => RimMindDefaults.QueueProcessInterval; set { } } public int MaxConcurrentRequests { get => RimMindDefaults.DefaultMaxConcurrentRequests; set { } } @@ -35,7 +32,6 @@ internal sealed class DefaultSettingsProvider : ISettingsProvider public string Provider { get => AIProviderRegistry.GetDefaultProviderId(); set { } } public string ApiKey { get => ""; set { } } public string ApiEndpoint { get => ""; set { } } - public string Player2RemoteUrl { get => ""; set { } } public IReadOnlyList? BackupEndpoints => null; public bool DebugLogging { get => false; set { } } public int CircuitBreakerFailureThreshold => kCircuitBreakerFailureThreshold; @@ -43,7 +39,7 @@ internal sealed class DefaultSettingsProvider : ISettingsProvider public int ContextCalibrateInterval { get => RimMindDefaults.FlywheelCalibrateInterval; set { } } public int ContextDiffLifetimeTicks { get => RimMindDefaults.ContextDiffLifetimeTicks; set { } } public bool IsConfigured => false; - public IContextSettings Context => new DefaultContextSettings(); + public IContextSettings Context => SharedDefaultContext; public bool RequestOverlayEnabled { get => true; set { } } public float RequestOverlayX { get => 20f; set { } } public float RequestOverlayY { get => 20f; set { } } @@ -56,7 +52,8 @@ internal sealed class DefaultSettingsProvider : ISettingsProvider public string CustomMapPrompt { get => ""; set { } } public FlywheelAutoApplyMode AutoApplyMode { get => FlywheelAutoApplyMode.Off; set { } } public float AutoApplyConfidenceThreshold { get => RimMindDefaults.AutoApplyConfidenceThreshold; set { } } - public bool IsOpenAIConfigured() => false; + public string GetProviderOption(string key) => ""; + public void SetProviderOption(string key, string value) { } public void Persist() { /* Null Object: defaults are immutable, nothing to persist */ } AgentAutonomyLevel IAgentAutonomySettings.AutonomyLevel { get => AgentAutonomyLevel.Autonomous; set { } } diff --git a/Source/Application/Features/Requests/Queue/RequestQueue.cs b/Source/Application/Features/Requests/Queue/RequestQueue.cs index 2bc74eec..ab128dd8 100644 --- a/Source/Application/Features/Requests/Queue/RequestQueue.cs +++ b/Source/Application/Features/Requests/Queue/RequestQueue.cs @@ -12,16 +12,15 @@ using RimMind.Application.Common.Helpers; using RimMind.Application.Common.Models.Client; using RimMind.Application.Common.Models; +using RimMind.Application.Features.Llm; using RimMind.Domain.Llm; using RimMind.Domain.ValueObjects; using AIRequestState = RimMind.Domain.Llm.AIRequestState; namespace RimMind.Application.Features.Requests.Queue { - public class RequestQueue : ITickableRequestQueue + public class RequestQueue : ITickableRequestQueue, IDisposable { - private const long TicksPerMillisecond = RimMindDefaults.TicksPerMillisecond; - private readonly RequestCompletionInbox _completionInbox = new RequestCompletionInbox(); private readonly object _queueLock = new object(); @@ -37,14 +36,13 @@ private readonly ConcurrentDictionary _requestIdToActive private readonly ILogSink? _logSink; private readonly ICompletionFence _completionFence; - private ILogSink? LogSink => _logSink; - private readonly Func? _settingsFactory; private int _lastQueueProcessTick; private int _nextTrackingId; private bool _isPaused; private bool _isProcessingLocalRequest; + private bool _disposed; private CancellationTokenSource _cts = new CancellationTokenSource(); public int CurrentTick { get; set; } @@ -77,7 +75,18 @@ public RequestQueue( _settingsFactory = settingsFactory; _logSink = logSink; _completionFence = completionFence ?? UnboundedCompletionFence.Instance; - _circuitBreaker = new QueueCircuitBreaker(Settings, logSink, modCooldowns); + _circuitBreaker = new QueueCircuitBreaker(settings: null, logSink: logSink, modCooldowns: modCooldowns); + } + + public void Dispose() + { + lock (_queueLock) + { + if (_disposed) return; + _disposed = true; + try { _cts.Cancel(); } catch (ObjectDisposedException) { } + try { _cts.Dispose(); } catch (ObjectDisposedException) { } + } } public void Tick() @@ -108,14 +117,15 @@ public void CancelAllRequests() lock (_queueLock) { var previous = _cts; - _cts = new CancellationTokenSource(); - previous.Cancel(); + if (!_disposed) + _cts = new CancellationTokenSource(); + try { previous.Cancel(); } catch (ObjectDisposedException) { } var cancelled = Result.Err( new RimMindError(RimMindErrorCode.Cancelled, "Request cancelled")); foreach (var tracked in _activeRequests.Values.ToList()) { - tracked.CancellationSource?.Cancel(); + try { tracked.CancellationSource?.Cancel(); } catch (ObjectDisposedException) { } Complete(tracked, cancelled); } foreach (var queue in _modQueues.Values) @@ -123,7 +133,10 @@ public void CancelAllRequests() foreach (var tracked in queue.ToList()) Complete(tracked, cancelled); queue.Clear(); } - previous.Dispose(); + if (!_disposed) + { + try { previous.Dispose(); } catch (ObjectDisposedException) { } + } } } @@ -264,6 +277,17 @@ private void PruneExpiredAndIneligibleHead(List queue, int now, while (queue.Count > 0) { var t = queue[0]; + if (t.Envelope.Ct.IsCancellationRequested) + { + queue.RemoveAt(0); + t.State = AIRequestState.Cancelled; + Complete(t, Result.Err( + new RimMindError(RimMindErrorCode.Cancelled, "Request cancelled before dispatch"))); + if (Settings.DebugLogging) + EnqueueLog($"[RimMind-Core] Dropped cancelled request {t.Envelope.RequestId} before dispatch"); + continue; + } + if (IsExpired(t, now, nowUtc, out string expireReason)) { queue.RemoveAt(0); @@ -355,10 +379,29 @@ private void TryProcessModQueue(string modId, int now) private void FireRequest(TrackedRequest tracked) { - tracked.CancellationSource = CancellationTokenSource.CreateLinkedTokenSource( - _cts.Token, - tracked.Envelope.Ct, - _completionFence.CancellationToken); + if (_disposed) + { + tracked.State = AIRequestState.Cancelled; + Complete(tracked, Result.Err( + new RimMindError(RimMindErrorCode.Cancelled, "Request queue disposed"))); + return; + } + + try + { + tracked.CancellationSource = CancellationTokenSource.CreateLinkedTokenSource( + _cts.Token, + tracked.Envelope.Ct, + _completionFence.CancellationToken); + } + catch (ObjectDisposedException) + { + tracked.State = AIRequestState.Cancelled; + Complete(tracked, Result.Err( + new RimMindError(RimMindErrorCode.Cancelled, "Request cancellation source disposed"))); + return; + } + var ct = tracked.CancellationSource.Token; Task.Run(async () => { @@ -375,7 +418,7 @@ private void FireRequest(TrackedRequest tracked) } catch (Exception ex) { - LogSink?.LogFromBackground($"[RimMind-Core] Execute threw for {tracked.Envelope.RequestId}: {ex.Message}", isWarning: true); + _logSink?.LogFromBackground($"[RimMind-Core] Execute threw for {tracked.Envelope.RequestId}: {LogSecretRedactor.ForLog(ex.Message)}", isWarning: true); result = Result.Err( new RimMindError(RimMindErrorCode.InternalError, ex.Message)); } @@ -409,7 +452,7 @@ private void CheckActiveRequestTimeouts() lock (_queueLock) { if (_activeRequests.Count == 0) return; - var nowUtc = DateTime.UtcNow; + var nowUtc = NowUtc(); int timeoutMs = Settings.RequestTimeoutMs; var timedOut = new List(); foreach (var kvp in _activeRequests) diff --git a/Source/Application/Features/Requests/RequestSubmissionService.cs b/Source/Application/Features/Requests/RequestSubmissionService.cs index 34e0ce29..6d24d3b5 100644 --- a/Source/Application/Features/Requests/RequestSubmissionService.cs +++ b/Source/Application/Features/Requests/RequestSubmissionService.cs @@ -2,15 +2,16 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; -using System.Text; using System.Threading; using System.Threading.Tasks; +using RimMind.Application.Common.Constants; using RimMind.Application.Common.Interfaces.Async; using RimMind.Application.Common.Interfaces.Internal; using RimMind.Application.Common.Interfaces.Pipeline; -using RimMind.Application.Common.Models.Context; using RimMind.Application.Common.Models.Debug; using RimMind.Application.Common.Models.Pipeline; +using RimMind.Application.Features.Context; +using RimMind.Application.Features.Llm; using RimMind.Application.Features.Requests.Queue; using RimMind.Domain.Llm; using RimMind.Domain.ValueObjects; @@ -137,23 +138,23 @@ private void StartTrace(LlmRequestEnvelope envelope) envelope.RequestId, GetTraceSource(envelope), _modelSettings?.ModelName ?? string.Empty, - BuildTracePrompt(envelope, "system"), - BuildTracePrompt(envelope, "user"), - BuildTracePrompt(envelope, "assistant")); + EnvelopePromptFormatter.FormatRolePrompt(envelope, "system"), + EnvelopePromptFormatter.FormatRolePrompt(envelope, "user"), + EnvelopePromptFormatter.FormatRolePrompt(envelope, "assistant")); string rolloutId = string.Empty; int turnIndex = 0; if (envelope.Hints != null) { - if (envelope.Hints.TryGetValue("rollout_id", out var hintedRollout) && !string.IsNullOrWhiteSpace(hintedRollout)) + if (envelope.Hints.TryGetValue(LlmHintKeys.RolloutId, out var hintedRollout) && !string.IsNullOrWhiteSpace(hintedRollout)) rolloutId = hintedRollout; - if (envelope.Hints.TryGetValue("turn_index", out var hintedTurn) && int.TryParse(hintedTurn, out var parsedTurn)) + if (envelope.Hints.TryGetValue(LlmHintKeys.TurnIndex, out var hintedTurn) && int.TryParse(hintedTurn, out var parsedTurn)) turnIndex = parsedTurn; } bool isAgentRollout = !string.IsNullOrWhiteSpace(rolloutId) - || ScenarioIds.IsDecisionScenario(envelope.ScenarioId) - || string.Equals(envelope.ModId, "RimMind.Agent", StringComparison.OrdinalIgnoreCase); + || ScenarioRegistry.IsDecisionScenario(envelope.ScenarioId) + || string.Equals(envelope.ModId, RimMindOwnerConsts.AgentModId, StringComparison.OrdinalIgnoreCase); if (isAgentRollout && string.IsNullOrWhiteSpace(rolloutId)) rolloutId = !string.IsNullOrWhiteSpace(envelope.TraceId) ? envelope.TraceId : envelope.RequestId; @@ -213,8 +214,9 @@ private void CompleteTrace( bool alreadyDispatched = envelope.ToolDispatchMode == ToolCallDispatchMode.Auto && dispatched != null && dispatched.Any(r => - (!string.IsNullOrEmpty(call.Id) && string.Equals(r.ToolCallId, call.Id, StringComparison.Ordinal)) - || string.Equals(r.ToolName, call.Name, StringComparison.OrdinalIgnoreCase)); + !string.IsNullOrEmpty(call.Id) + ? string.Equals(r.ToolCallId, call.Id, StringComparison.Ordinal) + : string.Equals(r.ToolName, call.Name, StringComparison.OrdinalIgnoreCase)); if (alreadyDispatched) continue; @@ -252,27 +254,5 @@ private static string GetTraceSource(LlmRequestEnvelope envelope) if (!string.IsNullOrWhiteSpace(envelope.NpcId)) parts.Add($"npc:{envelope.NpcId}"); return parts.Count > 0 ? string.Join(" | ", parts) : "unknown"; } - - private static string BuildTracePrompt(LlmRequestEnvelope envelope, string role) - { - if (envelope.Messages == null || envelope.Messages.Count == 0) - return string.Empty; - - var prompt = new StringBuilder(); - foreach (var message in envelope.Messages) - { - if (!string.Equals(message.Role, role, StringComparison.OrdinalIgnoreCase) || - string.IsNullOrWhiteSpace(message.Content)) - continue; - - if (prompt.Length > 0) - prompt.AppendLine().AppendLine(); - if (!string.IsNullOrWhiteSpace(message.LayerTag)) - prompt.Append('[').Append(message.LayerTag).Append("] "); - prompt.Append(message.Content); - } - - return prompt.ToString(); - } } } diff --git a/Source/Application/Features/Storage/SyncDecision.cs b/Source/Application/Features/Storage/SyncDecision.cs deleted file mode 100644 index a4fc8d9c..00000000 --- a/Source/Application/Features/Storage/SyncDecision.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace RimMind.Application.Features.Storage -{ - /// - /// Result of a remote sync comparison. - /// - internal enum SyncDecision - { - /// No sync needed — local and remote are identical. - NoChange, - /// Remote is newer — should pull. - PullRemote, - /// Local is newer — should push. - PushLocal, - /// Remote does not exist — should push. - PushNew, - } -} diff --git a/Source/Application/Features/Tools/CompositeToolExecutionTemplate.cs b/Source/Application/Features/Tools/CompositeToolExecutionTemplate.cs new file mode 100644 index 00000000..971d172e --- /dev/null +++ b/Source/Application/Features/Tools/CompositeToolExecutionTemplate.cs @@ -0,0 +1,165 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using RimMind.Application.Common.Models.Tools; +using RimMind.Domain.Common; +using RimMind.Domain.ValueObjects; + +namespace RimMind.Application.Features.Tools +{ + /// + /// Engine-free argument parsing, structured error construction, and guarded execution template + /// shared by composite ToolCall implementations (e.g. Presentation's CompositeToolCallBase). + /// Eliminates duplicated JSON parsing, preflight error handling, and exception-to-error boilerplate + /// across composite action tools. + /// + public static class CompositeToolExecutionTemplate + { + public static JObject? TryParseArgumentsObject(string? argumentsJson) + { + if (string.IsNullOrWhiteSpace(argumentsJson)) + return null; + + try + { + return JToken.Parse(argumentsJson!) as JObject; + } + catch + { + return null; + } + } + + public 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 || token.Type == JTokenType.Undefined) + 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; + } + } + + public static Result TryGetArgumentOrError(JObject? root, string key, string? traceId) + { + if (TryGetArgument(root, key, out T value)) + return Result.Ok(value); + + return Result.Err(InvalidActionError($"Missing or invalid {key}", traceId)); + } + + public static Result TryGetPawnIdOrError( + JObject? root, + ToolCallArgs args, + string key = "pawn_id") + { + if (args == null) + return Result.Err(InvalidActionError($"Missing or invalid {key}", null)); + + 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(InvalidActionError($"Missing or invalid {key}", args.TraceId)); + } + + public static RimMindError InvalidActionError(string message, string? traceId = null) + => new RimMindError(RimMindErrorCode.MechanismInvalidAction, message) { TraceId = traceId }; + + public static RimMindError PolicyDeniedError(string message, string? traceId = null) + => new RimMindError(RimMindErrorCode.ToolPolicyDenied, message) { TraceId = traceId }; + + public static RimMindError ExecutionFailedError(string message, string? traceId = null, Exception? inner = null) + => new RimMindError(RimMindErrorCode.ToolExecutionFailed, message) + { + TraceId = traceId, + InnerException = inner + }; + + /// + /// Runs the standard composite-tool execution sequence: + /// 1. Validates non-null args & cancellation; + /// 2. Parses JSON arguments once into a ; + /// 3. Executes optional preflight guard (e.g., main-thread / colonist liveness / autonomy check); + /// 4. Executes the tool body and converts unexpected exceptions into structured . + /// + public static async Task> ExecuteWithGuardsAsync( + string toolId, + ToolCallArgs? args, + Func>? preflightGuard, + Func>> body, + CancellationToken ct) + { + if (body == null) + throw new ArgumentNullException(nameof(body)); + + if (ct.IsCancellationRequested) + return Result.Err(RimMindErrors.Cancelled()); + + var effectiveArgs = args ?? new ToolCallArgs + { + ToolName = toolId, + ArgumentsJson = "{}" + }; + + var root = TryParseArgumentsObject(effectiveArgs.ArgumentsJson); + + if (preflightGuard != null) + { + var guardResult = preflightGuard(root, effectiveArgs); + if (guardResult.IsErr) + return Result.Err(guardResult.Error); + } + + try + { + return await body(root, effectiveArgs, ct).ConfigureAwait(false); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + return Result.Err(RimMindErrors.Cancelled()); + } + catch (Exception ex) + { + return Result.Err( + ExecutionFailedError($"Tool '{toolId}' failed: {ex.Message}", effectiveArgs.TraceId, ex)); + } + } + } +} diff --git a/Source/Application/Features/Tools/QueryToolHelpTool.cs b/Source/Application/Features/Tools/QueryToolHelpTool.cs index 756eb1ab..ba5143a2 100644 --- a/Source/Application/Features/Tools/QueryToolHelpTool.cs +++ b/Source/Application/Features/Tools/QueryToolHelpTool.cs @@ -8,7 +8,6 @@ using RimMind.Application.Common.Constants; using RimMind.Application.Common.Interfaces.Tools; using RimMind.Application.Common.Models.Tools; -using RimMind.Domain.Common; using RimMind.Domain.Enums; using RimMind.Domain.ValueObjects; @@ -35,7 +34,7 @@ public QueryToolHelpTool(IToolRegistry toolRegistry) Id = "query_tool_help", Category = "meta", Description = "Query parameter descriptions, schemas, and usage guidelines for registered AI tools. Can query a specific tool or list all available tools.", - ParametersSchema = "{\"type\":\"object\",\"properties\":{\"tool_name\":{\"type\":\"string\",\"description\":\"Name or Id of the tool to inspect (e.g. 'actions_place_blueprint', 'query_buildable_structures'). If omitted, returns all available tool IDs and brief summaries.\"}},\"required\":[]}", + ParametersSchema = "{\"type\":\"object\",\"properties\":{\"tool_name\":{\"type\":\"string\",\"description\":\"Name or Id of the tool to inspect (e.g. 'pawn.job.set', 'query_tool_help'). If omitted, returns all available tool IDs and brief summaries.\"}},\"required\":[]}", Manifest = new ToolManifest { OwnerModId = RimMindOwnerConsts.CoreModId, diff --git a/Source/Application/Features/Tools/ToolRegistry.cs b/Source/Application/Features/Tools/ToolRegistry.cs index c34b8188..51fe6de1 100644 --- a/Source/Application/Features/Tools/ToolRegistry.cs +++ b/Source/Application/Features/Tools/ToolRegistry.cs @@ -12,79 +12,97 @@ namespace RimMind.Application.Features.Tools { public sealed class ToolRegistry : IToolRegistry, IOwnedRegistry { + private readonly object _indexSync = new object(); private readonly ConcurrentDictionary _handlers = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); - private readonly ConcurrentDictionary _aliases + private readonly ConcurrentDictionary _normalizedAliases + = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); + private readonly ConcurrentDictionary _suffixIndex = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); - private readonly ILogSink? _log; - - internal static IToolRegistry? Current { get; private set; } - public ToolRegistry(ILogSink? log = null) - { - _log = log; - Current = this; - } + public ToolRegistry(ILogSink? log = null) { } public void Register(IToolHandler handler) { if (handler == null) return; - Current = this; - var canonicalId = handler.Definition.Id; - _handlers[canonicalId] = handler; - - var aliases = handler.Definition.Manifest?.Aliases; - if (aliases != null) + lock (_indexSync) { - for (int i = 0; i < aliases.Count; i++) - { - var alias = aliases[i]; - if (string.IsNullOrWhiteSpace(alias)) continue; - var trimmed = alias.Trim(); - _aliases[trimmed] = handler; - _aliases[trimmed.Replace('.', '_')] = handler; - _aliases[trimmed.Replace('_', '.')] = handler; - } + var canonicalId = handler.Definition.Id; + _handlers[canonicalId] = handler; + IndexHandlerLocked(handler); } } public bool Unregister(string toolId) { if (string.IsNullOrEmpty(toolId)) return false; - bool removed = _handlers.TryRemove(toolId, out var handler); - if (removed && handler != null) + lock (_indexSync) { - RemoveAliasesFor(handler); + bool removed = _handlers.TryRemove(toolId, out _); + if (removed) + { + RebuildSecondaryIndexesLocked(); + } + return removed; } - return removed; } /// public int UnregisterByOwner(string ownerModId) { if (ownerModId == null) throw new ArgumentNullException(nameof(ownerModId)); - var toRemove = _handlers.Values - .Where(h => h.OwnerModId == ownerModId) - .ToList(); - foreach (var handler in toRemove) + lock (_indexSync) { - _handlers.TryRemove(handler.Definition.Id, out _); - RemoveAliasesFor(handler); + var toRemove = _handlers.Values + .Where(h => h.OwnerModId == ownerModId) + .ToList(); + foreach (var handler in toRemove) + { + _handlers.TryRemove(handler.Definition.Id, out _); + } + if (toRemove.Count > 0) + { + RebuildSecondaryIndexesLocked(); + } + return toRemove.Count; } - return toRemove.Count; } - private void RemoveAliasesFor(IToolHandler handler) + private void IndexHandlerLocked(IToolHandler handler) { - var aliasKeys = _aliases - .Where(kvp => ReferenceEquals(kvp.Value, handler) || - string.Equals(kvp.Value.Definition.Id, handler.Definition.Id, StringComparison.OrdinalIgnoreCase)) - .Select(kvp => kvp.Key) - .ToList(); - for (int i = 0; i < aliasKeys.Count; i++) + var canonicalId = handler.Definition.Id; + var normalizedCanonical = canonicalId.Replace('.', '_'); + _normalizedAliases[normalizedCanonical] = handler; + + int sepIndex = normalizedCanonical.IndexOf('_'); + if (sepIndex > 0 && sepIndex + 1 < normalizedCanonical.Length) { - _aliases.TryRemove(aliasKeys[i], out _); + var suffix = normalizedCanonical.Substring(sepIndex + 1); + _suffixIndex[suffix] = handler; + } + + var aliases = handler.Definition.Manifest?.Aliases; + if (aliases != null) + { + for (int i = 0; i < aliases.Count; i++) + { + var alias = aliases[i]; + if (string.IsNullOrWhiteSpace(alias)) continue; + var trimmed = alias.Trim(); + _normalizedAliases[trimmed] = handler; + _normalizedAliases[trimmed.Replace('.', '_')] = handler; + } + } + } + + private void RebuildSecondaryIndexesLocked() + { + _normalizedAliases.Clear(); + _suffixIndex.Clear(); + foreach (var handler in _handlers.Values) + { + IndexHandlerLocked(handler); } } @@ -94,58 +112,11 @@ private void RemoveAliasesFor(IToolHandler handler) var trimmed = toolId.Trim(); if (_handlers.TryGetValue(trimmed, out var h)) return h; - if (_aliases.TryGetValue(trimmed, out h)) return h; - - if (trimmed.Contains(".")) - { - var underscored = trimmed.Replace('.', '_'); - if (_handlers.TryGetValue(underscored, out h)) return h; - if (_aliases.TryGetValue(underscored, out h)) return h; - } - if (trimmed.Contains("_")) - { - var dotted = trimmed.Replace('_', '.'); - if (_handlers.TryGetValue(dotted, out h)) return h; - if (_aliases.TryGetValue(dotted, out h)) return h; - } var targetNormalized = trimmed.Replace('.', '_'); - foreach (var kvp in _handlers) - { - if (string.Equals(kvp.Key.Replace('.', '_'), targetNormalized, StringComparison.OrdinalIgnoreCase)) - { - return kvp.Value; - } - - var manifestAliases = kvp.Value.Definition?.Manifest?.Aliases; - if (manifestAliases != null) - { - for (int i = 0; i < manifestAliases.Count; i++) - { - var alias = manifestAliases[i]; - if (!string.IsNullOrWhiteSpace(alias) && - string.Equals(alias.Trim().Replace('.', '_'), targetNormalized, StringComparison.OrdinalIgnoreCase)) - { - return kvp.Value; - } - } - } - } - - // Generic unqualified suffix match when a tool is registered under a module namespace prefix (e.g. "_" or ".") - foreach (var kvp in _handlers) - { - var normalizedKey = kvp.Key.Replace('.', '_'); - int sepIndex = normalizedKey.IndexOf('_'); - if (sepIndex > 0 && sepIndex + 1 < normalizedKey.Length) - { - var withoutPrefix = normalizedKey.Substring(sepIndex + 1); - if (string.Equals(withoutPrefix, targetNormalized, StringComparison.OrdinalIgnoreCase)) - { - return kvp.Value; - } - } - } + if (_normalizedAliases.TryGetValue(trimmed, out h)) return h; + if (_normalizedAliases.TryGetValue(targetNormalized, out h)) return h; + if (_suffixIndex.TryGetValue(targetNormalized, out h)) return h; return null; } diff --git a/Source/Application/Features/Tools/ToolScopeProjection.cs b/Source/Application/Features/Tools/ToolScopeProjection.cs index 96e944e1..ca555d9a 100644 --- a/Source/Application/Features/Tools/ToolScopeProjection.cs +++ b/Source/Application/Features/Tools/ToolScopeProjection.cs @@ -61,7 +61,15 @@ public static ToolScope ResolveScopes(ToolDefinition? definition) ToolScope inferred = ToolScope.None; - if (manifest?.DefaultDomain is AutonomyDomain domain) + AutonomyDomain? resolvedDomain = manifest?.DefaultDomain; + if (!resolvedDomain.HasValue + && !string.IsNullOrWhiteSpace(manifest?.AutonomyDomainId) + && Enum.TryParse(manifest!.AutonomyDomainId!.Trim(), ignoreCase: true, out var parsedDomain)) + { + resolvedDomain = parsedDomain; + } + + if (resolvedDomain is AutonomyDomain domain) { switch (domain) { diff --git a/Source/Application/RimMindCore.Application.csproj b/Source/Application/RimMindCore.Application.csproj index efc76817..e138ef2d 100644 --- a/Source/Application/RimMindCore.Application.csproj +++ b/Source/Application/RimMindCore.Application.csproj @@ -27,7 +27,4 @@ - - - diff --git a/Source/Domain/Agent/Policies/AgentAutonomyPolicy.cs b/Source/Domain/Agent/Policies/AgentAutonomyPolicy.cs index ff118973..82ad4666 100644 --- a/Source/Domain/Agent/Policies/AgentAutonomyPolicy.cs +++ b/Source/Domain/Agent/Policies/AgentAutonomyPolicy.cs @@ -9,6 +9,7 @@ namespace RimMind.Domain.Agent.Policies public sealed class AgentAutonomyPolicy { private readonly Dictionary _domainLevels = new(); + private readonly Dictionary _customDomainLevels = new(StringComparer.OrdinalIgnoreCase); public AgentAutonomyPolicy() { @@ -20,26 +21,62 @@ public AutonomyLevel GetLevel(AutonomyDomain domain) return _domainLevels.TryGetValue(domain, out var level) ? level : AutonomyLevel.RequireApproval; } + public AutonomyLevel GetLevel(string? domainId) + { + if (string.IsNullOrWhiteSpace(domainId)) + return AutonomyLevel.RequireApproval; + if (Enum.TryParse(domainId!.Trim(), ignoreCase: true, out var builtIn)) + return GetLevel(builtIn); + return _customDomainLevels.TryGetValue(domainId.Trim(), out var custom) ? custom : AutonomyLevel.RequireApproval; + } + public void SetLevel(AutonomyDomain domain, AutonomyLevel level) { _domainLevels[domain] = level; } + public void SetLevel(string domainId, AutonomyLevel level) + { + if (string.IsNullOrWhiteSpace(domainId)) return; + var trimmed = domainId.Trim(); + if (Enum.TryParse(trimmed, ignoreCase: true, out var builtIn)) + { + _domainLevels[builtIn] = level; + return; + } + _customDomainLevels[trimmed] = level; + } + public bool CanExecuteAutonomous(AutonomyDomain domain) { return GetLevel(domain) == AutonomyLevel.FullAutonomous; } + public bool CanExecuteAutonomous(string? domainId) + { + return GetLevel(domainId) == AutonomyLevel.FullAutonomous; + } + public bool RequiresApproval(AutonomyDomain domain) { return GetLevel(domain) == AutonomyLevel.RequireApproval; } + public bool RequiresApproval(string? domainId) + { + return GetLevel(domainId) == AutonomyLevel.RequireApproval; + } + public bool IsDisabled(AutonomyDomain domain) { return GetLevel(domain) == AutonomyLevel.Disabled; } + public bool IsDisabled(string? domainId) + { + return GetLevel(domainId) == AutonomyLevel.Disabled; + } + public void SetDefaultPreset() { _domainLevels[AutonomyDomain.EmergencySurvival] = AutonomyLevel.FullAutonomous; @@ -73,10 +110,15 @@ public void ApplyFullAutonomousPreset() public void CopyFrom(AgentAutonomyPolicy? other) { if (other == null) return; - foreach (AutonomyDomain domain in System.Enum.GetValues(typeof(AutonomyDomain))) + foreach (AutonomyDomain domain in Enum.GetValues(typeof(AutonomyDomain))) { _domainLevels[domain] = other.GetLevel(domain); } + _customDomainLevels.Clear(); + foreach (var kvp in other._customDomainLevels) + { + _customDomainLevels[kvp.Key] = kvp.Value; + } } public AgentAutonomyPolicy Clone() @@ -86,6 +128,10 @@ public AgentAutonomyPolicy Clone() { clone._domainLevels[kvp.Key] = kvp.Value; } + foreach (var kvp in _customDomainLevels) + { + clone._customDomainLevels[kvp.Key] = kvp.Value; + } return clone; } diff --git a/Source/Domain/Common/ThreadAffinityAttribute.cs b/Source/Domain/Common/ThreadAffinityAttribute.cs index 06dc2b1c..9f015dfb 100644 --- a/Source/Domain/Common/ThreadAffinityAttribute.cs +++ b/Source/Domain/Common/ThreadAffinityAttribute.cs @@ -1,21 +1,22 @@ using System; -namespace RimMind.Domain.Common; - -public enum ThreadAffinityKind -{ - MainOnly, - BackgroundOnly, - Any -} - -[AttributeUsage(AttributeTargets.Method | AttributeTargets.Interface)] -public class ThreadAffinityAttribute : Attribute +namespace RimMind.Domain.Common { - public ThreadAffinityKind Kind { get; } + public enum ThreadAffinityKind + { + MainOnly, + BackgroundOnly, + Any + } - public ThreadAffinityAttribute(ThreadAffinityKind kind) + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Interface)] + public class ThreadAffinityAttribute : Attribute { - Kind = kind; + public ThreadAffinityKind Kind { get; } + + public ThreadAffinityAttribute(ThreadAffinityKind kind) + { + Kind = kind; + } } } diff --git a/Source/Domain/Enums/AgentAutonomyLevel.cs b/Source/Domain/Enums/AgentAutonomyLevel.cs index 5269a442..32d7769e 100644 --- a/Source/Domain/Enums/AgentAutonomyLevel.cs +++ b/Source/Domain/Enums/AgentAutonomyLevel.cs @@ -1,7 +1,8 @@ namespace RimMind.Domain.Enums { /// - /// Controls how much autonomy an agent has in executing decisions. + /// Global risk-threshold autonomy setting persisted in ModSettings (coarse gate). + /// Distinct from per-domain used by . /// /// Manual — Agent only thinks; every decision requires player approval. /// Guided — Low/Medium risk actions auto-execute; High/Critical require approval. diff --git a/Source/Domain/Llm/LlmHintKeys.cs b/Source/Domain/Llm/LlmHintKeys.cs new file mode 100644 index 00000000..9d702ac3 --- /dev/null +++ b/Source/Domain/Llm/LlmHintKeys.cs @@ -0,0 +1,15 @@ +namespace RimMind.Domain.Llm +{ + /// + /// Canonical keys used in . + /// Centralizes request-hint keys so pipeline stages, clients, and submodules do not rely on magic strings. + /// + public static class LlmHintKeys + { + public const string ProviderId = "ProviderId"; + public const string RolloutId = "rollout_id"; + public const string TurnIndex = "turn_index"; + public const string IsMonologue = "IsMonologue"; + public const string SessionId = "session_id"; + } +} diff --git a/Source/Domain/Storage/IVectorIndex.cs b/Source/Domain/Storage/IVectorIndex.cs deleted file mode 100644 index 3f922e66..00000000 --- a/Source/Domain/Storage/IVectorIndex.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using RimMind.Domain.ValueObjects; - -namespace RimMind.Domain.Storage -{ - /// - /// Semantic search index. Skeleton only — implementation deferred to Phase 3. - /// - public interface IVectorIndex - { - string ProviderName { get; } - bool IsConfigured { get; } - - Task, RimMindError>> SearchAsync(string query, int limit, CancellationToken ct); - Task> IndexAsync(MemoryEntry entry, CancellationToken ct); - } -} diff --git a/Source/Domain/Storage/MemoryHit.cs b/Source/Domain/Storage/MemoryHit.cs deleted file mode 100644 index b9fd175c..00000000 --- a/Source/Domain/Storage/MemoryHit.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace RimMind.Domain.Storage -{ - public sealed record MemoryHit - { - public string Key { get; init; } = ""; - public string Content { get; init; } = ""; - public float Score { get; init; } - public string? Source { get; init; } - } -} diff --git a/Source/Infrastructure/Agent/MechanismActionExecutor.cs b/Source/Infrastructure/Agent/MechanismActionExecutor.cs index 8255f675..07144c26 100644 --- a/Source/Infrastructure/Agent/MechanismActionExecutor.cs +++ b/Source/Infrastructure/Agent/MechanismActionExecutor.cs @@ -102,7 +102,7 @@ private Result ExecuteTool(IToolHandler tool, AgentDecision string argsJson = AdaptToolArguments(tool, decision, pawnId); var toolArgs = new ToolCallArgs { - ToolCallId = string.IsNullOrEmpty(decision.ToolCallId) ? Guid.NewGuid().ToString("N") : decision.ToolCallId, + ToolCallId = string.IsNullOrEmpty(decision.ToolCallId) ? Guid.NewGuid().ToString("N") : decision.ToolCallId!, ToolName = tool.Definition.Id, ArgumentsJson = argsJson, PawnId = pawnId > 0 ? pawnId : (int?)null, @@ -141,12 +141,12 @@ private string AdaptToolArguments(IToolHandler tool, AgentDecision decision, int try { var parsed = JToken.Parse(decision.Param!); - obj = parsed as JObject ?? BuildObjectFromScalarParam(toolId, parsed.Type == JTokenType.String ? parsed.Value() : parsed.ToString()); + obj = parsed as JObject ?? BuildObjectFromScalarParam(parsed.Type == JTokenType.String ? parsed.Value() : parsed.ToString()); } catch { - // Plain text Param (e.g. "Construction"): keep it as the def target instead of discarding it. - obj = BuildObjectFromScalarParam(toolId, decision.Param); + // Plain text Param (e.g. "Construction"): preserve it as def_name for adapters/tools. + obj = BuildObjectFromScalarParam(decision.Param); } } else @@ -156,10 +156,7 @@ private string AdaptToolArguments(IToolHandler tool, AgentDecision decision, int if (pawnId > 0) { - bool isSelfTargetedTool = - tool.Definition?.Manifest?.IsSelfTargeted == true || - string.Equals(toolId, "prioritize_work", StringComparison.OrdinalIgnoreCase) || - string.Equals(toolId, "take_job", StringComparison.OrdinalIgnoreCase); + bool isSelfTargetedTool = tool.Definition?.Manifest?.IsSelfTargeted == true; // Only fill pawn_id when it is missing or unparseable. An explicit but non-resolving id must // reach the mechanism and fail there; silently redirecting it to the caller made target-style @@ -191,30 +188,6 @@ private string AdaptToolArguments(IToolHandler tool, AgentDecision decision, int } } - if (string.Equals(toolId, "pawn.job.set", StringComparison.OrdinalIgnoreCase) || - string.Equals(toolId, "pawn_job_set", StringComparison.OrdinalIgnoreCase)) - { - string? currentAction = obj.Value("action"); - if (string.IsNullOrWhiteSpace(currentAction) || - string.Equals(currentAction, "set", StringComparison.OrdinalIgnoreCase)) - { - if (obj["work_type"] != null || obj["job_type"] != null || obj["def_name"] != null) - { - obj["action"] = "assign_work"; - } - else if (obj["cell_x"] != null || obj["x"] != null) - { - obj["action"] = "move_to"; - } - else if (ContainsFoodKeyword(decision.Param) || ContainsFoodKeyword(decision.Reason)) - { - obj["action"] = "eat_food"; - } - // Otherwise leave 'action' unset: pawn.job rejects it with the list of valid operations. - // A silent force_rest default made colonists lie down instead of working or eating. - } - } - var adapters = GetArgumentAdapters(); if (adapters != null) { @@ -233,44 +206,16 @@ private string AdaptToolArguments(IToolHandler tool, AgentDecision decision, int return obj.ToString(Newtonsoft.Json.Formatting.None); } - private static JObject BuildObjectFromScalarParam(string toolId, string? raw) + private static JObject BuildObjectFromScalarParam(string? raw) { var obj = new JObject(); var value = raw?.Trim().Trim('"'); if (string.IsNullOrWhiteSpace(value)) return obj; - // pawn.job.set resolves its sub-action from keywords below; a def target would force assign_work. - if (string.Equals(toolId, "pawn.job.set", StringComparison.OrdinalIgnoreCase) - || string.Equals(toolId, "pawn_job_set", StringComparison.OrdinalIgnoreCase)) - return obj; - obj["def_name"] = value; - if (IsWorkPriorityTool(toolId)) - { - obj["work_type"] = value; - obj["priority"] = 1; - } return obj; } - private static bool IsWorkPriorityTool(string toolId) - { - return string.Equals(toolId, "pawn.work.set", StringComparison.OrdinalIgnoreCase) - || string.Equals(toolId, "pawn_work_set", StringComparison.OrdinalIgnoreCase) - || string.Equals(toolId, "prioritize_work", StringComparison.OrdinalIgnoreCase); - } - - private static readonly System.Text.RegularExpressions.Regex FoodKeywordPattern = new System.Text.RegularExpressions.Regex( - @"\b(eat|eating|food|meal|meals|hunger|hungry|starving|starvation|nutrition)\b", - System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.CultureInvariant); - - private static bool ContainsFoodKeyword(string? text) - { - if (string.IsNullOrEmpty(text)) return false; - // Whole words only: substring matching turned "retreat from the threat" into eat_food. - return FoodKeywordPattern.IsMatch(text!); - } - private IReadOnlyList? GetArgumentAdapters() { if (_argumentAdapterProvider != null) diff --git a/Source/Infrastructure/DependencyInjection.cs b/Source/Infrastructure/DependencyInjection.cs index b413c493..b49de46f 100644 --- a/Source/Infrastructure/DependencyInjection.cs +++ b/Source/Infrastructure/DependencyInjection.cs @@ -27,7 +27,6 @@ public sealed class InfrastructureServiceBag public IAudioPlayer AudioPlayer { get; init; } = null!; public ITickProvider TickProvider { get; init; } = null!; public IThreadChecker ThreadChecker { get; init; } = null!; - public IPathProvider PathProvider { get; init; } = null!; public ILogSink LogSink { get; init; } = null!; public ITranslationService TranslationService { get; init; } = null!; public IGameMechanismRegistry MechanismRegistry { get; init; } = null!; @@ -49,8 +48,6 @@ public static InfrastructureServiceBag AddInfrastructureServices( var threadChecker = new VerseThreadChecker(); - var pathProvider = new VersePathProvider(); - var logSink = new VerseLogSink(); var translationService = new VerseTranslationService(); @@ -70,7 +67,6 @@ public static InfrastructureServiceBag AddInfrastructureServices( AudioPlayer = audioPlayer, TickProvider = tickProvider, ThreadChecker = threadChecker, - PathProvider = pathProvider, LogSink = logSink, TranslationService = translationService, MechanismRegistry = mechanismRegistry, @@ -81,12 +77,6 @@ public static InfrastructureServiceBag AddInfrastructureServices( }; } - public static void AddGameDependentServices() - { - // Verse creates save-owned components. RimMindRuntimeGameComponent - // publishes them together after StartedNewGame/LoadedGame. - } - public static void RegisterBuiltinClientFactories(IExtensionRegistry registry, ILogSink? logSink = null, IOpenAISettings? openAISettings = null) { diff --git a/Source/Infrastructure/Mechanisms/MechanismListToolHandler.cs b/Source/Infrastructure/Mechanisms/MechanismListToolHandler.cs index d96ddffd..b87d00e0 100644 --- a/Source/Infrastructure/Mechanisms/MechanismListToolHandler.cs +++ b/Source/Infrastructure/Mechanisms/MechanismListToolHandler.cs @@ -33,7 +33,7 @@ public MechanismListToolHandler(IMechanismReader reader, IMechanismMetadata meta public string Id => Definition.Id; public string OwnerModId => string.IsNullOrWhiteSpace(_metadata?.OwnerModId) ? RimMindOwnerConsts.CoreModId - : _metadata.OwnerModId; + : _metadata!.OwnerModId; public ToolDefinition Definition { get; } public async Task> ExecuteAsync(ToolCallArgs args, CancellationToken ct) @@ -66,7 +66,7 @@ public async Task> ExecuteAsync(ToolCallArgs ar var items = result.Value; if (!string.IsNullOrEmpty(category) && items != null) { - items = FilterByCategory(items, category); + items = FilterByCategory(items, category!); } return Result.Ok(new ToolResult diff --git a/Source/Infrastructure/Mechanisms/MechanismToolHandler.cs b/Source/Infrastructure/Mechanisms/MechanismToolHandler.cs index bfab7842..6b212d13 100644 --- a/Source/Infrastructure/Mechanisms/MechanismToolHandler.cs +++ b/Source/Infrastructure/Mechanisms/MechanismToolHandler.cs @@ -87,7 +87,7 @@ public MechanismToolHandler( public string Id => Definition.Id; public string OwnerModId => string.IsNullOrWhiteSpace(_metadata?.OwnerModId) ? RimMindOwnerConsts.CoreModId - : _metadata.OwnerModId; + : _metadata!.OwnerModId; public ToolDefinition Definition { get; } public async Task> ExecuteAsync(ToolCallArgs args, CancellationToken ct) @@ -244,7 +244,7 @@ private MechanismWriteArgs BuildWriteArgs(JObject? root, ToolCallArgs args, int try { - return JObject.Parse(json); + return JObject.Parse(json!); } catch (Exception) { @@ -628,6 +628,13 @@ private static ToolScope ResolveMechanismScopes( MechanismOperationType operation, RimMind.Domain.Agent.Policies.AutonomyDomain? defaultDomain) { + if (metadata is IMechanismScopeMetadata scopeMetadata) + { + var declared = scopeMetadata.GetToolScopeForOperation(operation); + if (declared.HasValue) + return declared.Value; + } + if (operation == MechanismOperationType.List) return ToolScope.MetaQuery; @@ -644,17 +651,7 @@ private static ToolScope ResolveMechanismScopes( 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; } diff --git a/Source/Infrastructure/Mechanisms/Pawn/Health/HealthMechanism.cs b/Source/Infrastructure/Mechanisms/Pawn/Health/HealthMechanism.cs index 9d8ce1c3..a6a722c3 100644 --- a/Source/Infrastructure/Mechanisms/Pawn/Health/HealthMechanism.cs +++ b/Source/Infrastructure/Mechanisms/Pawn/Health/HealthMechanism.cs @@ -41,7 +41,7 @@ public override Task> ExecuteQueryAsync(MechanismRe var hediff = pawn.health?.hediffSet?.hediffs? .FirstOrDefault(h => h.def.defName == args.DefName); if (hediff == null) - return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(args.DefName))); + return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(args.DefName!))); var info = new { diff --git a/Source/Infrastructure/Mechanisms/Pawn/Inspiration/InspirationMechanism.cs b/Source/Infrastructure/Mechanisms/Pawn/Inspiration/InspirationMechanism.cs index f6eb9efb..88cd3623 100644 --- a/Source/Infrastructure/Mechanisms/Pawn/Inspiration/InspirationMechanism.cs +++ b/Source/Infrastructure/Mechanisms/Pawn/Inspiration/InspirationMechanism.cs @@ -56,9 +56,9 @@ public override Task> ExecuteTriggerAsync(MechanismWr if (string.IsNullOrEmpty(args.DefName)) return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(""))); - var inspirationDef = FindDef(args.DefName); + var inspirationDef = FindDef(args.DefName!); if (inspirationDef == null) - return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(args.DefName))); + return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(args.DefName!))); pawn.mindState?.inspirationHandler?.TryStartInspiration(inspirationDef); return Task.FromResult(Result.Ok(true)); diff --git a/Source/Infrastructure/Mechanisms/Pawn/Interaction/InteractionMechanism.cs b/Source/Infrastructure/Mechanisms/Pawn/Interaction/InteractionMechanism.cs index a514d3d6..54f2a290 100644 --- a/Source/Infrastructure/Mechanisms/Pawn/Interaction/InteractionMechanism.cs +++ b/Source/Infrastructure/Mechanisms/Pawn/Interaction/InteractionMechanism.cs @@ -5,6 +5,7 @@ using Newtonsoft.Json; using RimMind.Application.Common.Interfaces.Mechanisms; using RimMind.Application.Common.Models.Mechanisms; +using RimMind.Application.Common.Models.Tools; using RimMind.Domain.Enums; using RimMind.Domain.ValueObjects; using Verse; @@ -13,7 +14,7 @@ namespace RimMind.Infrastructure.Mechanisms.Pawn.Interaction { - public sealed class InteractionMechanism : GameMechanismBase + public sealed class InteractionMechanism : GameMechanismBase, IMechanismScopeMetadata { public override string MechanismId => "pawn.interaction"; public override MechanismScope Scope => MechanismScope.Pawn; @@ -21,6 +22,11 @@ public sealed class InteractionMechanism : GameMechanismBase public override IReadOnlyList SupportedOperations => _supportedOps; public override MechanismDocs Docs => _docs; + public ToolScope? GetToolScopeForOperation(MechanismOperationType operation) + => operation is MechanismOperationType.Query or MechanismOperationType.List + ? ToolScope.MetaQuery + : ToolScope.Social | ToolScope.ColonistSelf; + private static readonly IReadOnlyList _supportedOps = new List { MechanismOperationType.Query, MechanismOperationType.Trigger }.AsReadOnly(); diff --git a/Source/Infrastructure/Mechanisms/Pawn/Job/JobActionDispatcher.cs b/Source/Infrastructure/Mechanisms/Pawn/Job/JobActionDispatcher.cs index e5e92051..710c9c33 100644 --- a/Source/Infrastructure/Mechanisms/Pawn/Job/JobActionDispatcher.cs +++ b/Source/Infrastructure/Mechanisms/Pawn/Job/JobActionDispatcher.cs @@ -15,12 +15,6 @@ namespace RimMind.Infrastructure.Mechanisms.Pawn.Job { public static class JobActionDispatcher { - [ThreadStatic] - private static bool _captureJobForQueue; - - [ThreadStatic] - private static VerseJob? _capturedQueueJob; - /// /// Starts a forced job and verifies the game actually accepted it. StartJob can silently /// refuse (mental state, drafted pawn, failed reservation, job ending on its first toil); @@ -30,11 +24,6 @@ public static Result StartJobVerified(VersePawn pawn, VerseJ { if (pawn?.jobs == null || job == null) return Result.Err(RimMindErrors.InvalidAction(mechanismId, "no job tracker or job")); - if (_captureJobForQueue) - { - _capturedQueueJob = job; - return Result.Ok(true); - } pawn.jobs.StartJob(job, JobCondition.InterruptForced); if (!ReferenceEquals(pawn.CurJob, job)) { @@ -44,8 +33,50 @@ public static Result StartJobVerified(VersePawn pawn, VerseJ } return Result.Ok(true); } + + private static Result StartBuiltJob(VersePawn pawn, Result built) + { + if (built.IsErr) + return Result.Err(built.Error); + return StartJobVerified(pawn, built.Value); + } + public static Result HandleAssignWork(VersePawn pawn, MechanismWriteArgs args) { + if (TryBuildAssignWorkJob(pawn, args, allowPriorityOverrideFallback: true, out var job, out var handledByOverride, out var error)) + { + if (job != null) + return StartJobVerified(pawn, job); + + if (handledByOverride) + { + try + { + pawn.jobs?.CheckForJobOverride(); + } + catch + { + // Ignore job override transient errors + } + return Result.Ok(true); + } + } + + return Result.Err(error ?? RimMindErrors.Internal("assign_work failed")); + } + + private static bool TryBuildAssignWorkJob( + VersePawn pawn, + MechanismWriteArgs args, + bool allowPriorityOverrideFallback, + out VerseJob? job, + out bool handledByOverride, + out RimMindError? error) + { + job = null; + handledByOverride = false; + error = null; + var workType = ExtractParam(args, "work_type") ?? ExtractParam(args, "job_type") ?? args.DefName; if (string.IsNullOrEmpty(workType)) { @@ -61,14 +92,21 @@ public static Result HandleAssignWork(VersePawn pawn, Mechan anyWork = null; } if (anyWork == null) - return Result.Err(RimMindErrors.InvalidAction("pawn.job", "assign_work: missing work_type and no available work found")); - return StartJobVerified(pawn, anyWork); + { + error = RimMindErrors.InvalidAction("pawn.job", "assign_work: missing work_type and no available work found"); + return false; + } + job = anyWork; + return true; } var candidateGivers = ResolveCandidateWorkGivers(workType!); var workTypeDef = ResolveWorkTypeDef(workType!, candidateGivers); if (candidateGivers.Count == 0 && workTypeDef == null) - return Result.Err(RimMindErrors.InvalidDefName(workType ?? "")); + { + error = RimMindErrors.InvalidDefName(workType ?? ""); + return false; + } bool priorityUpdated = false; if (workTypeDef != null @@ -89,28 +127,23 @@ public static Result HandleAssignWork(VersePawn pawn, Mechan if (workGiver?.Worker == null) continue; if (workGiver.workType != null && pawn.WorkTypeIsDisabled(workGiver.workType)) continue; - var job = TryFindJobFromGiver(pawn, workGiver); - if (job != null) + var candidateJob = TryFindJobFromGiver(pawn, workGiver); + if (candidateJob != null) { - job.workGiverDef = workGiver; - return StartJobVerified(pawn, job); + candidateJob.workGiverDef = workGiver; + job = candidateJob; + return true; } } - if (!_captureJobForQueue && (priorityUpdated || (workTypeDef != null && !pawn.WorkTypeIsDisabled(workTypeDef)))) + if (allowPriorityOverrideFallback && (priorityUpdated || (workTypeDef != null && !pawn.WorkTypeIsDisabled(workTypeDef)))) { - try - { - pawn.jobs?.CheckForJobOverride(); - } - catch - { - // Ignore job override transient errors - } - return Result.Ok(true); + handledByOverride = true; + return true; } - return Result.Err(RimMindErrors.Internal($"No actionable target on map for work/job '{workType}'")); + error = RimMindErrors.Internal($"No actionable target on map for work/job '{workType}'"); + return false; } private static WorkTypeDef? ResolveWorkTypeDef(string rawType, System.Collections.Generic.List candidateGivers) @@ -264,34 +297,39 @@ private static System.Collections.Generic.List ResolveCandidateWor } public static Result HandleMoveTo(VersePawn pawn, MechanismWriteArgs args) + => StartBuiltJob(pawn, TryBuildMoveToJob(pawn, args)); + + private static Result TryBuildMoveToJob(VersePawn pawn, MechanismWriteArgs args) { var cellX = ExtractIntParam(args, "cell_x"); var cellZ = ExtractIntParam(args, "cell_z"); if (cellX == 0 && cellZ == 0) - return Result.Err(RimMindErrors.InvalidAction("pawn.job", "move_to: missing cell_x/cell_z")); + return Result.Err(RimMindErrors.InvalidAction("pawn.job", "move_to: missing cell_x/cell_z")); var map = pawn.Map; if (map == null) - return Result.Err(RimMindErrors.InvalidAction("pawn.job", "move_to: pawn has no map")); + return Result.Err(RimMindErrors.InvalidAction("pawn.job", "move_to: pawn has no map")); var cell = new IntVec3(cellX, 0, cellZ); if (!cell.IsValid || !cell.InBounds(map)) - return Result.Err(RimMindErrors.InvalidAction("pawn.job", "move_to: invalid or out of bounds cell")); + return Result.Err(RimMindErrors.InvalidAction("pawn.job", "move_to: invalid or out of bounds cell")); if (cell.Fogged(map)) - return Result.Err(RimMindErrors.InvalidAction("pawn.job", "move_to: cell is fogged")); + return Result.Err(RimMindErrors.InvalidAction("pawn.job", "move_to: cell is fogged")); if (!cell.Standable(map)) - return Result.Err(RimMindErrors.InvalidAction("pawn.job", "move_to: cell is not standable")); + return Result.Err(RimMindErrors.InvalidAction("pawn.job", "move_to: cell is not standable")); if (!pawn.CanReach(cell, PathEndMode.OnCell, Danger.Deadly)) - return Result.Err(RimMindErrors.InvalidAction("pawn.job", "move_to: cannot reach cell")); + return Result.Err(RimMindErrors.InvalidAction("pawn.job", "move_to: cannot reach cell")); - var job = JobMaker.MakeJob(JobDefOf.Goto, new LocalTargetInfo(cell)); - return StartJobVerified(pawn, job); + return Result.Ok(JobMaker.MakeJob(JobDefOf.Goto, new LocalTargetInfo(cell))); } public static Result HandleEatFood(VersePawn pawn, MechanismWriteArgs args) + => StartBuiltJob(pawn, TryBuildEatFoodJob(pawn, args)); + + private static Result TryBuildEatFoodJob(VersePawn pawn, MechanismWriteArgs args) { var food = pawn.inventory?.innerContainer?.FirstOrDefault( t => t != null && !t.Destroyed && t.def != null && t.def.IsNutritionGivingIngestible && t.IngestibleNow); @@ -361,18 +399,18 @@ public static Result HandleEatFood(VersePawn pawn, Mechanism var harvestPlantJob = TryDesignateAndHarvestWildFoodPlant(pawn, map); if (harvestPlantJob != null) { - return StartJobVerified(pawn, harvestPlantJob); + return Result.Ok(harvestPlantJob); } } if (food == null) { - return Result.Err(RimMindErrors.InvalidAction("pawn.job", "eat_food: no available food found")); + return Result.Err(RimMindErrors.InvalidAction("pawn.job", "eat_food: no available food found")); } var job = JobMaker.MakeJob(JobDefOf.Ingest, new LocalTargetInfo(food)); job.count = System.Math.Max(1, FoodUtility.WillIngestStackCountOf(pawn, food.def, food.GetStatValue(StatDefOf.Nutrition))); - return StartJobVerified(pawn, job); + return Result.Ok(job); } private static VerseJob? TryDesignateAndHarvestWildFoodPlant(VersePawn pawn, global::Verse.Map map) @@ -458,57 +496,69 @@ public static Result HandleEatFood(VersePawn pawn, Mechanism } public static Result HandleForceRest(VersePawn pawn, MechanismWriteArgs args) + => StartBuiltJob(pawn, TryBuildForceRestJob(pawn, args)); + + private static Result TryBuildForceRestJob(VersePawn pawn, MechanismWriteArgs args) { var bed = RestUtility.FindBedFor(pawn); var job = bed != null ? JobMaker.MakeJob(JobDefOf.LayDown, new LocalTargetInfo(bed)) : JobMaker.MakeJob(JobDefOf.LayDown, pawn.Position); - return StartJobVerified(pawn, job); + return Result.Ok(job); } public static Result HandleTendPawn(VersePawn pawn, MechanismWriteArgs args) + => StartBuiltJob(pawn, TryBuildTendPawnJob(pawn, args)); + + private static Result TryBuildTendPawnJob(VersePawn pawn, MechanismWriteArgs args) { var targetPawnId = ExtractIntParam(args, "target_pawn_id"); var targetPawn = FindTargetPawnOnSameMap(pawn, targetPawnId); if (targetPawn == null) - return Result.Err(RimMindErrors.PawnNotFound(targetPawnId)); + return Result.Err(RimMindErrors.PawnNotFound(targetPawnId)); if (!pawn.CanReserveAndReach(targetPawn, PathEndMode.Touch, Danger.Deadly)) - return Result.Err(RimMindErrors.InvalidAction("pawn.job", "tend_pawn: cannot reserve or reach target pawn")); + return Result.Err(RimMindErrors.InvalidAction("pawn.job", "tend_pawn: cannot reserve or reach target pawn")); var job = JobMaker.MakeJob(JobDefOf.TendPatient, new LocalTargetInfo(targetPawn)); job.count = 1; - return StartJobVerified(pawn, job); + return Result.Ok(job); } public static Result HandleRescuePawn(VersePawn pawn, MechanismWriteArgs args) + => StartBuiltJob(pawn, TryBuildRescuePawnJob(pawn, args)); + + private static Result TryBuildRescuePawnJob(VersePawn pawn, MechanismWriteArgs args) { var targetPawnId = ExtractIntParam(args, "target_pawn_id"); var targetPawn = FindTargetPawnOnSameMap(pawn, targetPawnId); if (targetPawn == null) - return Result.Err(RimMindErrors.PawnNotFound(targetPawnId)); + return Result.Err(RimMindErrors.PawnNotFound(targetPawnId)); Building_Bed bed = RestUtility.FindBedFor(targetPawn, pawn, checkSocialProperness: false, ignoreOtherReservations: false, targetPawn.GuestStatus); if (bed == null || !pawn.CanReserveAndReach(targetPawn, PathEndMode.OnCell, Danger.Deadly)) - return Result.Err(RimMindErrors.InvalidAction("pawn.job", "rescue_pawn: no available bed or cannot reserve/reach target pawn")); + return Result.Err(RimMindErrors.InvalidAction("pawn.job", "rescue_pawn: no available bed or cannot reserve/reach target pawn")); var job = JobMaker.MakeJob(JobDefOf.Rescue, targetPawn, bed); job.count = 1; - return StartJobVerified(pawn, job); + return Result.Ok(job); } public static Result HandleArrestPawn(VersePawn pawn, MechanismWriteArgs args) + => StartBuiltJob(pawn, TryBuildArrestPawnJob(pawn, args)); + + private static Result TryBuildArrestPawnJob(VersePawn pawn, MechanismWriteArgs args) { var targetPawnId = ExtractIntParam(args, "target_pawn_id"); var targetPawn = FindTargetPawnOnSameMap(pawn, targetPawnId); if (targetPawn == null) - return Result.Err(RimMindErrors.PawnNotFound(targetPawnId)); + return Result.Err(RimMindErrors.PawnNotFound(targetPawnId)); Building_Bed bed = RestUtility.FindBedFor(targetPawn, pawn, checkSocialProperness: false, ignoreOtherReservations: false, GuestStatus.Prisoner); if (bed == null || !pawn.CanReserveAndReach(targetPawn, PathEndMode.OnCell, Danger.Deadly)) - return Result.Err(RimMindErrors.InvalidAction("pawn.job", "arrest_pawn: no available prisoner bed or cannot reserve/reach target pawn")); + return Result.Err(RimMindErrors.InvalidAction("pawn.job", "arrest_pawn: no available prisoner bed or cannot reserve/reach target pawn")); var job = JobMaker.MakeJob(JobDefOf.Arrest, targetPawn, bed); job.count = 1; - return StartJobVerified(pawn, job); + return Result.Ok(job); } public static Result HandleCancelJob(VersePawn pawn, MechanismWriteArgs args) @@ -758,41 +808,40 @@ private static bool TryBuildJobWithoutStarting( builtJob = null; error = null; - bool prevCapture = _captureJobForQueue; - VerseJob? prevJob = _capturedQueueJob; - try + if (subAction == "assign_work" || subAction == "take_job") { - _captureJobForQueue = true; - _capturedQueueJob = null; - - Result res = subAction switch + if (TryBuildAssignWorkJob(pawn, subArgs, allowPriorityOverrideFallback: false, out var workJob, out _, out var workError) + && workJob != null) { - "assign_work" or "take_job" => HandleAssignWork(pawn, subArgs), - "move_to" => HandleMoveTo(pawn, subArgs), - "eat_food" => HandleEatFood(pawn, subArgs), - "force_rest" => HandleForceRest(pawn, subArgs), - "tend_pawn" => HandleTendPawn(pawn, subArgs), - "rescue_pawn" => HandleRescuePawn(pawn, subArgs), - "arrest_pawn" => HandleArrestPawn(pawn, subArgs), - _ => Result.Err(RimMindErrors.InvalidAction("pawn.job", $"unsupported queued sub-action '{subAction}'")) - }; - - if (res.IsOk && _capturedQueueJob != null) - { - builtJob = _capturedQueueJob; + builtJob = workJob; return true; } - error = res.IsErr - ? res.Error - : RimMindErrors.InvalidAction("pawn.job", $"failed to build queueable job for '{subAction}'"); + error = workError ?? RimMindErrors.InvalidAction("pawn.job", $"failed to build queueable job for '{subAction}'"); return false; } - finally + + Result res = subAction switch { - _captureJobForQueue = prevCapture; - _capturedQueueJob = prevJob; + "move_to" => TryBuildMoveToJob(pawn, subArgs), + "eat_food" => TryBuildEatFoodJob(pawn, subArgs), + "force_rest" => TryBuildForceRestJob(pawn, subArgs), + "tend_pawn" => TryBuildTendPawnJob(pawn, subArgs), + "rescue_pawn" => TryBuildRescuePawnJob(pawn, subArgs), + "arrest_pawn" => TryBuildArrestPawnJob(pawn, subArgs), + _ => Result.Err(RimMindErrors.InvalidAction("pawn.job", $"unsupported queued sub-action '{subAction}'")) + }; + + if (res.IsOk && res.Value != null) + { + builtJob = res.Value; + return true; } + + error = res.IsErr + ? res.Error + : RimMindErrors.InvalidAction("pawn.job", $"failed to build queueable job for '{subAction}'"); + return false; } private static string? ExtractParam(MechanismWriteArgs args, string key) diff --git a/Source/Infrastructure/Mechanisms/Pawn/Job/JobMechanismArgumentAdapter.cs b/Source/Infrastructure/Mechanisms/Pawn/Job/JobMechanismArgumentAdapter.cs new file mode 100644 index 00000000..0334eac6 --- /dev/null +++ b/Source/Infrastructure/Mechanisms/Pawn/Job/JobMechanismArgumentAdapter.cs @@ -0,0 +1,77 @@ +using System; +using System.Text.RegularExpressions; +using Newtonsoft.Json.Linq; +using RimMind.Application.Common.Constants; +using RimMind.Application.Common.Interfaces.Tools; +using RimMind.Domain.Agent.Modes; + +namespace RimMind.Infrastructure.Mechanisms.Pawn.Job +{ + /// + /// Adapts LLM tool arguments for Core's pawn.job.set / pawn_job_set tool: + /// prevents plain-text scalar parameters from being misread as def_name work targets, + /// and infers concrete sub-actions (assign_work, move_to, eat_food) without + /// silently defaulting argument-less calls to force_rest. + /// + public sealed class JobMechanismArgumentAdapter : IToolArgumentAdapter + { + private static readonly Regex FoodKeywordPattern = new Regex( + @"\b(eat|eating|food|meal|meals|hunger|hungry|starving|starvation|nutrition)\b", + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + public string Id => "core.tool_adapter.pawn_job"; + + public string OwnerModId => RimMindOwnerConsts.CoreModId; + + public bool CanAdapt(string toolId) + { + return string.Equals(toolId, "pawn.job.set", StringComparison.OrdinalIgnoreCase) + || string.Equals(toolId, "pawn_job_set", StringComparison.OrdinalIgnoreCase); + } + + public JObject AdaptArguments(string toolId, JObject args, AgentDecision decision, int callerPawnId) + { + if (args == null) + args = new JObject(); + + // Plain-text Param is placed into def_name by generic scalar fallback; + // for pawn.job.set a scalar phrase like "eat a meal" must not force assign_work. + string? rawScalar = decision?.Param?.Trim().Trim('"'); + if (!string.IsNullOrWhiteSpace(rawScalar) + && !rawScalar!.StartsWith("{", StringComparison.Ordinal) + && args["def_name"] != null + && string.Equals(args.Value("def_name"), rawScalar, StringComparison.Ordinal)) + { + args.Remove("def_name"); + } + + string? currentAction = args.Value("action"); + if (string.IsNullOrWhiteSpace(currentAction) + || string.Equals(currentAction, "set", StringComparison.OrdinalIgnoreCase)) + { + if (args["work_type"] != null || args["job_type"] != null || args["def_name"] != null) + { + args["action"] = "assign_work"; + } + else if (args["cell_x"] != null || args["x"] != null) + { + args["action"] = "move_to"; + } + else if (ContainsFoodKeyword(decision?.Param) || ContainsFoodKeyword(decision?.Reason)) + { + args["action"] = "eat_food"; + } + // Otherwise leave 'action' unset so JobMechanism rejects with the valid operations list. + } + + return args; + } + + private static bool ContainsFoodKeyword(string? text) + { + if (string.IsNullOrEmpty(text)) + return false; + return FoodKeywordPattern.IsMatch(text!); + } + } +} diff --git a/Source/Infrastructure/Mechanisms/Pawn/MentalState/MentalStateMechanism.cs b/Source/Infrastructure/Mechanisms/Pawn/MentalState/MentalStateMechanism.cs index 4ebc5cec..72cd82ea 100644 --- a/Source/Infrastructure/Mechanisms/Pawn/MentalState/MentalStateMechanism.cs +++ b/Source/Infrastructure/Mechanisms/Pawn/MentalState/MentalStateMechanism.cs @@ -67,9 +67,9 @@ public override Task> ExecuteTriggerAsync(MechanismWr if (string.IsNullOrEmpty(args.DefName)) return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(""))); - var mentalStateDef = FindDef(args.DefName); + var mentalStateDef = FindDef(args.DefName!); if (mentalStateDef == null) - return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(args.DefName))); + return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(args.DefName!))); bool started = pawn.mindState?.mentalStateHandler?.TryStartMentalState(mentalStateDef, "Triggered by AI", true) == true; if (!started) diff --git a/Source/Infrastructure/Mechanisms/Pawn/Need/NeedMechanism.cs b/Source/Infrastructure/Mechanisms/Pawn/Need/NeedMechanism.cs index d3c96270..1c0e6247 100644 --- a/Source/Infrastructure/Mechanisms/Pawn/Need/NeedMechanism.cs +++ b/Source/Infrastructure/Mechanisms/Pawn/Need/NeedMechanism.cs @@ -40,7 +40,7 @@ public override Task> ExecuteQueryAsync(MechanismRe { var need = pawn.needs?.AllNeeds?.FirstOrDefault(n => n.def.defName == args.DefName); if (need == null) - return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(args.DefName))); + return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(args.DefName!))); var info = new { def = args.DefName, curLevel = need.CurLevel }; return Task.FromResult(Result.Ok(JsonConvert.SerializeObject(info))); @@ -65,7 +65,7 @@ public override Task> ExecuteSetAsync(MechanismWriteA var need = pawn.needs?.AllNeeds?.FirstOrDefault(n => n.def.defName == args.DefName); if (need == null) - return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(args.DefName))); + return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(args.DefName!))); if (args.Action == "set_level" && float.TryParse(args.ValueJson, out var level)) { diff --git a/Source/Infrastructure/Mechanisms/Pawn/Recruit/RecruitMechanism.cs b/Source/Infrastructure/Mechanisms/Pawn/Recruit/RecruitMechanism.cs index 8a89e77c..a6ced04e 100644 --- a/Source/Infrastructure/Mechanisms/Pawn/Recruit/RecruitMechanism.cs +++ b/Source/Infrastructure/Mechanisms/Pawn/Recruit/RecruitMechanism.cs @@ -3,6 +3,7 @@ using System.Threading.Tasks; using RimMind.Application.Common.Interfaces.Mechanisms; using RimMind.Application.Common.Models.Mechanisms; +using RimMind.Application.Common.Models.Tools; using RimMind.Domain.Enums; using RimMind.Domain.ValueObjects; using Verse; @@ -10,7 +11,7 @@ namespace RimMind.Infrastructure.Mechanisms.Pawn.Recruit { - public sealed class RecruitMechanism : GameMechanismBaseNoDef + public sealed class RecruitMechanism : GameMechanismBaseNoDef, IMechanismScopeMetadata { public override string MechanismId => "pawn.recruit"; public override MechanismScope Scope => MechanismScope.Pawn; @@ -18,6 +19,11 @@ public sealed class RecruitMechanism : GameMechanismBaseNoDef public override IReadOnlyList SupportedOperations => _supportedOps; public override MechanismDocs Docs => _docs; + public ToolScope? GetToolScopeForOperation(MechanismOperationType operation) + => operation is MechanismOperationType.Query or MechanismOperationType.List + ? ToolScope.MetaQuery + : ToolScope.Social | ToolScope.ColonistSelf; + private static readonly IReadOnlyList _supportedOps = new List { MechanismOperationType.Trigger }.AsReadOnly(); diff --git a/Source/Infrastructure/Mechanisms/Pawn/Relations/RelationsMechanism.cs b/Source/Infrastructure/Mechanisms/Pawn/Relations/RelationsMechanism.cs index bcd09179..7798d676 100644 --- a/Source/Infrastructure/Mechanisms/Pawn/Relations/RelationsMechanism.cs +++ b/Source/Infrastructure/Mechanisms/Pawn/Relations/RelationsMechanism.cs @@ -5,6 +5,7 @@ using Newtonsoft.Json; using RimMind.Application.Common.Interfaces.Mechanisms; using RimMind.Application.Common.Models.Mechanisms; +using RimMind.Application.Common.Models.Tools; using RimMind.Domain.Enums; using RimMind.Domain.ValueObjects; using Verse; @@ -12,7 +13,7 @@ namespace RimMind.Infrastructure.Mechanisms.Pawn.Relations { - public sealed class RelationsMechanism : GameMechanismBaseNoDef + public sealed class RelationsMechanism : GameMechanismBaseNoDef, IMechanismScopeMetadata { public override string MechanismId => "pawn.relations"; public override MechanismScope Scope => MechanismScope.Pawn; @@ -20,6 +21,11 @@ public sealed class RelationsMechanism : GameMechanismBaseNoDef public override IReadOnlyList SupportedOperations => _supportedOps; public override MechanismDocs Docs => _docs; + public ToolScope? GetToolScopeForOperation(MechanismOperationType operation) + => operation is MechanismOperationType.Query or MechanismOperationType.List + ? ToolScope.MetaQuery + : ToolScope.Social | ToolScope.ColonistSelf; + private static readonly IReadOnlyList _supportedOps = new List { MechanismOperationType.Query }.AsReadOnly(); diff --git a/Source/Infrastructure/Mechanisms/Pawn/Skill/SkillMechanism.cs b/Source/Infrastructure/Mechanisms/Pawn/Skill/SkillMechanism.cs index 14b50dbe..b54c9955 100644 --- a/Source/Infrastructure/Mechanisms/Pawn/Skill/SkillMechanism.cs +++ b/Source/Infrastructure/Mechanisms/Pawn/Skill/SkillMechanism.cs @@ -41,7 +41,7 @@ public override Task> ExecuteQueryAsync(MechanismRe { var skill = pawn.skills?.skills?.FirstOrDefault(s => s.def.defName == args.DefName); if (skill == null) - return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(args.DefName))); + return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(args.DefName!))); var info = new { def = args.DefName, level = skill.Level, passion = skill.passion.ToString() }; return Task.FromResult(Result.Ok(JsonConvert.SerializeObject(info))); @@ -66,7 +66,7 @@ public override Task> ExecuteSetAsync(MechanismWriteA var skill = pawn.skills?.skills?.FirstOrDefault(s => s.def.defName == args.DefName); if (skill == null) - return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(args.DefName))); + return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(args.DefName!))); if (args.Action == "learn_xp" && float.TryParse(args.ValueJson, out var xp)) { diff --git a/Source/Infrastructure/Mechanisms/Pawn/Thought/ThoughtMechanism.cs b/Source/Infrastructure/Mechanisms/Pawn/Thought/ThoughtMechanism.cs index 0eb2381b..2a0bbc6d 100644 --- a/Source/Infrastructure/Mechanisms/Pawn/Thought/ThoughtMechanism.cs +++ b/Source/Infrastructure/Mechanisms/Pawn/Thought/ThoughtMechanism.cs @@ -39,9 +39,9 @@ public override Task> ExecuteQueryAsync(MechanismRe if (!string.IsNullOrEmpty(args.DefName)) { - var thought = pawn.needs?.mood?.thoughts?.memories?.GetFirstMemoryOfDef(FindDef(args.DefName)); + var thought = pawn.needs?.mood?.thoughts?.memories?.GetFirstMemoryOfDef(FindDef(args.DefName!)); if (thought == null) - return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(args.DefName))); + return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(args.DefName!))); var info = new { def = thought.def.defName, label = thought.LabelCap, moodOffset = thought.MoodOffset() }; return Task.FromResult(Result.Ok(JsonConvert.SerializeObject(info))); @@ -64,9 +64,9 @@ public override Task> ExecuteAddAsync(MechanismWriteA if (string.IsNullOrEmpty(args.DefName)) return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(""))); - var thoughtDef = FindDef(args.DefName); + var thoughtDef = FindDef(args.DefName!); if (thoughtDef == null) - return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(args.DefName))); + return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(args.DefName!))); pawn.needs?.mood?.thoughts?.memories?.TryGainMemory(thoughtDef); return Task.FromResult(Result.Ok(true)); diff --git a/Source/Infrastructure/Mechanisms/Pawn/Work/WorkMechanism.cs b/Source/Infrastructure/Mechanisms/Pawn/Work/WorkMechanism.cs index 32ca1f01..cb020d3c 100644 --- a/Source/Infrastructure/Mechanisms/Pawn/Work/WorkMechanism.cs +++ b/Source/Infrastructure/Mechanisms/Pawn/Work/WorkMechanism.cs @@ -59,9 +59,9 @@ public override Task> ExecuteQueryAsync(MechanismRe if (!string.IsNullOrEmpty(args.DefName)) { - var workDef = FindDef(args.DefName); + var workDef = FindDef(args.DefName!); if (workDef == null) - return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(args.DefName))); + return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(args.DefName!))); var info = new { def = workDef.defName, label = workDef.label, priority = pawn.workSettings.GetPriority(workDef) }; return Task.FromResult(Result.Ok(JsonConvert.SerializeObject(info))); diff --git a/Source/Infrastructure/Mechanisms/Pawn/Work/WorkMechanismArgumentAdapter.cs b/Source/Infrastructure/Mechanisms/Pawn/Work/WorkMechanismArgumentAdapter.cs new file mode 100644 index 00000000..9f1929ff --- /dev/null +++ b/Source/Infrastructure/Mechanisms/Pawn/Work/WorkMechanismArgumentAdapter.cs @@ -0,0 +1,44 @@ +using System; +using Newtonsoft.Json.Linq; +using RimMind.Application.Common.Constants; +using RimMind.Application.Common.Interfaces.Tools; +using RimMind.Domain.Agent.Modes; + +namespace RimMind.Infrastructure.Mechanisms.Pawn.Work +{ + /// + /// Adapts LLM tool arguments for Core's pawn.work.set / pawn_work_set tool: + /// maps plain-text scalar work type targets (def_name) to work_type with default priority 1. + /// + public sealed class WorkMechanismArgumentAdapter : IToolArgumentAdapter + { + public string Id => "core.tool_adapter.pawn_work"; + + public string OwnerModId => RimMindOwnerConsts.CoreModId; + + public bool CanAdapt(string toolId) + { + return string.Equals(toolId, "pawn.work.set", StringComparison.OrdinalIgnoreCase) + || string.Equals(toolId, "pawn_work_set", StringComparison.OrdinalIgnoreCase); + } + + public JObject AdaptArguments(string toolId, JObject args, AgentDecision decision, int callerPawnId) + { + if (args == null) + args = new JObject(); + + if (args["work_type"] == null && args["def_name"] != null) + { + string? target = args.Value("def_name"); + if (!string.IsNullOrWhiteSpace(target)) + { + args["work_type"] = target; + if (args["priority"] == null) + args["priority"] = 1; + } + } + + return args; + } + } +} diff --git a/Source/Infrastructure/Mechanisms/World/Storyteller/StorytellerMechanism.cs b/Source/Infrastructure/Mechanisms/World/Storyteller/StorytellerMechanism.cs index 95250772..eee56b2c 100644 --- a/Source/Infrastructure/Mechanisms/World/Storyteller/StorytellerMechanism.cs +++ b/Source/Infrastructure/Mechanisms/World/Storyteller/StorytellerMechanism.cs @@ -63,9 +63,9 @@ public override Task> ExecuteTriggerAsync(MechanismWr if (string.IsNullOrEmpty(args.DefName)) return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(""))); - var incidentDef = FindDef(args.DefName); + var incidentDef = FindDef(args.DefName!); if (incidentDef == null) - return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(args.DefName))); + return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(args.DefName!))); var map = ResolveMap(args); if (map == null) diff --git a/Source/Infrastructure/Patches/FloatMenu_InnerVoice.cs b/Source/Infrastructure/Patches/FloatMenu_InnerVoice.cs index b22c133a..dc2297e9 100644 --- a/Source/Infrastructure/Patches/FloatMenu_InnerVoice.cs +++ b/Source/Infrastructure/Patches/FloatMenu_InnerVoice.cs @@ -4,6 +4,7 @@ using RimMind.Application.Common.Interfaces.Internal; using RimMind.Application.Common.Models.Agent; using RimMind.Infrastructure.UI; +using RimMind.Presentation.Api; using RimMind.Presentation.Runtime.Services; using UnityEngine; using Verse; @@ -11,23 +12,12 @@ namespace RimMind.Infrastructure.Patches { -#if V1_5 - [HarmonyPatch(typeof(FloatMenuMakerMap), nameof(FloatMenuMakerMap.ChoicesAtFor))] -#else [HarmonyPatch(typeof(FloatMenuMakerMap), nameof(FloatMenuMakerMap.GetOptions))] -#endif internal static class FloatMenu_InnerVoice { private static readonly RuntimeServiceRef IdentityProvider = RuntimeServiceRef.Optional(); -#if V1_5 - [HarmonyPostfix] - internal static void Postfix(Vector3 clickPos, Pawn pawn, ref List __result) - { - TryAddInnerVoiceOption(pawn, __result); - } -#else [HarmonyPostfix] internal static void Postfix( List selectedPawns, @@ -38,19 +28,18 @@ internal static void Postfix( Pawn? pawn = (selectedPawns is { Count: 1 }) ? selectedPawns[0] : null; TryAddInnerVoiceOption(pawn, __result); } -#endif private static void TryAddInnerVoiceOption(Pawn? pawn, List opts) { if (opts == null) return; - if (pawn == null || !pawn.Spawned || pawn.Dead) return; + if (!RimMindPawnLookup.IsActiveSpawnedColonist(pawn)) return; // Only show for pawns that have a PawnAgent var identityProvider = IdentityProvider.ValueOrDefault; - var identity = identityProvider?.GetAgentIdentity(pawn); + var identity = identityProvider?.GetAgentIdentity(pawn!); if (identity == null) return; - var label = "RimMind.InnerVoice.Inject".Translate(pawn.LabelShort); + var label = RimMindText.TrOr("RimMind.InnerVoice.Inject", "Inner Voice ({0})", pawn!.LabelShort); var option = new FloatMenuOption(label, () => { var dialog = new Dialog_RimMindInnerVoice(pawn, identity); diff --git a/Source/Infrastructure/Psychology/VersePawnPsychologyDataProvider.cs b/Source/Infrastructure/Psychology/VersePawnPsychologyDataProvider.cs deleted file mode 100644 index 4c1554dc..00000000 --- a/Source/Infrastructure/Psychology/VersePawnPsychologyDataProvider.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using RimMind.Application.Common.Interfaces.Agent.Psychology; -using RimMind.Domain.Agent.Psychology; -using Verse; -using VersePawn = Verse.Pawn; - -namespace RimMind.Infrastructure.Psychology -{ - public sealed class VersePawnPsychologyDataProvider : IPawnPsychologyDataProvider - { - public float GetMoodLevel(int pawnId) - { - var pawn = FindPawn(pawnId); - return pawn?.needs?.mood?.CurLevel ?? 0.5f; - } - - public IReadOnlyList GetNeedLevels(int pawnId) - { - var pawn = FindPawn(pawnId); - if (pawn?.needs?.AllNeeds == null) - return new List().AsReadOnly(); - - return pawn.needs.AllNeeds - .Select(n => new NeedLevel { NeedId = n.def.defName, CurrentLevel = n.CurLevel }) - .ToList() - .AsReadOnly(); - } - - public float GetMentalBreakThreshold(int pawnId) - { - var pawn = FindPawn(pawnId); - return pawn?.mindState?.mentalBreaker?.BreakThresholdMajor ?? 0.1f; - } - - public bool IsInMentalState(int pawnId) - { - var pawn = FindPawn(pawnId); - return pawn?.MentalStateDef != null; - } - - // Read-only queries stay lenient (any live loaded pawn) but go through the shared lookup: - // no WorldPawns scan, cache-only off the main thread, negatively cached misses. - private static VersePawn? FindPawn(int pawnId) - => Presentation.Api.RimMindPawnLookup.FindPawnByNumber(pawnId); - } -} diff --git a/Source/Infrastructure/Services/Clients/HttpTransport.cs b/Source/Infrastructure/Services/Clients/HttpTransport.cs index 57e8a60b..aad1cafc 100644 --- a/Source/Infrastructure/Services/Clients/HttpTransport.cs +++ b/Source/Infrastructure/Services/Clients/HttpTransport.cs @@ -5,6 +5,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; +using RimMind.Application.Common.Interfaces.Client; using RimMind.Application.Features.Llm; using RimMind.Infrastructure.Services.Clients.Shared; @@ -54,16 +55,40 @@ public static HttpException FromResponse(int statusCode, string? body, string? r } public static void RegisterDecorator(IHttpRequestDecorator decorator) - => HttpRequestDecorators.Register(decorator); + => HttpRequestDecoratorRegistry.Register(decorator); - public static void ApplyDecorators(HttpRequestMessage request, string? url, string? authHeader, string? customSessionId = null) - => HttpRequestDecorators.ApplyAll(request, url, authHeader, customSessionId); + public static void ApplyDecorators(HttpRequestMessage request, HttpRequestDecorationContext context) + => HttpRequestDecoratorRegistry.ApplyAll(request, context); + + public static void ApplyDecorators( + HttpRequestMessage request, + string? url, + string? authHeader, + string? customSessionId = null, + string? requestId = null, + string? npcId = null, + string? provider = null) + => HttpRequestDecoratorRegistry.ApplyAll( + request, + new HttpRequestDecorationContext(url, authHeader, customSessionId, requestId, npcId, provider)); public static async Task<(string body, long statusCode)> PostAsync( string url, string jsonBody, string? authHeader = null, string? headerName = null, string? headerValue = null, float connectTimeout = 60f, CancellationToken cancellationToken = default) + { + return await PostAsync( + url, jsonBody, authHeader, headerName, headerValue, + connectTimeout, cancellationToken, decorationContext: null).ConfigureAwait(false); + } + + public static async Task<(string body, long statusCode)> PostAsync( + string url, string jsonBody, string? authHeader, + string? headerName, string? headerValue, + float connectTimeout, + CancellationToken cancellationToken, + HttpRequestDecorationContext? decorationContext) { using var timeoutCts = connectTimeout > 0 ? new CancellationTokenSource(TimeSpan.FromSeconds(connectTimeout)) : null; using var linkedCts = timeoutCts != null @@ -78,7 +103,9 @@ public static void ApplyDecorators(HttpRequestMessage request, string? url, stri if (headerName != null && headerValue != null) request.Headers.TryAddWithoutValidation(headerName, headerValue); - ApplyDecorators(request, url, authHeader, headerValue); + ApplyDecorators( + request, + decorationContext ?? new HttpRequestDecorationContext(url, authHeader, CustomSessionId: headerName == null ? headerValue : null)); using var response = await _http.SendAsync(request, effectiveToken).ConfigureAwait(false); string body = await response.Content.ReadAsStringAsync().ConfigureAwait(false); @@ -108,7 +135,7 @@ public static void ApplyDecorators(HttpRequestMessage request, string? url, stri if (headerName != null && headerValue != null) request.Headers.TryAddWithoutValidation(headerName, headerValue); - ApplyDecorators(request, url, authHeader, headerValue); + ApplyDecorators(request, new HttpRequestDecorationContext(url, authHeader)); 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/Hybrid/HybridAIClient.cs b/Source/Infrastructure/Services/Clients/Hybrid/HybridAIClient.cs deleted file mode 100644 index de124a1b..00000000 --- a/Source/Infrastructure/Services/Clients/Hybrid/HybridAIClient.cs +++ /dev/null @@ -1,90 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using RimMind.Application.Common.Interfaces.Abstractions; -using RimMind.Application.Common.Interfaces.Client; -using RimMind.Application.Common.Models.Npc; -using RimMind.Domain.Llm; -using RimMind.Domain.ValueObjects; - -namespace RimMind.Infrastructure.Services.Clients.Hybrid -{ - /// - /// Hybrid AI client: remote-first with local fallback on retryable errors. - /// Replaces the old HybridStorageDriver concept at the request layer. - /// - public sealed class HybridAIClient : IAIClient - { - private readonly IAIClient _remote; - private readonly IAIClient _local; - private readonly ILogSink? _logSink; - - public HybridAIClient(IAIClient remote, IAIClient local, ILogSink? logSink = null) - { - _remote = remote ?? throw new ArgumentNullException(nameof(remote)); - _local = local ?? throw new ArgumentNullException(nameof(local)); - _logSink = logSink; - } - - public bool IsLocalEndpoint => false; - public bool IsConfigured() => _remote.IsConfigured() || _local.IsConfigured(); - public bool SupportsStreaming => _remote.SupportsStreaming; - public bool SupportsNpcServerState => _remote.SupportsNpcServerState; - - public async Task> SendAsync(LlmRequestEnvelope envelope) - { - if (!_remote.IsConfigured()) - return await _local.SendAsync(envelope); - - var result = await _remote.SendAsync(envelope); - if (result.IsErr && IsRetryable(result.Error.Code)) - { - _logSink?.Message($"[HybridAIClient] Remote failed ({result.Error.Code}), falling back to local"); - return await _local.SendAsync(envelope); - } - return result; - } - - public async Task> SendStreamAsync(LlmRequestEnvelope envelope, Action onChunk, CancellationToken ct = default) - { - if (!_remote.IsConfigured() || !_remote.SupportsStreaming) - { - return await _local.SendStreamAsync(envelope, onChunk, ct); - } - - // Fallback is only safe before the remote emitted anything: once deltas reached the consumer, - // replaying the request on the local client would duplicate (or contradict) already-shown text. - // So we fail over pre-first-chunk only and otherwise surface the remote error as-is. - bool remoteEmitted = false; - var result = await _remote.SendStreamAsync(envelope, chunk => - { - remoteEmitted = true; - onChunk(chunk); - }, ct); - if (result.IsErr && IsRetryable(result.Error.Code) && !remoteEmitted && !ct.IsCancellationRequested) - { - _logSink?.Message($"[HybridAIClient] Remote streaming failed ({result.Error.Code}), falling back to local"); - return await _local.SendStreamAsync(envelope, onChunk, ct); - } - return result; - } - - public Task> SpawnNpcAsync(NpcProfile profile) => _remote.SpawnNpcAsync(profile); - public Task> KillNpcAsync(string npcId) => _remote.KillNpcAsync(npcId); - public Task, RimMindError>> QueryNpcMemoriesAsync(string npcId, string query, int limit) => _remote.QueryNpcMemoriesAsync(npcId, query, limit); - - public void Dispose() - { - _remote.Dispose(); - _local.Dispose(); - } - - private static bool IsRetryable(RimMindErrorCode code) - { - return code == RimMindErrorCode.ClientTransientFailure - || code == RimMindErrorCode.ClientCircuitOpen - || code == RimMindErrorCode.Timeout; - } - } -} diff --git a/Source/Infrastructure/Services/Clients/IHttpRequestDecorator.cs b/Source/Infrastructure/Services/Clients/IHttpRequestDecorator.cs deleted file mode 100644 index afad197e..00000000 --- a/Source/Infrastructure/Services/Clients/IHttpRequestDecorator.cs +++ /dev/null @@ -1,50 +0,0 @@ -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/Local/LocalAIClient.cs b/Source/Infrastructure/Services/Clients/Local/LocalAIClient.cs deleted file mode 100644 index c75b7467..00000000 --- a/Source/Infrastructure/Services/Clients/Local/LocalAIClient.cs +++ /dev/null @@ -1,81 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using RimMind.Application.Common.Interfaces.Client; -using RimMind.Application.Common.Models.Npc; -using RimMind.Domain.ValueObjects; - -namespace RimMind.Infrastructure.Services.Clients.Local -{ - /// - /// Local AI client that wraps an existing IAIClient's legacy SendAsync(AIRequest) - /// to provide the new unified IAIClient interface. - /// Used for local-only operation where no remote endpoint is available. - /// - public class LocalAIClient : IAIClient - { - private readonly IAIClient _inner; - - public bool IsLocalEndpoint => true; - public bool SupportsStreaming => false; - public bool SupportsNpcServerState => false; - - public LocalAIClient(IAIClient inner) - { - _inner = inner ?? throw new ArgumentNullException(nameof(inner)); - } - - public bool IsConfigured() => true; - - public async Task> SendAsync(RimMind.Domain.Llm.LlmRequestEnvelope envelope) - { - return await _inner.SendAsync(envelope); - } - - public async Task> SendStreamAsync(RimMind.Domain.Llm.LlmRequestEnvelope envelope, Action onChunk, CancellationToken ct) - { - var result = await SendAsync(envelope); - - if (result.IsOk) - { - onChunk(new RimMind.Domain.Llm.LlmChunk - { - DeltaContent = result.Value.Content, - }); - - onChunk(new RimMind.Domain.Llm.LlmChunk - { - IsLast = true, - FinalResponse = result.Value, - }); - - return result; - } - else - { - return result; - } - } - - public Task> SpawnNpcAsync(NpcProfile profile) - { - throw new NotSupportedException("LocalAIClient does not support NPC server-side state"); - } - - public Task> KillNpcAsync(string npcId) - { - throw new NotSupportedException("LocalAIClient does not support NPC server-side state"); - } - - public Task, RimMindError>> QueryNpcMemoriesAsync(string npcId, string query, int limit) - { - throw new NotSupportedException("LocalAIClient does not support NPC server-side state"); - } - - public void Dispose() - { - _inner.Dispose(); - } - } -} diff --git a/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClient.cs b/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClient.cs index e657b63d..33ba039e 100644 --- a/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClient.cs +++ b/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClient.cs @@ -101,7 +101,7 @@ private static long ResolveNodeIsolationCooldownMs(Exception ex, out bool isPerm private readonly IOpenAISettings _settings; private readonly ILogSink? _logSink; - private readonly HttpPostDelegate _postAsync; + private readonly HttpPostDelegate? _postAsyncOverride; internal Func>? StreamSendOverride { get; set; } @@ -109,7 +109,7 @@ public OpenAIClient(IOpenAISettings settings, ILogSink? logSink = null, HttpPost { _settings = settings; _logSink = logSink; - _postAsync = postAsyncOverride ?? HttpTransport.PostAsync; + _postAsyncOverride = postAsyncOverride; } private static float ResolveTimeoutSeconds(bool isLocal, int candidateCount, int attempt) => @@ -135,12 +135,13 @@ internal List ResolveOrderedCandidateNodes(long nowMs) { var allConfigured = new List(); - if (!string.IsNullOrWhiteSpace(_settings.ApiEndpoint) && !string.IsNullOrWhiteSpace(_settings.ApiKey)) + if (!string.IsNullOrWhiteSpace(_settings.ApiEndpoint) + && (!string.IsNullOrWhiteSpace(_settings.ApiKey) || IsLoopbackEndpoint(_settings.ApiEndpoint))) { allConfigured.Add(new BackupEndpointNode { Name = "Primary", - Provider = "openai", + Provider = AIProviders.OpenAI, ApiEndpoint = _settings.ApiEndpoint, ModelName = !string.IsNullOrWhiteSpace(_settings.ModelName) ? _settings.ModelName : "gpt-4o-mini", ApiKey = _settings.ApiKey, @@ -185,22 +186,35 @@ internal List ResolveOrderedCandidateNodes(long nowMs) string effectiveModel, RimMind.Domain.Llm.LlmRequestEnvelope envelope, string initialJson, - string? headerName, - string? headerValue, float connectTimeout) { string currentJson = initialJson; string cacheKey = BuildFormatCacheKey(node.ApiEndpoint, effectiveModel); + string authHeader = $"Bearer {node.ApiKey}"; + var decorationContext = new HttpRequestDecorationContext( + endpoint, + authHeader, + CustomSessionId: null, + RequestId: envelope.RequestId, + NpcId: envelope.NpcId, + Provider: node.Provider); while (true) { try { - var (responseText, httpStatusCode) = await _postAsync( - endpoint, currentJson, $"Bearer {node.ApiKey}", - headerName: headerName, headerValue: headerValue, - connectTimeout: connectTimeout, - cancellationToken: envelope.Ct); + (string responseText, long httpStatusCode) = _postAsyncOverride != null + ? await _postAsyncOverride( + endpoint, currentJson, authHeader, + headerName: null, headerValue: null, + connectTimeout: connectTimeout, + cancellationToken: envelope.Ct) + : await HttpTransport.PostAsync( + endpoint, currentJson, authHeader, + headerName: null, headerValue: null, + connectTimeout: connectTimeout, + cancellationToken: envelope.Ct, + decorationContext: decorationContext); bool isModeration = ClientExceptionMapper.IsContentModerationResponse((int)httpStatusCode, responseText); if (httpStatusCode == 400 && !isModeration && currentJson.IndexOf("\"response_format\"", StringComparison.Ordinal) >= 0) @@ -340,10 +354,6 @@ internal List ResolveOrderedCandidateNodes(long nowMs) { bool isLocal = IsLoopbackEndpoint(node.ApiEndpoint); float connectTimeout = ResolveTimeoutSeconds(isLocal, candidates.Count, attempt); - bool isOpenCode = IsOpenCodeGo(node.ApiEndpoint, node.ApiKey) || - string.Equals(node.Provider, "opencode", StringComparison.OrdinalIgnoreCase); - string? headerName = isOpenCode ? "x-opencode-session" : null; - string? headerValue = isOpenCode ? ResolveSessionId(envelope) : null; (string responseText, long httpStatusCode) = await PostWithFormatFallbackAsync( node, @@ -351,8 +361,6 @@ internal List ResolveOrderedCandidateNodes(long nowMs) effectiveModel, envelope, json, - headerName, - headerValue, connectTimeout); return BuildCompletedResponse( @@ -416,10 +424,6 @@ internal List ResolveOrderedCandidateNodes(long nowMs) endpointOverride: retryNode.ApiEndpoint); bool isLocal = IsLoopbackEndpoint(retryNode.ApiEndpoint); float connectTimeout = isLocal ? 300f : 60f; - bool isOpenCode = IsOpenCodeGo(retryNode.ApiEndpoint, retryNode.ApiKey) || - string.Equals(retryNode.Provider, "opencode", StringComparison.OrdinalIgnoreCase); - string? headerName = isOpenCode ? "x-opencode-session" : null; - string? headerValue = isOpenCode ? ResolveSessionId(envelope) : null; for (int backoffAttempt = 1; backoffAttempt <= 2; backoffAttempt++) { @@ -433,8 +437,6 @@ internal List ResolveOrderedCandidateNodes(long nowMs) effectiveModel, envelope, json, - headerName, - headerValue, connectTimeout); return BuildCompletedResponse( @@ -524,8 +526,17 @@ 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.ApplyDecorators(request, endpoint, $"Bearer {node.ApiKey}", ResolveSessionId(envelope)); + string authHeader = $"Bearer {node.ApiKey}"; + request.Headers.TryAddWithoutValidation("Authorization", authHeader); + HttpTransport.ApplyDecorators( + request, + new HttpRequestDecorationContext( + endpoint, + authHeader, + CustomSessionId: null, + RequestId: envelope.RequestId, + NpcId: envelope.NpcId, + Provider: node.Provider)); using var session = StreamSendOverride != null ? await HttpTransport.OpenStreamAsync(request, connectTimeout, effectiveCt, StreamSendOverride).ConfigureAwait(false) @@ -694,25 +705,5 @@ public Task, RimMindError>> QueryNpcMemoriesAsync(string npc { throw new NotSupportedException("OpenAI does not support NPC server-side state"); } - - private static bool IsOpenCodeGo(string? endpoint, string? apiKey) - { - if (!string.IsNullOrEmpty(endpoint) && endpoint.IndexOf("opencode", StringComparison.OrdinalIgnoreCase) >= 0) - return true; - if (!string.IsNullOrEmpty(apiKey) && apiKey.IndexOf("oc_sk_", StringComparison.OrdinalIgnoreCase) >= 0) - return true; - return false; - } - - private static string ResolveSessionId(RimMind.Domain.Llm.LlmRequestEnvelope envelope) - { - if (!string.IsNullOrEmpty(envelope.NpcId)) - return "rimmind-" + envelope.NpcId; - if (!string.IsNullOrEmpty(envelope.RequestId)) - return "rimmind-" + envelope.RequestId; - if (!string.IsNullOrEmpty(envelope.TraceId)) - return "rimmind-" + envelope.TraceId; - return "rimmind-" + Guid.NewGuid().ToString("N").Substring(0, 12); - } } } diff --git a/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClientFactory.cs b/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClientFactory.cs index 240d99d5..14ee4edf 100644 --- a/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClientFactory.cs +++ b/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClientFactory.cs @@ -69,7 +69,7 @@ public IAIClient Create(ISettingsProvider settings) var resolvedSettings = settings != null ? new OpenAISettingsAdapter(settings) : _openAISettings; - if (resolvedSettings == null) return null; + if (resolvedSettings == null) return null!; return new OpenAIClient(resolvedSettings, _logSink); } @@ -90,7 +90,27 @@ public OpenAISettingsAdapter(ISettingsProvider settings) public float DefaultTemperature => _settings.DefaultTemperature; public bool DebugLogging => _settings.DebugLogging; public System.Collections.Generic.IReadOnlyList? BackupEndpoints => _settings.BackupEndpoints; - public bool IsConfigured() => _settings.IsOpenAIConfigured(); + public bool IsConfigured() + { + if (!string.IsNullOrWhiteSpace(_settings.ApiEndpoint) + && (!string.IsNullOrWhiteSpace(_settings.ApiKey) + || RimMind.Application.Features.Llm.RimMindHttpClientPool.IsLoopbackEndpoint(_settings.ApiEndpoint))) + { + return true; + } + + var backups = _settings.BackupEndpoints; + if (backups != null) + { + for (int i = 0; i < backups.Count; i++) + { + if (backups[i]?.IsConfigured == true) + return true; + } + } + + return false; + } } } } diff --git a/Source/Infrastructure/Services/Clients/OpenAI/OpenCodeHeaderDecorator.cs b/Source/Infrastructure/Services/Clients/OpenAI/OpenCodeHeaderDecorator.cs index c72a007d..2e55fbe3 100644 --- a/Source/Infrastructure/Services/Clients/OpenAI/OpenCodeHeaderDecorator.cs +++ b/Source/Infrastructure/Services/Clients/OpenAI/OpenCodeHeaderDecorator.cs @@ -1,12 +1,14 @@ using System; using System.Net.Http; +using RimMind.Application.Common.Interfaces.Client; 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. + /// when targeting OpenCode endpoints, provider opencode, or oc_sk_ keys). + /// Kept strictly inside the concrete OpenAI client adapter directory so generic transport + /// and OpenAIClient stay vendor-free. /// internal sealed class OpenCodeHeaderDecorator : IHttpRequestDecorator { @@ -14,8 +16,10 @@ internal sealed class OpenCodeHeaderDecorator : IHttpRequestDecorator public string Id => "core.opencode_session_header"; - public static bool Matches(string? url, string? authOrKey) + public static bool Matches(string? url, string? authOrKey, string? provider = null) { + if (!string.IsNullOrEmpty(provider) && string.Equals(provider, "opencode", StringComparison.OrdinalIgnoreCase)) + return true; if (!string.IsNullOrEmpty(url) && url!.IndexOf("opencode", StringComparison.OrdinalIgnoreCase) >= 0) return true; if (!string.IsNullOrEmpty(authOrKey) && authOrKey!.IndexOf("oc_sk_", StringComparison.OrdinalIgnoreCase) >= 0) @@ -23,18 +27,27 @@ public static bool Matches(string? url, string? authOrKey) return false; } - public void Decorate(HttpRequestMessage request, string? url, string? authHeader, string? customSessionId = null) + public void Decorate(HttpRequestMessage request, HttpRequestDecorationContext context) { - if (request == null) return; - if (!Matches(url, authHeader)) return; + if (request == null || context == null) return; + if (!Matches(context.Url, context.AuthHeader, context.Provider)) return; if (!request.Headers.Contains("x-opencode-session")) { - string sessionId = !string.IsNullOrEmpty(customSessionId) - ? customSessionId! - : "rimmind-" + Guid.NewGuid().ToString("N").Substring(0, 12); + string sessionId = ResolveSessionId(context); request.Headers.TryAddWithoutValidation("x-opencode-session", sessionId); } } + + private static string ResolveSessionId(HttpRequestDecorationContext context) + { + if (!string.IsNullOrEmpty(context.CustomSessionId)) + return context.CustomSessionId!; + if (!string.IsNullOrEmpty(context.NpcId)) + return "rimmind-" + context.NpcId; + if (!string.IsNullOrEmpty(context.RequestId)) + return "rimmind-" + context.RequestId; + return "rimmind-" + Guid.NewGuid().ToString("N").Substring(0, 12); + } } } diff --git a/Source/Infrastructure/Services/Clients/Player2/Player2Client.Balance.cs b/Source/Infrastructure/Services/Clients/Player2/Player2Client.Balance.cs index a0306410..af7633a2 100644 --- a/Source/Infrastructure/Services/Clients/Player2/Player2Client.Balance.cs +++ b/Source/Infrastructure/Services/Clients/Player2/Player2Client.Balance.cs @@ -16,10 +16,8 @@ namespace RimMind.Infrastructure.Services.Clients.Player2 public partial class Player2Client { private const int BalanceQueryTimeoutSec = RimMindDefaults.Player2BalanceQueryTimeout; - private const int BalancePollingDelayMs = RimMindDefaults.Player2BalancePollingDelay; private static volatile float _cachedJoulesBalance = -1f; - private static DateTime _lastBalanceCheck = DateTime.MinValue; private static readonly object _balanceLock = new object(); public static float CachedJoulesBalance => _cachedJoulesBalance; @@ -79,7 +77,6 @@ public static void RefreshJoulesBalance(ISettingsProvider? settingsProvider) lock (_balanceLock) { _cachedJoulesBalance = balance; - _lastBalanceCheck = DateTime.Now; } } } diff --git a/Source/Infrastructure/Services/Clients/Player2/Player2Client.Discovery.cs b/Source/Infrastructure/Services/Clients/Player2/Player2Client.Discovery.cs index f68728df..5f1d48b8 100644 --- a/Source/Infrastructure/Services/Clients/Player2/Player2Client.Discovery.cs +++ b/Source/Infrastructure/Services/Clients/Player2/Player2Client.Discovery.cs @@ -89,7 +89,7 @@ public static void ResetDiscoveryCache() { _lastProbeUtc = DateTime.UtcNow; } - logSink?.LogFromBackground($"[RimMind-Core] Player2 probe error: {ex.Message}"); + logSink?.LogFromBackground($"[RimMind-Core] Player2 probe error: {Shared.LogSanitizer.ForLog(ex.Message)}"); return null; } }); @@ -103,7 +103,7 @@ public static void TriggerBackgroundDiscovery(Player2Client client, ISettingsPro var task = ProbeLocalPlayer2KeyAsync(logSink); if (task.IsCompleted) { - if (!string.IsNullOrEmpty(task.Result)) + if (task.Status == TaskStatus.RanToCompletion && !string.IsNullOrEmpty(task.Result)) { client.UpdateDiscoveredKey(task.Result!, isLocal: true); } @@ -161,7 +161,7 @@ public static void TriggerBackgroundDiscovery(Player2Client client, ISettingsPro } catch (Exception ex) { - logSink?.LogFromBackground($"[RimMind-Core] Local Player2 detection failed: {ex.Message}"); + logSink?.LogFromBackground($"[RimMind-Core] Local Player2 detection failed: {Shared.LogSanitizer.ForLog(ex.Message)}"); return null; } } diff --git a/Source/Infrastructure/Services/Clients/Player2/Player2Client.HealthCheck.cs b/Source/Infrastructure/Services/Clients/Player2/Player2Client.HealthCheck.cs index e10dd021..bed6651d 100644 --- a/Source/Infrastructure/Services/Clients/Player2/Player2Client.HealthCheck.cs +++ b/Source/Infrastructure/Services/Clients/Player2/Player2Client.HealthCheck.cs @@ -15,20 +15,21 @@ public partial class Player2Client private const int HealthCheckIntervalMs = RimMindDefaults.Player2HealthCheckIntervalMs; private const int MinHealthCheckIntervalSec = RimMindDefaults.Player2MinHealthCheckIntervalSec; private const int LocalAvailabilityTimeoutSec = 2; - private const int HealthCheckPollingDelayMs = RimMindDefaults.HealthCheckPollingDelayMs; + private static readonly object _healthCheckLock = new object(); private static DateTime _lastHealthCheck = DateTime.MinValue; private static volatile bool _healthCheckActive; - private static CancellationTokenSource _healthCheckCts = new CancellationTokenSource(); + private static CancellationTokenSource? _healthCheckCts; - private async Task StartHealthCheckLoopAsync() + private async Task StartHealthCheckLoopAsync(CancellationToken ct) { try { - while (_healthCheckActive && !_healthCheckCts.IsCancellationRequested) + while (_healthCheckActive && !ct.IsCancellationRequested) { - await Task.Delay(HealthCheckIntervalMs, _healthCheckCts.Token).ConfigureAwait(false); - if (_healthCheckActive) await EnsureHealthCheck(force: true).ConfigureAwait(false); + await Task.Delay(HealthCheckIntervalMs, ct).ConfigureAwait(false); + if (_healthCheckActive && !ct.IsCancellationRequested) + await EnsureHealthCheck(force: true).ConfigureAwait(false); } } catch (OperationCanceledException) @@ -37,13 +38,16 @@ private async Task StartHealthCheckLoopAsync() catch (Exception ex) { _logSink?.LogFromBackground($"[RimMind-Core] Player2 health check loop crashed: {Shared.LogSanitizer.ForLog(ex.Message)}", isWarning: true); - _healthCheckActive = false; + lock (_healthCheckLock) + { + _healthCheckActive = false; + } } } - private void StartHealthCheckLoop() + private void StartHealthCheckLoop(CancellationToken ct) { - _ = StartHealthCheckLoopAsync(); + _ = StartHealthCheckLoopAsync(ct); } private async Task EnsureHealthCheck(bool force = false) @@ -73,13 +77,20 @@ private async Task EnsureHealthCheck(bool force = false) public static void StopHealthCheck() { - _healthCheckActive = false; - try + CancellationTokenSource? ctsToCancel; + lock (_healthCheckLock) { - _healthCheckCts.Cancel(); + _healthCheckActive = false; + ctsToCancel = _healthCheckCts; + _healthCheckCts = null; } - catch (ObjectDisposedException) + + if (ctsToCancel != null) { + try { ctsToCancel.Cancel(); } + catch (ObjectDisposedException) { } + try { ctsToCancel.Dispose(); } + catch (ObjectDisposedException) { } } } @@ -116,16 +127,29 @@ private static async Task IsPlayer2LocalAppAvailableAsync() internal void InitiateHealthCheckIfNeeded() { - if (!_healthCheckActive && !string.IsNullOrEmpty(_apiKey) && !_isLocalConnection) + if (string.IsNullOrEmpty(_apiKey) || _isLocalConnection) + return; + + CancellationToken ct; + CancellationTokenSource? staleCts = null; + lock (_healthCheckLock) { - if (_healthCheckCts.IsCancellationRequested) - { - _healthCheckCts.Dispose(); - _healthCheckCts = new CancellationTokenSource(); - } + if (_healthCheckActive) + return; + + staleCts = _healthCheckCts; + _healthCheckCts = new CancellationTokenSource(); + ct = _healthCheckCts.Token; _healthCheckActive = true; - StartHealthCheckLoop(); } + + if (staleCts != null) + { + try { staleCts.Dispose(); } + catch (ObjectDisposedException) { } + } + + StartHealthCheckLoop(ct); } } } diff --git a/Source/Infrastructure/Services/Clients/Player2/Player2Client.cs b/Source/Infrastructure/Services/Clients/Player2/Player2Client.cs index 14a8792a..2921756b 100644 --- a/Source/Infrastructure/Services/Clients/Player2/Player2Client.cs +++ b/Source/Infrastructure/Services/Clients/Player2/Player2Client.cs @@ -37,9 +37,18 @@ public partial class Player2Client : IAIClient internal Func>? StreamSendOverride { get; set; } - private string RemoteUrl => string.IsNullOrWhiteSpace(_settings.Player2RemoteUrl) - ? "https://api.player2.game" - : _settings.Player2RemoteUrl.Trim().TrimEnd('/'); + private const string RemoteUrlOptionKey = "player2.remote_url"; + + private string RemoteUrl + { + get + { + string raw = _settings.GetProviderOption(RemoteUrlOptionKey); + return string.IsNullOrWhiteSpace(raw) + ? "https://api.player2.game" + : raw.Trim().TrimEnd('/'); + } + } private string CurrentApiUrl => _isLocalConnection ? LocalUrl : RemoteUrl; @@ -405,23 +414,6 @@ internal static (string endpoint, string json) BuildPayload( } } - private static bool TryParseJsonSchema(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; - } - } - public async Task> SpawnNpcAsync(NpcProfile profile) { if (profile == null) diff --git a/Source/Infrastructure/Services/Clients/Player2/Player2ClientFactory.cs b/Source/Infrastructure/Services/Clients/Player2/Player2ClientFactory.cs index f9a10c39..ed40c0e5 100644 --- a/Source/Infrastructure/Services/Clients/Player2/Player2ClientFactory.cs +++ b/Source/Infrastructure/Services/Clients/Player2/Player2ClientFactory.cs @@ -33,8 +33,11 @@ public IAIClient Create(ISettingsProvider settings) { return Player2Client.Create(settings, _logSink); } - catch (System.Exception) + catch (System.Exception ex) { + _logSink?.LogFromBackground( + $"[RimMind-Core] Failed to create Player2 client: {Shared.LogSanitizer.ForLog(ex.Message)}", + isWarning: true); return null!; } } diff --git a/Source/Infrastructure/Services/Clients/Shared/ClientExceptionMapper.cs b/Source/Infrastructure/Services/Clients/Shared/ClientExceptionMapper.cs index e5775d25..8894c7e6 100644 --- a/Source/Infrastructure/Services/Clients/Shared/ClientExceptionMapper.cs +++ b/Source/Infrastructure/Services/Clients/Shared/ClientExceptionMapper.cs @@ -21,7 +21,7 @@ internal static class ClientExceptionMapper /// /// while is cancelled → /// / otherwise (our own per-request timeout fired) → , - /// which the circuit breaker counts and HybridAIClient treats as retryable + /// which the circuit breaker counts and failover wrappers treat as retryable /// → or based on StatusCode /// Network failures (, ) → /// Other exceptions → (or ClientTransient if is true) diff --git a/Source/Infrastructure/Services/Verse/VersePathProvider.cs b/Source/Infrastructure/Services/Verse/VersePathProvider.cs deleted file mode 100644 index 10da371e..00000000 --- a/Source/Infrastructure/Services/Verse/VersePathProvider.cs +++ /dev/null @@ -1,9 +0,0 @@ -using RimMind.Application.Common.Interfaces.Abstractions; - -namespace RimMind.Infrastructure.Services.Verse -{ - public sealed class VersePathProvider : IPathProvider - { - public string SaveDataFolderPath => global::Verse.GenFilePaths.SaveDataFolderPath; - } -} diff --git a/Source/Infrastructure/Services/Verse/VerseTranslationService.cs b/Source/Infrastructure/Services/Verse/VerseTranslationService.cs index 0211c3e8..872ad559 100644 --- a/Source/Infrastructure/Services/Verse/VerseTranslationService.cs +++ b/Source/Infrastructure/Services/Verse/VerseTranslationService.cs @@ -7,11 +7,26 @@ namespace RimMind.Infrastructure.Services.Verse { public sealed class VerseTranslationService : ITranslationService { + public bool CanTranslate(string key) + { + if (string.IsNullOrEmpty(key)) + return false; + + try + { + return UnityData.IsInMainThread && key.CanTranslate(); + } + catch + { + return false; + } + } + public static string TranslateSafe(string key) { try { - if (!string.IsNullOrEmpty(key) && key.CanTranslate()) + if (!string.IsNullOrEmpty(key) && UnityData.IsInMainThread && key.CanTranslate()) return key.TranslateSimple(); return key ?? string.Empty; } @@ -24,7 +39,7 @@ public static string TranslateSafe(string key, params object[] args) { if (string.IsNullOrEmpty(key)) return string.Empty; - string template = key.CanTranslate() ? key.TranslateSimple() : key; + string template = UnityData.IsInMainThread && key.CanTranslate() ? key.TranslateSimple() : key; if (args == null || args.Length == 0) return template; return string.Format(template, args); diff --git a/Source/Infrastructure/Social/VerseDreamThoughtInjector.cs b/Source/Infrastructure/Social/VerseDreamThoughtInjector.cs deleted file mode 100644 index 40adb263..00000000 --- a/Source/Infrastructure/Social/VerseDreamThoughtInjector.cs +++ /dev/null @@ -1,30 +0,0 @@ -using RimMind.Application.Common.Interfaces.Agent.Psychology; -using RimMind.Application.Common.Interfaces.Agent.Social; -using RimMind.Domain.Agent.Social; -using RimMind.Domain.ValueObjects; - -namespace RimMind.Infrastructure.Social; - -public sealed class VerseDreamThoughtInjector : IDreamThoughtInjector -{ - private readonly IThoughtInjector _thoughtInjector; - - public VerseDreamThoughtInjector(IThoughtInjector thoughtInjector) - { - _thoughtInjector = thoughtInjector; - } - - public Result InjectDreamThought(int pawnId, DreamEntry dream) - { - var thoughtResult = _thoughtInjector.InjectThought( - pawnId, - $"[Dream] {dream.DreamContent}", - dream.MoodImpact * 5f, - 60000, - $"Dream:{dream.DreamType}"); - - return thoughtResult.Match( - ok => Result.Ok(dream), - err => Result.Err(err)); - } -} diff --git a/Source/Infrastructure/Social/VersePawnSleepDetector.cs b/Source/Infrastructure/Social/VersePawnSleepDetector.cs deleted file mode 100644 index 7bdc079f..00000000 --- a/Source/Infrastructure/Social/VersePawnSleepDetector.cs +++ /dev/null @@ -1,29 +0,0 @@ -using RimMind.Application.Common.Interfaces.Agent; -using RimMind.Application.Common.Interfaces.Agent.Social; -using RimMind.Presentation.Api; -using RimWorld; -using Verse; - -namespace RimMind.Infrastructure.Social; - -public sealed class VersePawnSleepDetector : ISleepDetector -{ - public bool IsSleeping(IAgentInfo agent) - { - var pawn = FindPawn(agent.NpcId); - if (pawn == null) return false; - return pawn.CurJobDef == JobDefOf.LayDown - && pawn.needs?.rest?.CurLevel < 0.3f; - } - - private static Pawn? FindPawn(string npcId) - { - var pawn = RimMindPawnLookup.FindPawnById(npcId); - if (pawn != null) return pawn; - if (int.TryParse(npcId, out var num)) - { - return RimMindPawnLookup.FindPawnByNumber(num); - } - return null; - } -} diff --git a/Source/Infrastructure/Social/VerseTraitEvolver.cs b/Source/Infrastructure/Social/VerseTraitEvolver.cs index ee592b82..71f59a90 100644 --- a/Source/Infrastructure/Social/VerseTraitEvolver.cs +++ b/Source/Infrastructure/Social/VerseTraitEvolver.cs @@ -1,4 +1,3 @@ -using System.Linq; using RimMind.Application.Common.Interfaces.Agent.Social; using RimMind.Domain.Agent.Social; using RimMind.Domain.Enums; @@ -12,47 +11,38 @@ public sealed class VerseTraitEvolver : ITraitEvolver { public Result ApplyTraitEvolution(int pawnId, TraitEvolutionRecord record) { - var pawn = FindPawn(pawnId); + var pawn = FindEligiblePawn(pawnId); if (pawn == null) return Result.Err( RimMindErrors.PawnNotFound(pawnId)); + var traits = pawn.story?.traits; + if (traits == null) return Result.Err( + RimMindErrors.PawnNotFound(pawnId)); + var traitDef = DefDatabase.GetNamedSilentFail(record.TraitDefName); if (traitDef == null) return Result.Err( RimMindErrors.InvalidDefName(record.TraitDefName)); if (record.Kind == TraitEvolutionKind.Gained) { - if (!pawn.story.traits.HasTrait(traitDef)) - pawn.story.traits.GainTrait(new Trait(traitDef)); + if (!traits.HasTrait(traitDef)) + traits.GainTrait(new Trait(traitDef)); } else { - var existing = pawn.story.traits.GetTrait(traitDef); + var existing = traits.GetTrait(traitDef); if (existing != null) - pawn.story.traits.RemoveTrait(existing); + traits.RemoveTrait(existing); } return Result.Ok(record); } - private static Pawn? FindPawn(int pawnId) + private static Pawn? FindEligiblePawn(int pawnId) { - var cached = Presentation.Api.RimMindPawnLookup.FindPawnByNumber(pawnId); - if (cached != null) return cached; - - if (UnityData.IsInMainThread && Find.Maps != null) - { - foreach (var map in Find.Maps) - { - var pawn = map.mapPawns?.FreeColonistsSpawned?.FirstOrDefault(p => p.thingIDNumber == pawnId); - if (pawn != null && Presentation.Api.RimMindPawnLookup.IsActiveSpawnedColonist(pawn)) - { - Presentation.Api.RimMindPawnLookup.CachePawn(pawn); - return pawn; - } - } - } - + var pawn = Presentation.Api.RimMindPawnLookup.FindPawnByNumber(pawnId); + if (pawn != null && Presentation.Api.RimMindPawnLookup.IsActiveSpawnedColonist(pawn)) + return pawn; return null; } } diff --git a/Source/Infrastructure/UI/AgentFlow/Window_AgentFlowLab.Mechanism.cs b/Source/Infrastructure/UI/AgentFlow/Window_AgentFlowLab.Mechanism.cs index 6e91a9cd..a1bc3d21 100644 --- a/Source/Infrastructure/UI/AgentFlow/Window_AgentFlowLab.Mechanism.cs +++ b/Source/Infrastructure/UI/AgentFlow/Window_AgentFlowLab.Mechanism.cs @@ -166,7 +166,6 @@ private void PerformDryRun() RuntimeServiceScope runtimeScope = RuntimeServiceHub.Shared.Capture(); var mechanismRegistry = runtimeScope.GetOptional(); var toolRegistry = runtimeScope.GetOptional(); - var approvalGate = runtimeScope.GetOptional(); if (mechanismRegistry == null) { @@ -197,21 +196,7 @@ private void PerformDryRun() } string riskStr = mech.Risk.ToString(); - string approvalStr = ""; - if (approvalGate != null && _lastDecision != null) - { - var riskLevel = mech.Risk switch - { - MechanismRisk.Safe => RiskLevel.Low, - MechanismRisk.Moderate => RiskLevel.Medium, - MechanismRisk.Dangerous => RiskLevel.High, - _ => RiskLevel.Low - }; - bool needsApproval = approvalGate.RequiresApproval(_lastDecision, riskLevel); - approvalStr = needsApproval ? " [APPROVAL REQUIRED]" : ""; - } - - sb.AppendLine($" {mech.MechanismId} [{mech.Scope}] risk={riskStr} actions={actionsStr}{toolMatch}{approvalStr}"); + sb.AppendLine($" {mech.MechanismId} [{mech.Scope}] risk={riskStr} actions={actionsStr}{toolMatch}"); } if (_lastDecision == null) @@ -261,14 +246,12 @@ private void PerformDryRun() if (toolRegistry != null) { - var validator = RuntimeServiceHub.Shared.Capture().GetOptional(); - if (validator != null) - { - var validationResult = validator.Validate(_lastDecision, toolRegistry); - _validationInfo = validationResult.IsValid - ? "RimMind.UI.AgentFlowLab.ValidationPassed".Translate() - : "RimMind.UI.AgentFlowLab.ValidationFailed".Translate(validationResult.Reason); - } + var validator = RuntimeServiceHub.Shared.Capture().GetOptional() + ?? new DecisionValidator(); + var validationResult = validator.Validate(_lastDecision, toolRegistry); + _validationInfo = validationResult.IsValid + ? "RimMind.UI.AgentFlowLab.ValidationPassed".Translate() + : "RimMind.UI.AgentFlowLab.ValidationFailed".Translate(validationResult.Reason); } } @@ -310,7 +293,7 @@ private void CompleteMechanismExecution() if (!string.IsNullOrEmpty(execution.Error)) { - _lastError = $"ExecuteMechanism: {LocalizeAsyncError(execution.Error)}"; + _lastError = $"ExecuteMechanism: {LocalizeAsyncError(execution.Error!)}"; _stepTracker.Set(FlowLabStep.Execute, StepStatus.Failed); return; } diff --git a/Source/Infrastructure/UI/AgentFlow/Window_AgentFlowLab.Target.cs b/Source/Infrastructure/UI/AgentFlow/Window_AgentFlowLab.Target.cs index 68c06180..4ead1cc6 100644 --- a/Source/Infrastructure/UI/AgentFlow/Window_AgentFlowLab.Target.cs +++ b/Source/Infrastructure/UI/AgentFlow/Window_AgentFlowLab.Target.cs @@ -306,7 +306,7 @@ private void DrawContextBuilding(ref float y, float w) "RimMind.UI.AgentFlowLab.Messages".Translate(msgCount.ToString())); y += LineH; - if (msgCount > 0) + if (_lastSnapshot.Messages != null && msgCount > 0) { var sb = new StringBuilder(); foreach (var msg in _lastSnapshot.Messages.Take(8)) @@ -342,7 +342,7 @@ private void CompleteContextBuild() if (!string.IsNullOrEmpty(error)) { - _lastError = $"BuildContext: {LocalizeAsyncError(error)}"; + _lastError = $"BuildContext: {LocalizeAsyncError(error!)}"; _stepTracker.Set(FlowLabStep.BuildContext, StepStatus.Failed); return; } diff --git a/Source/Infrastructure/UI/AgentsPage/AgentActivityStreamDrawer.cs b/Source/Infrastructure/UI/AgentsPage/AgentActivityStreamDrawer.cs index b3be9c02..0f1dbf10 100644 --- a/Source/Infrastructure/UI/AgentsPage/AgentActivityStreamDrawer.cs +++ b/Source/Infrastructure/UI/AgentsPage/AgentActivityStreamDrawer.cs @@ -136,7 +136,7 @@ private static string TraceRowLabel(AgentRequestTraceRow row) return label + ": " + (row.ErrorMessage?.Replace('\r', ' ').Replace('\n', ' ').Trim() ?? string.Empty); return row.HasError && !string.IsNullOrWhiteSpace(row.ErrorMessage) - ? label + ": " + summary + " - " + row.ErrorMessage.Replace('\r', ' ').Replace('\n', ' ').Trim() + ? label + ": " + summary + " - " + row.ErrorMessage!.Replace('\r', ' ').Replace('\n', ' ').Trim() : label + ": " + summary; } diff --git a/Source/Infrastructure/UI/AgentsPage/AgentListBuilder.cs b/Source/Infrastructure/UI/AgentsPage/AgentListBuilder.cs index 84cdcade..44791503 100644 --- a/Source/Infrastructure/UI/AgentsPage/AgentListBuilder.cs +++ b/Source/Infrastructure/UI/AgentsPage/AgentListBuilder.cs @@ -23,9 +23,10 @@ public static AgentListGroups Build( if (!string.IsNullOrWhiteSpace(pendingSelectedPawnId) && all.All(a => a.Id != pendingSelectedPawnId)) { + string pendingId = pendingSelectedPawnId!; pending.Add(AgentListItem.PendingPawn( - pendingSelectedPawnId, - pendingSelectedPawnLabel ?? pendingSelectedPawnId)); + pendingId, + pendingSelectedPawnLabel ?? pendingId)); } return new AgentListGroups( diff --git a/Source/Infrastructure/UI/AgentsPage/AgentListItem.cs b/Source/Infrastructure/UI/AgentsPage/AgentListItem.cs index 320140d7..32d8cf7d 100644 --- a/Source/Infrastructure/UI/AgentsPage/AgentListItem.cs +++ b/Source/Infrastructure/UI/AgentsPage/AgentListItem.cs @@ -77,7 +77,7 @@ private static string ResolveStatusSummary( string? errorSummary) { if (!string.IsNullOrWhiteSpace(errorSummary)) - return errorSummary; + return errorSummary!; if (isPendingCreation) return "Pending creation"; diff --git a/Source/Infrastructure/UI/AgentsPage/AgentListPanelDrawer.cs b/Source/Infrastructure/UI/AgentsPage/AgentListPanelDrawer.cs index 16a22318..5349daf5 100644 --- a/Source/Infrastructure/UI/AgentsPage/AgentListPanelDrawer.cs +++ b/Source/Infrastructure/UI/AgentsPage/AgentListPanelDrawer.cs @@ -23,20 +23,16 @@ public sealed class AgentListPanelDrawer _pawnById.Clear(); var map = Find.CurrentMap; - var allSpawned = map?.mapPawns?.AllPawnsSpawned; - if (allSpawned != null) + var colonists = RimMind.Presentation.Api.RimMindPawnLookup.GetSpawnedColonistsSafe(map); + for (int i = 0; i < colonists.Count; i++) { - for (int i = 0; i < allSpawned.Count; i++) - { - Pawn pawn = allSpawned[i]; - if (pawn == null) continue; - var comp = CompPawnAgent.GetComp(pawn); - if (comp?.Agent == null) continue; - AgentState state = comp.Agent.State; - string id = pawn.ThingID; - _agents.Add(AgentListItem.ExistingPawn(id, pawn.LabelShortCap, state)); - _pawnById[id] = pawn; - } + Pawn pawn = colonists[i]; + var comp = CompPawnAgent.GetComp(pawn); + if (comp?.Agent == null) continue; + AgentState state = comp.Agent.State; + string id = pawn.ThingID; + _agents.Add(AgentListItem.ExistingPawn(id, pawn.LabelShortCap, state)); + _pawnById[id] = pawn; } string? pendingId = hubSelectedPawn != null diff --git a/Source/Infrastructure/UI/AgentsPage/AgentRequestTraceRowBuilder.cs b/Source/Infrastructure/UI/AgentsPage/AgentRequestTraceRowBuilder.cs index ff41b6f0..2fde4c11 100644 --- a/Source/Infrastructure/UI/AgentsPage/AgentRequestTraceRowBuilder.cs +++ b/Source/Infrastructure/UI/AgentsPage/AgentRequestTraceRowBuilder.cs @@ -4,8 +4,9 @@ using System.Linq; using System.Text.RegularExpressions; using Newtonsoft.Json; +using RimMind.Application.Common.Interfaces.Diagnostics; using RimMind.Application.Common.Models.Debug; -using Verse; +using RimMind.Presentation.Api; namespace RimMind.Infrastructure.UI.AgentsPage { @@ -19,6 +20,22 @@ public static class AgentRequestTraceRowBuilder "reply", "narration", "dialogue", "speech", "text", "content", "message" }; + private static readonly Regex ReplyFieldRegex = new Regex( + "\"(?:reply|narration|dialogue|speech|text|content|message)\"\\s*:\\s*\"((?:\\\\\"|[^\"])+)\"", + RegexOptions.IgnoreCase | RegexOptions.Compiled); + + private static readonly Regex LayerTagRegex = new Regex( + @"\[L\d+\]\s*", + RegexOptions.Compiled); + + private static readonly Regex XmlTagRegex = new Regex( + @"<[^>]+>", + RegexOptions.Compiled); + + private static readonly Regex WhitespaceRegex = new Regex( + @"\s+", + RegexOptions.Compiled); + public static IReadOnlyList BuildRecent( IEnumerable? entries, int limit = DefaultLimit) @@ -39,8 +56,14 @@ public static IReadOnlyList BuildRecent( private static AgentRequestTraceRow BuildRow(AIRequestTraceEntry entry) { var status = MapStatus(entry.State); - string toolCallSummary = BuildToolCallSummary(entry); - string contentSummary = BuildContentSummary(entry, status); + RequestTraceSummary? customSummary = null; + if (status == AgentRequestTraceStatus.Success) + { + RequestTraceSummarizerRegistry.TrySummarizeResponse(entry, out customSummary); + } + + string toolCallSummary = BuildToolCallSummary(entry, customSummary?.SuppressToolNames); + string contentSummary = BuildContentSummary(entry, status, customSummary, toolCallSummary); string? error = ResolveError(entry); string tooltip = BuildTooltipDetail(entry, status, contentSummary, error); @@ -66,33 +89,27 @@ private static AgentRequestTraceStatus MapStatus(AIRequestTraceState state) } } - private static string BuildContentSummary(AIRequestTraceEntry entry, AgentRequestTraceStatus status) + private static string BuildContentSummary( + AIRequestTraceEntry entry, + AgentRequestTraceStatus status, + RequestTraceSummary? customSummary, + string toolCallSummary) { if (status == AgentRequestTraceStatus.Success) { - if (entry.ToolCalls.Count > 0) + if (customSummary != null && !string.IsNullOrWhiteSpace(customSummary.ContentSummary)) { - if (entry.ToolCalls.Any(t => t.ToolName == "express_dialogue") && !string.IsNullOrWhiteSpace(entry.Response)) - { - if (TryExtractDialogueToolCall(entry.Response, out string dialogueSpeech, out string? dialogueThought) - || TryExtractSpeechOrNarration(entry.Response, out dialogueSpeech, out dialogueThought)) - { - string speech = "\"" + ToSingleLine(dialogueSpeech) + "\""; - if (!string.IsNullOrWhiteSpace(dialogueThought)) - { - speech += " (" + ToSingleLine(dialogueThought) + ")"; - } - return speech; - } - } - string toolSummary = BuildToolCallSummary(entry); - if (!string.IsNullOrWhiteSpace(toolSummary)) - return toolSummary; + return ToSingleLine(customSummary.ContentSummary); + } + + if (!string.IsNullOrWhiteSpace(toolCallSummary)) + { + return toolCallSummary; } if (!string.IsNullOrWhiteSpace(entry.Response)) { - if (TryExtractSpeechOrNarration(entry.Response, out string text, out string? thoughtDesc)) + if (TryExtractStructuredReply(entry.Response, out string text, out string? thoughtDesc)) { string speech = "\"" + ToSingleLine(text) + "\""; if (!string.IsNullOrWhiteSpace(thoughtDesc)) @@ -112,18 +129,18 @@ private static string BuildContentSummary(AIRequestTraceEntry entry, AgentReques { return CleanPromptForSummary(entry.UserPrompt); } - return "RimMind.UI.AgentsPage.Trace.WaitingModel".Translate(); + return RimMindText.TrOr("RimMind.UI.AgentsPage.Trace.WaitingModel", "Waiting for model..."); } else if (status == AgentRequestTraceStatus.Error) { - string err = ResolveError(entry) ?? "RimMind.UI.AgentsPage.Trace.RequestError".Translate(); + string err = ResolveError(entry) ?? RimMindText.TrOr("RimMind.UI.AgentsPage.Trace.RequestError", "Request error"); return ToSingleLine(err); } return FirstNonEmpty(entry.Response, entry.UserPrompt, entry.Source, entry.RequestId); } - private static bool TryExtractSpeechOrNarration( + private static bool TryExtractStructuredReply( string rawResponse, out string extractedText, out string? thoughtDescription) @@ -135,12 +152,12 @@ private static bool TryExtractSpeechOrNarration( return false; string cleaned = rawResponse.Trim(); - if (cleaned.StartsWith("```")) + if (cleaned.StartsWith("```", StringComparison.Ordinal)) { int firstNewline = cleaned.IndexOf('\n'); if (firstNewline >= 0) cleaned = cleaned.Substring(firstNewline + 1); - if (cleaned.EndsWith("```")) + if (cleaned.EndsWith("```", StringComparison.Ordinal)) cleaned = cleaned.Substring(0, cleaned.Length - 3); cleaned = cleaned.Trim(); } @@ -189,14 +206,10 @@ private static bool TryExtractSpeechOrNarration( } catch { - // Fall through to regex + // Fall through to regex extraction for truncated JSON payloads. } - // Regex fallback for reply/narration - var match = Regex.Match( - cleaned, - "\"(?:reply|narration|dialogue|speech|text|content|message)\"\\s*:\\s*\"((?:\\\\\"|[^\"])+)\"", - RegexOptions.IgnoreCase); + var match = ReplyFieldRegex.Match(cleaned); if (match.Success) { extractedText = Regex.Unescape(match.Groups[1].Value); @@ -206,104 +219,23 @@ private static bool TryExtractSpeechOrNarration( return false; } - private static bool TryExtractDialogueToolCall(string raw, out string speechText, out string? thoughtText) - { - speechText = string.Empty; - thoughtText = null; - - if (string.IsNullOrWhiteSpace(raw)) return false; - - try - { - var token = Newtonsoft.Json.Linq.JToken.Parse(raw.Trim()); - Newtonsoft.Json.Linq.JObject? argsObj = null; - - if (token is Newtonsoft.Json.Linq.JArray arr) - { - foreach (var item in arr) - { - if (item is Newtonsoft.Json.Linq.JObject obj) - { - string? toolName = (obj["name"] ?? obj["function"]?["name"])?.ToString(); - if (string.Equals(toolName, "express_dialogue", StringComparison.OrdinalIgnoreCase)) - { - argsObj = ParseArgs(obj); - if (argsObj != null) break; - } - } - } - } - else if (token is Newtonsoft.Json.Linq.JObject singleObj) - { - argsObj = ParseArgs(singleObj); - } - - if (argsObj != null) - { - speechText = (argsObj["speech"] ?? argsObj["reply"] ?? argsObj["content"])?.ToString() ?? string.Empty; - thoughtText = (argsObj["thought_desc"] ?? argsObj["thought_tag"] ?? argsObj["thought"])?.ToString(); - - if (!string.IsNullOrWhiteSpace(speechText)) - return true; - } - } - catch - { - // Fallback to regex with escaped or unescaped quotes - } - - var match = Regex.Match( - raw, - @"\\?""speech\\?""\s*:\s*\\?""((?:\\.|[^""\\])+)\\?""", - RegexOptions.IgnoreCase); - if (match.Success) - { - speechText = Regex.Unescape(match.Groups[1].Value); - return !string.IsNullOrWhiteSpace(speechText); - } - - return false; - - static Newtonsoft.Json.Linq.JObject? ParseArgs(Newtonsoft.Json.Linq.JObject obj) - { - var argsToken = obj["arguments"] ?? obj["function"]?["arguments"]; - if (argsToken == null) return null; - if (argsToken.Type == Newtonsoft.Json.Linq.JTokenType.Object && argsToken is Newtonsoft.Json.Linq.JObject jobj) return jobj; - if (argsToken.Type == Newtonsoft.Json.Linq.JTokenType.String) - { - string str = (argsToken as Newtonsoft.Json.Linq.JValue)?.Value?.ToString()?.Trim() ?? string.Empty; - if (!string.IsNullOrWhiteSpace(str)) return Newtonsoft.Json.Linq.JObject.Parse(str); - } - return null; - } - } - private static string CleanPromptForSummary(string rawPrompt) { if (string.IsNullOrWhiteSpace(rawPrompt)) - return "RimMind.UI.AgentsPage.Trace.TriggerInteraction".Translate(); - - // Strip [L0] ~ [L9] headers - string cleaned = Regex.Replace(rawPrompt, @"\[L\d+\]\s*", string.Empty); + return RimMindText.TrOr("RimMind.UI.AgentsPage.Trace.TriggerInteraction", "Triggered interaction"); - // Check if it's auto trigger template before stripping - string autoTriggerPrompt = "RimMind.Dialogue.Prompt.AutoTrigger".CanTranslate() - ? (string)"RimMind.Dialogue.Prompt.AutoTrigger".Translate() - : string.Empty; - if ((!string.IsNullOrWhiteSpace(autoTriggerPrompt) && cleaned.Contains(autoTriggerPrompt)) - || rawPrompt.IndexOf("dialogue_trigger", StringComparison.OrdinalIgnoreCase) >= 0) + if (RequestTraceSummarizerRegistry.TrySummarizePrompt(rawPrompt, out string? customPrompt) + && !string.IsNullOrWhiteSpace(customPrompt)) { - return "RimMind.UI.AgentsPage.Trace.DailyReaction".Translate(); + return ToSingleLine(customPrompt); } - // Strip XML tags e.g. ... - cleaned = Regex.Replace(cleaned, @"<[^>]+>", string.Empty); - - // Collapse newlines and whitespace + string cleaned = LayerTagRegex.Replace(rawPrompt, string.Empty); + cleaned = XmlTagRegex.Replace(cleaned, string.Empty); cleaned = ToSingleLine(cleaned); if (string.IsNullOrWhiteSpace(cleaned)) - return "RimMind.UI.AgentsPage.Trace.DailyReaction".Translate(); + return RimMindText.TrOr("RimMind.UI.AgentsPage.Trace.DailyReaction", "Daily reaction"); return cleaned; } @@ -318,19 +250,19 @@ private static string BuildTooltipDetail( string statusText = status switch { - AgentRequestTraceStatus.Success => "RimMind.UI.AgentsPage.Trace.Success".Translate(), - AgentRequestTraceStatus.Waiting => "RimMind.UI.AgentsPage.Trace.Pending".Translate(), - AgentRequestTraceStatus.Streaming => "RimMind.UI.AgentsPage.Trace.Pending".Translate(), - AgentRequestTraceStatus.Error => "RimMind.UI.AgentsPage.Trace.Error".Translate(), - _ => "RimMind.UI.AgentsPage.Trace.Pending".Translate() + AgentRequestTraceStatus.Success => RimMindText.TrOr("RimMind.UI.AgentsPage.Trace.Success", "Success"), + AgentRequestTraceStatus.Waiting => RimMindText.TrOr("RimMind.UI.AgentsPage.Trace.Pending", "Pending"), + AgentRequestTraceStatus.Streaming => RimMindText.TrOr("RimMind.UI.AgentsPage.Trace.Pending", "Pending"), + AgentRequestTraceStatus.Error => RimMindText.TrOr("RimMind.UI.AgentsPage.Trace.Error", "Error"), + _ => RimMindText.TrOr("RimMind.UI.AgentsPage.Trace.Pending", "Pending") }; - lines.Add("RimMind.UI.AgentsPage.Trace.TooltipTitle".Translate(statusText)); + lines.Add(RimMindText.TrOr("RimMind.UI.AgentsPage.Trace.TooltipTitle", "Status: {0}", statusText)); var meta = new List(); - if (entry.ElapsedMs > 0) meta.Add("RimMind.UI.AgentsPage.Trace.TooltipElapsed".Translate(entry.ElapsedMs)); - if (entry.TokensUsed > 0) meta.Add("RimMind.UI.AgentsPage.Trace.TooltipTokens".Translate(entry.TokensUsed)); - if (!string.IsNullOrWhiteSpace(entry.Model)) meta.Add("RimMind.UI.AgentsPage.Trace.TooltipModel".Translate(entry.Model)); + if (entry.ElapsedMs > 0) meta.Add(RimMindText.TrOr("RimMind.UI.AgentsPage.Trace.TooltipElapsed", "{0}ms", entry.ElapsedMs)); + if (entry.TokensUsed > 0) meta.Add(RimMindText.TrOr("RimMind.UI.AgentsPage.Trace.TooltipTokens", "{0} tok", entry.TokensUsed)); + if (!string.IsNullOrWhiteSpace(entry.Model)) meta.Add(RimMindText.TrOr("RimMind.UI.AgentsPage.Trace.TooltipModel", "Model: {0}", entry.Model)); if (meta.Count > 0) { lines.Add(string.Join(" | ", meta)); @@ -338,35 +270,37 @@ private static string BuildTooltipDetail( if (!string.IsNullOrWhiteSpace(entry.Source)) { - lines.Add("RimMind.UI.AgentsPage.Trace.TooltipSource".Translate(entry.Source)); + lines.Add(RimMindText.TrOr("RimMind.UI.AgentsPage.Trace.TooltipSource", "Source: {0}", entry.Source)); } if (!string.IsNullOrWhiteSpace(entry.UserPrompt)) { string promptClean = CleanPromptForSummary(entry.UserPrompt); - lines.Add("RimMind.UI.AgentsPage.Trace.TooltipIntent".Translate(promptClean)); + lines.Add(RimMindText.TrOr("RimMind.UI.AgentsPage.Trace.TooltipIntent", "Intent: {0}", promptClean)); } if (entry.ToolCalls.Count > 0) { string tools = string.Join(", ", entry.ToolCalls.Select(t => t.ToolName)); - lines.Add("RimMind.UI.AgentsPage.Trace.TooltipTools".Translate(tools)); + lines.Add(RimMindText.TrOr("RimMind.UI.AgentsPage.Trace.TooltipTools", "Tools: {0}", tools)); } if (!string.IsNullOrWhiteSpace(contentSummary)) { - lines.Add("RimMind.UI.AgentsPage.Trace.TooltipContent".Translate(contentSummary)); + lines.Add(RimMindText.TrOr("RimMind.UI.AgentsPage.Trace.TooltipContent", "Content: {0}", contentSummary)); } if (!string.IsNullOrWhiteSpace(error)) { - lines.Add("RimMind.UI.AgentsPage.Trace.TooltipError".Translate(error)); + lines.Add(RimMindText.TrOr("RimMind.UI.AgentsPage.Trace.TooltipError", "Error: {0}", error!)); } return string.Join("\n", lines); } - private static string BuildToolCallSummary(AIRequestTraceEntry entry) + private static string BuildToolCallSummary( + AIRequestTraceEntry entry, + IReadOnlyList? suppressedToolNames) { if (entry.ToolCalls.Count == 0) return string.Empty; @@ -374,7 +308,7 @@ private static string BuildToolCallSummary(AIRequestTraceEntry entry) var relevantTools = entry.ToolCalls .Where(toolCall => toolCall != null && !string.IsNullOrWhiteSpace(toolCall.ToolName) - && !string.Equals(toolCall.ToolName, "express_dialogue", StringComparison.OrdinalIgnoreCase)) + && !IsSuppressedTool(toolCall.ToolName, suppressedToolNames)) .ToList(); if (relevantTools.Count == 0) @@ -385,7 +319,23 @@ private static string BuildToolCallSummary(AIRequestTraceEntry entry) .Take(ToolCallSummaryLimit) .Select(toolCall => toolCall.ToolName) .Where(name => !string.IsNullOrWhiteSpace(name))); - return "RimMind.UI.AgentsPage.Trace.CallTools".Translate(tools); + return RimMindText.TrOr("RimMind.UI.AgentsPage.Trace.CallTools", "Call: {0}", tools); + } + + private static bool IsSuppressedTool(string toolName, IReadOnlyList? suppressedToolNames) + { + if (RequestTraceSummarizerRegistry.ShouldSuppressToolCall(toolName)) + return true; + + if (suppressedToolNames == null || suppressedToolNames.Count == 0) + return false; + + for (int i = 0; i < suppressedToolNames.Count; i++) + { + if (string.Equals(suppressedToolNames[i], toolName, StringComparison.OrdinalIgnoreCase)) + return true; + } + return false; } private static string? ResolveError(AIRequestTraceEntry entry) @@ -401,17 +351,14 @@ private static string BuildToolCallSummary(AIRequestTraceEntry entry) private static string ToSingleLine(string? text) { if (string.IsNullOrWhiteSpace(text)) return string.Empty; - string s = Regex.Replace(text!, @"[\r\n]+", " "); - s = Regex.Replace(s, @"\s+", " "); - return s.Trim(); + return WhitespaceRegex.Replace(text!, " ").Trim(); } - private static string FirstNonEmpty(params string[] values) + private static string FirstNonEmpty(params string?[] values) { - foreach (string value in values) + foreach (string? value in values) { if (!string.IsNullOrWhiteSpace(value)) - return value; return ToSingleLine(value); } diff --git a/Source/Infrastructure/UI/DebugActions/AICoreDebugActions.ContextAndAgents.cs b/Source/Infrastructure/UI/DebugActions/AICoreDebugActions.ContextAndAgents.cs index a2bc3032..86481d92 100644 --- a/Source/Infrastructure/UI/DebugActions/AICoreDebugActions.ContextAndAgents.cs +++ b/Source/Infrastructure/UI/DebugActions/AICoreDebugActions.ContextAndAgents.cs @@ -145,7 +145,7 @@ public static void ShowRegisteredContextKeys() { RuntimeServiceScope runtimeScope = RuntimeServiceHub.Shared.Capture(); var keys = runtimeScope.GetOptional()?.GetAll(); - if (keys.Count == 0) + if (keys == null || keys.Count == 0) { Log.Message("[RimMind-Core] No registered context keys."); return; diff --git a/Source/Infrastructure/UI/DebugActions/AICoreDebugActions.Requests.cs b/Source/Infrastructure/UI/DebugActions/AICoreDebugActions.Requests.cs index c1e0bfa6..03454f6d 100644 --- a/Source/Infrastructure/UI/DebugActions/AICoreDebugActions.Requests.cs +++ b/Source/Infrastructure/UI/DebugActions/AICoreDebugActions.Requests.cs @@ -159,7 +159,7 @@ public static void ShowSettingsSummary() sb.AppendLine($" AutoApplyMode: (via Context)"); sb.AppendLine($" AutoApplyConfidenceThreshold: (via Context)"); sb.AppendLine($" RequestOverlayEnabled: (via UI)"); - sb.AppendLine($" Player2RemoteUrl: {s.Player2RemoteUrl}"); + sb.AppendLine($" Player2RemoteUrl: {s.GetProviderOption("player2.remote_url")}"); sb.AppendLine($" TelemetryDataPath: (via Infrastructure)"); sb.AppendLine($" AnalysisReportPath: (via Infrastructure)"); sb.AppendLine($" IsConfigured: {s.IsConfigured}"); diff --git a/Source/Infrastructure/UI/DebugActions/BehaviorAutotestRunner.cs b/Source/Infrastructure/UI/DebugActions/BehaviorAutotestRunner.cs index 3d86946b..f54554a9 100644 --- a/Source/Infrastructure/UI/DebugActions/BehaviorAutotestRunner.cs +++ b/Source/Infrastructure/UI/DebugActions/BehaviorAutotestRunner.cs @@ -1058,47 +1058,48 @@ private static void PostToolCleanup(string toolId, Pawn? pawn) private static bool IsExpectedDomainRejection(string toolId, string? error) { if (string.IsNullOrEmpty(error)) return false; + string err = error!; // pawn.recruit.trigger: pawn is already in player's faction - if (toolId == "pawn.recruit.trigger" && error.IndexOf("already a colonist", StringComparison.OrdinalIgnoreCase) >= 0) + if (toolId == "pawn.recruit.trigger" && err.IndexOf("already a colonist", StringComparison.OrdinalIgnoreCase) >= 0) return true; // pawn.equipment.set: drop_weapon when pawn has no weapon equipped - if (toolId == "pawn.equipment.set" && error.IndexOf("no weapon equipped", StringComparison.OrdinalIgnoreCase) >= 0) + if (toolId == "pawn.equipment.set" && err.IndexOf("no weapon equipped", StringComparison.OrdinalIgnoreCase) >= 0) return true; // pawn.interaction.trigger: social_relax when no joy activity is available - if (toolId == "pawn.interaction.trigger" && error.IndexOf("no social relax", StringComparison.OrdinalIgnoreCase) >= 0) + if (toolId == "pawn.interaction.trigger" && err.IndexOf("no social relax", StringComparison.OrdinalIgnoreCase) >= 0) return true; // world.storyteller.trigger: conditions for incident not currently met - if (toolId == "world.storyteller.trigger" && error.IndexOf("Failed to execute incident", StringComparison.OrdinalIgnoreCase) >= 0) + if (toolId == "world.storyteller.trigger" && err.IndexOf("Failed to execute incident", StringComparison.OrdinalIgnoreCase) >= 0) return true; // pawn.job.set: when specific job target not present or cannot work - if (toolId == "pawn.job.set" && (error.IndexOf("missing", StringComparison.OrdinalIgnoreCase) >= 0 - || error.IndexOf("not available", StringComparison.OrdinalIgnoreCase) >= 0 - || error.IndexOf("No job available", StringComparison.OrdinalIgnoreCase) >= 0)) + if (toolId == "pawn.job.set" && (err.IndexOf("missing", StringComparison.OrdinalIgnoreCase) >= 0 + || err.IndexOf("not available", StringComparison.OrdinalIgnoreCase) >= 0 + || err.IndexOf("No job available", StringComparison.OrdinalIgnoreCase) >= 0)) return true; // pawn.work.set: when player autonomy policy disables WorkPriorityModification - if (toolId == "pawn.work.set" && error.IndexOf("by player autonomy policy", StringComparison.OrdinalIgnoreCase) >= 0) + if (toolId == "pawn.work.set" && err.IndexOf("by player autonomy policy", StringComparison.OrdinalIgnoreCase) >= 0) return true; // Composite actions on fresh -quicktest map: resource safety guard or missing worktable if ((toolId == "actions_plan_room_project" || toolId == "actions_place_blueprint") && - (error.IndexOf("[Safety Guard]", StringComparison.OrdinalIgnoreCase) >= 0 || - error.IndexOf("minimum survival threshold", StringComparison.OrdinalIgnoreCase) >= 0)) + (err.IndexOf("[Safety Guard]", StringComparison.OrdinalIgnoreCase) >= 0 || + err.IndexOf("minimum survival threshold", StringComparison.OrdinalIgnoreCase) >= 0)) return true; if (toolId == "actions_add_worktable_bill" && - (error.IndexOf("No worktable found", StringComparison.OrdinalIgnoreCase) >= 0 || - error.IndexOf("worktable", StringComparison.OrdinalIgnoreCase) >= 0)) + (err.IndexOf("No worktable found", StringComparison.OrdinalIgnoreCase) >= 0 || + err.IndexOf("worktable", StringComparison.OrdinalIgnoreCase) >= 0)) return true; if (toolId == "actions_designate_resources" && - (error.IndexOf("No valid", StringComparison.OrdinalIgnoreCase) >= 0 || - error.IndexOf("found within", StringComparison.OrdinalIgnoreCase) >= 0)) + (err.IndexOf("No valid", StringComparison.OrdinalIgnoreCase) >= 0 || + err.IndexOf("found within", StringComparison.OrdinalIgnoreCase) >= 0)) return true; return false; @@ -1215,7 +1216,7 @@ private IEnumerator RunSuiteUiInteraction() if (resolved && callbackInvoked && isCleared) { checksPassed++; - result.Details.Add("[PASS] Simulated Click: [批准] button clicked -> Request resolved, callback executed, and cleared from overlay"); + result.Details.Add("[PASS] Simulated Click: [Approve] button clicked -> Request resolved, callback executed, and cleared from overlay"); } else { diff --git a/Source/Infrastructure/UI/DebugActions/ShowcaseSceneCaptureRunner.cs b/Source/Infrastructure/UI/DebugActions/ShowcaseSceneCaptureRunner.cs index 035834e5..462a62c1 100644 --- a/Source/Infrastructure/UI/DebugActions/ShowcaseSceneCaptureRunner.cs +++ b/Source/Infrastructure/UI/DebugActions/ShowcaseSceneCaptureRunner.cs @@ -281,14 +281,19 @@ private IEnumerator Run(string runId, string? repoRoot) if (colonist1 != null) { MoteMaker.ThrowText(colonist1.DrawPos + new Vector3(0f, 0f, 1.35f), map, - "“再吃靴子味的营养膏,本小姐就要去弹药库打保龄球了!”", new Color(1f, 0.85f, 0.45f), 25f); + RimMindText.TrOr("RimMind.Showcase.Advisor.Mote", "\"One more boot-flavored nutrient paste meal and I'm bowling in the mortar shell depot!\""), + new Color(1f, 0.85f, 0.45f), 25f); } } var advisorReq = new RequestEntry { - title = "傲娇女仆贝拉的绝食抗议 (Bella's Hunger Strike)", - description = "“本小姐已经连续吃了3天靴子味的营养膏了!如果晚餐再没有炙烤牛排,我就去弹药库把迫击炮弹当保龄球打!”", - options = new[] { "批准:烹饪精致牛排", "驳回:老实吃营养膏" }, + title = RimMindText.TrOr("RimMind.Showcase.Advisor.Title", "Bella's Hunger Strike Protest"), + description = RimMindText.TrOr("RimMind.Showcase.Advisor.Desc", "\"I have eaten boot-flavored nutrient paste for 3 days straight! If dinner isn't seared steak, I'm taking the mortar shells bowling!\""), + options = new[] + { + RimMindText.TrOr("RimMind.Showcase.Advisor.Approve", "Approve: Cook Fine Steak"), + RimMindText.TrOr("RimMind.Showcase.Advisor.Reject", "Reject: Stick to Paste") + }, source = "RimMind-Advisor" }; RequestOverlay.SetWindowRectForTest(new Rect(Screen.width * 0.5f - 260f, 95f, 520f, 185f)); @@ -321,12 +326,14 @@ private IEnumerator Run(string runId, string? repoRoot) if (colonist1 != null) { MoteMaker.ThrowText(colonist1.DrawPos + new Vector3(-0.8f, 0f, 1.35f), map, - "“终于端上热气腾腾的烤肉排了,今晚总算不用啃皮靴营养膏啦!”", Color.white, 25f); + RimMindText.TrOr("RimMind.Showcase.Dialogue.Line1", "\"Finally, sizzling grilled steak! No more chewing boot-flavored paste tonight!\""), + Color.white, 25f); } if (colonist2 != null && colonist2 != colonist1) { MoteMaker.ThrowText(colonist2.DrawPos + new Vector3(0.8f, 0f, 1.55f), map, - "“敬大厨一杯!+6 社交好感度 ❤️ [THOUGHT: GRATEFUL]”", new Color(1f, 0.5f, 0.75f), 25f); + RimMindText.TrOr("RimMind.Showcase.Dialogue.Line2", "\"Cheers to the chef! +6 Social Opinion [THOUGHT: GRATEFUL]\""), + new Color(1f, 0.5f, 0.75f), 25f); } } yield return null; @@ -374,8 +381,8 @@ private IEnumerator Run(string runId, string? repoRoot) Log.Message("[RimMind-Core] Staging Scene 7: 07-storyteller-playthrough.jpg..."); ClearAllLetters(); ChoiceLetter letter = (ChoiceLetter)LetterMaker.MakeLetter( - "因果律的制裁:狂怒鼠群的复仇", - "AI 叙事者已编排戏剧性事件:\n昨天贝拉击退松鼠并在屁股上留下牙印的事件引发了连锁因果反扑!\n\n根据地底啮齿类动物情报网的报告,附近的松鼠家族认为此举严重侵犯了森林主权。一支由 18 只狂暴嗜血松鼠组成的远征军正向殖民地奔袭而来……\n\n“它们目光如炬,誓要为昨天的屁股咬痕讨回公道!”", + RimMindText.TrOr("RimMind.Showcase.Storyteller.Title", "Causal Retribution: Revenge of the Mad Squirrel Swarm"), + RimMindText.TrOr("RimMind.Showcase.Storyteller.Body", "AI Storyteller orchestrated a dramatic event:\nYesterday's squirrel skirmish triggered a causal retaliation!\n\nAccording to underground rodent intelligence, the local squirrel clans consider the act a grave violation of forest sovereignty. An expedition of 18 maddened squirrels is charging toward the colony...\n\n\"Eyes blazing, they have come to settle yesterday's score!\""), LetterDefOf.ThreatBig); Find.LetterStack.ReceiveLetter(letter); letter.OpenLetter(); @@ -622,14 +629,44 @@ private static void PopulateAgentsTracesAndDialogue(List colonists, Pawn? ?? GameServiceHub.Shared.Capture().GetOptional(); if (traceLog != null) { - traceLog.StartRequest("req-personality-1", "RimMind-Personality", "deepseek-flash", "破晓心境自白", "观察日出麦浪", ""); - traceLog.CompleteRequest("req-personality-1", "“初升的朝阳照在木屋与麦浪上,虽然昨天屁股被松鼠咬得很痛,但有热饭和伙伴在身边,生活依旧充满希望。”", 340, 180); - - traceLog.StartRequest("req-actions-1", "RimMind-Actions", "deepseek-flash", "自主建造决策", "place_blueprint(Bed, WoodLog)", ""); - traceLog.CompleteRequest("req-actions-1", "{\"tool\":\"place_blueprint\",\"building_def\":\"Bed\",\"stuff_def\":\"WoodLog\",\"reason\":\"为同伴补充温暖的木床\"}", 412, 210); - - traceLog.StartRequest("req-dialogue-1", "RimMind-Dialogue", "deepseek-flash", "食堂晚宴交谈", "express_dialogue(speech, relation_delta=+6)", ""); - traceLog.CompleteRequest("req-dialogue-1", "“终于端上热气腾腾的烤肉排了,今晚总算不用啃皮靴营养膏啦!”", 285, 165); + traceLog.StartRequest( + "req-personality-1", + "RimMind-Personality", + "demo-model", + RimMindText.TrOr("RimMind.Showcase.Trace.PersonalityScenario", "Dawn Reflection"), + RimMindText.TrOr("RimMind.Showcase.Trace.PersonalityPrompt", "Watching sunrise over the wheat field"), + ""); + traceLog.CompleteRequest( + "req-personality-1", + RimMindText.TrOr("RimMind.Showcase.Trace.PersonalityReply", "\"Morning sunlight warms the wooden lodge and wheat fields. Yesterday's squirrel bite still stings, yet with hot meals and friends nearby, life remains full of hope.\""), + 340, + 180); + + traceLog.StartRequest( + "req-actions-1", + "RimMind-Actions", + "demo-model", + RimMindText.TrOr("RimMind.Showcase.Trace.ActionsScenario", "Autonomous Build Decision"), + "place_blueprint(Bed, WoodLog)", + ""); + traceLog.CompleteRequest( + "req-actions-1", + RimMindText.TrOr("RimMind.Showcase.Trace.ActionsReply", "{\"tool\":\"place_blueprint\",\"building_def\":\"Bed\",\"stuff_def\":\"WoodLog\",\"reason\":\"Build a warm wooden bed for companions\"}"), + 412, + 210); + + traceLog.StartRequest( + "req-dialogue-1", + "RimMind-Dialogue", + "demo-model", + RimMindText.TrOr("RimMind.Showcase.Trace.DialogueScenario", "Dining Hall Banter"), + "express_dialogue(speech, relation_delta=+6)", + ""); + traceLog.CompleteRequest( + "req-dialogue-1", + RimMindText.TrOr("RimMind.Showcase.Dialogue.Line1", "\"Finally, sizzling grilled steak! No more chewing boot-flavored paste tonight!\""), + 285, + 165); } // Populate RimMind-Dialogue overlay via reflection so top-left HUD shows real colonist banter @@ -649,7 +686,7 @@ private static void PopulateAgentsTracesAndDialogue(List colonists, Pawn? colonist2, chitchatVal, "Evening meal in the wooden dining hall", - "终于端上热气腾腾的烤肉排了,今晚总算不用啃皮靴营养膏啦!", + RimMindText.TrOr("RimMind.Showcase.Dialogue.HudLine1", "Finally, sizzling grilled steak! No more chewing boot-flavored paste tonight!"), "AMUSED", "Enjoying hot steak in the dining room" }); @@ -661,7 +698,7 @@ private static void PopulateAgentsTracesAndDialogue(List colonists, Pawn? colonist1, chitchatVal, "Evening meal reply", - "敬大厨一杯!木屋里点上火把暖和多了,明天我们把北边的稻田也收割入库吧。", + RimMindText.TrOr("RimMind.Showcase.Dialogue.HudLine2", "Cheers to the chef! The torches keep the lodge cozy — tomorrow let's harvest the northern rice fields."), "GRATEFUL", "Grateful for warm food and shelter" }); diff --git a/Source/Infrastructure/UI/DebugCenter/LiveAiProbeState.cs b/Source/Infrastructure/UI/DebugCenter/LiveAiProbeState.cs index e4be4dce..03176af2 100644 --- a/Source/Infrastructure/UI/DebugCenter/LiveAiProbeState.cs +++ b/Source/Infrastructure/UI/DebugCenter/LiveAiProbeState.cs @@ -4,11 +4,14 @@ using RimMind.Application.Common.Interfaces.Client; using RimMind.Application.Common.Interfaces.Internal; using RimMind.Application.Common.Models.Client; -using RimMind.Domain.Common; using RimMind.Domain.Llm; using RimMind.Domain.ValueObjects; +using RimMind.Infrastructure.Services.Clients.Shared; +using RimMind.Presentation.Api; +using RimMind.Presentation.Runtime.Services; +using RimMind.Presentation.UI; +using RimMind.Presentation.UI.Framework; using UnityEngine; -using Verse; namespace RimMind.Infrastructure.UI.DebugCenter { @@ -16,13 +19,14 @@ public static class LiveAiProbeState { private static readonly object Lock = new(); private static bool _isTesting; - private static string _lastStatus = "RimMind.UI.Hub.PingNotRun".Translate(); + private static string? _lastStatus; private static long _lastLatencyMs; private static int _lastTokensUsed; private static string? _lastSnippet; private static string? _lastError; private static Color _statusColor = RimMindUI.ColorMuted; private static bool _offlineSimulationMode; + private static GenerationUiOperation? _activeOperation; public static bool IsTesting { @@ -32,7 +36,15 @@ public static bool IsTesting public static string LastStatus { - get { lock (Lock) return _lastStatus; } + get + { + lock (Lock) + { + if (_lastStatus != null) + return _lastStatus; + } + return UiText.Get("RimMind.UI.Hub.PingNotRun", "Not tested"); + } private set { lock (Lock) _lastStatus = value; } } @@ -77,24 +89,30 @@ public static void TriggerProbe(ISettingsProvider settings, IClientManager? clie if (IsTesting) return; + var operation = GenerationUiOperation.Capture( + RuntimeServiceHub.Shared, + LifecycleEventSources.LiveAiProbe); + if (OfflineSimulationMode) { - IsTesting = true; - LastStatus = "RimMind.Settings.Status.Testing".Translate(); - StatusColor = RimMindUI.ColorPaused; + lock (Lock) + { + _activeOperation = operation; + _isTesting = true; + _lastStatus = UiText.Get("RimMind.Settings.Status.Testing", "Testing..."); + _statusColor = RimMindUI.ColorPaused; + } Task.Run(async () => { await Task.Delay(180).ConfigureAwait(false); - lock (Lock) - { - _lastStatus = "200 OK (Offline Sim)"; - _lastLatencyMs = 180; - _lastTokensUsed = 12; - _lastSnippet = "{\"status\":\"ok\",\"simulated\":true}"; - _lastError = null; - _statusColor = RimMindUI.ColorActive; - _isTesting = false; - } + RimMindAPI.MainThread.Post(() => PublishResult( + operation, + status: "200 OK (Offline Sim)", + latencyMs: 180, + tokensUsed: 12, + snippet: "{\"status\":\"ok\",\"simulated\":true}", + error: null, + color: RimMindUI.ColorActive)); }); return; } @@ -103,36 +121,39 @@ public static void TriggerProbe(ISettingsProvider settings, IClientManager? clie { lock (Lock) { - _lastStatus = "RimMind.Settings.Status.NotConfigured".Translate(); + _lastStatus = UiText.Get("RimMind.Settings.Status.NotConfigured", "Not configured"); _lastError = "API key or endpoint missing in Settings."; _statusColor = RimMindUI.ColorPaused; } return; } - IsTesting = true; - LastStatus = "RimMind.Settings.Status.Testing".Translate(); - StatusColor = RimMindUI.ColorPaused; - LastError = null; - LastSnippet = null; + lock (Lock) + { + _activeOperation = operation; + _isTesting = true; + _lastStatus = UiText.Get("RimMind.Settings.Status.Testing", "Testing..."); + _statusColor = RimMindUI.ColorPaused; + _lastError = null; + _lastSnippet = null; + } + string provider = settings.Provider; Task.Run(async () => { try { - IAIClient? client = settings.Provider == "player2" - ? clientManager?.GetPlayer2Client() - : clientManager?.GetClient(); - + IAIClient? client = clientManager?.GetClient(); if (client == null) { - lock (Lock) - { - _lastStatus = "FAIL (No Client)"; - _lastError = $"AIClient unavailable for provider '{settings.Provider}'."; - _statusColor = RimMindUI.ColorError; - _isTesting = false; - } + RimMindAPI.MainThread.Post(() => PublishResult( + operation, + status: "FAIL (No Client)", + latencyMs: 0, + tokensUsed: 0, + snippet: null, + error: $"AIClient unavailable for provider '{provider}'.", + color: RimMindUI.ColorError)); return; } @@ -156,45 +177,86 @@ public static void TriggerProbe(ISettingsProvider settings, IClientManager? clie var sw = System.Diagnostics.Stopwatch.StartNew(); Result result = await client.SendAsync(envelope).ConfigureAwait(false); sw.Stop(); + long elapsed = sw.ElapsedMilliseconds; - lock (Lock) + if (result.TryGetValue(out var response)) { - _lastLatencyMs = sw.ElapsedMilliseconds; - if (result.TryGetValue(out var response)) - { - _lastStatus = "200 OK"; - _lastTokensUsed = response?.TokensUsed ?? 0; - _lastSnippet = response?.Content?.Trim() ?? "OK"; - _lastError = null; - _statusColor = RimMindUI.ColorActive; - } - else - { - string codeStr = result.Error != null ? ((int)result.Error.Code).ToString() : "FAIL"; - _lastStatus = $"{codeStr} (FAIL)"; - _lastError = result.Error?.Message ?? "Unknown error"; - _lastTokensUsed = 0; - _statusColor = RimMindUI.ColorError; - } + int tokens = response?.TokensUsed ?? 0; + string snippet = response?.Content?.Trim() ?? "OK"; + RimMindAPI.MainThread.Post(() => PublishResult( + operation, + status: "200 OK", + latencyMs: elapsed, + tokensUsed: tokens, + snippet: snippet, + error: null, + color: RimMindUI.ColorActive)); + } + else + { + string codeStr = result.Error != null ? ((int)result.Error.Code).ToString() : "FAIL"; + string errorMsg = LogSanitizer.ForLog(result.Error?.Message ?? "Unknown error"); + RimMindAPI.MainThread.Post(() => PublishResult( + operation, + status: $"{codeStr} (FAIL)", + latencyMs: elapsed, + tokensUsed: 0, + snippet: null, + error: errorMsg, + color: RimMindUI.ColorError)); } } catch (Exception ex) { - lock (Lock) - { - _lastStatus = "ERROR"; - _lastError = ex.Message; - _statusColor = RimMindUI.ColorError; - } + string safeError = LogSanitizer.ForLog(ex.Message); + RimMindAPI.MainThread.Post(() => PublishResult( + operation, + status: "ERROR", + latencyMs: 0, + tokensUsed: 0, + snippet: null, + error: safeError, + color: RimMindUI.ColorError)); } - finally + }); + } + + private static void PublishResult( + GenerationUiOperation operation, + string status, + long latencyMs, + int tokensUsed, + string? snippet, + string? error, + Color color) + { + if (!operation.CanPublish()) + { + lock (Lock) { - lock (Lock) + if (ReferenceEquals(_activeOperation, operation)) { + _activeOperation = null; _isTesting = false; } } - }); + return; + } + + lock (Lock) + { + if (!ReferenceEquals(_activeOperation, operation)) + return; + + _activeOperation = null; + _isTesting = false; + _lastStatus = status; + _lastLatencyMs = latencyMs; + _lastTokensUsed = tokensUsed; + _lastSnippet = snippet; + _lastError = error; + _statusColor = color; + } } } } diff --git a/Source/Infrastructure/UI/DebugTables/DebugTableModels.cs b/Source/Infrastructure/UI/DebugTables/DebugTableModels.cs index 318f3a4c..865a2a99 100644 --- a/Source/Infrastructure/UI/DebugTables/DebugTableModels.cs +++ b/Source/Infrastructure/UI/DebugTables/DebugTableModels.cs @@ -123,7 +123,7 @@ public static string Preview(string? value, int maxChars = PreviewChars) int safeMaxChars = System.Math.Max(1, maxChars); - string oneLine = value + string oneLine = value! .Replace("\r", " ") .Replace("\n", " ") .Replace("<", "[") diff --git a/Source/Infrastructure/UI/MainTabWindow_RimMindHub.cs b/Source/Infrastructure/UI/MainTabWindow_RimMindHub.cs index d9888a5c..8e4f7b9e 100644 --- a/Source/Infrastructure/UI/MainTabWindow_RimMindHub.cs +++ b/Source/Infrastructure/UI/MainTabWindow_RimMindHub.cs @@ -84,7 +84,7 @@ protected override void DrawContents(Rect inRect, RimMindLayoutScope scope) string? requestedPageId = _navigation.ConsumeRequestedPageId(); if (!string.IsNullOrEmpty(requestedPageId)) - _pageId = ResolvePageId(requestedPageId); + _pageId = ResolvePageId(requestedPageId!); } private IReadOnlyList BuildTabModels() diff --git a/Source/Infrastructure/UI/WindowService.cs b/Source/Infrastructure/UI/WindowService.cs index 50e1d330..03794536 100644 --- a/Source/Infrastructure/UI/WindowService.cs +++ b/Source/Infrastructure/UI/WindowService.cs @@ -7,7 +7,8 @@ public class WindowService : IWindowService { public void OpenAgentDialogue(object pawn) { - Find.WindowStack.Add(new Window_AgentDialogue(pawn as Pawn)); + if (pawn is Pawn p) + Find.WindowStack.Add(new Window_AgentDialogue(p)); } public void OpenRequestLog() diff --git a/Source/Infrastructure/UI/Window_AgentDialogue.cs b/Source/Infrastructure/UI/Window_AgentDialogue.cs index 965d32b9..7099d9e8 100644 --- a/Source/Infrastructure/UI/Window_AgentDialogue.cs +++ b/Source/Infrastructure/UI/Window_AgentDialogue.cs @@ -237,14 +237,14 @@ private void SendMessage() var envelope = LlmRequestEnvelopeBuilder .ForNpc(agent.NpcId ?? $"NPC-{_pawn.thingIDNumber}", gameStateInfo: new GameStateInfo().AddSection("dialogue_input", message)) .ForScenarioId(ScenarioIds.Dialogue) - .WithModId("RimMind.Dialogue") + .WithModId(RimMind.Application.Common.Constants.RimMindOwnerConsts.CoreModId) .WithMaxTokens(settings?.MaxTokens ?? RimMindDefaults.MaxTokens) .WithTemperature(settings?.DefaultTemperature ?? RimMindDefaults.DefaultTemperature) .Streaming(chunk => { // Background thread: append under lock only; OnGUI reads a snapshot. if (!string.IsNullOrEmpty(chunk.DeltaContent)) - AppendStreamDelta(request, chunk.DeltaContent); + AppendStreamDelta(request, chunk.DeltaContent!); }) .Build(); diff --git a/Source/Infrastructure/UI/Window_AgentModeDebug.cs b/Source/Infrastructure/UI/Window_AgentModeDebug.cs index 76ffe82e..3e35d1fc 100644 --- a/Source/Infrastructure/UI/Window_AgentModeDebug.cs +++ b/Source/Infrastructure/UI/Window_AgentModeDebug.cs @@ -416,16 +416,13 @@ private void RefreshPawnCache() var map = Find.CurrentMap; if (map == null) return; - var allPawns = map.mapPawns?.AllPawns; - if (allPawns != null) + var colonists = RimMind.Presentation.Api.RimMindPawnLookup.GetSpawnedColonistsSafe(map); + for (int i = 0; i < colonists.Count; i++) { - for (int i = 0; i < allPawns.Count; i++) - { - Pawn pawn = allPawns[i]; - var comp = CompPawnAgent.GetComp(pawn); - if (comp?.Agent != null) - _cachedPawns.Add(pawn); - } + Pawn pawn = colonists[i]; + var comp = CompPawnAgent.GetComp(pawn); + if (comp?.Agent != null) + _cachedPawns.Add(pawn); } if (_initialPawn != null && _selectedPawnIndex < 0) diff --git a/Source/Infrastructure/UI/Window_ContextPayloadInspector.cs b/Source/Infrastructure/UI/Window_ContextPayloadInspector.cs index bd8e9114..df1f6810 100644 --- a/Source/Infrastructure/UI/Window_ContextPayloadInspector.cs +++ b/Source/Infrastructure/UI/Window_ContextPayloadInspector.cs @@ -144,13 +144,10 @@ public override void PostOpen() private void EnsurePawnSelection() { - if (_selectedPawn == null || _selectedPawn.Dead) + if (_selectedPawn == null || !RimMind.Presentation.Api.RimMindPawnLookup.IsActiveSpawnedColonist(_selectedPawn)) { - var colonists = Find.CurrentMap?.mapPawns?.FreeColonists?.Where(p => !p.Dead).ToList(); - if (colonists != null && colonists.Count > 0) - { - _selectedPawn = colonists[0]; - } + var colonists = RimMind.Presentation.Api.RimMindPawnLookup.GetSpawnedColonistsSafe(Find.CurrentMap); + _selectedPawn = colonists.Count > 0 ? colonists[0] : null; } } @@ -228,7 +225,7 @@ private void DrawSidebar(Rect rect) Widgets.Label(titleRect, "RimMind.Inspector.ColonistsList".Translate()); GUI.color = Color.white; - var colonists = Find.CurrentMap?.mapPawns?.FreeColonists?.Where(p => !p.Dead).ToList() ?? new List(); + var colonists = RimMind.Presentation.Api.RimMindPawnLookup.GetSpawnedColonistsSafe(Find.CurrentMap); float rowHeight = 28f; Rect viewRect = new Rect(0f, 0f, rect.width - 16f, colonists.Count * rowHeight); Rect scrollRect = new Rect(rect.x + 4f, rect.y + 30f, rect.width - 8f, rect.height - 34f); diff --git a/Source/Infrastructure/UI/Window_RequestLog.cs b/Source/Infrastructure/UI/Window_RequestLog.cs index d8f5b0d1..4be44ba4 100644 --- a/Source/Infrastructure/UI/Window_RequestLog.cs +++ b/Source/Infrastructure/UI/Window_RequestLog.cs @@ -188,18 +188,15 @@ private void DrawEmptyState(Rect rect, RequestLogOperationContext context) bool hasAgent = false; var map = Find.CurrentMap; - var allPawns = map?.mapPawns?.AllPawns; - if (allPawns != null) + var colonists = RimMind.Presentation.Api.RimMindPawnLookup.GetSpawnedColonistsSafe(map); + for (int i = 0; i < colonists.Count; i++) { - for (int i = 0; i < allPawns.Count; i++) + Pawn pawn = colonists[i]; + var comp = CompPawnAgent.GetComp(pawn); + if (comp?.Agent != null) { - Pawn pawn = allPawns[i]; - var comp = CompPawnAgent.GetComp(pawn); - if (comp?.Agent != null) - { - hasAgent = true; - break; - } + hasAgent = true; + break; } } if (!hasAgent) diff --git a/Source/Infrastructure/UI/Window_ToolCallDebug.cs b/Source/Infrastructure/UI/Window_ToolCallDebug.cs index 244c33cf..23b21c8d 100644 --- a/Source/Infrastructure/UI/Window_ToolCallDebug.cs +++ b/Source/Infrastructure/UI/Window_ToolCallDebug.cs @@ -281,65 +281,89 @@ private void ExecuteTool(string toolId) var handler = registry.FindById(toolId); if (handler == null) { - _executionResult = "RimMind.UI.ToolCallDebug.Failed".Translate(0) + "\n" + "RimMind.UI.ToolCallDebug.Id".Translate(toolId); + _executionResult = RimMind.Presentation.Api.RimMindText.TrOr("RimMind.UI.ToolCallDebug.Failed", "Failed ({0}ms)", 0) + + "\n" + + RimMind.Presentation.Api.RimMindText.TrOr("RimMind.UI.ToolCallDebug.Id", "ID: {0}", toolId); return; } _isExecuting = true; - _executionResult = "RimMind.UI.ToolCallDebug.Executing".Translate(); + _executionResult = RimMind.Presentation.Api.RimMindText.TrOr("RimMind.UI.ToolCallDebug.Executing", "Executing..."); var operation = new ToolExecutionOperation(runtimeScope.Token); _activeExecution = operation; string jsonInput = _jsonInput; var sw = Stopwatch.StartNew(); + var args = new ToolCallArgs + { + ToolCallId = "debug-1", + ToolName = toolId, + ArgumentsJson = jsonInput, + PawnId = null, + NpcId = null, + Ct = CancellationToken.None, + TraceId = "debug" + }; + + // Invoke handler.ExecuteAsync on the Unity main thread so Verse/RimWorld tool handlers never + // touch game state from a ThreadPool thread; marshal async continuations back to MainThread. + Task> execTask; + try + { + execTask = handler.ExecuteAsync(args, CancellationToken.None); + } + catch (Exception ex) + { + sw.Stop(); + long elapsed = sw.ElapsedMilliseconds; + string status = RimMind.Presentation.Api.RimMindText.TrOr("RimMind.UI.ToolCallDebug.Failed", "Failed ({0}ms)", elapsed); + TryPublishExecution(operation, () => _executionResult = status + "\n" + ex.Message); + return; + } - Task.Run(async () => + execTask.ContinueWith(completed => { - try - { - var args = new ToolCallArgs - { - ToolCallId = "debug-1", - ToolName = toolId, - ArgumentsJson = jsonInput, - PawnId = null, - NpcId = null, - Ct = CancellationToken.None, - TraceId = "debug" - }; - - var result = await handler.ExecuteAsync(args, CancellationToken.None); - sw.Stop(); - long elapsed = sw.ElapsedMilliseconds; - - // Translation and UI state are main-thread only; capture plain data here. - bool succeeded = result.IsOk && !result.Value.IsError; - string detail = result.IsOk - ? Truncate(result.Value.Content, (int)TruncateLen) - : result.Error.Message; + sw.Stop(); + long elapsed = sw.ElapsedMilliseconds; + if (completed.IsFaulted) + { + Exception root = completed.Exception?.GetBaseException() ?? completed.Exception!; + string message = root?.Message ?? "Unknown error"; RimMind.Presentation.Api.RimMindAPI.MainThread.Post(() => { - string statusKey = succeeded - ? "RimMind.UI.ToolCallDebug.Success" - : "RimMind.UI.ToolCallDebug.Failed"; - string status = statusKey.Translate(elapsed); - TryPublishExecution(operation, () => _executionResult = status + "\n" + detail); + string status = RimMind.Presentation.Api.RimMindText.TrOr("RimMind.UI.ToolCallDebug.Failed", "Failed ({0}ms)", elapsed); + TryPublishExecution(operation, () => _executionResult = status + "\n" + message); }); + return; } - catch (Exception ex) - { - sw.Stop(); - long elapsed = sw.ElapsedMilliseconds; - string message = ex.Message; + if (completed.IsCanceled) + { RimMind.Presentation.Api.RimMindAPI.MainThread.Post(() => { - string status = "RimMind.UI.ToolCallDebug.Failed".Translate(elapsed); - TryPublishExecution(operation, () => _executionResult = status + "\n" + message); + string status = RimMind.Presentation.Api.RimMindText.TrOr("RimMind.UI.ToolCallDebug.Failed", "Failed ({0}ms)", elapsed); + TryPublishExecution(operation, () => _executionResult = status + "\nCanceled"); }); + return; } - }); + + var result = completed.Result; + bool succeeded = result.IsOk && !result.Value.IsError; + string detail = result.IsOk + ? Truncate(result.Value.Content, (int)TruncateLen) + : result.Error.Message; + + RimMind.Presentation.Api.RimMindAPI.MainThread.Post(() => + { + string statusKey = succeeded + ? "RimMind.UI.ToolCallDebug.Success" + : "RimMind.UI.ToolCallDebug.Failed"; + string fallback = succeeded ? "Success ({0}ms)" : "Failed ({0}ms)"; + string status = RimMind.Presentation.Api.RimMindText.TrOr(statusKey, fallback, elapsed); + TryPublishExecution(operation, () => _executionResult = status + "\n" + detail); + }); + }, TaskScheduler.Default); } private void RefreshExecutionFence() @@ -360,7 +384,7 @@ private bool TryPublishExecution(ToolExecutionOperation operation, Action publis else { operation.RecordStaleOnce(RuntimeServiceHub.Shared); - _executionResult = "RimMind.UI.Lifecycle.StaleCompletion".Translate(); + _executionResult = RimMind.Presentation.Api.RimMindText.TrOr("RimMind.UI.Lifecycle.StaleCompletion", "Discarded stale completion."); } _activeExecution = null; diff --git a/Source/Infrastructure/Verse/AgentBusGameComponent.cs b/Source/Infrastructure/Verse/AgentBusGameComponent.cs index a231daa4..8078d7b5 100644 --- a/Source/Infrastructure/Verse/AgentBusGameComponent.cs +++ b/Source/Infrastructure/Verse/AgentBusGameComponent.cs @@ -13,15 +13,46 @@ namespace RimMind.Infrastructure.Verse { - public class AgentBusGameComponent : GameComponent + public class AgentBusGameComponent : GameComponent, IDisposable { + private static readonly object ActiveLock = new object(); + private static AgentBusGameComponent? _activeInstance; + private readonly RuntimeBinding _binding = new RuntimeBinding(); private AgentBusQueueTickCoordinator? _tickCoordinator; public AgentBusGameComponent(Game game) : base() { } + private void RegisterAsActive() + { + AgentBusGameComponent? previous = null; + lock (ActiveLock) + { + if (!ReferenceEquals(_activeInstance, this)) + { + previous = _activeInstance; + _activeInstance = this; + } + } + + previous?.Dispose(); + } + + internal static void DisposeActiveInstance() + { + AgentBusGameComponent? active; + lock (ActiveLock) + { + active = _activeInstance; + _activeInstance = null; + } + + active?.Dispose(); + } + private void Refresh() { + RegisterAsActive(); _binding.Refresh(Bind); } @@ -100,6 +131,12 @@ public override void GameComponentUpdate() public void Dispose() { + lock (ActiveLock) + { + if (ReferenceEquals(_activeInstance, this)) + _activeInstance = null; + } + _binding.Dispose(); _tickCoordinator = null; } @@ -125,4 +162,22 @@ public void Dispose() } } } + + internal sealed class AgentBusGameLifecycleService : RimMind.Application.Common.Interfaces.Extension.IGameScopedService + { + public static readonly AgentBusGameLifecycleService Instance = new AgentBusGameLifecycleService(); + + public string Id => "core.agent_bus.game_lifecycle"; + + public string OwnerModId => RimMind.Application.Common.Constants.RimMindOwnerConsts.CoreModId; + + public void OnGameStarted() + { + } + + public void OnGameStopped() + { + AgentBusGameComponent.DisposeActiveInstance(); + } + } } diff --git a/Source/Infrastructure/Verse/CompPawnAgent.cs b/Source/Infrastructure/Verse/CompPawnAgent.cs index d78d1089..8a127ff4 100644 --- a/Source/Infrastructure/Verse/CompPawnAgent.cs +++ b/Source/Infrastructure/Verse/CompPawnAgent.cs @@ -166,6 +166,10 @@ private void TearDownAgent() public override void PostDeSpawn(Map map, DestroyMode mode = DestroyMode.Vanish) { + if (parent is Pawn pawn) + { + RimMind.Presentation.Api.RimMindPawnLookup.UncachePawn(pawn); + } UnregisterFromAgentLoop(); ClearIntentSession(); base.PostDeSpawn(map, mode); @@ -234,13 +238,13 @@ public override void PostExposeData() public override IEnumerable CompGetGizmosExtra() { - if (!(parent is Pawn pawn)) + if (!(parent is Pawn pawn) || !RimMind.Presentation.Api.RimMindPawnLookup.IsActiveSpawnedColonist(pawn)) yield break; yield return new Command_Action { - defaultLabel = "RimMind.Agent.Gizmo.Control".Translate(), - defaultDesc = "RimMind.Agent.Gizmo.ControlDesc".Translate(), + defaultLabel = RimMind.Presentation.Api.RimMindText.TrOr("RimMind.Agent.Gizmo.Control", "AI Agent"), + defaultDesc = RimMind.Presentation.Api.RimMindText.TrOr("RimMind.Agent.Gizmo.ControlDesc", "Open RimMind AI Agent control panel."), icon = AgentIcon, action = () => { @@ -252,8 +256,8 @@ public override IEnumerable CompGetGizmosExtra() { yield return new Command_Action { - defaultLabel = "RimMind.Agent.Gizmo.DevView".Translate(), - defaultDesc = "RimMind.Agent.Gizmo.DevViewDesc".Translate(), + defaultLabel = RimMind.Presentation.Api.RimMindText.TrOr("RimMind.Agent.Gizmo.DevView", "Agent Debug"), + defaultDesc = RimMind.Presentation.Api.RimMindText.TrOr("RimMind.Agent.Gizmo.DevViewDesc", "Log AI Agent debug info."), icon = AgentDevIcon, action = () => { diff --git a/Source/Infrastructure/Verse/HistoryManagerGameComponent.cs b/Source/Infrastructure/Verse/HistoryManagerGameComponent.cs index 97b0c52b..753cf602 100644 --- a/Source/Infrastructure/Verse/HistoryManagerGameComponent.cs +++ b/Source/Infrastructure/Verse/HistoryManagerGameComponent.cs @@ -52,6 +52,14 @@ public override void ExposeData() } } + public override void StartedNewGame() + { + base.StartedNewGame(); + _restorePending = false; + _serializedHistory = EmptyHistory; + _historyManager.ValueOrDefault?.LoadFromSave(new Dictionary>()); + } + public override void LoadedGame() { base.LoadedGame(); diff --git a/Source/Infrastructure/Verse/ITab_Pawn_Agent.cs b/Source/Infrastructure/Verse/ITab_Pawn_Agent.cs index 3975bdaa..7be936e1 100644 --- a/Source/Infrastructure/Verse/ITab_Pawn_Agent.cs +++ b/Source/Infrastructure/Verse/ITab_Pawn_Agent.cs @@ -4,6 +4,7 @@ using RimMind.Application.Common.Models.Agent; using RimMind.Domain.Enums; using RimMind.Infrastructure.UI; +using RimMind.Presentation.Api; using RimMind.Presentation.Runtime.Services; using RimMind.Presentation.UI.Layout; using RimMind.Presentation.Agent; @@ -25,12 +26,14 @@ public ITab_Pawn_Agent() labelKey = "RimMind.Agent.ITab.Label"; } - private Pawn SelectedPawn => SelThing as Pawn; + private Pawn? SelectedPawn => SelThing as Pawn; + + public override bool IsVisible => SelectedPawn != null && RimMindPawnLookup.IsActiveSpawnedColonist(SelectedPawn); protected override void FillTabContents(Rect inRect, RimMindLayoutScope scope) { var pawn = SelectedPawn; - if (pawn == null) return; + if (pawn == null || !RimMindPawnLookup.IsActiveSpawnedColonist(pawn)) return; var comp = CompPawnAgent.GetComp(pawn); var agent = comp?.Agent; @@ -53,28 +56,28 @@ protected override void FillTabContents(Rect inRect, RimMindLayoutScope scope) float curY = 0f; // ── Section: Status ── - curY = RimMindUI.DrawSectionHeader(contentRect, curY, "RimMind.Agent.ITab.Status".Translate()); + curY = RimMindUI.DrawSectionHeader(contentRect, curY, RimMindText.TrOr("RimMind.Agent.ITab.Status", "Status")); var (stateTextColor, stateBgColor) = RimMindUI.GetStateBadgeColors( agent.State == AgentState.Active, agent.State == AgentState.Paused); string stateKey = $"RimMind.Agent.State.{agent.State}"; - string stateLabel = stateKey.CanTranslate() ? (string)stateKey.Translate() : agent.State.ToString(); + string stateLabel = RimMindText.TrOr(stateKey, agent.State.ToString()); curY = RimMindUI.DrawStatusBadge(contentRect, curY, stateLabel, stateTextColor, stateBgColor); - curY = RimMindUI.DrawKeyValueRow(contentRect, curY, "RimMind.Agent.ITab.Mode".Translate(), agent.CurrentModeId.Value); + curY = RimMindUI.DrawKeyValueRow(contentRect, curY, RimMindText.TrOr("RimMind.Agent.ITab.Mode", "Mode"), agent.CurrentModeId.Value); - curY = RimMindUI.DrawKeyValueRow(contentRect, curY, "WorkflowPhase", agent.WorkflowPhase.ToString()); - curY = RimMindUI.DrawKeyValueRow(contentRect, curY, "Autonomy", agent.AutonomyLevel.ToString()); + curY = RimMindUI.DrawKeyValueRow(contentRect, curY, RimMindText.TrOr("RimMind.Agent.ITab.WorkflowPhase", "Workflow Phase"), agent.WorkflowPhase.ToString()); + curY = RimMindUI.DrawKeyValueRow(contentRect, curY, RimMindText.TrOr("RimMind.Agent.ITab.Autonomy", "Autonomy"), agent.AutonomyLevel.ToString()); // ── Section: Goals ── curY = RimMindUI.DrawDivider(contentRect, curY); - curY = RimMindUI.DrawSectionHeader(contentRect, curY, "RimMind.Agent.ITab.Goals".Translate()); + curY = RimMindUI.DrawSectionHeader(contentRect, curY, RimMindText.TrOr("RimMind.Agent.ITab.Goals", "Goals")); var goals = agent.GoalStack.Goals; if (goals.Count == 0) { - curY = RimMindUI.DrawWrappedLabel(contentRect, curY, " (none)", RimMindUI.ColorMuted); + curY = RimMindUI.DrawWrappedLabel(contentRect, curY, " " + RimMindText.TrOr("RimMind.Agent.ITab.None", "(none)"), RimMindUI.ColorMuted); } else { @@ -93,12 +96,12 @@ protected override void FillTabContents(Rect inRect, RimMindLayoutScope scope) // ── Section: Strategy ── curY = RimMindUI.DrawDivider(contentRect, curY); - curY = RimMindUI.DrawSectionHeader(contentRect, curY, "RimMind.Agent.ITab.Strategy".Translate()); + curY = RimMindUI.DrawSectionHeader(contentRect, curY, RimMindText.TrOr("RimMind.Agent.ITab.Strategy", "Strategy")); var topW = agent.StrategyOptimizer.GetTopN(5); if (topW.Count == 0) { - curY = RimMindUI.DrawWrappedLabel(contentRect, curY, " (no data)", RimMindUI.ColorMuted); + curY = RimMindUI.DrawWrappedLabel(contentRect, curY, " " + RimMindText.TrOr("RimMind.Agent.ITab.NoData", "(no data)"), RimMindUI.ColorMuted); } else { @@ -110,12 +113,12 @@ protected override void FillTabContents(Rect inRect, RimMindLayoutScope scope) // ── Section: History ── curY = RimMindUI.DrawDivider(contentRect, curY); - curY = RimMindUI.DrawSectionHeader(contentRect, curY, "RimMind.Agent.ITab.History".Translate()); + curY = RimMindUI.DrawSectionHeader(contentRect, curY, RimMindText.TrOr("RimMind.Agent.ITab.History", "History")); var recent = agent.GetRecentHistory(5); if (recent.Count == 0) { - curY = RimMindUI.DrawWrappedLabel(contentRect, curY, " (no history)", RimMindUI.ColorMuted); + curY = RimMindUI.DrawWrappedLabel(contentRect, curY, " " + RimMindText.TrOr("RimMind.Agent.ITab.NoHistory", "(no history)"), RimMindUI.ColorMuted); } else { @@ -134,7 +137,7 @@ protected override void FillTabContents(Rect inRect, RimMindLayoutScope scope) { curY = RimMindUI.DrawDivider(contentRect, curY); Rect inspectBtn = new Rect(contentRect.x, curY, 180f, 26f); - if (Widgets.ButtonText(inspectBtn, "RimMind.Inspector.OpenButton".Translate())) + if (Widgets.ButtonText(inspectBtn, RimMindText.TrOr("RimMind.Inspector.OpenButton", "Inspect Context Payload"))) { Find.WindowStack.Add(new Window_ContextPayloadInspector(agent.Pawn)); } @@ -149,14 +152,22 @@ private void DrawNoAgentState(Rect rect, Pawn pawn, CompPawnAgent? comp, RimMind float y = rect.y; scope.Record(rect, "EmptyState:NoAgent"); - RimMindUI.DrawEmptyState(rect, "RimMind.Agent.ITab.NoAgent".Translate(), - "RimMind.Agent.ITab.NoAgentHint".Translate()); + RimMindUI.DrawEmptyState(rect, + RimMindText.TrOr("RimMind.Agent.ITab.NoAgent", "No AI Agent"), + RimMindText.TrOr("RimMind.Agent.ITab.NoAgentHint", "Create an AI Agent for this colonist.")); y = rect.y + rect.height - 40f; Rect createBtn = new Rect(rect.x, y, 160f, 28f); scope.Record(createBtn, "Button:CreateAgent"); - if (Widgets.ButtonText(createBtn, "RimMind.Agent.ITab.CreateAgent".Translate())) + if (Widgets.ButtonText(createBtn, RimMindText.TrOr("RimMind.Agent.ITab.CreateAgent", "Create Agent"))) { + if (!RimMindPawnLookup.IsActiveSpawnedColonist(pawn)) + { + Messages.Message(RimMindText.TrOr("RimMind.Agent.ITab.CreateFailed", "Failed to create AI Agent."), + MessageTypeDefOf.RejectInput, false); + return; + } + RuntimeServiceScope runtimeScope = RuntimeServiceHub.Shared.Capture(); var factory = runtimeScope.GetOptional(); var agentBus = runtimeScope.GetOptional(); @@ -171,13 +182,13 @@ private void DrawNoAgentState(Rect rect, Pawn pawn, CompPawnAgent? comp, RimMind else if (createdAgent != null) { RuntimeServiceHub.Shared.RecordStaleCompletion(LifecycleEventSources.PawnAgentTab); - Messages.Message("RimMind.Agent.ITab.CreateFailed".Translate(), + Messages.Message(RimMindText.TrOr("RimMind.Agent.ITab.CreateFailed", "Failed to create AI Agent."), MessageTypeDefOf.RejectInput, false); } } else { - Messages.Message("RimMind.Agent.ITab.CreateFailed".Translate(), + Messages.Message(RimMindText.TrOr("RimMind.Agent.ITab.CreateFailed", "Failed to create AI Agent."), MessageTypeDefOf.RejectInput, false); } } diff --git a/Source/Infrastructure/Verse/NpcManager.cs b/Source/Infrastructure/Verse/NpcManager.cs index 04751bf0..1e5f94fe 100644 --- a/Source/Infrastructure/Verse/NpcManager.cs +++ b/Source/Infrastructure/Verse/NpcManager.cs @@ -63,7 +63,11 @@ public void IndexPawn(Pawn pawn) } } - void INpcManager.IndexPawn(object pawn) => IndexPawn(pawn as Pawn); + void INpcManager.IndexPawn(object pawn) + { + if (pawn is Pawn p) + IndexPawn(p); + } public void UnindexPawn(int thingId) { diff --git a/Source/Presentation/Agent/MapContextBuilder.cs b/Source/Presentation/Agent/MapContextBuilder.cs index 2abd6f0a..eac09f0b 100644 --- a/Source/Presentation/Agent/MapContextBuilder.cs +++ b/Source/Presentation/Agent/MapContextBuilder.cs @@ -237,7 +237,7 @@ public List BuildMapContextEntries(Map map, bool brief = false) entries.Add(new ContextEntry(RimMindText.Tr("RimMind.Prompt.MapStatusHeader"))); - if (ctx.IncludeGameTime) + if (ctx.IncludeGameTime && Find.TickManager != null && Find.WorldGrid != null) { long ticks = Find.TickManager.TicksAbs; Vector2 longLat = Find.WorldGrid.LongLatOf(map.Tile); @@ -388,7 +388,7 @@ public PromptSection BuildMapContextSection(Map map, bool brief = false) private static string CompressRenderedMapContext(string? raw) { if (string.IsNullOrEmpty(raw)) return string.Empty; - var lines = raw.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None); + var lines = raw!.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None); var sb = new StringBuilder(); foreach (var line in lines) { diff --git a/Source/Presentation/Agent/PawnAgent.cs b/Source/Presentation/Agent/PawnAgent.cs index 8bca13bb..421f6008 100644 --- a/Source/Presentation/Agent/PawnAgent.cs +++ b/Source/Presentation/Agent/PawnAgent.cs @@ -232,8 +232,9 @@ public bool TransitionTo(AgentState newState) public void AddGoal(AgentGoal goal) { - if (goal != null && goal is not SerializableAgentGoal) - _log?.Warning($"[RimMind.Agent] action=NonSerializableGoal npcId={Identity.NpcId} goal={goal.Description}"); + if (goal == null) return; + if (goal is not SerializableAgentGoal) + _log?.Warning($"[RimMind.Agent] action=NonSerializableGoal npcId={Identity?.NpcId} goal={goal.Description}"); GoalStack.TryAdd(goal, Pawn.thingIDNumber); } @@ -379,12 +380,12 @@ private void SubmitDecisionForApproval(AgentDecision decision, RiskLevel riskLev { if (choice == approveLabel) { - _log?.Message($"[RimMind.Agent] action=ApprovedActionExecuting npcId={Identity.NpcId} intent={intent}"); + _log?.Message($"[RimMind.Agent] action=ApprovedActionExecuting npcId={Identity?.NpcId} intent={intent}"); _actor.ExecuteDecision(decision); } else { - _log?.Message($"[RimMind.Agent] action=RejectedAction npcId={Identity.NpcId} intent={intent}"); + _log?.Message($"[RimMind.Agent] action=RejectedAction npcId={Identity?.NpcId} intent={intent}"); } }, completionCallback = completionReason => @@ -392,7 +393,7 @@ private void SubmitDecisionForApproval(AgentDecision decision, RiskLevel riskLev if (completionReason == RequestCompletionReason.Selected) return; - _log?.Message($"[RimMind.Agent] action=ApprovalDismissedOrExpired npcId={Identity.NpcId} intent={intent} reason={completionReason}"); + _log?.Message($"[RimMind.Agent] action=ApprovalDismissedOrExpired npcId={Identity?.NpcId} intent={intent} reason={completionReason}"); } }; @@ -402,7 +403,7 @@ private void SubmitDecisionForApproval(AgentDecision decision, RiskLevel riskLev } catch (Exception ex) { - _log?.Warning($"[RimMind.Agent] Failed to register pending request for {Identity.NpcId}: {ex.Message}"); + _log?.Warning($"[RimMind.Agent] Failed to register pending request for {Identity?.NpcId}: {ex.Message}"); } } @@ -517,9 +518,8 @@ public void Destroy() // Clean up resources Cleanup(); - // Note: AgentBus uses key-based subscriptions, but PawnAgent doesn't track its subscription keys. - // The AgentBus.ClearAllSubscribers() in AgentBusGameComponent handles full cleanup on game load. - // Individual agent unsubscription requires tracking subscription keys (future enhancement). + // AgentBus subscribers owned by the game component are released via AgentBusGameComponent.Dispose() + // during CoreGameLifecycleCleanupService.OnGameStopped() and on new/loaded game rebind. } public string GetDebugInfo() diff --git a/Source/Presentation/Agent/PawnThinker.cs b/Source/Presentation/Agent/PawnThinker.cs index f7e37a36..f008a275 100644 --- a/Source/Presentation/Agent/PawnThinker.cs +++ b/Source/Presentation/Agent/PawnThinker.cs @@ -39,7 +39,7 @@ public class PawnThinker : IPawnThinker private readonly ProactiveBehaviorExecutor _proactiveExecutor; private readonly ThinkContextEnricher _contextEnricher; private readonly ILogSink? _log; - private readonly IDecisionProcessor _decisionProcessor; + private readonly DecisionProcessor _decisionProcessor; private readonly InnerVoiceHandler? _innerVoiceHandler; private readonly IPsychologyWatcher? _psychologyWatcher; private readonly ITickProvider _tickProvider; @@ -187,7 +187,7 @@ private void Think() _activeRolloutId = $"rollout-{_agent.Identity.NpcId}-{Find.TickManager?.TicksGame ?? 0}-{Guid.NewGuid().ToString("N").Substring(0, 6)}"; var envelope = strategy.BuildEnvelope(_agent, entries, availableTools); EnrichEnvelope(envelope, voiceText); - _requestSentTick = Find.TickManager.TicksGame; + _requestSentTick = Find.TickManager?.TicksGame ?? 0; _requestSentUtc = DateTime.UtcNow; SendThinkRequest(envelope, strategy, availableTools, 0); } diff --git a/Source/Presentation/Agent/ProactiveBehaviorExecutor.cs b/Source/Presentation/Agent/ProactiveBehaviorExecutor.cs index fb9a184f..35ab88b2 100644 --- a/Source/Presentation/Agent/ProactiveBehaviorExecutor.cs +++ b/Source/Presentation/Agent/ProactiveBehaviorExecutor.cs @@ -62,7 +62,8 @@ public void ExecuteProactiveExtensions(IPawnAgent agent, IAgentMode mode, int pa pawnId, _log, behaviorRegistry: behaviorRegistry, - completionFence: _completionFence); + completionFence: _completionFence, + mainThreadDispatch: RimMindAPI.MainThread.Post); } int currentTick = Find.TickManager?.TicksGame ?? 0; _cachedOrchestrator.ExecuteAll(agent, currentTick); diff --git a/Source/Presentation/Api/CompositeToolCallBase.cs b/Source/Presentation/Api/CompositeToolCallBase.cs index 5f1b1127..7a71561e 100644 --- a/Source/Presentation/Api/CompositeToolCallBase.cs +++ b/Source/Presentation/Api/CompositeToolCallBase.cs @@ -98,17 +98,79 @@ public virtual ToolPolicyDecision Classify(ToolCallArgs args) } protected static JObject? TryParseArgumentsObject(string? argumentsJson) + => CompositeToolExecutionTemplate.TryParseArgumentsObject(argumentsJson); + + /// + /// Runs the shared composite-tool execution template: cancellation check, single-pass JSON parsing, + /// optional Unity main-thread guard, and structured exception-to- mapping. + /// + protected Task> ExecuteTemplateAsync( + ToolCallArgs? args, + Func>> body, + CancellationToken ct, + bool requireMainThread = true) { - if (string.IsNullOrWhiteSpace(argumentsJson)) - return null; - try - { - return JToken.Parse(argumentsJson!) as JObject; - } - catch - { - return null; - } + return CompositeToolExecutionTemplate.ExecuteWithGuardsAsync( + Id, + args, + requireMainThread ? (_, effectiveArgs) => EnsureMainThread(effectiveArgs) : null, + body, + ct); + } + + /// + /// Runs the full colonist-targeted composite-tool template: main-thread guard, single-pass JSON parsing, + /// pawn_id resolution, active spawned colonist liveness verification, autonomy policy check, and + /// structured exception handling. Eliminates repeated boilerplate in colonist-scoped tools. + /// + protected Task> ExecuteColonistToolAsync( + ToolCallArgs? args, + Func>> body, + CancellationToken ct, + string pawnIdKey = "pawn_id", + AutonomyDomain? domainOverride = null) + { + if (body == null) + throw new ArgumentNullException(nameof(body)); + + Verse.Pawn? resolvedPawn = null; + + return CompositeToolExecutionTemplate.ExecuteWithGuardsAsync( + Id, + args, + (root, effectiveArgs) => + { + var threadGuard = EnsureMainThread(effectiveArgs); + if (threadGuard.IsErr) + return threadGuard; + + var pawnIdResult = TryGetPawnIdOrError(root, effectiveArgs, pawnIdKey); + if (pawnIdResult.IsErr) + return Result.Err(pawnIdResult.Error); + + int pawnId = pawnIdResult.Value; + var pawn = RimMindPawnLookup.FindPawnByNumber(pawnId); + if (pawn == null || !RimMindPawnLookup.IsActiveSpawnedColonist(pawn)) + { + return Result.Err( + CompositeToolExecutionTemplate.InvalidActionError( + $"{pawnIdKey} {pawnId} is not an active spawned colonist", + effectiveArgs.TraceId)); + } + + var domain = domainOverride ?? ResolveAutonomyDomain(root, effectiveArgs); + if (domain.HasValue) + { + var permission = CheckPermission(pawn, domain.Value, effectiveArgs); + if (permission.IsErr) + return permission; + } + + resolvedPawn = pawn; + return Result.Ok(Unit.Value); + }, + (root, effectiveArgs, token) => body(resolvedPawn!, root, effectiveArgs, token), + ct); } protected virtual IToolHandler? FindTool(string toolId) => RimMindAPI.Tools.FindById(toolId); @@ -253,39 +315,7 @@ protected virtual Result CheckPermission( /// 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; - } - } + => CompositeToolExecutionTemplate.TryGetArgument(root, key, out value); /// /// Reads a typed argument from raw JSON arguments. Prefer the overload when reading multiple keys. @@ -298,52 +328,15 @@ protected static bool TryGetArgument(string? argumentsJson, string key, out T 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 - }); - } + => CompositeToolExecutionTemplate.TryGetArgumentOrError(root, key, 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 - }); - } + => CompositeToolExecutionTemplate.TryGetArgumentOrError(TryParseArgumentsObject(argumentsJson), key, 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 - }); - } + => CompositeToolExecutionTemplate.TryGetPawnIdOrError(root, args, key); protected static Result TryGetPawnIdOrError( ToolCallArgs args, string key = "pawn_id") diff --git a/Source/Presentation/Api/RimMindAPI.Bus.cs b/Source/Presentation/Api/RimMindAPI.Bus.cs index a94affcc..7f549462 100644 --- a/Source/Presentation/Api/RimMindAPI.Bus.cs +++ b/Source/Presentation/Api/RimMindAPI.Bus.cs @@ -79,9 +79,6 @@ public static bool DismissPendingRequest(RequestEntry entry) public static void InvalidateClientCache() => CurrentRuntime.InvalidateClientCache(); - - public static IAIClient? GetPlayer2Client() - => CurrentRuntime.GetPlayer2Client(); } } } diff --git a/Source/Presentation/Api/RimMindAPI.Context.cs b/Source/Presentation/Api/RimMindAPI.Context.cs index c101c990..0a31359c 100644 --- a/Source/Presentation/Api/RimMindAPI.Context.cs +++ b/Source/Presentation/Api/RimMindAPI.Context.cs @@ -87,13 +87,13 @@ public static int GetScenarioBaseRounds(string scenarioId) private static SchemaRegistry Schemas => SchemaRegistries.Value; public static string SchemaPersonalityOutput - => Schemas.PersonalityOutput; + => Schemas.Find("PersonalityOutput") ?? string.Empty; public static string SchemaIncidentOutput - => Schemas.IncidentOutput; + => Schemas.Find("IncidentOutput") ?? string.Empty; public static string SchemaDarkMemoryOutput - => Schemas.DarkMemoryOutput; + => Schemas.Find("DarkMemoryOutput") ?? string.Empty; public static void RegisterSchema(string key, string schema) => Schemas.Register(key, schema); diff --git a/Source/Presentation/Api/RimMindAPI.Diagnostics.cs b/Source/Presentation/Api/RimMindAPI.Diagnostics.cs index c8137bd2..903cc1f7 100644 --- a/Source/Presentation/Api/RimMindAPI.Diagnostics.cs +++ b/Source/Presentation/Api/RimMindAPI.Diagnostics.cs @@ -1,3 +1,5 @@ +using System.Collections.Generic; +using RimMind.Application.Common.Interfaces.Diagnostics; using RimMind.Application.Features.Llm; namespace RimMind.Presentation.Api @@ -5,8 +7,7 @@ namespace RimMind.Presentation.Api public static partial class RimMindAPI { /// - /// Public diagnostic hygiene helpers for redacting credentials and truncating payloads - /// before writing to logs, UI status messages, or error surfaces. + /// Public diagnostic hygiene helpers and trace-summarization extension registration. /// public static class Diagnostics { @@ -15,6 +16,18 @@ public static string SanitizeForLog(string? text, int maxLength = LogSecretRedac public static string SanitizeMessage(string? text, string? literalSecret = null, int maxLength = 320) => LogSecretRedactor.ForMessageWithSecret(text, literalSecret, maxLength); + + public static void RegisterTraceSummarizer(IRequestTraceSummarizer summarizer) + => RequestTraceSummarizerRegistry.Register(summarizer); + + public static bool UnregisterTraceSummarizer(string id) + => RequestTraceSummarizerRegistry.Unregister(id); + + public static int UnregisterTraceSummarizersByOwner(string ownerModId) + => RequestTraceSummarizerRegistry.UnregisterByOwner(ownerModId); + + public static IReadOnlyList RegisteredTraceSummarizers + => RequestTraceSummarizerRegistry.All; } } } diff --git a/Source/Presentation/Common/RimMindPawnLookup.cs b/Source/Presentation/Common/RimMindPawnLookup.cs index fa5bbd7d..dc2b3179 100644 --- a/Source/Presentation/Common/RimMindPawnLookup.cs +++ b/Source/Presentation/Common/RimMindPawnLookup.cs @@ -99,7 +99,8 @@ public static void UncachePawn(int thingIDNumber) public static void UncachePawn(string? thingId) { if (string.IsNullOrEmpty(thingId)) return; - if (PawnByIdCache.TryRemove(thingId, out var pawn)) + string key = thingId!; + if (PawnByIdCache.TryRemove(key, out var pawn)) { if (pawn != null && pawn.thingIDNumber > 0) { @@ -110,7 +111,7 @@ public static void UncachePawn(string? thingId) { foreach (var kvp in PawnByNumberCache) { - if (kvp.Value?.ThingID == thingId) + if (kvp.Value?.ThingID == key) { PawnByNumberCache.TryRemove(kvp.Key, out _); } @@ -154,15 +155,16 @@ public static void ClearCache() public static Pawn? FindPawnById(string? pawnId) { if (string.IsNullOrEmpty(pawnId)) return null; + string id = pawnId!; - if (PawnByIdCache.TryGetValue(pawnId, out var cached)) + if (PawnByIdCache.TryGetValue(id, out var cached)) { if (cached != null && !cached.Dead && !cached.DestroyedOrNull()) { return cached; } UncachePawn(cached?.thingIDNumber ?? 0); - PawnByIdCache.TryRemove(pawnId, out _); + PawnByIdCache.TryRemove(id, out _); } // In RimWorld 1.6, accessing Find.Maps or mapPawns off the main thread triggers @@ -172,20 +174,20 @@ public static void ClearCache() return null; } - if (MissById.IsRecentMiss(pawnId)) return null; + if (MissById.IsRecentMiss(id)) return null; // ThingID is ""; compare the cheap number first so the scan // does not allocate a ThingID string for every pawn. - int numberHint = TryParseTrailingNumber(pawnId); + int numberHint = TryParseTrailingNumber(id); var pawn = ScanLoadedPawns(p => - (numberHint <= 0 || p.thingIDNumber == numberHint) && p.ThingID == pawnId); + (numberHint <= 0 || p.thingIDNumber == numberHint) && p.ThingID == id); if (pawn != null) { CachePawn(pawn); return pawn; } - MissById.RecordMiss(pawnId); + MissById.RecordMiss(id); return null; } @@ -406,8 +408,11 @@ public static List GetSpawnedColonistsSafe(Map? map) for (int i = 0; i < colonists.Count; i++) { var p = colonists[i]; - CachePawn(p); - snapshot.Add(p); + if (IsActiveSpawnedColonist(p)) + { + CachePawn(p); + snapshot.Add(p); + } } return snapshot; } @@ -491,53 +496,10 @@ public static bool IsNpcActiveColonist(string? npcId) /// /// 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. + /// for UI overlays, motes, and approval cards. Delegates to . /// public static string FormatHumanReadableActionName(string? rawName) - { - if (string.IsNullOrWhiteSpace(rawName)) - return "Action"; - - var trimmed = rawName!.Trim(); - 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) && - trimmed.Length > prefix.Length) - { - trimmed = trimmed.Substring(prefix.Length); - break; - } - } - - var tokens = trimmed.Split(new[] { '_', '.', '-', ' ' }, StringSplitOptions.RemoveEmptyEntries); - if (tokens.Length == 0) - return trimmed; - - var formatted = new string[tokens.Length]; - for (int i = 0; i < tokens.Length; i++) - { - var token = tokens[i]; - formatted[i] = token.Length == 1 - ? token.ToUpperInvariant() - : char.ToUpperInvariant(token[0]) + token.Substring(1); - } - - return string.Join(" ", formatted); - } + => ToolActionDisplayFormatter.FormatHumanReadableActionName(rawName); /// /// Checks if a pawn is an active spawned player colony domestic animal or pet (not dead, not destroyed, spawned on a map, player faction, animal). diff --git a/Source/Presentation/Common/RimMindText.cs b/Source/Presentation/Common/RimMindText.cs index 89470a49..6a985913 100644 --- a/Source/Presentation/Common/RimMindText.cs +++ b/Source/Presentation/Common/RimMindText.cs @@ -21,9 +21,16 @@ public static string TrOr(string key, string fallback, params object[] args) ? key.TranslateSimple() : effectiveFallback; - return args == null || args.Length == 0 - ? template - : string.Format(template, args); + if (args == null || args.Length == 0) + return template; + + if (template.IndexOf("{0}", StringComparison.Ordinal) < 0 + && effectiveFallback.IndexOf("{0}", StringComparison.Ordinal) >= 0) + { + template = effectiveFallback; + } + + return string.Format(template, args); } catch { diff --git a/Source/Presentation/Common/ToolActionDisplayFormatter.cs b/Source/Presentation/Common/ToolActionDisplayFormatter.cs new file mode 100644 index 00000000..cd74b7f2 --- /dev/null +++ b/Source/Presentation/Common/ToolActionDisplayFormatter.cs @@ -0,0 +1,67 @@ +using System; +using RimMind.Application.Common.Interfaces.Tools; +using RimMind.Presentation.Runtime.Services; + +namespace RimMind.Presentation.Api +{ + /// + /// Formats raw tool/action identifiers into human-readable titles for UI overlays, motes, + /// and approval cards, preferring registered . + /// + public static class ToolActionDisplayFormatter + { + private static readonly string[] StripPrefixes = + { + "pawn.job.", + "pawn.", + "map.", + "world.", + "pawn_", + "rimmind_" + }; + + public static string FormatHumanReadableActionName(string? rawName) + { + if (string.IsNullOrWhiteSpace(rawName)) + return "Action"; + + var trimmed = rawName!.Trim(); + 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). + } + + foreach (var prefix in StripPrefixes) + { + if (trimmed.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && + trimmed.Length > prefix.Length) + { + trimmed = trimmed.Substring(prefix.Length); + break; + } + } + + var tokens = trimmed.Split(new[] { '_', '.', '-', ' ' }, StringSplitOptions.RemoveEmptyEntries); + if (tokens.Length == 0) + return trimmed; + + var formatted = new string[tokens.Length]; + for (int i = 0; i < tokens.Length; i++) + { + var token = tokens[i]; + formatted[i] = token.Length == 1 + ? token.ToUpperInvariant() + : char.ToUpperInvariant(token[0]) + token.Substring(1); + } + + return string.Join(" ", formatted); + } + } +} diff --git a/Source/Presentation/Runtime/ClientManager.cs b/Source/Presentation/Runtime/ClientManager.cs index 15a480ee..ac2b55d0 100644 --- a/Source/Presentation/Runtime/ClientManager.cs +++ b/Source/Presentation/Runtime/ClientManager.cs @@ -3,14 +3,13 @@ using RimMind.Application.Common.Interfaces.Client; using RimMind.Application.Common.Interfaces.Extension; using RimMind.Application.Common.Interfaces.Internal; -using RimMind.Application.Common.Helpers; namespace RimMind.Presentation.Runtime { public class ClientManager : IClientManager, IDisposable { + private readonly object _sync = new object(); private IAIClient? _client; - private IAIClient? _player2Client; private string _lastProvider = ""; private string _lastApiKey = ""; private string _lastEndpoint = ""; @@ -37,37 +36,50 @@ public ClientManager(ISettingsProvider? settingsProvider = null, var s = GetSettings(); if (s == null) return null; - if (_client != null && - _lastProvider == s.Provider && - _lastApiKey == s.ApiKey && - _lastEndpoint == s.ApiEndpoint && - _lastModel == s.ModelName) - return _client; - - DisposeClient(ref _client); - _client = CreateClient(s); - _lastProvider = s.Provider; - _lastApiKey = s.ApiKey; - _lastEndpoint = s.ApiEndpoint; - _lastModel = s.ModelName; - return _client; - } + string provider = s.Provider; + string apiKey = s.ApiKey; + string endpoint = s.ApiEndpoint; + string model = s.ModelName; - public IAIClient? GetPlayer2Client() - { - var s = GetSettings(); - if (s == null) return null; - if (AIProviderRegistry.RequiresApiKey(s.Provider)) return null; + IAIClient? staleClient = null; + IAIClient? currentClient; - if (_player2Client != null) return _player2Client; - _player2Client = CreateClient(s); - return _player2Client; + lock (_sync) + { + if (_disposed) return null; + + if (_client != null && + _lastProvider == provider && + _lastApiKey == apiKey && + _lastEndpoint == endpoint && + _lastModel == model) + { + return _client; + } + + staleClient = _client; + _client = CreateClient(s); + _lastProvider = provider; + _lastApiKey = apiKey; + _lastEndpoint = endpoint; + _lastModel = model; + currentClient = _client; + } + + DisposeClient(staleClient); + return currentClient; } public void InvalidateCache() { - DisposeClient(ref _client); - DisposeClient(ref _player2Client); + IAIClient? staleClient; + lock (_sync) + { + staleClient = _client; + _client = null; + } + + DisposeClient(staleClient); } private IAIClient? CreateClient(ISettingsProvider s) @@ -77,22 +89,27 @@ public void InvalidateCache() return factory?.Create(s); } - private static void DisposeClient(ref IAIClient? client) + private static void DisposeClient(IAIClient? client) { if (client is IDisposable disposable) { try { disposable.Dispose(); } catch { /* swallow dispose errors */ } } - client = null; } public void Dispose() { - if (_disposed) return; - _disposed = true; - DisposeClient(ref _client); - DisposeClient(ref _player2Client); + IAIClient? staleClient; + lock (_sync) + { + if (_disposed) return; + _disposed = true; + staleClient = _client; + _client = null; + } + + DisposeClient(staleClient); } } } diff --git a/Source/Presentation/Runtime/Composition/AgentComposition.cs b/Source/Presentation/Runtime/Composition/AgentComposition.cs index a25e0dc7..2e263724 100644 --- a/Source/Presentation/Runtime/Composition/AgentComposition.cs +++ b/Source/Presentation/Runtime/Composition/AgentComposition.cs @@ -14,7 +14,6 @@ using RimMind.Application.Features.Agent; using RimMind.Application.Features.Agent.InnerVoice; using RimMind.Application.Features.Agent.Modes; -using RimMind.Application.Features.Agent.Psychology; using RimMind.Application.Features.Agent.Social; using RimMind.Application.Common.Interfaces.Extension; using RimMind.Domain.Events; @@ -60,11 +59,6 @@ public static AgentCompositionServices ComposeAgents( services.Bind(traitEvolver); IDreamThoughtInjector? dreamThoughtInjector = null; - if (thoughtInjector != null) - { - dreamThoughtInjector = new RimMind.Infrastructure.Social.VerseDreamThoughtInjector(thoughtInjector); - services.Bind(dreamThoughtInjector); - } var agentLoopScheduler = new AgentLoopScheduler(logSink); services.Bind(agentLoopScheduler); diff --git a/Source/Presentation/Runtime/Composition/ClientComposition.cs b/Source/Presentation/Runtime/Composition/ClientComposition.cs index 7f6fafdb..24801e51 100644 --- a/Source/Presentation/Runtime/Composition/ClientComposition.cs +++ b/Source/Presentation/Runtime/Composition/ClientComposition.cs @@ -37,6 +37,8 @@ public static ClientCompositionServices ComposeClientManager( services.Bind(clientFactoryRegistry); var gameScopedServices = extensions.GetExtensionRegistry(); + gameScopedServices.Register(CoreGameLifecycleCleanupService.Instance); + gameScopedServices.Register(RimMind.Infrastructure.Verse.AgentBusGameLifecycleService.Instance); gameScopedServices.Register(Player2GameLifecycleService.Instance); gameScopedServices.Register(RimMind.Presentation.Agent.MapContextBuilderCacheLifecycleService.Instance); services.Bind(gameScopedServices); diff --git a/Source/Presentation/Runtime/Composition/SettingsComposition.cs b/Source/Presentation/Runtime/Composition/SettingsComposition.cs index b51c44fd..b98d2616 100644 --- a/Source/Presentation/Runtime/Composition/SettingsComposition.cs +++ b/Source/Presentation/Runtime/Composition/SettingsComposition.cs @@ -74,7 +74,6 @@ public static void ComposeInfrastructureServices( services.Bind(infraBag.AudioPlayer); services.Bind(infraBag.TickProvider); services.Bind(infraBag.ThreadChecker); - services.Bind(infraBag.PathProvider); services.Bind(infraBag.LogSink); services.Bind(infraBag.TranslationService); services.Bind(infraBag.MechanismRegistry); diff --git a/Source/Presentation/Runtime/Composition/ToolMechanismComposition.cs b/Source/Presentation/Runtime/Composition/ToolMechanismComposition.cs index 5873a848..0efc8adf 100644 --- a/Source/Presentation/Runtime/Composition/ToolMechanismComposition.cs +++ b/Source/Presentation/Runtime/Composition/ToolMechanismComposition.cs @@ -1,12 +1,20 @@ using RimMind.Application.Common.Interfaces.Agent; +using RimMind.Application.Common.Interfaces.Extension; using RimMind.Application.Common.Interfaces.Internal; using RimMind.Application.Common.Interfaces.Mechanisms; +using RimMind.Application.Common.Interfaces.Tools; using RimMind.Presentation.Runtime.Services; namespace RimMind.Presentation.Runtime.Composition { internal static class ToolMechanismComposition { + public static void RegisterBuiltinArgumentAdapters(IExtensionRegistry registry) + { + registry.Register(new RimMind.Infrastructure.Mechanisms.Pawn.Job.JobMechanismArgumentAdapter()); + registry.Register(new RimMind.Infrastructure.Mechanisms.Pawn.Work.WorkMechanismArgumentAdapter()); + } + public static void RegisterAllMechanisms(IGameMechanismRegistry registry) { registry.Register(new RimMind.Infrastructure.Mechanisms.Pawn.Job.JobMechanism()); diff --git a/Source/Presentation/Runtime/RimMindCompositionRoot.cs b/Source/Presentation/Runtime/RimMindCompositionRoot.cs index 983a8b47..4f1f91f3 100644 --- a/Source/Presentation/Runtime/RimMindCompositionRoot.cs +++ b/Source/Presentation/Runtime/RimMindCompositionRoot.cs @@ -165,6 +165,7 @@ public RuntimeComposition Compose( services.Bind(actionBridge); ToolMechanismComposition.RegisterAllMechanisms(infraBag.MechanismRegistry); + ToolMechanismComposition.RegisterBuiltinArgumentAdapters(extensions.GetExtensionRegistry()); var clientServices = ClientComposition.ComposeClientManager( services, extensions, resolvedSettings); @@ -211,6 +212,7 @@ public RuntimeComposition Compose( var llmMiddleware = extensions.GetExtensionRegistry>(); services.Bind(llmMiddleware); + var deferredRuntime = new DeferredRuntimeProxy(); var unifiedPipeline = UnifiedRequestPipelineFactory.Build( appBag.ToolRegistry, logSink, @@ -221,7 +223,9 @@ public RuntimeComposition Compose( llmMiddleware, contextServices.RelevanceLearner, new AIResponseAnalyzer(), - infraBag.RequestTraceLog); + infraBag.RequestTraceLog, + runtime: deferredRuntime, + queueSettings: resolvedSettings); services.Bind>(unifiedPipeline); var requestSubmission = new RequestSubmissionService( appBag.Queue, @@ -275,6 +279,7 @@ public RuntimeComposition Compose( result.AgentBus, actionBridge); runtime = new RimMindRuntime(result, lifecycle, extensionManager, extensions); + deferredRuntime.Attach(runtime); var modeRegistry = extensions.GetExtensionRegistry(); extensionManager.RegisterBuiltinModes(modeRegistry); services.Bind(modeRegistry); @@ -303,5 +308,21 @@ public RuntimeComposition Compose( } } + private sealed class DeferredRuntimeProxy : IRimMindRuntime + { + private volatile RimMindRuntime? _target; + + public void Attach(RimMindRuntime runtime) => _target = runtime; + + public bool IsShutdown => _target?.IsShutdown == true; + + public IExtensionRegistry GetExtensionRegistry() where T : class, IExtension + => (_target ?? throw new InvalidOperationException("Runtime is not yet attached.")).GetExtensionRegistry(); + + public void AddMiddleware(IMiddleware middleware) where TContext : IPipelineContext + => (_target ?? throw new InvalidOperationException("Runtime is not yet attached.")).AddMiddleware(middleware); + + public void Dispose() => _target?.Dispose(); + } } } diff --git a/Source/Presentation/Runtime/RimMindRuntime.cs b/Source/Presentation/Runtime/RimMindRuntime.cs index 13b7c04a..73a72517 100644 --- a/Source/Presentation/Runtime/RimMindRuntime.cs +++ b/Source/Presentation/Runtime/RimMindRuntime.cs @@ -152,7 +152,6 @@ public void RegisterParameterTuner(IParameterTuner tuner) public IAIClient? GetClient() => ClientManager.GetClient(); public void InvalidateClientCache() => ClientManager.InvalidateCache(); - public IAIClient? GetPlayer2Client() => ClientManager.GetPlayer2Client(); public ISettingsProvider? GetSettingsProvider() => ResolveOptional(c => c.SettingsProvider); } } diff --git a/Source/Presentation/Runtime/RimMindRuntimeGameComponent.cs b/Source/Presentation/Runtime/RimMindRuntimeGameComponent.cs index befe87fe..aa047c2d 100644 --- a/Source/Presentation/Runtime/RimMindRuntimeGameComponent.cs +++ b/Source/Presentation/Runtime/RimMindRuntimeGameComponent.cs @@ -1,12 +1,16 @@ using System; using System.Collections; +using System.Collections.Generic; using System.Reflection; using RimMind.Application.Common.Constants; using RimMind.Application.Common.Helpers; using RimMind.Application.Common.Interfaces.Agent; +using RimMind.Application.Common.Interfaces.Context; using RimMind.Application.Common.Interfaces.Extension; using RimMind.Application.Common.Interfaces.Internal; using RimMind.Application.Common.Interfaces.Npc; +using RimMind.Application.Features.Requests.Queue; +using RimMind.Domain.ValueObjects; using RimMind.Presentation.Api; using RimMind.Presentation.Runtime.Services; using RimMind.Presentation.UI; @@ -23,6 +27,7 @@ public class RimMindRuntimeGameComponent : GameComponent private readonly Game _game; private int _lastTick = -1; private bool _initialized; + private bool _gameStartedNotified; private long _cachedHubGeneration = -1; public RimMindRuntimeGameComponent(Game game) : base() @@ -66,7 +71,7 @@ public override void StartedNewGame() EnsureInitialized(); PublishGameServices(); ResetRuntimeAgents(); - NotifyGameStarted(); + NotifyGameStartedOnce(); CheckMissingApiKeyNotification(); } @@ -77,7 +82,7 @@ public override void LoadedGame() EnsureInitialized(); PublishGameServices(); ResetRuntimeAgents(); - NotifyGameStarted(); + NotifyGameStartedOnce(); CheckMissingApiKeyNotification(); } @@ -85,6 +90,14 @@ public override void FinalizeInit() { base.FinalizeInit(); RimMindPawnLookup.ClearCache(); + NotifyGameStartedOnce(); + } + + private void NotifyGameStartedOnce() + { + if (_gameStartedNotified) + return; + _gameStartedNotified = true; NotifyGameStarted(); } @@ -245,6 +258,33 @@ private void ResetRuntimeAgents() } } + internal sealed class CoreGameLifecycleCleanupService : IGameScopedService + { + public static readonly CoreGameLifecycleCleanupService Instance = new CoreGameLifecycleCleanupService(); + + public string Id => "core.game_lifecycle_cleanup"; + + public string OwnerModId => RimMindOwnerConsts.CoreModId; + + public void OnGameStarted() + { + } + + public void OnGameStopped() + { + var scope = RuntimeServiceHub.Shared.Capture(); + scope.GetOptional()?.LoadFromSave(new Dictionary>()); + + var queue = scope.GetOptional(); + if (queue != null) + { + queue.CancelAllRequests(); + if (queue is ITickableRequestQueue tickable) + tickable.Reset(); + } + } + } + internal sealed class Player2GameLifecycleService : IGameScopedService { public static readonly Player2GameLifecycleService Instance = new Player2GameLifecycleService(); diff --git a/Source/Presentation/Runtime/Services/LifecycleEvents.cs b/Source/Presentation/Runtime/Services/LifecycleEvents.cs index 2bd947b6..e385110d 100644 --- a/Source/Presentation/Runtime/Services/LifecycleEvents.cs +++ b/Source/Presentation/Runtime/Services/LifecycleEvents.cs @@ -34,6 +34,7 @@ public static class LifecycleEventSources public const string RuntimeLifetime = "runtime_lifetime"; public const string SettingsUi = "settings_ui"; public const string RequestOverlay = "RequestOverlay"; + public const string LiveAiProbe = "live_ai_probe"; private static readonly HashSet Approved = new HashSet(StringComparer.Ordinal) { @@ -51,7 +52,8 @@ public static class LifecycleEventSources AgentContextPreview, RuntimeLifetime, SettingsUi, - RequestOverlay + RequestOverlay, + LiveAiProbe }; public static string Normalize(string? source) diff --git a/Source/Presentation/Settings/RimMindCoreSettings.cs b/Source/Presentation/Settings/RimMindCoreSettings.cs index fdf2b3af..93428fc2 100644 --- a/Source/Presentation/Settings/RimMindCoreSettings.cs +++ b/Source/Presentation/Settings/RimMindCoreSettings.cs @@ -104,14 +104,24 @@ public bool IsConfigured() { if (!AIProviderRegistry.RequiresApiKey(provider)) return true; - return IsOpenAIConfigured(); + return HasConfiguredEndpointAndCredentials(); } - public bool IsOpenAIConfigured() + private bool HasConfiguredEndpointAndCredentials() { - if (!string.IsNullOrWhiteSpace(apiKey) && !string.IsNullOrWhiteSpace(apiEndpoint)) - return true; - return backupEndpoints != null && backupEndpoints.Any(b => b != null && b.enabled && !string.IsNullOrWhiteSpace(b.apiKey) && !string.IsNullOrWhiteSpace(b.apiEndpoint)); + if (!string.IsNullOrWhiteSpace(apiEndpoint)) + { + if (!string.IsNullOrWhiteSpace(apiKey) || IsLoopbackEndpoint(apiEndpoint)) + return true; + } + return backupEndpoints != null && backupEndpoints.Any(b => + b != null && b.enabled && !string.IsNullOrWhiteSpace(b.apiEndpoint) + && (!string.IsNullOrWhiteSpace(b.apiKey) || IsLoopbackEndpoint(b.apiEndpoint))); + } + + private static bool IsLoopbackEndpoint(string? endpoint) + { + return Uri.TryCreate(endpoint?.Trim(), UriKind.Absolute, out var uri) && uri.IsLoopback; } public override void ExposeData() diff --git a/Source/Presentation/Settings/SettingsProvider.Core.cs b/Source/Presentation/Settings/SettingsProvider.Core.cs index 383c8214..710bf8eb 100644 --- a/Source/Presentation/Settings/SettingsProvider.Core.cs +++ b/Source/Presentation/Settings/SettingsProvider.Core.cs @@ -114,10 +114,29 @@ public string ApiEndpoint get => _settings.apiEndpoint ?? string.Empty; set => _settings.apiEndpoint = value; } - public string Player2RemoteUrl + private readonly System.Collections.Concurrent.ConcurrentDictionary _providerOptions = + new System.Collections.Concurrent.ConcurrentDictionary(System.StringComparer.OrdinalIgnoreCase); + + public string GetProviderOption(string key) { - get => _settings.player2RemoteUrl ?? string.Empty; - set => _settings.player2RemoteUrl = value; + if (string.IsNullOrWhiteSpace(key)) + return string.Empty; + if (string.Equals(key, "player2.remote_url", System.StringComparison.OrdinalIgnoreCase)) + return _settings.player2RemoteUrl ?? string.Empty; + return _providerOptions.TryGetValue(key, out var value) ? value : string.Empty; + } + + public void SetProviderOption(string key, string value) + { + if (string.IsNullOrWhiteSpace(key)) + return; + string normalized = value ?? string.Empty; + if (string.Equals(key, "player2.remote_url", System.StringComparison.OrdinalIgnoreCase)) + { + _settings.player2RemoteUrl = normalized; + return; + } + _providerOptions[key] = normalized; } // IDebugSettings @@ -202,6 +221,5 @@ public float AutoApplyConfidenceThreshold // IApiCredentialSettings public System.Collections.Generic.IReadOnlyList? BackupEndpoints => _settings.GetBackupEndpointNodes(); public bool IsConfigured => _settings.IsConfigured(); - public bool IsOpenAIConfigured() => _settings.IsOpenAIConfigured(); } } diff --git a/Source/Presentation/UI/AICoreSettingsUI.cs b/Source/Presentation/UI/AICoreSettingsUI.cs index 1795102b..ca07892b 100644 --- a/Source/Presentation/UI/AICoreSettingsUI.cs +++ b/Source/Presentation/UI/AICoreSettingsUI.cs @@ -58,6 +58,38 @@ public static void Draw(Rect inRect, RimMindLayoutScope? scope = null) DrawCurrentSettingsPage(layout.Content, settings, settingsTabRegistry, runtimeScope, scope); } + private sealed class BuiltinSettingsTab + { + public BuiltinSettingsTab( + string id, + string labelKey, + string fallbackLabel, + System.Action draw) + { + Id = id; + LabelKey = labelKey; + FallbackLabel = fallbackLabel; + Draw = draw; + } + + public string Id { get; } + public string LabelKey { get; } + public string FallbackLabel { get; } + public System.Action Draw { get; } + } + + private static readonly BuiltinSettingsTab[] BuiltinTabs = + { + new("api", "RimMind.Settings.Tab.Api", "API", + (content, settings, runtimeScope, scope) => ApiTabDrawer.Draw(content, settings, runtimeScope, scope)), + new("queue", "RimMind.Settings.Tab.Queue", "Queue", + (content, settings, runtimeScope, scope) => QueueTabDrawer.Draw(content, settings, runtimeScope, scope)), + new("prompts", "RimMind.Settings.Tab.Prompts", "Prompts", + (content, settings, _, scope) => PromptsTabDrawer.Draw(content, settings, scope)), + new("context", "RimMind.Settings.Tab.Context", "Context", + (content, settings, _, scope) => ContextTabDrawer.Draw(content, settings, scope)), + }; + private static void DrawCurrentSettingsPage( Rect content, ISettingsProvider settings, @@ -65,37 +97,41 @@ private static void DrawCurrentSettingsPage( RuntimeServiceScope runtimeScope, RimMindLayoutScope? scope) { - switch (_curTab) + for (int i = 0; i < BuiltinTabs.Length; i++) + { + if (BuiltinTabs[i].Id == _curTab) + { + BuiltinTabs[i].Draw(content, settings, runtimeScope, scope); + return; + } + } + + if (settingsTabRegistry != null) { - case "api": ApiTabDrawer.Draw(content, settings, runtimeScope, scope); break; - case "queue": QueueTabDrawer.Draw(content, settings, runtimeScope, scope); break; - case "context": ContextTabDrawer.Draw(content, settings, scope); break; - case "prompts": PromptsTabDrawer.Draw(content, settings, scope); break; - default: - if (settingsTabRegistry != null) - foreach (var tab in settingsTabRegistry.All) - if (tab.Id == _curTab) - { - if (tab is IRuntimeScopedSettingsTab runtimeScopedTab) - runtimeScopedTab.Draw(content, runtimeScope); - else - tab.Draw(content); - break; - } - break; + foreach (var tab in settingsTabRegistry.All) + { + if (tab.Id == _curTab) + { + if (tab is IRuntimeScopedSettingsTab runtimeScopedTab) + runtimeScopedTab.Draw(content, runtimeScope); + else + tab.Draw(content); + break; + } + } } } private static List CollectTabs( IExtensionRegistry? settingsTabRegistry) { - var tabs = new List + var tabs = new List(BuiltinTabs.Length + (settingsTabRegistry?.All.Count ?? 0)); + for (int i = 0; i < BuiltinTabs.Length; i++) { - CreateTab("api", "RimMind.Settings.Tab.Api"), - CreateTab("queue", "RimMind.Settings.Tab.Queue"), - CreateTab("prompts", "RimMind.Settings.Tab.Prompts"), - CreateTab("context", "RimMind.Settings.Tab.Context"), - }; + var builtin = BuiltinTabs[i]; + tabs.Add(CreateTab(builtin.Id, builtin.LabelKey, builtin.FallbackLabel)); + } + if (settingsTabRegistry != null) foreach (var tab in settingsTabRegistry.All) tabs.Add(new TabbedPageTabModel(tab.Id, tab.Label, tab.Id, _curTab == tab.Id, true, null)); @@ -104,8 +140,11 @@ private static List CollectTabs( private static void EnsureCurrentTab(IExtensionRegistry? settingsTabRegistry) { - if (_curTab == "api" || _curTab == "queue" || _curTab == "prompts" || _curTab == "context") - return; + for (int i = 0; i < BuiltinTabs.Length; i++) + { + if (BuiltinTabs[i].Id == _curTab) + return; + } if (settingsTabRegistry != null) { @@ -119,8 +158,8 @@ private static void EnsureCurrentTab(IExtensionRegistry? settingsT _curTab = "api"; } - private static TabbedPageTabModel CreateTab(string id, string labelKey) - => new(id, labelKey.Translate(), labelKey, _curTab == id, true, null); + private static TabbedPageTabModel CreateTab(string id, string labelKey, string fallbackLabel) + => new(id, UiText.Get(labelKey, fallbackLabel), labelKey, _curTab == id, true, null); } diff --git a/Source/Presentation/UI/ApiTabDrawer.TestConnection.cs b/Source/Presentation/UI/ApiTabDrawer.TestConnection.cs index 6897823e..5d9972c7 100644 --- a/Source/Presentation/UI/ApiTabDrawer.TestConnection.cs +++ b/Source/Presentation/UI/ApiTabDrawer.TestConnection.cs @@ -38,39 +38,33 @@ private static void RunConnectionTest( clientManager?.InvalidateCache(); Log.Message(BuildConnectionDebugLine("start", s, providerRegistry, null, null)); - // Each provider selects its client independently of RequiresApiKey. (Previously a brace-less - // `if (!RequiresApiKey) if (player2) {...} else if (extended_service) {...}` bound the else-if to the - // inner if, so extended_service silently fell through to the OpenAI path whenever it required a key.) - Func getClient; + Func getClient = () => clientManager?.GetClient(); string stage; string notConfiguredKey; bool requireConfiguredClient; - if (s.Provider == "player2") + if (!string.IsNullOrEmpty(AIProviderRegistry.GetSettingsTabId(s.Provider))) { - getClient = () => clientManager?.GetPlayer2Client(); - stage = "player2-client"; - notConfiguredKey = "RimMind.Settings.Player2.NotAvailable"; - requireConfiguredClient = false; - } - else if (!string.IsNullOrEmpty(AIProviderRegistry.GetSettingsTabId(s.Provider, providerRegistry))) - { - getClient = () => clientManager?.GetClient(); - stage = "modelservice-client"; + stage = "extended-provider-client"; notConfiguredKey = "RimMind.Settings.ModelService.NoActiveNodes"; requireConfiguredClient = true; } + else if (!AIProviderRegistry.RequiresApiKey(s.Provider, providerRegistry)) + { + stage = "keyless-provider-client"; + notConfiguredKey = "RimMind.Settings.Player2.NotAvailable"; + requireConfiguredClient = false; + } else { - if (!s.IsOpenAIConfigured()) + if (!s.IsConfigured) { - Log.Message(BuildConnectionDebugLine("openai-settings-not-configured", s, providerRegistry, null, null)); + Log.Message(BuildConnectionDebugLine("provider-settings-not-configured", s, providerRegistry, null, null)); _testStatus = UiText.Get("RimMind.Settings.Status.NotConfigured", "Not configured"); _testStatusColor = Color.yellow; return; } - getClient = () => clientManager?.GetClient(); - stage = "openai-client"; + stage = "api-key-provider-client"; notConfiguredKey = "RimMind.Settings.Status.NotConfigured"; requireConfiguredClient = false; } @@ -128,7 +122,7 @@ private static void RunConnectionProbe( long rttMs = stopwatch.ElapsedMilliseconds; if (result.TryGetValue(out var response)) { - string status = SafeFormat(okFormat, rttMs, (response.Content ?? string.Empty).Trim(), response.TokensUsed); + string status = SafeFormat(okFormat, rttMs, (response?.Content ?? string.Empty).Trim(), response?.TokensUsed ?? 0); PostToMainThread(() => TryPublishConnectionTest(operation, status, okColor)); } else @@ -139,7 +133,8 @@ private static void RunConnectionProbe( } catch (Exception ex) { - string status = SafeFormat(exceptionFormat, ex.Message); + string safeMessage = RimMind.Infrastructure.Services.Clients.Shared.LogSanitizer.ForLog(ex.Message); + string status = SafeFormat(exceptionFormat, safeMessage); PostToMainThread(() => TryPublishConnectionTest(operation, status, failColor)); } }); @@ -212,7 +207,10 @@ private static void NormalizeConnectionSettings(ISettingsProvider s) s.ApiKey = (s.ApiKey ?? string.Empty).Trim(); s.ApiEndpoint = (s.ApiEndpoint ?? string.Empty).Trim(); s.ModelName = (s.ModelName ?? string.Empty).Trim(); - s.Player2RemoteUrl = (s.Player2RemoteUrl ?? string.Empty).Trim(); + string rawRemoteUrl = s.GetProviderOption("player2.remote_url") ?? string.Empty; + string trimmedRemoteUrl = rawRemoteUrl.Trim(); + if (!string.Equals(rawRemoteUrl, trimmedRemoteUrl, StringComparison.Ordinal)) + s.SetProviderOption("player2.remote_url", trimmedRemoteUrl); } private static string BuildConnectionDebugLine( diff --git a/Source/Presentation/UI/ApiTabDrawer.cs b/Source/Presentation/UI/ApiTabDrawer.cs index 4cb4528e..9eebed3e 100644 --- a/Source/Presentation/UI/ApiTabDrawer.cs +++ b/Source/Presentation/UI/ApiTabDrawer.cs @@ -185,7 +185,6 @@ internal static void ApplyPresetEco(ISettingsProvider s) s.Persist(); } - internal static string? CurrentPresetFeedback => null; private static void DrawConnectionSection( Listing_Standard listing, ISettingsProvider s, @@ -208,7 +207,7 @@ private static void DrawConnectionSection( listing.Gap(6f); - if (!string.IsNullOrEmpty(AIProviderRegistry.GetSettingsTabId(s.Provider, providerRegistry))) + if (!string.IsNullOrEmpty(AIProviderRegistry.GetSettingsTabId(s.Provider))) { DrawExtendedServiceSection(listing, s, providerRegistry, scope); } @@ -230,32 +229,38 @@ internal static string GetActiveProviderDisplayLabel( ISettingsProvider s, IExtensionRegistry? providerRegistry = null) { - 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 => - string.Equals(f.ProviderId, s.Provider, StringComparison.OrdinalIgnoreCase)); - if (factory != null && !string.IsNullOrEmpty(factory.DisplayLabel)) - return factory.DisplayLabel; - } - - if (string.Equals(s.Provider, Domain.Common.AIProviders.OpenAI, StringComparison.OrdinalIgnoreCase)) + var providerPresets = AIProviderRegistry.GetPresets(s.Provider); + if (providerPresets.Count > 0) { - string openAiLabel = UiText.Get("RimMind.Settings.Provider.OpenAI"); var matchedPreset = AIProviderRegistry.MatchPresetByEndpoint(s.ApiEndpoint); - if (matchedPreset != null) + if (matchedPreset != null + && string.Equals(matchedPreset.ProviderId, s.Provider, StringComparison.OrdinalIgnoreCase)) { string presetLabel = ResolvePresetLabel(matchedPreset); if (!string.IsNullOrWhiteSpace(presetLabel)) return presetLabel; } - return openAiLabel + " (" + UiText.Get("RimMind.Settings.Provider.Custom") + ")"; + string baseLabel = ResolveFactoryOrDescriptorLabel(s.Provider, providerRegistry); + return baseLabel + " (" + UiText.Get("RimMind.Settings.Provider.Custom", "Custom") + ")"; + } + + return ResolveFactoryOrDescriptorLabel(s.Provider, providerRegistry); + } + + private static string ResolveFactoryOrDescriptorLabel( + string providerId, + IExtensionRegistry? providerRegistry) + { + if (providerRegistry != null) + { + var factory = providerRegistry.All.FirstOrDefault(f => + string.Equals(f.ProviderId, providerId, StringComparison.OrdinalIgnoreCase)); + if (factory != null && !string.IsNullOrEmpty(factory.DisplayLabel)) + return factory.DisplayLabel; } - return GetProviderLabel(s.Provider); + return GetProviderLabel(providerId); } private static string ResolvePresetLabel(AIProviderPreset preset) @@ -271,90 +276,105 @@ private static void OpenProviderSelectionMenu( IPlayer2Lifecycle? player2Lifecycle) { var options = new List(); + var addedProviderIds = new HashSet(StringComparer.OrdinalIgnoreCase); + + var orderedFactories = providerRegistry != null + ? providerRegistry.All.Where(f => f.VisibleInMenu).OrderBy(f => f.OrderWeight).ToList() + : new List(); - // 1. OpenAI-compatible presets registered via AIProviderRegistry - var openAiPresets = AIProviderRegistry.GetPresets(Domain.Common.AIProviders.OpenAI); - if (openAiPresets.Count > 0) + foreach (var factory in orderedFactories) { - foreach (var preset in openAiPresets) + if (!addedProviderIds.Add(factory.ProviderId)) + continue; + + var presets = AIProviderRegistry.GetPresets(factory.ProviderId); + if (presets.Count > 0) { - var capturedPreset = preset; - string label = ResolvePresetLabel(capturedPreset); - options.Add(new FloatMenuOption(label, () => + foreach (var preset in presets) { - ApplyProviderPreset( - s, - capturedPreset.ProviderId, - capturedPreset.Endpoint, - capturedPreset.ModelName, - label); - })); + var capturedPreset = preset; + string label = ResolvePresetLabel(capturedPreset); + options.Add(new FloatMenuOption(label, () => + { + ApplyProviderPreset( + s, + capturedPreset.ProviderId, + capturedPreset.Endpoint, + capturedPreset.ModelName, + label); + })); + } + continue; } - } - else - { - var openAiDescriptor = AIProviderRegistry.GetDescriptor(Domain.Common.AIProviders.OpenAI); - string openAiLabel = UiText.Get("RimMind.Settings.Provider.OpenAI"); - options.Add(new FloatMenuOption(openAiLabel, () => + + string factoryLabel = !string.IsNullOrEmpty(factory.DisplayLabel) + ? factory.DisplayLabel + : GetProviderLabel(factory.ProviderId); + var capturedFactory = factory; + options.Add(new FloatMenuOption(factoryLabel, () => { - ApplyProviderPreset( - s, - Domain.Common.AIProviders.OpenAI, - openAiDescriptor?.DefaultEndpoint ?? RimMindCoreSettings.DefaultApiEndpoint, - openAiDescriptor?.DefaultModelName ?? RimMindCoreSettings.DefaultModelName, - openAiLabel); + if (!string.IsNullOrEmpty(capturedFactory.DefaultEndpoint) + || !string.IsNullOrEmpty(capturedFactory.DefaultModelName)) + { + ApplyProviderPreset( + s, + capturedFactory.ProviderId, + capturedFactory.DefaultEndpoint ?? string.Empty, + capturedFactory.DefaultModelName ?? string.Empty, + factoryLabel); + } + else + { + SwitchToProvider(s, capturedFactory.ProviderId, player2Lifecycle); + } })); } - // 2. Player2 (local/cloud) - options.Add(new FloatMenuOption(UiText.Get("RimMind.Settings.Provider.Player2"), () => - { - s.Provider = Domain.Common.AIProviders.Player2; - s.Persist(); - RuntimeServiceScope operationScope = RuntimeServiceHub.Shared.Capture(); - var currentClientManager = ClientManager.ResolveOptional(operationScope); - currentClientManager?.InvalidateCache(); - })); - - // 3+. Dynamically registered provider factories (extensions such as ModelService) - if (providerRegistry != null) + var allProviders = AIProviderRegistry.GetAllProviderIds(providerRegistry); + foreach (var providerId in allProviders) { - var externalFactories = providerRegistry.All - .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); + if (!addedProviderIds.Add(providerId)) + continue; - foreach (var factory in externalFactories) + var presets = AIProviderRegistry.GetPresets(providerId); + if (presets.Count > 0) { - string label = !string.IsNullOrEmpty(factory.DisplayLabel) ? factory.DisplayLabel : GetProviderLabel(factory.ProviderId); - var capturedFactory = factory; - options.Add(new FloatMenuOption(label, () => + foreach (var preset in presets) { - s.Provider = capturedFactory.ProviderId; - if (!string.IsNullOrEmpty(capturedFactory.DefaultEndpoint)) - s.ApiEndpoint = capturedFactory.DefaultEndpoint!; - if (!string.IsNullOrEmpty(capturedFactory.DefaultModelName)) - s.ModelName = capturedFactory.DefaultModelName!; - s.Persist(); - RuntimeServiceScope operationScope = RuntimeServiceHub.Shared.Capture(); - var currentClientManager = ClientManager.ResolveOptional(operationScope); - currentClientManager?.InvalidateCache(); - })); + var capturedPreset = preset; + string label = ResolvePresetLabel(capturedPreset); + options.Add(new FloatMenuOption(label, () => + { + ApplyProviderPreset( + s, + capturedPreset.ProviderId, + capturedPreset.Endpoint, + capturedPreset.ModelName, + label); + })); + } + continue; } - } - var allProviders = AIProviderRegistry.GetAllProviderIds(providerRegistry); - foreach (var p in allProviders) - { - 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, () => + var descriptor = AIProviderRegistry.GetDescriptor(providerId); + string labelText = GetProviderLabel(providerId); + string capturedId = providerId; + options.Add(new FloatMenuOption(labelText, () => { - SwitchToProvider(s, p, player2Lifecycle); + if (!string.IsNullOrEmpty(descriptor?.DefaultEndpoint) + || !string.IsNullOrEmpty(descriptor?.DefaultModelName)) + { + ApplyProviderPreset( + s, + capturedId, + descriptor?.DefaultEndpoint ?? string.Empty, + descriptor?.DefaultModelName ?? string.Empty, + labelText); + } + else + { + SwitchToProvider(s, capturedId, player2Lifecycle); + } })); } @@ -411,7 +431,7 @@ private static void DrawExtendedServiceSection( new Color(0.5f, 0.9f, 0.6f)); listing.Gap(4f); - string? settingsTabId = AIProviderRegistry.GetSettingsTabId(s.Provider, providerRegistry); + string? settingsTabId = AIProviderRegistry.GetSettingsTabId(s.Provider); bool isRegistered = !string.IsNullOrEmpty(s.Provider) && (providerRegistry?.FindById(s.Provider) != null || !string.IsNullOrEmpty(settingsTabId)); if (isRegistered && !string.IsNullOrEmpty(settingsTabId)) @@ -759,7 +779,8 @@ private static void DrawPlayer2Section( listing.Gap(4f); string remoteUrlDesc = UiText.Get("RimMind.Settings.Player2.RemoteUrl.Desc"); listing.LabelWithTooltip(UiText.Get("RimMind.Settings.Player2.RemoteUrl"), remoteUrlDesc); - s.Player2RemoteUrl = listing.TextEntryWithTooltip(s.Player2RemoteUrl, remoteUrlDesc); + string remoteUrl = listing.TextEntryWithTooltip(s.GetProviderOption("player2.remote_url"), remoteUrlDesc); + s.SetProviderOption("player2.remote_url", remoteUrl); listing.Gap(4f); { diff --git a/Source/Presentation/UI/RimMindChatWindowBase.cs b/Source/Presentation/UI/RimMindChatWindowBase.cs index 725ab8d3..a957e023 100644 --- a/Source/Presentation/UI/RimMindChatWindowBase.cs +++ b/Source/Presentation/UI/RimMindChatWindowBase.cs @@ -48,7 +48,7 @@ public abstract class RimMindChatWindowBase : RimMindWindowBase private string _inputText = string.Empty; private bool _isWaiting; private bool _autoScroll = true; - private bool _closed; + private volatile bool _closed; protected RimMindChatWindowBase() { diff --git a/Source/RimMindAPI.cs b/Source/RimMindAPI.cs index 6f4c74fb..f8f2250c 100644 --- a/Source/RimMindAPI.cs +++ b/Source/RimMindAPI.cs @@ -1,33 +1,23 @@ -using RimMind.Application.Common.Interfaces; using RimMind.Application.Common.Interfaces.Agent; using RimMind.Application.Common.Interfaces.Agent.Modes; using RimMind.Application.Common.Interfaces.Client; using RimMind.Application.Common.Interfaces.Context; using RimMind.Application.Common.Interfaces.Extension; +using RimMind.Application.Common.Interfaces.Flywheel; using RimMind.Application.Common.Interfaces.Internal; using RimMind.Application.Common.Interfaces.Mechanisms; using RimMind.Application.Common.Interfaces.Npc; using RimMind.Application.Common.Interfaces.Pipeline; using RimMind.Application.Common.Interfaces.Tools; -using RimMind.Application.Common.Interfaces.UI; -using RimMind.Application.Common.Models.Client; using RimMind.Application.Common.Models.Context; -using RimMind.Application.Common.Models.Npc; -using RimMind.Application.Common.Models.Pipeline; -using RimMind.Application.Common.Models.Tools; -using RimMind.Application.Common.Models.UI; -using RimMind.Application.Common.Interfaces.Flywheel; using RimMind.Domain.Llm; using RimMind.Domain.ValueObjects; -using RimMind.Application.Common.Models.Agent; using RimMind.Presentation.Runtime; using RimMind.Presentation.Runtime.Services; using Verse; using System; using System.Collections.Generic; -using System.Threading; using System.Threading.Tasks; -using ClientTrackedRequest = RimMind.Application.Common.Models.Client.TrackedRequest; using UIRequestEntry = RimMind.Application.Common.Models.UI.RequestEntry; namespace RimMind.Presentation.Api @@ -43,41 +33,13 @@ public static partial class RimMindAPI RuntimeRef.ValueOrDefault ?? throw new InvalidOperationException("[RimMind-Core] Runtime is not running."); - [Obsolete("No code consumers in Core or any sub-mod. Scheduled for removal in a future version.")] - public static void Shutdown() - { - var runtime = RuntimeRef.ValueOrDefault; - if (runtime == null || runtime.IsShutdown) return; - runtime.Queue.CancelAllRequests(); - RimMindRuntimeHost.Shutdown(); - } - internal static void ResetForNewGame() => RimMindRuntime.ResetInstance(); - // === Unified Request API (K phase) === + // === Unified Request API === public static void Send(LlmRequestEnvelope envelope, Action> onComplete) => Request.Send(envelope, onComplete); public static Task> SendAsync(LlmRequestEnvelope envelope) => Request.SendAsync(envelope); - [Obsolete("Use RimMindAPI.Request.PauseQueue instead.")] - public static void PauseQueue() => Request.PauseQueue(); - [Obsolete("Use RimMindAPI.Request.ResumeQueue instead.")] - public static void ResumeQueue() => Request.ResumeQueue(); - [Obsolete("Use RimMindAPI.Request.ActiveRequestCount instead.")] - public static int ActiveRequestCount => Request.ActiveRequestCount; - [Obsolete("No code consumers in Core or any sub-mod. Scheduled for removal in a future version.")] - public static IReadOnlyList GetActiveRequests() => Request.GetActiveRequests(); - [Obsolete("No code consumers in Core or any sub-mod. Scheduled for removal in a future version.")] - public static IReadOnlyList GetAllQueuedRequests() => Request.GetAllQueuedRequests(); - [Obsolete("Use RimMindAPI.Request.TotalQueuedCount instead.")] - public static int TotalQueuedCount => Request.TotalQueuedCount; - [Obsolete("Use RimMindAPI.Request.ClearModCooldown instead.")] - public static void ClearModCooldown(string modId) => Request.ClearModCooldown(modId); - [Obsolete("Use RimMindAPI.Request.GetModCooldownTicksLeft instead.")] - public static int GetModCooldownTicksLeft(string modId) => Request.GetModCooldownTicksLeft(modId); - - [Obsolete("No code consumers in Core or any sub-mod. Scheduled for removal in a future version.")] - public static string BuildMapContext(Map map, bool brief = false) => ChatFlow.BuildMapContext(map, brief); public static IToolRegistry Tools => ToolSet.Registry; public static IGameMechanismRegistry Mechanisms => ToolSet.Mechanisms; @@ -85,66 +47,16 @@ public static Task> SendAsync(LlmRequestEnvelo public static IExtensionRegistry ModePolicies => Ext.Get(); public static IExtensionRegistry Extensions() where T : class, IExtension => Ext.Get(); - [Obsolete("Use RimMindAPI.Ext.ShouldSkipDialogue instead.")] - public static bool ShouldSkipDialogue(Pawn pawn, string trigger) => Ext.ShouldSkipDialogue(pawn, trigger); - [Obsolete("Use RimMindAPI.Ext.ShouldSkipFloatMenu instead.")] - public static bool ShouldSkipFloatMenu() => Ext.ShouldSkipFloatMenu(); - [Obsolete("Use RimMindAPI.Ext.ShouldSkipAction instead.")] - public static bool ShouldSkipAction(string intentId) => Ext.ShouldSkipAction(intentId); - [Obsolete("Use RimMindAPI.Ext.ShouldSkipStorytellerIncident instead.")] - public static bool ShouldSkipStorytellerIncident() => Ext.ShouldSkipStorytellerIncident(); - [Obsolete("Use RimMindAPI.Ext.TriggerDialogue instead.")] - public static void TriggerDialogue(Pawn pawn, string context, Pawn? recipient = null) => Ext.TriggerDialogue(pawn, context, recipient); - [Obsolete("Use RimMindAPI.Ext.NotifyIncidentExecuted instead.")] - public static void NotifyIncidentExecuted() => Ext.NotifyIncidentExecuted(); - [Obsolete("Use RimMindAPI.Ext.CanTriggerDialogue instead.")] - public static bool CanTriggerDialogue => Ext.CanTriggerDialogue; - [Obsolete("Use RimMindAPI.Ext.RegisterAgentIdentityProvider instead.")] - public static void RegisterAgentIdentityProvider(Func provider) => Ext.RegisterAgentIdentityProvider(provider); - [Obsolete("No code consumers in Core or any sub-mod. Scheduled for removal in a future version.")] - public static AgentIdentity? GetAgentIdentity(Pawn pawn) => Ext.GetAgentIdentity(pawn); - [Obsolete("Use RimMindAPI.Ext.RegisterAgentActionBridge instead.")] - public static void RegisterAgentActionBridge(IAgentActionBridge bridge) => Ext.RegisterAgentActionBridge(bridge); - [Obsolete("No code consumers in Core or any sub-mod. Scheduled for removal in a future version.")] - public static IAgentActionBridge GetAgentActionBridge() => Ext.GetAgentActionBridge(); public static void RegisterParameterTuner(IParameterTuner tuner) => Ext.RegisterParameterTuner(tuner); - [Obsolete("No code consumers in Core or any sub-mod. Scheduled for removal in a future version.")] - public static IReadOnlyList ParameterTuners => Ext.ParameterTuners; - - [Obsolete("Use RimMindAPI.Providers.GetProviderData instead.")] - public static Result GetProviderData(string category, Pawn pawn) => Providers.GetProviderData(category, pawn); - [Obsolete("Use RimMindAPI.Providers.GetStaticProviderData instead.")] - public static Result GetStaticProviderData(string category) => Providers.GetStaticProviderData(category); - [Obsolete("Use RimMindAPI.Providers.GetRegisteredCategories instead.")] - public static List GetRegisteredCategories() => Providers.GetRegisteredCategories(); - [Obsolete("Use RimMindAPI.Providers.UnregisterByOwner instead.")] - public static int UnregisterModProviders(string modId) => Providers.UnregisterByOwner(modId); - [Obsolete("Use RimMindAPI.Settings.IsConfigured instead.")] - public static bool IsConfigured() => Settings.IsConfigured(); internal static IHistoryManager GetHistoryManager() => Settings.GetHistoryManager(); - [Obsolete("Use RimMindAPI.Settings.GetContextEngine instead.")] - public static IContextEngine GetContextEngine() => Settings.GetContextEngine(); internal static IBudgetScheduler? GetContextScheduler() => Settings.GetContextScheduler(); internal static EmbeddingSnapshotStore? GetEmbeddingSnapshotStore() => Settings.GetEmbeddingSnapshotStore(); - [Obsolete("No code consumers in Core or any sub-mod. Scheduled for removal in a future version.")] - public static ITelemetryCollector Telemetry => Settings.Telemetry; - - [Obsolete("No code consumers in Core or any sub-mod. Scheduled for removal in a future version.")] - public static IAudioPlayer AudioPlayer => Audio.AudioPlayer; - [Obsolete("No code consumers in Core or any sub-mod. Scheduled for removal in a future version.")] - public static IAgentBus GetAgentBus() => Bus.GetAgentBus(); - [Obsolete("Use RimMindAPI.Bus.PublishPerception instead.")] - public static void PublishPerception(int pawnId, string type, string content, float importance = 0.5f) => Bus.PublishPerception(pawnId, type, content, importance); public static void RegisterPendingRequest(UIRequestEntry entry) => Bus.RegisterPendingRequest(entry); public static IReadOnlyList GetPendingRequests() => Bus.GetPendingRequests(); public static bool DismissPendingRequest(UIRequestEntry entry) => Bus.DismissPendingRequest(entry); internal static IAIClient? GetClient() => Bus.GetClient(); - [Obsolete("Use RimMindAPI.Bus.InvalidateClientCache instead.")] - public static void InvalidateClientCache() => Bus.InvalidateClientCache(); - [Obsolete("No code consumers in Core or any sub-mod. Scheduled for removal in a future version.")] - public static IAIClient? GetPlayer2Client() => Bus.GetPlayer2Client(); public static string? GetNpcForMap(Map map) => GameServiceRef.Optional().ValueOrDefault?.GetNpcForMap(map); diff --git a/Source/RimMindCore.csproj b/Source/RimMindCore.csproj index 4845c40a..7b3de355 100644 --- a/Source/RimMindCore.csproj +++ b/Source/RimMindCore.csproj @@ -15,7 +15,6 @@ false false false - CS8604;CS8601;CS8602;CS8603 @@ -59,18 +58,4 @@ DestinationFolder="$(OutputPath)" SkipUnchangedFiles="true" /> - - - - $(RIMWORLD_DIR)\Mods\RimMind-Core\ - - - - - - - - - diff --git a/Tests/Contracts/AgentDecisionParamAdaptationContracts.cs b/Tests/Contracts/AgentDecisionParamAdaptationContracts.cs index 520a5835..02ed7ad0 100644 --- a/Tests/Contracts/AgentDecisionParamAdaptationContracts.cs +++ b/Tests/Contracts/AgentDecisionParamAdaptationContracts.cs @@ -10,6 +10,8 @@ using RimMind.Domain.ValueObjects; using RimMind.Infrastructure.Agent; using RimMind.Infrastructure.Mechanisms; +using RimMind.Infrastructure.Mechanisms.Pawn.Job; +using RimMind.Infrastructure.Mechanisms.Pawn.Work; using Xunit; namespace RimMind.Tests.Contracts @@ -17,16 +19,23 @@ namespace RimMind.Tests.Contracts /// /// Regression: LLM decisions with plain-text Param (e.g. "param":"Construction") were silently /// replaced with {} so pawn.work.set failed with "Invalid def name ''". + /// Verifies Core's pluggable IToolArgumentAdapter implementations via MechanismActionExecutor. /// public sealed class AgentDecisionParamAdaptationContracts { + private static IToolArgumentAdapter[] CoreAdapters() => new IToolArgumentAdapter[] + { + new WorkMechanismArgumentAdapter(), + new JobMechanismArgumentAdapter() + }; + [Fact] public void PlainTextParam_IsForwardedAsWorkTarget_ForWorkSetTool() { var tools = new ToolRegistry(); var workTool = new RecordingToolHandler("pawn.work.set"); tools.Register(workTool); - var executor = new MechanismActionExecutor(new GameMechanismRegistry(), tools, () => Array.Empty()); + var executor = new MechanismActionExecutor(new GameMechanismRegistry(), tools, CoreAdapters); var result = executor.ExecuteDecision( new AgentDecision(ActionIntent: "pawn.work.set", Reason: "build shelter", Param: "Construction"), @@ -46,7 +55,7 @@ public void PlainTextParam_DoesNotForceAssignWork_ForJobSetTool() var tools = new ToolRegistry(); var jobTool = new RecordingToolHandler("pawn.job.set"); tools.Register(jobTool); - var executor = new MechanismActionExecutor(new GameMechanismRegistry(), tools, () => Array.Empty()); + var executor = new MechanismActionExecutor(new GameMechanismRegistry(), tools, CoreAdapters); var result = executor.ExecuteDecision( new AgentDecision(ActionIntent: "pawn.job.set", Reason: "starving", Param: "eat a meal"), @@ -66,7 +75,7 @@ public void ArgumentlessJobSet_IsNotSilentlyTurnedIntoForceRest() var tools = new ToolRegistry(); var jobTool = new RecordingToolHandler("pawn_job_set"); tools.Register(jobTool); - var executor = new MechanismActionExecutor(new GameMechanismRegistry(), tools, () => Array.Empty()); + var executor = new MechanismActionExecutor(new GameMechanismRegistry(), tools, CoreAdapters); executor.ExecuteDecision(new AgentDecision(ActionIntent: "pawn_job_set", Reason: "", Param: "{}"), pawnId: 5); diff --git a/Tests/Contracts/AgentTraceFormattingContracts.cs b/Tests/Contracts/AgentTraceFormattingContracts.cs index bf9a1b04..ae0c32f5 100644 --- a/Tests/Contracts/AgentTraceFormattingContracts.cs +++ b/Tests/Contracts/AgentTraceFormattingContracts.cs @@ -1,4 +1,6 @@ +using System; using System.Collections.Generic; +using RimMind.Application.Common.Interfaces.Diagnostics; using RimMind.Application.Common.Models.Debug; using RimMind.Infrastructure.UI.AgentsPage; using Xunit; @@ -44,7 +46,7 @@ public void BuildRow_CleansXmlTagsAndNewlines_WhenWaiting() { RequestId = "req-002", State = AIRequestTraceState.Running, - UserPrompt = "[L4] \n请根据你当前的状态和周围环境,自然地做出回应。\n" + UserPrompt = "[L4] \nObserve surrounding state and respond naturally.\n" }; var rows = AgentRequestTraceRowBuilder.BuildRecent(new[] { entry }); @@ -52,9 +54,9 @@ public void BuildRow_CleansXmlTagsAndNewlines_WhenWaiting() var row = rows[0]; Assert.Equal(AgentRequestTraceStatus.Waiting, row.Status); - Assert.Contains("DailyReaction", row.Summary); + Assert.Contains("Observe surrounding state", row.Summary); Assert.DoesNotContain("[L4]", row.Summary); - Assert.DoesNotContain("", row.Summary); + Assert.DoesNotContain("", row.Summary); Assert.DoesNotContain("\n", row.Summary); Assert.DoesNotContain("\r", row.Summary); } @@ -100,25 +102,78 @@ public void BuildRow_HandlesMarkdownCodeBlockJson() } [Fact] - public void BuildRow_HandlesExpressDialogueToolCallWithEscapedJsonArguments() + public void BuildRow_DelegatesSummarizationAndToolSuppression_ToRegisteredTraceSummarizer() { - var entry = new AIRequestTraceEntry + const string owner = "test.trace.summarizer"; + var summarizer = new StubTraceSummarizer(owner); + RequestTraceSummarizerRegistry.Register(summarizer); + try { - RequestId = "req-005", - State = AIRequestTraceState.Completed, - Response = "[{\"id\":\"call_99\",\"type\":\"function\",\"function\":{\"name\":\"express_dialogue\",\"arguments\":\"{\\\"speech\\\":\\\"今天天气真不错。\\\",\\\"thought_tag\\\":\\\"VALUED\\\",\\\"thought_desc\\\":\\\"轻松愉快\\\"}\"}}]" - }; - entry.ToolCalls.Add(new AIRequestToolCallTrace("call_99", "express_dialogue", true, null)); + var waitingEntry = new AIRequestTraceEntry + { + RequestId = "req-005-wait", + State = AIRequestTraceState.Running, + UserPrompt = "[L4] auto" + }; + var waitRow = Assert.Single(AgentRequestTraceRowBuilder.BuildRecent(new[] { waitingEntry })); + Assert.Equal(AgentRequestTraceStatus.Waiting, waitRow.Status); + Assert.Contains("CustomTriggerSummary", waitRow.Summary); + + var completedEntry = new AIRequestTraceEntry + { + RequestId = "req-005-done", + State = AIRequestTraceState.Completed, + Response = "[{\"id\":\"call_99\",\"type\":\"function\",\"function\":{\"name\":\"custom_speech_tool\",\"arguments\":\"{}\"}}]" + }; + completedEntry.ToolCalls.Add(new AIRequestToolCallTrace("call_99", "custom_speech_tool", true, null)); + + var doneRow = Assert.Single(AgentRequestTraceRowBuilder.BuildRecent(new[] { completedEntry })); + Assert.Equal(AgentRequestTraceStatus.Success, doneRow.Status); + Assert.Contains("Clear skies today.", doneRow.Summary); + Assert.DoesNotContain("custom_speech_tool", doneRow.Summary); + Assert.DoesNotContain("call_99", doneRow.Summary); + } + finally + { + RequestTraceSummarizerRegistry.UnregisterByOwner(owner); + } + } - var rows = AgentRequestTraceRowBuilder.BuildRecent(new[] { entry }); - Assert.Single(rows); + private sealed class StubTraceSummarizer : IRequestTraceSummarizer + { + public StubTraceSummarizer(string ownerModId) + { + OwnerModId = ownerModId; + } - var row = rows[0]; - Assert.Equal(AgentRequestTraceStatus.Success, row.Status); - Assert.Contains("今天天气真不错。", row.Summary); - Assert.Contains("轻松愉快", row.Summary); - Assert.DoesNotContain("express_dialogue", row.Summary); - Assert.DoesNotContain("call_99", row.Summary); + public string Id => "test.summarizer.custom"; + public string OwnerModId { get; } + public int Order => 10; + + public bool TrySummarizeResponse(AIRequestTraceEntry entry, out RequestTraceSummary? summary) + { + if (entry.Response != null && entry.Response.Contains("custom_speech_tool", StringComparison.Ordinal)) + { + summary = new RequestTraceSummary("Clear skies today.", new[] { "custom_speech_tool" }); + return true; + } + summary = null; + return false; + } + + public bool TrySummarizePrompt(string rawPrompt, out string? summary) + { + if (rawPrompt.Contains("", StringComparison.Ordinal)) + { + summary = "CustomTriggerSummary"; + return true; + } + summary = null; + return false; + } + + public bool ShouldSuppressToolCall(string toolName) + => string.Equals(toolName, "custom_speech_tool", StringComparison.OrdinalIgnoreCase); } } } diff --git a/Tests/Contracts/BackupEndpointFailoverContracts.cs b/Tests/Contracts/BackupEndpointFailoverContracts.cs index c60dd263..fac5c283 100644 --- a/Tests/Contracts/BackupEndpointFailoverContracts.cs +++ b/Tests/Contracts/BackupEndpointFailoverContracts.cs @@ -13,7 +13,6 @@ using Newtonsoft.Json.Linq; using RimMind.Application.Common.Models.Npc; using RimMind.Infrastructure.Services.Clients; -using RimMind.Infrastructure.Services.Clients.Hybrid; using RimMind.Infrastructure.Services.Clients.OpenAI; using RimMind.Infrastructure.Services.Clients.Player2; using RimMind.Infrastructure.Services.Clients.Shared; @@ -108,8 +107,20 @@ public async Task SendAsync_FailsOverToOpenCodeBackupOnPrimary503_AndIsolatesPri Assert.Contains("\"model\":\"grok-4.7\"", requestJsonPayloads[0]); Assert.Contains("\"model\":\"deepseek-v4.1-flash-free\"", requestJsonPayloads[1]); Assert.Contains("\"max_tokens\":800", requestJsonPayloads[1]); - Assert.Equal("x-opencode-session", capturedHeaderNames[1]); - Assert.Contains("rimmind-NPC-101", capturedHeaderValues[1]); + + // Verify OpenCodeHeaderDecorator injects x-opencode-session via HttpRequestDecorationContext + HttpTransport.RegisterDecorator(OpenCodeHeaderDecorator.Instance); + using var decoratedReq = new HttpRequestMessage(HttpMethod.Post, "https://opencode.ai/zen/go/v1/chat/completions"); + HttpTransport.ApplyDecorators( + decoratedReq, + new HttpRequestDecorationContext( + Url: "https://opencode.ai/zen/go/v1/chat/completions", + AuthHeader: "Bearer oc_sk_test_placeholder", + RequestId: "req-1", + NpcId: "NPC-101", + Provider: "opencode")); + Assert.True(decoratedReq.Headers.Contains("x-opencode-session")); + Assert.Contains("rimmind-NPC-101", string.Join(",", decoratedReq.Headers.GetValues("x-opencode-session"))); // 2nd request within 60s cooldown: Primary is isolated, so it routes directly to Backup #1! var secondResult = await client.SendAsync(CreateEnvelope("req-2")); @@ -355,7 +366,7 @@ public async Task SendStreamAsync_AccumulatesIndexedToolCalls_HandlesNoSpaceSse_ } [Fact] - public async Task HybridAIClient_AndPlayer2Dtos_PreserveStreamBoundaries_AndSnakeCaseToolPayloads() + public void Player2Dtos_PreserveSnakeCaseToolPayloads() { // Verify Player2RequestDto serializes snake_case fields for tools, tool_choice, and response_format var dto = new Player2RequestDto @@ -370,18 +381,6 @@ public async Task HybridAIClient_AndPlayer2Dtos_PreserveStreamBoundaries_AndSnak Assert.Contains("\"tool_choice\":\"auto\"", json); Assert.Contains("\"response_format\":{\"type\":\"json_object\"}", json); Assert.Contains("\"tools\":[", json); - - // Verify HybridAIClient does not fall back to local client if remote stream already emitted chunks - var remotePrimary = new StubStreamingClient(emitBeforeFail: true); - var localFallback = new StubStreamingClient(emitBeforeFail: false); - var hybrid = new HybridAIClient(remotePrimary, localFallback); - - var emitted = new List(); - var res = await hybrid.SendStreamAsync(CreateEnvelope("req-hybrid"), c => { if (!string.IsNullOrEmpty(c.DeltaContent)) emitted.Add(c.DeltaContent!); }, CancellationToken.None); - Assert.True(res.IsErr); - Assert.Equal(1, remotePrimary.StreamCalls); - Assert.Equal(0, localFallback.StreamCalls); - Assert.Single(emitted); } [Fact] @@ -495,44 +494,5 @@ public override int Read(byte[] buffer, int offset, int count) throw new IOException("Connection reset mid-stream"); } } - - private sealed class StubStreamingClient : IAIClient - { - private readonly bool _emitBeforeFail; - public int StreamCalls { get; private set; } - - public StubStreamingClient(bool emitBeforeFail) - { - _emitBeforeFail = emitBeforeFail; - } - - public bool IsLocalEndpoint => false; - public bool IsConfigured() => true; - public bool SupportsStreaming => true; - public bool SupportsNpcServerState => false; - - public Task> SendAsync(LlmRequestEnvelope envelope) - => Task.FromResult(Result.Ok(new LlmResponse { Content = "ok" })); - - public Task> SendStreamAsync(LlmRequestEnvelope envelope, Action onChunk, CancellationToken ct = default) - { - StreamCalls++; - if (_emitBeforeFail) - { - onChunk(new LlmChunk { DeltaContent = "partial-remote" }); - return Task.FromResult(Result.Err(RimMindErrors.ClientTransient("mid-stream drop"))); - } - onChunk(new LlmChunk { DeltaContent = "fallback-ok" }); - return Task.FromResult(Result.Ok(new LlmResponse { Content = "fallback-ok" })); - } - - public Task> SpawnNpcAsync(NpcProfile profile) - => Task.FromResult(Result.Ok(true)); - public Task> KillNpcAsync(string npcId) - => Task.FromResult(Result.Ok(true)); - public Task, RimMindError>> QueryNpcMemoriesAsync(string npcId, string query, int limit) - => Task.FromResult(Result, RimMindError>.Ok(new List())); - public void Dispose() { } - } } } diff --git a/Tests/Contracts/BatchBCoreAgentMechanismContracts.cs b/Tests/Contracts/BatchBCoreAgentMechanismContracts.cs index aa4539ef..0f50476e 100644 --- a/Tests/Contracts/BatchBCoreAgentMechanismContracts.cs +++ b/Tests/Contracts/BatchBCoreAgentMechanismContracts.cs @@ -37,6 +37,7 @@ namespace RimMind.Tests.Contracts { + [Collection("MechanismToolHandler")] public sealed class BatchBCoreAgentMechanismContracts { [Fact] diff --git a/Tests/Contracts/DomainApplicationContracts.cs b/Tests/Contracts/DomainApplicationContracts.cs index ca7ad933..0016826b 100644 --- a/Tests/Contracts/DomainApplicationContracts.cs +++ b/Tests/Contracts/DomainApplicationContracts.cs @@ -513,6 +513,7 @@ private sealed class PrefixTranslationService : ITranslationService { private readonly string _prefix; public PrefixTranslationService(string prefix) => _prefix = prefix; + public bool CanTranslate(string key) => !string.IsNullOrEmpty(key); public string Translate(string key) => _prefix + key; public string Translate(string key, object arg0) => Translate(key); public string Translate(string key, object arg0, object arg1) => Translate(key); diff --git a/Tests/Contracts/P6ApiVersionContracts.cs b/Tests/Contracts/P6ApiVersionContracts.cs index 78080f74..26ce0ba7 100644 --- a/Tests/Contracts/P6ApiVersionContracts.cs +++ b/Tests/Contracts/P6ApiVersionContracts.cs @@ -26,42 +26,29 @@ public void RimMindAPI_v2_version_constant_and_flat_alias_deprecations_are_locke Assert.Contains("public static IExtensionRegistry Modes => Ext.Get();", apiSource, StringComparison.Ordinal); Assert.Contains("public static IExtensionRegistry ModePolicies => Ext.Get();", apiSource, StringComparison.Ordinal); }), - ("flat forwarding aliases guide callers to nested groups via [Obsolete]", () => + ("retired [Obsolete] flat aliases have been hard-cut from RimMindAPI.cs", () => { - string[] expectedGuidance = + int totalObsoleteCount = Regex.Matches(apiSource, @"\[Obsolete\(").Count; + Assert.Equal(0, totalObsoleteCount); + + string[] retiredMembers = { - "[Obsolete(\"Use RimMindAPI.Request.PauseQueue instead.\")]", - "[Obsolete(\"Use RimMindAPI.Request.ResumeQueue instead.\")]", - "[Obsolete(\"Use RimMindAPI.Request.ActiveRequestCount instead.\")]", - "[Obsolete(\"Use RimMindAPI.Request.TotalQueuedCount instead.\")]", - "[Obsolete(\"Use RimMindAPI.Request.ClearModCooldown instead.\")]", - "[Obsolete(\"Use RimMindAPI.Request.GetModCooldownTicksLeft instead.\")]", - "[Obsolete(\"Use RimMindAPI.Ext.ShouldSkipDialogue instead.\")]", - "[Obsolete(\"Use RimMindAPI.Ext.ShouldSkipFloatMenu instead.\")]", - "[Obsolete(\"Use RimMindAPI.Ext.ShouldSkipAction instead.\")]", - "[Obsolete(\"Use RimMindAPI.Ext.ShouldSkipStorytellerIncident instead.\")]", - "[Obsolete(\"Use RimMindAPI.Ext.TriggerDialogue instead.\")]", - "[Obsolete(\"Use RimMindAPI.Ext.NotifyIncidentExecuted instead.\")]", - "[Obsolete(\"Use RimMindAPI.Ext.CanTriggerDialogue instead.\")]", - "[Obsolete(\"Use RimMindAPI.Ext.RegisterAgentIdentityProvider instead.\")]", - "[Obsolete(\"Use RimMindAPI.Ext.RegisterAgentActionBridge instead.\")]", - "[Obsolete(\"Use RimMindAPI.Providers.GetProviderData instead.\")]", - "[Obsolete(\"Use RimMindAPI.Providers.GetStaticProviderData instead.\")]", - "[Obsolete(\"Use RimMindAPI.Providers.GetRegisteredCategories instead.\")]", - "[Obsolete(\"Use RimMindAPI.Providers.UnregisterByOwner instead.\")]", - "[Obsolete(\"Use RimMindAPI.Settings.IsConfigured instead.\")]", - "[Obsolete(\"Use RimMindAPI.Settings.GetContextEngine instead.\")]", - "[Obsolete(\"Use RimMindAPI.Bus.PublishPerception instead.\")]", - "[Obsolete(\"Use RimMindAPI.Bus.InvalidateClientCache instead.\")]" + "PauseQueue(", + "ResumeQueue(", + "ActiveRequestCount =>", + "TotalQueuedCount =>", + "ShouldSkipDialogue(", + "TriggerDialogue(", + "GetProviderData(", + "GetAgentBus(", + "GetPlayer2Client(", + "InvalidateClientCache(" }; - foreach (string attr in expectedGuidance) + foreach (string retired in retiredMembers) { - Assert.Contains(attr, apiSource, StringComparison.Ordinal); + Assert.DoesNotContain(retired, apiSource, StringComparison.Ordinal); } - - int totalObsoleteCount = Regex.Matches(apiSource, @"\[Obsolete\(").Count; - Assert.True(totalObsoleteCount >= 34, $"Expected at least 34 [Obsolete] attributes on RimMindAPI.cs, found {totalObsoleteCount}."); })); } diff --git a/Tests/Contracts/PawnLookupContracts.cs b/Tests/Contracts/PawnLookupContracts.cs index 633230ac..adfe49ff 100644 --- a/Tests/Contracts/PawnLookupContracts.cs +++ b/Tests/Contracts/PawnLookupContracts.cs @@ -435,13 +435,22 @@ public void Lifecycle_and_dispatcher_static_invariants_contracts() string runtimeCode = File.ReadAllText(Path.Combine(root, "RimMind-Core", "Source", "Presentation", "Runtime", "RimMindRuntimeGameComponent.cs")); Assert.Contains("Player2Client.StopHealthCheck()", runtimeCode, StringComparison.Ordinal); })), - ("VersePawnSleepDetector and Window_AgentProgressFloat follow pawn lookup and thread-safety invariants", (Action)(() => + ("GetSpawnedColonistsSafe filters dead and prisoner pawns on main thread, and Window_AgentProgressFloat avoids raw AllPawns scans", (Action)(() => { - string root = FindRepoRoot(); - string sleepCode = File.ReadAllText(Path.Combine(root, "RimMind-Core", "Source", "Infrastructure", "Social", "VersePawnSleepDetector.cs")); - Assert.Contains("RimMindPawnLookup.FindPawnById", sleepCode, StringComparison.Ordinal); - Assert.DoesNotContain("WorldPawns", sleepCode, StringComparison.Ordinal); + UnityData.IsInMainThread = true; + var map = new Map(); + var liveColonist = new Pawn { thingIDNumber = 701, Map = map, Spawned = true, IsColonist = true, Faction = RimWorld.Faction.OfPlayer }; + var deadColonist = new Pawn { thingIDNumber = 702, Map = map, Spawned = true, IsColonist = true, Dead = true, Faction = RimWorld.Faction.OfPlayer }; + var prisoner = new Pawn { thingIDNumber = 703, Map = map, Spawned = true, IsColonist = true, IsPrisoner = true, Faction = RimWorld.Faction.OfPlayer }; + map.mapPawns.FreeColonistsSpawned.Add(liveColonist); + map.mapPawns.FreeColonistsSpawned.Add(deadColonist); + map.mapPawns.FreeColonistsSpawned.Add(prisoner); + var safeColonists = RimMindPawnLookup.GetSpawnedColonistsSafe(map); + Assert.Single(safeColonists); + Assert.Same(liveColonist, safeColonists[0]); + + string root = FindRepoRoot(); string floatCode = File.ReadAllText(Path.Combine(root, "RimMind-Core", "Source", "Infrastructure", "UI", "Window_AgentProgressFloat.cs")); Assert.Contains("RimMindPawnLookup.GetEligibleColonists(Find.CurrentMap)", floatCode, StringComparison.Ordinal); Assert.DoesNotContain("Find.CurrentMap.mapPawns.AllPawns", floatCode, StringComparison.Ordinal); diff --git a/Tests/Contracts/RequestSubmissionServiceContract.cs b/Tests/Contracts/RequestSubmissionServiceContract.cs index f12ce808..65eaf373 100644 --- a/Tests/Contracts/RequestSubmissionServiceContract.cs +++ b/Tests/Contracts/RequestSubmissionServiceContract.cs @@ -105,7 +105,6 @@ private sealed class StubClientManager : IClientManager public StubClientManager(IAIClient? client) => _client = client; public IAIClient? GetClient() => _client; - public IAIClient? GetPlayer2Client() => null; public void InvalidateCache() { } } diff --git a/Tests/Contracts/RuntimeAsyncFenceContract.cs b/Tests/Contracts/RuntimeAsyncFenceContract.cs index 65686272..50fbf5d4 100644 --- a/Tests/Contracts/RuntimeAsyncFenceContract.cs +++ b/Tests/Contracts/RuntimeAsyncFenceContract.cs @@ -61,7 +61,8 @@ public void Async_completions_are_cancelled_and_fenced_before_side_effects() Assert.Contains("new ProactiveBehaviorExecutor(", thinker, StringComparison.Ordinal); Assert.Contains("_completionFence);", thinker, StringComparison.Ordinal); Assert.Contains("ICompletionFence", executor, StringComparison.Ordinal); - Assert.Contains("_completionFence);", executor, StringComparison.Ordinal); + Assert.Contains("completionFence: _completionFence", executor, StringComparison.Ordinal); + Assert.Contains("mainThreadDispatch: RimMindAPI.MainThread.Post", executor, StringComparison.Ordinal); }), ("non-streaming queue and client invocation preserve the linked token", () => { diff --git a/Tests/Contracts/ToolCallDispatchMiddlewareContract.cs b/Tests/Contracts/ToolCallDispatchMiddlewareContract.cs index 7dbaab2b..10418136 100644 --- a/Tests/Contracts/ToolCallDispatchMiddlewareContract.cs +++ b/Tests/Contracts/ToolCallDispatchMiddlewareContract.cs @@ -21,6 +21,7 @@ namespace RimMind.Tests.Contracts { + [Collection("MechanismToolHandler")] public sealed class ToolCallDispatchMiddlewareContract { [Fact] diff --git a/Tests/Infrastructure/OpenAI/__snapshots__/decision-request.json b/Tests/Infrastructure/OpenAI/__snapshots__/decision-request.json deleted file mode 100644 index 1403e191..00000000 --- a/Tests/Infrastructure/OpenAI/__snapshots__/decision-request.json +++ /dev/null @@ -1,74 +0,0 @@ -{ - "model": "gpt-4o-mini", - "messages": [ - { - "role": "system", - "content": "You are an autonomous RimWorld colonist. Decide the single best next action. Respond ONLY with {\"action\":\"mechanism.operation\",\"reason\":\"...\",\"param\":\"...\"}." - }, - { - "role": "user", - "content": "[mood] Mood: 35% (importance:0.7)\n[need] Need: Food at 20% (importance:0.9)" - }, - { - "role": "assistant", - "content": "{\"action\":\"pawn.job.force_rest\",\"reason\":\"Mood and food needs are critical; rest first to stabilize mood before eating\"}" - }, - { - "role": "user", - "content": "[combat] Currently drafted for combat (importance:1.0)\n[health] Health issue: Bruise (importance:0.4)" - }, - { - "role": "assistant", - "content": "{\"action\":\"pawn.draft.toggle\",\"reason\":\"Enemy nearby; engage in combat defense despite minor injury\"}" - }, - { - "role": "user", - "content": "[environment] Environment: Clear, 22°C (importance:0.1)\n[social] Social: Alice (friend) (importance:0.3)" - }, - { - "role": "assistant", - "content": "{\"action\":\"pawn.work.set\",\"reason\":\"No urgent needs; assign to mining work with friend nearby\",\"param\":\"Mining\"}" - }, - { - "role": "user", - "content": "[combat] Enemy spotted at range 15 (importance:1.0)" - }, - { - "role": "assistant", - "content": "{\"action\":\"pawn.draft.toggle\",\"reason\":\"Need to engage enemy; drafting first to access combat tools\"}" - }, - { - "role": "user", - "content": "[tool_result] pawn.draft.toggle succeeded. Now drafted. (importance:0.8)" - }, - { - "role": "assistant", - "content": "{\"action\":\"pawn.equipment.set\",\"reason\":\"Drafted and need ranged weapon for enemy at range 15\",\"param\":\"SniperRifle\"}" - }, - { - "role": "user", - "content": "Pawn is hungry. Food available in stockpile." - } - ], - "max_tokens": 800, - "temperature": 0.7, - "stream": false, - "tools": [ - { - "type": "function", - "function": { - "name": "pawn.move.to", - "description": "Move the pawn to a target cell.", - "parameters": { - "type": "object", - "properties": { - "target": { - "type": "string" - } - } - } - } - } - ], - "tool_choice": "auto" -} diff --git a/Tests/Presentation/Settings/OverlaySettingsTests.cs b/Tests/Presentation/Settings/OverlaySettingsTests.cs deleted file mode 100644 index 3397129a..00000000 --- a/Tests/Presentation/Settings/OverlaySettingsTests.cs +++ /dev/null @@ -1,52 +0,0 @@ -using RimMind.Application.Common.Interfaces.Internal; -using RimMind.Application.Features.Requests.Queue; -using Xunit; - -namespace RimMind.Tests.Presentation.Settings -{ - public class OverlaySettingsTests - { - [Fact] - public void OverlaySettings_PropertyMutations_PersistCorrectly() - { - var provider = new DefaultSettingsProvider(); - IOverlaySettings settings = provider; - - Assert.False(settings.ShowAgentProgressFloat); - settings.RequestOverlayX = 150f; - settings.RequestOverlayY = 250f; - settings.RequestOverlayW = 400f; - settings.RequestOverlayH = 200f; - settings.RequestOverlayEnabled = false; - settings.RequestOverlayAutoHideWhenEmpty = false; - settings.ShowAgentProgressFloat = true; - settings.EnableFloatingMentalMonitor = true; - - Assert.Equal(150f, settings.RequestOverlayX); - Assert.Equal(250f, settings.RequestOverlayY); - Assert.Equal(400f, settings.RequestOverlayW); - Assert.Equal(200f, settings.RequestOverlayH); - Assert.False(settings.RequestOverlayEnabled); - Assert.False(settings.RequestOverlayAutoHideWhenEmpty); - Assert.True(settings.ShowAgentProgressFloat); - Assert.True(settings.EnableFloatingMentalMonitor); - } - - [Fact] - public void OverlaySettings_ToggleAutoHide_UpdatesState() - { - var provider = new DefaultSettingsProvider(); - IOverlaySettings settings = provider; - - Assert.True(settings.RequestOverlayW > 0); - Assert.True(settings.RequestOverlayH > 0); - Assert.True(settings.RequestOverlayEnabled); - Assert.True(settings.RequestOverlayAutoHideWhenEmpty); - Assert.False(settings.EnableFloatingMentalMonitor); - settings.RequestOverlayAutoHideWhenEmpty = false; - Assert.False(settings.RequestOverlayAutoHideWhenEmpty); - settings.RequestOverlayAutoHideWhenEmpty = true; - Assert.True(settings.RequestOverlayAutoHideWhenEmpty); - } - } -} diff --git a/Tests/RimMindCore.Tests.csproj b/Tests/RimMindCore.Tests.csproj index 2a78a203..a6157cce 100644 --- a/Tests/RimMindCore.Tests.csproj +++ b/Tests/RimMindCore.Tests.csproj @@ -14,7 +14,7 @@ - + @@ -39,6 +39,8 @@ + + @@ -57,9 +59,9 @@ - - - + + + @@ -94,8 +96,6 @@ - - @@ -106,6 +106,7 @@ + diff --git a/Tests/RimMindTestStubs.cs b/Tests/RimMindTestStubs.cs index 0987afd3..ef6e848d 100644 --- a/Tests/RimMindTestStubs.cs +++ b/Tests/RimMindTestStubs.cs @@ -88,25 +88,3 @@ public static void ResetForTests() } } } - -namespace RimMind.Application.Common.Interfaces.Internal -{ - // Test-only compatibility seam for legacy tests retained on disk until the - // compact contract-project cutover. Production has no service locator. - internal static class RimMindServiceLocator - { - private static readonly Dictionary Services = new Dictionary(); - - public static void Register(T instance) where T : class - => Services[typeof(T)] = instance; - - public static T? Get() where T : class - => Services.TryGetValue(typeof(T), out var value) ? (T)value : null; - - public static T? TryGet() where T : class => Get(); - - public static bool IsRegistered() => Services.ContainsKey(typeof(T)); - - public static void Reset() => Services.Clear(); - } -} diff --git a/Tests/RuntimeReferenceTests.cs b/Tests/RuntimeReferenceTests.cs deleted file mode 100644 index b9e1948c..00000000 --- a/Tests/RuntimeReferenceTests.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Reflection.Metadata; -using System.Reflection.PortableExecutable; -using Xunit; - -namespace RimMind.Core.Tests -{ - public class RuntimeReferenceTests - { - [Fact] - public void BuiltMod_UsesOnlyPackagedRuntimeDependencies() - { - string dll = Path.GetFullPath( - Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "1.6", "Assemblies", "RimMindCore.dll")); - - using var stream = File.OpenRead(dll); - using var pe = new PEReader(stream); - MetadataReader metadata = pe.GetMetadataReader(); - string[] references = metadata.AssemblyReferences - .Select(handle => metadata.GetString(metadata.GetAssemblyReference(handle).Name)) - .ToArray(); - - Assert.DoesNotContain("System.Net.Http", references); - Assert.Contains("Newtonsoft.Json", references); - - string jsonDll = Path.Combine(Path.GetDirectoryName(dll)!, "Newtonsoft.Json.dll"); - Assert.True(File.Exists(jsonDll), "Newtonsoft.Json.dll must be deployed beside RimMindCore.dll."); - Assert.Equal(new Version(13, 0, 0, 0), AssemblyName.GetAssemblyName(jsonDll).Version); - } - } -} diff --git a/Tests/_snapshots/ui/agent_active.html b/Tests/_snapshots/ui/agent_active.html deleted file mode 100644 index 1db98fe8..00000000 --- a/Tests/_snapshots/ui/agent_active.html +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - -
    -
    -
    -
    Nickie - Active
    -
    Pause
    -
    -
    -
    - - diff --git a/Tests/_snapshots/ui/agent_active.svg b/Tests/_snapshots/ui/agent_active.svg deleted file mode 100644 index 0fb6d5fa..00000000 --- a/Tests/_snapshots/ui/agent_active.svg +++ /dev/null @@ -1,10 +0,0 @@ - - - - - Nickie - Active - - Pause - - - diff --git a/Tests/_snapshots/ui/agent_error.html b/Tests/_snapshots/ui/agent_error.html deleted file mode 100644 index dba1fbff..00000000 --- a/Tests/_snapshots/ui/agent_error.html +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - -
    -
    -
    -
    -
    Cashton - Error
    -
    Open Requests
    -
    -
    - - diff --git a/Tests/_snapshots/ui/agent_error.svg b/Tests/_snapshots/ui/agent_error.svg deleted file mode 100644 index ab682295..00000000 --- a/Tests/_snapshots/ui/agent_error.svg +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - Cashton - Error - - Open Requests - - diff --git a/Tests/_snapshots/ui/agent_paused.html b/Tests/_snapshots/ui/agent_paused.html deleted file mode 100644 index e98f6bab..00000000 --- a/Tests/_snapshots/ui/agent_paused.html +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - -
    -
    -
    -
    -
    Nickie - Paused
    -
    Resume
    -
    -
    - - diff --git a/Tests/_snapshots/ui/agent_paused.svg b/Tests/_snapshots/ui/agent_paused.svg deleted file mode 100644 index c3c8383a..00000000 --- a/Tests/_snapshots/ui/agent_paused.svg +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - Nickie - Paused - - Resume - - diff --git a/Tests/_snapshots/ui/agent_pending.html b/Tests/_snapshots/ui/agent_pending.html deleted file mode 100644 index da4ca70e..00000000 --- a/Tests/_snapshots/ui/agent_pending.html +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - -
    -
    -
    -
    Cashton - Pending
    -
    Start
    -
    -
    - - diff --git a/Tests/_snapshots/ui/agent_pending.svg b/Tests/_snapshots/ui/agent_pending.svg deleted file mode 100644 index b9336e1c..00000000 --- a/Tests/_snapshots/ui/agent_pending.svg +++ /dev/null @@ -1,9 +0,0 @@ - - - - - Cashton - Pending - - Start - - diff --git a/Tests/_snapshots/ui/context_keys_dense.html b/Tests/_snapshots/ui/context_keys_dense.html deleted file mode 100644 index b151a891..00000000 --- a/Tests/_snapshots/ui/context_keys_dense.html +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - -
    -
    -
    Context Keys
    -
    Status | Time | Scope | Actor | Channel | Model | Summary | Duration
    -
    -
    -
    Completed | 10:08 | L0 | Core | pawn.identity | context | Pawn identity snapshot | 120 tokens
    -
    Completed | 10:08 | L1 | Core | pawn.needs | context | Need and mood summary | 220 tokens
    -
    Completed | 10:08 | L1 | Memory | memory.recent | context | Recent memories compacted | 310 tokens
    -
    Completed | 10:08 | L2 | Advisor | advisor.options | context | Available actions and risks | 260 tokens
    -
    Waiting | 10:09 | L3 | Storyteller | world.threats | context | Awaiting threat scan | 0 tokens
    -
    Cancelled | 10:09 | L4 | Dialogue | dialogue.history | context | Skipped by budget | 0 tokens
    -
    - - diff --git a/Tests/_snapshots/ui/context_keys_dense.svg b/Tests/_snapshots/ui/context_keys_dense.svg deleted file mode 100644 index 176d424b..00000000 --- a/Tests/_snapshots/ui/context_keys_dense.svg +++ /dev/null @@ -1,21 +0,0 @@ - - - - Context Keys - - Status | Time | Scope | Actor | Channel | Model | Summary | Duration - - - - Completed | 10:08 | L0 | Core | pawn.identity | context | Pawn identity snapshot | 120 tokens - - Completed | 10:08 | L1 | Core | pawn.needs | context | Need and mood summary | 220 tokens - - Completed | 10:08 | L1 | Memory | memory.recent | context | Recent memories compacted | 310 tokens - - Completed | 10:08 | L2 | Advisor | advisor.options | context | Available actions and risks | 260 tokens - - Waiting | 10:09 | L3 | Storyteller | world.threats | context | Awaiting threat scan | 0 tokens - - Cancelled | 10:09 | L4 | Dialogue | dialogue.history | context | Skipped by budget | 0 tokens - diff --git a/Tests/_snapshots/ui/debug_center_tabs.html b/Tests/_snapshots/ui/debug_center_tabs.html deleted file mode 100644 index 1e0e6b10..00000000 --- a/Tests/_snapshots/ui/debug_center_tabs.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - -
    -
    overview
    -
    agents
    -
    ai_requests
    -
    toolcalls
    -
    mechanisms
    -
    context
    -
    -
    - - diff --git a/Tests/_snapshots/ui/debug_center_tabs.svg b/Tests/_snapshots/ui/debug_center_tabs.svg deleted file mode 100644 index c99281e7..00000000 --- a/Tests/_snapshots/ui/debug_center_tabs.svg +++ /dev/null @@ -1,15 +0,0 @@ - - - overview - - agents - - ai_requests - - toolcalls - - mechanisms - - context - - diff --git a/Tests/_snapshots/ui/debug_overview.html b/Tests/_snapshots/ui/debug_overview.html deleted file mode 100644 index 5bbaf6df..00000000 --- a/Tests/_snapshots/ui/debug_overview.html +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - -
    -
    -
    Health
    -
    Operational
    -
    -
    Agents
    -
    3 / 6
    -
    -
    Queue
    -
    Queue: Running
    -
    -
    Selection
    -
    Nickie
    -
    Pending AI requests: 4
    -
    Agent runtime loop: 3 pawn / 1 scoped
    -
    Last loop tick: 900
    -
    Loop faults: 0
    -
    Quick Actions
    -
    Agents
    -
    AI Requests
    -
    ToolCalls
    -
    Mechanisms
    -
    - - diff --git a/Tests/_snapshots/ui/debug_overview.svg b/Tests/_snapshots/ui/debug_overview.svg deleted file mode 100644 index c4cd87ac..00000000 --- a/Tests/_snapshots/ui/debug_overview.svg +++ /dev/null @@ -1,40 +0,0 @@ - - - - Health - - Operational - - - Agents - - 3 / 6 - - - Queue - - Queue: Running - - - Selection - - Nickie - - Pending AI requests: 4 - - Agent runtime loop: 3 pawn / 1 scoped - - Last loop tick: 900 - - Loop faults: 0 - - Quick Actions - - Agents - - AI Requests - - ToolCalls - - Mechanisms - diff --git a/Tests/_snapshots/ui/requests_mixed_status.html b/Tests/_snapshots/ui/requests_mixed_status.html deleted file mode 100644 index 97c883e1..00000000 --- a/Tests/_snapshots/ui/requests_mixed_status.html +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - -
    -
    -
    Request | Summary
    -
    -
    -
    Request Detail
    -
    -
    req-001
    -
    Queued for cont...
    -
    -
    req-002
    -
    Streaming 3 chu...
    -
    -
    req-003
    -
    Completed ToolC...
    -
    -
    req-004
    -
    HTTP timeout af...
    -
    - - diff --git a/Tests/_snapshots/ui/requests_mixed_status.svg b/Tests/_snapshots/ui/requests_mixed_status.svg deleted file mode 100644 index fc6bd87e..00000000 --- a/Tests/_snapshots/ui/requests_mixed_status.svg +++ /dev/null @@ -1,29 +0,0 @@ - - - - Request | Summary - - - - Request Detail - - - req-001 - - Queued for cont... - - - req-002 - - Streaming 3 chu... - - - req-003 - - Completed ToolC... - - - req-004 - - HTTP timeout af... - diff --git a/Tests/_snapshots/ui/requests_table.html b/Tests/_snapshots/ui/requests_table.html deleted file mode 100644 index e5860598..00000000 --- a/Tests/_snapshots/ui/requests_table.html +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - -
    -
    -
    Status
    -
    -
    -
    - - diff --git a/Tests/_snapshots/ui/requests_table.svg b/Tests/_snapshots/ui/requests_table.svg deleted file mode 100644 index 852dad6e..00000000 --- a/Tests/_snapshots/ui/requests_table.svg +++ /dev/null @@ -1,7 +0,0 @@ - - - - Status - - - diff --git a/Tests/_snapshots/ui/settings_api.html b/Tests/_snapshots/ui/settings_api.html deleted file mode 100644 index a0dc2de1..00000000 --- a/Tests/_snapshots/ui/settings_api.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - -
    -
    api
    -
    queue
    -
    prompts
    -
    context
    -
    -
    API Key
    -
    Saved (35 chars)
    -
    - - diff --git a/Tests/_snapshots/ui/settings_api.svg b/Tests/_snapshots/ui/settings_api.svg deleted file mode 100644 index f219c628..00000000 --- a/Tests/_snapshots/ui/settings_api.svg +++ /dev/null @@ -1,15 +0,0 @@ - - - api - - queue - - prompts - - context - - - API Key - - Saved (35 chars) - diff --git a/Tests/_snapshots/ui/toolcalls_mixed_status.html b/Tests/_snapshots/ui/toolcalls_mixed_status.html deleted file mode 100644 index 2ffea6b1..00000000 --- a/Tests/_snapshots/ui/toolcalls_mixed_status.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - -
    -
    -
    ToolCalls
    -
    Status | Time | Scope | Actor | Channel | Model | Summary | Duration
    -
    -
    -
    Completed | 10:04 | Pawn | Nickie | move_to | mechanism | Moved to stockpile | 180ms
    -
    Streaming | 10:04 | Pawn | Tynan | inspect_need | mechanism | Reading hunger state | 80ms
    -
    Failed | 10:05 | Pawn | Maya | reserve_target | mechanism | Target reservation denied | 220ms
    -
    - - diff --git a/Tests/_snapshots/ui/toolcalls_mixed_status.svg b/Tests/_snapshots/ui/toolcalls_mixed_status.svg deleted file mode 100644 index eee29476..00000000 --- a/Tests/_snapshots/ui/toolcalls_mixed_status.svg +++ /dev/null @@ -1,15 +0,0 @@ - - - - ToolCalls - - Status | Time | Scope | Actor | Channel | Model | Summary | Duration - - - - Completed | 10:04 | Pawn | Nickie | move_to | mechanism | Moved to stockpile | 180ms - - Streaming | 10:04 | Pawn | Tynan | inspect_need | mechanism | Reading hunger state | 80ms - - Failed | 10:05 | Pawn | Maya | reserve_target | mechanism | Target reservation denied | 220ms - diff --git a/script/deploy-single.ps1 b/script/deploy-single.ps1 index a92cde23..76709908 100644 --- a/script/deploy-single.ps1 +++ b/script/deploy-single.ps1 @@ -1,22 +1,22 @@ -# Deploy this RimMind mod to RimWorld Mods folder. +# Deploy this RimMind mod to RimWorld Mods folder (Windows PowerShell). # Place at: RimMind-*/script/deploy-single.ps1 # # Usage: # .\script\deploy-single.ps1 # .\script\deploy-single.ps1 "D:\Games\RimWorld" -# $env:RIMWORLD_PATH="D:\Games\RimWorld"; .\script\deploy-single.ps1 +# $env:RIMWORLD_DIR="D:\Games\RimWorld"; .\script\deploy-single.ps1 param( - [string]$RimWorldDir = "" + [string]$RimWorldDir = "", + [string[]]$GameVersions = @("1.7", "1.6") ) $ErrorActionPreference = "Stop" $ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path -$ModDir = Resolve-Path (Join-Path $ScriptDir "..") +$ModDir = (Resolve-Path (Join-Path $ScriptDir "..")).Path $ModName = Split-Path -Leaf $ModDir -# 自动检测常见 RimWorld 安装路径 function Detect-RimWorldPath { $paths = @( "C:\Program Files (x86)\Steam\steamapps\common\RimWorld", @@ -31,15 +31,16 @@ function Detect-RimWorldPath { return $null } -# 解析 RimWorld 路径 -if ($env:RIMWORLD_PATH) { +if ($RimWorldDir -eq "" -and $env:RIMWORLD_DIR) { + $RimWorldDir = $env:RIMWORLD_DIR +} elseif ($RimWorldDir -eq "" -and $env:RIMWORLD_PATH) { $RimWorldDir = $env:RIMWORLD_PATH } elseif ($RimWorldDir -eq "") { $RimWorldDir = Detect-RimWorldPath if (-not $RimWorldDir) { Write-Error "Cannot find RimWorld installation" Write-Host " Usage: .\script\deploy-single.ps1 [RimWorldPath]" -ForegroundColor Yellow - Write-Host " Or: `$env:RIMWORLD_PATH='D:\Games\RimWorld'; .\script\deploy-single.ps1" -ForegroundColor Yellow + Write-Host " Or: `$env:RIMWORLD_DIR='D:\Games\RimWorld'; .\script\deploy-single.ps1" -ForegroundColor Yellow exit 1 } } @@ -50,92 +51,88 @@ if (-not (Test-Path $RimWorldDir)) { } $RimWorldMods = Join-Path $RimWorldDir "Mods" - -# 确保 Mods 目录存在 if (-not (Test-Path $RimWorldMods)) { Write-Error "Mods directory not found at $RimWorldMods" exit 1 } -# 构建 +# Build for all target game versions (1.7 & 1.6) $SourceDir = Join-Path $ModDir "Source" -if ($ModName -eq "RimMind-Core") { - $domainCsproj = Join-Path $SourceDir "Domain\RimMindCore.Domain.csproj" - $applicationCsproj = Join-Path $SourceDir "Application\RimMindCore.Application.csproj" - $coreCsproj = Get-ChildItem -Path $SourceDir -Filter "RimMindCore.csproj" -File -ErrorAction SilentlyContinue | Select-Object -First 1 +foreach ($gameVersion in $GameVersions) { + Write-Host "=== Building $ModName (RimWorld $gameVersion) ===" -ForegroundColor Cyan - if (-not (Test-Path $domainCsproj)) { - Write-Error "Domain csproj not found: $domainCsproj" - exit 1 - } - if (-not (Test-Path $applicationCsproj)) { - Write-Error "Application csproj not found: $applicationCsproj" - exit 1 - } - if (-not $coreCsproj) { - Write-Error "Core csproj not found in $SourceDir" - exit 1 - } + if ($ModName -eq "RimMind-Core") { + $domainCsproj = Join-Path $SourceDir "Domain\RimMindCore.Domain.csproj" + $applicationCsproj = Join-Path $SourceDir "Application\RimMindCore.Application.csproj" + $coreCsproj = Get-ChildItem -Path $SourceDir -Filter "RimMindCore.csproj" -File -ErrorAction SilentlyContinue | Select-Object -First 1 - Write-Host "=== Building $ModName (Domain) ===" -ForegroundColor Cyan - dotnet build $domainCsproj -c Release --nologo -v quiet - if ($LASTEXITCODE -ne 0) { Write-Error "Domain build failed"; exit $LASTEXITCODE } - Write-Host " Domain build successful" - - Write-Host "=== Building $ModName (Application) ===" -ForegroundColor Cyan - dotnet build $applicationCsproj -c Release --nologo -v quiet - if ($LASTEXITCODE -ne 0) { Write-Error "Application build failed"; exit $LASTEXITCODE } - Write-Host " Application build successful" - - Write-Host "=== Building $ModName (Core) ===" -ForegroundColor Cyan - dotnet build $coreCsproj.FullName -c Release --nologo -v quiet - if ($LASTEXITCODE -ne 0) { Write-Error "Core build failed"; exit $LASTEXITCODE } - Write-Host " Core build successful" -} else { - $CSPROJ = Get-ChildItem -Path $SourceDir -Filter "*.csproj" -File -ErrorAction SilentlyContinue | Select-Object -First 1 - if ($CSPROJ) { - Write-Host "=== Building $ModName ===" -ForegroundColor Cyan - dotnet build $CSPROJ.FullName -c Release --nologo -v quiet - if ($LASTEXITCODE -ne 0) { - Write-Error "Build failed" - exit $LASTEXITCODE + if (-not (Test-Path $domainCsproj)) { + Write-Error "Domain csproj not found: $domainCsproj" + exit 1 + } + if (-not (Test-Path $applicationCsproj)) { + Write-Error "Application csproj not found: $applicationCsproj" + exit 1 + } + if (-not $coreCsproj) { + Write-Error "Core csproj not found in $SourceDir" + exit 1 } - Write-Host " Build successful" + + dotnet build $domainCsproj -c Release -p:GameVersion=$gameVersion -p:SkipDeployToModsFolder=true --nologo -v quiet + if ($LASTEXITCODE -ne 0) { Write-Error "Domain build failed ($gameVersion)"; exit $LASTEXITCODE } + + dotnet build $applicationCsproj -c Release -p:GameVersion=$gameVersion -p:SkipDeployToModsFolder=true --nologo -v quiet + if ($LASTEXITCODE -ne 0) { Write-Error "Application build failed ($gameVersion)"; exit $LASTEXITCODE } + + dotnet build $coreCsproj.FullName -c Release -p:GameVersion=$gameVersion -p:SkipDeployToModsFolder=true --nologo -v quiet + if ($LASTEXITCODE -ne 0) { Write-Error "Core build failed ($gameVersion)"; exit $LASTEXITCODE } } else { - Write-Host "No .csproj found in Source\, skipping build" -ForegroundColor Yellow + $csproj = Get-ChildItem -Path $SourceDir -Filter "*.csproj" -File -ErrorAction SilentlyContinue | Select-Object -First 1 + if ($csproj) { + dotnet build $csproj.FullName -c Release -p:GameVersion=$gameVersion -p:SkipDeployToModsFolder=true --nologo -v quiet + if ($LASTEXITCODE -ne 0) { + Write-Error "Build failed ($gameVersion)" + exit $LASTEXITCODE + } + } else { + Write-Host "No .csproj found in Source\, skipping build" -ForegroundColor Yellow + } } } -# 部署 +# Deploy with clean runtime exclusions (never copy Core/Newtonsoft DLLs into non-Core mods) $DestDir = Join-Path $RimWorldMods $ModName Write-Host "=== Deploying $ModName -> $DestDir ===" -ForegroundColor Cyan -$ExcludeDirs = @('Source', 'Tests', 'obj', '.git', 'script') -$ExcludeFiles = @('*.csproj', '*.user', '.gitignore') -$SourceItems = Get-ChildItem -Path $ModDir | Where-Object { - $item = $_ - if ($item.PSIsContainer -and $ExcludeDirs -contains $item.Name) { return $false } - if (-not $item.PSIsContainer) { - foreach ($pattern in $ExcludeFiles) { - if ($item.Name -like $pattern) { return $false } - } - } - return $true +$excludeFiles = @( + "*.csproj", "*.user", ".gitignore", ".git", ".gitattributes", + ".coderabbit.yaml", ".pre-commit-config.yaml", + "AGENTS.md", "CLAUDE.md", "Directory.Build.props", "Directory.Build.targets", + "INTRODUCTION.txt", "*.deps.json" +) +if ($ModName -ne "RimMind-Core") { + $excludeFiles += @( + "0_RimMindDomain.*", "1_RimMindApplication.*", "2_RimMindCore.*", "Newtonsoft.Json.*" + ) } -if (Test-Path $DestDir) { - Get-ChildItem -Path $DestDir | Remove-Item -Recurse -Force +robocopy $ModDir $DestDir /MIR /XD Source Tests ArchTests IntegrationTests TestSupport obj bin .git .github .claude docs script /XF $excludeFiles /NFL /NDL /NJH /NJS /NP +if ($LASTEXITCODE -ge 8) { + Write-Error "Deployment failed (robocopy exit $LASTEXITCODE)" + exit $LASTEXITCODE } -foreach ($item in $SourceItems) { - Copy-Item -Path $item.FullName -Destination $DestDir -Recurse -Force +if ($ModName -ne "RimMind-Core") { + foreach ($ver in $GameVersions) { + $deployedAssemblies = Join-Path $DestDir "$ver\Assemblies" + if (Test-Path $deployedAssemblies) { + foreach ($pattern in @("0_RimMindDomain.*", "1_RimMindApplication.*", "2_RimMindCore.*", "Newtonsoft.Json.*")) { + Get-ChildItem -Path $deployedAssemblies -Filter $pattern -File -ErrorAction SilentlyContinue | Remove-Item -Force -ErrorAction SilentlyContinue + } + } + } } -# 验证部署 -if (Test-Path $DestDir) { - Write-Host " Done: $DestDir" -ForegroundColor Green -} else { - Write-Error "Deployment verification failed" - exit 1 -} +Write-Host " Done: $DestDir" -ForegroundColor Green diff --git a/script/deploy-single.sh b/script/deploy-single.sh deleted file mode 100644 index 8683913a..00000000 --- a/script/deploy-single.sh +++ /dev/null @@ -1,137 +0,0 @@ -#!/bin/bash -# Deploy this RimMind mod to RimWorld Mods folder. -# Place at: RimMind-*/script/deploy-single.sh -# -# Usage: -# ./script/deploy-single.sh # use default path -# ./script/deploy-single.sh /path/to/RimWorld # custom path -# RIMWORLD_PATH=/path/to/RimWorld ./script/deploy-single.sh # env var override - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -MOD_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" -MOD_NAME="$(basename "$MOD_DIR")" - -# 自动检测常见 RimWorld 安装路径 -detect_rimworld_path() { - local paths=( - "/mnt/c/Program Files (x86)/Steam/steamapps/common/RimWorld" - "/mnt/c/Program Files/Steam/steamapps/common/RimWorld" - "$HOME/.steam/steam/steamapps/common/RimWorld" - "$HOME/.local/share/Steam/steamapps/common/RimWorld" - ) - for path in "${paths[@]}"; do - if [[ -d $path ]]; then - echo "$path" - return 0 - fi - done - return 1 -} - -# 解析 RimWorld 路径 -if [[ -n ${RIMWORLD_PATH:-} ]]; then - RIMWORLD_PATH="$RIMWORLD_PATH" -elif [[ $# -gt 0 ]]; then - RIMWORLD_PATH="$1" -else - RIMWORLD_PATH=$(detect_rimworld_path) || { - echo "Error: Cannot find RimWorld installation" - echo " Usage: $0 [/path/to/RimWorld]" - echo " Or: export RIMWORLD_PATH=/path/to/RimWorld && $0" - exit 1 - } -fi - -RIMWORLD_MODS="$RIMWORLD_PATH/Mods" - -if [[ ! -d $RIMWORLD_PATH ]]; then - echo "Error: RimWorld not found at $RIMWORLD_PATH" - exit 1 -fi - -# 确保 Mods 目录存在 -if [[ ! -d $RIMWORLD_MODS ]]; then - echo "Error: Mods directory not found at $RIMWORLD_MODS" - exit 1 -fi - -# 构建 -SOURCE_DIR="$MOD_DIR/Source" - -if [[ $MOD_NAME == "RimMind-Core" ]]; then - CONTRACTS_CSPROJ="$SOURCE_DIR/Contracts/RimMindCore.Contracts.csproj" - KERNEL_CSPROJ="$SOURCE_DIR/Kernel/RimMindCore.Kernel.csproj" - CORE_CSPROJ=$(find "$SOURCE_DIR" -maxdepth 1 -name "RimMindCore.csproj" 2>/dev/null | head -1) - - if [[ ! -f $CONTRACTS_CSPROJ ]]; then - echo "Error: Contracts csproj not found: $CONTRACTS_CSPROJ" - exit 1 - fi - if [[ ! -f $KERNEL_CSPROJ ]]; then - echo "Error: Kernel csproj not found: $KERNEL_CSPROJ" - exit 1 - fi - if [[ -z $CORE_CSPROJ ]]; then - echo "Error: Core csproj not found in $SOURCE_DIR" - exit 1 - fi - - echo "=== Building $MOD_NAME (Contracts) ===" - if ! dotnet build "$CONTRACTS_CSPROJ" -c Release --nologo -v quiet; then - echo "Error: Contracts build failed" - exit 1 - fi - echo " Contracts build successful" - - echo "=== Building $MOD_NAME (Kernel) ===" - if ! dotnet build "$KERNEL_CSPROJ" -c Release --nologo -v quiet; then - echo "Error: Kernel build failed" - exit 1 - fi - echo " Kernel build successful" - - echo "=== Building $MOD_NAME (Core) ===" - if ! dotnet build "$CORE_CSPROJ" -c Release --nologo -v quiet; then - echo "Error: Core build failed" - exit 1 - fi - echo " Core build successful" -else - CSPROJ=$(find "$SOURCE_DIR" -maxdepth 1 -name "*.csproj" 2>/dev/null | head -1) - if [[ -n $CSPROJ ]]; then - echo "=== Building $MOD_NAME ===" - if ! dotnet build "$CSPROJ" -c Release --nologo -v quiet; then - echo "Error: Build failed" - exit 1 - fi - echo " Build successful" - else - echo "No .csproj found in Source/, skipping build" - fi -fi - -# 部署 -echo "=== Deploying $MOD_NAME -> $RIMWORLD_MODS/$MOD_NAME ===" -if ! rsync -a --delete \ - --exclude='Source/' \ - --exclude='Tests/' \ - --exclude='*.csproj' \ - --exclude='*.user' \ - --exclude='obj/' \ - --exclude='.git/' \ - --exclude='.gitignore' \ - --exclude='script/' \ - "$MOD_DIR/" "$RIMWORLD_MODS/$MOD_NAME/"; then - echo "Error: Deployment failed" - exit 1 -fi - -# 验证部署 -if [[ -d "$RIMWORLD_MODS/$MOD_NAME" ]]; then - echo " Done: $RIMWORLD_MODS/$MOD_NAME" -else - echo "Error: Deployment verification failed" - exit 1 -fi