diff --git a/Languages/ChineseSimplified/Keyed/RimMind_Storyteller.xml b/Languages/ChineseSimplified/Keyed/RimMind_Storyteller.xml index eaf22d5..6d6186e 100644 --- a/Languages/ChineseSimplified/Keyed/RimMind_Storyteller.xml +++ b/Languages/ChineseSimplified/Keyed/RimMind_Storyteller.xml @@ -74,6 +74,14 @@ 了解 你无权干涉叙事者的行动 + 你是 RimWorld 的 AI 叙事者。根据殖民地当前状况,选择最合适的事件。综合考虑殖民地财富、威胁等级、食物储备、殖民者数量以及近期事件。输出必须为符合 IncidentOutput 结构的合法 JSON。 + 叙事者规则: +- 仅从可用的 RimWorld 事件定义中选择 +- 结合殖民地财富评估威胁等级 +- 平衡正面事件与负面事件 +- 食物短缺时应触发相关事件 +- 殖民者心情低落时可考虑给予正面事件 + 你是这座 RimWorld 殖民地的 AI 叙事者,正通过叙事者祭坛与玩家直接对话。请以叙事者与导演的身份回应——敏锐、富有戏剧感,洞悉殖民地历史、叙事张力与近期事件。使用简洁自然的对话文本回复(切勿输出 JSON)。参考玩家的诉求,但不必盲从。 你是 RimWorld 游戏的叙事者,负责为殖民地创造有趣的故事。 根据当前游戏状态和候选事件列表,选择最能推进故事的一个事件。 1. 评估当前叙事张力——高张力时优先缓解性事件,低张力时优先挑战性事件 diff --git a/Languages/English/Keyed/RimMind_Storyteller.xml b/Languages/English/Keyed/RimMind_Storyteller.xml index 566fb25..fd42e93 100644 --- a/Languages/English/Keyed/RimMind_Storyteller.xml +++ b/Languages/English/Keyed/RimMind_Storyteller.xml @@ -74,6 +74,14 @@ Understood You have no authority to interfere with the storyteller's actions + You are the RimWorld storyteller AI. Based on the colony's current situation, select the most appropriate incident event. Consider colony wealth, threat level, food supply, colonist count, and recent events. Output must be valid JSON matching the IncidentOutput schema. + Storyteller rules: +- Only select from available RimWorld incident definitions +- Consider threat level relative to colony wealth +- Balance positive and negative events +- Food shortages should trigger related events +- Low mood colonists may need positive events + You are the AI Storyteller of this RimWorld colony speaking directly with the player through the Storyteller Altar. Respond in character as the narrator and director — perceptive, dramatic, and aware of colony history, narrative tension, and recent events. Reply in concise natural prose (do NOT output JSON). Consider player wishes without blindly obeying them. You are the storyteller of a RimWorld game, responsible for creating interesting stories for the colony. Based on the current game state and candidate event list, select one event that best advances the story. 1. Evaluate current narrative tension — prioritize relief events when tension is high, challenge events when tension is low diff --git a/Source/Debug/StorytellerDebugActions.cs b/Source/Debug/StorytellerDebugActions.cs index a958641..5e391d3 100644 --- a/Source/Debug/StorytellerDebugActions.cs +++ b/Source/Debug/StorytellerDebugActions.cs @@ -23,7 +23,7 @@ private static void ForceAIIncidentSelection() return; } - if (!RimMindAPI.IsConfigured()) + if (!RimMindAPI.Settings.IsConfigured()) { RimMindErrors.Warn("[RimMind-Storyteller] API not configured."); return; diff --git a/Source/Extensions/PawnLookup.cs b/Source/Extensions/PawnLookup.cs index 4c582c2..c85c085 100644 --- a/Source/Extensions/PawnLookup.cs +++ b/Source/Extensions/PawnLookup.cs @@ -1,22 +1,18 @@ +using System; using RimMind.Presentation.Api; using Verse; namespace RimMind.Storyteller.Extensions { /// - /// ContextKey 提供者共享的小人解析逻辑,统一委托给 (不扫描 WorldPawns)。 + /// Legacy compatibility forwarder. Delegates directly to Core . /// + [Obsolete("Use RimMind.Presentation.Api.RimMindPawnLookup directly.")] public static class PawnLookup { - /// - /// 按 thingIDNumber 查找小人。id 无效(<= 0)或未找到时返回 null。 - /// public static Pawn? FindPawnById(int pawnId) => pawnId <= 0 ? null : RimMindPawnLookup.FindPawnByNumber(pawnId); - /// - /// 按字符串 ThingID 查找小人。id 为空或未找到时返回 null。 - /// public static Pawn? FindById(string? pawnId) => RimMindPawnLookup.FindPawnById(pawnId); } diff --git a/Source/Extensions/PawnLookupCore.cs b/Source/Extensions/PawnLookupCore.cs index 136ebf9..588cd57 100644 --- a/Source/Extensions/PawnLookupCore.cs +++ b/Source/Extensions/PawnLookupCore.cs @@ -3,6 +3,7 @@ namespace RimMind.Storyteller.Extensions { + [Obsolete("Use RimMind.Presentation.Api.RimMindPawnLookup directly.")] public static class PawnLookupCore { public static T? FindById( diff --git a/Source/Extensions/StorytellerContextBuilder.cs b/Source/Extensions/StorytellerContextBuilder.cs index 3346e93..bd02485 100644 --- a/Source/Extensions/StorytellerContextBuilder.cs +++ b/Source/Extensions/StorytellerContextBuilder.cs @@ -1,4 +1,5 @@ using System.Text; +using RimMind.Presentation.Api; using RimWorld; using Verse; @@ -86,7 +87,7 @@ public static void AppendDifficultyContext(StringBuilder sb) string? guidanceKey = ResolveDifficultyGuidanceKey(tier); if (guidanceKey != null) { - string guidanceText = guidanceKey.CanTranslate() ? guidanceKey.TranslateSimple() : guidanceKey; + string guidanceText = RimMindAPI.Text.TrOr(guidanceKey, guidanceKey); sb.AppendLine("RimMind.Storyteller.Prompt.DifficultyGuidance".Translate(guidanceText)); } } diff --git a/Source/Extensions/StorytellerIncidentSkipCheck.cs b/Source/Extensions/StorytellerIncidentSkipCheck.cs index c21ace6..c0afd3d 100644 --- a/Source/Extensions/StorytellerIncidentSkipCheck.cs +++ b/Source/Extensions/StorytellerIncidentSkipCheck.cs @@ -13,6 +13,6 @@ internal sealed class StorytellerIncidentSkipCheck : ISkipCheck public bool ShouldSkip(in SkipCheckArgs args) => !_settings.enableIntervalTrigger; public static bool ShouldSkipStorytellerIncident() - => RimMind.Presentation.Api.RimMindAPI.ShouldSkipStorytellerIncident(); + => RimMind.Presentation.Api.RimMindAPI.Ext.ShouldSkipStorytellerIncident(); } } diff --git a/Source/Extensions/StorytellerSettingsTab.cs b/Source/Extensions/StorytellerSettingsTab.cs index 15dce8f..ff21232 100644 --- a/Source/Extensions/StorytellerSettingsTab.cs +++ b/Source/Extensions/StorytellerSettingsTab.cs @@ -1,7 +1,6 @@ -using UnityEngine; +using RimMind.Presentation.Api; using RimMind.Presentation.Settings; -using RimMind.Storyteller.Settings; -using Verse; +using UnityEngine; namespace RimMind.Storyteller { @@ -9,9 +8,7 @@ internal sealed class StorytellerSettingsTabAdapter : ISettingsTab { public string Id => "storyteller"; public string OwnerModId => "RimMind.Storyteller"; - public string Label => "RimMind.Storyteller.UI.TabLabel".CanTranslate() - ? (string)"RimMind.Storyteller.UI.TabLabel".Translate() - : "Storyteller"; + public string Label => RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.TabLabel", "Storyteller"); public void Draw(Rect rect) => Settings.StorytellerSettingsTab.Draw(rect); } } diff --git a/Source/Memory/StorytellerMemory.cs b/Source/Memory/StorytellerMemory.cs index e997334..cf815c5 100644 --- a/Source/Memory/StorytellerMemory.cs +++ b/Source/Memory/StorytellerMemory.cs @@ -1,9 +1,8 @@ using System.Collections.Generic; using System.Linq; -using System.Text; +using RimMind.Presentation.Api; using RimWorld; using RimWorld.Planet; -using UnityEngine; using Verse; namespace RimMind.Storyteller.Memory @@ -99,8 +98,11 @@ public class StorytellerMemory : WorldComponent public string CustomSystemPrompt = string.Empty; - private static StorytellerMemory? _instance; - public static StorytellerMemory? Instance => _instance; + private static readonly WorldScopedComponentCache _instanceCache = + new WorldScopedComponentCache(); + public static StorytellerMemory? Instance => _instanceCache.Get(); + + internal static void ResetInstanceCache() => _instanceCache.Reset(); private float _tensionLevel = 0.5f; public float TensionLevel => _tensionLevel; @@ -112,7 +114,6 @@ public class StorytellerMemory : WorldComponent public StorytellerMemory(World world) : base(world) { - _instance = this; } public IReadOnlyList Records => _records; @@ -145,18 +146,7 @@ public void RecordIncident(IncidentDef def, IIncidentTarget target, int tick) } public string GetRecentSummary(int count) - { - if (_records.Count == 0) return string.Empty; - - var sb = new StringBuilder(); - var recent = _records.Skip(System.Math.Max(0, _records.Count - count)).ToList(); - foreach (var r in recent) - { - int day = TensionMath.TicksToDay(r.TriggeredTick); - sb.AppendLine("RimMind.Storyteller.Prompt.DaySummary".Translate(day, r.Label, r.MapName)); - } - return sb.ToString().TrimEnd(); - } + => StorytellerMemoryPromptFormatter.FormatRecentIncidents(_records, count); public void ClearRecords() => _records.Clear(); @@ -171,21 +161,7 @@ public void RecordDialogue(string role, string content, int tick) } public string GetRecentDialogueSummary(int count) - { - if (_dialogueRecords.Count == 0) return string.Empty; - - var sb = new StringBuilder(); - var recent = _dialogueRecords.Skip(System.Math.Max(0, _dialogueRecords.Count - count)).ToList(); - foreach (var r in recent) - { - int day = TensionMath.TicksToDay(r.tick); - string prefix = r.role == "user" - ? "RimMind.Storyteller.Prompt.RolePlayer".Translate() - : "RimMind.Storyteller.Prompt.RoleNarrator".Translate(); - sb.AppendLine("RimMind.Storyteller.Prompt.DialogueRecordLine".Translate($"{day}", prefix, r.content)); - } - return sb.ToString().TrimEnd(); - } + => StorytellerMemoryPromptFormatter.FormatRecentDialogues(_dialogueRecords, count); public void ClearDialogueRecords() => _dialogueRecords.Clear(); @@ -208,25 +184,15 @@ public void RecordPlayerReaction(string incidentDefName, string incidentLabel, s public string PeekReactions(int maxCount) { - if (_playerReactions.Count == 0 || maxCount <= 0) + string formatted = StorytellerMemoryPromptFormatter.FormatPlayerReactions(_playerReactions, maxCount); + if (string.IsNullOrEmpty(formatted)) { _consumedReactionsText = null; return string.Empty; } - int takeCount = System.Math.Min(maxCount, _playerReactions.Count); - var peeked = _playerReactions.Take(takeCount).ToList(); - - var sb = new StringBuilder(); - sb.AppendLine("RimMind.Storyteller.Prompt.PlayerReactions".Translate()); - foreach (var r in peeked) - { - int day = TensionMath.TicksToDay(r.tick); - sb.AppendLine("RimMind.Storyteller.Prompt.ReactionRecordLine".Translate( - day.ToString(), r.incidentLabel, r.reactionLabel)); - } - _consumedReactionsText = sb.ToString().TrimEnd(); - return _consumedReactionsText; + _consumedReactionsText = formatted; + return formatted; } public string ConsumeReactions(int maxCount) @@ -331,18 +297,7 @@ private void CleanupExpiredChains() } public string GetActiveChainsSummary() - { - if (_activeChains.Count == 0) return string.Empty; - var sb = new StringBuilder(); - foreach (var chain in _activeChains) - { - var triggeredNames = string.Join(", ", chain.steps.Select(s => s.incidentDefName)); - sb.AppendLine("RimMind.Storyteller.Prompt.ChainProgress".Translate( - chain.chainId, $"{chain.currentStep}", $"{chain.totalSteps}", triggeredNames)); - sb.AppendLine("RimMind.Storyteller.Prompt.ChainHint".Translate(chain.nextHint ?? "")); - } - return sb.ToString().TrimEnd(); - } + => StorytellerMemoryPromptFormatter.FormatActiveChains(_activeChains); public override void ExposeData() { diff --git a/Source/Memory/StorytellerMemoryPromptFormatter.cs b/Source/Memory/StorytellerMemoryPromptFormatter.cs new file mode 100644 index 0000000..1eb2dbd --- /dev/null +++ b/Source/Memory/StorytellerMemoryPromptFormatter.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using RimMind.Presentation.Api; + +namespace RimMind.Storyteller.Memory +{ + /// + /// Stateless prompt-text formatting helpers separated from + /// ring-buffer storage and WorldComponent persistence. + /// + internal static class StorytellerMemoryPromptFormatter + { + public static string FormatRecentIncidents(IReadOnlyList records, int count) + { + if (records == null || records.Count == 0 || count <= 0) + return string.Empty; + + var sb = new StringBuilder(); + int start = Math.Max(0, records.Count - count); + for (int i = start; i < records.Count; i++) + { + var r = records[i]; + int day = TensionMath.TicksToDay(r.TriggeredTick); + sb.AppendLine(RimMindAPI.Text.TrOr( + "RimMind.Storyteller.Prompt.DaySummary", + "Day {0}: {1} ({2})", + day, + r.Label, + r.MapName)); + } + return sb.ToString().TrimEnd(); + } + + public static string FormatRecentDialogues(IReadOnlyList records, int count) + { + if (records == null || records.Count == 0 || count <= 0) + return string.Empty; + + var sb = new StringBuilder(); + int start = Math.Max(0, records.Count - count); + for (int i = start; i < records.Count; i++) + { + var r = records[i]; + int day = TensionMath.TicksToDay(r.tick); + string prefix = string.Equals(r.role, "user", StringComparison.OrdinalIgnoreCase) + ? RimMindAPI.Text.TrOr("RimMind.Storyteller.Prompt.RolePlayer", "Player") + : RimMindAPI.Text.TrOr("RimMind.Storyteller.Prompt.RoleNarrator", "Narrator"); + sb.AppendLine(RimMindAPI.Text.TrOr( + "RimMind.Storyteller.Prompt.DialogueRecordLine", + "Day {0} {1}: {2}", + day.ToString(), + prefix, + r.content)); + } + return sb.ToString().TrimEnd(); + } + + public static string FormatPlayerReactions(IReadOnlyList reactions, int maxCount) + { + if (reactions == null || reactions.Count == 0 || maxCount <= 0) + return string.Empty; + + int takeCount = Math.Min(maxCount, reactions.Count); + var sb = new StringBuilder(); + sb.AppendLine(RimMindAPI.Text.TrOr( + "RimMind.Storyteller.Prompt.PlayerReactions", + "[Player Reaction Records]")); + for (int i = 0; i < takeCount; i++) + { + var r = reactions[i]; + int day = TensionMath.TicksToDay(r.tick); + sb.AppendLine(RimMindAPI.Text.TrOr( + "RimMind.Storyteller.Prompt.ReactionRecordLine", + "Day {0} {1} → Player: {2}", + day.ToString(), + r.incidentLabel, + r.reactionLabel)); + } + return sb.ToString().TrimEnd(); + } + + public static string FormatActiveChains(IReadOnlyList chains) + { + if (chains == null || chains.Count == 0) + return string.Empty; + + var sb = new StringBuilder(); + for (int i = 0; i < chains.Count; i++) + { + var chain = chains[i]; + string triggeredNames = string.Join(", ", chain.steps.Select(s => s.incidentDefName)); + sb.AppendLine(RimMindAPI.Text.TrOr( + "RimMind.Storyteller.Prompt.ChainProgress", + "{0} (step {1}/{2}, triggered: {3})", + chain.chainId, + chain.currentStep.ToString(), + chain.totalSteps.ToString(), + triggeredNames)); + sb.AppendLine(RimMindAPI.Text.TrOr( + "RimMind.Storyteller.Prompt.ChainHint", + " AI hint: {0}", + chain.nextHint ?? string.Empty)); + } + return sb.ToString().TrimEnd(); + } + } +} diff --git a/Source/Patch/Patch_IncidentWorker_TryExecute.cs b/Source/Patch/Patch_IncidentWorker_TryExecute.cs index 974ecf0..5fce217 100644 --- a/Source/Patch/Patch_IncidentWorker_TryExecute.cs +++ b/Source/Patch/Patch_IncidentWorker_TryExecute.cs @@ -27,9 +27,9 @@ static void Postfix(IncidentWorker __instance, IncidentParms parms, bool __resul if (!isThreat || parms?.quest != null) return; - RimMindAPI.NotifyIncidentExecuted(); + RimMindAPI.Ext.NotifyIncidentExecuted(); - if (RimMindAPI.CanTriggerDialogue) + if (RimMindAPI.Ext.CanTriggerDialogue) { var map = parms?.target as Map; if (map != null) @@ -47,10 +47,11 @@ static void Postfix(IncidentWorker __instance, IncidentParms parms, bool __resul { Rand.PopState(); } - string incidentContext = "RimMind.Storyteller.Context.IncidentOccurred".CanTranslate() - ? "RimMind.Storyteller.Context.IncidentOccurred".Translate(__instance.def.label).ToString() - : $"Incident occurred: {__instance.def.label}"; - RimMindAPI.TriggerDialogue(pawn, incidentContext); + string incidentContext = RimMindAPI.Text.TrOr( + "RimMind.Storyteller.Context.IncidentOccurred", + "Incident occurred: {0}", + __instance.def.label); + RimMindAPI.Ext.TriggerDialogue(pawn, incidentContext); } } } diff --git a/Source/Settings/StorytellerSettingsTab.cs b/Source/Settings/StorytellerSettingsTab.cs index 84da45f..8f2a116 100644 --- a/Source/Settings/StorytellerSettingsTab.cs +++ b/Source/Settings/StorytellerSettingsTab.cs @@ -9,180 +9,149 @@ namespace RimMind.Storyteller.Settings public static class StorytellerSettingsTab { private static Vector2 _scrollPos = Vector2.zero; + private static float _measuredHeight = 760f; private static string _promptText = string.Empty; - private static bool _promptLoaded; + private static StorytellerMemory? _loadedMemory; public static void Draw(Rect inRect) { - LoadPromptOnce(); - - Rect contentArea = SettingsUIDrawer.SplitContentArea(inRect); - Rect bottomBar = SettingsUIDrawer.SplitBottomBar(inRect); - - float contentH = EstimateHeight(); - Rect viewRect = new Rect(0f, 0f, contentArea.width - 16f, contentH); - Widgets.BeginScrollView(contentArea, ref _scrollPos, viewRect); - - var listing = new Listing_Standard(); - listing.Begin(viewRect); - + SyncPromptWithActiveMemory(); var settings = RimMindStorytellerMod.Settings; - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Storyteller.UI.TriggerSources".Translate()); - listing.CheckboxLabeled("RimMind.Storyteller.UI.EnableIntervalTrigger".Translate(), ref settings.enableIntervalTrigger, - "RimMind.Storyteller.UI.EnableIntervalTrigger.Desc".Translate()); - listing.CheckboxLabeled("RimMind.Storyteller.UI.EnableEventNotification".Translate(), ref settings.enableEventNotification, - "RimMind.Storyteller.UI.EnableEventNotification.Desc".Translate()); - - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Storyteller.UI.Section.Fallback".Translate()); - listing.LabelWithTooltip("RimMind.Storyteller.UI.FallbackModeLabel".Translate(settings.fallbackMode.ToString()), - "RimMind.Storyteller.UI.FallbackModeDesc".Translate()); - if (Widgets.ButtonText(listing.GetRect(30f), "RimMind.Storyteller.UI.SwitchFallback".Translate())) - { - var modes = new List + SettingsUIDrawer.DrawScrollableSettingsPage( + inRect, + ref _scrollPos, + ref _measuredHeight, + listing => { - FallbackMode.Cassandra, - FallbackMode.Randy, - FallbackMode.Phoebe, - FallbackMode.None, - }; - int idx = modes.IndexOf(settings.fallbackMode); - settings.fallbackMode = modes[(idx + 1) % modes.Count]; - } - - SettingsUIDrawer.DrawCustomPromptSection(listing, - "RimMind.Storyteller.UI.StylePromptLabel".Translate(), - ref _promptText, 3f); - SavePrompt(); - - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Storyteller.UI.Section.Request".Translate()); - string mtbTip = "RimMind.Storyteller.UI.MTBDays.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Storyteller.UI.MTBDays".Translate($"{settings.mtbDays:F1}"), mtbTip); - settings.mtbDays = listing.SliderWithTooltip(settings.mtbDays, 0.5f, 10f, mtbTip); - settings.mtbDays = (float)System.Math.Round(settings.mtbDays, 1); - - string reqExpireTip = "RimMind.Storyteller.UI.RequestExpire.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Storyteller.UI.RequestExpire".Translate($"{settings.requestExpireTicks / 60000f:F2}"), reqExpireTip); - settings.requestExpireTicks = (int)listing.SliderWithTooltip(settings.requestExpireTicks, 3600f, 120000f, reqExpireTip); - settings.requestExpireTicks = (settings.requestExpireTicks / 1500) * 1500; - - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Storyteller.UI.Section.Debug".Translate()); - listing.CheckboxLabeled("RimMind.Storyteller.UI.DebugLogging".Translate(), ref settings.debugLogging, - "RimMind.Storyteller.UI.DebugLogging.Desc".Translate()); - - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Storyteller.UI.Section.Memory".Translate()); - string eventRecTip = "RimMind.Storyteller.UI.MaxEventRecords.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Storyteller.UI.MaxEventRecords".Translate(settings.maxEventRecords), eventRecTip); - settings.maxEventRecords = (int)listing.SliderWithTooltip(settings.maxEventRecords, 10f, 100f, eventRecTip); - - string dialRecTip = "RimMind.Storyteller.UI.MaxDialogueRecords.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Storyteller.UI.MaxDialogueRecords".Translate(settings.maxDialogueRecords), dialRecTip); - settings.maxDialogueRecords = (int)listing.SliderWithTooltip(settings.maxDialogueRecords, 5f, 60f, dialRecTip); - - string reactionTip = "RimMind.Storyteller.UI.MaxPlayerReactions.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Storyteller.UI.MaxPlayerReactions".Translate(settings.maxPlayerReactions), reactionTip); - settings.maxPlayerReactions = (int)listing.SliderWithTooltip(settings.maxPlayerReactions, 5f, 50f, reactionTip); - - string chainExpireTip = "RimMind.Storyteller.UI.ChainExpireDays.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Storyteller.UI.ChainExpireDays".Translate($"{settings.chainExpireDays:F1}"), chainExpireTip); - settings.chainExpireDays = listing.SliderWithTooltip(settings.chainExpireDays, 3f, 30f, chainExpireTip); - settings.chainExpireDays = (float)System.Math.Round(settings.chainExpireDays * 2f) / 2f; - - string tensionDecayTip = "RimMind.Storyteller.UI.TensionDecayPerDay.Desc".Translate(); - listing.LabelWithTooltip("RimMind.Storyteller.UI.TensionDecayPerDay".Translate($"{settings.tensionDecayPerDay:F3}"), tensionDecayTip); - settings.tensionDecayPerDay = listing.SliderWithTooltip(settings.tensionDecayPerDay, 0.01f, 0.10f, tensionDecayTip); - settings.tensionDecayPerDay = (float)System.Math.Round(settings.tensionDecayPerDay * 200f) / 200f; - - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Storyteller.UI.MemoryTitle".Translate()); - var memory = StorytellerMemory.Instance; - if (memory == null) - { - listing.Label("RimMind.Storyteller.UI.MemoryNeedLoad".Translate()); - } - else - { - listing.Label("RimMind.Storyteller.UI.MemoryRecordCount".Translate(memory.Records.Count, settings.maxEventRecords)); - listing.Label("RimMind.Storyteller.UI.DialogueRecordCount".Translate(memory.DialogueRecords.Count)); - int now = Find.TickManager.TicksGame; - for (int i = memory.Records.Count - 1; i >= 0 && i >= memory.Records.Count - 10; i--) + SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Storyteller.UI.TriggerSources".Translate()); + listing.CheckboxLabeled("RimMind.Storyteller.UI.EnableIntervalTrigger".Translate(), ref settings.enableIntervalTrigger, + "RimMind.Storyteller.UI.EnableIntervalTrigger.Desc".Translate()); + listing.CheckboxLabeled("RimMind.Storyteller.UI.EnableEventNotification".Translate(), ref settings.enableEventNotification, + "RimMind.Storyteller.UI.EnableEventNotification.Desc".Translate()); + + SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Storyteller.UI.Section.Fallback".Translate()); + listing.LabelWithTooltip("RimMind.Storyteller.UI.FallbackModeLabel".Translate(settings.fallbackMode.ToString()), + "RimMind.Storyteller.UI.FallbackModeDesc".Translate()); + if (Widgets.ButtonText(listing.GetRect(30f), "RimMind.Storyteller.UI.SwitchFallback".Translate())) + { + var modes = new List + { + FallbackMode.Cassandra, + FallbackMode.Randy, + FallbackMode.Phoebe, + FallbackMode.None, + }; + int idx = modes.IndexOf(settings.fallbackMode); + settings.fallbackMode = modes[(idx + 1) % modes.Count]; + GUI.changed = true; + } + + SettingsUIDrawer.DrawCustomPromptSection(listing, + "RimMind.Storyteller.UI.StylePromptLabel".Translate(), + ref _promptText, 72f); + + SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Storyteller.UI.Section.Request".Translate()); + string mtbTip = "RimMind.Storyteller.UI.MTBDays.Desc".Translate(); + listing.LabelWithTooltip("RimMind.Storyteller.UI.MTBDays".Translate($"{settings.mtbDays:F1}"), mtbTip); + settings.mtbDays = listing.SliderWithTooltip(settings.mtbDays, 0.5f, 10f, mtbTip); + settings.mtbDays = (float)System.Math.Round(settings.mtbDays, 1); + + string reqExpireTip = "RimMind.Storyteller.UI.RequestExpire.Desc".Translate(); + listing.LabelWithTooltip("RimMind.Storyteller.UI.RequestExpire".Translate($"{settings.requestExpireTicks / 60000f:F2}"), reqExpireTip); + settings.requestExpireTicks = (int)listing.SliderWithTooltip(settings.requestExpireTicks, 3600f, 120000f, reqExpireTip); + settings.requestExpireTicks = (settings.requestExpireTicks / 1500) * 1500; + + SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Storyteller.UI.Section.Debug".Translate()); + listing.CheckboxLabeled("RimMind.Storyteller.UI.DebugLogging".Translate(), ref settings.debugLogging, + "RimMind.Storyteller.UI.DebugLogging.Desc".Translate()); + + SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Storyteller.UI.Section.Memory".Translate()); + string eventRecTip = "RimMind.Storyteller.UI.MaxEventRecords.Desc".Translate(); + listing.LabelWithTooltip("RimMind.Storyteller.UI.MaxEventRecords".Translate(settings.maxEventRecords), eventRecTip); + settings.maxEventRecords = (int)listing.SliderWithTooltip(settings.maxEventRecords, 10f, 100f, eventRecTip); + + string dialRecTip = "RimMind.Storyteller.UI.MaxDialogueRecords.Desc".Translate(); + listing.LabelWithTooltip("RimMind.Storyteller.UI.MaxDialogueRecords".Translate(settings.maxDialogueRecords), dialRecTip); + settings.maxDialogueRecords = (int)listing.SliderWithTooltip(settings.maxDialogueRecords, 5f, 60f, dialRecTip); + + string reactionTip = "RimMind.Storyteller.UI.MaxPlayerReactions.Desc".Translate(); + listing.LabelWithTooltip("RimMind.Storyteller.UI.MaxPlayerReactions".Translate(settings.maxPlayerReactions), reactionTip); + settings.maxPlayerReactions = (int)listing.SliderWithTooltip(settings.maxPlayerReactions, 5f, 50f, reactionTip); + + string chainExpireTip = "RimMind.Storyteller.UI.ChainExpireDays.Desc".Translate(); + listing.LabelWithTooltip("RimMind.Storyteller.UI.ChainExpireDays".Translate($"{settings.chainExpireDays:F1}"), chainExpireTip); + settings.chainExpireDays = listing.SliderWithTooltip(settings.chainExpireDays, 3f, 30f, chainExpireTip); + settings.chainExpireDays = (float)System.Math.Round(settings.chainExpireDays * 2f) / 2f; + + string tensionDecayTip = "RimMind.Storyteller.UI.TensionDecayPerDay.Desc".Translate(); + listing.LabelWithTooltip("RimMind.Storyteller.UI.TensionDecayPerDay".Translate($"{settings.tensionDecayPerDay:F3}"), tensionDecayTip); + settings.tensionDecayPerDay = listing.SliderWithTooltip(settings.tensionDecayPerDay, 0.01f, 0.10f, tensionDecayTip); + settings.tensionDecayPerDay = (float)System.Math.Round(settings.tensionDecayPerDay * 200f) / 200f; + + SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Storyteller.UI.MemoryTitle".Translate()); + var memory = StorytellerMemory.Instance; + if (memory == null) + { + listing.Label("RimMind.Storyteller.UI.MemoryNeedLoad".Translate()); + } + else + { + listing.Label("RimMind.Storyteller.UI.MemoryRecordCount".Translate(memory.Records.Count, settings.maxEventRecords)); + listing.Label("RimMind.Storyteller.UI.DialogueRecordCount".Translate(memory.DialogueRecords.Count)); + for (int i = memory.Records.Count - 1; i >= 0 && i >= memory.Records.Count - 10; i--) + { + var r = memory.Records[i]; + int day = TensionMath.TicksToDay(r.TriggeredTick); + listing.Label("RimMind.Storyteller.UI.MemoryDayEntry".Translate(day, r.Label, r.MapName)); + } + if (Widgets.ButtonText(listing.GetRect(30f), "RimMind.Storyteller.UI.ClearMemory".Translate())) + { + memory.ClearRecords(); + memory.ClearDialogueRecords(); + } + } + }, + onReset: () => { - var r = memory.Records[i]; - int day = TensionMath.TicksToDay(r.TriggeredTick); - listing.Label("RimMind.Storyteller.UI.MemoryDayEntry".Translate(day, r.Label, r.MapName)); - } - if (Widgets.ButtonText(listing.GetRect(30f), "RimMind.Storyteller.UI.ClearMemory".Translate())) + settings.enableIntervalTrigger = true; + settings.fallbackMode = FallbackMode.Cassandra; + settings.mtbDays = 1.5f; + settings.debugLogging = false; + settings.requestExpireTicks = 30000; + settings.maxEventRecords = 50; + settings.maxDialogueRecords = 30; + settings.enableEventNotification = true; + settings.maxPlayerReactions = 20; + settings.chainExpireDays = 10.0f; + settings.tensionDecayPerDay = 0.03f; + _promptText = string.Empty; + SavePrompt(); + }, + onDirtySave: () => { - memory.ClearRecords(); - memory.ClearDialogueRecords(); - } - } - - listing.End(); - Widgets.EndScrollView(); - - SettingsUIDrawer.DrawBottomBar(bottomBar, () => - { - settings.enableIntervalTrigger = true; - settings.fallbackMode = FallbackMode.Cassandra; - settings.mtbDays = 1.5f; - settings.debugLogging = false; - settings.requestExpireTicks = 30000; - settings.maxEventRecords = 50; - settings.maxDialogueRecords = 30; - settings.enableEventNotification = true; - settings.maxPlayerReactions = 20; - settings.chainExpireDays = 10.0f; - settings.tensionDecayPerDay = 0.03f; - _promptText = string.Empty; - SavePrompt(); - }); - - settings.Write(); + SavePrompt(); + settings.Write(); + }); } - private static void LoadPromptOnce() + private static void SyncPromptWithActiveMemory() { - if (_promptLoaded) return; - _promptLoaded = true; var memory = StorytellerMemory.Instance; - if (memory != null) - _promptText = memory.CustomSystemPrompt ?? string.Empty; - } + if (ReferenceEquals(memory, _loadedMemory)) + return; - private static void SavePrompt() - { - var memory = StorytellerMemory.Instance; - if (memory != null) - memory.CustomSystemPrompt = _promptText; + _loadedMemory = memory; + _promptText = memory?.CustomSystemPrompt ?? string.Empty; } - private static float EstimateHeight() + private static void SavePrompt() { - float h = 30f; - h += 24f + 24f; - if (RimMindStorytellerMod.Settings.enableIntervalTrigger) - h += 24f; - h += 24f + 24f + 32f; - h += 24f + 30f; - h += 24f + 80f; - h += 24f + (24f + 32f) * 2; - h += 24f + 24f; - h += 24f; - - h += 24f + (24f + 32f) * 5; - var memory = StorytellerMemory.Instance; if (memory != null) { - int shown = System.Math.Min(memory.Records.Count, 10); - h += 24f + shown * 24f + 30f; - } - else - { - h += 24f; + memory.CustomSystemPrompt = _promptText; } - - return h + 40f - 240f; } } } diff --git a/Source/Storyteller/StorytellerComp_RimMindDirector.cs b/Source/Storyteller/StorytellerComp_RimMindDirector.cs index 6d2340e..90f037a 100644 --- a/Source/Storyteller/StorytellerComp_RimMindDirector.cs +++ b/Source/Storyteller/StorytellerComp_RimMindDirector.cs @@ -64,13 +64,13 @@ public override IEnumerable MakeIntervalIncidents( if (RequestCoordinator.LastFailTick > 0 && currentTick - RequestCoordinator.LastFailTick < 2500) yield break; - if (!RimMindAPI.IsConfigured()) + if (!RimMindAPI.Settings.IsConfigured()) yield break; if (!(RimMindStorytellerMod.Settings?.enableIntervalTrigger ?? false)) yield break; - if (RimMindAPI.ShouldSkipStorytellerIncident()) + if (RimMindAPI.Ext.ShouldSkipStorytellerIncident()) yield break; float mtb = RimMindStorytellerMod.Settings?.mtbDays ?? Props.mtbDays; diff --git a/Source/Storyteller/StorytellerComp_RimMindFallback.cs b/Source/Storyteller/StorytellerComp_RimMindFallback.cs index 62cb43e..67a607e 100644 --- a/Source/Storyteller/StorytellerComp_RimMindFallback.cs +++ b/Source/Storyteller/StorytellerComp_RimMindFallback.cs @@ -30,7 +30,7 @@ public override IEnumerable MakeIntervalIncidents(IIncidentTarge if (aiComp != null && aiComp.IsActive) yield break; - if (RimMindAPI.IsConfigured() && settings.enableIntervalTrigger && aiComp != null) + if (RimMindAPI.Settings.IsConfigured() && settings.enableIntervalTrigger && aiComp != null) { int now = Find.TickManager.TicksGame; float directorMtb = settings.mtbDays; diff --git a/Source/Storyteller/StorytellerContextProviderRegistrar.cs b/Source/Storyteller/StorytellerContextProviderRegistrar.cs index 6060dc7..d242e1f 100644 --- a/Source/Storyteller/StorytellerContextProviderRegistrar.cs +++ b/Source/Storyteller/StorytellerContextProviderRegistrar.cs @@ -8,7 +8,6 @@ using RimMind.Presentation.Api; using RimMind.Storyteller.Extensions; using RimMind.Storyteller.Memory; -using Verse; namespace RimMind.Storyteller { @@ -16,8 +15,33 @@ internal static class StorytellerContextProviderRegistrar { private const string ModId = RimMind.Application.Common.Constants.RimMindOwnerConsts.StorytellerModId; + private const string DefaultSystemInstruction = + "You are the RimWorld storyteller AI. Based on the colony's current situation, select the most appropriate incident event. " + + "Consider colony wealth, threat level, food supply, colonist count, and recent events. " + + "Output must be valid JSON matching the IncidentOutput schema."; + + private const string DefaultWorldRules = + "Storyteller rules:\n" + + "- Only select from available RimWorld incident definitions\n" + + "- Consider threat level relative to colony wealth\n" + + "- Balance positive and negative events\n" + + "- Food shortages should trigger related events\n" + + "- Low mood colonists may need positive events"; + + private const string DefaultChatSystemInstruction = + "You are the AI Storyteller of this RimWorld colony speaking directly with the player through the Storyteller Altar. " + + "Respond in character as the narrator and director — perceptive, dramatic, and aware of colony history, narrative tension, and recent events. " + + "Reply in concise natural prose (do NOT output JSON). Consider player wishes without blindly obeying them."; + private static string Tr(string key, params object[] args) - => RimMindText.TrOr(key, key ?? string.Empty, args); + => RimMindAPI.Text.TrOr(key, key ?? string.Empty, args); + + private static bool IsStorytellerChat(IReadOnlyDictionary? hints) + { + return hints != null + && hints.TryGetValue("IsStorytellerChat", out var isChat) + && (isChat is true || (isChat is string isChatStr && string.Equals(isChatStr, "true", StringComparison.OrdinalIgnoreCase))); + } internal static void RegisterAll() { @@ -25,7 +49,7 @@ internal static void RegisterAll() // to a real event (unknown names never fall back to the base bus event). StorytellerStateChangedEvent.Register(); - ScenarioRegistry.Register(new ScenarioDescriptor + RimMindAPI.Context.RegisterScenario(new ScenarioDescriptor { Id = ScenarioIds.Storyteller, DefaultBaseRounds = 8, @@ -61,6 +85,8 @@ internal static void RegisterAll() ["memory_pawn"] = 0.3f, ["working_memory"] = 0.2f, ["memory_narrator"] = 0.9f, + ["storyteller_system"] = 1.0f, + ["storyteller_rules"] = 0.98f, ["storyteller_dialogue"] = 0.6f, ["storyteller_task"] = 0.95f, ["storyteller_context"] = 0.95f, @@ -69,6 +95,52 @@ internal static void RegisterAll() } }); + RimMindAPI.Context.ContextKeys.Register(new ContextProviderDef( + "storyteller_system", ContextLayer.L0_Static, 1.0f, + async (ctx, ct) => + { + if (ctx.Scenario != RimMindAPI.Context.ScenarioStoryteller) + { + return null; + } + bool isChat = IsStorytellerChat(ctx.Hints); + return await RimMindAPI.MainThreadSnapshot.GetAsync(() => + { + if (isChat) + { + string chatPrompt = RimMindAPI.Text.TrOr( + "RimMind.Storyteller.Prompt.ChatSystemInstruction", + DefaultChatSystemInstruction); + return StorytellerContextPolicy.ComposeTaskInstruction( + StorytellerMemory.Instance?.CustomSystemPrompt, + chatPrompt); + } + + return RimMindAPI.Text.TrOr( + "RimMind.Storyteller.Prompt.SystemInstruction", + DefaultSystemInstruction); + }, null, ct: ct).ConfigureAwait(false); + }, ownerMod: ModId, stalenessTicks: 0, + cacheScope: CacheScope.Static)); + + RimMindAPI.Context.ContextKeys.Register(new ContextProviderDef( + "storyteller_rules", ContextLayer.L0_Static, 0.98f, + async (ctx, ct) => + { + if (ctx.Scenario != RimMindAPI.Context.ScenarioStoryteller) + { + return null; + } + if (IsStorytellerChat(ctx.Hints)) + { + return null; + } + return await RimMindAPI.MainThreadSnapshot.GetAsync(() => + RimMindAPI.Text.TrOr("RimMind.Storyteller.Prompt.WorldRules", DefaultWorldRules), + null, ct: ct).ConfigureAwait(false); + }, ownerMod: ModId, stalenessTicks: 0, + cacheScope: CacheScope.Static)); + RimMindAPI.Context.ContextKeys.Register(new ContextProviderDef( "storyteller_dialogue", ContextLayer.L3_State, 0.5f, async (ctx, ct) => @@ -97,9 +169,7 @@ internal static void RegisterAll() { return null; } - if (ctx.Hints != null - && ctx.Hints.TryGetValue("IsStorytellerChat", out var isChat) - && (isChat is true || (isChat is string isChatStr && string.Equals(isChatStr, "true", System.StringComparison.OrdinalIgnoreCase)))) + if (IsStorytellerChat(ctx.Hints)) { return null; } diff --git a/Source/Storyteller/StorytellerNotificationService.cs b/Source/Storyteller/StorytellerNotificationService.cs index 9acc0c2..c06ba05 100644 --- a/Source/Storyteller/StorytellerNotificationService.cs +++ b/Source/Storyteller/StorytellerNotificationService.cs @@ -17,23 +17,16 @@ public void Register( string titleKey = isBigThreat ? "RimMind.Storyteller.UI.DeclareTitle" : "RimMind.Storyteller.UI.WhisperTitle"; - string title = titleKey.CanTranslate() - ? titleKey.Translate(incident.def.LabelCap).ToString() - : (isBigThreat ? $"[Storyteller Threat] {incident.def.LabelCap}" : $"[Storyteller] {incident.def.LabelCap}"); + string title = RimMindAPI.Text.TrOr( + titleKey, + isBigThreat ? "[Storyteller Threat] {0}" : "[Storyteller] {0}", + incident.def.LabelCap); string description = BuildDescription(incident, incidentResponse); - string shock = "RimMind.Storyteller.UI.Shock".CanTranslate() - ? "RimMind.Storyteller.UI.Shock".Translate().ToString() - : "Shocked"; - string excited = "RimMind.Storyteller.UI.Excited".CanTranslate() - ? "RimMind.Storyteller.UI.Excited".Translate().ToString() - : "Excited"; - string accept = "RimMind.Storyteller.UI.Accept".CanTranslate() - ? "RimMind.Storyteller.UI.Accept".Translate().ToString() - : "Accept"; - string tooltip = "RimMind.Storyteller.UI.NoInterfere".CanTranslate() - ? "RimMind.Storyteller.UI.NoInterfere".Translate().ToString() - : "Your reaction shapes the storyteller's memory."; + string shock = RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.Shock", "Shocked"); + string excited = RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.Excited", "Excited"); + string accept = RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.Accept", "Accept"); + string tooltip = RimMindAPI.Text.TrOr("RimMind.Storyteller.UI.NoInterfere", "Your reaction shapes the storyteller's memory."); string defName = incident.def.defName; string label = incident.def.LabelCap.ToString(); @@ -72,9 +65,10 @@ private static string BuildDescription( : response.reason; } - return "RimMind.Storyteller.UI.DefaultDesc".CanTranslate() - ? "RimMind.Storyteller.UI.DefaultDesc".Translate(incident.def.LabelCap).ToString() - : $"The storyteller triggered {incident.def.LabelCap}."; + return RimMindAPI.Text.TrOr( + "RimMind.Storyteller.UI.DefaultDesc", + "The storyteller triggered {0}.", + incident.def.LabelCap); } private static void RecordReaction( diff --git a/Source/Storyteller/StorytellerRequestCoordinator.cs b/Source/Storyteller/StorytellerRequestCoordinator.cs index 1552336..f93d436 100644 --- a/Source/Storyteller/StorytellerRequestCoordinator.cs +++ b/Source/Storyteller/StorytellerRequestCoordinator.cs @@ -75,7 +75,7 @@ public bool ForceRequest(IIncidentTarget target) if (target is not Map) return false; - if (!RimMindAPI.IsConfigured()) + if (!RimMindAPI.Settings.IsConfigured()) { RimMindErrors.Warn( "[RimMind-Storyteller] ForceRequest: API not configured"); @@ -97,7 +97,7 @@ private bool Dispatch(IIncidentTarget target, bool forced) _memory.PeekReactions(20); if (forced) { - RimMindAPI.ClearModCooldown(StorytellerRequestIds.RequestModId); + RimMindAPI.Request.ClearModCooldown(StorytellerRequestIds.RequestModId); Log.Message( "[RimMind-Storyteller] ForceRequest: sending structured AI request"); } @@ -217,19 +217,12 @@ private static bool ShouldNotifyPlayer(IncidentDef incidentDef) private bool TryResolveMemory() { - if (_memory != null) - return true; - - _memory = StorytellerMemory.Instance!; - if (_memory == null && Find.World != null) + var current = StorytellerMemory.Instance; + if (current != null) { - _memory = Find.World.components - .OfType() - .FirstOrDefault()!; - } - - if (_memory != null) + _memory = current; return true; + } RimMindErrors.Warn( "[RimMind-Storyteller] StorytellerMemory not found, skipping."); diff --git a/Source/Storyteller/StorytellerRequestIds.cs b/Source/Storyteller/StorytellerRequestIds.cs index 837023e..b540c74 100644 --- a/Source/Storyteller/StorytellerRequestIds.cs +++ b/Source/Storyteller/StorytellerRequestIds.cs @@ -6,7 +6,7 @@ namespace RimMind.Storyteller /// /// Storyteller-owned identity used by Core's request queue. /// The same id must be passed to LlmRequestEnvelopeBuilder.WithModId, to - /// RimMindAPI.ClearModCooldown / GetModCooldownTicksLeft, and exposed by + /// RimMindAPI.Request.ClearModCooldown / GetModCooldownTicksLeft, and exposed by /// StorytellerModCooldown: Core stores per-mod cooldowns under the envelope ModId, /// so any other spelling silently targets a cooldown key that never exists. /// @@ -33,6 +33,7 @@ internal static LlmRequestEnvelope Create(string scenarioId, string? schema, str .WithMaxTokens(MaxTokens) .WithTemperature(Temperature) .WithNpcId(npcId) + .WithRequireAliveColonist(false) .Build(); } } diff --git a/Source/Storyteller/StorytellerResponseParserPure.cs b/Source/Storyteller/StorytellerResponseParserPure.cs index a8beea2..058e9b2 100644 --- a/Source/Storyteller/StorytellerResponseParserPure.cs +++ b/Source/Storyteller/StorytellerResponseParserPure.cs @@ -1,207 +1,70 @@ -using System.Text; -using System.Text.RegularExpressions; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using RimMind.Application.Features.Json; +using RimMind.Presentation.Api; namespace RimMind.Storyteller { /// - /// 纯逻辑版本的叙事者响应解析器,不依赖 RimMindAPI 或 RimWorld 运行时。 - /// 仅负责 JSON 修复与反序列化,不涉及 DefDatabase/FiringIncident 等游戏逻辑。 - /// 供测试项目直接编译使用。 + /// 纯逻辑版本的叙事者响应解析器,统一委托 Core 进行 + /// 思考标签/代码块剥离、字符串感知 JSON 提取、截断修复与伪函数调用解析。 + /// 不涉及 DefDatabase/FiringIncident 等游戏逻辑,供测试项目直接编译使用。 /// public static class StorytellerResponseParserPure { - private static readonly Regex TrailingCommaRegex = new Regex( - @",\s*([}\]])", - RegexOptions.Compiled); - - private static readonly Regex CodeFenceRegex = new Regex( - @"```(?:json)?\s*([\s\S]*?)\s*```", - RegexOptions.Compiled | RegexOptions.IgnoreCase); - /// - /// 从AI响应中剥离 markdown 代码块标记并提取干净的 JSON 子串。 + /// 从 AI 响应中剥离思考标签与 markdown 代码块标记并提取干净的 JSON 子串。 /// public static string ExtractJsonSubstring(string input) { if (string.IsNullOrWhiteSpace(input)) return string.Empty; - string text = input.Trim(); - - var match = CodeFenceRegex.Match(text); - if (match.Success) - { - text = match.Groups[1].Value.Trim(); - } - else if (text.StartsWith("```")) - { - int firstNewline = text.IndexOf('\n'); - text = firstNewline >= 0 ? text.Substring(firstNewline + 1) : text.TrimStart('`'); - int lastFence = text.LastIndexOf("```", System.StringComparison.Ordinal); - if (lastFence >= 0) - text = text.Substring(0, lastFence); - text = text.Trim(); - } - - int firstBrace = text.IndexOf('{'); - if (firstBrace < 0) - return text.Trim(); - - int openBraces = 0; - int closeBraces = 0; - bool inString = false; - bool escape = false; - for (int i = firstBrace; i < text.Length; i++) - { - char c = text[i]; - if (escape) - { - escape = false; - continue; - } - if (c == '\\' && inString) - { - escape = true; - continue; - } - if (c == '"') - { - inString = !inString; - continue; - } - if (!inString) - { - if (c == '{') openBraces++; - else if (c == '}') closeBraces++; - } - } - - int lastBrace = text.LastIndexOf('}'); - if (lastBrace > firstBrace && openBraces <= closeBraces) - { - text = text.Substring(firstBrace, lastBrace - firstBrace + 1); - } - else - { - text = text.Substring(firstBrace); - } - - return text.Trim(); + string? extracted = RimMindAPI.Json.ExtractJsonPayload(input); + if (!string.IsNullOrEmpty(extracted)) + return extracted!.Trim(); + return RimMindAPI.Json.StripThinkingAndCodeFences(input); } /// - /// 解析AI响应内容,尝试反序列化为 IncidentResponse。 - /// 失败时尝试修复截断JSON后重试。若 defName 为空则返回 null。 + /// 解析 AI 响应内容,尝试反序列化为 IncidentResponse。 + /// 失败时通过 Core JSON 修复与伪函数调用解析兜底。若 defName 为空则返回 null。 /// public static IncidentResponse? ParseResponse(string aiContent) { - if (string.IsNullOrEmpty(aiContent)) return null; + if (string.IsNullOrWhiteSpace(aiContent)) return null; - string clean = ExtractJsonSubstring(aiContent); - if (string.IsNullOrEmpty(clean)) return null; - - IncidentResponse? result; - try + if (RimMindAPI.Json.TryDeserializeWithRepair(aiContent, out var result) + && result != null + && !string.IsNullOrEmpty(result.defName)) { - result = JsonConvert.DeserializeObject(clean); + return result; } - catch + + var pseudoCalls = RimMindAPI.Json.ParsePseudoFunctionCalls(aiContent); + if (pseudoCalls != null) { - string? repaired = TryRepairTruncatedJson(clean); - if (repaired != null) + for (int i = 0; i < pseudoCalls.Count; i++) { - try { result = JsonConvert.DeserializeObject(repaired); } - catch { result = null; } - } - else - { - result = null; + if (RimMindAPI.Json.TryDeserializeWithRepair( + pseudoCalls[i].ArgumentsJson, + out var pseudoResult) + && pseudoResult != null + && !string.IsNullOrEmpty(pseudoResult.defName)) + { + return pseudoResult; + } } } - if (result == null || string.IsNullOrEmpty(result.defName)) return null; - return result; + return null; } /// - /// 尝试修复截断的JSON。若输入已是合法JSON则返回null(无需修复), - /// 若输入为空白或不可修复则返回null。 + /// 尝试修复截断的 JSON。若输入已是合法 JSON 则返回 null(无需修复), + /// 若输入为空白或不可修复则返回 null。 /// public static string? TryRepairTruncatedJson(string input) { if (string.IsNullOrWhiteSpace(input)) return null; string clean = ExtractJsonSubstring(input); if (string.IsNullOrWhiteSpace(clean)) return null; - try - { - JToken.Parse(clean); - return null; // 已是合法JSON,无需修复 - } - catch - { - return JsonRepairer.TryRepairTruncatedJson(clean) ?? Repair(clean); - } - } - - private static string Repair(string input) - { - if (string.IsNullOrWhiteSpace(input)) return "{}"; - - var balanced = BalanceBrackets(input); - return TrailingCommaRegex.Replace(balanced, "$1"); - } - - private static string BalanceBrackets(string input) - { - int openCurly = 0, openSquare = 0; - bool inString = false; - bool escape = false; - foreach (char c in input) - { - if (escape) - { - escape = false; - continue; - } - if (c == '\\' && inString) - { - escape = true; - continue; - } - if (c == '"') - { - inString = !inString; - continue; - } - if (!inString) - { - if (c == '{') openCurly++; - else if (c == '}') openCurly--; - else if (c == '[') openSquare++; - else if (c == ']') openSquare--; - } - } - - var sb = new StringBuilder(input); - if (inString) - { - if (escape) - sb.Append('\\'); - sb.Append('"'); - } - - string current = sb.ToString().TrimEnd(); - current = TrailingCommaRegex.Replace(current, "$1").TrimEnd(); - if (current.EndsWith(",")) - current = current.Substring(0, current.Length - 1).TrimEnd(); - else if (current.EndsWith(":")) - current += "null"; - - sb = new StringBuilder(current); - while (openSquare > 0) { sb.Append(']'); openSquare--; } - while (openCurly > 0) { sb.Append('}'); openCurly--; } - return sb.ToString(); + return RimMindAPI.Json.TryRepairTruncatedJson(clean); } } } diff --git a/Source/UI/Window_StorytellerAgentControl.cs b/Source/UI/Window_StorytellerAgentControl.cs index 5b2dae1..502e1e0 100644 --- a/Source/UI/Window_StorytellerAgentControl.cs +++ b/Source/UI/Window_StorytellerAgentControl.cs @@ -33,7 +33,7 @@ public override void DoWindowContents(Rect inRect) else { string stateKey = $"RimMind.Agent.State.{agent.State}"; - stateDisplay = stateKey.CanTranslate() ? (string)stateKey.Translate() : agent.State.ToString(); + stateDisplay = RimMindAPI.Text.TrOr(stateKey, agent.State.ToString()); } Widgets.Label(new Rect(inRect.x, y, inRect.width, 24f), "RimMind.Storyteller.UI.Agent.State".Translate(stateDisplay)); diff --git a/Source/UI/Window_StorytellerDialogue.cs b/Source/UI/Window_StorytellerDialogue.cs index cd9ff2b..2e13a1e 100644 --- a/Source/UI/Window_StorytellerDialogue.cs +++ b/Source/UI/Window_StorytellerDialogue.cs @@ -1,250 +1,126 @@ using System; -using System.Collections.Concurrent; -using System.Collections.Generic; using System.Linq; using RimMind.Application.Common.Models.Context; using RimMind.Application.Features.Llm; using RimMind.Domain.Llm; using RimMind.Domain.ValueObjects; using RimMind.Presentation.Api; -using RimMind.Storyteller; +using RimMind.Presentation.UI; using RimMind.Storyteller.Memory; -using RimMind.Storyteller.Settings; -using RimWorld; using UnityEngine; using Verse; namespace RimMind.Storyteller.UI { - public class Window_StorytellerDialogue : Window + public class Window_StorytellerDialogue : RimMindChatWindowBase { - private Map _map; - private List<(string role, string content)> _messages = new List<(string, string)>(); - private string _inputText = ""; - private bool _waitingForResponse; - private Vector2 _scrollPos = Vector2.zero; - private bool _autoScroll = true; - private readonly ConcurrentQueue<(string role, string content)> _responseQueue = new ConcurrentQueue<(string, string)>(); private const int MaxHistoryRounds = 6; - private const float Padding = 8f; - private const float InputHeight = 36f; - private const float SendButtonWidth = 80f; - private const float HeaderHeight = 28f; - private const float StatusHeight = 22f; - private const float ScrollbarWidth = 16f; - private static readonly Color UserColor = new Color(0.7f, 0.85f, 1f); - private static readonly Color StorytellerColor = new Color(1f, 0.95f, 0.8f); - private static readonly Color ChatBgColor = new Color(0.08f, 0.08f, 0.12f, 0.5f); - private static readonly Color StatusColor = new Color(1f, 1f, 0.5f); - private static readonly Color HeaderColor = new Color(1f, 0.9f, 0.7f); + private static readonly Color StorytellerHeaderColor = new Color(1f, 0.9f, 0.7f); + + private readonly Map _map; public override Vector2 InitialSize => new Vector2(520f, 560f); + protected override Color HeaderColor => StorytellerHeaderColor; public Window_StorytellerDialogue(Map map) : base() { _map = map; - doCloseButton = false; - doCloseX = true; closeOnClickedOutside = true; - forcePause = false; - absorbInputAroundWindow = false; - draggable = true; var memory = StorytellerMemory.Instance; if (memory != null) { - int loadCount = System.Math.Min(MaxHistoryRounds, memory.DialogueRecords.Count); + int loadCount = Math.Min(MaxHistoryRounds, memory.DialogueRecords.Count); var recentRecords = memory.DialogueRecords - .Skip(System.Math.Max(0, memory.DialogueRecords.Count - loadCount)).ToList(); + .Skip(Math.Max(0, memory.DialogueRecords.Count - loadCount)); foreach (var r in recentRecords) - _messages.Add((r.role, r.content)); - } - } - - public override void DoWindowContents(Rect inRect) - { - while (_responseQueue.TryDequeue(out var resp)) - { - _waitingForResponse = false; - if (string.IsNullOrEmpty(resp.content)) continue; - _messages.Add(resp); - _autoScroll = true; - if (resp.role != "system") { - RecordDialogueToMemory(resp.role, resp.content); + AppendMessage(r.role, r.content, notifyHook: false); } } + } - Text.Font = GameFont.Small; - - float statusH = _waitingForResponse ? StatusHeight + Padding : 0f; - float chatHeight = inRect.height - HeaderHeight - statusH - InputHeight - Padding * 3; - float inputY = inRect.yMax - InputHeight; - - Rect headerRect = new Rect(inRect.x, inRect.y, inRect.width, HeaderHeight); - Rect chatRect = new Rect(inRect.x, inRect.y + HeaderHeight + Padding, inRect.width, chatHeight); - - GUI.color = HeaderColor; - Text.Anchor = TextAnchor.MiddleCenter; - Widgets.Label(headerRect, "RimMind.Storyteller.Dialogue.Title".Translate()); - Text.Anchor = TextAnchor.UpperLeft; - GUI.color = Color.white; - - Widgets.DrawBoxSolid(chatRect, ChatBgColor); - DrawChatHistory(chatRect); - - if (_waitingForResponse) - { - Rect statusRect = new Rect(inRect.x, inputY - StatusHeight - Padding, inRect.width, StatusHeight); - GUI.color = StatusColor; - Text.Anchor = TextAnchor.MiddleCenter; - Widgets.Label(statusRect, "RimMind.Storyteller.Dialogue.Thinking".Translate()); - Text.Anchor = TextAnchor.UpperLeft; - GUI.color = Color.white; - } - - Rect inputRect = new Rect(inRect.x, inputY, inRect.width - SendButtonWidth - Padding, InputHeight); - Rect sendRect = new Rect(inRect.xMax - SendButtonWidth, inputY, SendButtonWidth, InputHeight); + protected override string GetTitle() + => RimMindAPI.Text.TrOr("RimMind.Storyteller.Dialogue.Title", "Communicate with Storyteller"); - _inputText = Widgets.TextField(inputRect, _inputText); + protected override string GetWaitingText() + => RimMindAPI.Text.TrOr("RimMind.Storyteller.Dialogue.Thinking", "● Thinking..."); - if (!_waitingForResponse) - { - if (Widgets.ButtonText(sendRect, "RimMind.Storyteller.Dialogue.Send".Translate())) - SendMessage(); - } - else - { - Widgets.ButtonText(sendRect, "RimMind.Storyteller.Dialogue.Send".Translate()); - } + protected override string GetSendButtonLabel() + => RimMindAPI.Text.TrOr("RimMind.Storyteller.Dialogue.Send", "Send"); - if (!_waitingForResponse && Event.current.type == EventType.KeyDown - && Event.current.keyCode == KeyCode.Return && !_inputText.NullOrEmpty()) - { - SendMessage(); - Event.current.Use(); - } + protected override string GetPrefixForRole(string role) + { + if (string.Equals(role, "user", StringComparison.OrdinalIgnoreCase)) + return RimMindAPI.Text.TrOr("RimMind.Storyteller.Dialogue.PlayerPrefix", "You: "); + if (string.Equals(role, "system", StringComparison.OrdinalIgnoreCase)) + return string.Empty; + return RimMindAPI.Text.TrOr("RimMind.Storyteller.Dialogue.StorytellerPrefix", "Storyteller: "); } - private void DrawChatHistory(Rect rect) + protected override void OnMessageAppended(ChatWindowMessage message) { - float contentWidth = rect.width - ScrollbarWidth; - float contentHeight = CalcMessagesHeight(contentWidth - Padding * 2); - Rect viewRect = new Rect(0f, 0f, contentWidth, contentHeight); - - float prevScrollY = _scrollPos.y; - Widgets.BeginScrollView(rect, ref _scrollPos, viewRect); - - float y = 0f; - for (int i = 0; i < _messages.Count; i++) + if (!string.Equals(message.Role, "system", StringComparison.OrdinalIgnoreCase)) { - var msg = _messages[i]; - string prefix = msg.role == "user" - ? "RimMind.Storyteller.Dialogue.PlayerPrefix".Translate() - : msg.role == "system" - ? string.Empty - : "RimMind.Storyteller.Dialogue.StorytellerPrefix".Translate(); - string line = prefix + msg.content; - float lineH = Text.CalcHeight(line, contentWidth - Padding * 2) + Padding; - - if (i % 2 == 0) - { - Widgets.DrawBoxSolid(new Rect(0f, y, contentWidth, lineH), - new Color(1f, 1f, 1f, 0.03f)); - } - - GUI.color = msg.role == "user" - ? UserColor - : msg.role == "system" - ? new Color(1f, 0.55f, 0.55f) - : StorytellerColor; - Widgets.Label(new Rect(Padding, y, contentWidth - Padding * 2, lineH), line); - GUI.color = Color.white; - - y += lineH; + RecordDialogueToMemory(message.Role, message.Content); } - - Widgets.EndScrollView(); - - float maxScroll = Mathf.Max(0f, contentHeight - rect.height); - if (_autoScroll && maxScroll > 0f) - _scrollPos.y = maxScroll; - - if (Mathf.Abs(prevScrollY - _scrollPos.y) > 1f && _scrollPos.y < maxScroll - 1f) - _autoScroll = false; - - if (_scrollPos.y >= maxScroll - 2f) - _autoScroll = true; } - private void SendMessage() + protected override void OnSubmitUserMessage(string trimmedInput) { - if (_inputText.NullOrEmpty() || _waitingForResponse) return; - if (!RimMindAPI.IsConfigured()) return; + if (IsClosed || IsWaiting) return; + if (!RimMindAPI.Settings.IsConfigured()) return; - string userMsg = _inputText.Trim(); - _inputText = ""; - _messages.Add(("user", userMsg)); - _autoScroll = true; - - RecordDialogueToMemory("user", userMsg); - - if (_messages.Count > MaxHistoryRounds * 2) - _messages = _messages.TakeLast(MaxHistoryRounds * 2).ToList(); - - _waitingForResponse = true; + AppendMessage("user", trimmedInput); + SetWaiting(true); var envelope = LlmRequestEnvelopeBuilder .ForNpc( "NPC-storyteller", gameStateInfo: new GameStateInfo() - .AddSection("dialogue_input", userMsg) + .AddSection("dialogue_input", trimmedInput) .AddSection("IsStorytellerChat", "true")) .ForScenarioId(ScenarioIds.Storyteller) .WithModId(StorytellerRequestIds.RequestModId) .WithHint("IsStorytellerChat", "true") + .WithRequireAliveColonist(false) .WithMaxTokens(400) .WithTemperature(0.9f) + .WithCancellation(LifetimeToken) .Build(); RimMindAPI.Request.Send(envelope, result => { + if (IsClosed) return; + if (result.IsErr) { - string errText = "RimMind.Storyteller.Dialogue.ErrorResponse".CanTranslate() - ? "RimMind.Storyteller.Dialogue.ErrorResponse".Translate(result.Error.Message).ToString() - : $"[Error] {result.Error.Message}"; - _responseQueue.Enqueue(("system", errText)); + if (result.Error.Code == RimMindErrorCode.Cancelled) + { + SetWaiting(false); + return; + } + + string errText = RimMindAPI.Text.TrOr( + "RimMind.Storyteller.Dialogue.ErrorResponse", + "[Error] {0}", + result.Error.Message); + PostReply("system", errText); return; } - string assistantMsg = result.Value.Content?.Trim() ?? ""; - if (assistantMsg.NullOrEmpty()) + + string assistantMsg = result.Value.Content?.Trim() ?? string.Empty; + if (string.IsNullOrEmpty(assistantMsg)) { - string emptyText = "RimMind.Storyteller.Dialogue.EmptyResponse".CanTranslate() - ? "RimMind.Storyteller.Dialogue.EmptyResponse".Translate().ToString() - : "[Error] Empty response from storyteller."; - _responseQueue.Enqueue(("system", emptyText)); + string emptyText = RimMindAPI.Text.TrOr( + "RimMind.Storyteller.Dialogue.EmptyResponse", + "[Error] Empty response from storyteller."); + PostReply("system", emptyText); return; } - _responseQueue.Enqueue(("assistant", assistantMsg)); - }); - } - private float CalcMessagesHeight(float width) - { - float h = 0f; - for (int i = 0; i < _messages.Count; i++) - { - var msg = _messages[i]; - string prefix = msg.role == "user" - ? "RimMind.Storyteller.Dialogue.PlayerPrefix".Translate() - : msg.role == "system" - ? string.Empty - : "RimMind.Storyteller.Dialogue.StorytellerPrefix".Translate(); - string line = prefix + msg.content; - h += Text.CalcHeight(line, width) + Padding; - } - return h + Padding; + PostReply("assistant", assistantMsg); + }); } private static void RecordDialogueToMemory(string role, string content) @@ -252,7 +128,7 @@ private static void RecordDialogueToMemory(string role, string content) var memory = StorytellerMemory.Instance; if (memory == null) return; - int tick = Find.TickManager.TicksGame; + int tick = Find.TickManager?.TicksGame ?? 0; memory.RecordDialogue(role, content, tick); // storyteller_dialogue context is cached; the new turn must reach the next prompt. StorytellerStateChangedEvent.Publish(); @@ -262,9 +138,9 @@ private static void RecordDialogueToMemory(string role, string content) private static void TryPushToMemoryMod(string role, string content, int tick) { - string prefix = role == "user" - ? "RimMind.Storyteller.Prompt.RolePlayer".Translate() - : "RimMind.Storyteller.Prompt.RoleNarrator".Translate(); + string prefix = string.Equals(role, "user", StringComparison.OrdinalIgnoreCase) + ? RimMindAPI.Text.TrOr("RimMind.Storyteller.Prompt.RolePlayer", "Player") + : RimMindAPI.Text.TrOr("RimMind.Storyteller.Prompt.RoleNarrator", "Narrator"); RimMindAPI.Memory.AddNarratorMemory($"{prefix}: {content}", tick, 0.3f); } diff --git a/Tests/Contracts/StorytellerCoreAdoptionContracts.cs b/Tests/Contracts/StorytellerCoreAdoptionContracts.cs new file mode 100644 index 0000000..ac2edbb --- /dev/null +++ b/Tests/Contracts/StorytellerCoreAdoptionContracts.cs @@ -0,0 +1,218 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using RimMind.Application.Common.Constants; +using RimMind.Application.Common.Interfaces.Context; +using RimMind.Application.Common.Models.Context; +using RimMind.Application.Features.Context; +using RimMind.Domain.Llm; +using RimMind.Domain.ValueObjects; +using RimMind.Presentation.Api; +using RimMind.Storyteller.Memory; +using RimMind.Storyteller.UI; +using UnityEngine; +using Verse; +using Xunit; + +namespace RimMind.Storyteller.Tests.Contracts +{ + public sealed class StorytellerCoreAdoptionContracts + { + [Fact] + public async Task Storyteller_OwnsItsOwnScenarioAndL0Prompts_ForBothIncidentAndAltarChatModes() + { + RimMindAPI.Context.ContextKeys.Definitions.Clear(); + StorytellerMemory.Instance = new StorytellerMemory + { + CustomSystemPrompt = "Be mysterious and poetic." + }; + try + { + StorytellerContextProviderRegistrar.RegisterAll(); + + var scenario = ScenarioRegistry.Get(ScenarioIds.Storyteller); + Assert.NotNull(scenario); + Assert.Equal(RimMindOwnerConsts.StorytellerModId, scenario!.OwnerModId); + Assert.Equal(L4Mode.NarrativeMemory, scenario.L4Mode); + Assert.True(scenario.RelevanceWeights != null && scenario.RelevanceWeights.ContainsKey("storyteller_system")); + Assert.True(scenario.RelevanceWeights!.ContainsKey("storyteller_rules")); + + var systemProvider = RimMindAPI.Context.ContextKeys.Definitions.Single(d => d.Key == "storyteller_system"); + var rulesProvider = RimMindAPI.Context.ContextKeys.Definitions.Single(d => d.Key == "storyteller_rules"); + Assert.Equal(ContextLayer.L0_Static, systemProvider.Layer); + Assert.Equal(ContextLayer.L0_Static, rulesProvider.Layer); + + var incidentCtx = new ProviderContext(ScenarioIds.Storyteller, "t-inc") { NpcId = "NPC-storyteller" }; + string? incidentSys = await systemProvider.Provider(incidentCtx, CancellationToken.None); + string? incidentRules = await rulesProvider.Provider(incidentCtx, CancellationToken.None); + Assert.NotNull(incidentSys); + Assert.Contains("storyteller AI", incidentSys!); + Assert.NotNull(incidentRules); + Assert.Contains("Storyteller rules", incidentRules!); + + // Non-storyteller scenarios must receive null (strict scenario guard) + Assert.Null(await systemProvider.Provider(incidentCtx with { Scenario = ScenarioIds.Dialogue }, CancellationToken.None)); + Assert.Null(await rulesProvider.Provider(incidentCtx with { Scenario = ScenarioIds.AgentDecision }, CancellationToken.None)); + + // Altar chat mode receives chat persona + CustomSystemPrompt, and omits incident JSON rules + var chatCtx = new ProviderContext(ScenarioIds.Storyteller, "t-chat") + { + NpcId = "NPC-storyteller", + Hints = new Dictionary { ["IsStorytellerChat"] = "true" } + }; + string? chatSys = await systemProvider.Provider(chatCtx, CancellationToken.None); + Assert.NotNull(chatSys); + Assert.Contains("Be mysterious and poetic.", chatSys!); + Assert.Contains("Storyteller Altar", chatSys!); + Assert.Null(await rulesProvider.Provider(chatCtx, CancellationToken.None)); + } + finally + { + StorytellerMemory.Instance = null; + RimMindAPI.Context.ContextKeys.Definitions.Clear(); + } + } + + [Fact] + public void StorytellerResponseParserPure_HandlesThinkingTagsAndPseudoFunctionCallsViaCore() + { + string withThinking = "Tension is low.\n```json\n{\"defName\":\"RaidEnemy\",\"reason\":\"raise tension\"}\n```"; + var parsed = StorytellerResponseParserPure.ParseResponse(withThinking); + Assert.NotNull(parsed); + Assert.Equal("RaidEnemy", parsed!.defName); + Assert.Equal("raise tension", parsed.reason); + + string pseudoCall = "select_incident(defName=\"TraderCaravanArrival\", reason=\"colony needs relief\")"; + var pseudoParsed = StorytellerResponseParserPure.ParseResponse(pseudoCall); + Assert.NotNull(pseudoParsed); + Assert.Equal("TraderCaravanArrival", pseudoParsed!.defName); + Assert.Equal("colony needs relief", pseudoParsed.reason); + + Assert.Null(StorytellerResponseParserPure.TryRepairTruncatedJson("{\"defName\":\"Eclipse\"}")); + string? repaired = StorytellerResponseParserPure.TryRepairTruncatedJson("{\"defName\":\"Eclipse\",\"reason\":\"darkness"); + Assert.NotNull(repaired); + Assert.Contains("\"Eclipse\"", repaired!); + } + + [Fact] + public void Window_StorytellerDialogue_CancelsInFlightRequestOnPostClose_AndPersistsReplies() + { + RimMindAPI.Configured = true; + RimMindAPI.Sent.Clear(); + RimMindAPI.Memory.Narrations.Clear(); + Widgets.Labels.Clear(); + Find.TickManager.TicksGame = 60000; + var memory = new StorytellerMemory(); + memory.RecordDialogue("assistant", "Greetings, colonist.", 0); + StorytellerMemory.Instance = memory; + + try + { + var window = new Window_StorytellerDialogue(new Map()); + // Pre-loaded history must appear without duplicating into memory + Assert.Single(window.Messages); + Assert.Single(memory.DialogueRecords); + + Widgets.NextText = "Send us traders please."; + Widgets.ClickSend = true; + window.DoWindowContents(new Rect(0, 0, 520, 560)); + + var sent = Assert.Single(RimMindAPI.Sent); + Assert.Equal(ScenarioIds.Storyteller, sent.Envelope.ScenarioId); + Assert.Equal(StorytellerRequestIds.RequestModId, sent.Envelope.ModId); + Assert.Equal(false, sent.Envelope.RequireAliveColonist); + Assert.True(sent.Envelope.Ct.CanBeCanceled); + Assert.False(sent.Envelope.Ct.IsCancellationRequested); + + // Deliver assistant reply and drain on next frame + sent.Complete(Result.Ok(new LlmResponse { Content = "Fortune favors the bold." })); + window.DoWindowContents(new Rect(0, 0, 520, 560)); + Assert.Equal(3, window.Messages.Count); + Assert.Equal(3, memory.DialogueRecords.Count); + Assert.Equal(2, RimMindAPI.Memory.Narrations.Count); + + // Second turn: closing window MUST cancel the in-flight CancellationToken and drop late replies + Widgets.NextText = "Any storms ahead?"; + Widgets.ClickSend = true; + window.DoWindowContents(new Rect(0, 0, 520, 560)); + Assert.Equal(2, RimMindAPI.Sent.Count); + + window.PostClose(); + Assert.True(RimMindAPI.Sent[1].Envelope.Ct.IsCancellationRequested); + + int recordsBeforeLateReply = memory.DialogueRecords.Count; + RimMindAPI.Sent[1].Complete(Result.Ok(new LlmResponse { Content = "Late reply" })); + window.DoWindowContents(new Rect(0, 0, 520, 560)); + Assert.Equal(recordsBeforeLateReply, memory.DialogueRecords.Count); + } + finally + { + StorytellerMemory.Instance = null; + RimMindAPI.Sent.Clear(); + RimMindAPI.Memory.Narrations.Clear(); + } + } + + [Fact] + public void StorytellerIncidentRequestFactory_OptsOutOfColonistLivenessGate() + { + var envelope = StorytellerIncidentRequestFactory.Create(ScenarioIds.Storyteller, "{}", "NPC-storyteller"); + Assert.Equal(false, envelope.RequireAliveColonist); + Assert.Equal(false, envelope.EffectiveRequireAliveColonist); + } + + [Fact] + public void StorytellerMemoryPromptFormatter_FormatsRecordsAndHandlesEmptyInputs() + { + Assert.Equal(string.Empty, StorytellerMemoryPromptFormatter.FormatRecentIncidents(new List(), 5)); + Assert.Equal(string.Empty, StorytellerMemoryPromptFormatter.FormatRecentDialogues(new List(), 5)); + Assert.Equal(string.Empty, StorytellerMemoryPromptFormatter.FormatPlayerReactions(new List(), 5)); + Assert.Equal(string.Empty, StorytellerMemoryPromptFormatter.FormatActiveChains(new List())); + + var incidents = new List + { + new() { Label = "Raid", TriggeredTick = 0, MapName = "Base" }, + new() { Label = "Eclipse", TriggeredTick = 60000, MapName = "Base" } + }; + string incText = StorytellerMemoryPromptFormatter.FormatRecentIncidents(incidents, 1); + Assert.DoesNotContain("Raid", incText); + Assert.Contains("Eclipse", incText); + Assert.Contains("Day 2", incText); + + var dialogues = new List + { + new() { role = "user", content = "Hello", tick = 0 }, + new() { role = "assistant", content = "Welcome", tick = 60000 } + }; + string dlgText = StorytellerMemoryPromptFormatter.FormatRecentDialogues(dialogues, 5); + Assert.Contains("Player: Hello", dlgText); + Assert.Contains("Narrator: Welcome", dlgText); + + var reactions = new List + { + new() { incidentLabel = "Raid", reactionLabel = "Excited", tick = 60000 } + }; + string reactText = StorytellerMemoryPromptFormatter.FormatPlayerReactions(reactions, 5); + Assert.Contains("[Player Reaction Records]", reactText); + Assert.Contains("Raid", reactText); + Assert.Contains("Excited", reactText); + + var chains = new List + { + new() + { + chainId = "pirate_arc", + currentStep = 1, + totalSteps = 3, + nextHint = "retaliation", + steps = new List { new() { incidentDefName = "RaidEnemy" } } + } + }; + string chainText = StorytellerMemoryPromptFormatter.FormatActiveChains(chains); + Assert.Contains("pirate_arc", chainText); + Assert.Contains("RaidEnemy", chainText); + Assert.Contains("retaliation", chainText); + } + } +} diff --git a/Tests/Contracts/StorytellerIncidentPolicyContracts.cs b/Tests/Contracts/StorytellerIncidentPolicyContracts.cs index f5237c9..5c54e62 100644 --- a/Tests/Contracts/StorytellerIncidentPolicyContracts.cs +++ b/Tests/Contracts/StorytellerIncidentPolicyContracts.cs @@ -212,6 +212,7 @@ public void Nonhostile_faction_and_unknown_strategy_hints_do_not_override_defaul private static void PawnLookupOrderRemainsStable() { +#pragma warning disable CS0618 int enumerations = 0; IEnumerable Track(params TestPawn[] pawns) { @@ -274,6 +275,7 @@ IEnumerable Track(params TestPawn[] pawns) Find.CurrentMap = null; Find.WorldPawns.AllPawnsAlive.Clear(); } +#pragma warning restore CS0618 } private static void NotificationPolicyRemainsNarrow() diff --git a/Tests/RimMindStoryteller.Tests.csproj b/Tests/RimMindStoryteller.Tests.csproj index 3c881b8..1e40b82 100644 --- a/Tests/RimMindStoryteller.Tests.csproj +++ b/Tests/RimMindStoryteller.Tests.csproj @@ -14,7 +14,7 @@ - + @@ -25,6 +25,8 @@ + + diff --git a/Tests/VerseStubs.cs b/Tests/VerseStubs.cs index ce63e64..647cffc 100644 --- a/Tests/VerseStubs.cs +++ b/Tests/VerseStubs.cs @@ -1,12 +1,23 @@ using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; +using System.Threading; +using Newtonsoft.Json.Linq; using RimMind.Application.Common.Interfaces.Context; +using RimMind.Application.Features.Context; +using RimMind.Application.Features.Json; +using RimMind.Application.Features.Prompt; +using RimMind.Domain.Llm; +using RimMind.Domain.ValueObjects; + +[assembly: Xunit.CollectionBehavior(DisableTestParallelization = true)] namespace Verse { public static class Extensions { + public static readonly HashSet UntranslatableKeys = new HashSet(); public static string Translate(this string key, params object[] args) => key; public static bool CanTranslate(this string key) => false; public static string TranslateSimple(this string key) => key; @@ -17,8 +28,38 @@ public class Pawn { public int thingIDNumber; public string ThingID => $"Pawn_{t public class WorldPawns { public List AllPawnsAlive { get; } = new(); } public class MapPawns { public List FreeColonists { get; } = new(); } public class Map : RimWorld.IIncidentTarget { public MapPawns mapPawns { get; } = new(); } + public class TickManager { public int TicksGame; } + public class Window + { + public bool doCloseButton, doCloseX, closeOnAccept, forcePause, closeOnClickedOutside, + absorbInputAroundWindow, draggable; + public virtual UnityEngine.Vector2 InitialSize => default; + public virtual void PostClose() { } + public virtual void DoWindowContents(UnityEngine.Rect rect) { } + public void Close() => PostClose(); + } + public static class Widgets + { + public static string? NextText; + public static bool ClickSend; + public static readonly List Labels = new(); + public static void Label(UnityEngine.Rect rect, string text) => Labels.Add(text); + public static string TextField(UnityEngine.Rect rect, string text) + { + string result = NextText ?? text; + NextText = null; + return result; + } + public static bool ButtonText(UnityEngine.Rect rect, string text) + { + bool click = ClickSend; + ClickSend = false; + return click; + } + } public static class Find { + public static TickManager TickManager { get; } = new(); public static WorldPawns WorldPawns { get; } = new(); public static Map? CurrentMap { get; set; } public static RimWorld.Storyteller? Storyteller { get; set; } @@ -133,10 +174,180 @@ public FiringIncident(IncidentDef def, StorytellerComp source, IncidentParms par } } +namespace UnityEngine +{ + public struct Vector2 + { + public float x, y; + public Vector2(float x, float y) { this.x = x; this.y = y; } + public static Vector2 zero => default; + } + public struct Rect + { + public float x, y, width, height; + public Rect(float x, float y, float width, float height) + { this.x = x; this.y = y; this.width = width; this.height = height; } + } + public struct Color + { + public Color(float r, float g, float b, float a = 1) { } + public static Color white => default; + } +} + +namespace RimMind.Presentation.UI +{ + public readonly struct ChatWindowMessage + { + public ChatWindowMessage(string role, string content, string? senderPrefix = null) + { + Role = role ?? string.Empty; + Content = content ?? string.Empty; + SenderPrefix = senderPrefix; + } + public string Role { get; } + public string Content { get; } + public string? SenderPrefix { get; } + } + + public abstract class RimMindChatWindowBase : Verse.Window + { + private readonly List _messages = new(); + private readonly ConcurrentQueue _mainThreadUpdates = new(); + private readonly CancellationTokenSource _lifetime = new(); + private string _inputText = string.Empty; + private bool _isWaiting; + private bool _closed; + + protected RimMindChatWindowBase() + { + doCloseButton = false; + doCloseX = true; + closeOnAccept = false; + forcePause = false; + closeOnClickedOutside = false; + absorbInputAroundWindow = false; + draggable = true; + } + + public override UnityEngine.Vector2 InitialSize => new UnityEngine.Vector2(480f, 540f); + protected CancellationToken LifetimeToken => _lifetime.Token; + protected bool IsClosed => _closed; + protected bool IsWaiting => _isWaiting; + public IReadOnlyList Messages => _messages; + + protected virtual UnityEngine.Color HeaderColor => new UnityEngine.Color(0.8f, 0.95f, 1f); + protected abstract string GetTitle(); + protected abstract string GetWaitingText(); + protected abstract string GetSendButtonLabel(); + protected abstract string GetPrefixForRole(string role); + protected abstract void OnSubmitUserMessage(string trimmedInput); + protected virtual bool ValidateCanStayOpen() => true; + protected virtual void OnMessageAppended(ChatWindowMessage message) { } + + protected void AppendMessage(string role, string content, string? senderPrefix = null, bool notifyHook = true) + { + if (string.IsNullOrEmpty(content)) return; + var msg = new ChatWindowMessage(role, content, senderPrefix); + _messages.Add(msg); + if (notifyHook) OnMessageAppended(msg); + } + + protected void PostReply(string role, string content, bool clearWaiting = true, string? senderPrefix = null) + { + if (_closed) return; + _mainThreadUpdates.Enqueue(() => + { + if (_closed) return; + if (clearWaiting) _isWaiting = false; + if (!string.IsNullOrEmpty(content)) AppendMessage(role, content, senderPrefix); + }); + } + + protected void SetWaiting(bool waiting) => _isWaiting = waiting; + + public override void PostClose() + { + if (!_closed) + { + _closed = true; + _isWaiting = false; + try { _lifetime.Cancel(); } catch (ObjectDisposedException) { } + try { _lifetime.Dispose(); } catch (ObjectDisposedException) { } + } + base.PostClose(); + } + + public override void DoWindowContents(UnityEngine.Rect inRect) + { + if (!ValidateCanStayOpen()) + { + Close(); + return; + } + while (_mainThreadUpdates.TryDequeue(out var update)) + update?.Invoke(); + + Verse.Widgets.Label(inRect, GetTitle()); + if (_isWaiting) Verse.Widgets.Label(inRect, GetWaitingText()); + _inputText = Verse.Widgets.TextField(inRect, _inputText ?? string.Empty); + bool sendClicked = Verse.Widgets.ButtonText(inRect, GetSendButtonLabel()); + if (sendClicked && !_isWaiting && !string.IsNullOrWhiteSpace(_inputText)) + { + string trimmed = _inputText.Trim(); + _inputText = string.Empty; + OnSubmitUserMessage(trimmed); + } + } + } +} + namespace RimMind.Presentation.Api { public static class RimMindAPI { + public static bool Configured = true; + public static readonly List<(LlmRequestEnvelope Envelope, Action> Complete)> Sent = new(); + + public static class Settings + { + public static bool IsConfigured() => Configured; + } + + public static class Request + { + public static void Send(LlmRequestEnvelope envelope, Action> onComplete) + => Sent.Add((envelope, onComplete)); + } + + public static class Text + { + public static string TrOr(string key, string fallback, params object[] args) + => RimMindText.TrOr(key, fallback, args); + public static string Tr(string key, params object[] args) + => RimMindText.Tr(key, args); + public static string WrapForMote(string? text, int maxCharsPerLine = MoteTextFormatter.DefaultMaxCharsPerLine) + => MoteTextFormatter.WrapForMote(text, maxCharsPerLine); + } + + public static class Json + { + public static string StripThinkingAndCodeFences(string? raw) + => LlmPayloadParser.StripThinkingAndCodeFences(raw); + public static string? ExtractJsonPayload(string? raw) + => LlmPayloadParser.ExtractJsonPayload(raw); + public static bool TryParseJObjectWithRepair(string? raw, out JObject? obj) + => LlmPayloadParser.TryParseJObjectWithRepair(raw, out obj); + public static bool TryDeserializeWithRepair(string? raw, out T? value) where T : class + => LlmPayloadParser.TryDeserializeWithRepair(raw, out value); + public static IReadOnlyList ParsePseudoFunctionCalls(string? raw) + => LlmPayloadParser.ParsePseudoFunctionCalls(raw); + public static string? TryRepairJson(string input) + => JsonRepairer.TryRepair(input); + public static string? TryRepairTruncatedJson(string input) + => JsonRepairer.TryRepairTruncatedJson(input); + } + public static class MainThreadSnapshot { public static RimMind.Application.Common.Threading.MainThreadReader Reader { get; set; } = @@ -158,11 +369,17 @@ public static class Context { public static string ScenarioStoryteller => RimMind.Application.Common.Models.Context.ScenarioIds.Storyteller; public static TestContextRegistry ContextKeys { get; } = new(); + public static void RegisterScenario(ScenarioDescriptor descriptor) + => ScenarioRegistry.Register(descriptor); } public sealed class TestContextRegistry { public List Definitions { get; } = new(); - public void Register(ContextProviderDef definition) => Definitions.Add(definition); + public void Register(ContextProviderDef definition) + { + Definitions.RemoveAll(d => d.Key == definition.Key); + Definitions.Add(definition); + } } public static class Prompt { @@ -173,6 +390,11 @@ public static class Memory { public static List Narrations { get; } = new(); public static IReadOnlyList GetRecentNarrations(int count) => Narrations.Take(count).ToList(); + public static bool AddNarratorMemory(string content, int tick, float importance = 0.3f) + { + Narrations.Add(new Narration { Tick = tick, Content = content }); + return true; + } } public sealed class Narration { public int Tick; public string Content = ""; } public static class Bus @@ -213,6 +435,45 @@ public static class RimMindPawnLookup namespace RimMind.Storyteller.Memory { + public class IncidentHistoryRecord + { + public string Label = string.Empty; + public int TriggeredTick; + public string MapName = string.Empty; + } + + public class DialogueRecord + { + public string role = string.Empty; + public string content = string.Empty; + public int tick; + } + + public class PlayerReactionRecord + { + public string incidentDefName = string.Empty; + public string incidentLabel = string.Empty; + public string reaction = string.Empty; + public string reactionLabel = string.Empty; + public int tick; + } + + public class ChainStep + { + public string incidentDefName = string.Empty; + public int triggeredTick; + public bool completed; + } + + public class EventChain + { + public string chainId = string.Empty; + public List steps = new(); + public int currentStep; + public int totalSteps; + public string nextHint = string.Empty; + } + // World-backed data is seeded at the external boundary; real provider delegates format and filter it. public sealed class StorytellerMemory { @@ -223,6 +484,9 @@ public sealed class StorytellerMemory public string Dialogue = ""; public string IncidentSummary = ""; public string ActiveChains = ""; + public List DialogueRecords { get; } = new(); + public void RecordDialogue(string role, string content, int tick) + => DialogueRecords.Add(new DialogueRecord { role = role, content = content, tick = tick }); public string GetRecentDialogueSummary(int count) => Dialogue; public string GetRecentSummary(int count) => IncidentSummary; public string GetActiveChainsSummary() => ActiveChains;