diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7bc9682..db3d327 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -174,6 +174,9 @@ jobs: --exclude='docs/' \ --exclude='*.csproj' \ --exclude='*.sln' \ + --exclude='.coderabbit.yaml' \ + --exclude='.pre-commit-config.yaml' \ + --exclude='INTRODUCTION.txt' \ --exclude='.gitignore' \ --exclude='.gitattributes' \ --exclude='*.md' \ diff --git a/About/About.xml b/About/About.xml index a8038fb..ebf2ff5 100644 --- a/About/About.xml +++ b/About/About.xml @@ -8,7 +8,64 @@
  • 1.6
  • 1.7
  • - AI-powered pawn advisor. Reads each colonist's state, personality, and available work, then selects the most character-appropriate next action via LLM. [v2.0 BREAKING CHANGES] + [h1]RimMind - Advisor (v2.0)[/h1] +Autonomous colonist advisor, player approval workflow, and 3-round execution feedback engine. Analyzes colonist thoughts, personality traits, and macro colony crises to formulate character-consistent action proposals or execute low-risk tasks autonomously. + +[b]v2.0 Clean Architecture & RimWorld 1.6 / 1.7 Dual-Version Support:[/b] +[list] +[*][b]RimWorld 1.6 & 1.7 (Waylith / .NET 10) Ready[/b]: Native multi-target compilation supporting both RimWorld 1.6 (.NET Framework 4.8) and RimWorld 1.7 (.NET 10 / Harmony 2.x & 3.x). +[*][b]v2.0 5-Domain Autonomy & Cabinet Proposals[/b]: Fine-grained per-domain autonomy policies, multi-colonist Cabinet Meeting crisis proposals, and smooth Mini-Pill HUD auto-collapse. Note: v1.x saves are not compatible with v2.0. +[*][b]3-Round Execution Feedback Loop[/b]: Tracks tool execution outcomes and player approval/rejection history across up to 3 feedback cycles so the AI learns your command preferences. +[/list] + +[h2]What Is RimMind[/h2] +RimMind is an enterprise-grade, AI-powered RimWorld mod suite. Integrated with Large Language Models (LLM), it transforms colonists into self-reflecting agents with distinct personalities, three-tier memories, natural spoken dialogues, autonomous mechanisms, and dynamic storytelling. + +[h2]Sub-mod List & Dependency Relationships[/h2] +[table] +[tr][th]Mod[/th][th]Responsibility[/th][th]Dependencies[/th][th]GitHub[/th][/tr] +[tr][td]RimMind-Core[/td][td]LLM runtime, 4-Zone context engine, async queue, ToolCall registry & F8 Hub[/td][td]Harmony[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Core]Link[/url][/td][/tr] +[tr][td]RimMind-Actions[/td][td]Composite ToolCall mechanisms, battlefield triage & autonomous construction[/td][td]Core[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Actions]Link[/url][/td][/tr] +[tr][td][b]RimMind-Advisor[/b][/td][td]Colonist self-reflective advice cards, 5-domain autonomy & player approval[/td][td]Core, Actions[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Advisor]Link[/url][/td][/tr] +[tr][td]RimMind-Dialogue[/td][td]Contextual spoken dialogue via express_dialogue ToolCall & speech bubbles[/td][td]Core[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Dialogue]Link[/url][/td][/tr] +[tr][td]RimMind-Memory[/td][td]3-Tier cognitive memory hierarchy, work aggregation & temporal decay[/td][td]Core[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Memory]Link[/url][/td][/tr] +[tr][td]RimMind-Personality[/td][td]Big-Five psychological profiles, dawn monologues & dynamic mood thoughts[/td][td]Core[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Personality]Link[/url][/td][/tr] +[tr][td]RimMind-Storyteller[/td][td]AI Story Director, dramatic tension curve, chained arcs & Storyteller Altar[/td][td]Core, Memory[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Storyteller]Link[/url][/td][/tr] +[tr][td]RimMind-Extension-ModelService[/td][td]Multi-provider routing, Anthropic KV cache, local gateways & load balancing[/td][td]Core[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Extension-ModelService]Link[/url][/td][/tr] +[tr][td]RimMind-Bridge-RimChat[/td][td]RimChat compatibility bridge: dialogue/action mutual exclusion & context sync[/td][td]Core, RimChat[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Bridge-RimChat]Link[/url][/td][/tr] +[tr][td]RimMind-Bridge-RimTalk[/td][td]RimTalk compatibility bridge: bubble harmonization & bidirectional context[/td][td]Core, RimTalk[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Bridge-RimTalk]Link[/url][/td][/tr] +[/table] +[code]Core ──┬── Actions ── Advisor + ├── Dialogue + ├── Memory ── Storyteller + ├── Personality + ├── Extension-ModelService + ├── Bridge-RimChat + └── Bridge-RimTalk[/code] + +[h2]Core Features[/h2] +[list] +[*][b]5-Domain Autonomy Governance[/b] - Configure [i]Disabled[/i], [i]RequireApproval[/i], or [i]FullAutonomous[/i] across 5 operational domains: [i]EmergencySurvival, ResourceMarking, WorktableBills, BlueprintPlacement, HighRiskOperations[/i]. +[*][b]Interactive Approval Cards & Mini-Pill Collapse[/b] - Proposals appear in a clean, zoomable floating HUD card with colonist reasoning, urgency badges, and [b][Approve][/b] / [b][Reject][/b] controls, collapsing into an unobtrusive mini-pill when idle. +[*][b]ColonyMacroPerceiver & Cabinet Meetings[/b] - Detects colony-wide food shortages, medical emergencies, defense gaps, and mood crises, convening multi-colonist Cabinet Proposals with executable action plans. +[*][b]Thought-Driven Decision Pipeline[/b] - Receives psychological Thought events from [code]RimMind-Personality[/code] and [code]RimMind-Dialogue[/code] via Core's loose-coupled event bus, turning inner monologues into concrete actions. +[*][b]Pawn Lifecycle Safety[/b] - Automatically cancels pending proposals and cleans up state if a colonist is downed, kidnapped, or killed. +[/list] + +[h2]Advisor Decision Workflow[/h2] +[list] +[*][b]1. State & Thought Perception[/b] - Synthesizes pawn mood, skills, health, nearby work candidates, and macro colony alerts. +[*][b]2. LLM ToolCall Reasoning[/b] - Selects character-appropriate mechanisms from [code]RimMind-Core[/code] and [code]RimMind-Actions[/code]. +[*][b]3. Risk & Policy Resolution[/b] - [code]AdvisorToolRiskResolver[/code] checks domain autonomy rules to either execute immediately or queue for player approval. +[*][b]4. Execution & 3-Round Feedback[/b] - Monitors completion and injects outcome feedback into subsequent advisor cycles. +[/list] + +[h2]Frequently Asked Questions[/h2] +[b]Q: Will the AI perform dangerous actions without my permission?[/b] +A: No. High-risk operations default to [i]RequireApproval[/i], presenting a floating proposal card so you stay in full command. + +[b]Q: Does Advisor work better with Personality and Memory?[/b] +A: Yes! [code]RimMind-Personality[/code] supplies Big-Five psychological traits and inner thoughts, while [code]RimMind-Memory[/code] provides long-term historical context for deeply consistent roleplay decisions.
  • brrainz.harmony diff --git a/Languages/ChineseSimplified/Keyed/RimMind_Advisor.xml b/Languages/ChineseSimplified/Keyed/RimMind_Advisor.xml index 7703a86..52d3529 100644 --- a/Languages/ChineseSimplified/Keyed/RimMind_Advisor.xml +++ b/Languages/ChineseSimplified/Keyed/RimMind_Advisor.xml @@ -37,6 +37,8 @@ 开启后,达到风险等级阈值的动作会被自动拦截,需玩家批准后才执行。 自动拦截风险等级阈值:{0} 达到此风险等级的动作会被自动拦截,需玩家批准后才执行。 + 殖民者独立托管开关 + 取消勾选即可忽略该殖民者,AI 顾问将不会自动为其分配行动。 AI顾问:开启 diff --git a/Languages/English/Keyed/RimMind_Advisor.xml b/Languages/English/Keyed/RimMind_Advisor.xml index d983771..28db90a 100644 --- a/Languages/English/Keyed/RimMind_Advisor.xml +++ b/Languages/English/Keyed/RimMind_Advisor.xml @@ -37,6 +37,8 @@ When enabled, actions at or above the risk threshold are automatically blocked and require player approval. Auto-block risk level threshold: {0} Actions at or above this risk level are automatically blocked and require player approval. + Per-Colonist AI Advisor Control + Uncheck to ignore this colonist so AI Advisor will not automatically assign actions to them. AI Advisor: On diff --git a/Source/Advisor/AdvisorCycleCoordinator.cs b/Source/Advisor/AdvisorCycleCoordinator.cs index 0d4e834..2096cf1 100644 --- a/Source/Advisor/AdvisorCycleCoordinator.cs +++ b/Source/Advisor/AdvisorCycleCoordinator.cs @@ -153,8 +153,11 @@ private void OnAdviceReceived( if (toolCalls == null || toolCalls.Count == 0) { - RimMindErrors.Warn( - $"[RimMind-Advisor] No actionable response for {_pawn.Name.ToStringShort} (no tool_calls, content unparseable)"); + if (!isFeedbackResponse) + { + RimMindErrors.Warn( + $"[RimMind-Advisor] No actionable response for {_pawn.Name.ToStringShort} (no tool_calls, content unparseable)"); + } CompleteRequestCycle(taskDriver, requestCycle); return; } diff --git a/Source/Advisor/AdvisorRecommendationParser.cs b/Source/Advisor/AdvisorRecommendationParser.cs index 0f0f23a..a03a4af 100644 --- a/Source/Advisor/AdvisorRecommendationParser.cs +++ b/Source/Advisor/AdvisorRecommendationParser.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using Newtonsoft.Json; +using Newtonsoft.Json.Linq; using Verse; using ClientStructuredToolCall = RimMind.Domain.Llm.StructuredToolCall; @@ -61,39 +62,40 @@ public bool TryParseNative( try { string trimmed = ExtractJsonObject(nonBlankContent.Trim()); - var parsed = JsonConvert.DeserializeObject>(trimmed); - if (parsed != null && parsed.TryGetValue("advices", out object? advicesToken)) + var token = JToken.Parse(trimmed); + if (token is JArray arrayToken) { - var advices = JsonConvert.DeserializeObject?>>( - JsonConvert.SerializeObject(advicesToken)); - if (advices != null && advices.Count > 0) + var arrayCalls = new List(); + foreach (var item in arrayToken) + { + var call = ParseSingleAdvice(item as JObject, arrayCalls.Count); + if (call != null) + arrayCalls.Add(call); + } + if (arrayCalls.Count > 0) + return arrayCalls; + } + else if (token is JObject root) + { + if (root["advices"] is JArray advicesArray) { var toolCalls = new List(); - foreach (var advice in advices) + foreach (var adviceToken in advicesArray) { - if (advice == null - || !advice.TryGetValue("action", out string? actionName) - || actionName.NullOrEmpty() - || !_toolExists(actionName)) - { - continue; - } - - var args = new Dictionary(); - CopyNonBlank(advice, args, "target"); - CopyNonBlank(advice, args, "param"); - CopyNonBlank(advice, args, "reason"); - toolCalls.Add(new ClientStructuredToolCall - { - Id = $"fallback_{toolCalls.Count}", - Name = actionName, - Arguments = JsonConvert.SerializeObject(args), - }); + var call = ParseSingleAdvice(adviceToken as JObject, toolCalls.Count); + if (call != null) + toolCalls.Add(call); } if (toolCalls.Count > 0) return toolCalls; } + else + { + var singleCall = ParseSingleAdvice(root, 0); + if (singleCall != null) + return new List { singleCall }; + } } } catch (Exception) @@ -104,74 +106,203 @@ public bool TryParseNative( return TryParsePseudoFunctionCall(nonBlankContent); } + private ClientStructuredToolCall? ParseSingleAdvice(JObject? advice, int index) + { + if (advice == null) + return null; + + string? actionName = advice.Value("action") + ?? advice.Value("name") + ?? advice.Value("tool") + ?? (advice["function"] as JObject)?.Value("name"); + + if (actionName.NullOrEmpty() || !_toolExists(actionName!)) + return null; + + var paramsToken = advice["parameters"] + ?? advice["arguments"] + ?? (advice["function"] as JObject)?["arguments"]; + + if (paramsToken is JObject paramsObj) + { + var cloned = (JObject)paramsObj.DeepClone(); + string? topReason = advice.Value("reason"); + if (!string.IsNullOrEmpty(topReason) && cloned["reason"] == null) + cloned["reason"] = topReason; + string? topTarget = advice.Value("target"); + if (!string.IsNullOrEmpty(topTarget) && cloned["target"] == null) + cloned["target"] = topTarget; + return new ClientStructuredToolCall + { + Id = $"fallback_{index}", + Name = actionName!, + Arguments = cloned.ToString(Formatting.None), + }; + } + + if (paramsToken != null && paramsToken.Type == JTokenType.String) + { + string rawParams = paramsToken.ToString(); + if (rawParams.TrimStart().StartsWith("{", StringComparison.Ordinal)) + { + return new ClientStructuredToolCall + { + Id = $"fallback_{index}", + Name = actionName!, + Arguments = rawParams, + }; + } + } + + var args = new Dictionary(); + CopyNonBlank(advice, args, "target"); + CopyNonBlank(advice, args, "param"); + CopyNonBlank(advice, args, "reason"); + foreach (var prop in advice.Properties()) + { + if (args.ContainsKey(prop.Name) || + string.Equals(prop.Name, "action", StringComparison.OrdinalIgnoreCase) || + string.Equals(prop.Name, "name", StringComparison.OrdinalIgnoreCase) || + string.Equals(prop.Name, "tool", StringComparison.OrdinalIgnoreCase) || + string.Equals(prop.Name, "function", StringComparison.OrdinalIgnoreCase) || + string.Equals(prop.Name, "id", StringComparison.OrdinalIgnoreCase) || + string.Equals(prop.Name, "type", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + if (prop.Value != null && prop.Value.Type != JTokenType.Null) + { + string val = prop.Value.Type == JTokenType.String + ? prop.Value.ToString() + : prop.Value.ToString(Formatting.None); + if (!val.NullOrEmpty()) + args[prop.Name] = val; + } + } + + return new ClientStructuredToolCall + { + Id = $"fallback_{index}", + Name = actionName!, + Arguments = JsonConvert.SerializeObject(args), + }; + } + private List? TryParsePseudoFunctionCall(string content) { var match = System.Text.RegularExpressions.Regex.Match( content.Trim(), - @"\b(?[a-z][a-z0-9_]{2,})\s*\((?[\s\S]+?)\)?\s*$", + @"\b(?[a-z][a-z0-9_.]{2,})\s*\((?[\s\S]+?)\)?\s*$", System.Text.RegularExpressions.RegexOptions.Singleline | System.Text.RegularExpressions.RegexOptions.IgnoreCase); if (!match.Success) { match = System.Text.RegularExpressions.Regex.Match( content, - @"(?[a-z][a-z0-9_]{2,})\s*\((?[^)]*)\)", + @"(?[a-z][a-z0-9_.]{2,})\s*\((?[^)]*)\)", System.Text.RegularExpressions.RegexOptions.Singleline | System.Text.RegularExpressions.RegexOptions.IgnoreCase); } - if (!match.Success) - return null; - - string toolName = match.Groups["tool"].Value.Trim(); - if (!_toolExists(toolName)) - return null; - - string argsBody = match.Groups["args"].Value; - var argsDict = new Dictionary(); - var kvMatches = System.Text.RegularExpressions.Regex.Matches( - argsBody, - @"(?[a-zA-Z_][a-zA-Z0-9_]*)\)?\s*[:=]\s*(?:""(?(?:\\.|[^""])*)""|'(?(?:\\.|[^'])*)'|\((?[^)]*)\)|(?[^,)]+))"); - foreach (System.Text.RegularExpressions.Match kv in kvMatches) + if (match.Success) { - string key = kv.Groups["key"].Value.Trim(); - string val = kv.Groups["dq"].Success - ? kv.Groups["dq"].Value - : kv.Groups["sq"].Success - ? kv.Groups["sq"].Value - : kv.Groups["pq"].Success - ? kv.Groups["pq"].Value.Trim() - : kv.Groups["raw"].Value.Trim(); - argsDict[key] = val; + string toolName = match.Groups["tool"].Value.Trim(); + if (_toolExists(toolName)) + { + string argsBody = match.Groups["args"].Value; + var argsDict = new Dictionary(); + var kvMatches = System.Text.RegularExpressions.Regex.Matches( + argsBody, + @"(?[a-zA-Z_][a-zA-Z0-9_]*)\)?\s*[:=]\s*(?:""(?(?:\\.|[^""])*)""|'(?(?:\\.|[^'])*)'|\((?[^)]*)\)|(?[^,)]+))"); + foreach (System.Text.RegularExpressions.Match kv in kvMatches) + { + string key = kv.Groups["key"].Value.Trim(); + string val = kv.Groups["dq"].Success + ? kv.Groups["dq"].Value + : kv.Groups["sq"].Success + ? kv.Groups["sq"].Value + : kv.Groups["pq"].Success + ? kv.Groups["pq"].Value.Trim() + : kv.Groups["raw"].Value.Trim(); + argsDict[key] = val; + } + + return new List + { + new ClientStructuredToolCall + { + Id = "fallback_pseudo_0", + Name = toolName, + Arguments = JsonConvert.SerializeObject(argsDict), + } + }; + } } - return new List + var toMatch = System.Text.RegularExpressions.Regex.Match( + content, + @"\bto=(?:functions\.|tools\.)?(?[a-z][a-z0-9_.]{2,})", + System.Text.RegularExpressions.RegexOptions.IgnoreCase); + if (toMatch.Success) { - new ClientStructuredToolCall + string toolName = toMatch.Groups["tool"].Value.Trim(); + if (_toolExists(toolName)) { - Id = "fallback_pseudo_0", - Name = toolName, - Arguments = JsonConvert.SerializeObject(argsDict), + string afterMatch = content.Substring(toMatch.Index + toMatch.Length).Trim(); + string argsJson = "{}"; + int braceStart = afterMatch.IndexOf('{'); + int braceEnd = afterMatch.LastIndexOf('}'); + if (braceStart >= 0 && braceEnd > braceStart) + { + argsJson = afterMatch.Substring(braceStart, braceEnd - braceStart + 1); + } + return new List + { + new ClientStructuredToolCall + { + Id = "fallback_pseudo_0", + Name = toolName, + Arguments = argsJson, + } + }; } - }; + } + + return null; } private static string ExtractJsonObject(string content) { - if (!content.StartsWith("```", StringComparison.Ordinal)) - return content; + if (content.StartsWith("```", StringComparison.Ordinal)) + { + int firstNewline = content.IndexOf('\n'); + string stripped = firstNewline >= 0 ? content.Substring(firstNewline + 1) : content.TrimStart('`'); + if (stripped.EndsWith("```", StringComparison.Ordinal)) + stripped = stripped.Substring(0, stripped.Length - 3); + content = stripped.Trim(); + } int firstBrace = content.IndexOf('{'); int lastBrace = content.LastIndexOf('}'); + int firstBracket = content.IndexOf('['); + int lastBracket = content.LastIndexOf(']'); + + if (firstBracket >= 0 && (firstBrace < 0 || firstBracket < firstBrace) && lastBracket > firstBracket) + { + return content.Substring(firstBracket, lastBracket - firstBracket + 1); + } + return firstBrace >= 0 && lastBrace > firstBrace ? content.Substring(firstBrace, lastBrace - firstBrace + 1) : content; } private static void CopyNonBlank( - IReadOnlyDictionary source, + JObject source, IDictionary destination, string key) { - if (source.TryGetValue(key, out string? value) && !value.NullOrEmpty()) - destination[key] = value; + string? value = source.Value(key); + if (!value.NullOrEmpty()) + destination[key] = value!; } } } diff --git a/Source/Advisor/AdvisorToolCallExecutor.cs b/Source/Advisor/AdvisorToolCallExecutor.cs index 99c780d..a745d55 100644 --- a/Source/Advisor/AdvisorToolCallExecutor.cs +++ b/Source/Advisor/AdvisorToolCallExecutor.cs @@ -5,6 +5,7 @@ using RimMind.Application.Common.Interfaces.Tools; using RimMind.Application.Common.Models.Tools; using RimMind.Application.Common.Threading; +using RimMind.Application.Features.Tools; using RimMind.Domain.Llm; using RimMind.Presentation.Api; @@ -36,6 +37,7 @@ public async Task> ExecuteAsync( bool playerApproved = false) { var results = new List(calls.Count); + PawnIdParser.TryParse(npcId, out var callerPawnId); foreach (var call in calls) { @@ -51,6 +53,7 @@ public async Task> ExecuteAsync( ToolCallId = call.Id, ToolName = call.Name, ArgumentsJson = string.IsNullOrEmpty(call.Arguments) ? "{}" : call.Arguments, + PawnId = callerPawnId > 0 ? callerPawnId : (int?)null, NpcId = npcId, TraceId = traceId, Ct = ct, diff --git a/Source/Advisor/AdvisorToolRiskResolver.cs b/Source/Advisor/AdvisorToolRiskResolver.cs index 20b4b27..4005a25 100644 --- a/Source/Advisor/AdvisorToolRiskResolver.cs +++ b/Source/Advisor/AdvisorToolRiskResolver.cs @@ -276,6 +276,7 @@ private static RiskLevel MapAutonomyDomainRisk(AutonomyDomain domain) => AutonomyDomain.ResourceMarking => RiskLevel.Low, AutonomyDomain.WorktableBills => RiskLevel.Medium, AutonomyDomain.BlueprintPlacement => RiskLevel.Medium, + AutonomyDomain.WorkPriorityModification => RiskLevel.Medium, AutonomyDomain.HighRiskOperations => RiskLevel.High, _ => RiskLevel.Low }; diff --git a/Source/Comps/CompAIAdvisor.cs b/Source/Comps/CompAIAdvisor.cs index 5003f8c..ed8d213 100644 --- a/Source/Comps/CompAIAdvisor.cs +++ b/Source/Comps/CompAIAdvisor.cs @@ -14,7 +14,8 @@ public class CompAIAdvisor : ThingComp private int _lastRequestTick = -9999; private AdvisorCycleCoordinator? _cycle; - private Pawn Pawn => (Pawn)parent; + private Pawn? PawnOrNull => parent as Pawn; + private Pawn? Pawn => parent as Pawn; private RimMindAdvisorSettings Settings => RimMindAdvisorMod.Settings; private AdvisorCycleCoordinator Cycle { @@ -34,25 +35,29 @@ private AdvisorCycleCoordinator Cycle public bool HasPendingRequest => _cycle != null && _cycle.HasPendingRequest; public int LastRequestTick => _cycle != null ? (_lastRequestTick = _cycle.LastRequestTick) : _lastRequestTick; public AdvisorTaskDriver? TaskDriver => _cycle?.TaskDriver; - public int AdvisorCooldownTicksLeft => _cycle != null - ? _cycle.CooldownTicksLeft - : AdvisorCooldownCalculator.CooldownTicksLeft( - AdvisorCooldownCalculator.CalculateCooldownForPawn(Pawn, Settings), - Find.TickManager?.TicksGame ?? 0, - _lastRequestTick); + public int AdvisorCooldownTicksLeft => PawnOrNull == null + ? 0 + : (_cycle != null + ? _cycle.CooldownTicksLeft + : AdvisorCooldownCalculator.CooldownTicksLeft( + AdvisorCooldownCalculator.CalculateCooldownForPawn(PawnOrNull, Settings), + Find.TickManager?.TicksGame ?? 0, + _lastRequestTick)); public bool CanRequestAdvice() => - IsEnabled && !HasPendingRequest && IsEligible() && AdvisorCooldownTicksLeft <= 0; + PawnOrNull != null && IsEnabled && !HasPendingRequest && IsEligible() && AdvisorCooldownTicksLeft <= 0; public bool IsEligible() => - Pawn.IsFreeNonSlaveColonist && - !Pawn.Dead && - !(Pawn.drafter?.Drafted ?? false) && - Pawn.needs?.mood != null; + PawnOrNull is Pawn pawn && + pawn.IsFreeNonSlaveColonist && + !pawn.Dead && + !(pawn.drafter?.Drafted ?? false) && + pawn.needs?.mood != null; public bool IsIdle() { - var job = Pawn.jobs?.curJob; + if (PawnOrNull is not Pawn pawn) return false; + var job = pawn.jobs?.curJob; if (job == null) return true; if (job.playerForced) return false; @@ -65,7 +70,8 @@ public bool IsIdle() public bool IsMoodBelowThreshold() { - var mood = Pawn.needs?.mood; + if (PawnOrNull is not Pawn pawn) return false; + var mood = pawn.needs?.mood; return mood != null && mood.CurLevelPercentage < Settings.moodThreshold; } @@ -73,16 +79,23 @@ public bool IsMoodBelowThreshold() public bool ShouldMoodTrigger() => Settings.enableMoodTrigger && IsMoodBelowThreshold(); - public void RequestAdvice(RimMindAdvisorSettings settings) => Cycle.RequestAdvice(settings); + public void RequestAdvice(RimMindAdvisorSettings settings) + { + if (PawnOrNull == null) return; + Cycle.RequestAdvice(settings); + } public void ForceRequestAdvice() { + if (PawnOrNull == null) return; IsEnabled = true; Cycle.ForceRequestAdvice(); } public override IEnumerable CompGetGizmosExtra() { + if (PawnOrNull == null) yield break; + var label = IsEnabled ? "RimMind.Advisor.UI.Gizmo.Enabled".Translate() : "RimMind.Advisor.UI.Gizmo.Disabled".Translate(); @@ -125,13 +138,19 @@ public override IEnumerable CompGetGizmosExtra() public override void PostDeSpawn(Map map, DestroyMode mode = DestroyMode.Vanish) { - ApprovalManager.CancelPendingForPawn(Pawn); + if (Pawn != null) + { + ApprovalManager.CancelPendingForPawn(Pawn); + } base.PostDeSpawn(map, mode); } public override void PostDestroy(DestroyMode mode, Map previousMap) { - ApprovalManager.CancelPendingForPawn(Pawn); + if (Pawn != null) + { + ApprovalManager.CancelPendingForPawn(Pawn); + } base.PostDestroy(mode, previousMap); } @@ -144,11 +163,11 @@ public override void PostExposeData() _lastRequestTick = _cycle.LastRequestTick; } Scribe_Values.Look(ref _lastRequestTick, "aiAdvisorLastRequestTick", -9999); - if (Scribe.mode == LoadSaveMode.LoadingVars) + if (Scribe.mode == LoadSaveMode.LoadingVars && parent is Pawn pawn) { if (_lastRequestTick <= 0 && Find.TickManager != null) { - int stagger = (Pawn.thingIDNumber & 0x7FFF) % 1500; + int stagger = (pawn.thingIDNumber & 0x7FFF) % 1500; _lastRequestTick = Find.TickManager.TicksGame - (Settings.requestCooldownTicks - stagger); } if (_cycle != null) diff --git a/Source/Patches/AddCompToHumanlikePatch.cs b/Source/Patches/AddCompToHumanlikePatch.cs index a63a830..64b3b21 100644 --- a/Source/Patches/AddCompToHumanlikePatch.cs +++ b/Source/Patches/AddCompToHumanlikePatch.cs @@ -8,12 +8,8 @@ namespace RimMind.Advisor.Patches { /// - /// 在所æœ?ThingDef 解析完继承关系之后, - /// 动态为所有人形智能小人(å�?AlienRaces 外星种族)注å…?CompProperties_AIAdvisorã€? - /// - /// 使用 C# Harmony Postfix 而非 XML PatchOperationï¼? - /// 原因å�?RimMind-Personality:XML Patch 在继承解析前运行ï¼? - /// race/intelligence 字段尚未继承,XPath 过滤匹配 0 个节点ã€? + /// Dynamically injects CompProperties_AIAdvisor into all humanlike Pawn ThingDefs + /// after ThingDef.ResolveReferences completes (excluding Corpse ThingDefs). /// [HarmonyPatch(typeof(ThingDef), nameof(ThingDef.ResolveReferences))] public static class AddAdvisorCompPatch @@ -21,6 +17,8 @@ public static class AddAdvisorCompPatch [HarmonyPostfix] public static void Postfix(ThingDef __instance) { + if (__instance == null || __instance.IsCorpse) return; + if (__instance.thingClass == null || !typeof(Pawn).IsAssignableFrom(__instance.thingClass)) return; if (__instance.race?.intelligence != Intelligence.Humanlike) return; __instance.comps ??= new List(); diff --git a/Source/Perception/ColonyMacroPerceiver.cs b/Source/Perception/ColonyMacroPerceiver.cs index f2948e0..d19e6b4 100644 --- a/Source/Perception/ColonyMacroPerceiver.cs +++ b/Source/Perception/ColonyMacroPerceiver.cs @@ -26,6 +26,8 @@ public class ColonyMacroSnapshot public int FreeColonistBedCount { get; set; } public int HostileThreatCount { get; set; } public int UnbuiltBlueprintsCount { get; set; } + public int GrowingZoneCellsCount { get; set; } = -1; + public List ActiveColonistRoster { get; set; } = new List(); } public class ColonyMacroState @@ -38,6 +40,7 @@ public class ColonyMacroState public int SteelCount { get; set; } public int MedicineCount { get; set; } public float OutdoorTemperature { get; set; } + public List ActiveColonistRoster { get; set; } = new List(); public bool IsFoodCritical { get; set; } public bool IsExtremeCold { get; set; } @@ -66,7 +69,10 @@ public static ColonyMacroState Evaluate(ColonyMacroSnapshot snapshot) WoodCount = snapshot.WoodCount, SteelCount = snapshot.SteelCount, MedicineCount = snapshot.MedicineCount, - OutdoorTemperature = snapshot.OutdoorTemperature + OutdoorTemperature = snapshot.OutdoorTemperature, + ActiveColonistRoster = snapshot.ActiveColonistRoster != null + ? new List(snapshot.ActiveColonistRoster) + : new List() }; float dailyConsumption = Math.Max(1, snapshot.ColonistCount) * 1.6f; @@ -92,6 +98,10 @@ public static ColonyMacroState Evaluate(ColonyMacroSnapshot snapshot) { state.CriticalBottlenecks.Add($"[Food Crisis] Colony only has {state.FoodDaysRemaining:F1} days of food remaining! (Nutrition: {snapshot.TotalFoodNutrition:F1})"); } + if (snapshot.GrowingZoneCellsCount >= 0 && snapshot.GrowingZoneCellsCount < 15 && snapshot.ColonistCount > 0) + { + state.CriticalBottlenecks.Add("[No Agriculture] Colony has 0 Growing Zones! Crops take 6 days to mature; call actions_manage_zone (zone_type='Growing', crop_def='Plant_Rice', width=6, height=6) IMMEDIATELY so crops mature before starting rations run out!"); + } if (state.IsExtremeCold) { state.CriticalBottlenecks.Add($"[Extreme Cold] Outdoor temp is {snapshot.OutdoorTemperature:F1}°C! Risk of severe hypothermia."); @@ -127,6 +137,10 @@ public static string FormatPromptAugmentation(ColonyMacroState state) var sb = new StringBuilder(); sb.AppendLine("=== COLONY MACRO STATUS & SURVIVAL PRIORITIES ==="); sb.AppendLine($"- Colonists: {state.ColonistCount} active (Downed: {state.DownedColonistCount})"); + if (state.ActiveColonistRoster != null && state.ActiveColonistRoster.Count > 0) + { + sb.AppendLine($"- Active Colonist Roster: {string.Join(", ", state.ActiveColonistRoster)}"); + } sb.AppendLine($"- Food Supply: {state.TotalFoodNutrition:F1} nutrition (~{state.FoodDaysRemaining:F1} days remaining)"); sb.AppendLine($"- Outdoor Temperature: {state.OutdoorTemperature:F1}°C"); sb.AppendLine($"- Resources: Wood {state.WoodCount}, Steel {state.SteelCount}, Medicine {state.MedicineCount}"); @@ -166,6 +180,9 @@ public static ColonyMacroSnapshot CaptureSnapshot(Map map) .ToList(); snapshot.ColonistCount = colonists.Count; snapshot.DownedColonistCount = colonists.Count(p => p.Downed); + snapshot.ActiveColonistRoster = colonists + .Select(c => $"{c.Name?.ToStringShort ?? c.LabelShort} (pawn_id: {c.thingIDNumber})") + .ToList(); float nutrition = 0f; var foodThings = map.listerThings?.ThingsInGroup(ThingRequestGroup.FoodSourceNotPlantOrTree); @@ -173,7 +190,12 @@ public static ColonyMacroSnapshot CaptureSnapshot(Map map) { foreach (var thing in foodThings) { - if (thing != null && thing.Spawned && !thing.Position.Fogged(map)) + if (thing != null && thing.Spawned && !thing.Position.Fogged(map) + && !(thing is Corpse) && !(thing is Pawn) + && thing.def?.ingestible != null && thing.def.IsNutritionGivingIngestible && thing.def.ingestible.HumanEdible + && thing.def.ingestible.drugCategory == DrugCategory.None + && thing.def.ingestible.preferability >= FoodPreferability.RawBad + && !thing.IsForbidden(Faction.OfPlayer)) { float perItem = thing.GetStatValue(StatDefOf.Nutrition); nutrition += perItem * thing.stackCount; @@ -182,13 +204,10 @@ public static ColonyMacroSnapshot CaptureSnapshot(Map map) } snapshot.TotalFoodNutrition = nutrition; - if (map.resourceCounter != null) - { - snapshot.WoodCount = map.resourceCounter.GetCount(ThingDefOf.WoodLog); - snapshot.SteelCount = map.resourceCounter.GetCount(ThingDefOf.Steel); - snapshot.MedicineCount = map.resourceCounter.GetCount(ThingDefOf.MedicineIndustrial) - + map.resourceCounter.GetCount(ThingDefOf.MedicineHerbal); - } + snapshot.WoodCount = CountAvailableResource(map, ThingDefOf.WoodLog); + snapshot.SteelCount = CountAvailableResource(map, ThingDefOf.Steel); + snapshot.MedicineCount = CountAvailableResource(map, ThingDefOf.MedicineIndustrial) + + CountAvailableResource(map, ThingDefOf.MedicineHerbal); snapshot.OutdoorTemperature = map.mapTemperature?.OutdoorTemp ?? 21f; @@ -237,6 +256,10 @@ public static ColonyMacroSnapshot CaptureSnapshot(Map map) { snapshot.UnbuiltBlueprintsCount = blueprints.Count(b => b != null && b.Faction == Faction.OfPlayer); } + + snapshot.GrowingZoneCellsCount = map.zoneManager?.AllZones + ?.OfType() + .Sum(z => z.cells?.Count ?? 0) ?? 0; } catch (Exception ex) { @@ -245,6 +268,27 @@ public static ColonyMacroSnapshot CaptureSnapshot(Map map) return snapshot; } + + private static int CountAvailableResource(Map map, ThingDef? def) + { + if (map == null || def == null) return 0; + int counted = map.resourceCounter?.GetCount(def) ?? 0; + var list = map.listerThings?.ThingsOfDef(def); + if (list != null && list.Count > 0) + { + int unforbidden = 0; + for (int i = 0; i < list.Count; i++) + { + var t = list[i]; + if (t != null && t.Spawned && !t.Destroyed && !t.Position.Fogged(map) && !t.IsForbidden(Faction.OfPlayer)) + { + unforbidden += t.stackCount; + } + } + if (unforbidden > counted) counted = unforbidden; + } + return counted; + } #endif } } diff --git a/Source/Settings/AdvisorSettingsDrawer.cs b/Source/Settings/AdvisorSettingsDrawer.cs index d20bc6e..e06c4b7 100644 --- a/Source/Settings/AdvisorSettingsDrawer.cs +++ b/Source/Settings/AdvisorSettingsDrawer.cs @@ -1,4 +1,6 @@ +using RimMind.Advisor.Comps; using RimMind.Domain.Enums; +using RimMind.Presentation.Api; using RimMind.Presentation.UI; using UnityEngine; using Verse; @@ -99,6 +101,26 @@ internal static void Draw(Rect inRect) RimMindAdvisorMod.Settings.autoBlockRiskLevel = (RiskLevel)riskVal; } + if (Current.ProgramState == ProgramState.Playing && Find.CurrentMap != null) + { + var colonists = RimMindPawnLookup.GetSpawnedColonistsSafe(Find.CurrentMap); + if (colonists.Count > 0) + { + SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Advisor.Settings.Section.ColonistFilter".Translate()); + string colonistTip = "RimMind.Advisor.Settings.ColonistFilter.Tip".Translate(); + for (int i = 0; i < colonists.Count; i++) + { + Pawn p = colonists[i]; + if (!RimMindPawnLookup.IsActiveSpawnedColonist(p)) continue; + var comp = p.TryGetComp(); + if (comp == null) continue; + bool enabled = comp.IsEnabled; + listing.CheckboxLabeled(" " + p.LabelShortCap, ref enabled, colonistTip); + comp.IsEnabled = enabled; + } + } + } + listing.End(); Widgets.EndScrollView(); @@ -145,6 +167,12 @@ private static float EstimateHeight() h += 24f; if (RimMindAdvisorMod.Settings.enableRiskApproval) h += 24f + 32f; + if (Current.ProgramState == ProgramState.Playing && Find.CurrentMap != null) + { + int colonistCount = RimMindPawnLookup.GetSpawnedColonistsSafe(Find.CurrentMap).Count; + if (colonistCount > 0) + h += 32f + colonistCount * 26f; + } return h + 40f; } } diff --git a/Tests/Contracts/AdvisorLifecycleContracts.cs b/Tests/Contracts/AdvisorLifecycleContracts.cs index f719b98..e69991c 100644 --- a/Tests/Contracts/AdvisorLifecycleContracts.cs +++ b/Tests/Contracts/AdvisorLifecycleContracts.cs @@ -88,6 +88,7 @@ public void Request_cycle_aggregates_feedback_and_reaches_one_terminal_state() Assert.Contains("OnAdviceReceived", coordinator, StringComparison.Ordinal); Assert.Contains("SubmitToolCallForApproval", coordinator, StringComparison.Ordinal); Assert.Contains("TryAdvanceRequestCycle", coordinator, StringComparison.Ordinal); + Assert.Contains("if (!isFeedbackResponse)", coordinator, StringComparison.Ordinal); })); } diff --git a/Tests/Contracts/AdvisorRecommendationContracts.cs b/Tests/Contracts/AdvisorRecommendationContracts.cs index 5436b12..ac72e46 100644 --- a/Tests/Contracts/AdvisorRecommendationContracts.cs +++ b/Tests/Contracts/AdvisorRecommendationContracts.cs @@ -61,6 +61,24 @@ public void Recommendation_payload_boundaries_are_explicit_and_safe() Assert.Equal("known.tool", call.Name); Assert.Contains("\"target\":\"pawn\"", call.Arguments, StringComparison.Ordinal); }), + ("fallback accepts single tool JSON objects, arrays, and to= commentary", () => + { + var singleObj = parser.ParseLegacy( + "{\"name\":\"known.tool\",\"parameters\":{\"target\":\"pawn\",\"reason\":\"help\"}}"); + var singleCall = Assert.Single(singleObj!); + Assert.Equal("known.tool", singleCall.Name); + Assert.Contains("\"target\":\"pawn\"", singleCall.Arguments, StringComparison.Ordinal); + + var arrayObj = parser.ParseLegacy( + "[{\"tool\":\"known.tool\",\"arguments\":{\"reason\":\"batch\"}}]"); + var arrayCall = Assert.Single(arrayObj!); + Assert.Equal("known.tool", arrayCall.Name); + + var commentary = parser.ParseLegacy( + "Executing tool to=known.tool {\"target\":\"pawn\"}"); + var commentaryCall = Assert.Single(commentary!); + Assert.Equal("known.tool", commentaryCall.Name); + }), ("empty recommendations produce no executable calls", () => { Assert.Null(parser.ParseLegacy("{\"advices\":[]}")); diff --git a/Tests/Contracts/ColonyMacroPerceiverTests.cs b/Tests/Contracts/ColonyMacroPerceiverTests.cs index 09974b3..7465403 100644 --- a/Tests/Contracts/ColonyMacroPerceiverTests.cs +++ b/Tests/Contracts/ColonyMacroPerceiverTests.cs @@ -211,13 +211,15 @@ public void FormatPromptAugmentation_FormatsCorrectSummaryAndBottlenecks() WoodCount = 40, SteelCount = 30, OutdoorTemperature = -18f, - FreeColonistBedCount = 2 + FreeColonistBedCount = 2, + ActiveColonistRoster = new List { "Alice (pawn_id: 294)", "Bob (pawn_id: 301)" } }; var state = ColonyMacroPerceiver.Evaluate(snapshot); var text = ColonyMacroPerceiver.FormatPromptAugmentation(state); Assert.Contains("=== COLONY MACRO STATUS & SURVIVAL PRIORITIES ===", text); + Assert.Contains("- Active Colonist Roster: Alice (pawn_id: 294), Bob (pawn_id: 301)", text); Assert.Contains("CRITICAL SURVIVAL BOTTLENECKS", text); Assert.Contains("[Food Crisis]", text); Assert.Contains("[Extreme Cold]", text);