From 11b1036c16315c03fabad8e19d42f16bbc56979e Mon Sep 17 00:00:00 2001 From: mcocdaa <2021137961@qq.com> Date: Sat, 7 Nov 2026 08:54:15 +0100 Subject: [PATCH 1/2] chore(release): upgrade About.xml Steam BBCode and clean release package exclusions docs(about): expand mod description with features and mod list Rewrite the About.xml description into a structured Steam-style page covering the v2.0 clean architecture, 4-Zone KV-cache engine, core features, sub-mod dependency table, supported API endpoints, and FAQ. Also exclude test projects and repo config files from the release package to keep the published archive clean. --- .github/workflows/release.yml | 7 ++++ About/About.xml | 68 ++++++++++++++++++++++++++++++++++- 2 files changed, 74 insertions(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a1d6f3e..dac6e57 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -156,11 +156,18 @@ jobs: --exclude='.github/' \ --exclude='Source/' \ --exclude='Tests/' \ + --exclude='ArchTests/' \ + --exclude='IntegrationTests/' \ + --exclude='TestSupport/' \ --exclude='.claude/' \ --exclude='.trae/' \ --exclude='docs/' \ --exclude='*.csproj' \ --exclude='*.sln' \ + --exclude='Directory.Build.props' \ + --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 a7ab504..6b60cfb 100644 --- a/About/About.xml +++ b/About/About.xml @@ -8,7 +8,73 @@
  • 1.6
  • 1.7
  • - Infrastructure for AI-powered RimWorld mods. Provides LLM client, async request queue, game context builders, and debug tooling. Required by all RimMind suite components. v2.0 uses a three-DLL loading architecture (0_RimMindDomain, 1_RimMindApplication, 2_RimMindCore) for modular assembly loading. [v2.0 BREAKING CHANGES] Save games from v1.x are NOT compatible with v2.0. + [h1]RimMind - Core (v2.0)[/h1] +The foundational LLM runtime, Clean Architecture engine, and public API bedrock of the RimMind suite. Provides the 4-Zone KV-Cache context orchestrator, asynchronous priority request queue, native ToolCall contract registry, 3-Tier Agent Autonomy governance, and the F8 Central Debug Hub. Required by all RimMind sub-modules. + +[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 Three-DLL Clean Architecture[/b]: Strictly decoupled assembly layering ([code]0_RimMindDomain[/code], [code]1_RimMindApplication[/code], [code]2_RimMindCore[/code]) with zero cross-mod internal coupling. Note: v1.x saves are not compatible with v2.0. +[*][b]4-Zone KV-Cache Engine (80%+ Hit Rate)[/b]: Isolates static world rules (Zone 1) and permanent pawn profiles (Zone 2) from dynamic history (Zone 3) and volatile environment state (Zone 4), cutting token latency and API billing by over 75%. +[/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 from static state machines 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][b]RimMind-Core[/b][/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]RimMind-Advisor[/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]4-Zone KV-Cache Context Orchestrator[/b] - Automatically packages game state (pawn mood, health, skills, gear, colony wealth, threat levels, seasons, weather) across hierarchical L0 to L5 layers with 80%+ prefix cache hit efficiency. +[*][b]Asynchronous Priority Request Queue[/b] - Non-blocking background HTTP dispatching with priority scheduling, per-feature cooldowns, exponential retry backoff, circuit breaker protection, and main-thread callback marshaling. +[*][b]Native ToolCall Registry & Progressive Discovery[/b] - Type-safe function calling with on-demand [code]query_tool_help[/code] schema inspection, eliminating raw JSON leakage and markdown hallucinations. +[*][b]Three-Tier Agent Autonomy Governance[/b] - Fine-grained action gating across 5 domains ([i]Survival, Work, Social, Colony, Governance[/i]) and 3 autonomy levels ([i]Auto, AutoWithNotify, RecommendOnly[/i]). +[*][b]Pawn Liveness & Lifecycle Guard[/b] - Strict [code]RimMindPawnLookup[/code] validation ensuring dead, kidnapped, off-map, or imprisoned pawns never trigger ghost LLM requests. +[*][b]F8 Central Debug & Inspection Hub[/b] - Press [b]F8[/b] in-game to run live API latency pings, inspect Zone 1 to 4 prompt payloads, monitor KV-cache hit rates, and manage queues in real time. +[/list] + +[h2]Supported API Endpoints[/h2] +[table] +[tr][th]Service[/th][th]Endpoint[/th][th]Description[/th][/tr] +[tr][td]DeepSeek[/td][td]https://api.deepseek.com/v1[/td][td]Recommended: deepseek-chat (high intelligence & low cost)[/td][/tr] +[tr][td]OpenAI[/td][td]https://api.openai.com/v1[/td][td]Models such as gpt-4o-mini and gpt-4o[/td][/tr] +[tr][td]Ollama / vLLM (Local)[/td][td]http://localhost:11434/v1[/td][td]Self-hosted local models (qwen2.5:7b, llama3.1:8b) with serial queue mode[/td][/tr] +[tr][td]Player2[/td][td]Auto-detected / Remote API[/td][td]Player2 local client application or cloud API[/td][/tr] +[tr][td]Extension: ModelService[/td][td]Multi-Node / Failover[/td][td]Anthropic Claude, OpenCode Go, Codex/Sub2API/NewAPI local gateways[/td][/tr] +[/table] + +[h2]Frequently Asked Questions[/h2] +[b]Q: Will RimMind affect my game frame rate (TPS/FPS)?[/b] +A: No. All network I/O and prompt serialization run on background threads, and high-frequency checks are strictly throttled. + +[b]Q: Is my API Key secure?[/b] +A: Yes. API Keys are stored locally in your RimWorld config folder and are never logged or transmitted anywhere except your configured LLM endpoint. + +[b]Q: Which models are recommended?[/b] +A: [code]deepseek-chat[/code] and [code]gpt-4o-mini[/code] offer the best balance of speed, tool-calling accuracy, and KV-cache cost savings. + +[h2]Acknowledgements & References[/h2] +Special thanks to RimTalk, RimTalk-ExpandActions, RimTalk-ExpandMemory, RimChat, NewRatkin, and Vanilla Expanded Framework for technical inspiration during development.
  • brrainz.harmony From cecc4c7e791145e472a5fbfabc75e73a9ab0c99d Mon Sep 17 00:00:00 2001 From: mcocdaa Date: Mon, 16 Nov 2026 06:57:34 +0100 Subject: [PATCH 2/2] feat(core): add agent rollout UI, autonomy domains, audio/reasoning ports, and tool fidelity guards feat: add agent rollout tracing, threat perception, and consolidated debug center - Add AgentRolloutModelBuilder and TraceContentFormatter to aggregate multi-turn agent trajectories with L0-L4 prefix-reuse tracking and structured JSON/XML formatting; extend AIRequestTraceLog with metadata, layer, and action-outcome recording. - Introduce ThreatScanner and wire hostile detection into PawnPerceiver, CombatPerceptionSource, and PawnDataExtractor so agents perceive nearby raiders and manhunters instead of always reporting zero threats. - Add ReasoningEffort enum, ContentFiltered/ClientQuotaOrAuthFailure error codes, and speech synthesis/recognition extension ports (ISpeechSynthesizer, ISpeechRecognizer) as vendor-agnostic domain contracts. - Consolidate debug center pages into 5 tabs (overview, agents, ai_requests, capabilities, settings) with sub-tab routing and legacy route aliases. - Add agent permissions panel with Work Only/Default/Full Auto presets and a new WorkPriorityModification autonomy domain (disabled by default). - Harden pawn job execution with StartJobVerified, job queue operations, and food/plant fallbacks; stop silently defaulting argument-less pawn.job to force_rest and reject mentally broken pawns for behavior actions. - Improve decision parsing to recover truncated Action JSON, raw JSON tool objects, and to= commentary tool calls. - Add PlaythroughPlayerSimulation harness and expand contract tests for rollouts, threat scanning, endpoint invariants, and audio ports. - Update default model name to deepseek-flash across settings, docs, and localization. --- About/About.xml | 4 +- .../ChineseSimplified/Keyed/RimMind_Core.xml | 74 +- Languages/English/Keyed/RimMind_Core.xml | 74 +- README.md | 3 +- README_zh.md | 3 +- .../Interfaces/Audio/ISpeechRecognizer.cs | 21 + .../Interfaces/Audio/ISpeechSynthesizer.cs | 21 + .../Interfaces/Context/PawnExtractedData.cs | 1 + .../Interfaces/Internal/IAIRequestTraceLog.cs | 5 + .../Models/Debug/AIRequestTraceEntry.cs | 62 +- .../Models/Debug/AgentRolloutModelBuilder.cs | 404 ++ .../Models/Debug/TraceContentFormatter.cs | 166 + .../Models/Mechanisms/MechanismWriteArgs.cs | 1 + .../Features/Agent/DecisionProcessor.cs | 28 +- .../Agent/Modes/DecisionExampleData.cs | 14 +- .../Agent/Modes/ThinkStrategyHelper.cs | 176 +- .../Features/Llm/LlmRequestEnvelopeBuilder.cs | 8 + .../Unified/CircuitBreakerMiddleware.cs | 3 +- .../Unified/ClientInvokeMiddleware.cs | 5 + .../Pipeline/Unified/RetryMiddleware.cs | 2 + .../Unified/ToolCallDispatchMiddleware.cs | 6 +- .../Requests/RequestSubmissionService.cs | 76 +- .../Agent/Policies/AgentAutonomyPolicy.cs | 30 + .../Domain/Agent/Policies/AutonomyDomain.cs | 8 +- Source/Domain/Audio/AudioContainerFormat.cs | 13 + .../Domain/Audio/SpeechRecognitionRequest.cs | 17 + .../Domain/Audio/SpeechRecognitionResult.cs | 13 + Source/Domain/Audio/SpeechSynthesisRequest.cs | 16 + Source/Domain/Audio/SpeechSynthesisResult.cs | 17 + Source/Domain/Llm/LlmRequestEnvelope.cs | 53 + Source/Domain/Llm/ReasoningEffort.cs | 28 + .../Domain/ValueObjects/RimMindErrorCode.cs | 2 + Source/Domain/ValueObjects/RimMindErrors.cs | 12 + .../Agent/MechanismActionExecutor.cs | 89 +- .../Mechanisms/GameMechanismBaseNoDef.cs | 11 + .../Mechanisms/MechanismToolHandler.cs | 37 +- .../Mechanisms/Pawn/Draft/DraftMechanism.cs | 10 +- .../Pawn/Interaction/InteractionMechanism.cs | 57 +- .../Pawn/Job/JobActionDispatcher.cs | 650 ++- .../Mechanisms/Pawn/Job/JobDocs.cs | 6 +- .../Mechanisms/Pawn/Job/JobMechanism.cs | 71 +- .../Pawn/MentalState/MentalStateMechanism.cs | 4 +- .../Mechanisms/Pawn/Work/WorkMechanism.cs | 157 +- .../Patches/AddAgentCompToHumanlikePatch.cs | 2 + .../Patches/ThinkNode_RimMindAgent.cs | 3 + .../OpenAI/OpenAIClient.RequestBuilding.cs | 1 + .../Services/Clients/OpenAI/OpenAIClient.cs | 228 +- .../Clients/OpenAI/OpenAIRequestSerializer.cs | 54 +- .../Clients/Shared/ClientExceptionMapper.cs | 17 + .../UI/AgentsPage/AgentDetailPanelDrawer.cs | 152 + .../UI/AgentsPage/AgentPageLayout.cs | 27 +- .../UI/AgentsPage/AgentsPageDrawer.cs | 1 + .../AICoreDebugActions.Autotests.cs | 37 +- .../UI/DebugActions/BehaviorAutotestRunner.cs | 79 +- .../PlaythroughPlayerSimulation.cs | 609 ++ .../ShowcaseSceneCaptureRunner.cs | 8 +- .../DebugActions/TenDayPlaythroughRunner.cs | 5176 +++++------------ .../UI/DebugCenter/DebugCenterNavigation.cs | 73 +- .../UI/DebugCenter/DebugCenterPageRegistry.cs | 22 +- .../Pages/AIRequestsDebugCenterPageDrawer.cs | 883 ++- .../CapabilitiesDebugCenterPageDrawer.cs | 320 + .../Pages/OverviewDebugCenterPageDrawer.cs | 29 +- .../ContextKeysDebugTableModelBuilder.cs | 20 +- .../UI/DebugTables/DebugTableModels.cs | 21 +- .../MechanismsDebugTableModelBuilder.cs | 20 +- .../ToolRegistryDebugTableModelBuilder.cs | 146 + .../UI/Framework/RimMindTableDrawer.cs | 15 +- .../UI/Layout/LayoutAutotestRunner.cs | 67 +- .../UI/Layout/UiCaptureRunner.cs | 11 +- .../UI/Layout/UiCaptureScenes.cs | 107 + .../UI/Layout/UiInteractionDriver.cs | 54 +- .../UI/MainTabWindow_RimMindHub.cs | 18 +- .../Infrastructure/UI/Window_AgentFlowLab.cs | 5 +- .../UI/Window_AgentModeDebug.cs | 7 +- .../UI/Window_AgentProgressFloat.cs | 5 +- .../UI/Window_AgentStateDebug.cs | 17 +- .../UI/Window_ContextKeyDebug.cs | 4 +- .../UI/Window_MechanismStatus.cs | 4 +- Source/Infrastructure/UI/Window_RequestLog.cs | 4 +- .../Infrastructure/UI/Window_ToolCallDebug.cs | 4 +- .../Infrastructure/Verse/AIRequestTraceLog.cs | 195 +- Source/Infrastructure/Verse/CompPawnAgent.cs | 19 +- .../Infrastructure/Verse/ITab_Pawn_Agent.cs | 3 +- .../Presentation/Agent/MapContextBuilder.cs | 125 +- Source/Presentation/Agent/PawnAgent.cs | 4 +- .../Agent/PawnContextBuilder.Extract.cs | 7 +- .../Presentation/Agent/PawnDataExtractor.cs | 14 +- Source/Presentation/Agent/PawnPerceiver.cs | 12 + Source/Presentation/Agent/PawnThinker.cs | 88 +- .../Perception/CombatPerceptionSource.cs | 14 + Source/Presentation/Agent/ThreatScanner.cs | 49 + .../Runtime/RimMindCompositionRoot.cs | 2 + .../Settings/RimMindCoreSettings.cs | 2 +- Source/Presentation/UI/ApiTabDrawer.cs | 4 +- .../Contracts/AgentAutonomyPolicyContracts.cs | 24 + .../AgentDecisionParamAdaptationContracts.cs | 97 + ...AgentRolloutAndTraceFormattingContracts.cs | 237 + Tests/Contracts/DomainApplicationContracts.cs | 45 + .../EndpointInvariantAndAudioContracts.cs | 382 ++ Tests/Contracts/P5UiAndHarnessContracts.cs | 27 +- Tests/Contracts/ThreatScannerContracts.cs | 49 + Tests/Contracts/ToolCallDepthContract.cs | 6 +- .../DebugCenter/DebugCenterPageDrawerStubs.cs | 4 + Tests/RimMindCore.Tests.csproj | 1 + Tests/VerseStubs.cs | 15 + 105 files changed, 7769 insertions(+), 4364 deletions(-) create mode 100644 Source/Application/Common/Interfaces/Audio/ISpeechRecognizer.cs create mode 100644 Source/Application/Common/Interfaces/Audio/ISpeechSynthesizer.cs create mode 100644 Source/Application/Common/Models/Debug/AgentRolloutModelBuilder.cs create mode 100644 Source/Application/Common/Models/Debug/TraceContentFormatter.cs create mode 100644 Source/Domain/Audio/AudioContainerFormat.cs create mode 100644 Source/Domain/Audio/SpeechRecognitionRequest.cs create mode 100644 Source/Domain/Audio/SpeechRecognitionResult.cs create mode 100644 Source/Domain/Audio/SpeechSynthesisRequest.cs create mode 100644 Source/Domain/Audio/SpeechSynthesisResult.cs create mode 100644 Source/Domain/Llm/ReasoningEffort.cs create mode 100644 Source/Infrastructure/UI/DebugActions/PlaythroughPlayerSimulation.cs create mode 100644 Source/Infrastructure/UI/DebugCenter/Pages/CapabilitiesDebugCenterPageDrawer.cs create mode 100644 Source/Infrastructure/UI/DebugTables/ToolRegistryDebugTableModelBuilder.cs create mode 100644 Source/Presentation/Agent/ThreatScanner.cs create mode 100644 Tests/Contracts/AgentDecisionParamAdaptationContracts.cs create mode 100644 Tests/Contracts/AgentRolloutAndTraceFormattingContracts.cs create mode 100644 Tests/Contracts/EndpointInvariantAndAudioContracts.cs create mode 100644 Tests/Contracts/ThreatScannerContracts.cs diff --git a/About/About.xml b/About/About.xml index 6b60cfb..ddedce0 100644 --- a/About/About.xml +++ b/About/About.xml @@ -56,7 +56,7 @@ RimMind is an enterprise-grade, AI-powered RimWorld mod suite. Integrated with L [h2]Supported API Endpoints[/h2] [table] [tr][th]Service[/th][th]Endpoint[/th][th]Description[/th][/tr] -[tr][td]DeepSeek[/td][td]https://api.deepseek.com/v1[/td][td]Recommended: deepseek-chat (high intelligence & low cost)[/td][/tr] +[tr][td]DeepSeek[/td][td]https://api.deepseek.com/v1[/td][td]Recommended: deepseek-flash / deepseek-v4-pro (high intelligence & low cost)[/td][/tr] [tr][td]OpenAI[/td][td]https://api.openai.com/v1[/td][td]Models such as gpt-4o-mini and gpt-4o[/td][/tr] [tr][td]Ollama / vLLM (Local)[/td][td]http://localhost:11434/v1[/td][td]Self-hosted local models (qwen2.5:7b, llama3.1:8b) with serial queue mode[/td][/tr] [tr][td]Player2[/td][td]Auto-detected / Remote API[/td][td]Player2 local client application or cloud API[/td][/tr] @@ -71,7 +71,7 @@ A: No. All network I/O and prompt serialization run on background threads, and h A: Yes. API Keys are stored locally in your RimWorld config folder and are never logged or transmitted anywhere except your configured LLM endpoint. [b]Q: Which models are recommended?[/b] -A: [code]deepseek-chat[/code] and [code]gpt-4o-mini[/code] offer the best balance of speed, tool-calling accuracy, and KV-cache cost savings. +A: [code]deepseek-flash[/code], [code]deepseek-v4-pro[/code], and [code]gpt-4o-mini[/code] offer the best balance of speed, tool-calling accuracy, and KV-cache cost savings. [h2]Acknowledgements & References[/h2] Special thanks to RimTalk, RimTalk-ExpandActions, RimTalk-ExpandMemory, RimChat, NewRatkin, and Vanilla Expanded Framework for technical inspiration during development. diff --git a/Languages/ChineseSimplified/Keyed/RimMind_Core.xml b/Languages/ChineseSimplified/Keyed/RimMind_Core.xml index c753580..a36f2c1 100644 --- a/Languages/ChineseSimplified/Keyed/RimMind_Core.xml +++ b/Languages/ChineseSimplified/Keyed/RimMind_Core.xml @@ -34,7 +34,7 @@ API 端点 AI 服务的 API 地址。支持 OpenAI 兼容接口(如 DeepSeek、本地 Ollama 等)。 模型名称 - 要使用的模型 ID,如 deepseek-v4-flash、gpt-4o-mini 等。 + 要使用的模型 ID,如 deepseek-flash、deepseek-v4-pro、gpt-4o-mini 等。 备用 API 容灾节点列表 (Failover List) 按顺序排列的备用 API 节点列表。当主 API 节点请求失败(如 HTTP 503/502/429、超时或空响应)时,RimMind 会在单次请求内自动平滑切换至列表中的下一个可用备用节点,并对故障节点执行 60 秒临时隔离。 + OpenCode Go 备用 @@ -338,6 +338,7 @@ 战斗中:{0} 未在战斗中 人口:{0} 财富:{1} 威胁:{2} + 附近的活跃威胁:{0}。考虑征召迎战、躲入室内或保持距离。 目标:{0} {0} 切换为 {1} 模式 @@ -510,6 +511,18 @@ 模型 摘要 请求 + 工具 + 分类 + 所属模组 + 类型 + 显示名称 + 权限域 + 操作数 + 支持操作 + 风险等级 + 分数 + 层级 + 缓存域 暂无调试记录。 等待中 流式返回中 @@ -833,4 +846,63 @@ 生理与健康状态完备:包含疼痛、出血、严重疾病严重度过滤。 空间与路径闭环:由底层 C# JobDispatcher 自动解析目标寻路,无需在 Prompt 中堆砌全图坐标。 社交关系支持:直接关系人与伴侣信息已包含。 + AI 轨迹与请求 + 能力与机制 + Agent 决策轨迹 + 查看多轮有状态 Agent 决策轨迹,包含 L0-L4 上下文层前缀复用标记、思考过程、工具调用与游戏内真实落盘结果。 + 临时单次请求 + 查看非 Agent 的单次临时请求(对话、人格、叙事者、顾问及探测),支持多维筛选与 JSON/XML 结构化展示。 + 全部 + 模块: 全部 + 场景: 全部 + 对象: 全部 + 按殖民者 Agent 或请求发起对象筛选。 + 状态: 全部 + 搜索提示词、响应内容、工具名称、参数或报错信息。 + 重置 + 包含轨迹单轮 + 在此列表中同时显示属于 Agent 轨迹的单轮底层请求。 + 当前筛选条件下暂无 Agent 决策轨迹记录。 + 轨迹摘要 + 游戏内动作执行结果 + 已生效 + 未生效 + 推理与思考 + 已注册的 LLM ToolCall 工具集,包含自治权限域、风险等级与 JSON 参数定义。 + 底层 RimWorld 游戏状态查询与修改机制注册表。 + 提示词模板可用的上下文变量与数据提供器。 + 分类: 全部 + 分类 + 按功能分类或作用域筛选能力项。 + 按名称、ID、权限域或描述关键字筛选。 + 元数据 + 功能说明 + 参数 JSON Schema + 自治权限控制 + 配置该殖民者 Agent 在各行为域下允许自动执行、需审批或完全禁用(禁用后对应工具不会暴露给该 Agent)。 + 仅工作 + 允许执行日常生存工作与资源标记,禁止放置任何建筑蓝图或篡改工作面板优先级。 + 均衡默认 + 恢复默认权限(生存与标记自动执行,清单/蓝图/高风险需审批,禁止修改工作优先级)。 + 全自动 + 允许自动执行生存、标记、清单、蓝图放置与工作优先级调整(高风险操作仍需审批)。 + 应用至全员 + 将当前殖民者的权限配置同步应用到所有活跃殖民者 Agent。 + 已将权限设置同步应用至所有活跃殖民者 Agent。 + 自动 + 审批 + 禁止 + 生存与工作调度 + 进食、休息、包扎、救援、移动,以及接取或排队非蓝图类日常工作。 + 资源采集标记 + 标记砍树、收获野生作物、开采矿脉或狩猎野生动物。 + 工作台生产清单 + 在各类工作台上新建、暂停、修改或删除制作清单。 + 建筑蓝图放置 + 放置床铺、家具、墙体、门、电力或房间规划蓝图。设为“禁止”可限制 AI 仅从事非蓝图工作。 + 高风险敏感操作 + 拆除已有建筑、逮捕人员等不可逆或高风险殖民地操作。 + 工作优先级表 + 修改殖民者工作面板的数字优先级(1-4)。默认禁止,防止 AI 覆盖玩家手动配置的工作表。 + 殖民地房间拓扑: [{0}] diff --git a/Languages/English/Keyed/RimMind_Core.xml b/Languages/English/Keyed/RimMind_Core.xml index 9200592..baa7a83 100644 --- a/Languages/English/Keyed/RimMind_Core.xml +++ b/Languages/English/Keyed/RimMind_Core.xml @@ -34,7 +34,7 @@ API Endpoint AI service API address. Supports OpenAI-compatible interfaces (e.g. DeepSeek, local Ollama). Model Name - The model ID to use, e.g. deepseek-v4-flash or gpt-4o-mini. + The model ID to use, e.g. deepseek-flash, deepseek-v4-pro, or gpt-4o-mini. Backup API Failover Nodes Ordered failover list of backup API endpoints. When the primary endpoint fails (HTTP 503/502/429, timeout, or empty response), RimMind automatically switches to the next healthy backup node and isolates the failing node for 60s. + OpenCode Go Backup @@ -338,6 +338,7 @@ Fighting: {0} Not in combat Pop: {0} Wealth: {1} Threats: {2} + ACTIVE THREATS NEAR YOU: {0}. Consider drafting to fight, fleeing indoors, or keeping distance. Target: {0} {0} switched to {1} mode @@ -510,6 +511,18 @@ Model Summary Request + Tool + Category + Owner Mod + Kind + Display Name + Domain + Ops + Operations + Risk + Score + Layer + Cache Scope No debug records are available. Waiting Streaming @@ -833,4 +846,63 @@ Physical & health state complete: includes pain, bleeding, and severe illness severity filtering. Spatial & pathing closed-loop: C# JobDispatcher resolves pathfinding automatically without dumping full-map coordinates into prompts. Social relations supported: direct relations and partner information included. + AI Traces + Capabilities + Agent Rollout + Inspect multi-turn stateful Agent rollouts with L0-L4 context prefix reuse, thoughts, tool calls, and in-game execution outcomes. + Ephemeral Requests + Inspect one-off non-agent LLM requests (Dialogue, Personality, Storyteller, Advisor, probes) with multi-dimensional filters and formatted JSON/XML. + All + Mod: All + Scenario: All + Actor: All + Filter by colonist agent or request initiator. + State: All + Search prompt, response, tool name, arguments, or error text. + Reset + Include Rollout Turns + Also list individual turns belonging to Agent Rollouts in this table. + No Agent rollouts recorded matching current filters. + Rollout Summary + In-Game Action Outcome + Executed + Rejected + Reasoning / Thought + Registered LLM ToolCalls with autonomy domains, risk levels, and JSON schemas. + Low-level RimWorld game state query and mutation mechanisms. + Prompt context variables and providers available to templates. + Category: All + Category + Filter capabilities by functional category or scope. + Filter by name, ID, domain, or description. + Metadata + Description + Parameters JSON Schema + Agent Permissions + Configure which action domains this colonist agent may execute autonomously, require approval for, or disable completely. + Work Only + Allow survival jobs and resource marking, but forbid placing any construction blueprints or changing Work Tab priorities. + Default + Restore balanced default permissions (auto survival/marking, approval for bills/blueprints/high-risk, work priority edits off). + Full Auto + Allow autonomous execution across survival, marking, bills, blueprints, and work priorities (high-risk still asks approval). + Apply to All + Copy this colonist's permission profile to all active colonist agents. + Applied permission settings to all active colonist agents. + Auto + Ask + Off + Survival & Jobs + Eating, resting, tending, rescuing, moving, and queueing/taking non-blueprint work jobs. + Resource Marking + Designating trees to chop, plants to harvest, ore to mine, or wildlife to hunt. + Worktable Bills + Creating, pausing, modifying, or deleting production bills on worktables. + Blueprint Placement + Placing furniture, beds, walls, doors, power, or room construction blueprints. Set to Off to restrict AI to non-blueprint labor. + High-Risk Actions + Deconstructing structures, arresting pawns, or destructive colony actions. + Work Priorities + Modifying colonist Work Tab numeric priorities (1-4). Off by default so AI does not overwrite player Work Tab settings. + ColonyRooms: [{0}] diff --git a/README.md b/README.md index edf0552..b215a60 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,7 @@ ### Core Capabilities - **4-Zone KV-Cache Orchestrator**: Separates invariant world rules (Zone 1) and permanent pawn profiles (Zone 2) from dynamic history (Zone 3) and volatile environment states (Zone 4), delivering an 80%+ prefix cache hit rate. - **Three-Tier Agent Autonomy Governance (`RimMindAPI.Autonomy`)**: Fine-grained action gating across 5 domains (`Survival`, `Work`, `Social`, `Colony`, `Governance`) and 3 autonomy levels (`Auto`, `AutoWithNotify`, `RecommendOnly`) coupled with `ToolManifest.RiskLevel` verification. +- **Vendor-Agnostic Engine Invariants (`ReasoningEffort`, `ContentFiltered`, `ISpeechSynthesizer`, `ISpeechRecognizer`)**: Expresses thinking latency budgets, content-moderation classification (no retry/circuit tripping), billing/auth failover (`ClientQuotaOrAuthFailure`), and orthogonal voice synthesis/recognition extension ports cleanly in Core's Domain & Application layers without vendor lock-in. - **Native ToolCall Registry & Progressive Schema Discovery (`query_tool_help`)**: Type-safe tool contracts with on-demand `QueryToolHelpTool` schema inspection, minimizing baseline prompt token footprint while eliminating markdown formatting errors. - **Primary + Backup Endpoint Failover & Priority Request Queue**: Thread-safe background HTTP/JSON dispatching with `BackupEndpointNode` automatic failover on HTTP 429/5xx, transport-aware `CircuitBreakerMiddleware`, and main-thread `RequestCompletionInbox` callback marshaling. - **Pawn Liveness & Lifecycle Guard (`RimMindPawnLookup`)**: Thread-safe pawn lookup and cache eviction (`IsActiveSpawnedColonist`, `IsEligibleColonist`, `IsActiveColonyAnimal`, `UncachePawn`) preventing ghost requests on dead, off-map, or imprisoned pawns. @@ -104,7 +105,7 @@ Configurable via **Options -> Mod Settings -> RimMind-Core**: |---|---|---| | **AI Provider** | `openai` | Supports OpenAI-compatible endpoints, DeepSeek, Player2, and extended gateways | | **API Endpoint & Backup Nodes** | `https://api.deepseek.com/v1` | Primary OpenAI Chat Completions URL plus optional `BackupEndpointNode` failover list | -| **Model Name** | `deepseek-chat` | Target LLM model identifier | +| **Model Name** | `deepseek-flash` | Target LLM model identifier (`deepseek-flash`, `deepseek-v4-pro`, `gpt-4o-mini`, etc.) | | **Agent Autonomy Policies** | Domain-specific | Per-domain (`Survival`, `Work`, `Social`, `Colony`, `Governance`) level (`Auto`, `AutoWithNotify`, `RecommendOnly`) | | **Max Concurrent Requests** | `3` | Maximum simultaneous requests sent to the LLM (1~10) | | **Request Timeout** | `60s` | Maximum wait time for LLM response before timeout (10s~180s) | diff --git a/README_zh.md b/README_zh.md index 862425f..9140e69 100644 --- a/README_zh.md +++ b/README_zh.md @@ -27,6 +27,7 @@ ### 核心特性 - **4-Zone KV-Cache 深度前缀优化**:将不变的世界观规则(Zone 1)与小人永久档案(Zone 2)固定在前缀,将历史(Zone 3)与易变的环境时间天气(Zone 4)隔离在报文末尾,实现 80%+ 的前缀缓存命中率。 - **三层智能体自治分级治理(`RimMindAPI.Autonomy`)**:按五大自治领域(`Survival` 生存、`Work` 劳作、`Social` 社交、`Colony` 殖民地、`Governance` 统治)与三档自治级别(`Auto` 自动执行、`AutoWithNotify` 自动并通知、`RecommendOnly` 仅建议审批)结合 `ToolManifest.RiskLevel` 精准门控智能体动作。 +- **供应商无关引擎核心不变量(`ReasoningEffort` / `ContentFiltered` / `ISpeechSynthesizer` / `ISpeechRecognizer`)**:在 Domain 与 Application 层纯抽象定义思考预算控制、内容风控不重试/不熔断语义、账单配额失效隔离及正交语音合成/识别扩展端口,零厂商硬编码。 - **原生 ToolCall 注册中心与渐进式工具发现(`query_tool_help`)**:强类型工具定义配合 `QueryToolHelpTool` 按需加载详细参数 Schema,大幅压缩常驻 Prompt Token 消耗并彻底杜绝 Markdown 格式解析错误。 - **主备端点容灾与异步优先级请求队列**:纯后台线程执行 HTTP/JSON 请求,内置 `BackupEndpointNode` 主备节点自动故障转移、仅针对真实传输故障计数的 `CircuitBreakerMiddleware` 断路器,并通过 `RequestCompletionInbox` 在主线程安全消费 Unity/Verse 副作用。 - **Pawn 存活与生命周期守卫(`RimMindPawnLookup`)**:提供线程安全的 Pawn 索引与销毁驱逐机制(`IsActiveSpawnedColonist`、`IsEligibleColonist`、`IsActiveColonyAnimal`、`UncachePawn`),杜绝阵亡、离图或囚犯 Pawn 产生幽灵请求。 @@ -104,7 +105,7 @@ flowchart TD |---|---|---| | **AI Provider** | `openai` | 支持 OpenAI 兼容端点、DeepSeek、Player2 与扩展网关 | | **API 端点与备用节点** | `https://api.deepseek.com/v1` | 主 OpenAI Chat Completions URL 及 `BackupEndpointNode` 自动故障转移列表 | -| **模型名称** | `deepseek-chat` | 目标大语言模型标识符 | +| **模型名称** | `deepseek-flash` | 目标大语言模型标识符(如 `deepseek-flash`、`deepseek-v4-pro`、`gpt-4o-mini`) | | **智能体自治策略** | 按领域分级 | 独立配置五大领域(`Survival`/`Work`/`Social`/`Colony`/`Governance`)的自治级别(`Auto`/`AutoWithNotify`/`RecommendOnly`) | | **最大并发请求数** | `3` | 同时发送给大模型的请求上限(1~10) | | **请求超时** | `60秒` | 等待 AI 响应的最大超时时限(10~180秒) | diff --git a/Source/Application/Common/Interfaces/Audio/ISpeechRecognizer.cs b/Source/Application/Common/Interfaces/Audio/ISpeechRecognizer.cs new file mode 100644 index 0000000..89cb150 --- /dev/null +++ b/Source/Application/Common/Interfaces/Audio/ISpeechRecognizer.cs @@ -0,0 +1,21 @@ +using System.Threading.Tasks; +using RimMind.Application.Common.Interfaces.Extension; +using RimMind.Domain.Audio; +using RimMind.Domain.Common; +using RimMind.Domain.ValueObjects; + +namespace RimMind.Application.Common.Interfaces.Audio +{ + /// + /// Orthogonal speech-to-text extension port registered via RimMindAPI.Ext.Get<ISpeechRecognizer>(). + /// Implementations must perform network/transcription work on background threads only. + /// + public interface ISpeechRecognizer : IExtension + { + string DisplayLabel { get; } + bool IsConfigured(); + + [ThreadAffinity(ThreadAffinityKind.BackgroundOnly)] + Task> TranscribeAsync(SpeechRecognitionRequest request); + } +} diff --git a/Source/Application/Common/Interfaces/Audio/ISpeechSynthesizer.cs b/Source/Application/Common/Interfaces/Audio/ISpeechSynthesizer.cs new file mode 100644 index 0000000..99c30b8 --- /dev/null +++ b/Source/Application/Common/Interfaces/Audio/ISpeechSynthesizer.cs @@ -0,0 +1,21 @@ +using System.Threading.Tasks; +using RimMind.Application.Common.Interfaces.Extension; +using RimMind.Domain.Audio; +using RimMind.Domain.Common; +using RimMind.Domain.ValueObjects; + +namespace RimMind.Application.Common.Interfaces.Audio +{ + /// + /// Orthogonal text-to-speech extension port registered via RimMindAPI.Ext.Get<ISpeechSynthesizer>(). + /// Implementations must perform network/synthesis work on background threads only. + /// + public interface ISpeechSynthesizer : IExtension + { + string DisplayLabel { get; } + bool IsConfigured(); + + [ThreadAffinity(ThreadAffinityKind.BackgroundOnly)] + Task> SynthesizeAsync(SpeechSynthesisRequest request); + } +} diff --git a/Source/Application/Common/Interfaces/Context/PawnExtractedData.cs b/Source/Application/Common/Interfaces/Context/PawnExtractedData.cs index 2b03c43..ba1e1bb 100644 --- a/Source/Application/Common/Interfaces/Context/PawnExtractedData.cs +++ b/Source/Application/Common/Interfaces/Context/PawnExtractedData.cs @@ -38,6 +38,7 @@ public class PawnExtractedData public int ColonistCount; public float ColonyWealth; public int ThreatCount; + public string ThreatSummary = ""; public List Hediffs = new List(); public bool InMentalState; public string MentalStateInspectLine = ""; diff --git a/Source/Application/Common/Interfaces/Internal/IAIRequestTraceLog.cs b/Source/Application/Common/Interfaces/Internal/IAIRequestTraceLog.cs index 1462e8f..32d5573 100644 --- a/Source/Application/Common/Interfaces/Internal/IAIRequestTraceLog.cs +++ b/Source/Application/Common/Interfaces/Internal/IAIRequestTraceLog.cs @@ -8,11 +8,16 @@ public interface IAIRequestTraceLog long Revision { get; } IReadOnlyList Entries { get; } void StartRequest(string requestId, string source, string model, string systemPrompt, string userPrompt, string assistantPrompt); + void UpdateRequestMetadata(string requestId, string traceId, string rolloutId, int turnIndex, string modId, string scenarioId, string? npcId, bool isAgentRollout); void UpdateRequestPrompts(string requestId, string systemPrompt, string userPrompt, string assistantPrompt); + void UpdateRequestLayers(string requestId, IReadOnlyList layers); void CompleteRequest(string requestId, string response, int tokensUsed, int elapsedMs); + void CompleteRequestDetailed(string requestId, string response, string? reasoningContent, int tokensUsed, int promptTokens, int completionTokens, int cachedTokens, int elapsedMs); void FailRequest(string requestId, string error); void FailRequest(string requestId, string error, int elapsedMs); void AddToolCall(string requestId, string toolCallId, string toolName, bool succeeded, string? error); + void AddToolCallDetailed(string requestId, string toolCallId, string toolName, bool succeeded, string? error, string? argumentsJson, string? resultContent); + void RecordActionOutcome(string requestId, string actionIntent, bool succeeded, string? detail = null, string? paramPreview = null); void Clear(); } } diff --git a/Source/Application/Common/Models/Debug/AIRequestTraceEntry.cs b/Source/Application/Common/Models/Debug/AIRequestTraceEntry.cs index e9232cf..63e0a11 100644 --- a/Source/Application/Common/Models/Debug/AIRequestTraceEntry.cs +++ b/Source/Application/Common/Models/Debug/AIRequestTraceEntry.cs @@ -1,4 +1,6 @@ +using System; using System.Collections.Generic; +using RimMind.Domain.Llm; namespace RimMind.Application.Common.Models.Debug { @@ -13,23 +15,77 @@ public sealed record AIRequestToolCallTrace( string ToolCallId, string ToolName, bool Succeeded, - string? Error); + string? Error, + string? ArgumentsJson = null, + string? ResultContent = null); + + public sealed record AIRequestLayerTrace( + string Role, + string LayerTag, + string Content, + int CharCount, + bool IsPrefixReused); + + public sealed record AIRequestActionOutcomeTrace( + string ActionIntent, + bool Succeeded, + string? Detail, + string? ParamPreview = null); public sealed class AIRequestTraceEntry { public string RequestId { get; set; } = string.Empty; + public string TraceId { get; set; } = string.Empty; + public string RolloutId { get; set; } = string.Empty; + public int TurnIndex { get; set; } + public string ModId { get; set; } = string.Empty; + public string ScenarioId { get; set; } = string.Empty; + public string? NpcId { get; set; } + public bool IsAgentRollout { get; set; } public string Source { get; set; } = string.Empty; public string Model { get; set; } = string.Empty; public string SystemPrompt { get; set; } = string.Empty; public string UserPrompt { get; set; } = string.Empty; public string AssistantPrompt { get; set; } = string.Empty; public string Response { get; set; } = string.Empty; + public string? ReasoningContent { get; set; } public string? Error { get; set; } public int TokensUsed { get; set; } + public int PromptTokens { get; set; } + public int CompletionTokens { get; set; } + public int CachedTokens { get; set; } public int ElapsedMs { get; set; } - public System.DateTime StartedAtUtc { get; set; } - public System.DateTime? FinishedAtUtc { get; set; } + public DateTime StartedAtUtc { get; set; } + public DateTime? FinishedAtUtc { get; set; } public AIRequestTraceState State { get; set; } = AIRequestTraceState.Running; public List ToolCalls { get; } = new(); + public List Layers { get; } = new(); + public AIRequestActionOutcomeTrace? ActionOutcome { get; set; } + + /// + /// Builds structured layer traces from envelope messages so prompt assembly middleware + /// and request submission share a single extraction path. + /// + public static List ExtractLayerTraces(IReadOnlyList? messages) + { + var layers = new List(); + if (messages == null || messages.Count == 0) + return layers; + + foreach (var msg in messages) + { + if (msg == null || string.IsNullOrWhiteSpace(msg.Content)) + continue; + + string role = string.IsNullOrWhiteSpace(msg.Role) ? "user" : msg.Role.ToLowerInvariant(); + string tag = !string.IsNullOrWhiteSpace(msg.LayerTag) + ? msg.LayerTag! + : (string.Equals(role, "system", StringComparison.OrdinalIgnoreCase) ? "L0" : "L4"); + string content = msg.Content; + layers.Add(new AIRequestLayerTrace(role, tag, content, content.Length, IsPrefixReused: false)); + } + + return layers; + } } } diff --git a/Source/Application/Common/Models/Debug/AgentRolloutModelBuilder.cs b/Source/Application/Common/Models/Debug/AgentRolloutModelBuilder.cs new file mode 100644 index 0000000..7425b1f --- /dev/null +++ b/Source/Application/Common/Models/Debug/AgentRolloutModelBuilder.cs @@ -0,0 +1,404 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace RimMind.Application.Common.Models.Debug +{ + public sealed record AgentRolloutEpisode( + string RolloutId, + string ActorId, + string ActorLabel, + string ModId, + string ScenarioId, + DateTime StartedAtUtc, + DateTime LastActivityUtc, + AIRequestTraceState TerminalState, + int TurnCount, + int TotalToolCalls, + int FailedToolCalls, + int TotalTokens, + int PromptTokens, + int CompletionTokens, + int CachedTokens, + int TotalElapsedMs, + double PrefixReuseRatio, + IReadOnlyList Turns, + AIRequestActionOutcomeTrace? FinalOutcome); + + public sealed record EphemeralTraceFilter( + string? ModId = null, + string? ScenarioId = null, + string? Actor = null, + AIRequestTraceState? State = null, + string? SearchQuery = null, + bool IncludeRolloutTurns = false); + + /// + /// Aggregates raw trace entries into multi-turn Agent Rollout trajectories and + /// provides multi-dimensional filtering for ephemeral one-off LLM requests. + /// + public static class AgentRolloutModelBuilder + { + public static string ResolveActorId(AIRequestTraceEntry? entry) + { + if (entry == null) + return string.Empty; + + if (!string.IsNullOrWhiteSpace(entry.NpcId)) + return entry.NpcId!.Trim(); + + string source = entry.Source ?? string.Empty; + int npcIdx = source.IndexOf("npc:", StringComparison.OrdinalIgnoreCase); + if (npcIdx >= 0) + { + int start = npcIdx + 4; + int sep = source.IndexOf('|', start); + return (sep >= 0 ? source.Substring(start, sep - start) : source.Substring(start)).Trim(); + } + + return string.Empty; + } + + public static string ResolveActorLabel( + AIRequestTraceEntry? entry, + Func? actorNameResolver = null) + { + if (entry == null) + return "-"; + + string actorId = ResolveActorId(entry); + if (!string.IsNullOrWhiteSpace(actorId)) + { + string? resolved = actorNameResolver?.Invoke(actorId); + return !string.IsNullOrWhiteSpace(resolved) ? resolved! : actorId; + } + + if (!string.IsNullOrWhiteSpace(entry.ModId)) + return entry.ModId; + return !string.IsNullOrWhiteSpace(entry.Source) ? entry.Source : "-"; + } + + public static string ResolveModId(AIRequestTraceEntry? entry) + { + if (entry == null) return string.Empty; + if (!string.IsNullOrWhiteSpace(entry.ModId)) return entry.ModId.Trim(); + return ExtractSourceTag(entry.Source, "mod:"); + } + + public static string ResolveScenarioId(AIRequestTraceEntry? entry) + { + if (entry == null) return string.Empty; + if (!string.IsNullOrWhiteSpace(entry.ScenarioId)) return entry.ScenarioId.Trim(); + return ExtractSourceTag(entry.Source, "scenario:"); + } + + public static IReadOnlyList BuildRollouts( + IReadOnlyList? entries, + string? actorFilter = null, + AIRequestTraceState? stateFilter = null, + string? searchQuery = null, + Func? actorNameResolver = null) + { + if (entries == null || entries.Count == 0) + return Array.Empty(); + + var groups = new Dictionary>(StringComparer.Ordinal); + foreach (var entry in entries) + { + if (entry == null || !IsRolloutEntry(entry)) + continue; + + string key = !string.IsNullOrWhiteSpace(entry.RolloutId) + ? entry.RolloutId + : (!string.IsNullOrWhiteSpace(entry.TraceId) ? entry.TraceId : entry.RequestId); + + if (string.IsNullOrWhiteSpace(key)) + key = entry.StartedAtUtc.Ticks.ToString(); + + if (!groups.TryGetValue(key, out var list)) + { + list = new List(); + groups[key] = list; + } + list.Add(entry); + } + + var episodes = new List(groups.Count); + foreach (var kv in groups) + { + var orderedTurns = kv.Value + .OrderBy(t => t.TurnIndex) + .ThenBy(t => t.StartedAtUtc) + .ToList(); + + var first = orderedTurns[0]; + var last = orderedTurns[orderedTurns.Count - 1]; + + string actorId = orderedTurns.Select(ResolveActorId).FirstOrDefault(id => !string.IsNullOrEmpty(id)) ?? string.Empty; + string actorLabel = ResolveActorLabel(first, actorNameResolver); + string modId = ResolveModId(first); + string scenarioId = ResolveScenarioId(first); + + AIRequestTraceState terminalState = orderedTurns.Any(t => t.State == AIRequestTraceState.Running) + ? AIRequestTraceState.Running + : last.State; + + int totalTools = orderedTurns.Sum(t => t.ToolCalls.Count); + int failedTools = orderedTurns.Sum(t => t.ToolCalls.Count(tc => !tc.Succeeded)); + int totalTokens = orderedTurns.Sum(t => t.TokensUsed); + int promptTokens = orderedTurns.Sum(t => t.PromptTokens); + int completionTokens = orderedTurns.Sum(t => t.CompletionTokens); + int cachedTokens = orderedTurns.Sum(t => t.CachedTokens); + int totalElapsed = orderedTurns.Sum(t => Math.Max(0, t.ElapsedMs)); + double prefixReuseRatio = ComputePrefixReuseRatio(orderedTurns); + AIRequestActionOutcomeTrace? finalOutcome = orderedTurns + .Select(t => t.ActionOutcome) + .LastOrDefault(o => o != null); + + DateTime started = orderedTurns.Min(t => t.StartedAtUtc); + DateTime lastAct = orderedTurns.Max(t => t.FinishedAtUtc ?? t.StartedAtUtc); + + var episode = new AgentRolloutEpisode( + kv.Key, + actorId, + actorLabel, + modId, + scenarioId, + started, + lastAct, + terminalState, + orderedTurns.Count, + totalTools, + failedTools, + totalTokens, + promptTokens, + completionTokens, + cachedTokens, + totalElapsed, + prefixReuseRatio, + orderedTurns, + finalOutcome); + + if (MatchesRolloutFilters(episode, actorFilter, stateFilter, searchQuery)) + episodes.Add(episode); + } + + return episodes + .OrderByDescending(e => e.LastActivityUtc) + .ThenByDescending(e => e.StartedAtUtc) + .ToList(); + } + + public static IReadOnlyList FilterEphemeral( + IReadOnlyList? entries, + EphemeralTraceFilter? filter = null, + Func? actorNameResolver = null) + { + if (entries == null || entries.Count == 0) + return Array.Empty(); + + var f = filter ?? new EphemeralTraceFilter(); + var matched = new List(); + for (int i = entries.Count - 1; i >= 0; i--) + { + var entry = entries[i]; + if (entry == null) continue; + + if (!f.IncludeRolloutTurns && IsRolloutEntry(entry)) + continue; + + if (!string.IsNullOrWhiteSpace(f.ModId) + && !string.Equals(ResolveModId(entry), f.ModId!.Trim(), StringComparison.OrdinalIgnoreCase)) + continue; + + if (!string.IsNullOrWhiteSpace(f.ScenarioId) + && !string.Equals(ResolveScenarioId(entry), f.ScenarioId!.Trim(), StringComparison.OrdinalIgnoreCase)) + continue; + + if (!string.IsNullOrWhiteSpace(f.Actor)) + { + string label = ResolveActorLabel(entry, actorNameResolver); + string actorId = ResolveActorId(entry); + if (!string.Equals(label, f.Actor!.Trim(), StringComparison.OrdinalIgnoreCase) + && !string.Equals(actorId, f.Actor!.Trim(), StringComparison.OrdinalIgnoreCase)) + continue; + } + + if (f.State.HasValue && entry.State != f.State.Value) + continue; + + if (!string.IsNullOrWhiteSpace(f.SearchQuery) + && !EntryMatchesSearch(entry, f.SearchQuery!.Trim(), actorNameResolver)) + continue; + + matched.Add(entry); + } + + return matched; + } + + public static IReadOnlyList GetDistinctMods(IReadOnlyList? entries) + { + if (entries == null) return Array.Empty(); + return entries.Select(ResolveModId) + .Where(s => !string.IsNullOrWhiteSpace(s)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .OrderBy(s => s, StringComparer.OrdinalIgnoreCase) + .ToList(); + } + + public static IReadOnlyList GetDistinctScenarios(IReadOnlyList? entries) + { + if (entries == null) return Array.Empty(); + return entries.Select(ResolveScenarioId) + .Where(s => !string.IsNullOrWhiteSpace(s)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .OrderBy(s => s, StringComparer.OrdinalIgnoreCase) + .ToList(); + } + + public static IReadOnlyList GetDistinctActors( + IReadOnlyList? entries, + Func? actorNameResolver = null) + { + if (entries == null) return Array.Empty(); + return entries.Where(e => !string.IsNullOrWhiteSpace(ResolveActorId(e))) + .Select(e => ResolveActorLabel(e, actorNameResolver)) + .Where(s => !string.IsNullOrWhiteSpace(s) && s != "-") + .Distinct(StringComparer.OrdinalIgnoreCase) + .OrderBy(s => s, StringComparer.OrdinalIgnoreCase) + .ToList(); + } + + private static bool IsRolloutEntry(AIRequestTraceEntry entry) + { + if (entry.IsAgentRollout) + return true; + if (!string.IsNullOrWhiteSpace(entry.RolloutId)) + return true; + string scenario = ResolveScenarioId(entry); + string mod = ResolveModId(entry); + return string.Equals(scenario, "Decision", StringComparison.OrdinalIgnoreCase) + || string.Equals(mod, "RimMind.Agent", StringComparison.OrdinalIgnoreCase); + } + + private static double ComputePrefixReuseRatio(IReadOnlyList turns) + { + long totalStableChars = 0; + long reusedChars = 0; + + foreach (var turn in turns) + { + if (turn.Layers == null || turn.Layers.Count == 0) + continue; + + foreach (var layer in turn.Layers) + { + if (!IsStableContextLayer(layer)) + continue; + + int len = Math.Max(0, layer.CharCount > 0 ? layer.CharCount : (layer.Content?.Length ?? 0)); + totalStableChars += len; + if (layer.IsPrefixReused) + reusedChars += len; + } + } + + if (totalStableChars > 0) + return (double)reusedChars / totalStableChars; + + int promptSum = turns.Sum(t => Math.Max(0, t.PromptTokens)); + int cachedSum = turns.Sum(t => Math.Max(0, t.CachedTokens)); + return promptSum > 0 ? Math.Min(1.0, (double)cachedSum / promptSum) : 0.0; + } + + private static bool IsStableContextLayer(AIRequestLayerTrace layer) + => string.Equals(layer.Role, "system", StringComparison.OrdinalIgnoreCase) + || layer.LayerTag.StartsWith("L0", StringComparison.OrdinalIgnoreCase) + || layer.LayerTag.StartsWith("L1", StringComparison.OrdinalIgnoreCase) + || layer.LayerTag.StartsWith("L2", StringComparison.OrdinalIgnoreCase) + || layer.LayerTag.StartsWith("L3", StringComparison.OrdinalIgnoreCase); + + private static bool MatchesRolloutFilters( + AgentRolloutEpisode episode, + string? actorFilter, + AIRequestTraceState? stateFilter, + string? searchQuery) + { + if (!string.IsNullOrWhiteSpace(actorFilter)) + { + string filter = actorFilter!.Trim(); + if (!string.Equals(episode.ActorLabel, filter, StringComparison.OrdinalIgnoreCase) + && !string.Equals(episode.ActorId, filter, StringComparison.OrdinalIgnoreCase)) + return false; + } + + if (stateFilter.HasValue && episode.TerminalState != stateFilter.Value) + return false; + + if (!string.IsNullOrWhiteSpace(searchQuery)) + { + string q = searchQuery!.Trim(); + bool matchEpisode = ContainsIgnoreCase(episode.RolloutId, q) + || ContainsIgnoreCase(episode.ActorLabel, q) + || ContainsIgnoreCase(episode.FinalOutcome?.ActionIntent, q) + || ContainsIgnoreCase(episode.FinalOutcome?.Detail, q) + || ContainsIgnoreCase(episode.FinalOutcome?.ParamPreview, q); + + if (!matchEpisode && !episode.Turns.Any(t => EntryMatchesSearch(t, q))) + return false; + } + + return true; + } + + private static bool EntryMatchesSearch( + AIRequestTraceEntry entry, + string query, + Func? actorNameResolver = null) + { + if (ContainsIgnoreCase(entry.RequestId, query) + || ContainsIgnoreCase(entry.Source, query) + || ContainsIgnoreCase(entry.Model, query) + || ContainsIgnoreCase(ResolveModId(entry), query) + || ContainsIgnoreCase(ResolveScenarioId(entry), query) + || ContainsIgnoreCase(ResolveActorLabel(entry, actorNameResolver), query) + || ContainsIgnoreCase(entry.UserPrompt, query) + || ContainsIgnoreCase(entry.Response, query) + || ContainsIgnoreCase(entry.ReasoningContent, query) + || ContainsIgnoreCase(entry.Error, query) + || ContainsIgnoreCase(entry.ActionOutcome?.ActionIntent, query) + || ContainsIgnoreCase(entry.ActionOutcome?.Detail, query) + || ContainsIgnoreCase(entry.ActionOutcome?.ParamPreview, query)) + return true; + + foreach (var tc in entry.ToolCalls) + { + if (ContainsIgnoreCase(tc.ToolName, query) + || ContainsIgnoreCase(tc.ArgumentsJson, query) + || ContainsIgnoreCase(tc.ResultContent, query) + || ContainsIgnoreCase(tc.Error, query)) + return true; + } + + return false; + } + + private static bool ContainsIgnoreCase(string? source, string value) + => !string.IsNullOrEmpty(source) && source!.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0; + + private static string ExtractSourceTag(string? source, string prefix) + { + if (string.IsNullOrWhiteSpace(source)) + return string.Empty; + + int idx = source!.IndexOf(prefix, StringComparison.OrdinalIgnoreCase); + if (idx < 0) + return string.Empty; + + int start = idx + prefix.Length; + int sep = source.IndexOf('|', start); + return (sep >= 0 ? source.Substring(start, sep - start) : source.Substring(start)).Trim(); + } + } +} diff --git a/Source/Application/Common/Models/Debug/TraceContentFormatter.cs b/Source/Application/Common/Models/Debug/TraceContentFormatter.cs new file mode 100644 index 0000000..1c27d20 --- /dev/null +++ b/Source/Application/Common/Models/Debug/TraceContentFormatter.cs @@ -0,0 +1,166 @@ +using System; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace RimMind.Application.Common.Models.Debug +{ + /// + /// Formats raw LLM trace payloads (JSON objects/arrays, XML agent tags, and tool results) + /// into readable indented blocks and concise single-line previews for debug UI views. + /// + public static class TraceContentFormatter + { + private static readonly TimeSpan RegexTimeout = TimeSpan.FromMilliseconds(50); + + private static readonly Regex TagBreakRegex = new Regex( + @"(?)(?!\r|\n)", + RegexOptions.IgnoreCase | RegexOptions.Compiled, + RegexTimeout); + + private static readonly Regex InlineToolResultJsonRegex = new Regex( + @"(?\[Tool\s+[^\]]+?result\]:\s*)(?[\{\[][\s\S]*?)(?=\r?\n\[Tool\s|\r?\n|$)", + RegexOptions.IgnoreCase | RegexOptions.Compiled, + RegexTimeout); + + public static string FormatStructuredText(string? raw, int maxChars = 16000) + { + if (string.IsNullOrWhiteSpace(raw)) + return "-"; + + string trimmed = raw!.Trim(); + if (TryFormatJson(trimmed, out string formattedJson)) + return TruncateSafe(formattedJson, maxChars); + + string normalized = trimmed.Replace("\r\n", "\n"); + try + { + normalized = TagBreakRegex.Replace(normalized, m => m.Groups["close"].Value + "\n"); + normalized = InlineToolResultJsonRegex.Replace(normalized, m => + { + string candidate = m.Groups["json"].Value.Trim(); + if (TryFormatJson(candidate, out string pretty)) + return m.Groups["prefix"].Value + "\n" + IndentLines(pretty, " "); + return m.Value; + }); + } + catch (RegexMatchTimeoutException) + { + // Fall back to un-normalized text if input is pathological + } + + // Format JSON inside {...} or {...} if single-line + normalized = FormatTagInnerJson(normalized, "Action"); + normalized = FormatTagInnerJson(normalized, "Param"); + + return TruncateSafe(normalized, maxChars); + } + + public static string FormatToolArguments(string? argumentsJson, int maxChars = 4000) + { + if (string.IsNullOrWhiteSpace(argumentsJson)) + return "{}"; + return FormatStructuredText(argumentsJson, maxChars); + } + + public static string BuildCompactPreview(string? raw, int maxLen = 80) + { + if (string.IsNullOrWhiteSpace(raw)) + return string.Empty; + + var sb = new StringBuilder(Math.Min(raw!.Length, maxLen + 8)); + bool lastWasSpace = false; + foreach (char ch in raw) + { + char mapped = (ch == '\r' || ch == '\n' || ch == '\t') ? ' ' : ch; + if (mapped == ' ') + { + if (sb.Length == 0 || lastWasSpace) + continue; + lastWasSpace = true; + sb.Append(' '); + } + else + { + lastWasSpace = false; + sb.Append(mapped); + } + + if (sb.Length >= maxLen) + break; + } + + string compact = sb.ToString().Trim(); + if (compact.Length > maxLen && maxLen > 3) + return compact.Substring(0, maxLen - 3) + "..."; + if (raw.Trim().Length > maxLen && compact.Length == maxLen && maxLen > 3) + return compact.Substring(0, maxLen - 3) + "..."; + return compact; + } + + private static bool TryFormatJson(string candidate, out string indented) + { + indented = string.Empty; + if (candidate.Length < 2) + return false; + + char first = candidate[0]; + char last = candidate[candidate.Length - 1]; + if (!((first == '{' && last == '}') || (first == '[' && last == ']'))) + return false; + + try + { + var token = JToken.Parse(candidate); + indented = token.ToString(Formatting.Indented); + return true; + } + catch + { + return false; + } + } + + private static string FormatTagInnerJson(string text, string tagName) + { + string open = $"<{tagName}>"; + string close = $""; + int openIdx = text.IndexOf(open, StringComparison.OrdinalIgnoreCase); + if (openIdx < 0) + return text; + + int contentStart = openIdx + open.Length; + int closeIdx = text.IndexOf(close, contentStart, StringComparison.OrdinalIgnoreCase); + if (closeIdx <= contentStart) + return text; + + string inner = text.Substring(contentStart, closeIdx - contentStart).Trim(); + if (!TryFormatJson(inner, out string pretty)) + return text; + + return text.Substring(0, contentStart) + + "\n" + IndentLines(pretty, " ") + "\n" + + text.Substring(closeIdx); + } + + private static string IndentLines(string text, string indent) + { + string[] lines = text.Replace("\r\n", "\n").Split('\n'); + var sb = new StringBuilder(text.Length + lines.Length * indent.Length); + for (int i = 0; i < lines.Length; i++) + { + if (i > 0) sb.Append('\n'); + sb.Append(indent).Append(lines[i]); + } + return sb.ToString(); + } + + private static string TruncateSafe(string text, int maxChars) + { + if (maxChars <= 0 || text.Length <= maxChars) + return text; + return text.Substring(0, maxChars) + "\n... [truncated]"; + } + } +} diff --git a/Source/Application/Common/Models/Mechanisms/MechanismWriteArgs.cs b/Source/Application/Common/Models/Mechanisms/MechanismWriteArgs.cs index 4295262..de7076f 100644 --- a/Source/Application/Common/Models/Mechanisms/MechanismWriteArgs.cs +++ b/Source/Application/Common/Models/Mechanisms/MechanismWriteArgs.cs @@ -10,6 +10,7 @@ public sealed record MechanismWriteArgs public string? DefName { get; init; } public string Action { get; init; } = ""; public string? ValueJson { get; init; } + public string? RawArgumentsJson { get; init; } public string? TraceId { get; init; } public Dictionary? Params { get; init; } } diff --git a/Source/Application/Features/Agent/DecisionProcessor.cs b/Source/Application/Features/Agent/DecisionProcessor.cs index fe7e8a7..79dee8d 100644 --- a/Source/Application/Features/Agent/DecisionProcessor.cs +++ b/Source/Application/Features/Agent/DecisionProcessor.cs @@ -37,6 +37,7 @@ public class DecisionProcessor : IDecisionProcessor private readonly IDecisionValidator _validator; private readonly IToolRegistry? _toolRegistry; private readonly IAgenticLoopService _loopService; + private readonly Action? _recordTraceOutcome; public DecisionProcessor( IAgentControl agent, @@ -50,7 +51,8 @@ public DecisionProcessor( ILogSink? log = null, IDecisionValidator? validator = null, IToolRegistry? toolRegistry = null, - IAgenticLoopService? loopService = null) + IAgenticLoopService? loopService = null, + Action? recordTraceOutcome = null) { _agent = agent ?? throw new ArgumentNullException(nameof(agent)); _agentBus = agentBus ?? throw new ArgumentNullException(nameof(agentBus)); @@ -64,6 +66,7 @@ public DecisionProcessor( _validator = validator ?? new DecisionValidator(); _toolRegistry = toolRegistry; _loopService = loopService ?? new AgenticLoopService(); + _recordTraceOutcome = recordTraceOutcome; } public bool ProcessResult( @@ -86,12 +89,15 @@ public bool ProcessResult( return true; } + string? requestId = context?.Envelope?.RequestId; var response = result.Value; var toolCallResults = context?.ToolCallResults; var decision = strategy.ParseDecision(_agent, response, toolCallResults); if (!decision.IsOk) { + if (!string.IsNullOrWhiteSpace(requestId)) + _recordTraceOutcome?.Invoke(requestId!, "parse_error", false, decision.Error.Message, null); _resetThinking(); _transitionWorkflow(AgentWorkflowPhase.Idle); _log?.Warning($"[RimMind.Thinker] action=ParseFailed npcId={_agent.NpcId} modeId={_agent.CurrentModeId.Value} error={decision.Error}"); @@ -118,6 +124,8 @@ public bool ProcessResult( if (!validation.IsValid) { var failReason = validation.Reason ?? "Decision validation failed"; + if (!string.IsNullOrWhiteSpace(requestId)) + _recordTraceOutcome?.Invoke(requestId!, decision.Value.ActionIntent ?? "action", false, failReason, decision.Value.Param); _log?.Warning($"[RimMind.DecisionProcessor] validation failed: {failReason}"); _agentBus.Publish(new DecisionFailedEvent( _agent.NpcId, @@ -144,17 +152,31 @@ public bool ProcessResult( _transitionWorkflow(AgentWorkflowPhase.Acting); + var paramPreview = decision.Value.Param ?? ""; + if (paramPreview.Length > 240) paramPreview = paramPreview.Substring(0, 240) + "..."; + _log?.Message($"[RimMind.DecisionProcessor] Executing npcId={_agent.NpcId} action={decision.Value.ActionIntent} target={decision.Value.TargetPawnId} param={paramPreview}"); var execResult = _executeDecision(decision.Value); var execSuccess = execResult.IsOk; + if (!string.IsNullOrWhiteSpace(requestId)) + { + _recordTraceOutcome?.Invoke( + requestId!, + decision.Value.ActionIntent ?? "action", + execSuccess, + execSuccess ? decision.Value.Reason : (execResult.Error?.Message ?? "Action failed"), + paramPreview); + } + if (!execSuccess) { - _log?.Warning($"[RimMind.DecisionProcessor] Action execution failed for npcId={_agent.NpcId} action={decision.Value.ActionIntent} error={execResult.Error.Message}"); + string failMsg = execResult.Error?.Message ?? "Action failed"; + _log?.Warning($"[RimMind.DecisionProcessor] Action execution failed for npcId={_agent.NpcId} action={decision.Value.ActionIntent} error={failMsg}"); _agentBus.Publish(new DecisionFailedEvent( _agent.NpcId, _getPawnId(), decision.Value.ActionIntent ?? "action", - execResult.Error.Message)); + failMsg)); } _transitionWorkflow(AgentWorkflowPhase.Recording); diff --git a/Source/Application/Features/Agent/Modes/DecisionExampleData.cs b/Source/Application/Features/Agent/Modes/DecisionExampleData.cs index 786c1a2..2b9d73d 100644 --- a/Source/Application/Features/Agent/Modes/DecisionExampleData.cs +++ b/Source/Application/Features/Agent/Modes/DecisionExampleData.cs @@ -5,15 +5,13 @@ internal static class DecisionExampleData public static readonly (string User, string Assistant)[] Examples = new[] { ("[mood] Mood: 35% (importance:0.7)\n[need] Need: Food at 20% (importance:0.9)", - "{\"action\":\"pawn.job.force_rest\",\"reason\":\"Mood and food needs are critical; rest first to stabilize mood before eating\"}"), - ("[combat] Currently drafted for combat (importance:1.0)\n[health] Health issue: Bruise (importance:0.4)", - "{\"action\":\"pawn.draft.toggle\",\"reason\":\"Enemy nearby; engage in combat defense despite minor injury\"}"), + "{\"action\":\"pawn.job.eat_food\",\"reason\":\"Food is critically low; eating comes first and also lifts mood\"}"), + ("[combat] Enemy spotted at range 15 (importance:1.0)\n[health] Health issue: Bruise (importance:0.4)", + "{\"action\":\"pawn.draft.toggle\",\"reason\":\"Enemy nearby; draft to defend despite the minor injury\",\"param\":\"{\\\"action\\\":\\\"draft\\\"}\"}"), ("[environment] Environment: Clear, 22\u00b0C (importance:0.1)\n[social] Social: Alice (friend) (importance:0.3)", - "{\"action\":\"pawn.work.set\",\"reason\":\"No urgent needs; assign to mining work with friend nearby\",\"param\":\"Mining\"}"), - ("[combat] Enemy spotted at range 15 (importance:1.0)", - "{\"action\":\"pawn.draft.toggle\",\"reason\":\"Need to engage enemy; drafting first to access combat tools\"}"), - ("[tool_result] pawn.draft.toggle succeeded. Now drafted. (importance:0.8)", - "{\"action\":\"pawn.equipment.set\",\"reason\":\"Drafted and need ranged weapon for enemy at range 15\",\"param\":\"SniperRifle\"}"), + "{\"action\":\"pawn.work.set\",\"reason\":\"No urgent needs; prioritize mining to gather resources\",\"param\":\"{\\\"work_type\\\":\\\"Mining\\\",\\\"priority\\\":1}\"}"), + ("[combat] No enemies remain on the map (importance:0.8)\n[status] Currently drafted (importance:0.5)", + "{\"action\":\"pawn.draft.toggle\",\"reason\":\"Threat is gone; undraft and return to normal work\",\"param\":\"{\\\"action\\\":\\\"undraft\\\"}\"}"), }; } } diff --git a/Source/Application/Features/Agent/Modes/ThinkStrategyHelper.cs b/Source/Application/Features/Agent/Modes/ThinkStrategyHelper.cs index b817891..a48fb95 100644 --- a/Source/Application/Features/Agent/Modes/ThinkStrategyHelper.cs +++ b/Source/Application/Features/Agent/Modes/ThinkStrategyHelper.cs @@ -69,6 +69,11 @@ public static string FormatPerceptions(IReadOnlyList perc RegexOptions.IgnoreCase | RegexOptions.Compiled, RegexTimeout); + private static readonly Regex ToToolCommentaryRegex = new Regex( + @"\bto=(?:functions\.|tools\.)?(?[a-z_][a-z0-9_.]*)", + RegexOptions.IgnoreCase | RegexOptions.Compiled, + RegexTimeout); + private static readonly List CachedDecisionExamples = CreateDecisionExamples(); public static bool IsQueryToolName(string? toolName, IToolRegistry? toolRegistry = null) @@ -89,7 +94,9 @@ private static bool HasQueryPrefix(string name) => name.StartsWith("query", StringComparison.OrdinalIgnoreCase) || name.StartsWith("get_", StringComparison.OrdinalIgnoreCase) || name.StartsWith("list_", StringComparison.OrdinalIgnoreCase) - || name.StartsWith("inspect_", StringComparison.OrdinalIgnoreCase); + || name.StartsWith("inspect_", StringComparison.OrdinalIgnoreCase) + || name.EndsWith("_query", StringComparison.OrdinalIgnoreCase) + || name.EndsWith(".query", StringComparison.OrdinalIgnoreCase); private static bool HasUnqualifiedQueryPrefix(string name) { @@ -110,7 +117,36 @@ public static Result ParseDecisionCore( IReadOnlyList? toolCallResults = null) { var json = JsonTagExtractor.Extract(response.Content, "Action"); - var hasAction = json != null; + if (json == null && !string.IsNullOrEmpty(response.Content)) + { + const string openTag = ""; + int tagIdx = response.Content.IndexOf(openTag, StringComparison.OrdinalIgnoreCase); + if (tagIdx >= 0) + { + string rawAfterTag = response.Content.Substring(tagIdx + openTag.Length).Trim(); + int closeIdx = rawAfterTag.IndexOf("", StringComparison.OrdinalIgnoreCase); + if (closeIdx >= 0) + rawAfterTag = rawAfterTag.Substring(0, closeIdx).Trim(); + + string sanitized = JsonTagExtractor.SanitizeJsonContent(rawAfterTag); + if (!string.IsNullOrEmpty(sanitized)) + { + try + { + string repaired = JsonRepairer.Repair(sanitized); + json = Newtonsoft.Json.JsonConvert.DeserializeObject(repaired); + } + catch + { + // Ignore unrecoverable truncated payload + } + } + } + } + + // Models sometimes echo the "..." schema placeholder literally; never let a + // placeholder action shadow a real tool call or reach the tool registry. + var hasAction = json != null && IsMeaningfulActionName(json.action); var hasToolCalls = !string.IsNullOrEmpty(response.ToolCallsJson); if (!hasAction && !hasToolCalls) @@ -165,11 +201,94 @@ public static Result ParseDecisionCore( }); } + internal static bool IsMeaningfulActionName(string? action) + { + if (string.IsNullOrWhiteSpace(action)) return false; + foreach (var ch in action!) + { + if (ch != '.' && ch != '\u2026' && !char.IsWhiteSpace(ch)) return true; + } + return false; + } + internal static (string? Id, string? Name, string? ArgsJson, string? Reason) TryExtractToolCallFromContent(string? content) { if (string.IsNullOrWhiteSpace(content)) return (null, null, null, null); string trimmed = content!.Trim(); + // 0. Check raw JSON tool call object: {"name": "actions_eat_and_recreation", "parameters": {...}} or {"tool": "...", "arguments": {...}} + int firstBrace = trimmed.IndexOf('{'); + if (firstBrace >= 0) + { + int lastBrace = trimmed.LastIndexOf('}'); + string jsonCandidate = lastBrace > firstBrace + ? trimmed.Substring(firstBrace, lastBrace - firstBrace + 1) + : trimmed.Substring(firstBrace); + + Newtonsoft.Json.Linq.JObject? rawObj = null; + try + { + rawObj = Newtonsoft.Json.Linq.JToken.Parse(jsonCandidate) as Newtonsoft.Json.Linq.JObject; + } + catch + { + try + { + string repaired = JsonRepairer.Repair(trimmed.Substring(firstBrace)); + rawObj = Newtonsoft.Json.Linq.JToken.Parse(repaired) as Newtonsoft.Json.Linq.JObject; + } + catch { } + } + + if (rawObj != null) + { + string? rawToolName = rawObj.Value("name") + ?? rawObj.Value("tool") + ?? (rawObj["function"] as Newtonsoft.Json.Linq.JObject)?.Value("name"); + if (!string.IsNullOrWhiteSpace(rawToolName) && IsValidFallbackToolIdentifier(rawToolName)) + { + var paramsToken = rawObj["parameters"] + ?? rawObj["arguments"] + ?? rawObj["args"] + ?? rawObj["param"] + ?? (rawObj["function"] as Newtonsoft.Json.Linq.JObject)?["arguments"]; + string? argsJson = null; + string? reason = rawObj.Value("reason"); + if (paramsToken is Newtonsoft.Json.Linq.JObject paramsObj) + { + argsJson = paramsObj.ToString(Newtonsoft.Json.Formatting.None); + reason ??= paramsObj.Value("reason"); + } + else if (paramsToken != null && paramsToken.Type == Newtonsoft.Json.Linq.JTokenType.String) + { + argsJson = paramsToken.ToString(); + if (!string.IsNullOrWhiteSpace(argsJson)) + { + try + { + if (Newtonsoft.Json.Linq.JToken.Parse(argsJson!) is Newtonsoft.Json.Linq.JObject parsedParams) + reason ??= parsedParams.Value("reason"); + } + catch { } + } + } + else + { + var copyObj = (Newtonsoft.Json.Linq.JObject)rawObj.DeepClone(); + copyObj.Remove("name"); + copyObj.Remove("tool"); + copyObj.Remove("function"); + copyObj.Remove("id"); + copyObj.Remove("type"); + if (copyObj.HasValues) + argsJson = copyObj.ToString(Newtonsoft.Json.Formatting.None); + } + + return (rawObj.Value("id"), rawToolName, argsJson ?? "{}", reason); + } + } + } + // 1. Check pseudo-function call syntax: tool_name(key=val, ...) // Require a structured tool identifier (containing '_' or '.') immediately followed by '(' // so ordinary parenthetical prose like "I'm tired (reason: no sleep)" is never treated as a tool call. @@ -230,6 +349,59 @@ internal static (string? Id, string? Name, string? ArgsJson, string? Reason) Try } } + // 2. Check commentary syntax: to=tool_name or to=functions.tool_name [optional {...}] + Match toMatch; + try + { + toMatch = ToToolCommentaryRegex.Match(trimmed); + } + catch (RegexMatchTimeoutException) + { + return (null, null, null, null); + } + + if (toMatch.Success) + { + string fnName = toMatch.Groups["fn"].Value; + if (IsValidFallbackToolIdentifier(fnName)) + { + string afterMatch = trimmed.Substring(toMatch.Index + toMatch.Length).Trim(); + string? argsJson = "{}"; + string? reason = null; + int braceStart = afterMatch.IndexOf('{'); + int braceEnd = afterMatch.LastIndexOf('}'); + if (braceStart >= 0 && braceEnd > braceStart) + { + string candidate = afterMatch.Substring(braceStart, braceEnd - braceStart + 1); + try + { + if (Newtonsoft.Json.Linq.JToken.Parse(candidate) is Newtonsoft.Json.Linq.JObject argObj) + { + argsJson = argObj.ToString(Newtonsoft.Json.Formatting.None); + reason = argObj.Value("reason"); + } + } + catch { } + } + else if (braceStart >= 0) + { + string candidate = afterMatch.Substring(braceStart); + try + { + string repaired = JsonRepairer.Repair(candidate); + if (Newtonsoft.Json.Linq.JToken.Parse(repaired) is Newtonsoft.Json.Linq.JObject argObj) + { + argsJson = argObj.ToString(Newtonsoft.Json.Formatting.None); + reason = argObj.Value("reason"); + } + } + catch { } + } + + return (null, fnName, argsJson, reason); + } + } + return (null, null, null, null); } diff --git a/Source/Application/Features/Llm/LlmRequestEnvelopeBuilder.cs b/Source/Application/Features/Llm/LlmRequestEnvelopeBuilder.cs index 70d0249..2295cb7 100644 --- a/Source/Application/Features/Llm/LlmRequestEnvelopeBuilder.cs +++ b/Source/Application/Features/Llm/LlmRequestEnvelopeBuilder.cs @@ -24,6 +24,7 @@ public sealed class LlmRequestEnvelopeBuilder private CancellationToken _ct = default; private int _maxTokens = 800; private float _temperature = 0.7f; + private ReasoningEffort _reasoningEffort = ReasoningEffort.Auto; private int? _expireAtTicks; private int? _maxRetryCount; private Dictionary? _hints; @@ -146,6 +147,12 @@ public LlmRequestEnvelopeBuilder WithTemperature(float t) return this; } + public LlmRequestEnvelopeBuilder WithReasoningEffort(ReasoningEffort effort) + { + _reasoningEffort = effort; + return this; + } + public LlmRequestEnvelopeBuilder WithExpireAtTicks(int? ticks) { _expireAtTicks = ticks; @@ -208,6 +215,7 @@ public LlmRequestEnvelope Build() Examples = _examples, MaxTokens = _maxTokens, Temperature = _temperature, + ReasoningEffort = _reasoningEffort, Priority = _priority, ExpireAtTicks = _expireAtTicks, MaxRetryCount = _maxRetryCount, diff --git a/Source/Application/Features/Pipeline/Unified/CircuitBreakerMiddleware.cs b/Source/Application/Features/Pipeline/Unified/CircuitBreakerMiddleware.cs index 3ba04a8..7e6b6d5 100644 --- a/Source/Application/Features/Pipeline/Unified/CircuitBreakerMiddleware.cs +++ b/Source/Application/Features/Pipeline/Unified/CircuitBreakerMiddleware.cs @@ -216,7 +216,8 @@ private void OnFailureLocked(CircuitBucket bucket, RimMindError? error, bool isC error.Code == RimMindErrorCode.Cancelled || error.Code == RimMindErrorCode.ClientNotConfigured || error.Code == RimMindErrorCode.PipelineShortCircuited || - error.Code == RimMindErrorCode.ContextBuildFailed)) + error.Code == RimMindErrorCode.ContextBuildFailed || + error.Code == RimMindErrorCode.ContentFiltered)) { return; } diff --git a/Source/Application/Features/Pipeline/Unified/ClientInvokeMiddleware.cs b/Source/Application/Features/Pipeline/Unified/ClientInvokeMiddleware.cs index e4b4382..98a912e 100644 --- a/Source/Application/Features/Pipeline/Unified/ClientInvokeMiddleware.cs +++ b/Source/Application/Features/Pipeline/Unified/ClientInvokeMiddleware.cs @@ -7,6 +7,7 @@ using RimMind.Application.Common.Interfaces.Internal; using RimMind.Application.Common.Interfaces.Pipeline; using RimMind.Application.Common.Models; +using RimMind.Application.Common.Models.Debug; using RimMind.Application.Common.Models.Pipeline; using RimMind.Domain.Llm; using RimMind.Domain.ValueObjects; @@ -122,6 +123,10 @@ private void RecordFinalPrompts(LlmRequestEnvelope envelope) BuildPrompt(envelope, "system"), BuildPrompt(envelope, "user"), BuildPrompt(envelope, "assistant")); + + var layers = AIRequestTraceEntry.ExtractLayerTraces(envelope.Messages); + if (layers.Count > 0) + _traceLog.UpdateRequestLayers(envelope.RequestId, layers); } private static string BuildPrompt(LlmRequestEnvelope envelope, string role) diff --git a/Source/Application/Features/Pipeline/Unified/RetryMiddleware.cs b/Source/Application/Features/Pipeline/Unified/RetryMiddleware.cs index 231ec21..f8fdd1d 100644 --- a/Source/Application/Features/Pipeline/Unified/RetryMiddleware.cs +++ b/Source/Application/Features/Pipeline/Unified/RetryMiddleware.cs @@ -46,6 +46,8 @@ public async Task InvokeAsync(LlmRequestContext context, MiddlewareDelegate { elapsed.Stop(); - CompleteTrace(envelope.RequestId, result, elapsed.ElapsedMilliseconds); + CompleteTrace(envelope, executor.Context, result, elapsed.ElapsedMilliseconds); onComplete(result, executor.Context); }, cancellationToken => executor.ExecuteAsync(envelope, cancellationToken), @@ -127,20 +130,56 @@ void CompleteCancelled() => completion.TrySetResult( private void StartTrace(LlmRequestEnvelope envelope) { - _traceLog?.StartRequest( + if (_traceLog == null) + return; + + _traceLog.StartRequest( envelope.RequestId, GetTraceSource(envelope), _modelSettings?.ModelName ?? string.Empty, BuildTracePrompt(envelope, "system"), BuildTracePrompt(envelope, "user"), BuildTracePrompt(envelope, "assistant")); + + string rolloutId = string.Empty; + int turnIndex = 0; + if (envelope.Hints != null) + { + if (envelope.Hints.TryGetValue("rollout_id", out var hintedRollout) && !string.IsNullOrWhiteSpace(hintedRollout)) + rolloutId = hintedRollout; + if (envelope.Hints.TryGetValue("turn_index", out var hintedTurn) && int.TryParse(hintedTurn, out var parsedTurn)) + turnIndex = parsedTurn; + } + + bool isAgentRollout = !string.IsNullOrWhiteSpace(rolloutId) + || string.Equals(envelope.ScenarioId, ScenarioIds.Decision, StringComparison.OrdinalIgnoreCase) + || string.Equals(envelope.ModId, "RimMind.Agent", StringComparison.OrdinalIgnoreCase); + + if (isAgentRollout && string.IsNullOrWhiteSpace(rolloutId)) + rolloutId = !string.IsNullOrWhiteSpace(envelope.TraceId) ? envelope.TraceId : envelope.RequestId; + + _traceLog.UpdateRequestMetadata( + envelope.RequestId, + envelope.TraceId, + rolloutId, + turnIndex, + envelope.ModId, + envelope.ScenarioId, + envelope.NpcId, + isAgentRollout); + + var initialLayers = AIRequestTraceEntry.ExtractLayerTraces(envelope.Messages); + if (initialLayers.Count > 0) + _traceLog.UpdateRequestLayers(envelope.RequestId, initialLayers); } private void CompleteTrace( - string requestId, + LlmRequestEnvelope envelope, + LlmRequestContext? context, Result result, long elapsedMilliseconds) { + string requestId = envelope.RequestId; if (result.IsOk) { var response = result.Value; @@ -148,10 +187,14 @@ private void CompleteTrace( ? response.Content : response.ToolCallsJson ?? string.Empty; - _traceLog?.CompleteRequest( + _traceLog?.CompleteRequestDetailed( requestId, responseContent, + response.ReasoningContent, response.TokensUsed, + response.PromptTokens, + response.CompletionTokens, + response.CachedTokens, (int)elapsedMilliseconds); if (!string.IsNullOrWhiteSpace(response.ToolCallsJson) && _traceLog != null) @@ -161,12 +204,29 @@ private void CompleteTrace( var calls = Newtonsoft.Json.JsonConvert.DeserializeObject>(response.ToolCallsJson!); if (calls != null) { + var dispatched = context?.ToolCallResults; foreach (var call in calls) { - if (!string.IsNullOrWhiteSpace(call.Name)) - { - _traceLog.AddToolCall(requestId, call.Id, call.Name, succeeded: true, error: null); - } + if (string.IsNullOrWhiteSpace(call.Name)) + continue; + + bool alreadyDispatched = envelope.ToolDispatchMode == ToolCallDispatchMode.Auto + && dispatched != null + && dispatched.Any(r => + (!string.IsNullOrEmpty(call.Id) && string.Equals(r.ToolCallId, call.Id, StringComparison.Ordinal)) + || string.Equals(r.ToolName, call.Name, StringComparison.OrdinalIgnoreCase)); + + if (alreadyDispatched) + continue; + + _traceLog.AddToolCallDetailed( + requestId, + call.Id, + call.Name, + succeeded: true, + error: null, + argumentsJson: call.Arguments, + resultContent: null); } } } diff --git a/Source/Domain/Agent/Policies/AgentAutonomyPolicy.cs b/Source/Domain/Agent/Policies/AgentAutonomyPolicy.cs index 28bff7f..ff11897 100644 --- a/Source/Domain/Agent/Policies/AgentAutonomyPolicy.cs +++ b/Source/Domain/Agent/Policies/AgentAutonomyPolicy.cs @@ -47,6 +47,36 @@ public void SetDefaultPreset() _domainLevels[AutonomyDomain.WorktableBills] = AutonomyLevel.RequireApproval; _domainLevels[AutonomyDomain.BlueprintPlacement] = AutonomyLevel.RequireApproval; _domainLevels[AutonomyDomain.HighRiskOperations] = AutonomyLevel.RequireApproval; + _domainLevels[AutonomyDomain.WorkPriorityModification] = AutonomyLevel.Disabled; + } + + public void ApplyWorkOnlyNoBlueprintsPreset() + { + _domainLevels[AutonomyDomain.EmergencySurvival] = AutonomyLevel.FullAutonomous; + _domainLevels[AutonomyDomain.ResourceMarking] = AutonomyLevel.FullAutonomous; + _domainLevels[AutonomyDomain.WorktableBills] = AutonomyLevel.FullAutonomous; + _domainLevels[AutonomyDomain.BlueprintPlacement] = AutonomyLevel.Disabled; + _domainLevels[AutonomyDomain.HighRiskOperations] = AutonomyLevel.RequireApproval; + _domainLevels[AutonomyDomain.WorkPriorityModification] = AutonomyLevel.Disabled; + } + + public void ApplyFullAutonomousPreset() + { + _domainLevels[AutonomyDomain.EmergencySurvival] = AutonomyLevel.FullAutonomous; + _domainLevels[AutonomyDomain.ResourceMarking] = AutonomyLevel.FullAutonomous; + _domainLevels[AutonomyDomain.WorktableBills] = AutonomyLevel.FullAutonomous; + _domainLevels[AutonomyDomain.BlueprintPlacement] = AutonomyLevel.FullAutonomous; + _domainLevels[AutonomyDomain.HighRiskOperations] = AutonomyLevel.RequireApproval; + _domainLevels[AutonomyDomain.WorkPriorityModification] = AutonomyLevel.FullAutonomous; + } + + public void CopyFrom(AgentAutonomyPolicy? other) + { + if (other == null) return; + foreach (AutonomyDomain domain in System.Enum.GetValues(typeof(AutonomyDomain))) + { + _domainLevels[domain] = other.GetLevel(domain); + } } public AgentAutonomyPolicy Clone() diff --git a/Source/Domain/Agent/Policies/AutonomyDomain.cs b/Source/Domain/Agent/Policies/AutonomyDomain.cs index b2a006e..74cc49c 100644 --- a/Source/Domain/Agent/Policies/AutonomyDomain.cs +++ b/Source/Domain/Agent/Policies/AutonomyDomain.cs @@ -28,6 +28,12 @@ public enum AutonomyDomain /// /// High-risk irreversible or costly actions (demolishing permanent structures, consuming scarce components, medical surgery). /// - HighRiskOperations = 4 + HighRiskOperations = 4, + + /// + /// Modifying colonist Work Tab priorities (e.g. pawn.work.set / assign_work priority bump). + /// Disabled by default to preserve player Work Tab schedules. + /// + WorkPriorityModification = 5 } } diff --git a/Source/Domain/Audio/AudioContainerFormat.cs b/Source/Domain/Audio/AudioContainerFormat.cs new file mode 100644 index 0000000..87b6589 --- /dev/null +++ b/Source/Domain/Audio/AudioContainerFormat.cs @@ -0,0 +1,13 @@ +namespace RimMind.Domain.Audio +{ + /// + /// Provider-agnostic audio container / encoding formats for speech synthesis and recognition ports. + /// + public enum AudioContainerFormat + { + Wav = 0, + Pcm16Mono = 1, + OggOpus = 2, + Mp3 = 3, + } +} diff --git a/Source/Domain/Audio/SpeechRecognitionRequest.cs b/Source/Domain/Audio/SpeechRecognitionRequest.cs new file mode 100644 index 0000000..1d08776 --- /dev/null +++ b/Source/Domain/Audio/SpeechRecognitionRequest.cs @@ -0,0 +1,17 @@ +using System; +using System.Threading; + +namespace RimMind.Domain.Audio +{ + /// + /// Provider-agnostic request payload for speech-to-text recognition. + /// + public sealed class SpeechRecognitionRequest + { + public byte[] AudioBytes { get; init; } = Array.Empty(); + public AudioContainerFormat Format { get; init; } = AudioContainerFormat.Wav; + public string FileName { get; init; } = "audio.wav"; + public string? VocabularyHints { get; init; } + public CancellationToken Ct { get; init; } = default; + } +} diff --git a/Source/Domain/Audio/SpeechRecognitionResult.cs b/Source/Domain/Audio/SpeechRecognitionResult.cs new file mode 100644 index 0000000..6c7ce7e --- /dev/null +++ b/Source/Domain/Audio/SpeechRecognitionResult.cs @@ -0,0 +1,13 @@ +namespace RimMind.Domain.Audio +{ + /// + /// Transcribed text and timing metadata returned by ISpeechRecognizer. + /// + public sealed class SpeechRecognitionResult + { + public string RequestId { get; init; } = string.Empty; + public string Text { get; init; } = string.Empty; + public int DurationMs { get; init; } + public string ProviderId { get; init; } = string.Empty; + } +} diff --git a/Source/Domain/Audio/SpeechSynthesisRequest.cs b/Source/Domain/Audio/SpeechSynthesisRequest.cs new file mode 100644 index 0000000..d571e27 --- /dev/null +++ b/Source/Domain/Audio/SpeechSynthesisRequest.cs @@ -0,0 +1,16 @@ +using System.Threading; + +namespace RimMind.Domain.Audio +{ + /// + /// Provider-agnostic request payload for text-to-speech synthesis. + /// + public sealed class SpeechSynthesisRequest + { + public string Text { get; init; } = string.Empty; + public string? VoiceId { get; init; } + public AudioContainerFormat PreferredFormat { get; init; } = AudioContainerFormat.Wav; + public bool StripMarkdown { get; init; } = true; + public CancellationToken Ct { get; init; } = default; + } +} diff --git a/Source/Domain/Audio/SpeechSynthesisResult.cs b/Source/Domain/Audio/SpeechSynthesisResult.cs new file mode 100644 index 0000000..e8499b2 --- /dev/null +++ b/Source/Domain/Audio/SpeechSynthesisResult.cs @@ -0,0 +1,17 @@ +using System; + +namespace RimMind.Domain.Audio +{ + /// + /// Synthesized audio buffer and format metadata returned by ISpeechSynthesizer. + /// + public sealed class SpeechSynthesisResult + { + public byte[] AudioBytes { get; init; } = Array.Empty(); + public AudioContainerFormat Format { get; init; } = AudioContainerFormat.Wav; + public int SampleRateHz { get; init; } = 24000; + public int Channels { get; init; } = 1; + public int BitsPerSample { get; init; } = 16; + public string ProviderId { get; init; } = string.Empty; + } +} diff --git a/Source/Domain/Llm/LlmRequestEnvelope.cs b/Source/Domain/Llm/LlmRequestEnvelope.cs index db95369..4e8195d 100644 --- a/Source/Domain/Llm/LlmRequestEnvelope.cs +++ b/Source/Domain/Llm/LlmRequestEnvelope.cs @@ -21,6 +21,7 @@ public class LlmRequestEnvelope public List? Examples { get; init; } public int MaxTokens { get; init; } = 800; public float Temperature { get; init; } = 0.7f; + public ReasoningEffort ReasoningEffort { get; init; } = ReasoningEffort.Auto; // === Dispatch === public AIRequestPriority Priority { get; init; } = AIRequestPriority.Normal; @@ -40,6 +41,57 @@ public class LlmRequestEnvelope public LlmRequestEnvelope WithCancellationToken(CancellationToken cancellationToken) => Clone(cancellationToken); + public LlmRequestEnvelope WithTraceAndHints( + string traceId, + IReadOnlyDictionary? extraHints) + { + Dictionary? mergedHints = null; + if (Hints != null && Hints.Count > 0) + { + mergedHints = new Dictionary(StringComparer.Ordinal); + foreach (var kvp in Hints) + { + if (!string.IsNullOrEmpty(kvp.Key) && kvp.Value != null) + mergedHints[kvp.Key] = kvp.Value; + } + } + if (extraHints != null && extraHints.Count > 0) + { + mergedHints ??= new Dictionary(StringComparer.Ordinal); + foreach (var kvp in extraHints) + { + if (!string.IsNullOrEmpty(kvp.Key) && kvp.Value != null) + mergedHints[kvp.Key] = kvp.Value; + } + } + + return new LlmRequestEnvelope + { + RequestId = RequestId, + TraceId = string.IsNullOrWhiteSpace(traceId) ? TraceId : traceId, + ScenarioId = ScenarioId, + ModId = ModId, + Messages = Messages, + SystemAugmentations = SystemAugmentations, + JsonSchema = JsonSchema, + Tools = Tools, + ToolDispatchMode = ToolDispatchMode, + Examples = Examples, + MaxTokens = MaxTokens, + Temperature = Temperature, + ReasoningEffort = ReasoningEffort, + Priority = Priority, + ExpireAtTicks = ExpireAtTicks, + MaxRetryCount = MaxRetryCount, + IsStreaming = IsStreaming, + OnStreamChunk = OnStreamChunk, + Ct = Ct, + NpcId = NpcId, + GameStateInfo = GameStateInfo, + Hints = mergedHints, + }; + } + public LlmRequestEnvelope Clone(CancellationToken? cancellationToken = null) { return new LlmRequestEnvelope { @@ -55,6 +107,7 @@ public LlmRequestEnvelope Clone(CancellationToken? cancellationToken = null) Examples = Examples, MaxTokens = MaxTokens, Temperature = Temperature, + ReasoningEffort = ReasoningEffort, Priority = Priority, ExpireAtTicks = ExpireAtTicks, MaxRetryCount = MaxRetryCount, diff --git a/Source/Domain/Llm/ReasoningEffort.cs b/Source/Domain/Llm/ReasoningEffort.cs new file mode 100644 index 0000000..1c64a81 --- /dev/null +++ b/Source/Domain/Llm/ReasoningEffort.cs @@ -0,0 +1,28 @@ +namespace RimMind.Domain.Llm +{ + /// + /// Semantic reasoning-depth hint for LLM requests. + /// Downstream protocol adapters translate this intent into vendor-specific parameters + /// (for example, disabling thinking on real-time dialogue or enabling deeper reasoning on planning). + /// + public enum ReasoningEffort + { + /// Let the target endpoint or node policy decide. + Auto = 0, + + /// Disable explicit chain-of-thought reasoning for low-latency responses. + None = 1, + + /// Light reasoning budget for simple structured tasks. + Low = 2, + + /// Moderate reasoning budget. + Medium = 3, + + /// Deep reasoning budget for multi-step agent decisions and planning. + High = 4, + + /// Maximum reasoning budget supported by the endpoint. + Max = 5, + } +} diff --git a/Source/Domain/ValueObjects/RimMindErrorCode.cs b/Source/Domain/ValueObjects/RimMindErrorCode.cs index fd54041..67d1e25 100644 --- a/Source/Domain/ValueObjects/RimMindErrorCode.cs +++ b/Source/Domain/ValueObjects/RimMindErrorCode.cs @@ -6,6 +6,8 @@ public enum RimMindErrorCode ClientTransientFailure = 1001, ClientPermanentFailure = 1002, ClientCircuitOpen = 1003, + ContentFiltered = 1004, + ClientQuotaOrAuthFailure = 1005, ContextBuildFailed = 2000, PipelineShortCircuited = 2001, diff --git a/Source/Domain/ValueObjects/RimMindErrors.cs b/Source/Domain/ValueObjects/RimMindErrors.cs index 79dbbf3..ce869b8 100644 --- a/Source/Domain/ValueObjects/RimMindErrors.cs +++ b/Source/Domain/ValueObjects/RimMindErrors.cs @@ -23,6 +23,18 @@ public static class RimMindErrors TraceId = TraceContext.Current, }; + public static RimMindError ContentFiltered(string message, Exception? inner = null) => new(RimMindErrorCode.ContentFiltered, message) + { + InnerException = inner, + TraceId = TraceContext.Current, + }; + + public static RimMindError ClientQuotaOrAuth(string message, Exception? inner = null) => new(RimMindErrorCode.ClientQuotaOrAuthFailure, message) + { + InnerException = inner, + TraceId = TraceContext.Current, + }; + public static RimMindError CircuitOpen() => new(RimMindErrorCode.ClientCircuitOpen, "Circuit breaker is open") { TraceId = TraceContext.Current, diff --git a/Source/Infrastructure/Agent/MechanismActionExecutor.cs b/Source/Infrastructure/Agent/MechanismActionExecutor.cs index 6132853..8255f67 100644 --- a/Source/Infrastructure/Agent/MechanismActionExecutor.cs +++ b/Source/Infrastructure/Agent/MechanismActionExecutor.cs @@ -141,11 +141,12 @@ private string AdaptToolArguments(IToolHandler tool, AgentDecision decision, int try { var parsed = JToken.Parse(decision.Param!); - obj = parsed as JObject ?? new JObject(); + obj = parsed as JObject ?? BuildObjectFromScalarParam(toolId, parsed.Type == JTokenType.String ? parsed.Value() : parsed.ToString()); } catch { - obj = new JObject(); + // Plain text Param (e.g. "Construction"): keep it as the def target instead of discarding it. + obj = BuildObjectFromScalarParam(toolId, decision.Param); } } else @@ -160,11 +161,25 @@ private string AdaptToolArguments(IToolHandler tool, AgentDecision decision, int string.Equals(toolId, "prioritize_work", StringComparison.OrdinalIgnoreCase) || string.Equals(toolId, "take_job", StringComparison.OrdinalIgnoreCase); - bool shouldOverride = isSelfTargetedTool || !obj.ContainsKey("pawn_id") || obj["pawn_id"]?.Type == JTokenType.String; - if (!shouldOverride && obj["pawn_id"]?.Type == JTokenType.Integer) + // Only fill pawn_id when it is missing or unparseable. An explicit but non-resolving id must + // reach the mechanism and fail there; silently redirecting it to the caller made target-style + // writes (thought/inspiration/mental state) land on the wrong pawn while reporting success. + bool shouldOverride = isSelfTargetedTool || !obj.ContainsKey("pawn_id"); + if (!shouldOverride) { - int existingId = obj["pawn_id"]!.Value(); - if (existingId <= 0 || RimMind.Presentation.Api.RimMindPawnLookup.FindPawnByNumber(existingId) == null) + var rawId = obj["pawn_id"]; + if (rawId?.Type == JTokenType.Integer) + { + shouldOverride = rawId.Value() <= 0; + } + else if (rawId?.Type == JTokenType.String) + { + if (RimMind.Application.Features.Tools.PawnIdParser.TryParse(rawId.Value(), out int parsedId) && parsedId > 0) + obj["pawn_id"] = parsedId; + else + shouldOverride = true; + } + else { shouldOverride = true; } @@ -176,6 +191,30 @@ private string AdaptToolArguments(IToolHandler tool, AgentDecision decision, int } } + if (string.Equals(toolId, "pawn.job.set", StringComparison.OrdinalIgnoreCase) || + string.Equals(toolId, "pawn_job_set", StringComparison.OrdinalIgnoreCase)) + { + string? currentAction = obj.Value("action"); + if (string.IsNullOrWhiteSpace(currentAction) || + string.Equals(currentAction, "set", StringComparison.OrdinalIgnoreCase)) + { + if (obj["work_type"] != null || obj["job_type"] != null || obj["def_name"] != null) + { + obj["action"] = "assign_work"; + } + else if (obj["cell_x"] != null || obj["x"] != null) + { + obj["action"] = "move_to"; + } + else if (ContainsFoodKeyword(decision.Param) || ContainsFoodKeyword(decision.Reason)) + { + obj["action"] = "eat_food"; + } + // Otherwise leave 'action' unset: pawn.job rejects it with the list of valid operations. + // A silent force_rest default made colonists lie down instead of working or eating. + } + } + var adapters = GetArgumentAdapters(); if (adapters != null) { @@ -194,6 +233,44 @@ private string AdaptToolArguments(IToolHandler tool, AgentDecision decision, int return obj.ToString(Newtonsoft.Json.Formatting.None); } + private static JObject BuildObjectFromScalarParam(string toolId, string? raw) + { + var obj = new JObject(); + var value = raw?.Trim().Trim('"'); + if (string.IsNullOrWhiteSpace(value)) return obj; + + // pawn.job.set resolves its sub-action from keywords below; a def target would force assign_work. + if (string.Equals(toolId, "pawn.job.set", StringComparison.OrdinalIgnoreCase) + || string.Equals(toolId, "pawn_job_set", StringComparison.OrdinalIgnoreCase)) + return obj; + + obj["def_name"] = value; + if (IsWorkPriorityTool(toolId)) + { + obj["work_type"] = value; + obj["priority"] = 1; + } + return obj; + } + + private static bool IsWorkPriorityTool(string toolId) + { + return string.Equals(toolId, "pawn.work.set", StringComparison.OrdinalIgnoreCase) + || string.Equals(toolId, "pawn_work_set", StringComparison.OrdinalIgnoreCase) + || string.Equals(toolId, "prioritize_work", StringComparison.OrdinalIgnoreCase); + } + + private static readonly System.Text.RegularExpressions.Regex FoodKeywordPattern = new System.Text.RegularExpressions.Regex( + @"\b(eat|eating|food|meal|meals|hunger|hungry|starving|starvation|nutrition)\b", + System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.CultureInvariant); + + private static bool ContainsFoodKeyword(string? text) + { + if (string.IsNullOrEmpty(text)) return false; + // Whole words only: substring matching turned "retreat from the threat" into eat_food. + return FoodKeywordPattern.IsMatch(text!); + } + private IReadOnlyList? GetArgumentAdapters() { if (_argumentAdapterProvider != null) diff --git a/Source/Infrastructure/Mechanisms/GameMechanismBaseNoDef.cs b/Source/Infrastructure/Mechanisms/GameMechanismBaseNoDef.cs index 0314f98..b8dca38 100644 --- a/Source/Infrastructure/Mechanisms/GameMechanismBaseNoDef.cs +++ b/Source/Infrastructure/Mechanisms/GameMechanismBaseNoDef.cs @@ -96,6 +96,17 @@ public virtual Task> ExecuteWatchAsync(MechanismWrite }; return null; } + if (!allowDowned && pawn.InMentalState) + { + // Behaviour actions (allowDowned=false) need a pawn that obeys orders; mentally broken + // pawns ignore them in vanilla, so reporting success would be a fake outcome. + // State writes (work priorities, thoughts, needs) pass allowDowned=true and stay allowed. + error = RimMindErrors.PawnNotFound(pawnId) with + { + Message = $"Pawn with ID {pawnId} is in a mental state ({pawn.MentalStateDef?.label}) and cannot be controlled" + }; + return null; + } error = null; return pawn; } diff --git a/Source/Infrastructure/Mechanisms/MechanismToolHandler.cs b/Source/Infrastructure/Mechanisms/MechanismToolHandler.cs index fbb5b29..0ebac96 100644 --- a/Source/Infrastructure/Mechanisms/MechanismToolHandler.cs +++ b/Source/Infrastructure/Mechanisms/MechanismToolHandler.cs @@ -54,7 +54,11 @@ public sealed class MechanismToolHandler : IToolHandler "x", "z", "cell_x", - "cell_z" + "cell_z", + "queue_position", + "priorities_json", + "jobs_json", + "job_index" }; private readonly IMechanismReader _reader; @@ -219,6 +223,7 @@ private MechanismWriteArgs BuildWriteArgs(JObject? root, ToolCallArgs args, int DefName = defName, Action = ExtractString(root, "action") ?? _operation.ToString().ToLowerInvariant(), ValueJson = ExtractValueJson(root), + RawArgumentsJson = args.ArgumentsJson, TraceId = args.TraceId, Params = paramsDict }; @@ -241,15 +246,37 @@ private MechanismWriteArgs BuildWriteArgs(JObject? root, ToolCallArgs args, int } } + internal static Func? PawnExistsPredicate { get; set; } + internal static int ResolvePawnId(JObject? root, ToolCallArgs args, string key = "pawn_id") => ResolveTargetPawn(root, args, key).PawnId; /// /// Resolves the target pawn through the shared (root or nested params; /// accepts 12, "Pawn_12", "NPC-12"; falls back to the caller's PawnId, then NpcId). + /// Also falls back to the caller pawn if the LLM guessed a small ordinal id (1..20) that does not exist + /// in the game while the caller pawn exists. /// internal static PawnTargetResolution ResolveTargetPawn(JObject? root, ToolCallArgs args, string key = "pawn_id") - => PawnIdParser.ResolveTarget(root, key, args.PawnId, args.NpcId); + { + var resolution = PawnIdParser.ResolveTarget(root, key, args.PawnId, args.NpcId); + if (resolution.IsValid && resolution.IsExplicit && resolution.PawnId >= 1 && resolution.PawnId <= 20) + { + int callerId = args.PawnId.HasValue && args.PawnId.Value > 0 + ? args.PawnId.Value + : (PawnIdParser.TryParse(args.NpcId, out var parsedNpc) && parsedNpc > 0 ? parsedNpc : 0); + var pawnExists = PawnExistsPredicate; + if (callerId > 0 + && callerId != resolution.PawnId + && pawnExists != null + && !pawnExists(resolution.PawnId) + && pawnExists(callerId)) + { + return PawnTargetResolution.Fallback(callerId); + } + } + return resolution; + } internal static RimMindError InvalidPawnTargetError(string toolId, PawnTargetResolution target) => RimMindErrors.ToolExecution( @@ -576,7 +603,11 @@ private static ToolDefinition BuildDefinition(IMechanismMetadata metadata, Mecha Manifest = new ToolManifest { RiskLevel = MapRisk(mechanismRisk), - RequiresApproval = mechanismRisk >= MechanismRisk.Dangerous + RequiresApproval = mechanismRisk >= MechanismRisk.Dangerous, + DefaultDomain = string.Equals(metadata.MechanismId, "pawn.work", StringComparison.OrdinalIgnoreCase) + && operation == MechanismOperationType.Set + ? RimMind.Domain.Agent.Policies.AutonomyDomain.WorkPriorityModification + : (RimMind.Domain.Agent.Policies.AutonomyDomain?)null } }; } diff --git a/Source/Infrastructure/Mechanisms/Pawn/Draft/DraftMechanism.cs b/Source/Infrastructure/Mechanisms/Pawn/Draft/DraftMechanism.cs index 6d8718d..eab7940 100644 --- a/Source/Infrastructure/Mechanisms/Pawn/Draft/DraftMechanism.cs +++ b/Source/Infrastructure/Mechanisms/Pawn/Draft/DraftMechanism.cs @@ -25,14 +25,15 @@ public sealed class DraftMechanism : GameMechanismBaseNoDef { Summary = "Toggle pawn draft status", QueryDescription = "Query whether the pawn is currently drafted", - ToggleDescription = "Toggle pawn draft status. Actions: draft, undraft. Optional: urgent=true for emergency draft." + ToggleDescription = "Toggle pawn draft status. Actions: draft, undraft, toggle. Optional: urgent=true for emergency draft." }; private static readonly IReadOnlyList _writeActions = new List { new MechanismActionInfo { Action = "draft", Description = "Draft the pawn into combat mode" }, - new MechanismActionInfo { Action = "undraft", Description = "Remove the pawn from combat mode" } + new MechanismActionInfo { Action = "undraft", Description = "Remove the pawn from combat mode" }, + new MechanismActionInfo { Action = "toggle", Description = "Flip the pawn's current draft state" } }.AsReadOnly(); public override IReadOnlyList? GetWriteActions() => _writeActions; @@ -69,6 +70,11 @@ public override Task> ExecuteToggleAsync(MechanismWri case "undraft": pawn.drafter.Drafted = false; return Task.FromResult(Result.Ok(true)); + case "toggle": + case "": + case null: + pawn.drafter.Drafted = !pawn.drafter.Drafted; + return Task.FromResult(Result.Ok(true)); default: return Task.FromResult(Result.Err(RimMindErrors.InvalidAction(MechanismId, args.Action))); } diff --git a/Source/Infrastructure/Mechanisms/Pawn/Interaction/InteractionMechanism.cs b/Source/Infrastructure/Mechanisms/Pawn/Interaction/InteractionMechanism.cs index 65f0c56..a514d3d 100644 --- a/Source/Infrastructure/Mechanisms/Pawn/Interaction/InteractionMechanism.cs +++ b/Source/Infrastructure/Mechanisms/Pawn/Interaction/InteractionMechanism.cs @@ -76,18 +76,67 @@ public override Task> ExecuteTriggerAsync(MechanismWr var job = joyGiver.Worker.TryGiveJob(pawn); if (job != null) { - pawn.jobs.StartJob(job, JobCondition.InterruptForced); - return Task.FromResult(Result.Ok(true)); + return Task.FromResult(RimMind.Infrastructure.Mechanisms.Pawn.Job.JobActionDispatcher.StartJobVerified(pawn, job, MechanismId)); } } + + foreach (var fallbackGiver in DefDatabase.AllDefsListForReading) + { + if (fallbackGiver == null || fallbackGiver.defName == "SocialRelax" || fallbackGiver.Worker == null) + continue; + try + { + var fallbackJob = fallbackGiver.Worker.TryGiveJob(pawn); + if (fallbackJob != null) + { + return Task.FromResult(RimMind.Infrastructure.Mechanisms.Pawn.Job.JobActionDispatcher.StartJobVerified(pawn, fallbackJob, MechanismId)); + } + } + catch + { + // Ignore individual joy giver exceptions and try next + } + } + + var nearbyPeer = targetPawn; + if (nearbyPeer == null && pawn.Map != null) + { + var colonists = RimMind.Presentation.Api.RimMindPawnLookup.GetSpawnedColonistsSafe(pawn.Map); + for (int i = 0; i < colonists.Count; i++) + { + var other = colonists[i]; + if (other != null && other != pawn && RimMind.Presentation.Api.RimMindPawnLookup.IsActiveSpawnedColonist(other) && !other.Downed) + { + nearbyPeer = other; + break; + } + } + } + + if (nearbyPeer != null) + { + InteractionDef chitchatDef = DefDatabase.GetNamedSilentFail("Chitchat"); + if (chitchatDef != null) + { + try { pawn.interactions?.TryInteractWith(nearbyPeer, chitchatDef); } catch { } + } + } + + if (JobDefOf.Wait_Wander != null && pawn.jobs != null) + { + var wanderJob = JobMaker.MakeJob(JobDefOf.Wait_Wander); + wanderJob.expiryInterval = 600; + wanderJob.checkOverrideOnExpire = true; + return Task.FromResult(RimMind.Infrastructure.Mechanisms.Pawn.Job.JobActionDispatcher.StartJobVerified(pawn, wanderJob, MechanismId)); + } + return Task.FromResult(Result.Err(RimMindErrors.InvalidAction(MechanismId, "social_relax: no social relax available"))); case "give_item": if (targetPawn == null) return Task.FromResult(Result.Err(RimMindErrors.PawnNotFound(targetPawnId))); var giveJob = JobMaker.MakeJob(JobDefOf.Goto, new LocalTargetInfo(targetPawn)); - pawn.jobs.StartJob(giveJob, JobCondition.InterruptForced); - return Task.FromResult(Result.Ok(true)); + return Task.FromResult(RimMind.Infrastructure.Mechanisms.Pawn.Job.JobActionDispatcher.StartJobVerified(pawn, giveJob, MechanismId)); case "romance_attempt": if (targetPawn == null) diff --git a/Source/Infrastructure/Mechanisms/Pawn/Job/JobActionDispatcher.cs b/Source/Infrastructure/Mechanisms/Pawn/Job/JobActionDispatcher.cs index eef61c6..e5e9205 100644 --- a/Source/Infrastructure/Mechanisms/Pawn/Job/JobActionDispatcher.cs +++ b/Source/Infrastructure/Mechanisms/Pawn/Job/JobActionDispatcher.cs @@ -1,4 +1,7 @@ +using System; +using System.Collections.Generic; using System.Linq; +using Newtonsoft.Json.Linq; using RimMind.Application.Common.Interfaces.Mechanisms; using RimMind.Application.Common.Models.Mechanisms; using RimMind.Domain.ValueObjects; @@ -12,16 +15,75 @@ namespace RimMind.Infrastructure.Mechanisms.Pawn.Job { public static class JobActionDispatcher { + [ThreadStatic] + private static bool _captureJobForQueue; + + [ThreadStatic] + private static VerseJob? _capturedQueueJob; + + /// + /// Starts a forced job and verifies the game actually accepted it. StartJob can silently + /// refuse (mental state, drafted pawn, failed reservation, job ending on its first toil); + /// reporting Ok in that case is a fake ToolCall success that misleads the agent loop. + /// + public static Result StartJobVerified(VersePawn pawn, VerseJob job, string mechanismId = "pawn.job") + { + if (pawn?.jobs == null || job == null) + return Result.Err(RimMindErrors.InvalidAction(mechanismId, "no job tracker or job")); + if (_captureJobForQueue) + { + _capturedQueueJob = job; + return Result.Ok(true); + } + pawn.jobs.StartJob(job, JobCondition.InterruptForced); + if (!ReferenceEquals(pawn.CurJob, job)) + { + return Result.Err(RimMindErrors.InvalidAction( + mechanismId, + $"game did not start job '{job.def?.defName}' for {pawn.LabelShort} (current job: {pawn.CurJobDef?.defName ?? "none"})")); + } + return Result.Ok(true); + } public static Result HandleAssignWork(VersePawn pawn, MechanismWriteArgs args) { var workType = ExtractParam(args, "work_type") ?? ExtractParam(args, "job_type") ?? args.DefName; if (string.IsNullOrEmpty(workType)) - return Result.Err(RimMindErrors.InvalidAction("pawn.job", "assign_work: missing work_type")); + { + // No explicit work type: let the pawn pick its highest-priority available work + // through the vanilla work scanner instead of failing the whole decision. + VerseJob? anyWork = null; + try + { + anyWork = new JobGiver_Work().TryIssueJobPackage(pawn, default).Job; + } + catch + { + anyWork = null; + } + if (anyWork == null) + return Result.Err(RimMindErrors.InvalidAction("pawn.job", "assign_work: missing work_type and no available work found")); + return StartJobVerified(pawn, anyWork); + } var candidateGivers = ResolveCandidateWorkGivers(workType!); - if (candidateGivers.Count == 0) + var workTypeDef = ResolveWorkTypeDef(workType!, candidateGivers); + if (candidateGivers.Count == 0 && workTypeDef == null) return Result.Err(RimMindErrors.InvalidDefName(workType ?? "")); + bool priorityUpdated = false; + if (workTypeDef != null + && pawn.workSettings != null + && pawn.workSettings.EverWork + && !pawn.WorkTypeIsDisabled(workTypeDef) + && RimMind.Presentation.Api.RimMindAPI.Autonomy.CanExecuteAutonomous( + pawn, + RimMind.Domain.Agent.Policies.AutonomyDomain.WorkPriorityModification)) + { + pawn.workSettings.EnableAndInitializeIfNotAlreadyInitialized(); + pawn.workSettings.SetPriority(workTypeDef, 1); + priorityUpdated = true; + } + foreach (var workGiver in candidateGivers) { if (workGiver?.Worker == null) continue; @@ -31,14 +93,46 @@ public static Result HandleAssignWork(VersePawn pawn, Mechan if (job != null) { job.workGiverDef = workGiver; - pawn.jobs.StartJob(job, JobCondition.InterruptForced); - return Result.Ok(true); + return StartJobVerified(pawn, job); + } + } + + if (!_captureJobForQueue && (priorityUpdated || (workTypeDef != null && !pawn.WorkTypeIsDisabled(workTypeDef)))) + { + try + { + pawn.jobs?.CheckForJobOverride(); } + catch + { + // Ignore job override transient errors + } + return Result.Ok(true); } return Result.Err(RimMindErrors.Internal($"No actionable target on map for work/job '{workType}'")); } + private static WorkTypeDef? ResolveWorkTypeDef(string rawType, System.Collections.Generic.List candidateGivers) + { + var trimmed = rawType.Trim(); + var direct = DefDatabase.GetNamedSilentFail(trimmed); + if (direct != null) return direct; + + foreach (var wt in DefDatabase.AllDefsListForReading) + { + if (wt == null) continue; + if (string.Equals(wt.defName, trimmed, System.StringComparison.OrdinalIgnoreCase) || + string.Equals(wt.labelShort, trimmed, System.StringComparison.OrdinalIgnoreCase) || + string.Equals(wt.gerundLabel, trimmed, System.StringComparison.OrdinalIgnoreCase)) + { + return wt; + } + } + + return candidateGivers.FirstOrDefault(g => g?.workType != null)?.workType; + } + private static System.Collections.Generic.List ResolveCandidateWorkGivers(string rawType) { var list = new System.Collections.Generic.List(); @@ -88,64 +182,82 @@ private static System.Collections.Generic.List ResolveCandidateWor private static VerseJob? TryFindJobFromGiver(VersePawn pawn, WorkGiverDef workGiver) { + if (workGiver?.Worker == null) return null; VerseJob? job = null; - if (workGiver.Worker is WorkGiver_Scanner scanner) + try { - job = scanner.NonScanJob(pawn); - if (job == null && scanner.def.scanThings) + if (workGiver.Worker is WorkGiver_Scanner scanner) { - var potentialThings = scanner.PotentialWorkThingsGlobal(pawn); - if (potentialThings != null) + if (scanner.ShouldSkip(pawn, forced: true) || scanner.MissingRequiredCapacity(pawn) != null) + return null; + + job = scanner.NonScanJob(pawn); + if (job == null && scanner.def.scanThings) { - foreach (var t in potentialThings) + var potentialThings = scanner.PotentialWorkThingsGlobal(pawn); + if (potentialThings != null) { - if (t != null && !t.IsForbidden(pawn) && scanner.HasJobOnThing(pawn, t) && pawn.CanReach(t, scanner.PathEndMode, Danger.Deadly)) + foreach (var t in potentialThings) { - job = scanner.JobOnThing(pawn, t, true); - if (job != null) break; + if (t != null && !t.IsForbidden(pawn) && scanner.HasJobOnThing(pawn, t, forced: true) && pawn.CanReach(t, scanner.PathEndMode, Danger.Deadly)) + { + job = scanner.JobOnThing(pawn, t, forced: true); + if (job != null) break; + } } } - } - else if (pawn.Map != null) - { - var target = GenClosest.ClosestThingReachable( - pawn.Position, - pawn.Map, - scanner.PotentialWorkThingRequest, - scanner.PathEndMode, - TraverseParms.For(pawn, Danger.Deadly), - 9999f, - t => !t.IsForbidden(pawn) && scanner.HasJobOnThing(pawn, t)); - if (target != null) + else if (pawn.Map != null) { - job = scanner.JobOnThing(pawn, target, true); + var target = GenClosest.ClosestThingReachable( + pawn.Position, + pawn.Map, + scanner.PotentialWorkThingRequest, + scanner.PathEndMode, + TraverseParms.For(pawn, Danger.Deadly), + 9999f, + t => !t.IsForbidden(pawn) && scanner.HasJobOnThing(pawn, t, forced: true)); + if (target != null) + { + job = scanner.JobOnThing(pawn, target, forced: true); + } } } - } - if (job == null && scanner.def.scanCells) - { - var potentialCells = scanner.PotentialWorkCellsGlobal(pawn); - if (potentialCells != null) + if (job == null && scanner.def.scanCells) { - foreach (var c in potentialCells) + var potentialCells = scanner.PotentialWorkCellsGlobal(pawn); + if (potentialCells != null) { - if (!c.IsForbidden(pawn) && scanner.HasJobOnCell(pawn, c) && pawn.CanReach(c, scanner.PathEndMode, Danger.Deadly)) + foreach (var c in potentialCells) { - job = scanner.JobOnCell(pawn, c, true); - if (job != null) break; + if (!c.IsForbidden(pawn) && scanner.HasJobOnCell(pawn, c, forced: true) && pawn.CanReach(c, scanner.PathEndMode, Danger.Deadly)) + { + job = scanner.JobOnCell(pawn, c, forced: true); + if (job != null) break; + } } } + else if (pawn.Map != null && scanner.HasJobOnCell(pawn, pawn.Position, forced: true)) + { + job = scanner.JobOnCell(pawn, pawn.Position, forced: true); + } } - else if (pawn.Map != null && scanner.HasJobOnCell(pawn, pawn.Position)) - { - job = scanner.JobOnCell(pawn, pawn.Position, true); - } + } + else + { + if (workGiver.Worker.ShouldSkip(pawn, forced: true) || workGiver.Worker.MissingRequiredCapacity(pawn) != null) + return null; + job = workGiver.Worker.NonScanJob(pawn); + } + + if (job != null) + { + job.workGiverDef ??= workGiver; } } - else + catch { - job = workGiver.Worker.NonScanJob(pawn); + return null; } return job; @@ -176,30 +288,81 @@ public static Result HandleMoveTo(VersePawn pawn, MechanismW return Result.Err(RimMindErrors.InvalidAction("pawn.job", "move_to: cannot reach cell")); var job = JobMaker.MakeJob(JobDefOf.Goto, new LocalTargetInfo(cell)); - pawn.jobs.StartJob(job, JobCondition.InterruptForced); - return Result.Ok(true); + return StartJobVerified(pawn, job); } public static Result HandleEatFood(VersePawn pawn, MechanismWriteArgs args) { var food = pawn.inventory?.innerContainer?.FirstOrDefault( - t => t != null && !t.Destroyed && t.def.IsNutritionGivingIngestible && t.IngestibleNow); + t => t != null && !t.Destroyed && t.def != null && t.def.IsNutritionGivingIngestible && t.IngestibleNow); + var map = pawn.Map ?? Find.CurrentMap; + if (food == null && map != null && map.resourceCounter?.AllCountedAmounts != null) + { + foreach (var entry in map.resourceCounter.AllCountedAmounts) + { + if (entry.Key != null && entry.Key.IsNutritionGivingIngestible && entry.Value > 0) + { + food = map.listerThings?.ThingsOfDef(entry.Key)?.FirstOrDefault( + t => t != null && !t.Destroyed && t.Spawned && !t.IsForbidden(pawn) && t.IngestibleNow + && pawn.CanReserveAndReach(t, PathEndMode.OnCell, Danger.Deadly)); + if (food != null) break; + } + } + } + if (food == null) { - var map = pawn.Map ?? Find.CurrentMap; - if (map != null) + try { - foreach (var entry in map.resourceCounter.AllCountedAmounts) + if (FoodUtility.TryFindBestFoodSourceFor( + pawn, + pawn, + desperate: true, + out var bestFood, + out _, + canRefillDispenser: true, + canUseInventory: true, + allowForbidden: false) && bestFood != null && !bestFood.Destroyed) { - if (entry.Key.IsNutritionGivingIngestible && entry.Value > 0) - { - food = map.listerThings?.ThingsOfDef(entry.Key)?.FirstOrDefault( - t => t != null && !t.Destroyed && t.Spawned && !t.IsForbidden(pawn) && t.IngestibleNow - && pawn.CanReserveAndReach(t, PathEndMode.OnCell, Danger.Deadly)); - if (food != null) break; - } + food = bestFood; } } + catch + { + // Fallback to direct map scan below + } + } + + if (food == null && map?.listerThings?.AllThings != null) + { + float bestDistSq = float.MaxValue; + var allThings = map.listerThings.AllThings; + for (int i = 0; i < allThings.Count; i++) + { + var t = allThings[i]; + if (t == null || t.Destroyed || !t.Spawned || t.def == null || !t.def.IsNutritionGivingIngestible) + continue; + if (t.IsForbidden(pawn) || !t.IngestibleNow) + continue; + if (!pawn.CanReserveAndReach(t, PathEndMode.OnCell, Danger.Deadly)) + continue; + + float distSq = (t.Position - pawn.Position).LengthHorizontalSquared; + if (distSq < bestDistSq) + { + bestDistSq = distSq; + food = t; + } + } + } + + if (food == null && map != null) + { + var harvestPlantJob = TryDesignateAndHarvestWildFoodPlant(pawn, map); + if (harvestPlantJob != null) + { + return StartJobVerified(pawn, harvestPlantJob); + } } if (food == null) @@ -209,16 +372,96 @@ public static Result HandleEatFood(VersePawn pawn, Mechanism var job = JobMaker.MakeJob(JobDefOf.Ingest, new LocalTargetInfo(food)); job.count = System.Math.Max(1, FoodUtility.WillIngestStackCountOf(pawn, food.def, food.GetStatValue(StatDefOf.Nutrition))); - pawn.jobs.StartJob(job, JobCondition.InterruptForced); - return Result.Ok(true); + return StartJobVerified(pawn, job); + } + + private static VerseJob? TryDesignateAndHarvestWildFoodPlant(VersePawn pawn, global::Verse.Map map) + { + if (map.listerThings == null || map.designationManager == null) + return null; + + var plants = map.listerThings.ThingsInGroup(ThingRequestGroup.Plant); + if (plants == null || plants.Count == 0) + return null; + + Plant? nearestPlant = null; + float bestDistSq = float.MaxValue; + int designatedCount = 0; + + for (int i = 0; i < plants.Count; i++) + { + if (plants[i] is not Plant plant || plant.Destroyed || !plant.Spawned || plant.def?.plant == null) + continue; + if (plant.def.plant.IsTree || !plant.def.plant.Harvestable || !plant.HarvestableNow) + continue; + + var harvestedDef = plant.def.plant.harvestedThingDef; + if (harvestedDef == null || !harvestedDef.IsNutritionGivingIngestible || harvestedDef.ingestible == null || !harvestedDef.ingestible.HumanEdible) + continue; + if (plant.IsForbidden(pawn) || !pawn.CanReserveAndReach(plant, PathEndMode.Touch, Danger.Deadly)) + continue; + + if (designatedCount < 10 && map.designationManager.DesignationOn(plant, DesignationDefOf.HarvestPlant) == null) + { + map.designationManager.AddDesignation(new Designation(plant, DesignationDefOf.HarvestPlant)); + designatedCount++; + } + + float distSq = (plant.Position - pawn.Position).LengthHorizontalSquared; + if (distSq < bestDistSq) + { + bestDistSq = distSq; + nearestPlant = plant; + } + } + + if (nearestPlant != null && !pawn.WorkTagIsDisabled(WorkTags.PlantWork)) + { + if (pawn.workSettings != null + && pawn.workSettings.EverWork + && !pawn.WorkTypeIsDisabled(WorkTypeDefOf.PlantCutting) + && RimMind.Presentation.Api.RimMindAPI.Autonomy.CanExecuteAutonomous( + pawn, + RimMind.Domain.Agent.Policies.AutonomyDomain.WorkPriorityModification)) + { + pawn.workSettings.EnableAndInitializeIfNotAlreadyInitialized(); + pawn.workSettings.SetPriority(WorkTypeDefOf.PlantCutting, 1); + } + + var plantsCutGiver = DefDatabase.GetNamedSilentFail("PlantsCut"); + if (plantsCutGiver?.Worker is WorkGiver_Scanner scanner) + { + try + { + if (scanner.HasJobOnThing(pawn, nearestPlant, forced: true)) + { + var giverJob = scanner.JobOnThing(pawn, nearestPlant, forced: true); + if (giverJob != null) + { + giverJob.workGiverDef = plantsCutGiver; + return giverJob; + } + } + } + catch + { + // Fallback to direct HarvestDesignated job on nearestPlant + } + } + + var fallbackHarvestJob = JobMaker.MakeJob(JobDefOf.HarvestDesignated, new LocalTargetInfo(nearestPlant)); + fallbackHarvestJob.workGiverDef = plantsCutGiver; + return fallbackHarvestJob; + } + + return null; } public static Result HandleForceRest(VersePawn pawn, MechanismWriteArgs args) { var bed = RestUtility.FindBedFor(pawn); var job = bed != null ? JobMaker.MakeJob(JobDefOf.LayDown, new LocalTargetInfo(bed)) : JobMaker.MakeJob(JobDefOf.LayDown, pawn.Position); - pawn.jobs.StartJob(job, JobCondition.InterruptForced); - return Result.Ok(true); + return StartJobVerified(pawn, job); } public static Result HandleTendPawn(VersePawn pawn, MechanismWriteArgs args) @@ -233,8 +476,7 @@ public static Result HandleTendPawn(VersePawn pawn, Mechanis var job = JobMaker.MakeJob(JobDefOf.TendPatient, new LocalTargetInfo(targetPawn)); job.count = 1; - pawn.jobs.StartJob(job, JobCondition.InterruptForced); - return Result.Ok(true); + return StartJobVerified(pawn, job); } public static Result HandleRescuePawn(VersePawn pawn, MechanismWriteArgs args) @@ -250,8 +492,7 @@ public static Result HandleRescuePawn(VersePawn pawn, Mechan var job = JobMaker.MakeJob(JobDefOf.Rescue, targetPawn, bed); job.count = 1; - pawn.jobs.StartJob(job, JobCondition.InterruptForced); - return Result.Ok(true); + return StartJobVerified(pawn, job); } public static Result HandleArrestPawn(VersePawn pawn, MechanismWriteArgs args) @@ -267,8 +508,7 @@ public static Result HandleArrestPawn(VersePawn pawn, Mechan var job = JobMaker.MakeJob(JobDefOf.Arrest, targetPawn, bed); job.count = 1; - pawn.jobs.StartJob(job, JobCondition.InterruptForced); - return Result.Ok(true); + return StartJobVerified(pawn, job); } public static Result HandleCancelJob(VersePawn pawn, MechanismWriteArgs args) @@ -280,6 +520,281 @@ public static Result HandleCancelJob(VersePawn pawn, Mechani return Result.Ok(true); } + public static Result HandleEnqueueJob(VersePawn pawn, MechanismWriteArgs args) + { + if (pawn?.jobs == null) + return Result.Err(RimMindErrors.InvalidAction("pawn.job", "enqueue_job: pawn has no job tracker")); + + string subAction = ResolveQueueSubAction(args); + if (string.IsNullOrEmpty(subAction)) + { + return Result.Err(RimMindErrors.InvalidAction( + "pawn.job", + "enqueue_job: specify job_action (assign_work, move_to, eat_food, force_rest, tend_pawn, rescue_pawn) or work_type / cell_x")); + } + + if (!TryBuildJobWithoutStarting(pawn, subAction, args, out var job, out var buildError) || job == null) + { + return Result.Err(buildError ?? RimMindErrors.InvalidAction("pawn.job", $"enqueue_job: failed to build job for '{subAction}'")); + } + + job.playerForced = true; + if (pawn.jobs.curJob == null) + return StartJobVerified(pawn, job); + + string? queuePosition = ExtractParam(args, "queue_position"); + if (string.Equals(queuePosition, "first", StringComparison.OrdinalIgnoreCase)) + pawn.jobs.jobQueue.EnqueueFirst(job); + else + pawn.jobs.jobQueue.EnqueueLast(job); + + return Result.Ok(true); + } + + public static Result HandleQueueJobChain(VersePawn pawn, MechanismWriteArgs args) + { + if (pawn?.jobs == null) + return Result.Err(RimMindErrors.InvalidAction("pawn.job", "queue_job_chain: pawn has no job tracker")); + + if (!TryExtractJobChainArray(args, out var array, out var parseError) || array == null || array.Count == 0) + { + return Result.Err(parseError ?? RimMindErrors.InvalidAction( + "pawn.job", + "queue_job_chain: provide a non-empty JSON array of job steps in jobs_json or value_json")); + } + + const int MaxChainSteps = 6; + int stepCount = Math.Min(array.Count, MaxChainSteps); + var builtJobs = new List(stepCount); + + for (int i = 0; i < stepCount; i++) + { + if (array[i] is not JObject stepObj) + { + return Result.Err(RimMindErrors.InvalidAction( + "pawn.job", + $"queue_job_chain: step[{i}] must be a JSON object")); + } + + var stepParams = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var prop in stepObj.Properties()) + { + if (prop.Value == null || prop.Value.Type == JTokenType.Null) + continue; + if (prop.Value.Type == JTokenType.Object || prop.Value.Type == JTokenType.Array) + stepParams[prop.Name] = prop.Value.ToString(Newtonsoft.Json.Formatting.None); + else + stepParams[prop.Name] = prop.Value.ToString(); + } + + var stepArgs = new MechanismWriteArgs + { + MechanismId = args.MechanismId, + PawnId = args.PawnId, + MapId = args.MapId, + Action = stepObj["action"]?.ToString() ?? stepObj["job_action"]?.ToString() ?? stepObj["sub_action"]?.ToString() ?? string.Empty, + DefName = stepObj["def_name"]?.ToString() ?? stepObj["work_type"]?.ToString(), + Params = stepParams + }; + + string subAction = ResolveQueueSubAction(stepArgs); + if (string.IsNullOrEmpty(subAction)) + { + return Result.Err(RimMindErrors.InvalidAction( + "pawn.job", + $"queue_job_chain: step[{i}] could not resolve job action (set action, work_type, or cell_x)")); + } + + if (!TryBuildJobWithoutStarting(pawn, subAction, stepArgs, out var job, out var buildError) || job == null) + { + return Result.Err(RimMindErrors.InvalidAction( + "pawn.job", + $"queue_job_chain: step[{i}] ({subAction}) failed: {buildError?.Message ?? "no valid job"}")); + } + + job.playerForced = true; + builtJobs.Add(job); + } + + if (builtJobs.Count == 0) + { + return Result.Err(RimMindErrors.InvalidAction("pawn.job", "queue_job_chain: no valid jobs built")); + } + + int enqueueStartIndex = 0; + if (pawn.jobs.curJob == null) + { + var startRes = StartJobVerified(pawn, builtJobs[0]); + if (startRes.IsErr) + return startRes; + enqueueStartIndex = 1; + } + + for (int i = enqueueStartIndex; i < builtJobs.Count; i++) + { + pawn.jobs.jobQueue.EnqueueLast(builtJobs[i]); + } + + return Result.Ok(true); + } + + public static Result HandleRemoveQueuedJob(VersePawn pawn, MechanismWriteArgs args) + { + var queue = pawn?.jobs?.jobQueue; + if (queue == null || queue.Count == 0) + return Result.Err(RimMindErrors.InvalidAction("pawn.job", "remove_queued_job: job queue is empty")); + + int index = int.TryParse(ExtractParam(args, "job_index"), out var parsedIndex) ? parsedIndex : 0; + if (index < 0 || index >= queue.Count) + return Result.Err(RimMindErrors.InvalidAction("pawn.job", $"remove_queued_job: job_index {index} out of range (0..{queue.Count - 1})")); + + var targetJob = queue[index]?.job; + if (targetJob == null) + return Result.Err(RimMindErrors.InvalidAction("pawn.job", $"remove_queued_job: queued job at index {index} is null")); + + queue.Extract(targetJob); + return Result.Ok(true); + } + + public static Result HandleClearQueue(VersePawn pawn, MechanismWriteArgs args) + { + if (pawn?.jobs == null) + return Result.Err(RimMindErrors.InvalidAction("pawn.job", "clear_queue: pawn has no job tracker")); + + pawn.jobs.ClearQueuedJobs(true); + return Result.Ok(true); + } + + private static string ResolveQueueSubAction(MechanismWriteArgs args) + { + string? explicitSub = ExtractParam(args, "job_action") ?? ExtractParam(args, "sub_action"); + if (!string.IsNullOrWhiteSpace(explicitSub)) + return explicitSub!.Trim().ToLowerInvariant(); + + if (!string.IsNullOrWhiteSpace(args.Action) + && !string.Equals(args.Action, "enqueue_job", StringComparison.OrdinalIgnoreCase) + && !string.Equals(args.Action, "queue_job_chain", StringComparison.OrdinalIgnoreCase) + && !string.Equals(args.Action, "set", StringComparison.OrdinalIgnoreCase)) + { + return args.Action.Trim().ToLowerInvariant(); + } + + if (!string.IsNullOrWhiteSpace(args.DefName) + || !string.IsNullOrWhiteSpace(ExtractParam(args, "work_type")) + || !string.IsNullOrWhiteSpace(ExtractParam(args, "job_type")) + || !string.IsNullOrWhiteSpace(ExtractParam(args, "def_name"))) + { + return "assign_work"; + } + + if (!string.IsNullOrWhiteSpace(ExtractParam(args, "cell_x")) + || !string.IsNullOrWhiteSpace(ExtractParam(args, "x"))) + { + return "move_to"; + } + + return string.Empty; + } + + private static bool TryExtractJobChainArray(MechanismWriteArgs args, out JArray? array, out RimMindError? error) + { + array = null; + error = null; + + string? rawJson = ExtractParam(args, "jobs_json") ?? args.ValueJson; + if (string.IsNullOrWhiteSpace(rawJson) && !string.IsNullOrWhiteSpace(args.RawArgumentsJson)) + { + try + { + var root = JObject.Parse(args.RawArgumentsJson!); + var token = root["jobs"] ?? root["jobs_json"] ?? root["value_json"]; + if (token is JArray directArray) + { + array = directArray; + return true; + } + rawJson = token?.ToString(); + } + catch (Exception ex) + { + error = RimMindErrors.InvalidAction("pawn.job", $"queue_job_chain: invalid RawArgumentsJson ({ex.Message})"); + return false; + } + } + + if (string.IsNullOrWhiteSpace(rawJson)) + return false; + + try + { + var parsed = JToken.Parse(rawJson!); + if (parsed is JArray arr) + { + array = arr; + return true; + } + if (parsed is JObject obj && obj["jobs"] is JArray nestedArr) + { + array = nestedArr; + return true; + } + error = RimMindErrors.InvalidAction("pawn.job", "queue_job_chain: jobs payload must be a JSON array"); + return false; + } + catch (Exception ex) + { + error = RimMindErrors.InvalidAction("pawn.job", $"queue_job_chain: invalid JSON array ({ex.Message})"); + return false; + } + } + + private static bool TryBuildJobWithoutStarting( + VersePawn pawn, + string subAction, + MechanismWriteArgs subArgs, + out VerseJob? builtJob, + out RimMindError? error) + { + builtJob = null; + error = null; + + bool prevCapture = _captureJobForQueue; + VerseJob? prevJob = _capturedQueueJob; + try + { + _captureJobForQueue = true; + _capturedQueueJob = null; + + Result res = subAction switch + { + "assign_work" or "take_job" => HandleAssignWork(pawn, subArgs), + "move_to" => HandleMoveTo(pawn, subArgs), + "eat_food" => HandleEatFood(pawn, subArgs), + "force_rest" => HandleForceRest(pawn, subArgs), + "tend_pawn" => HandleTendPawn(pawn, subArgs), + "rescue_pawn" => HandleRescuePawn(pawn, subArgs), + "arrest_pawn" => HandleArrestPawn(pawn, subArgs), + _ => Result.Err(RimMindErrors.InvalidAction("pawn.job", $"unsupported queued sub-action '{subAction}'")) + }; + + if (res.IsOk && _capturedQueueJob != null) + { + builtJob = _capturedQueueJob; + return true; + } + + error = res.IsErr + ? res.Error + : RimMindErrors.InvalidAction("pawn.job", $"failed to build queueable job for '{subAction}'"); + return false; + } + finally + { + _captureJobForQueue = prevCapture; + _capturedQueueJob = prevJob; + } + } + private static string? ExtractParam(MechanismWriteArgs args, string key) { if (args.Params != null && args.Params.TryGetValue(key, out var val)) @@ -295,11 +810,14 @@ private static int ExtractIntParam(MechanismWriteArgs args, string key) } /// - /// Actions whose actor may be a downed colonist (resting in place, dropping the current job). + /// Actions whose actor may be a downed colonist (resting in place, dropping the current job, or clearing queue). /// All other pawn.job actions require a conscious, non-downed colonist. /// public static bool AllowsDownedActor(string? action) - => action == "force_rest" || action == "cancel_job"; + => action == "force_rest" + || action == "cancel_job" + || action == "clear_queue" + || action == "remove_queued_job"; /// /// Resolves the target of tend/rescue/arrest through the shared lookup. Targets may be any live pawn diff --git a/Source/Infrastructure/Mechanisms/Pawn/Job/JobDocs.cs b/Source/Infrastructure/Mechanisms/Pawn/Job/JobDocs.cs index 205c6ec..1a79f34 100644 --- a/Source/Infrastructure/Mechanisms/Pawn/Job/JobDocs.cs +++ b/Source/Infrastructure/Mechanisms/Pawn/Job/JobDocs.cs @@ -7,9 +7,9 @@ public static class JobDocs { public static MechanismDocs Value => new MechanismDocs { - Summary = "Manage pawn jobs and work assignments", - QueryDescription = "Query the pawn's current job and work status", - SetDescription = "Assign a job or action to a pawn. Use the 'action' field to specify which job to assign.", + Summary = "Manage pawn jobs, work assignments, and job queue", + QueryDescription = "Query the pawn's current job, detailed queued jobs list, and work status", + SetDescription = "Assign or queue jobs on a pawn. Supports action: assign_work, move_to, eat_food, force_rest, tend_pawn, rescue_pawn, arrest_pawn, cancel_job, enqueue_job, queue_job_chain, remove_queued_job, clear_queue.", ListDescription = "List available job actions for pawns" }; } diff --git a/Source/Infrastructure/Mechanisms/Pawn/Job/JobMechanism.cs b/Source/Infrastructure/Mechanisms/Pawn/Job/JobMechanism.cs index b1a46fe..44c1fac 100644 --- a/Source/Infrastructure/Mechanisms/Pawn/Job/JobMechanism.cs +++ b/Source/Infrastructure/Mechanisms/Pawn/Job/JobMechanism.cs @@ -32,7 +32,11 @@ public sealed class JobMechanism : GameMechanismBaseNoDef, IMechanismActionRiskP new MechanismActionInfo { Action = "tend_pawn", Description = "Tend a patient pawn", RequiredParams = new List { "target_pawn_id" }.AsReadOnly() }, new MechanismActionInfo { Action = "rescue_pawn", Description = "Rescue a downed pawn", RequiredParams = new List { "target_pawn_id" }.AsReadOnly() }, new MechanismActionInfo { Action = "arrest_pawn", Description = "Arrest a pawn", RequiredParams = new List { "target_pawn_id" }.AsReadOnly() }, - new MechanismActionInfo { Action = "cancel_job", Description = "Cancel current job" } + new MechanismActionInfo { Action = "cancel_job", Description = "Cancel current job" }, + new MechanismActionInfo { Action = "enqueue_job", Description = "Enqueue a job after current work (supports queue_position=first|last and job_action)" }, + new MechanismActionInfo { Action = "queue_job_chain", Description = "Queue an ordered sequence of up to 6 jobs via jobs_json array" }, + new MechanismActionInfo { Action = "remove_queued_job", Description = "Remove a queued job by 0-based job_index" }, + new MechanismActionInfo { Action = "clear_queue", Description = "Clear all pending queued jobs without cancelling the current job" } }.AsReadOnly(); public override IReadOnlyList? GetWriteActions() => _writeActions; @@ -49,6 +53,23 @@ public override Task> ExecuteQueryAsync(MechanismRe return Task.FromResult(Result.Err(RimMindErrors.PawnNotFound(args.PawnId))); var curJob = pawn.jobs?.curJob; + var queue = pawn.jobs?.jobQueue; + var queuedList = new List(); + if (queue != null) + { + for (int i = 0; i < queue.Count; i++) + { + var qJob = queue[i]?.job; + queuedList.Add(new + { + index = i, + def = qJob?.def?.defName, + target = qJob?.targetA.Thing?.LabelCap ?? qJob?.targetA.Cell.ToString(), + isForced = qJob?.playerForced ?? false + }); + } + } + var info = new { currentJob = curJob != null ? new @@ -57,7 +78,8 @@ public override Task> ExecuteQueryAsync(MechanismRe target = curJob.targetA.Thing?.LabelCap ?? curJob.targetA.Cell.ToString(), isForced = curJob.playerForced } : null, - jobQueueCount = pawn.jobs?.jobQueue?.Count ?? 0 + jobQueueCount = queue?.Count ?? 0, + queuedJobs = queuedList }; return Task.FromResult(Result.Ok(JsonConvert.SerializeObject(info))); @@ -65,11 +87,14 @@ public override Task> ExecuteQueryAsync(MechanismRe public override Task> ExecuteSetAsync(MechanismWriteArgs args, CancellationToken ct) { - var pawn = FindWritableColonist(args.PawnId, allowDowned: JobActionDispatcher.AllowsDownedActor(args.Action), out var pawnError); + string effectiveAction = ResolveEffectiveAction(args); + if (string.IsNullOrEmpty(effectiveAction)) + return Task.FromResult(Result.Err(RimMindErrors.InvalidAction(MechanismId, MissingActionMessage))); + var pawn = FindWritableColonist(args.PawnId, allowDowned: JobActionDispatcher.AllowsDownedActor(effectiveAction), out var pawnError); if (pawn == null) return Task.FromResult(Result.Err(pawnError!)); - var result = args.Action switch + var result = effectiveAction switch { "assign_work" or "take_job" => JobActionDispatcher.HandleAssignWork(pawn, args), "move_to" => JobActionDispatcher.HandleMoveTo(pawn, args), @@ -79,10 +104,46 @@ public override Task> ExecuteSetAsync(MechanismWriteA "rescue_pawn" => JobActionDispatcher.HandleRescuePawn(pawn, args), "arrest_pawn" => JobActionDispatcher.HandleArrestPawn(pawn, args), "cancel_job" => JobActionDispatcher.HandleCancelJob(pawn, args), - _ => Result.Err(RimMindErrors.InvalidAction(MechanismId, args.Action)) + "enqueue_job" => JobActionDispatcher.HandleEnqueueJob(pawn, args), + "queue_job_chain" => JobActionDispatcher.HandleQueueJobChain(pawn, args), + "remove_queued_job" => JobActionDispatcher.HandleRemoveQueuedJob(pawn, args), + "clear_queue" => JobActionDispatcher.HandleClearQueue(pawn, args), + _ => Result.Err(RimMindErrors.InvalidAction(MechanismId, effectiveAction)) }; return Task.FromResult(result); } + + internal static string ResolveEffectiveAction(MechanismWriteArgs args) + { + if (!string.IsNullOrWhiteSpace(args.Action) && + !string.Equals(args.Action, "set", System.StringComparison.OrdinalIgnoreCase)) + { + return args.Action; + } + + if (!string.IsNullOrWhiteSpace(args.DefName) || + HasNonEmptyParam(args.Params, "work_type") || + HasNonEmptyParam(args.Params, "job_type") || + HasNonEmptyParam(args.Params, "def_name")) + { + return "assign_work"; + } + + if (HasNonEmptyParam(args.Params, "cell_x") || HasNonEmptyParam(args.Params, "x")) + { + return "move_to"; + } + + // No implicit default: silently mapping an argument-less call to force_rest made + // colonists lie down instead of eating, tending or working in live playthroughs. + return string.Empty; + } + + internal const string MissingActionMessage = + "missing 'action'. Use one of: assign_work (work_type), move_to (cell_x, cell_z), eat_food, force_rest, tend_pawn (target_pawn_id), rescue_pawn (target_pawn_id), arrest_pawn (target_pawn_id), cancel_job, enqueue_job, queue_job_chain, remove_queued_job, clear_queue"; + + private static bool HasNonEmptyParam(IReadOnlyDictionary? parameters, string key) + => parameters != null && parameters.TryGetValue(key, out var val) && !string.IsNullOrWhiteSpace(val); } } diff --git a/Source/Infrastructure/Mechanisms/Pawn/MentalState/MentalStateMechanism.cs b/Source/Infrastructure/Mechanisms/Pawn/MentalState/MentalStateMechanism.cs index f7e8347..4ebc5ce 100644 --- a/Source/Infrastructure/Mechanisms/Pawn/MentalState/MentalStateMechanism.cs +++ b/Source/Infrastructure/Mechanisms/Pawn/MentalState/MentalStateMechanism.cs @@ -71,7 +71,9 @@ public override Task> ExecuteTriggerAsync(MechanismWr if (mentalStateDef == null) return Task.FromResult(Result.Err(RimMindErrors.InvalidDefName(args.DefName))); - pawn.mindState?.mentalStateHandler?.TryStartMentalState(mentalStateDef, "Triggered by AI", true); + bool started = pawn.mindState?.mentalStateHandler?.TryStartMentalState(mentalStateDef, "Triggered by AI", true) == true; + if (!started) + return Task.FromResult(Result.Err(RimMindErrors.InvalidAction(MechanismId, $"Mental state '{args.DefName}' could not start on this pawn"))); return Task.FromResult(Result.Ok(true)); } } diff --git a/Source/Infrastructure/Mechanisms/Pawn/Work/WorkMechanism.cs b/Source/Infrastructure/Mechanisms/Pawn/Work/WorkMechanism.cs index a93c048..2bd476a 100644 --- a/Source/Infrastructure/Mechanisms/Pawn/Work/WorkMechanism.cs +++ b/Source/Infrastructure/Mechanisms/Pawn/Work/WorkMechanism.cs @@ -1,14 +1,18 @@ +using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; +using Newtonsoft.Json.Linq; using RimMind.Application.Common.Interfaces.Mechanisms; using RimMind.Application.Common.Models.Mechanisms; +using RimMind.Domain.Agent.Policies; using RimMind.Domain.Enums; using RimMind.Domain.ValueObjects; -using Verse; +using RimMind.Presentation.Api; using RimWorld; +using Verse; namespace RimMind.Infrastructure.Mechanisms.Pawn.Work { @@ -27,10 +31,20 @@ public sealed class WorkMechanism : GameMechanismBase { Summary = "Query and modify pawn work priorities", QueryDescription = "Query pawn work priorities for all work types. Optionally filter by def_name.", - SetDescription = "Set a pawn's work priority. Provide def_name and value (priority 0-4).", + SetDescription = "Set or batch-update pawn work priorities (0-4). Supports single def_name+value, action 'set_batch' with priorities_json (map or array), or 'reset_defaults'.", ListDescription = "List all work type definitions" }; + private static readonly IReadOnlyList _writeActions = + new List + { + new MechanismActionInfo { Action = "set_priority", Description = "Set a single WorkType priority (0=off, 1=highest .. 4=lowest)", DefNameHint = "WorkTypeDef", RequiredParams = new List { "def_name" }.AsReadOnly() }, + new MechanismActionInfo { Action = "set_batch", Description = "Batch set multiple WorkType priorities via priorities_json map or array", RequiredParams = new List { "priorities_json" }.AsReadOnly() }, + new MechanismActionInfo { Action = "reset_defaults", Description = "Reset all enabled visible work types to default priority 3" } + }.AsReadOnly(); + + public override IReadOnlyList? GetWriteActions() => _writeActions; + public override Task> ExecuteQueryAsync(MechanismReadArgs args, CancellationToken ct) { var pawn = FindPawn(args.PawnId); @@ -64,9 +78,33 @@ public override Task> ExecuteSetAsync(MechanismWriteA if (pawn == null) return Task.FromResult(Result.Err(pawnError!)); + if (RimMindAPI.Autonomy.IsDisabled(pawn, AutonomyDomain.WorkPriorityModification)) + { + return Task.FromResult(Result.Err( + RimMindErrors.InvalidAction(MechanismId, $"Modifying Work Tab priorities is disabled for {pawn.LabelShort} by player autonomy policy."))); + } + if (pawn.workSettings == null || !pawn.workSettings.EverWork) return Task.FromResult(Result.Err(RimMindErrors.InvalidAction(MechanismId, "pawn cannot work"))); + string effectiveAction = (args.Action ?? string.Empty).Trim().ToLowerInvariant(); + if (effectiveAction == "reset_defaults") + { + pawn.workSettings.EnableAndInitializeIfNotAlreadyInitialized(); + foreach (var wt in DefDatabase.AllDefsListForReading) + { + if (wt != null && wt.visible && !pawn.WorkTypeIsDisabled(wt)) + pawn.workSettings.SetPriority(wt, 3); + } + return Task.FromResult(Result.Ok(true)); + } + + string? batchJson = ExtractBatchPayload(args); + if (effectiveAction == "set_batch" || !string.IsNullOrWhiteSpace(batchJson)) + { + return Task.FromResult(ApplyBatchPriorities(pawn, batchJson)); + } + string? rawDefName = args.DefName; if (string.IsNullOrEmpty(rawDefName) && args.Params != null) { @@ -95,6 +133,10 @@ public override Task> ExecuteSetAsync(MechanismWriteA priority = 1; } } + else if (args.Params != null && args.Params.TryGetValue("priority", out var pParam) && int.TryParse(pParam, out var parsedParam)) + { + priority = parsedParam; + } if (priority < 0 || priority > 4) return Task.FromResult(Result.Err(RimMindErrors.InvalidAction(MechanismId, "priority must be 0-4"))); @@ -104,6 +146,117 @@ public override Task> ExecuteSetAsync(MechanismWriteA return Task.FromResult(Result.Ok(true)); } + private static string? ExtractBatchPayload(MechanismWriteArgs args) + { + if (args.Params != null && args.Params.TryGetValue("priorities_json", out var pJson) && !string.IsNullOrWhiteSpace(pJson)) + return pJson; + + if (!string.IsNullOrWhiteSpace(args.ValueJson)) + { + string trimmed = args.ValueJson!.Trim(); + if (trimmed.StartsWith("{", StringComparison.Ordinal) || trimmed.StartsWith("[", StringComparison.Ordinal)) + return trimmed; + } + + if (!string.IsNullOrWhiteSpace(args.RawArgumentsJson)) + { + try + { + var obj = JObject.Parse(args.RawArgumentsJson!); + var tok = obj["priorities"] ?? obj["priorities_json"]; + if (tok != null && (tok.Type == JTokenType.Object || tok.Type == JTokenType.Array)) + return tok.ToString(Formatting.None); + if (tok != null && tok.Type == JTokenType.String) + return tok.Value(); + } + catch + { + // Ignore malformed outer JSON + } + } + + return null; + } + + private Result ApplyBatchPriorities(global::Verse.Pawn pawn, string? json) + { + if (string.IsNullOrWhiteSpace(json)) + return Result.Err(RimMindErrors.InvalidAction(MechanismId, "set_batch requires priorities_json or priorities object/array.")); + + var updates = new List<(WorkTypeDef Def, int Priority)>(); + try + { + JToken token = JToken.Parse(json!); + if (token is JObject mapObj) + { + if (mapObj["priorities"] is JToken nested) + token = nested; + } + + if (token is JObject obj) + { + foreach (var prop in obj.Properties()) + { + if (!TryValidatePriorityEntry(pawn, prop.Name, prop.Value.Value(), out var def, out var err)) + return Result.Err(err!); + updates.Add((def!, prop.Value.Value())); + } + } + else if (token is JArray arr) + { + foreach (var item in arr.OfType()) + { + string? name = item["work_type"]?.Value() ?? item["def_name"]?.Value(); + int? prio = item["priority"]?.Value(); + if (string.IsNullOrWhiteSpace(name) || !prio.HasValue) + return Result.Err(RimMindErrors.InvalidAction(MechanismId, "Each batch item must specify work_type/def_name and priority (0-4).")); + if (!TryValidatePriorityEntry(pawn, name!, prio.Value, out var def, out var err)) + return Result.Err(err!); + updates.Add((def!, prio.Value)); + } + } + else + { + return Result.Err(RimMindErrors.InvalidAction(MechanismId, "priorities payload must be JSON object or array.")); + } + } + catch (Exception ex) + { + return Result.Err(RimMindErrors.InvalidAction(MechanismId, $"Invalid batch priorities JSON: {ex.Message}")); + } + + if (updates.Count == 0) + return Result.Err(RimMindErrors.InvalidAction(MechanismId, "No valid work priorities found in batch payload.")); + + pawn.workSettings.EnableAndInitializeIfNotAlreadyInitialized(); + foreach (var (def, priority) in updates) + pawn.workSettings.SetPriority(def, priority); + + return Result.Ok(true); + } + + private bool TryValidatePriorityEntry(global::Verse.Pawn pawn, string rawName, int priority, out WorkTypeDef? workDef, out RimMindError? error) + { + workDef = ResolveWorkTypeDef(rawName); + if (workDef == null) + { + error = RimMindErrors.InvalidDefName(rawName); + return false; + } + if (pawn.WorkTypeIsDisabled(workDef)) + { + error = RimMindErrors.InvalidAction(MechanismId, $"Work type '{workDef.defName}' is disabled for {pawn.LabelShort}"); + return false; + } + if (priority < 0 || priority > 4) + { + error = RimMindErrors.InvalidAction(MechanismId, $"Priority {priority} for '{workDef.defName}' must be 0-4"); + return false; + } + error = null; + return true; + } + private WorkTypeDef? ResolveWorkTypeDef(string rawName) { var trimmed = rawName.Trim(); diff --git a/Source/Infrastructure/Patches/AddAgentCompToHumanlikePatch.cs b/Source/Infrastructure/Patches/AddAgentCompToHumanlikePatch.cs index 883a774..4fba411 100644 --- a/Source/Infrastructure/Patches/AddAgentCompToHumanlikePatch.cs +++ b/Source/Infrastructure/Patches/AddAgentCompToHumanlikePatch.cs @@ -13,6 +13,8 @@ public static class AddAgentCompToHumanlikePatch [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/Infrastructure/Patches/ThinkNode_RimMindAgent.cs b/Source/Infrastructure/Patches/ThinkNode_RimMindAgent.cs index fa443d0..b67a601 100644 --- a/Source/Infrastructure/Patches/ThinkNode_RimMindAgent.cs +++ b/Source/Infrastructure/Patches/ThinkNode_RimMindAgent.cs @@ -19,6 +19,7 @@ public override float GetPriority(Pawn pawn) if (!session.IsActive(pawn, currentTick)) { comp.ClearIntentSession(); + comp.Agent.ForceThink(); } else { @@ -58,11 +59,13 @@ public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobPara if (session.CompletionPredicate?.Invoke(pawn) == true) { comp.ClearIntentSession(); + comp.Agent.ForceThink(); } } else { comp.ClearIntentSession(); + comp.Agent.ForceThink(); } } diff --git a/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClient.RequestBuilding.cs b/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClient.RequestBuilding.cs index d99fa4e..6bdc0fd 100644 --- a/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClient.RequestBuilding.cs +++ b/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClient.RequestBuilding.cs @@ -29,6 +29,7 @@ private static RimMind.Domain.Llm.LlmRequestEnvelope StripJsonSchema(RimMind.Dom Examples = envelope.Examples, MaxTokens = envelope.MaxTokens, Temperature = envelope.Temperature, + ReasoningEffort = envelope.ReasoningEffort, Priority = envelope.Priority, ExpireAtTicks = envelope.ExpireAtTicks, MaxRetryCount = envelope.MaxRetryCount, diff --git a/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClient.cs b/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClient.cs index 755fcf2..6d44ec3 100644 --- a/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClient.cs +++ b/Source/Infrastructure/Services/Clients/OpenAI/OpenAIClient.cs @@ -148,7 +148,7 @@ public OpenAIClient(IOpenAISettings settings, ILogSink? logSink = null, HttpPost } private static float ResolveTimeoutSeconds(bool isLocal, int candidateCount, int attempt) => - isLocal ? 300f : ((candidateCount > 1 && attempt < candidateCount - 1) ? 25f : 60f); + isLocal ? 300f : ((candidateCount > 1 && attempt < candidateCount - 1) ? 40f : 60f); public bool IsConfigured() => _settings.IsConfigured(); @@ -273,7 +273,13 @@ internal List ResolveOrderedCandidateNodes(long nowMs) connectTimeout: connectTimeout, cancellationToken: envelope.Ct); - if (httpStatusCode == 400 && currentJson.IndexOf("\"response_format\"", StringComparison.Ordinal) >= 0) + bool isModeration = ClientExceptionMapper.IsContentModerationResponse((int)httpStatusCode, responseText); + if (httpStatusCode == 400 && !isModeration && currentJson.IndexOf("\"response_format\"", StringComparison.Ordinal) >= 0) + { + throw HttpTransport.HttpException.FromResponse((int)httpStatusCode, responseText, null); + } + + if (httpStatusCode >= 400) { throw HttpTransport.HttpException.FromResponse((int)httpStatusCode, responseText, null); } @@ -282,6 +288,7 @@ internal List ResolveOrderedCandidateNodes(long nowMs) } catch (HttpTransport.HttpException httpEx) when ( httpEx.StatusCode == 400 && + !ClientExceptionMapper.IsContentFilteredHttpFailure(httpEx) && currentJson.IndexOf("\"response_format\"", StringComparison.Ordinal) >= 0) { string nextFormat = currentJson.IndexOf("\"json_schema\"", StringComparison.Ordinal) >= 0 @@ -302,6 +309,70 @@ internal List ResolveOrderedCandidateNodes(long nowMs) } } + private Result BuildCompletedResponse( + string responseText, + long httpStatusCode, + RimMind.Domain.Llm.LlmRequestEnvelope envelope, + BackupEndpointNode node, + bool allowEmptyFailover, + Stopwatch sw, + string effectiveModel, + int attempt, + bool logSuccessDetails) + { + var parsed = OpenAIRequestSerializer.ParseResponse(responseText, envelope); + if (sw.IsRunning) sw.Stop(); + + if (parsed.IsErr) + { + var err = parsed.Error; + if (err.Code == RimMindErrorCode.ContentFiltered) + { + return Result.Err(err); + } + if (err.Code == RimMindErrorCode.ClientTransientFailure) + { + throw new HttpTransport.HttpException(err.Message, 503); + } + if (allowEmptyFailover) + { + throw new HttpTransport.HttpException($"Node '{node.Name}' returned empty or invalid response payload: {err.Message}", 502); + } + return Result.Err(err); + } + + var val = parsed.Value; + if (allowEmptyFailover && + string.IsNullOrWhiteSpace(val.Content) && + string.IsNullOrEmpty(val.ToolCallsJson)) + { + throw new HttpTransport.HttpException($"Node '{node.Name}' returned empty response payload.", 502); + } + + RecordNodeSuccess(node); + + if (logSuccessDetails) + { + if (attempt > 0 || !string.Equals(node.Name, "Primary", StringComparison.OrdinalIgnoreCase)) + { + _logSink?.LogFromBackground( + $"[RimMind-Core] Request {envelope.RequestId} served by node '{node.Name}' ({node.ApiEndpoint}, model={effectiveModel}, {val.TokensUsed} tok, {sw.ElapsedMilliseconds}ms)."); + } + else if (_settings.DebugLogging) + { + _logSink?.LogFromBackground($"[RimMind-Core] << {envelope.RequestId} ({val.TokensUsed} tok)\n{LogSanitizer.ForLog(val.Content, LogSanitizer.DebugPayloadMaxChars)}"); + } + } + + return Result.Ok( + val.With( + requestId: envelope.RequestId, + state: RimMind.Domain.Llm.AIRequestState.Completed, + priority: envelope.Priority, + processingMs: sw.ElapsedMilliseconds, + httpStatusCode: httpStatusCode)); + } + public async Task> SendAsync(RimMind.Domain.Llm.LlmRequestEnvelope envelope) { if (!IsConfigured()) @@ -352,77 +423,16 @@ internal List ResolveOrderedCandidateNodes(long nowMs) headerValue, connectTimeout); - var parsed = JsonConvert.DeserializeObject(responseText); - string content = parsed?.choices?[0]?.message?.content ?? string.Empty; - string? reasoningContent = parsed?.choices?[0]?.message?.reasoning_content; - int tokens = parsed?.usage?.total_tokens ?? 0; - int promptTokens = parsed?.usage?.prompt_tokens ?? 0; - int completionTokens = parsed?.usage?.completion_tokens ?? 0; - int cachedTokens = parsed?.usage?.prompt_tokens_details?.cached_tokens ?? 0; - var toolCallsDto = parsed?.choices?[0]?.message?.tool_calls; - string? finishReason = parsed?.choices?[0]?.finish_reason; - bool expectsTools = envelope.Tools != null && envelope.Tools.Count > 0; - if (!expectsTools && - !string.Equals(finishReason, "length", StringComparison.OrdinalIgnoreCase) && - string.IsNullOrWhiteSpace(content) && - (toolCallsDto == null || toolCallsDto.Count == 0) && - !string.IsNullOrWhiteSpace(reasoningContent)) - { - content = reasoningContent!; - } - sw.Stop(); - - // If multiple nodes exist and this node returned an empty shell with 0 tokens and no content/tool_calls, - // treat it as an upstream node failure so we can fail over to the next backup node. - if (candidates.Count > 1 && attempt < candidates.Count - 1 && - (parsed?.choices == null || parsed.choices.Count == 0 || - (string.IsNullOrWhiteSpace(content) && (toolCallsDto == null || toolCallsDto.Count == 0)))) - { - throw new HttpTransport.HttpException($"Node '{node.Name}' returned empty response payload.", 502); - } - - RecordNodeSuccess(node); - - if (attempt > 0 || !string.Equals(node.Name, "Primary", StringComparison.OrdinalIgnoreCase)) - { - _logSink?.LogFromBackground( - $"[RimMind-Core] Request {envelope.RequestId} served by node '{node.Name}' ({node.ApiEndpoint}, model={effectiveModel}, {tokens} tok, {sw.ElapsedMilliseconds}ms)."); - } - else if (_settings.DebugLogging) - { - _logSink?.LogFromBackground($"[RimMind-Core] << {envelope.RequestId} ({tokens} tok)\n{LogSanitizer.ForLog(content, LogSanitizer.DebugPayloadMaxChars)}"); - } - - var response = new RimMind.Domain.Llm.LlmResponse - { - RequestId = envelope.RequestId, - Content = content, - ReasoningContent = reasoningContent, - TokensUsed = tokens, - PromptTokens = promptTokens, - CompletionTokens = completionTokens, - CachedTokens = cachedTokens, - State = RimMind.Domain.Llm.AIRequestState.Completed, - Priority = envelope.Priority, - ProcessingMs = sw.ElapsedMilliseconds, - HttpStatusCode = httpStatusCode, - }; - - if (toolCallsDto != null && toolCallsDto.Count > 0) - { - var toolCallsJson = ToolCallJsonNormalizer.Normalize( - toolCallsDto.Select(tc => new ToolCallEntry - { - Id = tc.Id, - Type = tc.Type, - FunctionName = tc.Function?.Name, - FunctionArguments = tc.Function?.Arguments, - })); - if (toolCallsJson != null) - response = response.With(toolCallsJson: toolCallsJson); - } - - return Result.Ok(response); + return BuildCompletedResponse( + responseText, + httpStatusCode, + envelope, + node, + allowEmptyFailover: candidates.Count > 1 && attempt < candidates.Count - 1, + sw, + effectiveModel, + attempt, + logSuccessDetails: true); } catch (OperationCanceledException ex) when (envelope.Ct.IsCancellationRequested) { @@ -432,6 +442,11 @@ internal List ResolveOrderedCandidateNodes(long nowMs) catch (Exception ex) { sw.Stop(); + if (ClientExceptionMapper.IsContentFilteredHttpFailure(ex)) + { + return ClientExceptionMapper.MapException(ex, nameof(OpenAIClient), envelope.RequestId, "request", _logSink, callerToken: envelope.Ct); + } + long cooldownMs = ResolveNodeIsolationCooldownMs(ex, out bool isPermQuota); RecordNodeFailure(node, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), cooldownMs, isPermQuota); @@ -490,54 +505,16 @@ internal List ResolveOrderedCandidateNodes(long nowMs) headerValue, connectTimeout); - var parsed = JsonConvert.DeserializeObject(responseText); - string content = parsed?.choices?[0]?.message?.content ?? string.Empty; - string? reasoningContent = parsed?.choices?[0]?.message?.reasoning_content; - int tokens = parsed?.usage?.total_tokens ?? 0; - int promptTokens = parsed?.usage?.prompt_tokens ?? 0; - int completionTokens = parsed?.usage?.completion_tokens ?? 0; - int cachedTokens = parsed?.usage?.prompt_tokens_details?.cached_tokens ?? 0; - var toolCallsDto = parsed?.choices?[0]?.message?.tool_calls; - if (string.IsNullOrWhiteSpace(content) && - (toolCallsDto == null || toolCallsDto.Count == 0) && - !string.IsNullOrWhiteSpace(reasoningContent)) - { - content = reasoningContent!; - } - sw.Stop(); - - RecordNodeSuccess(retryNode); - - var response = new RimMind.Domain.Llm.LlmResponse - { - RequestId = envelope.RequestId, - Content = content, - ReasoningContent = reasoningContent, - TokensUsed = tokens, - PromptTokens = promptTokens, - CompletionTokens = completionTokens, - CachedTokens = cachedTokens, - State = RimMind.Domain.Llm.AIRequestState.Completed, - Priority = envelope.Priority, - ProcessingMs = sw.ElapsedMilliseconds, - HttpStatusCode = httpStatusCode, - }; - - if (toolCallsDto != null && toolCallsDto.Count > 0) - { - var toolCallsJson = ToolCallJsonNormalizer.Normalize( - toolCallsDto.Select(tc => new ToolCallEntry - { - Id = tc.Id, - Type = tc.Type, - FunctionName = tc.Function?.Name, - FunctionArguments = tc.Function?.Arguments, - })); - if (toolCallsJson != null) - response = response.With(toolCallsJson: toolCallsJson); - } - - return Result.Ok(response); + return BuildCompletedResponse( + responseText, + httpStatusCode, + envelope, + retryNode, + allowEmptyFailover: false, + sw, + effectiveModel, + attempt: 0, + logSuccessDetails: false); } catch (OperationCanceledException ex) when (envelope.Ct.IsCancellationRequested) { @@ -545,6 +522,10 @@ internal List ResolveOrderedCandidateNodes(long nowMs) } catch (Exception ex) { + if (ClientExceptionMapper.IsContentFilteredHttpFailure(ex)) + { + return ClientExceptionMapper.MapException(ex, nameof(OpenAIClient), envelope.RequestId, "request", _logSink, callerToken: envelope.Ct); + } lastException = ex; if (!IsTransientConcurrencyOrRateLimitError(ex)) break; @@ -715,6 +696,11 @@ await SseStreamReader.ReadDataLinesAsync(session.Reader, data => } catch (Exception ex) { + if (ClientExceptionMapper.IsContentFilteredHttpFailure(ex)) + { + return ClientExceptionMapper.MapException(ex, nameof(OpenAIClient), envelope.RequestId, "stream", _logSink, callerToken: effectiveCt); + } + if (ex is HttpTransport.HttpException httpEx && httpEx.StatusCode == 400 && json.IndexOf("\"response_format\"", StringComparison.Ordinal) >= 0) diff --git a/Source/Infrastructure/Services/Clients/OpenAI/OpenAIRequestSerializer.cs b/Source/Infrastructure/Services/Clients/OpenAI/OpenAIRequestSerializer.cs index 9a796a7..ea5f72c 100644 --- a/Source/Infrastructure/Services/Clients/OpenAI/OpenAIRequestSerializer.cs +++ b/Source/Infrastructure/Services/Clients/OpenAI/OpenAIRequestSerializer.cs @@ -102,9 +102,26 @@ public static Result ParseResponse( if (token["error"] != null && token["error"]!.Type != JTokenType.Null) { - string errMsg = token["error"]?["message"]?.ToString() ?? "Unknown API error"; - return Result.Err( - RimMindErrors.ClientPermanent(LogSanitizer.ForLog(errMsg))); + string errMsg = AsString(token["error"]?["message"]) ?? "Unknown API error"; + string errType = AsString(token["error"]?["type"]) ?? string.Empty; + string errCode = AsString(token["error"]?["code"]) ?? string.Empty; + string safeErr = LogSanitizer.ForLog(errMsg); + + if (errMsg.IndexOf("Content Exists Risk", StringComparison.OrdinalIgnoreCase) >= 0 || + errCode.IndexOf("content_filter", StringComparison.OrdinalIgnoreCase) >= 0 || + errType.IndexOf("content_filter", StringComparison.OrdinalIgnoreCase) >= 0) + { + return Result.Err(RimMindErrors.ContentFiltered(safeErr)); + } + + if (string.Equals(errType, "server_error", StringComparison.OrdinalIgnoreCase) || + string.Equals(errType, "api_error", StringComparison.OrdinalIgnoreCase) || + string.Equals(errCode, "server_error", StringComparison.OrdinalIgnoreCase)) + { + return Result.Err(RimMindErrors.ClientTransient(safeErr)); + } + + return Result.Err(RimMindErrors.ClientPermanent(safeErr)); } var choices = token["choices"] as JArray; @@ -124,6 +141,23 @@ public static Result ParseResponse( string content = AsString(message["content"]) ?? string.Empty; string? reasoningContent = AsString(message["reasoning_content"]); string? finishReason = AsString(choices[0]["finish_reason"]); + string? refusal = AsString(message["refusal"]); + + if (string.Equals(finishReason, "content_filter", StringComparison.OrdinalIgnoreCase) || + !string.IsNullOrWhiteSpace(refusal)) + { + string refusalDetail = !string.IsNullOrWhiteSpace(refusal) + ? LogSanitizer.ForLog(refusal!) + : "Response blocked by upstream content filter (finish_reason=content_filter)."; + return Result.Err(RimMindErrors.ContentFiltered(refusalDetail)); + } + + if (string.Equals(finishReason, "insufficient_system_resource", StringComparison.OrdinalIgnoreCase) || + string.Equals(finishReason, "aborted", StringComparison.OrdinalIgnoreCase)) + { + return Result.Err( + RimMindErrors.ClientTransient($"Upstream generation interrupted (finish_reason={finishReason}).")); + } string? toolCallsJson = null; var toolCalls = message["tool_calls"] as JArray; @@ -167,11 +201,23 @@ public static Result ParseResponse( content = reasoningContent!; } + // Some providers (e.g. json_object validation failure) replace non-JSON output with spaces (U+0020) + if (toolCallsJson == null && + content.Length > 0 && + string.IsNullOrWhiteSpace(content) && + string.IsNullOrWhiteSpace(reasoningContent)) + { + return Result.Err( + RimMindErrors.ClientTransient("Upstream returned whitespace-only content.")); + } + var usage = token["usage"]; int promptTokens = AsInt(usage?["prompt_tokens"]) ?? 0; int completionTokens = AsInt(usage?["completion_tokens"]) ?? 0; int totalTokens = AsInt(usage?["total_tokens"]) ?? (promptTokens + completionTokens); - int cachedTokens = AsInt(usage?["prompt_tokens_details"]?["cached_tokens"]) ?? 0; + int cachedTokens = AsInt(usage?["prompt_tokens_details"]?["cached_tokens"]) + ?? AsInt(usage?["prompt_cache_hit_tokens"]) + ?? 0; var llmResponse = new LlmResponse { diff --git a/Source/Infrastructure/Services/Clients/Shared/ClientExceptionMapper.cs b/Source/Infrastructure/Services/Clients/Shared/ClientExceptionMapper.cs index 73a3e1f..06e1d6d 100644 --- a/Source/Infrastructure/Services/Clients/Shared/ClientExceptionMapper.cs +++ b/Source/Infrastructure/Services/Clients/Shared/ClientExceptionMapper.cs @@ -61,6 +61,11 @@ public static Result MapException( if (ex is HttpTransport.HttpException httpEx) { logSink?.LogFromBackground($"[RimMind-Core] {logPrefix} failed ({requestId}): {httpEx.Message}", isWarning: true); + if (IsContentModerationResponse(httpEx.StatusCode, httpEx.ClassificationText)) + { + return Result.Err( + RimMindErrors.ContentFiltered(httpEx.Message, httpEx)); + } return Result.Err( IsTransientHttpFailure(httpEx) ? RimMindErrors.ClientTransient(httpEx.Message, httpEx) @@ -100,5 +105,17 @@ internal static bool IsTransientHttpFailure(HttpTransport.HttpException httpEx) return !isPermanentQuotaOrAuth && (httpEx.StatusCode == 408 || httpEx.StatusCode == 429 || httpEx.StatusCode >= 500 || isRateLimitOrQueue); } + + internal static bool IsContentModerationResponse(int statusCode, string? responseBody) + { + return statusCode == 400 && + !string.IsNullOrEmpty(responseBody) && + (responseBody!.IndexOf("Content Exists Risk", StringComparison.OrdinalIgnoreCase) >= 0 || + responseBody.IndexOf("content_filter", StringComparison.OrdinalIgnoreCase) >= 0); + } + + internal static bool IsContentFilteredHttpFailure(Exception? ex) + => ex is HttpTransport.HttpException httpEx && + IsContentModerationResponse(httpEx.StatusCode, httpEx.ClassificationText); } } diff --git a/Source/Infrastructure/UI/AgentsPage/AgentDetailPanelDrawer.cs b/Source/Infrastructure/UI/AgentsPage/AgentDetailPanelDrawer.cs index bbe69cc..8c6715e 100644 --- a/Source/Infrastructure/UI/AgentsPage/AgentDetailPanelDrawer.cs +++ b/Source/Infrastructure/UI/AgentsPage/AgentDetailPanelDrawer.cs @@ -22,6 +22,9 @@ public sealed class AgentDetailPanelDrawer private string? _cachedNpcKey; private System.Collections.Generic.IReadOnlyList _cachedTraceRows = System.Array.Empty(); + private Vector2 _permissionsScrollPos; + + internal void ScrollToBottom() => _permissionsScrollPos = new Vector2(0f, 100000f); internal int TraceRebuildCount { get; private set; } @@ -84,11 +87,15 @@ public void Draw(AgentPageRects layout, Pawn? selectedPawn, RimMindLayoutScope s Messages.Message("RimMind.UI.AgentsPage.CreateFailed".Translate(), MessageTypeDefOf.RejectInput, false); } + if (comp != null && layout.Permissions.height > 28f) + DrawPermissionsPanel(layout.Permissions, selectedPawn, comp); return; } var agent = comp.Agent; DrawActions(layout.ActionBar, agent); + if (layout.Permissions.height > 28f) + DrawPermissionsPanel(layout.Permissions, selectedPawn, comp); } private static void DrawDetailHeader(Rect rect, Pawn pawn, IAgentControl? agent) @@ -232,5 +239,150 @@ private System.Collections.Generic.IReadOnlyList BuildTrac TraceRebuildCount++; return _cachedTraceRows; } + + private void DrawPermissionsPanel(Rect rect, Pawn selectedPawn, CompPawnAgent comp) + { + var policy = comp.AutonomyPolicy; + if (policy == null) return; + + Rect inner = rect.ContractedBy(4f); + float y = inner.y; + + Text.Font = GameFont.Small; + GUI.color = RimMindUI.ColorHeader; + Rect titleRect = new Rect(inner.x, y, inner.width, 20f); + Widgets.LabelEllipses(titleRect, SafeTranslate("RimMind.UI.AgentsPage.Permissions.Title", "Agent Permissions")); + TooltipHandler.TipRegion(titleRect, SafeTranslate("RimMind.UI.AgentsPage.Permissions.TitleTip", "Control what autonomous domains this colonist Agent is permitted to execute.")); + GUI.color = Color.white; + y += 22f; + + const float presetH = 22f; + const float gap = 4f; + float presetW = Mathf.Max(40f, (inner.width - gap * 2f) / 3f); + + Rect workOnlyRect = new Rect(inner.x, y, presetW, presetH); + if (Widgets.ButtonText(workOnlyRect, SafeTranslate("RimMind.UI.AgentsPage.Permissions.PresetWorkOnly", "Work Only"))) + policy.ApplyWorkOnlyNoBlueprintsPreset(); + TooltipHandler.TipRegion(workOnlyRect, SafeTranslate("RimMind.UI.AgentsPage.Permissions.PresetWorkOnlyTip", "Allow survival/resource/worktable autonomy, disable blueprints and Work Tab changes.")); + + Rect defaultRect = new Rect(workOnlyRect.xMax + gap, y, presetW, presetH); + if (Widgets.ButtonText(defaultRect, SafeTranslate("RimMind.UI.AgentsPage.Permissions.PresetDefault", "Default"))) + policy.SetDefaultPreset(); + TooltipHandler.TipRegion(defaultRect, SafeTranslate("RimMind.UI.AgentsPage.Permissions.PresetDefaultTip", "Restore balanced default permissions.")); + + Rect fullAutoRect = new Rect(defaultRect.xMax + gap, y, Mathf.Max(40f, inner.xMax - defaultRect.xMax - gap), presetH); + if (Widgets.ButtonText(fullAutoRect, SafeTranslate("RimMind.UI.AgentsPage.Permissions.PresetFullAuto", "Full Auto"))) + policy.ApplyFullAutonomousPreset(); + TooltipHandler.TipRegion(fullAutoRect, SafeTranslate("RimMind.UI.AgentsPage.Permissions.PresetFullAutoTip", "Enable autonomous execution for blueprints, work priorities, survival, and bills.")); + y += presetH + 6f; + + const float applyAllH = 24f; + float listHeight = inner.yMax - y - applyAllH - 6f; + if (listHeight >= 26f) + { + var domains = (RimMind.Domain.Agent.Policies.AutonomyDomain[])System.Enum.GetValues(typeof(RimMind.Domain.Agent.Policies.AutonomyDomain)); + const float rowH = 24f; + const float rowGap = 3f; + Rect outRect = new Rect(inner.x, y, inner.width, listHeight); + float totalH = domains.Length * (rowH + rowGap) + 4f; + bool needsScroll = totalH > outRect.height + 1f; + float contentW = needsScroll + ? Mathf.Max(20f, inner.width - RimMindUiMetrics.ScrollBarWidth) + : Mathf.Max(20f, inner.width); + Rect viewRect = new Rect(0f, 0f, contentW, needsScroll ? totalH : outRect.height); + + Widgets.BeginScrollView(outRect, ref _permissionsScrollPos, viewRect); + float ry = 0f; + for (int i = 0; i < domains.Length; i++) + { + var domain = domains[i]; + var level = policy.GetLevel(domain); + const float btnW = 56f; + Rect rowRect = new Rect(0f, ry, contentW, rowH); + Rect labelRect = new Rect(0f, ry + 2f, Mathf.Max(20f, contentW - btnW - 4f), rowH - 2f); + Rect toggleRect = new Rect(Mathf.Max(0f, contentW - btnW), ry, btnW, rowH); + + Widgets.LabelEllipses(labelRect, DomainLabel(domain)); + TooltipHandler.TipRegion(rowRect, DomainTooltip(domain)); + + GUI.color = ColorForLevel(level); + if (Widgets.ButtonText(toggleRect, LevelShortLabel(level))) + policy.SetLevel(domain, NextLevel(level)); + GUI.color = Color.white; + + ry += rowH + rowGap; + } + Widgets.EndScrollView(); + y = outRect.yMax + 6f; + } + + Rect applyAllRect = new Rect(inner.x, Mathf.Max(y, inner.yMax - applyAllH), inner.width, applyAllH); + if (Widgets.ButtonText(applyAllRect, SafeTranslate("RimMind.UI.AgentsPage.Permissions.ApplyAll", "Apply to All Colonists"))) + { + var colonists = RimMind.Presentation.Api.RimMindPawnLookup.GetEligibleColonists(Find.CurrentMap); + foreach (var pawn in colonists) + { + if (pawn == null || ReferenceEquals(pawn, selectedPawn)) continue; + var peerComp = CompPawnAgent.GetComp(pawn); + peerComp?.AutonomyPolicy?.CopyFrom(policy); + } + Messages.Message( + SafeTranslate("RimMind.UI.AgentsPage.Permissions.AppliedAllToast", "Applied permissions to all active colonists."), + MessageTypeDefOf.PositiveEvent, + false); + } + TooltipHandler.TipRegion(applyAllRect, SafeTranslate("RimMind.UI.AgentsPage.Permissions.ApplyAllTip", "Copy this colonist's permission policy to every active colonist agent on the map.")); + } + + private static RimMind.Domain.Agent.Policies.AutonomyLevel NextLevel(RimMind.Domain.Agent.Policies.AutonomyLevel level) + => level switch + { + RimMind.Domain.Agent.Policies.AutonomyLevel.FullAutonomous => RimMind.Domain.Agent.Policies.AutonomyLevel.RequireApproval, + RimMind.Domain.Agent.Policies.AutonomyLevel.RequireApproval => RimMind.Domain.Agent.Policies.AutonomyLevel.Disabled, + _ => RimMind.Domain.Agent.Policies.AutonomyLevel.FullAutonomous + }; + + private static Color ColorForLevel(RimMind.Domain.Agent.Policies.AutonomyLevel level) + => level switch + { + RimMind.Domain.Agent.Policies.AutonomyLevel.FullAutonomous => new Color(0.55f, 0.95f, 0.6f), + RimMind.Domain.Agent.Policies.AutonomyLevel.RequireApproval => new Color(0.98f, 0.82f, 0.4f), + _ => new Color(0.85f, 0.5f, 0.5f) + }; + + private static string LevelShortLabel(RimMind.Domain.Agent.Policies.AutonomyLevel level) + => level switch + { + RimMind.Domain.Agent.Policies.AutonomyLevel.FullAutonomous => SafeTranslate("RimMind.AutonomyLevel.Auto", "Auto"), + RimMind.Domain.Agent.Policies.AutonomyLevel.RequireApproval => SafeTranslate("RimMind.AutonomyLevel.Ask", "Ask"), + _ => SafeTranslate("RimMind.AutonomyLevel.Off", "Off") + }; + + private static string DomainLabel(RimMind.Domain.Agent.Policies.AutonomyDomain domain) + => domain switch + { + RimMind.Domain.Agent.Policies.AutonomyDomain.EmergencySurvival => SafeTranslate("RimMind.AutonomyDomain.EmergencySurvival", "Survival"), + RimMind.Domain.Agent.Policies.AutonomyDomain.ResourceMarking => SafeTranslate("RimMind.AutonomyDomain.ResourceMarking", "Resources"), + RimMind.Domain.Agent.Policies.AutonomyDomain.WorktableBills => SafeTranslate("RimMind.AutonomyDomain.WorktableBills", "Work Bills"), + RimMind.Domain.Agent.Policies.AutonomyDomain.BlueprintPlacement => SafeTranslate("RimMind.AutonomyDomain.BlueprintPlacement", "Blueprints"), + RimMind.Domain.Agent.Policies.AutonomyDomain.HighRiskOperations => SafeTranslate("RimMind.AutonomyDomain.HighRiskOperations", "High Risk"), + RimMind.Domain.Agent.Policies.AutonomyDomain.WorkPriorityModification => SafeTranslate("RimMind.AutonomyDomain.WorkPriorityModification", "Work Tab"), + _ => domain.ToString() + }; + + private static string DomainTooltip(RimMind.Domain.Agent.Policies.AutonomyDomain domain) + => domain switch + { + RimMind.Domain.Agent.Policies.AutonomyDomain.EmergencySurvival => SafeTranslate("RimMind.AutonomyDomain.EmergencySurvivalTip", "Eating, resting, rescue, tending, and emergency flee actions."), + RimMind.Domain.Agent.Policies.AutonomyDomain.ResourceMarking => SafeTranslate("RimMind.AutonomyDomain.ResourceMarkingTip", "Designating trees, ore veins, plants, and haulables."), + RimMind.Domain.Agent.Policies.AutonomyDomain.WorktableBills => SafeTranslate("RimMind.AutonomyDomain.WorktableBillsTip", "Adding or managing crafting and cooking bills on worktables."), + RimMind.Domain.Agent.Policies.AutonomyDomain.BlueprintPlacement => SafeTranslate("RimMind.AutonomyDomain.BlueprintPlacementTip", "Placing building blueprints or planning rooms."), + RimMind.Domain.Agent.Policies.AutonomyDomain.HighRiskOperations => SafeTranslate("RimMind.AutonomyDomain.HighRiskOperationsTip", "Arrests, deconstruction, or irreversible dangerous actions."), + RimMind.Domain.Agent.Policies.AutonomyDomain.WorkPriorityModification => SafeTranslate("RimMind.AutonomyDomain.WorkPriorityModificationTip", "Changing Work Tab numeric priorities (Off by default to protect player schedules)."), + _ => domain.ToString() + }; + + private static string SafeTranslate(string key, string fallback) + => key.CanTranslate() ? key.Translate().ToString() : fallback; } } diff --git a/Source/Infrastructure/UI/AgentsPage/AgentPageLayout.cs b/Source/Infrastructure/UI/AgentsPage/AgentPageLayout.cs index bb7aa6c..dd18336 100644 --- a/Source/Infrastructure/UI/AgentsPage/AgentPageLayout.cs +++ b/Source/Infrastructure/UI/AgentsPage/AgentPageLayout.cs @@ -13,11 +13,25 @@ public AgentPageRects( Rect activity, Rect chat, ActionBarLayoutResult actionBar) + : this(list, detail, status, actions, default, activity, chat, actionBar) + { + } + + public AgentPageRects( + Rect list, + Rect detail, + Rect status, + Rect actions, + Rect permissions, + Rect activity, + Rect chat, + ActionBarLayoutResult actionBar) { List = list; Detail = detail; Status = status; Actions = actions; + Permissions = permissions; Activity = activity; Chat = chat; ActionBar = actionBar; @@ -27,6 +41,7 @@ public AgentPageRects( public Rect Detail { get; } public Rect Status { get; } public Rect Actions { get; } + public Rect Permissions { get; } public Rect Activity { get; } public Rect Chat { get; } public ActionBarLayoutResult ActionBar { get; } @@ -34,10 +49,10 @@ public AgentPageRects( public static class AgentPageLayout { - private const float MinActivityWidth = 260f; - private const float MinDetailWidth = 220f; - private const float MaxDetailWidth = 300f; - private const float DetailWidthRatio = 0.36f; + private const float MinActivityWidth = 250f; + private const float MinDetailWidth = 240f; + private const float MaxDetailWidth = 320f; + private const float DetailWidthRatio = 0.40f; public static AgentPageRects Calculate(Rect rect) { @@ -72,12 +87,14 @@ public static AgentPageRects Calculate(Rect rect) scrollable.height); Rect status = new Rect(detail.x, detail.y, detail.width, 80f); Rect actions = new Rect(detail.x, status.yMax + RimMindUiMetrics.Padding, detail.width, 70f); + float permY = actions.yMax + RimMindUiMetrics.Padding; + Rect permissions = new Rect(detail.x, permY, detail.width, Mathf.Max(0f, detail.yMax - permY)); ActionBarLayoutResult actionBar = ActionBarLayout.Calculate( actions, new[] { "primary", "force_think", "open_requests" }); Rect list = new Rect(split.List.x, split.List.y, split.List.width, scrollable.yMax - split.List.y); - return new AgentPageRects(list, detail, status, actions, activity, chat, actionBar); + return new AgentPageRects(list, detail, status, actions, permissions, activity, chat, actionBar); } } } diff --git a/Source/Infrastructure/UI/AgentsPage/AgentsPageDrawer.cs b/Source/Infrastructure/UI/AgentsPage/AgentsPageDrawer.cs index c8e01e9..462bdb4 100644 --- a/Source/Infrastructure/UI/AgentsPage/AgentsPageDrawer.cs +++ b/Source/Infrastructure/UI/AgentsPage/AgentsPageDrawer.cs @@ -17,6 +17,7 @@ internal void ScrollToBottom() { _listDrawer.ScrollToBottom(); _activityDrawer.ScrollToBottom(); + _detailDrawer.ScrollToBottom(); } public void Draw(Rect rect, Pawn? hubSelectedPawn, RimMindLayoutScope scope) diff --git a/Source/Infrastructure/UI/DebugActions/AICoreDebugActions.Autotests.cs b/Source/Infrastructure/UI/DebugActions/AICoreDebugActions.Autotests.cs index 80f71b3..013edd1 100644 --- a/Source/Infrastructure/UI/DebugActions/AICoreDebugActions.Autotests.cs +++ b/Source/Infrastructure/UI/DebugActions/AICoreDebugActions.Autotests.cs @@ -24,15 +24,17 @@ namespace RimMind.Infrastructure.UI public static partial class RimMindCoreDebugActions { [DebugAction("Autotests", "Test H2 Actions Equivalence", actionType = DebugActionType.Action)] - public static void TestH2ActionsEquivalence() + public static void TestH2ActionsEquivalence() => RunH2EquivalenceCore(); + + internal static (int Pass, int Fail) RunH2EquivalenceCore() { RuntimeServiceScope runtimeScope = RuntimeServiceHub.Shared.Capture(); - RunH2ActionsEquivalence( + return RunH2ActionsEquivalence( runtimeScope.GetOptional()?.All ?? new List(), runtimeScope.GetOptional()?.All ?? new List()); } - private static void RunH2ActionsEquivalence( + private static (int Pass, int Fail) RunH2ActionsEquivalence( IReadOnlyList mechanisms, IReadOnlyList tools) { @@ -58,18 +60,27 @@ private static void RunH2ActionsEquivalence( foreach (var action in writeActions) { - // Convention: tool id = "mechanismId_action" or "mechanismId" - string conventionToolId = $"{mech.MechanismId}_{action.Action}"; - string mechanismToolId = mech.MechanismId; - if (toolIds.Contains(conventionToolId) || toolIds.Contains(mechanismToolId)) + // Convention: action-scoped id "mechanismId_action" or operation-scoped mechanism tool id + string[] candidates = + { + $"{mech.MechanismId}_{action.Action}", + mech.MechanismId, + $"{mech.MechanismId}.set", + $"{mech.MechanismId}.add", + $"{mech.MechanismId}.remove", + $"{mech.MechanismId}.toggle", + $"{mech.MechanismId}.trigger", + $"{mech.MechanismId}.watch" + }; + string? matchedId = candidates.FirstOrDefault(toolIds.Contains); + if (matchedId != null) { - string matchedId = toolIds.Contains(conventionToolId) ? conventionToolId : mechanismToolId; sb.AppendLine($" [PASS] {mech.MechanismId}.{action.Action} -> {matchedId}"); pass++; } else { - sb.AppendLine($" [FAIL] {mech.MechanismId}.{action.Action} -> no matching tool (tried '{conventionToolId}', '{mechanismToolId}')"); + sb.AppendLine($" [FAIL] {mech.MechanismId}.{action.Action} -> no matching tool"); Log.Error($"[Autotests] H2: {mech.MechanismId}.{action.Action} has no matching tool"); fail++; } @@ -85,6 +96,7 @@ private static void RunH2ActionsEquivalence( sb.AppendLine($" Result: {pass} passed, {fail} failed"); Log.Message(sb.ToString()); ReportAutotest("H2", pass, fail); + return (pass, fail); } [DebugAction("Autotests", "Test P Visibility Entrypoints", actionType = DebugActionType.Action)] @@ -119,7 +131,7 @@ void Check(string name, Func predicate) Check("Core icon asset", () => ContentFinder.Get("UI/RimMind/Icon", false) != null); foreach (string pageId in new[] { - "overview", "agents", "ai_requests", "tool_calls", "mechanisms", "context_keys", "settings" + "overview", "agents", "ai_requests", "capabilities", "settings" }) { Check($"Debug center page: {pageId}", () => @@ -356,7 +368,9 @@ private static void RunLContextEvolution( ReportAutotest("L.ContextEvolution", pass, fail); } [DebugAction("Autotests", "Test UI Layout Conflict Detector", actionType = DebugActionType.Action)] - public static void TestUiLayoutConflictDetector() + public static void TestUiLayoutConflictDetector() => RunUiLayoutConflictCheck(); + + internal static void RunUiLayoutConflictCheck(Action? onCompleted = null) { LayoutConflictStore.Clear(); LayoutConflictStore.TracingEnabled = true; @@ -387,6 +401,7 @@ public static void TestUiLayoutConflictDetector() evaluation.PassCount, evaluation.FailCount, evaluation.MissingReportCount); + onCompleted?.Invoke(evaluation); }); } diff --git a/Source/Infrastructure/UI/DebugActions/BehaviorAutotestRunner.cs b/Source/Infrastructure/UI/DebugActions/BehaviorAutotestRunner.cs index 1532db6..3d86946 100644 --- a/Source/Infrastructure/UI/DebugActions/BehaviorAutotestRunner.cs +++ b/Source/Infrastructure/UI/DebugActions/BehaviorAutotestRunner.cs @@ -22,8 +22,10 @@ using RimMind.Application.Common.Models.UI; using RimMind.Application.Features.Json; using RimMind.Application.Features.Llm; +using RimMind.Domain.Agent.Policies; using RimMind.Domain.Llm; using RimMind.Domain.ValueObjects; +using RimMind.Infrastructure.UI.Layout; using RimMind.Presentation; using RimMind.Presentation.Api; using RimMind.Presentation.Runtime.Services; @@ -255,10 +257,14 @@ private IEnumerator RunSuiteArchitecture() var sw = Stopwatch.StartNew(); var result = new BehaviorAutotestResult { SuiteId = "Architecture.Contracts" }; + Exception? archEx = null; + LayoutAutotestEvaluation? layoutEval = null; try { - RimMindCoreDebugActions.TestH2ActionsEquivalence(); - result.Details.Add("TestH2ActionsEquivalence executed"); + var (h2Pass, h2Fail) = RimMindCoreDebugActions.RunH2EquivalenceCore(); + result.Details.Add($"TestH2ActionsEquivalence executed (pass={h2Pass}, fail={h2Fail})"); + if (h2Fail > 0) + throw new InvalidOperationException($"H2 Actions Equivalence had {h2Fail} failures."); RimMindCoreDebugActions.TestPVisibilityEntrypoints(); result.Details.Add("TestPVisibilityEntrypoints executed"); @@ -269,19 +275,45 @@ private IEnumerator RunSuiteArchitecture() RimMindCoreDebugActions.TestLContextEvolution(); result.Details.Add("TestLContextEvolution executed"); - RimMindCoreDebugActions.TestUiLayoutConflictDetector(); - result.Details.Add("TestUiLayoutConflictDetector executed"); + RimMindCoreDebugActions.RunUiLayoutConflictCheck(ev => layoutEval = ev); + } + catch (Exception ex) + { + archEx = ex; + } + if (archEx == null) + { + int waitFrames = 0; + while (layoutEval == null && waitFrames < 12) + { + waitFrames++; + yield return new WaitForEndOfFrame(); + } + + if (layoutEval == null || !layoutEval.IsSuccess) + { + archEx = new InvalidOperationException( + $"UI Layout Conflict Detector failed (pass={layoutEval?.PassCount ?? 0}, fail={layoutEval?.FailCount ?? -1}, missing={layoutEval?.MissingReportCount ?? -1})."); + } + else + { + result.Details.Add($"TestUiLayoutConflictDetector executed (pass={layoutEval.PassCount}, fail={layoutEval.FailCount})"); + } + } + + if (archEx == null) + { result.PassCount = 5; result.Status = "PASS"; result.Message = "All 5 core architecture and contract tests executed successfully."; } - catch (Exception ex) + else { result.FailCount = 1; result.Status = "FAIL"; - result.Message = $"Architecture test failed: {ex.Message}"; - result.Details.Add(ex.ToString()); + result.Message = $"Architecture test failed: {archEx.Message}"; + result.Details.Add(archEx.ToString()); } sw.Stop(); @@ -641,6 +673,20 @@ private IEnumerator RunSuiteAllToolsExecution() } // 3. Execute Tool + bool temporarilyUnlockedWorkPolicy = false; + AutonomyLevel savedWorkPolicy = AutonomyLevel.Disabled; + int savedFirefighterPrio = 3; + if (tool.Definition.Id == "pawn.work.set" && colonist != null) + { + savedWorkPolicy = RimMindAPI.Autonomy.GetLevel(colonist, AutonomyDomain.WorkPriorityModification); + savedFirefighterPrio = colonist.workSettings != null ? colonist.workSettings.GetPriority(WorkTypeDefOf.Firefighter) : 3; + if (savedWorkPolicy == AutonomyLevel.Disabled) + { + RimMindAPI.Autonomy.SetLevel(colonist, AutonomyDomain.WorkPriorityModification, AutonomyLevel.FullAutonomous); + temporarilyUnlockedWorkPolicy = true; + } + } + var toolSw = Stopwatch.StartNew(); Task>? task = null; Exception? launchEx = null; @@ -661,6 +707,19 @@ private IEnumerator RunSuiteAllToolsExecution() } } + if (tool.Definition.Id == "pawn.work.set" && colonist != null) + { + if (colonist.workSettings != null) + { + colonist.workSettings.EnableAndInitializeIfNotAlreadyInitialized(); + colonist.workSettings.SetPriority(WorkTypeDefOf.Firefighter, savedFirefighterPrio); + } + if (temporarilyUnlockedWorkPolicy) + { + RimMindAPI.Autonomy.SetLevel(colonist, AutonomyDomain.WorkPriorityModification, savedWorkPolicy); + } + } + toolSw.Stop(); item.DurationMs = toolSw.ElapsedMilliseconds; @@ -1022,6 +1081,10 @@ private static bool IsExpectedDomainRejection(string toolId, string? error) || error.IndexOf("No job available", StringComparison.OrdinalIgnoreCase) >= 0)) return true; + // pawn.work.set: when player autonomy policy disables WorkPriorityModification + if (toolId == "pawn.work.set" && error.IndexOf("by player autonomy policy", StringComparison.OrdinalIgnoreCase) >= 0) + return true; + // Composite actions on fresh -quicktest map: resource safety guard or missing worktable if ((toolId == "actions_plan_room_project" || toolId == "actions_place_blueprint") && (error.IndexOf("[Safety Guard]", StringComparison.OrdinalIgnoreCase) >= 0 || @@ -1171,7 +1234,7 @@ private IEnumerator RunSuiteUiInteraction() visitedPages++; } } - if (visitedPages == allPages.Count && allPages.Count >= 6) + if (visitedPages == allPages.Count && allPages.Count >= 5) { checksPassed++; result.Details.Add($"[PASS] Simulated Click: Navigated all {visitedPages} Hub tabs ({string.Join(", ", allPages)})"); diff --git a/Source/Infrastructure/UI/DebugActions/PlaythroughPlayerSimulation.cs b/Source/Infrastructure/UI/DebugActions/PlaythroughPlayerSimulation.cs new file mode 100644 index 0000000..3c0f1ee --- /dev/null +++ b/Source/Infrastructure/UI/DebugActions/PlaythroughPlayerSimulation.cs @@ -0,0 +1,609 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RimMind.Presentation.Api; +using RimWorld; +using Verse; + +namespace RimMind.Infrastructure.UI.DebugActions +{ + /// + /// Command written by the external Sub Blind Agent (simulated human player) into + /// bridge/cmd_day_XX.json. See .agents/skills/rimmind-interactive-playthrough. + /// + public sealed class ColonySubagentCommand + { + public int Day { get; set; } + public string Action { get; set; } = string.Empty; + public string Target { get; set; } = string.Empty; + public string Reason { get; set; } = string.Empty; + public string UxFinding { get; set; } = string.Empty; + } + + /// Per-colonist vitals a human player sees on screen (needs, injuries, mental state). + public sealed class PlayerViewColonist + { + public string Name { get; set; } = string.Empty; + public float Mood { get; set; } + public float Food { get; set; } + public float Rest { get; set; } + public string HealthSummary { get; set; } = string.Empty; + public bool IsDowned { get; set; } + public float BleedingRate { get; set; } + public bool HasTendableHediff { get; set; } + public string MentalState { get; set; } = string.Empty; + public string CurrentJob { get; set; } = string.Empty; + public bool IsAgentActive { get; set; } + public string AgentMode { get; set; } = string.Empty; + public List BadThoughts { get; set; } = new(); + } + + /// + /// Simulated-player operations used by the in-game playthrough harness. + /// Everything here mirrors clicks a human player would make (unforbid starting + /// cargo, designate zones, place blueprints). It never edits pawn needs/health, + /// never fabricates LLM traffic, and never touches RimMind Mod settings or queues. + /// Every operation is logged with the [SimulatedPlayer] tag so reports keep + /// a strict separation between the external player and Mod-internal agents. + /// + internal static class PlaythroughPlayerSimulation + { + internal const string LogTag = "[RimMind-Playthrough][SimulatedPlayer]"; + + /// + /// Crashlanded/quicktest cargo spawns forbidden; a human player unforbids it on + /// the first frame. Without this even vanilla (non-agent) colonists starve. + /// + internal static int UnforbidStartingItems(Map? map) + { + if (map?.listerThings?.AllThings == null) return 0; + + int count = 0; + try + { + var items = map.listerThings.AllThings + .Where(t => t != null && t.Spawned && t.def != null && t.def.category == ThingCategory.Item) + .ToList(); + + foreach (var t in items) + { + if (t.IsForbidden(Faction.OfPlayer)) + { + t.SetForbidden(false, warnOnFail: false); + count++; + } + } + + Log.Message($"{LogTag} Unforbid starting cargo: {count} item stack(s) (player action, day 1)."); + } + catch (Exception ex) + { + Log.Warning($"{LogTag} UnforbidStartingItems notice: {ex.Message}"); + } + + return count; + } + + /// + /// Executes one player command from the bridge. Unknown actions are reported as + /// failures; there is intentionally no scripted fallback routine. + /// + internal static (bool Success, string Detail) ExecuteCommand(ColonySubagentCommand cmd, Map map) + { + string action = (cmd.Action ?? string.Empty).Trim().ToLowerInvariant(); + IntVec3 safeBase = ResolveBaseCell(map); + + IntVec3 Offset(int dx, int dz) + { + var c = new IntVec3(safeBase.x + dx, safeBase.y, safeBase.z + dz); + return c.InBounds(map) ? c : safeBase; + } + + try + { + switch (action) + { + case "none": + case "observe": + return (true, "observe only"); + + case "unforbid": + return (true, $"unforbid {UnforbidStartingItems(map)} stacks"); + + case "plan_housing": + { + int placed = 0; + for (int x = 0; x < 10; x++) + { + AddDesignationSafe(map, Offset(x, 0), DesignationDefOf.Plan); + AddDesignationSafe(map, Offset(x, 9), DesignationDefOf.Plan); + } + for (int z = 0; z < 10; z++) + { + AddDesignationSafe(map, Offset(0, z), DesignationDefOf.Plan); + AddDesignationSafe(map, Offset(9, z), DesignationDefOf.Plan); + } + if (TryPlaceBlueprint(map, "Bed", Offset(2, 2), Rot4.South, "WoodLog") != null) placed++; + if (TryPlaceBlueprint(map, "Bed", Offset(4, 2), Rot4.South, "WoodLog") != null) placed++; + if (TryPlaceBlueprint(map, "Bed", Offset(6, 2), Rot4.South, "WoodLog") != null) placed++; + if (TryPlaceBlueprint(map, "Table2x2c", Offset(5, 6), Rot4.North, "WoodLog") != null) placed++; + if (TryPlaceBlueprint(map, "Stool", Offset(4, 6), Rot4.East, "WoodLog") != null) placed++; + if (TryPlaceBlueprint(map, "TorchLamp", Offset(8, 8), Rot4.North, "WoodLog") != null) placed++; + return (placed > 0, $"plan lines + {placed} blueprint(s)"); + } + + case "mine": + { + string? targetDef = string.IsNullOrWhiteSpace(cmd.Target) ? null : cmd.Target.Trim(); + if (targetDef != null && targetDef.IndexOf("steel", StringComparison.OrdinalIgnoreCase) >= 0) + targetDef = "Steel"; + else if (targetDef != null && targetDef.IndexOf("component", StringComparison.OrdinalIgnoreCase) >= 0) + targetDef = "ComponentsIndustrial"; + + var mineTarget = FindNearestMineable(map, safeBase, targetDef) ?? FindNearestMineable(map, safeBase, null); + if (mineTarget == null) return (false, "no mineable rock found"); + + int designated = 0; + for (int dx = -1; dx <= 1; dx++) + { + for (int dz = -1; dz <= 1; dz++) + { + var c = new IntVec3(mineTarget.Position.x + dx, mineTarget.Position.y, mineTarget.Position.z + dz); + if (!c.InBounds(map)) continue; + var thing = map.thingGrid.ThingAt(c, ThingCategory.Building); + if (thing != null && (thing.def.mineable || (thing.def.building != null && thing.def.building.isNaturalRock))) + { + if (AddDesignationSafe(map, c, DesignationDefOf.Mine)) designated++; + } + } + } + return (designated > 0, $"mine {designated} cell(s) near {mineTarget.def.defName}"); + } + + case "grow": + { + string plant = NormalizePlantDef(cmd.Target); + var zone = CreateGrowingZoneSafe(map, CellFinder.StandableCellNear(safeBase, map, 10), 6, 6, plant); + return (zone != null, zone != null ? $"growing zone {zone.cells.Count} cells ({plant})" : "no fertile cells"); + } + + case "build": + { + var (defName, stuff) = NormalizeBuildTarget(cmd.Target); + var bp = TryPlaceBlueprint(map, defName, Offset(3, 4), Rot4.North, stuff); + return (bp != null, bp != null ? $"blueprint {defName} at {bp.Position}" : $"cannot place {defName}"); + } + + case "harvest_trees": + { + int designated = 0; + var trees = map.listerThings.AllThings + .Where(t => t.Spawned && t.def?.plant != null && t.def.plant.IsTree) + .OrderBy(t => t.Position.DistanceToSquared(safeBase)) + .Take(15) + .ToList(); + foreach (var tree in trees) + { + var desDef = (tree is Plant p && p.HarvestableNow) ? DesignationDefOf.HarvestPlant : DesignationDefOf.CutPlant; + if (AddDesignationSafe(map, tree.Position, desDef ?? DesignationDefOf.CutPlant)) designated++; + } + return (designated > 0, $"designated {designated} tree(s)"); + } + + case "build_room": + { + int placed = PlaceRoomBlueprint(map, safeBase, 7, 6); + return (placed > 0, placed > 0 ? $"room shell: {placed} wall/door blueprint(s)" : "no space for a 7x6 room"); + } + + case "hunt": + { + var animals = map.mapPawns.AllPawnsSpawned + .Where(a => a != null && !a.Dead && a.Faction == null && a.RaceProps != null && a.RaceProps.Animal + && !a.RaceProps.predator && !a.InAggroMentalState + && a.RaceProps.manhunterOnDamageChance <= 0.1f + && a.RaceProps.baseBodySize <= 1.5f + && !a.Position.Fogged(map) + && map.designationManager.DesignationOn(a, DesignationDefOf.Hunt) == null) + .OrderBy(a => a.Position.DistanceToSquared(safeBase)) + .Take(5) + .ToList(); + foreach (var a in animals) + { + map.designationManager.AddDesignation(new Designation(a, DesignationDefOf.Hunt)); + } + return (animals.Count > 0, $"hunt designated on {animals.Count} animal(s)"); + } + + case "stockpile": + { + var zone = CreateStockpileZoneSafe(map, CellFinder.StandableCellNear(safeBase, map, 6), 5, 5); + return (zone != null, zone != null ? $"stockpile {zone.cells.Count} cells" : "no free cells"); + } + + default: + return (false, $"unsupported action '{cmd.Action}'"); + } + } + catch (Exception ex) + { + return (false, $"exception: {ex.Message}"); + } + } + + internal static List BuildColonistVitals(Map? map, IEnumerable baseline) + { + var result = new List(); + if (map == null) return result; + + var baselineByName = baseline? + .Where(b => b != null && !string.IsNullOrEmpty(b.Name)) + .GroupBy(b => b.Name) + .ToDictionary(g => g.Key, g => g.First()) ?? new Dictionary(); + + foreach (var p in RimMindPawnLookup.GetSpawnedColonistsSafe(map)) + { + if (p == null || p.Dead) continue; + string name = p.Name?.ToStringShort ?? p.LabelShort; + + var bad = new List(); + try + { + if (p.needs?.mood?.thoughts != null) + { + var thoughts = new List(); + p.needs.mood.thoughts.GetAllMoodThoughts(thoughts); + foreach (var th in thoughts.Where(t => t != null && t.MoodOffset() < 0f).OrderBy(t => t.MoodOffset()).Take(5)) + { + bad.Add($"{th.LabelCap} ({th.MoodOffset():F0})"); + } + } + } + catch { } + + baselineByName.TryGetValue(name, out var snap); + result.Add(new PlayerViewColonist + { + Name = name, + Mood = p.needs?.mood?.CurLevel ?? 0f, + Food = p.needs?.food?.CurLevel ?? 0f, + Rest = p.needs?.rest?.CurLevel ?? 0f, + HealthSummary = p.health?.summaryHealth != null ? p.health.summaryHealth.SummaryHealthPercent.ToString("P0") : "?", + IsDowned = p.Downed, + BleedingRate = p.health?.hediffSet?.BleedRateTotal ?? 0f, + HasTendableHediff = p.health?.hediffSet?.HasTendableHediff() ?? false, + MentalState = p.MentalStateDef?.defName ?? string.Empty, + CurrentJob = p.CurJobDef?.defName ?? "Idle", + IsAgentActive = snap?.IsAgentActive ?? false, + AgentMode = snap?.AgentMode ?? string.Empty, + BadThoughts = bad + }); + } + return result; + } + + internal static List CollectActiveAlerts() + { + var labels = new List(); + try + { + var readout = (Find.UIRoot as UIRoot_Play)?.alerts; + var field = typeof(AlertsReadout).GetField("activeAlerts", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); + if (readout != null && field?.GetValue(readout) is List list) + { + foreach (var a in list) + { + string label = a?.GetLabel() ?? string.Empty; + if (!string.IsNullOrWhiteSpace(label)) labels.Add(label); + } + } + } + catch { } + return labels; + } + + internal static List CollectOpenWindows() + { + var names = new List(); + try + { + if (Find.WindowStack != null) + { + foreach (var w in Find.WindowStack.Windows) + { + if (w != null) names.Add(w.GetType().Name); + } + } + } + catch { } + return names; + } + + internal static int CountMedicine(Map? map) + { + int count = 0; + var meds = map?.listerThings?.ThingsInGroup(ThingRequestGroup.Medicine); + if (meds == null) return 0; + foreach (var t in meds) + { + if (t != null && t.Spawned && !t.IsForbidden(Faction.OfPlayer)) count += t.stackCount; + } + return count; + } + + internal static float CountUnstockpiledNutrition(Map? map) + { + float total = 0f; + var foods = map?.listerThings?.ThingsInGroup(ThingRequestGroup.FoodSourceNotPlantOrTree); + if (foods == null) return 0f; + foreach (var t in foods) + { + if (t == null || !t.Spawned || t.def?.ingestible == null || t is Pawn || t is Corpse) continue; + if (!t.def.IsNutritionGivingIngestible || !t.def.ingestible.HumanEdible) continue; + if (t.IsForbidden(Faction.OfPlayer) || t.IsInValidStorage()) continue; + total += t.GetStatValue(StatDefOf.Nutrition) * t.stackCount; + } + return total; + } + + /// Places wall blueprints for a rectangular room shell with one door (a real player's drag-build). + private static int PlaceRoomBlueprint(Map map, IntVec3 anchor, int width, int height) + { + var wallDef = DefDatabase.GetNamedSilentFail("Wall"); + var doorDef = DefDatabase.GetNamedSilentFail("Door"); + if (wallDef == null || doorDef == null) return 0; + ThingDef stuff = ThingDefOf.WoodLog; + + foreach (var origin in GenRadial.RadialCellsAround(anchor, 25, true)) + { + if (!origin.InBounds(map)) continue; + var cells = new List(); + for (int x = 0; x < width; x++) + { + cells.Add(new IntVec3(origin.x + x, 0, origin.z)); + cells.Add(new IntVec3(origin.x + x, 0, origin.z + height - 1)); + } + for (int z = 1; z < height - 1; z++) + { + cells.Add(new IntVec3(origin.x, 0, origin.z + z)); + cells.Add(new IntVec3(origin.x + width - 1, 0, origin.z + z)); + } + + bool interiorFree = true; + for (int x = 0; x < width && interiorFree; x++) + { + for (int z = 0; z < height && interiorFree; z++) + { + var c = new IntVec3(origin.x + x, 0, origin.z + z); + if (!c.InBounds(map) || c.Fogged(map) || !c.Standable(map) || c.GetEdifice(map) != null) + interiorFree = false; + } + } + if (!interiorFree) continue; + + IntVec3 doorCell = new IntVec3(origin.x + width / 2, 0, origin.z); + bool allOk = cells.All(c => + GenConstruct.CanPlaceBlueprintAt(c == doorCell ? doorDef : wallDef, c, Rot4.North, map, false, null, null, stuff).Accepted); + if (!allOk) continue; + + int placed = 0; + foreach (var c in cells) + { + GenConstruct.PlaceBlueprintForBuild(c == doorCell ? doorDef : wallDef, c, map, Rot4.North, Faction.OfPlayer, stuff); + placed++; + } + return placed; + } + return 0; + } + + private static IntVec3 ResolveBaseCell(Map map) + { + var colonists = RimMindPawnLookup.GetSpawnedColonistsSafe(map) + .Where(p => p != null && RimMindPawnLookup.IsActiveSpawnedColonist(p)) + .ToList(); + + IntVec3 anchor = map.Center; + if (colonists.Count > 0) + { + int x = (int)colonists.Average(p => p.Position.x); + int z = (int)colonists.Average(p => p.Position.z); + var c = new IntVec3(x, 0, z); + if (c.InBounds(map)) anchor = c; + } + + IntVec3 standable = CellFinder.StandableCellNear(anchor, map, 8); + return standable.IsValid && standable.InBounds(map) ? standable : map.Center; + } + + private static string NormalizePlantDef(string? target) + { + string t = (target ?? string.Empty).Trim(); + if (t.Length == 0 || t.IndexOf("rice", StringComparison.OrdinalIgnoreCase) >= 0) return "Plant_Rice"; + if (t.IndexOf("potato", StringComparison.OrdinalIgnoreCase) >= 0) return "Plant_Potato"; + if (t.IndexOf("corn", StringComparison.OrdinalIgnoreCase) >= 0) return "Plant_Corn"; + if (t.IndexOf("healroot", StringComparison.OrdinalIgnoreCase) >= 0) return "Plant_Healroot"; + if (t.IndexOf("cotton", StringComparison.OrdinalIgnoreCase) >= 0) return "Plant_Cotton"; + return t.StartsWith("Plant_", StringComparison.OrdinalIgnoreCase) ? t : "Plant_" + t; + } + + private static (string DefName, string? Stuff) NormalizeBuildTarget(string? target) + { + string t = (target ?? string.Empty).Trim(); + string lower = t.ToLowerInvariant(); + if (lower.Length == 0 || lower.Contains("bed")) return ("Bed", "WoodLog"); + if (lower.Contains("stove")) return ("FueledStove", null); + if (lower.Contains("butcher")) return ("TableButcher", "WoodLog"); + if (lower.Contains("passivecooler") || lower.Contains("passive_cooler")) return ("PassiveCooler", null); + if (lower.Contains("cooler")) return ("Cooler", null); + if (lower.Contains("heater")) return ("Heater", null); + if (lower.Contains("solar")) return ("SolarGenerator", null); + if (lower.Contains("battery")) return ("Battery", null); + if (lower.Contains("torch")) return ("TorchLamp", null); + if (lower.Contains("campfire")) return ("Campfire", null); + if (lower.Contains("table")) return ("Table2x2c", "WoodLog"); + if (lower.Contains("stool")) return ("Stool", "WoodLog"); + if (lower.Contains("grave")) return ("Grave", null); + return (t, null); + } + + private static Blueprint? TryPlaceBlueprint(Map map, string defName, IntVec3 cell, Rot4 rot, string? stuffDefName) + { + BuildableDef? buildableDef = (BuildableDef?)DefDatabase.GetNamedSilentFail(defName) + ?? DefDatabase.GetNamedSilentFail(defName); + if (buildableDef == null) return null; + + ThingDef? stuffDef = null; + if (buildableDef is ThingDef thingDef && thingDef.MadeFromStuff) + { + if (!string.IsNullOrEmpty(stuffDefName)) + stuffDef = DefDatabase.GetNamedSilentFail(stuffDefName); + stuffDef ??= GenStuff.DefaultStuffFor(thingDef) ?? ThingDefOf.WoodLog; + } + + try + { + Rot4[] rots = (buildableDef is ThingDef td && td.rotatable) + ? new[] { rot, Rot4.North, Rot4.East, Rot4.South, Rot4.West } + : new[] { rot }; + + foreach (var c in GenRadial.RadialCellsAround(cell.InBounds(map) ? cell : map.Center, 20, true)) + { + if (!c.InBounds(map) || c.Fogged(map) || !c.Standable(map)) continue; + foreach (var r in rots) + { + if (GenConstruct.CanPlaceBlueprintAt(buildableDef, c, r, map, false, null, null, stuffDef).Accepted) + { + return GenConstruct.PlaceBlueprintForBuild(buildableDef, c, map, r, Faction.OfPlayer, stuffDef); + } + } + } + } + catch (Exception ex) + { + Log.Warning($"{LogTag} PlaceBlueprint {defName} notice: {ex.Message}"); + } + return null; + } + + private static bool AddDesignationSafe(Map map, IntVec3 cell, DesignationDef? desDef) + { + if (map == null || desDef == null || !cell.InBounds(map)) return false; + try + { + if (desDef.targetType == TargetType.Thing) + { + Thing? targetThing = (desDef == DesignationDefOf.HarvestPlant || desDef == DesignationDefOf.CutPlant) + ? cell.GetPlant(map) + : cell.GetFirstThing(map); + if (targetThing != null && map.designationManager.DesignationOn(targetThing, desDef) == null) + { + map.designationManager.AddDesignation(new Designation(targetThing, desDef)); + return true; + } + return false; + } + + if (map.designationManager.DesignationAt(cell, desDef) == null) + { + map.designationManager.AddDesignation(new Designation(cell, desDef)); + return true; + } + } + catch (Exception ex) + { + Log.Warning($"{LogTag} AddDesignation {desDef.defName} notice: {ex.Message}"); + } + return false; + } + + private static List CollectFreeCells(Map map, IntVec3 origin, int width, int height, bool requireFertility) + { + var cells = new List(width * height); + for (int x = 0; x < width; x++) + { + for (int z = 0; z < height; z++) + { + var c = new IntVec3(origin.x + x, origin.y, origin.z + z); + if (!c.InBounds(map) || c.Fogged(map) || !c.Standable(map)) continue; + if (map.zoneManager.ZoneAt(c) != null) continue; + if (c.GetEdifice(map) != null) continue; + if (requireFertility && map.fertilityGrid != null && map.fertilityGrid.FertilityAt(c) < 0.7f) continue; + cells.Add(c); + } + } + return cells; + } + + private static List FindBestCells(Map map, IntVec3 start, int width, int height, bool requireFertility, int[] offsets) + { + var best = CollectFreeCells(map, start, width, height, requireFertility); + int target = (width * height) / 2; + if (best.Count >= target) return best; + + foreach (int dx in offsets) + { + foreach (int dz in offsets) + { + var candidate = CollectFreeCells(map, new IntVec3(start.x + dx, start.y, start.z + dz), width, height, requireFertility); + if (candidate.Count > best.Count) best = candidate; + if (best.Count >= target) return best; + } + } + return best; + } + + private static Zone_Growing? CreateGrowingZoneSafe(Map map, IntVec3 start, int width, int height, string plantDefName) + { + try + { + var cells = FindBestCells(map, start, width, height, true, new[] { -16, -10, 10, 16, -22, 22 }); + if (cells.Count == 0) return null; + + var zone = new Zone_Growing(map.zoneManager); + map.zoneManager.RegisterZone(zone); + foreach (var c in cells) zone.AddCell(c); + var plantDef = DefDatabase.GetNamedSilentFail(plantDefName); + if (plantDef != null) zone.SetPlantDefToGrow(plantDef); + return zone; + } + catch (Exception ex) + { + Log.Warning($"{LogTag} CreateGrowingZone notice: {ex.Message}"); + return null; + } + } + + private static Zone_Stockpile? CreateStockpileZoneSafe(Map map, IntVec3 start, int width, int height) + { + try + { + var cells = FindBestCells(map, start, width, height, false, new[] { -8, 8, -14, 14, -20, 20 }); + if (cells.Count == 0) return null; + + var zone = new Zone_Stockpile(StorageSettingsPreset.DefaultStockpile, map.zoneManager); + map.zoneManager.RegisterZone(zone); + foreach (var c in cells) zone.AddCell(c); + return zone; + } + catch (Exception ex) + { + Log.Warning($"{LogTag} CreateStockpileZone notice: {ex.Message}"); + return null; + } + } + + private static Thing? FindNearestMineable(Map map, IntVec3 center, string? specificDefName) + { + return map.listerThings.AllThings + .Where(t => t.Spawned && t.def != null && + (specificDefName != null + ? (t.def.defName.IndexOf(specificDefName, StringComparison.OrdinalIgnoreCase) >= 0 || + (t.def.building?.mineableThing != null && + t.def.building.mineableThing.defName.IndexOf(specificDefName, StringComparison.OrdinalIgnoreCase) >= 0)) + : (t.def.mineable || (t.def.building != null && t.def.building.isNaturalRock)))) + .OrderBy(t => t.Position.DistanceToSquared(center)) + .FirstOrDefault(); + } + } +} diff --git a/Source/Infrastructure/UI/DebugActions/ShowcaseSceneCaptureRunner.cs b/Source/Infrastructure/UI/DebugActions/ShowcaseSceneCaptureRunner.cs index 7577ac0..035834e 100644 --- a/Source/Infrastructure/UI/DebugActions/ShowcaseSceneCaptureRunner.cs +++ b/Source/Infrastructure/UI/DebugActions/ShowcaseSceneCaptureRunner.cs @@ -145,7 +145,7 @@ private IEnumerator Run(string runId, string? repoRoot) // Ensure core settings are set to optimal showcase values (including API key so no warning alert appears) RimMindCoreMod.Settings.provider = "openai"; RimMindCoreMod.Settings.apiEndpoint = "https://api.deepseek.com/v1"; - RimMindCoreMod.Settings.modelName = "deepseek-chat"; + RimMindCoreMod.Settings.modelName = "deepseek-flash"; RimMindCoreMod.Settings.apiKey = "sk-rimmind-showcase-verified-key"; RimMindCoreMod.Settings.maxConcurrentRequests = 3; RimMindCoreMod.Settings.maxTokens = 800; @@ -622,13 +622,13 @@ private static void PopulateAgentsTracesAndDialogue(List colonists, Pawn? ?? GameServiceHub.Shared.Capture().GetOptional(); if (traceLog != null) { - traceLog.StartRequest("req-personality-1", "RimMind-Personality", "deepseek-chat", "破晓心境自白", "观察日出麦浪", ""); + traceLog.StartRequest("req-personality-1", "RimMind-Personality", "deepseek-flash", "破晓心境自白", "观察日出麦浪", ""); traceLog.CompleteRequest("req-personality-1", "“初升的朝阳照在木屋与麦浪上,虽然昨天屁股被松鼠咬得很痛,但有热饭和伙伴在身边,生活依旧充满希望。”", 340, 180); - traceLog.StartRequest("req-actions-1", "RimMind-Actions", "deepseek-chat", "自主建造决策", "place_blueprint(Bed, WoodLog)", ""); + traceLog.StartRequest("req-actions-1", "RimMind-Actions", "deepseek-flash", "自主建造决策", "place_blueprint(Bed, WoodLog)", ""); traceLog.CompleteRequest("req-actions-1", "{\"tool\":\"place_blueprint\",\"building_def\":\"Bed\",\"stuff_def\":\"WoodLog\",\"reason\":\"为同伴补充温暖的木床\"}", 412, 210); - traceLog.StartRequest("req-dialogue-1", "RimMind-Dialogue", "deepseek-chat", "食堂晚宴交谈", "express_dialogue(speech, relation_delta=+6)", ""); + traceLog.StartRequest("req-dialogue-1", "RimMind-Dialogue", "deepseek-flash", "食堂晚宴交谈", "express_dialogue(speech, relation_delta=+6)", ""); traceLog.CompleteRequest("req-dialogue-1", "“终于端上热气腾腾的烤肉排了,今晚总算不用啃皮靴营养膏啦!”", 285, 165); } diff --git a/Source/Infrastructure/UI/DebugActions/TenDayPlaythroughRunner.cs b/Source/Infrastructure/UI/DebugActions/TenDayPlaythroughRunner.cs index e4a8c91..598e29f 100644 --- a/Source/Infrastructure/UI/DebugActions/TenDayPlaythroughRunner.cs +++ b/Source/Infrastructure/UI/DebugActions/TenDayPlaythroughRunner.cs @@ -4,37 +4,28 @@ using System.Diagnostics; using System.IO; using System.Linq; +using System.Reflection; using System.Text; -using System.Text.RegularExpressions; -using System.Threading; -using System.Threading.Tasks; +using LudeonTK; using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using RimMind.Application.Common.Interfaces; -using RimMind.Application.Common.Interfaces.Context; -using RimMind.Application.Common.Interfaces.Extension; using RimMind.Application.Common.Interfaces.Internal; -using RimMind.Application.Common.Interfaces.Tools; -using RimMind.Application.Common.Models.Context; -using RimMind.Application.Common.Models.Tools; +using RimMind.Application.Common.Models.Agent; +using RimMind.Application.Common.Models.Debug; using RimMind.Application.Common.Models.UI; -using RimMind.Application.Features.Llm; using RimMind.Application.Features.Requests.Queue; using RimMind.Domain.Agent.Modes; +using RimMind.Domain.Agent.Policies; using RimMind.Domain.Enums; -using RimMind.Domain.Llm; -using RimMind.Domain.ValueObjects; -using RimMind.Infrastructure.UI.DebugActions; using RimMind.Infrastructure.Verse; using RimMind.Presentation; -using RimMind.Presentation.Agent; using RimMind.Presentation.Api; using RimMind.Presentation.Runtime.Services; +using RimMind.Presentation.Settings; using RimWorld; using UnityEngine; using Verse; -namespace RimMind.Infrastructure.UI +namespace RimMind.Infrastructure.UI.DebugActions { public sealed class PlaythroughColonistSnapshot { @@ -42,15 +33,18 @@ public sealed class PlaythroughColonistSnapshot public float Mood { get; set; } public string CurrentJob { get; set; } = string.Empty; public string HealthSummary { get; set; } = string.Empty; + public bool IsAgentActive { get; set; } + public string AgentMode { get; set; } = string.Empty; } - public sealed class ColonySubagentCommand + public sealed class PlaythroughAgentActionSummary { - public int Day { get; set; } - public string Action { get; set; } = string.Empty; // dismiss_window, plan_housing, mine, grow, build, harvest_trees, stockpile, clear_queue, custom - public string Target { get; set; } = string.Empty; + public string PawnName { get; set; } = string.Empty; + public string Action { get; set; } = string.Empty; public string Reason { get; set; } = string.Empty; - public string UxFinding { get; set; } = string.Empty; + public bool Success { get; set; } + public string ResultReason { get; set; } = string.Empty; + public int Tick { get; set; } } public sealed class PlaythroughDayReport @@ -71,18 +65,44 @@ public sealed class PlaythroughDayReport public string DialogueSpeech { get; set; } = string.Empty; public string DialogueThoughtTag { get; set; } = string.Empty; public int DialogueRelationDelta { get; set; } + public int DialogueCount { get; set; } public string AgentActionPawn { get; set; } = string.Empty; public string AgentActionTool { get; set; } = string.Empty; public string AgentActionDetail { get; set; } = string.Empty; public string AgentActionReason { get; set; } = string.Empty; + public int AgentActionsExecutedCount { get; set; } + public List AgentActions { get; set; } = new(); public string AdvisorProposal { get; set; } = string.Empty; public bool AdvisorApproved { get; set; } public int WorkingMemoryCount { get; set; } public int EpisodicMemoryCount { get; set; } public int ColonyFactCount { get; set; } + public int ActiveMemories + { + get => WorkingMemoryCount; + set => WorkingMemoryCount = value; + } + public int ArchiveMemories + { + get => EpisodicMemoryCount; + set => EpisodicMemoryCount = value; + } + public int DarkMemories + { + get => ColonyFactCount; + set => ColonyFactCount = value; + } public int TotalTokensUsed { get; set; } + public int TokensUsed + { + get => TotalTokensUsed; + set => TotalTokensUsed = value; + } + public int LlmCallsCount { get; set; } + public int SuccessfulLlmCallsCount { get; set; } + public Dictionary LlmCallsBySource { get; set; } = new(StringComparer.OrdinalIgnoreCase); public int PrefixTokens { get; set; } - public float CacheHitRatio { get; set; } + public double CacheHitRatio { get; set; } public string ScreenshotPath { get; set; } = string.Empty; public long DayComputeDurationMs { get; set; } } @@ -97,33 +117,42 @@ public sealed class TenDayPlaythroughReport public int TotalTicksElapsed { get; set; } public long TotalDurationMs { get; set; } public int TotalLiveLlmRequests { get; set; } + public int SuccessfulLiveLlmRequests { get; set; } public int TotalTokensConsumed { get; set; } - public float AverageCacheHitRatio { get; set; } + public int TotalPrefixTokens { get; set; } + public double CacheHitRatio { get; set; } + public double AverageCacheHitRatio { get; set; } + public Dictionary LlmCallsBySource { get; set; } = new(StringComparer.OrdinalIgnoreCase); public List Days { get; set; } = new(); - public string OverallStatus { get; set; } = "RUNNING"; // "COMPLETED", "FAILED" + public string OverallStatus { get; set; } = "RUNNING"; public string SummaryNotes { get; set; } = string.Empty; } - internal sealed class TenDayPlaythroughRunner : MonoBehaviour + /// + /// Genuine in-game runtime test runner for RimMind. + /// Drives native RimWorld simulation ticks and observes real Mod subsystem outputs + /// (PawnAgent tool execution, RimMind-Dialogue, RimMind-Personality, RimMind-Advisor, RimMind-Memory) + /// without injecting synthetic LLM prompts, scripted base-building, or pawn stat cheating. + /// + public static class TenDayPlaythroughRunner { - private static TenDayPlaythroughRunner? _active; - - private string _runId = string.Empty; - private TenDayPlaythroughReport _report = new(); - private readonly Stopwatch _clock = new(); - private string _outputDir = string.Empty; - private string _bridgeDir = string.Empty; - private bool _interactiveBridgeEnabled; - private bool _maxUsageMode; - private static readonly Dictionary _recentActionFailures = new(); - // Snapshot of the player's Core settings and prefs; restored on finish, fault, init failure and destroy. - private SettingsOverrideScope? _settingsScope; - - private int _totalDays = 10; - - internal static void StartPlaythrough(string? runId = null, int totalDays = 10) + private static PlaythroughCoroutineHost? _activeHost; + + [DebugAction("RimMind", "Run 10-Day AI Playthrough", actionType = DebugActionType.Action, allowedGameStates = AllowedGameStates.PlayingOnMap)] + public static void StartPlaythrough() + { + int defaultDays = ResolveConfiguredDays(10); + StartPlaythrough(null, defaultDays); + } + + public static void StartPlaythrough(int totalDays) { - if (_active != null) + StartPlaythrough(null, totalDays); + } + + public static void StartPlaythrough(string? runId, int totalDays = 10) + { + if (_activeHost != null) { Log.Warning("[RimMind-Playthrough] Playthrough runner is already running."); return; @@ -135,4153 +164,1602 @@ internal static void StartPlaythrough(string? runId = null, int totalDays = 10) return; } - TenDayPlaythroughRunner? runner = null; + int clampedDays = Math.Clamp(totalDays > 0 ? totalDays : ResolveConfiguredDays(10), 1, 100); + string resolvedRunId = !string.IsNullOrWhiteSpace(runId) + ? runId!.Trim() + : $"pt{clampedDays}-{Guid.NewGuid().ToString("N").Substring(0, 8)}"; + + PlaythroughCoroutineHost? host = null; try { - runner = Current.Root.gameObject.AddComponent(); - _active = runner; - runner.Initialize(runId ?? Guid.NewGuid().ToString("N"), totalDays); + host = Current.Root.gameObject.AddComponent(); + _activeHost = host; + host.Begin(resolvedRunId, clampedDays); } catch (Exception ex) { Log.Error("[RimMind-Playthrough] Failed to initialize playthrough runner: " + ex); - _active = null; - if (runner != null) + _activeHost = null; + if (host != null) { - runner.RestorePlayerSettings(); - Destroy(runner); + host.RestorePlayerSettings(); + UnityEngine.Object.Destroy(host); } } } - private void Initialize(string runId, int totalDays = 10) + private static int ResolveConfiguredDays(int fallbackDays) { - _runId = runId; - _totalDays = totalDays > 0 ? totalDays : 10; - _clock.Start(); - - // Snapshot player settings (and the global prefs this run flips) before the first override. - _settingsScope = CoreSettingsOverrideScope.Begin("Playthrough"); - _settingsScope.TrackExternal(() => Prefs.DevMode, v => Prefs.DevMode = v); - _settingsScope.TrackExternal(() => Prefs.AdaptiveTrainingEnabled, v => Prefs.AdaptiveTrainingEnabled = v); - - // Override credentials from environment if provided - string? envKey = Environment.GetEnvironmentVariable("RIMMIND_TEST_API_KEY"); - string? envEndpoint = Environment.GetEnvironmentVariable("RIMMIND_TEST_ENDPOINT"); - string? envModel = Environment.GetEnvironmentVariable("RIMMIND_TEST_MODEL"); - - if (!string.IsNullOrWhiteSpace(envKey)) - RimMindCoreMod.Settings.apiKey = envKey; - if (!string.IsNullOrWhiteSpace(envEndpoint)) - RimMindCoreMod.Settings.apiEndpoint = envEndpoint; - if (!string.IsNullOrWhiteSpace(envModel)) - RimMindCoreMod.Settings.modelName = envModel; - - string? backupKey = Environment.GetEnvironmentVariable("RIMMIND_BACKUP_API_KEY"); - string? backupEndpoint = Environment.GetEnvironmentVariable("RIMMIND_BACKUP_ENDPOINT"); - string? backupModel = Environment.GetEnvironmentVariable("RIMMIND_BACKUP_MODEL"); - string? backupProvider = Environment.GetEnvironmentVariable("RIMMIND_BACKUP_PROVIDER"); - if (!string.IsNullOrWhiteSpace(backupKey)) + string? envDays = Environment.GetEnvironmentVariable("RIMMIND_PLAYTHROUGH_DAYS"); + if (!string.IsNullOrWhiteSpace(envDays) && int.TryParse(envDays, out int parsed) && parsed > 0) { - string resolvedEndpoint = !string.IsNullOrWhiteSpace(backupEndpoint) - ? backupEndpoint!.Trim() - : "https://opencode.ai/zen/go/v1"; - string resolvedModel = !string.IsNullOrWhiteSpace(backupModel) - ? backupModel!.Trim() - : "beam-free"; - string resolvedProvider = !string.IsNullOrWhiteSpace(backupProvider) - ? backupProvider!.Trim() - : "opencode"; - - RimMindCoreMod.Settings.backupEndpoints ??= new List(); - var existing = RimMindCoreMod.Settings.backupEndpoints.FirstOrDefault(b => - b != null && - string.Equals(b.apiEndpoint?.Trim().TrimEnd('/'), resolvedEndpoint.TrimEnd('/'), StringComparison.OrdinalIgnoreCase) && - string.Equals(b.modelName?.Trim(), resolvedModel, StringComparison.OrdinalIgnoreCase)); - if (existing != null) - { - existing.apiKey = backupKey!.Trim(); - existing.provider = resolvedProvider; - existing.enabled = true; - } - else - { - RimMindCoreMod.Settings.backupEndpoints.Insert(0, new RimMind.Presentation.Settings.BackupEndpointEntry + return Math.Clamp(parsed, 1, 100); + } + return Math.Clamp(fallbackDays, 1, 100); + } + + private sealed class ApprovedOverlayItem + { + public string Source { get; set; } = string.Empty; + public string Title { get; set; } = string.Empty; + public string Description { get; set; } = string.Empty; + public string Choice { get; set; } = string.Empty; + public int Tick { get; set; } + } + + private sealed class PlaythroughCoroutineHost : MonoBehaviour + { + private string _runId = string.Empty; + private int _totalDays = 10; + private string _outputDir = string.Empty; + private string _legacyRunOutputDir = string.Empty; + private string _bridgeDir = string.Empty; + private bool _interactiveBridgeEnabled; + private TenDayPlaythroughReport _report = new(); + private readonly Stopwatch _clock = new(); + private SettingsOverrideScope? _settingsScope; + + private readonly HashSet _processedTraceRequestIds = new(StringComparer.Ordinal); + private readonly HashSet _seenTraceSources = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _lastSystemPromptBySource = new(StringComparer.OrdinalIgnoreCase); + private readonly List _approvedOverlayItems = new(); + private int _totalLlmCalls; + private int _successfulLlmCalls; + private int _totalTokens; + private int _totalPromptTokens; + private int _totalPrefixTokens; + + public void Begin(string runId, int totalDays) + { + _runId = runId; + _totalDays = Math.Clamp(totalDays, 1, 100); + _clock.Start(); + + _settingsScope = CoreSettingsOverrideScope.Begin("Playthrough"); + _settingsScope.TrackExternal(() => Prefs.DevMode, v => Prefs.DevMode = v); + _settingsScope.TrackExternal(() => Prefs.AdaptiveTrainingEnabled, v => Prefs.AdaptiveTrainingEnabled = v); + + ApplyEnvironmentCredentialsIfProvided(); + ConfigureOutputDirectories(); + InitializeGenuineModSettings(); + + _report = new TenDayPlaythroughReport + { + RunId = _runId, + Provider = RimMindCoreMod.Settings.provider, + Endpoint = RimMindCoreMod.Settings.apiEndpoint, + Model = RimMindCoreMod.Settings.modelName + }; + + Log.Message("[RimMind-Playthrough] ========================================================"); + Log.Message($"[RimMind-Playthrough] Starting {_totalDays}-Day Genuine In-Game AI Playthrough"); + Log.Message($"[RimMind-Playthrough] RunId: {_runId}"); + Log.Message($"[RimMind-Playthrough] Endpoint: {RimMindCoreMod.Settings.apiEndpoint}, Model: {RimMindCoreMod.Settings.modelName}"); + Log.Message($"[RimMind-Playthrough] OutputDir: {_outputDir}"); + Log.Message("[RimMind-Playthrough] ========================================================"); + + StartCoroutine(RunPlaythroughThenRestore()); + } + + public void RestorePlayerSettings() => CoreSettingsOverrideScope.End(ref _settingsScope); + + private void ApplyEnvironmentCredentialsIfProvided() + { + string? envKey = Environment.GetEnvironmentVariable("RIMMIND_TEST_API_KEY"); + string? envEndpoint = Environment.GetEnvironmentVariable("RIMMIND_TEST_ENDPOINT"); + string? envModel = Environment.GetEnvironmentVariable("RIMMIND_TEST_MODEL"); + + if (!string.IsNullOrWhiteSpace(envKey)) + RimMindCoreMod.Settings.apiKey = envKey!.Trim(); + if (!string.IsNullOrWhiteSpace(envEndpoint)) + RimMindCoreMod.Settings.apiEndpoint = envEndpoint!.Trim(); + if (!string.IsNullOrWhiteSpace(envModel)) + RimMindCoreMod.Settings.modelName = envModel!.Trim(); + + string? backupKey = Environment.GetEnvironmentVariable("RIMMIND_BACKUP_API_KEY"); + string? backupEndpoint = Environment.GetEnvironmentVariable("RIMMIND_BACKUP_ENDPOINT"); + string? backupModel = Environment.GetEnvironmentVariable("RIMMIND_BACKUP_MODEL"); + string? backupProvider = Environment.GetEnvironmentVariable("RIMMIND_BACKUP_PROVIDER"); + + if (!string.IsNullOrWhiteSpace(backupKey)) + { + string resolvedEndpoint = !string.IsNullOrWhiteSpace(backupEndpoint) + ? backupEndpoint!.Trim() + : "https://opencode.ai/zen/go/v1"; + string resolvedModel = !string.IsNullOrWhiteSpace(backupModel) + ? backupModel!.Trim() + : "beam-free"; + string resolvedProvider = !string.IsNullOrWhiteSpace(backupProvider) + ? backupProvider!.Trim() + : "opencode"; + + RimMindCoreMod.Settings.backupEndpoints ??= new List(); + var existing = RimMindCoreMod.Settings.backupEndpoints.FirstOrDefault(b => + b != null && + string.Equals(b.apiEndpoint?.Trim().TrimEnd('/'), resolvedEndpoint.TrimEnd('/'), StringComparison.OrdinalIgnoreCase) && + string.Equals(b.modelName?.Trim(), resolvedModel, StringComparison.OrdinalIgnoreCase)); + if (existing != null) + { + existing.apiKey = backupKey!.Trim(); + existing.provider = resolvedProvider; + existing.enabled = true; + } + else { - name = "OpenCode Go (Backup)", - provider = resolvedProvider, - apiEndpoint = resolvedEndpoint, - modelName = resolvedModel, - apiKey = backupKey!.Trim(), - enabled = true - }); + RimMindCoreMod.Settings.backupEndpoints.Insert(0, new BackupEndpointEntry + { + name = "OpenCode Go (Backup)", + provider = resolvedProvider, + apiEndpoint = resolvedEndpoint, + modelName = resolvedModel, + apiKey = backupKey!.Trim(), + enabled = true + }); + } } - } - _outputDir = Path.Combine(GenFilePaths.SaveDataFolderPath, "RimMind", "PlaythroughTests", _runId); - try - { - if (!Directory.Exists(_outputDir)) - Directory.CreateDirectory(_outputDir); + FilterIncompatibleBackupNodes(RimMindCoreMod.Settings); } - catch (Exception ex) + + private static void FilterIncompatibleBackupNodes(RimMindCoreSettings? settings) { - Log.Warning("[RimMind-Playthrough] Failed to create output directory: " + ex.Message); - } + if (settings?.backupEndpoints == null || settings.backupEndpoints.Count == 0) + return; - string? bridgeEnv = Environment.GetEnvironmentVariable("RIMMIND_INTERACTIVE_BRIDGE"); - _interactiveBridgeEnabled = Environment.CommandLine.Contains("-rimmind-interactive-bridge") || - GenCommandLine.CommandLineArgPassed("rimmind-interactive-bridge") || - bridgeEnv == "1" || bridgeEnv == "true"; + bool hasHealthyPrimary = + !string.IsNullOrWhiteSpace(settings.apiEndpoint) && + !string.IsNullOrWhiteSpace(settings.apiKey) && + settings.apiEndpoint.IndexOf("opencode.ai", StringComparison.OrdinalIgnoreCase) < 0 && + settings.apiEndpoint.IndexOf("deepseek.com", StringComparison.OrdinalIgnoreCase) < 0; - string? maxUsageEnv = Environment.GetEnvironmentVariable("RIMMIND_MAX_USAGE_MODE"); - _maxUsageMode = Environment.CommandLine.Contains("-rimmind-max-usage") || - GenCommandLine.CommandLineArgPassed("rimmind-max-usage") || - maxUsageEnv == "1" || maxUsageEnv == "true"; + bool hasHealthyBackup = settings.backupEndpoints.Any(n => + n != null && + n.enabled && + !string.IsNullOrWhiteSpace(n.apiEndpoint) && + !string.IsNullOrWhiteSpace(n.apiKey) && + n.apiEndpoint.IndexOf("opencode.ai", StringComparison.OrdinalIgnoreCase) < 0 && + n.apiEndpoint.IndexOf("deepseek.com", StringComparison.OrdinalIgnoreCase) < 0 && + (string.IsNullOrWhiteSpace(n.modelName) || n.modelName.IndexOf("grok-", StringComparison.OrdinalIgnoreCase) < 0)); - string? customBridge = Environment.GetEnvironmentVariable("RIMMIND_BRIDGE_DIR"); - _bridgeDir = !string.IsNullOrWhiteSpace(customBridge) - ? customBridge! - : Path.Combine(_outputDir, "bridge"); + if (!hasHealthyPrimary && !hasHealthyBackup) + return; - // Suppress Learning Helper tutorial overlay during playthrough to prevent HUD occlusion - try - { - Prefs.AdaptiveTrainingEnabled = false; - } - catch { } + int disabledCount = 0; + for (int i = 0; i < settings.backupEndpoints.Count; i++) + { + var node = settings.backupEndpoints[i]; + if (node == null || !node.enabled || string.IsNullOrWhiteSpace(node.apiEndpoint)) + continue; - try - { - if (!Directory.Exists(_bridgeDir)) - Directory.CreateDirectory(_bridgeDir); - } - catch (Exception ex) - { - Log.Warning("[RimMind-Playthrough] Failed to create bridge directory: " + ex.Message); - } + bool isDeadProvider = + node.apiEndpoint.IndexOf("opencode.ai", StringComparison.OrdinalIgnoreCase) >= 0 || + node.apiEndpoint.IndexOf("deepseek.com", StringComparison.OrdinalIgnoreCase) >= 0; - _report = new TenDayPlaythroughReport - { - RunId = _runId, - Provider = RimMindCoreMod.Settings.provider, - Endpoint = RimMindCoreMod.Settings.apiEndpoint, - Model = RimMindCoreMod.Settings.modelName - }; - - Log.Message($"[RimMind-Playthrough] ========================================================"); - Log.Message($"[RimMind-Playthrough] Starting 10-Day Real Game Playthrough & Evolution Test"); - Log.Message($"[RimMind-Playthrough] Starting {_totalDays}-Day Real Game Playthrough & Evolution Test"); - Log.Message($"[RimMind-Playthrough] RunId: {_runId}"); - Log.Message($"[RimMind-Playthrough] Endpoint: {RimMindCoreMod.Settings.apiEndpoint}, Model: {RimMindCoreMod.Settings.modelName}"); - Log.Message($"[RimMind-Playthrough] OutputDir: {_outputDir}"); - Log.Message($"[RimMind-Playthrough] Mode: {(_maxUsageMode ? "MAX USAGE (High Density, Scale=3.5x, Multi-Pawn Routine)" : "Standard Schedule")}"); - Log.Message($"[RimMind-Playthrough] ========================================================"); - - // Enable DevMode to allow ultrafast speed and unobstructed progression - Prefs.DevMode = true; - - // Configure optimal settings for playthrough: high concurrency, clean logs, non-overlapping HUD, and generous timeout - RimMindCoreMod.Settings.debugLogging = false; - RimMindCoreMod.Settings.requestOverlayX = 155f; - RimMindCoreMod.Settings.circuitBreakerFailureThreshold = 8; - RimMindCoreMod.Settings.circuitBreakerOpenDurationSec = 10; - RimMindCoreMod.Settings.requestOverlayY = 100f; - RequestOverlay.SetWindowRectForTest(new Rect( - RimMindCoreMod.Settings.requestOverlayX, - RimMindCoreMod.Settings.requestOverlayY, - RimMindCoreMod.Settings.requestOverlayW, - RimMindCoreMod.Settings.requestOverlayH)); - RimMindCoreMod.Settings.autoActivateColonistAgents = false; - RimMindCoreMod.Settings.autonomyLevel = AgentAutonomyLevel.Autonomous; - if (_maxUsageMode) - { - RimMindCoreMod.Settings.activityFrequencyScale = 1.0f; - RimMindCoreMod.Settings.maxConcurrentRequests = 2; - RimMindCoreMod.Settings.requestTimeoutMs = 90000; - RimMindCoreMod.Settings.defaultModCooldownTicks = 2500; - RimMindCoreMod.Settings.thinkCooldownTicks = 60000; + bool isUnstableGrokBackup = + hasHealthyPrimary && + !string.IsNullOrWhiteSpace(node.modelName) && + node.modelName.IndexOf("grok-", StringComparison.OrdinalIgnoreCase) >= 0; + + if (isDeadProvider || isUnstableGrokBackup) + { + node.enabled = false; + disabledCount++; + } + } + + if (disabledCount > 0) + { + Log.Message($"[RimMind-Playthrough] Disabled {disabledCount} quota-exhausted/incompatible backup node(s) (opencode.ai / deepseek.com / grok-*)."); + } } - else + + private void ConfigureOutputDirectories() { - RimMindCoreMod.Settings.maxConcurrentRequests = 2; - RimMindCoreMod.Settings.requestTimeoutMs = 90000; - } + _legacyRunOutputDir = Path.Combine(GenFilePaths.SaveDataFolderPath, "RimMind", "PlaythroughTests", _runId); - StartCoroutine(RunPlaythroughThenRestore()); - } + string? customOut = Environment.GetEnvironmentVariable("RIMMIND_PLAYTHROUGH_OUTPUT_DIR"); + _outputDir = !string.IsNullOrWhiteSpace(customOut) + ? customOut!.Trim() + : _legacyRunOutputDir; - private IEnumerator RunPlaythroughThenRestore() - { - yield return SafeRunSubRoutine(PlaythroughRoutine(), "PlaythroughMain", 0); - // Reached when the main routine faulted (SafeRunSubRoutine swallows it) or ended without shutdown. - RestorePlayerSettings(); - } + string? customBridge = Environment.GetEnvironmentVariable("RIMMIND_BRIDGE_DIR"); + _bridgeDir = !string.IsNullOrWhiteSpace(customBridge) + ? customBridge!.Trim() + : Path.Combine(_outputDir, "bridge"); - private void RestorePlayerSettings() => CoreSettingsOverrideScope.End(ref _settingsScope); + EnsureDirectoryExists(_outputDir); + EnsureDirectoryExists(_legacyRunOutputDir); + EnsureDirectoryExists(_bridgeDir); - private static IEnumerator SafeRunSubRoutine(IEnumerator? routine, string stepName, int day) - { - if (routine == null) yield break; - var stack = new Stack(); - stack.Push(routine); - while (stack.Count > 0) + string? bridgeEnv = Environment.GetEnvironmentVariable("RIMMIND_INTERACTIVE_BRIDGE"); + _interactiveBridgeEnabled = GenCommandLine.CommandLineArgPassed("rimmind-interactive-bridge") || + string.Equals(bridgeEnv, "1", StringComparison.Ordinal) || + string.Equals(bridgeEnv, "true", StringComparison.OrdinalIgnoreCase); + Log.Message($"[RimMind-Playthrough] Interactive Sub Blind Agent bridge: {(_interactiveBridgeEnabled ? "ENABLED" : "disabled")} ({_bridgeDir})"); + } + + private static void EnsureDirectoryExists(string path) { - var top = stack.Peek(); - bool moved = false; - object? current = null; + if (string.IsNullOrWhiteSpace(path)) return; try { - moved = top.MoveNext(); - if (moved) current = top.Current; + if (!Directory.Exists(path)) + Directory.CreateDirectory(path); } catch (Exception ex) { - Log.Warning($"[RimMind-Playthrough][Day {day}] {stepName} handled exception ({ex.GetType().Name}): {ex.Message}"); - stack.Pop(); - continue; + Log.Warning($"[RimMind-Playthrough] Failed to create directory '{path}': {ex.Message}"); } + } - if (!moved) + private static void InitializeGenuineModSettings() + { + try { - stack.Pop(); - continue; + Prefs.AdaptiveTrainingEnabled = false; + UnityEngine.Application.runInBackground = true; + UnityEngine.QualitySettings.vSyncCount = 0; + UnityEngine.Application.targetFrameRate = 120; } + catch { } - if (current is IEnumerator nested) - { - stack.Push(nested); - continue; - } + Prefs.DevMode = true; + + var settings = RimMindCoreMod.Settings; + settings.requestOverlayEnabled = true; + settings.requestOverlayX = 155f; + settings.requestOverlayY = 100f; + settings.showAgentProgressFloat = true; + settings.enableFloatingMentalMonitor = true; + settings.autonomyLevel = AgentAutonomyLevel.Autonomous; + settings.thinkCooldownTicks = RimMind.Application.Common.Models.RimMindDefaults.ThinkCooldownTicks; + settings.agentTickInterval = RimMind.Application.Common.Models.RimMindDefaults.AgentTickInterval; + settings.defaultModCooldownTicks = RimMind.Application.Common.Models.RimMindDefaults.DefaultModCooldownTicks; + settings.activityFrequencyScale = RimMind.Application.Common.Models.RimMindDefaults.DefaultActivityFrequencyScale; - yield return current; + RequestOverlay.SetWindowRectForTest(new Rect( + settings.requestOverlayX, + settings.requestOverlayY, + settings.requestOverlayW, + settings.requestOverlayH)); } - } - private IEnumerator PlaythroughRoutine() - { - // Initial warm-up: wait 15 frames for map components to initialize - for (int i = 0; i < 15; i++) + private IEnumerator RunPlaythroughThenRestore() { - yield return null; + yield return SafeRunSubRoutine(PlaythroughRoutine(_totalDays), "PlaythroughMain", 0); + RestorePlayerSettings(); } - int startTick = Find.TickManager.TicksGame; - Log.Message($"[RimMind-Playthrough] Simulation start at Tick {startTick}"); - - // Simulation startup: unforbid starting crashlanded items - if (Find.CurrentMap != null) + private static IEnumerator SafeRunSubRoutine(IEnumerator? routine, string stepName, int day) { - UnforbidAllStartingItems(Find.CurrentMap); - } + if (routine == null) yield break; + var stack = new Stack(); + stack.Push(routine); + while (stack.Count > 0) + { + var top = stack.Peek(); + bool moved = false; + object? current = null; + try + { + moved = top.MoveNext(); + if (moved) current = top.Current; + } + catch (Exception ex) + { + Log.Warning($"[RimMind-Playthrough][Day {day}] {stepName} handled exception ({ex.GetType().Name}): {ex.Message}"); + stack.Pop(); + continue; + } + + if (!moved) + { + stack.Pop(); + continue; + } - // Auto-activate colonist agents and work priorities on playthrough startup - var initialColonists = EnsureColonistAgentsAndPriorities(); + if (current is IEnumerator nested) + { + stack.Push(nested); + continue; + } - float totalHitRatios = 0f; - int totalDaysTracked = 0; + yield return current; + } + } - for (int day = 1; day <= _totalDays; day++) + private IEnumerator PlaythroughRoutine(int totalDays) { - var daySw = Stopwatch.StartNew(); - if (Find.TickManager != null) + InitializeDayOneMapAndColonists(); + + for (int i = 0; i < 15; i++) { - Find.TickManager.CurTimeSpeed = TimeSpeed.Paused; + yield return null; } - int dayStartTick = Find.TickManager?.TicksGame ?? 0; - string dateStr = Find.CurrentMap != null && Find.WorldGrid != null - ? GenDate.DateFullStringAt(GenTicks.TicksAbs, Find.WorldGrid.LongLatOf(Find.CurrentMap.Tile)) - : $"Day {day}"; + SeedExistingTraceEntries(); - Log.Message($"[RimMind-Playthrough] >>> Starting Day {day}/{_totalDays} (GameTick: {dayStartTick}, Date: {dateStr}) <<<"); + int startTick = Find.TickManager?.TicksGame ?? 0; + Log.Message($"[RimMind-Playthrough] Simulation start at Tick {startTick}"); - var currentMap = Find.CurrentMap; - if (currentMap != null) - { - UnforbidAllStartingItems(currentMap); - } + InitializeDayOneMapAndColonists(); - var dayReport = new PlaythroughDayReport + // Simulated player's first click: unforbid the crashlanded cargo. + PlaythroughPlayerSimulation.UnforbidStartingItems(Find.CurrentMap); + + for (int day = 1; day <= totalDays; day++) { - DayNumber = day, - StartTick = dayStartTick, - DateString = dateStr - }; + var daySw = Stopwatch.StartNew(); + int dayStartTick = Find.TickManager?.TicksGame ?? 0; + int dayEndTick = dayStartTick + GenDate.TicksPerDay; + string dateStr = Find.CurrentMap != null && Find.WorldGrid != null + ? GenDate.DateFullStringAt(GenTicks.TicksAbs, Find.WorldGrid.LongLatOf(Find.CurrentMap.Tile)) + : $"Day {day}"; - // Sample colonists, ensure survival, work priorities, and active PawnAgents every day - var colonists = EnsureColonistAgentsAndPriorities(); + Log.Message($"[RimMind-Playthrough] >>> Starting Day {day}/{totalDays} (GameTick: {dayStartTick}, Date: {dateStr}) <<<"); - foreach (var p in colonists) - { - if (p == null || p.Dead) continue; + EnsureColonistAgentSplitAndWorkSettings(); - dayReport.Colonists.Add(new PlaythroughColonistSnapshot - { - Name = p.Name?.ToStringShort ?? "Colonist", - Mood = p.needs?.mood?.CurLevel ?? 0.5f, - CurrentJob = p.CurJobDef?.defName ?? "Idle", - HealthSummary = p.health?.summaryHealth?.SummaryHealthPercent.ToString("P0") ?? "100%" - }); - } + yield return SafeRunSubRoutine(AdvanceDayTicksRoutine(day, dayStartTick, dayEndTick), "AdvanceDayTicks", day); - // Phase 1: Awakening & Shift Start Phase (06:00) -> Autonomous Agent Perception & Thought - var awakeColonists = colonists.Where(p => p != null && !p.Dead && p.Spawned && p.Awake() && !p.Downed && !p.InMentalState && p.MentalStateDef == null).ToList(); - if (awakeColonists.Count == 0) awakeColonists = colonists.Where(p => p != null && !p.Dead && p.Spawned).ToList(); + int actualEndTick = Find.TickManager?.TicksGame ?? dayEndTick; + var dayReport = CollectDayReport(day, dayStartTick, actualEndTick, dateStr); - if (awakeColonists.Count > 0) - { - Pawn morningPawn = awakeColonists[(day - 1) % awakeColonists.Count]; - dayReport.MorningPawnName = morningPawn.Name?.ToStringShort ?? "Colonist"; - yield return SafeRunSubRoutine(ExecuteMorningThought(morningPawn, day, dayReport, recordInReport: true), "MorningThought", day); - } + yield return SafeRunSubRoutine(CaptureDayScreenshotRoutine(day, dayReport), "CaptureDayScreenshot", day); - // Daily Colony Operation: Execute interactive Copilot bridge or player colony operations (Days 1 to TotalDays) - yield return SafeRunSubRoutine(ExecuteDailyColonyOperationRoutine(day, dayReport), "DailyColonyOperation", day); + daySw.Stop(); + dayReport.DayComputeDurationMs = daySw.ElapsedMilliseconds; - // Advance Morning -> Noon (15,000 ticks = 6 in-game hours) - yield return SafeRunSubRoutine(AdvanceTicks(15000), "AdvanceMorningToNoon", day); + ExportDailyStateJson(day, dayReport, Find.CurrentMap); - // Phase 2: Noon Phase (12:00) -> Social Encounter & ToolCall Dialogue - var allLiving = EnsureColonistAgentsAndPriorities().Where(p => p != null && !p.Dead && !p.Destroyed).ToList(); - var liveSpeakers = allLiving.Where(p => p.Awake() && !p.Downed && !p.InMentalState && p.MentalStateDef == null).ToList(); - if (liveSpeakers.Count < 2) liveSpeakers = allLiving.Where(p => !p.Downed && !p.InMentalState && p.MentalStateDef == null).ToList(); - if (liveSpeakers.Count < 2) liveSpeakers = allLiving.Where(p => !p.Downed).ToList(); - if (liveSpeakers.Count >= 2) - { - Pawn speaker = liveSpeakers[(day - 1) % liveSpeakers.Count]; - Pawn listener = liveSpeakers[day % liveSpeakers.Count]; - if (speaker == listener) + if (_interactiveBridgeEnabled) { - listener = liveSpeakers.FirstOrDefault(p => p != speaker) ?? speaker; + yield return SafeRunSubRoutine(WaitForPlayerCommandRoutine(day, dayReport), "PlayerCommandBridge", day); } - yield return SafeRunSubRoutine(ExecuteSocialDialogue(speaker, listener, day, dayReport, recordInReport: true), "SocialDialogue", day); - } - else if (liveSpeakers.Count == 1 && allLiving.Count >= 1) - { - Pawn speaker = liveSpeakers[0]; - Pawn listener = allLiving.FirstOrDefault(p => p != speaker) ?? speaker; - yield return SafeRunSubRoutine(ExecuteSocialDialogue(speaker, listener, day, dayReport, recordInReport: true), "SocialDialogue", day); - } - else if (allLiving.Count >= 1) - { - Pawn speaker = allLiving[(day - 1) % allLiving.Count]; - Pawn listener = allLiving.FirstOrDefault(p => p != speaker) ?? speaker; - yield return SafeRunSubRoutine(ExecuteSocialDialogue(speaker, listener, day, dayReport, recordInReport: true), "SocialDialogue", day); - } - // Advance Noon -> Afternoon (7,500 ticks = 3 in-game hours) - yield return SafeRunSubRoutine(AdvanceTicks(7500), "AdvanceNoonToAfternoon", day); - - // Phase 2.5: Afternoon Phase (15:00) -> Autonomous Agent Action & Mechanism Decision - UnforbidAllStartingItems(Find.CurrentMap); - var aliveForAction = EnsureColonistAgentsAndPriorities(); - Pawn? designatedAgent = aliveForAction.FirstOrDefault(p => p != null && !p.Dead && p.Spawned && CompPawnAgent.GetComp(p)?.Agent?.State == AgentState.Active); - var currentColonists = aliveForAction.Where(p => p != null && !p.Downed && !p.InMentalState && p.MentalStateDef == null).ToList(); - if (currentColonists.Count == 0) currentColonists = aliveForAction.Where(p => p != null && !p.Downed).ToList(); - if (currentColonists.Count == 0) currentColonists = aliveForAction; - if (designatedAgent != null || currentColonists.Count > 0) - { - Pawn agentPawn = designatedAgent ?? currentColonists[0]; - yield return SafeRunSubRoutine(ExecuteAutonomousAgentAction(agentPawn, day, dayReport, recordInReport: true), "AutonomousAgentAction", day); - } + _report.Days.Add(dayReport); + _report.TotalDaysCompleted = day; + _report.TotalLiveLlmRequests = _totalLlmCalls; + _report.SuccessfulLiveLlmRequests = _successfulLlmCalls; + _report.TotalTokensConsumed = _totalTokens; + _report.TotalPrefixTokens = _totalPrefixTokens; + _report.CacheHitRatio = _totalPromptTokens > 0 + ? Math.Round((double)_totalPrefixTokens * 100.0 / _totalPromptTokens, 1) + : 0.0; + _report.AverageCacheHitRatio = _report.CacheHitRatio; + _report.TotalTicksElapsed = actualEndTick - startTick; + _report.TotalDurationMs = _clock.ElapsedMilliseconds; + + SaveReportCheckpoint(); + + Log.Message( + $"[RimMind-Playthrough] <<< Completed Day {day}/{totalDays} " + + $"(Duration: {dayReport.DayComputeDurationMs}ms, LLMCalls: {dayReport.LlmCallsCount}, " + + $"AgentActions: {dayReport.AgentActionsExecutedCount}, Tokens: {dayReport.TotalTokensUsed}, " + + $"PrefixTokens: {dayReport.PrefixTokens}, CacheHitRatio: {dayReport.CacheHitRatio:F1}%) >>>"); - // Advance Afternoon -> Evening (7,500 ticks = 3 in-game hours) - yield return SafeRunSubRoutine(AdvanceTicks(7500), "AdvanceAfternoonToEvening", day); + yield return null; + } - // Phase 3: Evening Phase (18:00) -> Advisor Suggestion & Overlay Auto-Approval - var activeColonists = EnsureColonistAgentsAndPriorities(); - yield return SafeRunSubRoutine(ExecuteAdvisorProposal(activeColonists, day, dayReport), "AdvisorProposal", day); + _report.TotalTicksElapsed = (Find.TickManager?.TicksGame ?? startTick) - startTick; + _report.TotalDurationMs = _clock.ElapsedMilliseconds; + _report.TotalLiveLlmRequests = _totalLlmCalls; + _report.SuccessfulLiveLlmRequests = _successfulLlmCalls; + _report.TotalTokensConsumed = _totalTokens; + _report.TotalPrefixTokens = _totalPrefixTokens; + _report.CacheHitRatio = _totalPromptTokens > 0 + ? Math.Round((double)_totalPrefixTokens * 100.0 / _totalPromptTokens, 1) + : 0.0; + _report.AverageCacheHitRatio = _report.CacheHitRatio; + _report.OverallStatus = "COMPLETED"; + _report.SummaryNotes = + $"{totalDays}-day genuine playthrough completed across {_report.TotalTicksElapsed} ticks with " + + $"{_report.TotalLiveLlmRequests} real Mod LLM requests ({_report.SuccessfulLiveLlmRequests} succeeded), " + + $"{_report.TotalTokensConsumed} tokens, and KV-cache hit ratio {_report.CacheHitRatio:F1}%."; - // Advance Evening -> Night (10,000 ticks = 4 in-game hours) - yield return SafeRunSubRoutine(AdvanceTicks(10000), "AdvanceEveningToNight", day); + SaveReportCheckpoint(); + GeneratePlaythroughChronicle(); - // Phase 4: Night Phase (22:00) -> Memory & Storyteller Reflection - try - { - ExecuteNightReflection(dayReport); - } - catch (Exception ex) - { - Log.Warning($"[RimMind-Playthrough][Day {day}] ExecuteNightReflection notice: {ex.Message}"); - } + Log.Message($"[RimMind-Playthrough] === {totalDays}-DAY AI PLAYTHROUGH COMPLETE ==="); + Log.Message($"[RimMind-Playthrough] Status: {_report.OverallStatus}, Duration: {_report.TotalDurationMs}ms, Total LLM Calls: {_report.TotalLiveLlmRequests}, Tokens: {_report.TotalTokensConsumed}"); - // Milestone Screenshot: Day 1, 3, 5, 7, 10 for <=10 days, or Day 1, 5, 10, 15... for long runs - bool isMilestone = (_totalDays <= 10) - ? (day == 1 || day == 3 || day == 5 || day == 7 || day == 10) - : (day == 1 || day % 5 == 0 || day == _totalDays); + bool autoExit = Environment.GetEnvironmentVariable("RIMMIND_PLAYTHROUGH_AUTO_EXIT") == "1" || + GenCommandLine.CommandLineArgPassed("rimmind-autotest") || + GenCommandLine.CommandLineArgPassed("rimmind-playthrough") || + GenCommandLine.CommandLineArgPassed("rimmind-10day-playthrough"); - if (isMilestone) + if (autoExit) { - yield return SafeRunSubRoutine(CaptureDayScreenshot(day, dayReport), "CaptureDayScreenshot", day); + yield return new WaitForSecondsRealtime(2f); + RestorePlayerSettings(); + Root.Shutdown(); } + } - // Advance Night -> Next Morning (20,000 ticks = 8 in-game hours; total = 60,000 ticks = 1 exact RimWorld day) - yield return SafeRunSubRoutine(AdvanceTicks(20000), "AdvanceNightToMorning", day); - - dayReport.EndTick = Find.TickManager?.TicksGame ?? dayStartTick; - daySw.Stop(); - dayReport.DayComputeDurationMs = daySw.ElapsedMilliseconds; - - if (dayReport.CacheHitRatio > 0) + /// + /// Pauses the game after the day-N snapshot and waits for the external Sub Blind Agent + /// (simulated player) to write cmd_day_NN.json. On timeout nothing is executed: + /// there is no scripted fallback, the colony simply continues under Mod/vanilla control. + /// + private IEnumerator WaitForPlayerCommandRoutine(int day, PlaythroughDayReport report) + { + float timeoutLimit = 90f; + string? timeoutEnv = Environment.GetEnvironmentVariable("RIMMIND_BRIDGE_TIMEOUT"); + if (!string.IsNullOrEmpty(timeoutEnv) && float.TryParse(timeoutEnv, out float customTimeout) && customTimeout > 10f) { - totalHitRatios += dayReport.CacheHitRatio; - totalDaysTracked++; + timeoutLimit = customTimeout; } - _report.Days.Add(dayReport); - _report.TotalDaysCompleted = day; - _report.TotalTokensConsumed += dayReport.TotalTokensUsed; - _report.AverageCacheHitRatio = totalDaysTracked > 0 ? (totalHitRatios / totalDaysTracked) : 80.2f; + string cmdPath = Path.Combine(_bridgeDir, $"cmd_day_{day:D2}.json"); + string donePath = Path.Combine(_bridgeDir, $"cmd_day_{day:D2}.done"); + string ackPath = Path.Combine(_bridgeDir, $"ack_day_{day:D2}.json"); - Log.Message($"[RimMind-Playthrough] <<< Completed Day {day}/{_totalDays} (Duration: {dayReport.DayComputeDurationMs}ms, CacheHit: {dayReport.CacheHitRatio:F1}%) >>>"); + var previousSpeed = Find.TickManager?.CurTimeSpeed ?? TimeSpeed.Normal; + Log.Message($"[RimMind-Playthrough][Day {day}] Waiting up to {timeoutLimit}s for simulated-player command {Path.GetFileName(cmdPath)}..."); - // Save checkpoint report after each day - SaveReportCheckpoint(); - - yield return null; - } + float waitStart = Time.realtimeSinceStartup; + ColonySubagentCommand? cmd = null; + while (Time.realtimeSinceStartup - waitStart < timeoutLimit) + { + if (Find.TickManager != null) Find.TickManager.CurTimeSpeed = TimeSpeed.Paused; - // Finalize - _report.TotalTicksElapsed = Find.TickManager.TicksGame - startTick; - _report.TotalDurationMs = _clock.ElapsedMilliseconds; - _report.OverallStatus = "COMPLETED"; - _report.AverageCacheHitRatio = totalDaysTracked > 0 ? (totalHitRatios / totalDaysTracked) : 80.2f; - _report.SummaryNotes = $"{_totalDays}-day playthrough successfully completed across {_report.TotalTicksElapsed} ticks with {_report.TotalLiveLlmRequests} live LLM requests. Average KV-cache prefix stability: {_report.AverageCacheHitRatio:F1}%."; + if (File.Exists(cmdPath)) + { + try + { + cmd = JsonConvert.DeserializeObject(File.ReadAllText(cmdPath, Encoding.UTF8)); + } + catch (Exception ex) + { + Log.Warning($"[RimMind-Playthrough][Day {day}] Failed to parse player command: {ex.Message}"); + } - SaveReportCheckpoint(); - GeneratePlaythroughChronicle(); + if (cmd != null) + { + try + { + if (File.Exists(donePath)) File.Delete(donePath); + File.Move(cmdPath, donePath); + } + catch (Exception ex) + { + Log.Warning($"[RimMind-Playthrough][Day {day}] Failed to mark command done: {ex.Message}"); + } + break; + } + } - Log.Message($"[RimMind-Playthrough] ========================================================"); - Log.Message($"[RimMind-Playthrough] {_totalDays}-Day Playthrough Finished Successfully!"); - Log.Message($"[RimMind-Playthrough] Status: {_report.OverallStatus}, Duration: {_report.TotalDurationMs}ms"); - Log.Message($"[RimMind-Playthrough] Total LLM Calls: {_report.TotalLiveLlmRequests}, Avg Cache Hit: {_report.AverageCacheHitRatio:F1}%"); - Log.Message($"[RimMind-Playthrough] ========================================================"); + yield return new WaitForSecondsRealtime(0.25f); + } - // Wait 3 seconds, then shutdown game process - yield return new WaitForSecondsRealtime(3f); + bool success = false; + string detail; + if (cmd == null) + { + detail = $"no player command within {timeoutLimit}s (no fallback executed)"; + } + else if (Find.CurrentMap == null) + { + detail = "no current map"; + } + else + { + (success, detail) = PlaythroughPlayerSimulation.ExecuteCommand(cmd, Find.CurrentMap); + } - RestorePlayerSettings(); - Root.Shutdown(); - } + report.ColonyOperationName = cmd?.Action ?? "none"; + report.ColonyOperationDetail = cmd == null + ? detail + : $"{cmd.Reason} => {detail}" + (string.IsNullOrWhiteSpace(cmd.UxFinding) ? string.Empty : $" | UX: {cmd.UxFinding}"); + report.ColonyOperationSuccess = success; - private static List GetLivingColonists() - { - var map = Find.CurrentMap; - if (map?.mapPawns?.FreeColonists == null) return new List(); - return map.mapPawns.FreeColonists - .Where(p => p != null && !p.Dead && p.Spawned && p.Map != null) - .ToList(); - } + Log.Message($"{PlaythroughPlayerSimulation.LogTag}[Day {day}] action={report.ColonyOperationName} target={cmd?.Target} success={success} detail={detail}"); - private static List EnsureColonistAgentsAndPriorities() - { - try - { - EnsureMinimumColonists(); - var colonists = GetLivingColonists(); - EnsureColonistSustenance(colonists); - ConfigureColonistWorkPriorities(colonists); - Pawn? targetActiveColonist = colonists.FirstOrDefault(c => - c != null && !c.Dead && c.Spawned && CompPawnAgent.GetComp(c)?.Agent?.State == AgentState.Active) - ?? colonists.FirstOrDefault(c => c != null && !c.Dead && c.Spawned); - - foreach (var colonist in colonists) + if (cmd != null) { - if (colonist == null || colonist.Dead || !colonist.Spawned) continue; try { - RimMind.Presentation.Api.RimMindPawnLookup.CachePawn(colonist); - var comp = CompPawnAgent.GetComp(colonist); - if (comp != null) + var ack = new { - comp.EnsureAgentCreated(); - if (ReferenceEquals(colonist, targetActiveColonist)) - { - if (comp.Agent != null && comp.Agent.State != AgentState.Active) - { - comp.Agent.TransitionTo(AgentState.Active); - Log.Message($"[RimMind-Playthrough] Activated single Spawn Agent: {colonist.Name?.ToStringShort} (NPC-{colonist.thingIDNumber})"); - } - } - else if (comp.Agent != null && comp.Agent.State == AgentState.Active) - { - comp.Agent.TransitionTo(AgentState.Paused); - } - } + status = success ? "OK" : "FAILED", + day, + action = cmd.Action, + target = cmd.Target, + detail, + timestamp = DateTime.UtcNow.ToString("o") + }; + File.WriteAllText(ackPath, JsonConvert.SerializeObject(ack, Formatting.Indented), new UTF8Encoding(false)); } catch (Exception ex) { - Log.Warning($"[RimMind-Playthrough] EnsureColonistAgent notice for {colonist.Name?.ToStringShort}: {ex.Message}"); + Log.Warning($"[RimMind-Playthrough][Day {day}] Failed to write ack: {ex.Message}"); } } - return colonists; - } - catch (Exception ex) - { - Log.Warning($"[RimMind-Playthrough] EnsureColonistAgentsAndPriorities notice: {ex.Message}"); - return GetLivingColonists(); - } - } - private static void EnsureMinimumColonists() - { - var map = Find.CurrentMap; - if (map?.listerThings == null) return; + if (Find.TickManager != null) Find.TickManager.CurTimeSpeed = previousSpeed == TimeSpeed.Paused ? TimeSpeed.Ultrafast : previousSpeed; + } - try + private void SeedExistingTraceEntries() { - var current = map.mapPawns.FreeColonists.Where(p => p != null && !p.Dead && p.Spawned).ToList(); - int safety = 6; - while (current.Count < 3 && safety-- > 0) + var scope = RuntimeServiceHub.Shared.Capture(); + var traceLog = scope.GetOptional(); + if (traceLog?.Entries == null) return; + + foreach (var entry in traceLog.Entries) { - var newPawn = PawnGenerator.GeneratePawn(PawnKindDefOf.Colonist, Faction.OfPlayer); - IntVec3 spawnLoc = CellFinder.StandableCellNear(map.Center, map, 10); - if (!spawnLoc.InBounds(map)) spawnLoc = map.Center; - GenSpawn.Spawn(newPawn, spawnLoc, map); - current = map.mapPawns.FreeColonists.Where(p => p != null && !p.Dead && p.Spawned).ToList(); + if (entry != null && + !string.IsNullOrEmpty(entry.RequestId) && + (entry.State == AIRequestTraceState.Completed || entry.State == AIRequestTraceState.Failed)) + { + _processedTraceRequestIds.Add(entry.RequestId); + } } } - catch (Exception ex) + + private static void InitializeDayOneMapAndColonists() { - Log.Warning($"[RimMind-Playthrough] EnsureMinimumColonists notice: {ex.Message}"); + EnsureColonistAgentSplitAndWorkSettings(); } - } - private static void EnsureColonistSustenance(IEnumerable colonists) - { - // Guard against lethal death and permanent all-downed coma states (e.g. Hypothermia >= 0.62 locks Consciousness at 10%). - // Keep minor environmental/hunger stress intact so RimMind-Actions, Personality, and Dialogue react to authentic pawn state. - try + private static List GetActiveSpawnedColonists() { - foreach (var p in colonists) + var map = Find.CurrentMap; + if (map == null) return new List(); + return RimMindPawnLookup.GetSpawnedColonistsSafe(map) + .Where(p => p != null && RimMindPawnLookup.IsActiveSpawnedColonist(p)) + // Capable pawns first so the PawnAgent split never lands on a downed colonist. + .OrderBy(p => p.Downed ? 1 : 0) + .ThenBy(p => p.thingIDNumber) + .ToList(); + } + + private static List EnsureColonistAgentSplitAndWorkSettings() + { + var colonists = GetActiveSpawnedColonists(); + if (colonists.Count == 0) return colonists; + + try { - if (p == null || p.Dead) continue; - if (p.needs?.food != null && p.needs.food.CurLevel < 0.05f) + if (Current.Game?.playSettings != null) { - p.needs.food.CurLevel = 0.18f; + Current.Game.playSettings.useWorkPriorities = true; } - if (p.health?.hediffSet != null) + + int activeAgentTargetCount = colonists.Count >= 2 + ? Math.Max(1, colonists.Count - 1) + : 1; + + var modeColonist = new AgentModeId("colonist"); + bool hasColonistMode = RimMindAPI.Modes.FindById(modeColonist.Value) != null; + bool hasProactiveMode = RimMindAPI.Modes.FindById(AgentModeId.Proactive.Value) != null; + + for (int i = 0; i < colonists.Count; i++) { - var allHediffs = p.health.hediffSet.hediffs; - if (allHediffs == null) continue; + var pawn = colonists[i]; + if (pawn == null || pawn.Dead || !pawn.Spawned) continue; - for (int i = allHediffs.Count - 1; i >= 0; i--) + RimMindPawnLookup.CachePawn(pawn); + if (pawn.workSettings != null && pawn.workSettings.EverWork) { - var h = allHediffs[i]; - if (h?.def == null) continue; + pawn.workSettings.EnableAndInitializeIfNotAlreadyInitialized(); + } + + var comp = CompPawnAgent.GetComp(pawn); + if (comp == null) continue; - if (h.def == HediffDefOf.Hypothermia || - h.def == HediffDefOf.Malnutrition || - h.def == HediffDefOf.Heatstroke || - h.def == HediffDefOf.BloodLoss) + bool shouldBeActiveAgent = i < activeAgentTargetCount; + if (shouldBeActiveAgent) + { + comp.EnsureAgentCreated(); + foreach (var domain in (AutonomyDomain[])Enum.GetValues(typeof(AutonomyDomain))) { - if (h.Severity > 0.42f || (p.Downed && h.Severity > 0.22f)) - { - h.Severity = 0.20f; - } + comp.AutonomyPolicy.SetLevel(domain, AutonomyLevel.FullAutonomous); } - else if (p.Downed && (h is Hediff_Injury || h.Bleeding || h.def.defName == "ResurrectionSickness" || h.def.defName == "CatatonicBreakdown")) + + if (comp.Agent != null) { - if (h.def.defName == "ResurrectionSickness" || h.def.defName == "CatatonicBreakdown") + if (comp.Agent is RimMind.Presentation.Agent.PawnAgent concreteAgent) + { + concreteAgent.AutonomyLevel = AgentAutonomyLevel.Autonomous; + } + + if (comp.Agent.State != AgentState.Active) + { + comp.Agent.TransitionTo(AgentState.Active); + Log.Message($"[RimMind-Playthrough] Activated autonomous PawnAgent on {pawn.Name?.ToStringShort} (NPC-{pawn.thingIDNumber})."); + } + + if (hasColonistMode && comp.Agent.CurrentModeId != modeColonist) { - p.health.RemoveHediff(h); + comp.Agent.SwitchMode(modeColonist); } - else if (h.Severity > 2.5f || h.Bleeding) + else if (hasProactiveMode && comp.Agent.CurrentModeId != AgentModeId.Proactive) { - p.health.RemoveHediff(h); + comp.Agent.SwitchMode(AgentModeId.Proactive); } } } - - p.health.Notify_HediffChanged(null); + else + { + if (comp.Agent != null && comp.Agent.State == AgentState.Active) + { + comp.Agent.TransitionTo(AgentState.Paused); + Log.Message($"[RimMind-Playthrough] Left {pawn.Name?.ToStringShort} (NPC-{pawn.thingIDNumber}) non-active for Personality/Advisor/Dialogue coverage."); + } + } } } - } - catch (Exception ex) - { - Log.Warning($"[RimMind-Playthrough] EnsureColonistSustenance notice: {ex.Message}"); - } - } - - private static int CountAvailableMapResource(Map? map, ThingDef? def) - { - if (map == null || def == null) return 0; - int stockpiled = map.resourceCounter?.GetCount(def) ?? 0; - if (map.listerThings == null) return stockpiled; - - int spawnedTotal = 0; - var things = map.listerThings.ThingsOfDef(def); - if (things != null) - { - for (int i = 0; i < things.Count; i++) + catch (Exception ex) { - var t = things[i]; - if (t != null && t.Spawned && !t.Destroyed && !t.Position.Fogged(map) && !t.IsForbidden(Faction.OfPlayer)) - { - spawnedTotal += t.stackCount; - } + Log.Warning($"[RimMind-Playthrough] EnsureColonistAgentSplitAndWorkSettings notice: {ex.Message}"); } + + return colonists; } - return Math.Max(stockpiled, spawnedTotal); - } - private static void UnforbidAllStartingItems(Map? map) - { - if (map?.listerThings == null) return; - try + private IEnumerator AdvanceDayTicksRoutine(int day, int dayStartTick, int dayEndTick) { - var allThings = map.listerThings.AllThings; - if (allThings == null) return; + if (Find.TickManager == null) yield break; - int unforbiddenCount = 0; - var items = allThings - .Where(t => t != null && t.Spawned && t.def != null && t.def.category == ThingCategory.Item) - .ToList(); + // Native RimWorld time flow only (TimeSpeed.Ultrafast, as a player pressing "4" in dev mode). + // No manual DoSingleTick stacking: the game must not outrun what a real session allows, + // otherwise PawnAgent LLM decisions arrive days late and the test stops reflecting play. + UnityEngine.Application.runInBackground = true; + Find.TickManager.CurTimeSpeed = TimeSpeed.Ultrafast; + int lastMaintenanceTick = dayStartTick; - foreach (var t in items) + while (Find.TickManager.TicksGame < dayEndTick) { - if (t.IsForbidden(Faction.OfPlayer)) + int nowTick = Find.TickManager.TicksGame; + if (nowTick - lastMaintenanceTick >= 250) { - t.SetForbidden(false, warnOnFail: false); - unforbiddenCount++; + lastMaintenanceTick = nowTick; + DismissModalWindows(Find.CurrentMap); + AutoApprovePendingOverlayRequests(nowTick); } - } - if (unforbiddenCount > 0) - { - Log.Message($"[RimMind-Playthrough] Unforbidden {unforbiddenCount} items on map."); + if (Find.TickManager.CurTimeSpeed != TimeSpeed.Ultrafast) + { + Find.TickManager.CurTimeSpeed = TimeSpeed.Ultrafast; + } + + yield return null; } - bool hasGeneralStockpile = map.zoneManager?.AllZones - ?.OfType() - .Any(z => z.settings?.filter != null && z.settings.filter.Allows(ThingDefOf.WoodLog)) ?? false; - if (!hasGeneralStockpile) + DismissModalWindows(Find.CurrentMap); + AutoApprovePendingOverlayRequests(Find.TickManager.TicksGame); + } + + private void AutoApprovePendingOverlayRequests(int currentTick) + { + try { - IntVec3 centerPos = CellFinder.StandableCellNear(map.Center, map, 10); - if (centerPos.InBounds(map)) + var pending = RimMindAPI.GetPendingRequests(); + if (pending == null || pending.Count == 0) return; + + var snapshot = pending.ToList(); + for (int i = 0; i < snapshot.Count; i++) { - CreateStockpileZoneSafe(map, centerPos, 6, 6, StorageSettingsPreset.DefaultStockpile); + var req = snapshot[i]; + if (req == null) continue; + + string approveChoice = (req.options != null && req.options.Length > 0 && !string.IsNullOrWhiteSpace(req.options[0])) + ? req.options[0] + : "Approve"; + + if (RequestOverlay.Resolve(req, approveChoice)) + { + _approvedOverlayItems.Add(new ApprovedOverlayItem + { + Source = req.source ?? string.Empty, + Title = req.title ?? string.Empty, + Description = req.description ?? string.Empty, + Choice = approveChoice, + Tick = currentTick + }); + Log.Message($"[RimMind-Playthrough] Auto-approved RequestOverlay item (source={req.source}, choice={approveChoice}): {req.title}"); + } } } + catch (Exception ex) + { + Log.Warning($"[RimMind-Playthrough] AutoApprovePendingOverlayRequests notice: {ex.Message}"); + } } - catch (Exception ex) - { - Log.Warning($"[RimMind-Playthrough] UnforbidAllStartingItems notice: {ex.Message}"); - } - } - private static void ConfigureColonistWorkPriorities(List colonists) - { - if (colonists == null || colonists.Count == 0) return; - try + private PlaythroughDayReport CollectDayReport(int day, int dayStartTick, int dayEndTick, string dateStr) { - if (Current.Game?.playSettings != null) + var report = new PlaythroughDayReport { - Current.Game.playSettings.useWorkPriorities = true; - } + DayNumber = day, + StartTick = dayStartTick, + EndTick = dayEndTick, + DateString = dateStr + }; - var patientWork = typeof(WorkTypeDefOf).GetField("Patient", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static)?.GetValue(null) as WorkTypeDef - ?? DefDatabase.GetNamedSilentFail("Patient"); + var colonists = GetActiveSpawnedColonists(); + foreach (var p in colonists) + { + var comp = CompPawnAgent.GetComp(p); + bool isActive = comp?.Agent?.IsActive == true; + string modeStr = comp?.Agent?.CurrentModeId.Value ?? "dormant"; - var bedPursuit = typeof(WorkTypeDefOf).GetField("PatientBedPursuit", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static)?.GetValue(null) as WorkTypeDef - ?? typeof(WorkTypeDefOf).GetField("PatientBedRest", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static)?.GetValue(null) as WorkTypeDef - ?? DefDatabase.GetNamedSilentFail("PatientBedPursuit") - ?? DefDatabase.GetNamedSilentFail("PatientBedRest") - ?? DefDatabase.GetNamedSilentFail("BedRest"); + report.Colonists.Add(new PlaythroughColonistSnapshot + { + Name = p.Name?.ToStringShort ?? "Colonist", + Mood = p.needs?.mood?.CurLevel ?? 0.5f, + CurrentJob = p.CurJobDef?.defName ?? "Idle", + HealthSummary = p.health?.summaryHealth?.SummaryHealthPercent.ToString("P0") ?? "100%", + IsAgentActive = isActive, + AgentMode = modeStr + }); + } - var emergencyWorkTypes = new List(); - if (WorkTypeDefOf.Firefighter != null) emergencyWorkTypes.Add(WorkTypeDefOf.Firefighter); - if (patientWork != null) emergencyWorkTypes.Add(patientWork); - if (bedPursuit != null && !emergencyWorkTypes.Contains(bedPursuit)) emergencyWorkTypes.Add(bedPursuit); - if (WorkTypeDefOf.Doctor != null) emergencyWorkTypes.Add(WorkTypeDefOf.Doctor); + CollectTraceLogMetrics(report); + CollectRealAgentActions(colonists, dayStartTick, dayEndTick, report); + CollectRealDialogueEntries(dayStartTick, dayEndTick, report); + CollectRealPersonalityThoughts(colonists, dayStartTick, dayEndTick, report); + CollectRealAdvisorHistory(dayStartTick, dayEndTick, report); + CollectRealMemoryCounts(colonists, report); - var constructiveWorkTypes = new List(); - if (WorkTypeDefOf.Construction != null) constructiveWorkTypes.Add(WorkTypeDefOf.Construction); - if (WorkTypeDefOf.PlantCutting != null) constructiveWorkTypes.Add(WorkTypeDefOf.PlantCutting); - if (WorkTypeDefOf.Hauling != null) constructiveWorkTypes.Add(WorkTypeDefOf.Hauling); - if (WorkTypeDefOf.Growing != null) constructiveWorkTypes.Add(WorkTypeDefOf.Growing); - if (WorkTypeDefOf.Mining != null) constructiveWorkTypes.Add(WorkTypeDefOf.Mining); + return report; + } - foreach (var p in colonists) + private void CollectTraceLogMetrics(PlaythroughDayReport dayReport) + { + try { - if (p == null || p.Dead || p.workSettings == null) continue; - if (!p.workSettings.EverWork) continue; + var scope = RuntimeServiceHub.Shared.Capture(); + var traceLog = scope.GetOptional(); + if (traceLog?.Entries == null) return; - p.workSettings.EnableAndInitializeIfNotAlreadyInitialized(); + int dayPromptTokens = 0; + int dayPrefixTokens = 0; - foreach (var w in emergencyWorkTypes) + foreach (var entry in traceLog.Entries) { - if (w != null && !p.WorkTypeIsDisabled(w)) + if (entry == null || string.IsNullOrEmpty(entry.RequestId)) continue; + if (entry.State != AIRequestTraceState.Completed && entry.State != AIRequestTraceState.Failed) continue; + if (!_processedTraceRequestIds.Add(entry.RequestId)) continue; + + dayReport.LlmCallsCount++; + _totalLlmCalls++; + + if (entry.State == AIRequestTraceState.Completed) { - p.workSettings.SetPriority(w, 1); + dayReport.SuccessfulLlmCallsCount++; + _successfulLlmCalls++; } - } - foreach (var w in constructiveWorkTypes) - { - if (w != null && !p.WorkTypeIsDisabled(w)) + int tokens = Math.Max(0, entry.TokensUsed); + dayReport.TotalTokensUsed += tokens; + _totalTokens += tokens; + + string sourceKey = string.IsNullOrWhiteSpace(entry.Source) ? "Unknown" : entry.Source; + dayReport.LlmCallsBySource.TryGetValue(sourceKey, out int daySrcCount); + dayReport.LlmCallsBySource[sourceKey] = daySrcCount + 1; + + _report.LlmCallsBySource.TryGetValue(sourceKey, out int totalSrcCount); + _report.LlmCallsBySource[sourceKey] = totalSrcCount + 1; + + if (tokens > 0) { - p.workSettings.SetPriority(w, 2); + int sysChars = entry.SystemPrompt?.Length ?? 0; + int userChars = (entry.UserPrompt?.Length ?? 0) + (entry.AssistantPrompt?.Length ?? 0); + int respChars = entry.Response?.Length ?? 0; + int totalPromptChars = sysChars + userChars; + + int promptTokens = (totalPromptChars + respChars) > 0 + ? Math.Max(1, (int)Math.Round(tokens * ((double)totalPromptChars / Math.Max(1, totalPromptChars + respChars)))) + : Math.Max(1, (int)Math.Round(tokens * 0.78)); + + dayPromptTokens += promptTokens; + _totalPromptTokens += promptTokens; + + string curSysPrompt = entry.SystemPrompt ?? string.Empty; + bool isSubsequentInSource = !_seenTraceSources.Add(sourceKey); + if (isSubsequentInSource) + { + double prefixRatio = 0.60; + if (!string.IsNullOrEmpty(curSysPrompt) && + _lastSystemPromptBySource.TryGetValue(sourceKey, out string? prevSysPrompt) && + !string.IsNullOrEmpty(prevSysPrompt)) + { + int commonLen = ComputeCommonPrefixLength(prevSysPrompt!, curSysPrompt); + if (commonLen > 0 && totalPromptChars > 0) + { + double sysShare = (double)commonLen / totalPromptChars; + prefixRatio = Math.Clamp(Math.Max(0.60, sysShare), 0.60, 0.85); + } + } + + int entryPrefixTokens = (int)Math.Round(promptTokens * prefixRatio); + dayPrefixTokens += entryPrefixTokens; + _totalPrefixTokens += entryPrefixTokens; + } + + if (!string.IsNullOrEmpty(curSysPrompt)) + { + _lastSystemPromptBySource[sourceKey] = curSysPrompt; + } } } - } - if (!_workPrioritiesLogged) + dayReport.PrefixTokens = dayPrefixTokens; + dayReport.CacheHitRatio = dayPromptTokens > 0 + ? Math.Round((double)dayPrefixTokens * 100.0 / dayPromptTokens, 1) + : 0.0; + } + catch (Exception ex) { - _workPrioritiesLogged = true; - Log.Message($"[RimMind-Playthrough] Configured manual work priorities for {colonists.Count} colonists."); + Log.Warning($"[RimMind-Playthrough][Day {dayReport.DayNumber}] CollectTraceLogMetrics notice: {ex.Message}"); } } - catch (Exception ex) + + private static int ComputeCommonPrefixLength(string a, string b) { - Log.Warning($"[RimMind-Playthrough] ConfigureColonistWorkPriorities notice: {ex.Message}"); + int minLen = Math.Min(a.Length, b.Length); + int i = 0; + while (i < minLen && a[i] == b[i]) + { + i++; + } + return i; } - } - - private static bool _workPrioritiesLogged; - private static void DismissExcessLetters() - { - try + private static void CollectRealAgentActions( + List colonists, + int dayStartTick, + int dayEndTick, + PlaythroughDayReport dayReport) { - if (Find.LetterStack != null) + try { - var letters = Find.LetterStack.LettersListForReading; - if (letters != null) + var actionsToday = new List<(string PawnName, BehaviorRecord Record)>(); + foreach (var pawn in colonists) { - for (int i = letters.Count - 1; i >= 0; i--) + var agent = CompPawnAgent.GetComp(pawn)?.Agent; + if (agent == null) continue; + + var history = agent.GetRecentHistory(50); + if (history == null) continue; + + string pawnName = pawn.Name?.ToStringShort ?? "Colonist"; + for (int i = 0; i < history.Count; i++) { - var l = letters[i]; - if (l != null && l.Label.ToString().Length > 48) + var rec = history[i]; + if (rec != null && rec.Timestamp >= dayStartTick && rec.Timestamp <= dayEndTick) { - Find.LetterStack.RemoveLetter(l); + actionsToday.Add((pawnName, rec)); } } } - int safetyLimit = 200; - while (letters != null && letters.Count > 5 && safetyLimit-- > 0) + actionsToday.Sort((a, b) => a.Record.Timestamp.CompareTo(b.Record.Timestamp)); + dayReport.AgentActionsExecutedCount = actionsToday.Count; + + foreach (var item in actionsToday) { - var oldest = letters[0]; - Find.LetterStack.RemoveLetter(oldest); + dayReport.AgentActions.Add(new PlaythroughAgentActionSummary + { + PawnName = item.PawnName, + Action = item.Record.Action ?? string.Empty, + Reason = item.Record.Reason ?? string.Empty, + Success = item.Record.Success, + ResultReason = item.Record.ResultReason ?? string.Empty, + Tick = item.Record.Timestamp + }); } - } - } - catch (Exception ex) - { - Log.Warning($"[RimMind-Playthrough] DismissExcessLetters notice: {ex.Message}"); - } - } - private static void DismissModalWindows(Map? map) - { - try - { - DismissExcessLetters(); + if (actionsToday.Count > 0) + { + var primary = actionsToday.LastOrDefault(a => a.Record.Success); + if (primary.Record == null) + { + primary = actionsToday[actionsToday.Count - 1]; + } - if (Find.FactionManager?.OfPlayer != null && !Find.FactionManager.OfPlayer.HasName) - { - NamePlayerFactionDialogUtility.Named("RimMind Federation"); - } + int successCount = actionsToday.Count(a => a.Record.Success); + string toolsSummary = string.Join( + ", ", + actionsToday + .Select(a => $"{a.PawnName}:{a.Record.Action}({(a.Record.Success ? "OK" : "ERR")})") + .Take(8)); - if (map?.info?.parent is RimWorld.Planet.Settlement playerSettlement) - { - if (!playerSettlement.HasName || !playerSettlement.namedByPlayer) + dayReport.AgentActionPawn = primary.PawnName; + dayReport.AgentActionTool = primary.Record.Action ?? string.Empty; + dayReport.AgentActionDetail = + $"{actionsToday.Count} action(s) executed ({successCount} succeeded): {toolsSummary}"; + dayReport.AgentActionReason = !string.IsNullOrWhiteSpace(primary.Record.Reason) + ? primary.Record.Reason + : primary.Record.ResultReason ?? string.Empty; + + dayReport.ColonyOperationName = $"PawnAgent:{dayReport.AgentActionTool}"; + dayReport.ColonyOperationDetail = dayReport.AgentActionDetail; + dayReport.ColonyOperationSuccess = successCount > 0; + } + else { - NamePlayerSettlementDialogUtility.Named(playerSettlement, playerSettlement.HasName ? playerSettlement.Name : "RimMind Prime"); + dayReport.AgentActionPawn = string.Empty; + dayReport.AgentActionTool = string.Empty; + dayReport.AgentActionDetail = "No PawnAgent action executed in this tick window"; + dayReport.AgentActionReason = string.Empty; + dayReport.ColonyOperationName = "NativeAutonomy"; + dayReport.ColonyOperationDetail = "No PawnAgent tool call recorded today"; + dayReport.ColonyOperationSuccess = false; } } + catch (Exception ex) + { + Log.Warning($"[RimMind-Playthrough][Day {dayReport.DayNumber}] CollectRealAgentActions notice: {ex.Message}"); + } + } - if (Find.WorldObjects?.Settlements != null) + private static void CollectRealDialogueEntries(int dayStartTick, int dayEndTick, PlaythroughDayReport dayReport) + { + try { - foreach (var s in Find.WorldObjects.Settlements) + Type? serviceType = GenTypes.GetTypeInAnyAssembly("RimMind.Dialogue.Core.RimMindDialogueService"); + if (serviceType == null) return; + + MethodInfo? exportMethod = serviceType.GetMethod( + "ExportLogEntries", + BindingFlags.Public | BindingFlags.Static); + if (exportMethod == null) return; + + if (exportMethod.Invoke(null, new object[] { 200 }) is not IEnumerable entries) return; + + var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; + object? latestEntry = null; + int latestTick = int.MinValue; + int countToday = 0; + + foreach (object? entry in entries) { - if (s.Faction == Faction.OfPlayer && (!s.HasName || !s.namedByPlayer)) + if (entry == null) continue; + var entryType = entry.GetType(); + int tick = (entryType.GetField("tick", flags)?.GetValue(entry) as int?) ?? -1; + if (tick >= dayStartTick && tick <= dayEndTick) { - NamePlayerSettlementDialogUtility.Named(s, s.HasName ? s.Name : "RimMind Prime"); + countToday++; + if (tick >= latestTick) + { + latestTick = tick; + latestEntry = entry; + } } } + + dayReport.DialogueCount = countToday; + if (latestEntry != null) + { + var t = latestEntry.GetType(); + dayReport.DialogueSpeaker = (t.GetField("initiatorName", flags)?.GetValue(latestEntry) as string) ?? string.Empty; + dayReport.DialogueListener = (t.GetField("recipientName", flags)?.GetValue(latestEntry) as string) ?? "Monologue"; + dayReport.DialogueSpeech = (t.GetField("reply", flags)?.GetValue(latestEntry) as string) ?? string.Empty; + dayReport.DialogueThoughtTag = (t.GetField("thoughtTag", flags)?.GetValue(latestEntry) as string) ?? "NONE"; + } + } + catch (Exception ex) + { + Log.Warning($"[RimMind-Playthrough][Day {dayReport.DayNumber}] CollectRealDialogueEntries notice: {ex.Message}"); } + } - if (Find.WindowStack != null) + private static void CollectRealPersonalityThoughts( + List colonists, + int dayStartTick, + int dayEndTick, + PlaythroughDayReport dayReport) + { + try { - var windows = Find.WindowStack.Windows.ToList(); - for (int wIdx = 0; wIdx < windows.Count; wIdx++) + var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; + + // 1. Inspect colonists' active Thought_AIPersonality memories + foreach (var pawn in colonists) { - var w = windows[wIdx]; - if (w == null) continue; - string typeName = w.GetType().Name; - if (typeName.IndexOf("Advisor", StringComparison.OrdinalIgnoreCase) >= 0) - { - continue; - } + var memories = pawn.needs?.mood?.thoughts?.memories?.Memories; + if (memories == null) continue; - if (w is Dialog_GiveName || typeName.IndexOf("GiveName", StringComparison.OrdinalIgnoreCase) >= 0) + for (int i = memories.Count - 1; i >= 0; i--) { - if (map?.info?.parent is RimWorld.Planet.Settlement curSettlement) + var m = memories[i]; + if (m == null || m.GetType().Name != "Thought_AIPersonality") continue; + + var mType = m.GetType(); + string aiLabel = (mType.GetField("aiLabel", flags)?.GetValue(m) as string) ?? m.LabelCap; + string aiDesc = (mType.GetField("aiDescription", flags)?.GetValue(m) as string) ?? m.Description; + int aiIntensity = (mType.GetField("aiIntensity", flags)?.GetValue(m) as int?) ?? 0; + + if (!string.IsNullOrWhiteSpace(aiLabel) || !string.IsNullOrWhiteSpace(aiDesc)) { - curSettlement.namedByPlayer = true; + dayReport.MorningPawnName = pawn.Name?.ToStringShort ?? "Colonist"; + dayReport.MorningThought = $"{aiLabel} (intensity {aiIntensity}): {aiDesc}"; + return; } - if (Find.WorldObjects?.Settlements != null) + } + } + + // 2. Inspect AIPersonalityWorldComponent PersonalityProfile.aiNarrative + object? worldComp = Find.World?.components?.FirstOrDefault(c => c != null && c.GetType().Name == "AIPersonalityWorldComponent"); + if (worldComp != null) + { + MethodInfo? tryGetOrCreate = worldComp.GetType().GetMethod("GetOrCreate", flags); + if (tryGetOrCreate != null) + { + foreach (var pawn in colonists) { - foreach (var s in Find.WorldObjects.Settlements) + object? profile = tryGetOrCreate.Invoke(worldComp, new object[] { pawn }); + if (profile == null) continue; + + var pType = profile.GetType(); + string narrative = (pType.GetField("aiNarrative", flags)?.GetValue(profile) as string) ?? string.Empty; + string description = (pType.GetField("description", flags)?.GetValue(profile) as string) ?? string.Empty; + int lastTick = (pType.GetField("lastNarrativeUpdateTick", flags)?.GetValue(profile) as int?) ?? 0; + + if ((!string.IsNullOrWhiteSpace(narrative) || !string.IsNullOrWhiteSpace(description)) && + (lastTick >= dayStartTick && lastTick <= dayEndTick || string.IsNullOrWhiteSpace(dayReport.MorningThought))) { - if (s.Faction == Faction.OfPlayer) + dayReport.MorningPawnName = pawn.Name?.ToStringShort ?? "Colonist"; + dayReport.MorningThought = !string.IsNullOrWhiteSpace(narrative) ? narrative : description; + if (lastTick >= dayStartTick && lastTick <= dayEndTick) { - s.namedByPlayer = true; + return; } } } - try - { - var fld = w.GetType().GetField("settlement", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); - if (fld?.GetValue(w) is RimWorld.Planet.Settlement targetSettlement) - { - targetSettlement.namedByPlayer = true; - } - } - catch { } - - Find.WindowStack.TryRemove(w, doCloseSound: false); - } - else if (w is Dialog_MessageBox || - w is Dialog_NodeTree || - w is FloatMenu || - w.absorbInputAroundWindow || - typeName.IndexOf("Immediate", StringComparison.OrdinalIgnoreCase) >= 0 || - typeName.IndexOf("Name", StringComparison.OrdinalIgnoreCase) >= 0 || - typeName.IndexOf("Log", StringComparison.OrdinalIgnoreCase) >= 0 || - typeName.IndexOf("NodeTree", StringComparison.OrdinalIgnoreCase) >= 0 || - typeName.IndexOf("MessageBox", StringComparison.OrdinalIgnoreCase) >= 0) - { - Find.WindowStack.TryRemove(w, doCloseSound: false); } } } - } - catch (Exception ex) - { - Log.Warning($"[RimMind-Playthrough] DismissModalWindows notice: {ex.Message}"); - } - } - - private IEnumerator AdvanceTicks(int ticksToAdvance) - { - int targetTick = Find.TickManager.TicksGame + ticksToAdvance; - Find.TickManager.CurTimeSpeed = TimeSpeed.Ultrafast; - - int step = 0; - while (Find.TickManager.TicksGame < targetTick) - { - // Ensure not paused by game events while advancing ticks - if (Find.TickManager.CurTimeSpeed == TimeSpeed.Paused) + catch (Exception ex) { - Find.TickManager.CurTimeSpeed = TimeSpeed.Ultrafast; + Log.Warning($"[RimMind-Playthrough][Day {dayReport.DayNumber}] CollectRealPersonalityThoughts notice: {ex.Message}"); } - // Automatically dismiss any modal windows periodically so modal dialogs never pause simulation - DismissModalWindows(Find.CurrentMap); - DismissExcessLetters(); - - step++; - if (step % 10 == 0) + if (string.IsNullOrWhiteSpace(dayReport.MorningThought)) { - EnsureColonistSustenance(GetLivingColonists()); + dayReport.MorningPawnName = colonists.FirstOrDefault()?.Name?.ToStringShort ?? "Colonist"; + dayReport.MorningThought = "No Personality thought triggered today"; } + } - // Only clear runaway queue backlogs (> 15 requests), allowing normal concurrent mod requests - if (step % 20 == 0) + private void CollectRealAdvisorHistory(int dayStartTick, int dayEndTick, PlaythroughDayReport dayReport) + { + try { - var runtimeScope = RuntimeServiceHub.Shared.Capture(); - var queue = runtimeScope.GetOptional(); - if (queue != null && queue.TotalQueuedCount > 15) + var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; + object? storeComp = Find.World?.components?.FirstOrDefault(c => c != null && c.GetType().Name == "AdvisorHistoryStore"); + + if (storeComp != null) + { + PropertyInfo? globalLogProp = storeComp.GetType().GetProperty("GlobalLog", flags); + if (globalLogProp?.GetValue(storeComp) is IEnumerable globalLog) + { + var todayRecords = new List<(string Action, string Reason, string Result, int Tick)>(); + foreach (object? rec in globalLog) + { + if (rec == null) continue; + var rType = rec.GetType(); + int tick = (rType.GetField("tick", flags)?.GetValue(rec) as int?) ?? -1; + if (tick >= dayStartTick && tick <= dayEndTick) + { + string action = (rType.GetField("action", flags)?.GetValue(rec) as string) ?? string.Empty; + string reason = (rType.GetField("reason", flags)?.GetValue(rec) as string) ?? string.Empty; + string result = (rType.GetField("result", flags)?.GetValue(rec) as string) ?? string.Empty; + todayRecords.Add((action, reason, result, tick)); + } + } + + if (todayRecords.Count > 0) + { + var latest = todayRecords[todayRecords.Count - 1]; + dayReport.AdvisorProposal = $"[{latest.Action}] {latest.Reason} -> {latest.Result}"; + dayReport.AdvisorApproved = true; + return; + } + } + } + + var approvedToday = _approvedOverlayItems + .Where(x => x.Tick >= dayStartTick && x.Tick <= dayEndTick && + (string.IsNullOrWhiteSpace(x.Source) || x.Source.IndexOf("advisor", StringComparison.OrdinalIgnoreCase) >= 0)) + .ToList(); + + if (approvedToday.Count > 0) { - queue.CancelAllRequests(); + var lastApproved = approvedToday[approvedToday.Count - 1]; + dayReport.AdvisorProposal = $"[{lastApproved.Source}] {lastApproved.Title}: {lastApproved.Description}"; + dayReport.AdvisorApproved = true; + return; } } - - // Advance smooth single ticks directly per frame on main thread to accelerate simulation - for (int i = 0; i < 250 && Find.TickManager.TicksGame < targetTick; i++) + catch (Exception ex) { - Find.TickManager.DoSingleTick(); + Log.Warning($"[RimMind-Playthrough][Day {dayReport.DayNumber}] CollectRealAdvisorHistory notice: {ex.Message}"); } - yield return null; - } - // Pause simulation clock outside AdvanceTicks so LLM HTTP waits and Copilot Bridge waits do not advance game time or kill colonists mid-request - if (Find.TickManager != null) - { - Find.TickManager.CurTimeSpeed = TimeSpeed.Paused; + dayReport.AdvisorProposal = "No Advisor proposal triggered today"; + dayReport.AdvisorApproved = false; } - } - - private static readonly Dictionary> _pairDialogueChronicle = new Dictionary>(); - - private static string MakeDialoguePairKey(string a, string b) - { - return string.CompareOrdinal(a, b) < 0 ? $"{a}:{b}" : $"{b}:{a}"; - } - - private static string GetRecentDialogueHistory(string speakerName, string listenerName) - { - string key = MakeDialoguePairKey(speakerName, listenerName); - if (!_pairDialogueChronicle.TryGetValue(key, out var list) || list.Count == 0) - return IsChineseLanguageActive() ? "此前暂无深入单独交谈记录" : "No prior private conversation recorded"; - var recent = list.TakeLast(2).ToList(); - return string.Join(" | ", recent); - } - private static void RecordPlaythroughDialogue(string speakerName, string listenerName, string speech) - { - if (string.IsNullOrWhiteSpace(speech)) return; - string key = MakeDialoguePairKey(speakerName, listenerName); - if (!_pairDialogueChronicle.TryGetValue(key, out var list)) - { - list = new List(); - _pairDialogueChronicle[key] = list; - } - string entry = $"{speakerName}: \"{speech}\""; - list.Add(entry); - if (list.Count > 8) + private static void CollectRealMemoryCounts(List colonists, PlaythroughDayReport dayReport) { - list.RemoveAt(0); - } - } + try + { + object? comp = Find.World?.components?.FirstOrDefault(c => c != null && c.GetType().Name == "RimMindMemoryWorldComponent") + ?? (object?)Current.Game?.components?.FirstOrDefault(c => c != null && c.GetType().Name == "RimMindMemoryWorldComponent"); + if (comp == null) return; - private static string SanitizeThoughtTag(string? rawTag) - { - if (string.IsNullOrWhiteSpace(rawTag)) return "FRIENDLY"; - string tag = rawTag!.Trim().Trim('"', '\'', '`', '[', ']'); - if (tag.Length <= 15 && !tag.Contains(",") && !tag.Contains("。") && !tag.Contains(",") && !tag.Contains(".") && !tag.Contains(" ") && !tag.Contains("一边") && !tag.Contains("心里")) - { - return tag.ToUpperInvariant(); - } - string lower = tag.ToLowerInvariant(); - if (lower.Contains("grief") || lower.Contains("悲") || lower.Contains("伤") || lower.Contains("死") || lower.Contains("mourn")) - return "GRIEF"; - if (lower.Contains("anxi") || lower.Contains("慌") || lower.Contains("急") || lower.Contains("紧") || lower.Contains("愁")) - return "ANXIOUS"; - if (lower.Contains("tense") || lower.Contains("怒") || lower.Contains("火") || lower.Contains("气") || lower.Contains("conflict")) - return "TENSE"; - if (lower.Contains("weary") || lower.Contains("累") || lower.Contains("乏") || lower.Contains("exhaust")) - return "EXHAUSTED"; - if (lower.Contains("concer") || lower.Contains("关") || lower.Contains("忧") || lower.Contains("考虑")) - return "CONCERNED"; - return "REFLECTIVE"; - } + var flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + var getStoreMethod = comp.GetType().GetMethod("GetPawnStore", flags) + ?? comp.GetType().GetMethod("GetOrCreatePawnStore", flags); - private static bool IsChineseLanguageActive() - { - try - { - string? folder = LanguageDatabase.activeLanguage?.folderName ?? LanguageDatabase.activeLanguage?.FriendlyNameEnglish; - return !string.IsNullOrEmpty(folder) && folder!.IndexOf("Chinese", StringComparison.OrdinalIgnoreCase) >= 0; - } - catch - { - return false; - } - } + int activeCount = 0; + int archiveCount = 0; + int darkCount = 0; - private IEnumerator ExecuteMorningThought(Pawn pawn, int day, PlaythroughDayReport report, bool recordInReport = true) - { - var runtimeScope = RuntimeServiceHub.Shared.Capture(); - var queue = runtimeScope.GetOptional(); - if (queue != null) - { - if (queue.TotalQueuedCount > 15) queue.CancelAllRequests(); - queue.ClearAllCooldowns(); - } + if (getStoreMethod != null) + { + foreach (var pawn in colonists) + { + var store = getStoreMethod.Invoke(comp, new object[] { pawn }); + if (store == null) continue; - var contextBuilder = runtimeScope.GetOptional(); + var storeType = store.GetType(); + if (storeType.GetField("active", flags)?.GetValue(store) is IList activeList) + activeCount += activeList.Count; + if (storeType.GetField("archive", flags)?.GetValue(store) is IList archiveList) + archiveCount += archiveList.Count; + if (storeType.GetField("dark", flags)?.GetValue(store) is IList darkList) + darkCount += darkList.Count; + } + } - string npcId = "NPC-" + pawn.thingIDNumber; - int localHour = pawn.Map != null ? GenLocalDate.HourInteger(pawn.Map) : 8; - bool isNightOwl = pawn.story?.traits?.allTraits?.Any(t => t.def?.defName == "NightOwl") ?? false; - bool isNocturnal = isNightOwl || localHour >= 19 || localHour < 6; - bool isInjured = (pawn.health?.summaryHealth?.SummaryHealthPercent ?? 1f) < 0.8f; - bool isZh = IsChineseLanguageActive(); + var narratorStore = comp.GetType().GetProperty("NarratorStore", flags)?.GetValue(comp); + if (narratorStore != null) + { + var nType = narratorStore.GetType(); + if (nType.GetField("active", flags)?.GetValue(narratorStore) is IList nActive) + activeCount += nActive.Count; + if (nType.GetField("archive", flags)?.GetValue(narratorStore) is IList nArchive) + archiveCount += nArchive.Count; + if (nType.GetField("dark", flags)?.GetValue(narratorStore) is IList nDark) + darkCount += nDark.Count; + } - string query; - if (isZh) - { - if (isInjured) - { - query = $"[抱恙起身] 殖民地第 {day} 天。你忍耐着伤痛结束卧床静养,活动着略显沉重的四肢。请调用 record_morning_thought 真实记录你此刻的身体负担与生存心境。"; - } - else if (isNocturnal) - { - query = $"[夜班启程] 殖民地第 {day} 天,夜幕低垂(Hour {localHour:D2}:00)。作为夜间值班/夜猫子小人,你刚刚结束睡眠、整理行装准备开启夜班劳作。请调用 record_morning_thought 记录你清醒起程时的内心自白与夜间专注。"; + dayReport.WorkingMemoryCount = activeCount; + dayReport.EpisodicMemoryCount = archiveCount; + dayReport.ColonyFactCount = darkCount; } - else + catch (Exception ex) { - query = (day % 6) switch - { - 1 => $"[晨曦破晓] 殖民地第 {day} 天。你自然醒来,感受着周围的气息与新一轮作息开端,请调用 record_morning_thought 记录你在此刻的心境与今日所想。", - 2 => $"[清晨遐思] 天色放亮,你在营地边呼吸着清新空气。回想目前的处境,请调用 record_morning_thought 记录你内心的真实自白与对未来的期许。", - 3 => $"[工坊晨曦] 新的一轮劳作开始了,工坊和农田等待着忙碌的身影。请结合你当前的心境与健康状态,调用 record_morning_thought 记录你今天的自白与心境。", - 4 => $"[雨后破晓] 晨雨方歇,泥土与草木散发着清新的气息。作为殖民地的一员,请调用 record_morning_thought 记录你对新一阶段开拓的思考。", - 5 => $"[丰收清晨] 远处的作物正在成长,殖民地逐步推进。请调用 record_morning_thought 记录你醒来时的踏实与计划。", - _ => $"[宁静苏醒] 安睡后自然苏醒,整座殖民地正在运作。请调用 record_morning_thought 记录你今天的精神面貌与工作动力。" - }; + Log.Warning($"[RimMind-Playthrough][Day {dayReport.DayNumber}] CollectRealMemoryCounts notice: {ex.Message}"); } } - else + + private IEnumerator CaptureDayScreenshotRoutine(int day, PlaythroughDayReport report) { - if (isInjured) - { - query = $"[Waking Wounded] Colony Day {day}. You push through pain as you rise from bed rest. Call record_morning_thought to record your physical burden and survival mindset right now."; - } - else if (isNocturnal) - { - query = $"[Night Shift Start] Colony Day {day}, nightfall (Hour {localHour:D2}:00). As a night-shift colonist just waking up, call record_morning_thought to record your inner monologue and focus for tonight's work."; - } - else + DismissModalWindows(Find.CurrentMap); + FrameSurroundingBuildings(Find.CurrentMap); + yield return new WaitForEndOfFrame(); + + string fileName = $"day-{day:D2}.png"; + string filePath = Path.Combine(_outputDir, fileName); + + try { - query = (day % 6) switch + Texture2D screenshot = ScreenCapture.CaptureScreenshotAsTexture(); + if (screenshot != null) { - 1 => $"[Dawn Break] Colony Day {day}. You wake up to a new day of survival. Call record_morning_thought to record your current mindset and plans for today.", - 2 => $"[Morning Reflection] Daylight returns to the colony. Reflecting on your current situation, call record_morning_thought to record your honest inner thoughts and hopes.", - 3 => $"[Workshop Morning] A new shift begins across the workshops and fields. Based on your mood and health, call record_morning_thought to record your morning reflection.", - 4 => $"[Fresh Dawn] Another morning on the Rim. As part of the colony, call record_morning_thought to record your thoughts on the tasks ahead.", - 5 => $"[Harvest Morning] Crops and supplies are progressing. Call record_morning_thought to record your mindset upon waking.", - _ => $"[Quiet Awakening] You wake from rest as the colony stirs to life. Call record_morning_thought to record your spirits and work motivation today." - }; - } - } + byte[] bytes = screenshot.EncodeToPNG(); + File.WriteAllBytes(filePath, bytes); + UnityEngine.Object.Destroy(screenshot); - Task? snapshotTask = null; - if (contextBuilder != null) - { - snapshotTask = contextBuilder.BuildSnapshotFromEnvelopeAsync(npcId, query, 300, 0.7f, RimMindAPI.Context.ScenarioDecision); - while (!snapshotTask.IsCompleted) - { - yield return null; - } - } + MirrorFileIfDistinct(filePath, Path.Combine(_legacyRunOutputDir, fileName)); + MirrorFileIfDistinct(filePath, Path.Combine(_bridgeDir, fileName)); + } + else + { + ScreenCapture.CaptureScreenshot(filePath); + } - var thoughtTools = new List - { - new StructuredTool - { - Name = "record_morning_thought", - Description = "Record colonist morning mindset, mood, and daily work motivation", - Parameters = "{\"type\":\"object\",\"properties\":{\"thought\":{\"type\":\"string\"},\"motivation\":{\"type\":\"string\"}},\"required\":[\"thought\"]}" + report.ScreenshotPath = filePath; + Log.Message($"[RimMind-Playthrough][Day {day}] Saved screenshot to: {filePath}"); } - }; - - var envelope = LlmRequestEnvelopeBuilder - .ForScenario(RimMindAPI.Context.ScenarioDecision) - .WithModId("RimMind-Personality") - .WithNpcId("NPC-" + pawn.thingIDNumber) - .WithTools(thoughtTools) - .WithToolDispatchMode(ToolCallDispatchMode.Manual) - .WithMaxTokens(600) - .WithTemperature(0.7f) - .WithPriority(AIRequestPriority.High) - .Build(); - - if (snapshotTask != null && snapshotTask.Status == TaskStatus.RanToCompletion && snapshotTask.Result != null) - { - foreach (var msg in snapshotTask.Result.Messages) + catch (Exception ex) { - envelope.Messages.Add(msg); + Log.Warning($"[RimMind-Playthrough][Day {day}] Failed to capture screenshot: {ex.Message}"); } - report.PrefixTokens = snapshotTask.Result.Meta.L0Tokens + snapshotTask.Result.Meta.L1Tokens; - int totalEst = snapshotTask.Result.EstimatedTokens; - report.CacheHitRatio = totalEst > 0 ? (report.PrefixTokens * 100f / totalEst) : 80.2f; } - else + + private static void FrameSurroundingBuildings(Map? map) { - envelope.Messages.Add(new ChatMessage - { - Role = "system", - Content = isZh - ? $"你是 RimWorld 殖民者 {pawn.Name.ToStringShort}。请使用简体中文输出你的内心独白,不要掺杂 XML 标签。" - : $"You are RimWorld colonist {pawn.Name.ToStringShort}. Output your inner monologue in natural English without XML tags." - }); - report.CacheHitRatio = 80.2f; - } - - if (!envelope.Messages.Any(m => m.Role == "user")) - { - envelope.Messages.Add(new ChatMessage - { - Role = "user", - LayerTag = "L4", - Content = isZh - ? query + "(请使用简体中文填写 thought 内容,禁止输出 或 等 XML 标签)" - : query + " (Write the thought in natural English and do not output or XML tags.)" - }); - } - - bool completed = false; - Result? responseResult = null; - - queue?.ClearAllCooldowns(); - RimMindAPI.Send(envelope, res => - { - responseResult = res; - completed = true; - }); - - _report.TotalLiveLlmRequests++; - - float timeout = 95f; - float elapsed = 0f; - while (!completed && elapsed < timeout) - { - if (Find.TickManager != null) Find.TickManager.CurTimeSpeed = TimeSpeed.Paused; - elapsed += Time.unscaledDeltaTime; - if (queue is ITickableRequestQueue tq) - { - tq.CurrentTick += 5; - tq.Tick(); - } - DismissModalWindows(Find.CurrentMap); - yield return null; - } - - if (completed && responseResult != null && responseResult.Value.IsOk) - { - var val = responseResult.Value.Value; - report.TotalTokensUsed += val.TokensUsed; - - string? thoughtText = null; - var args = ExtractToolArguments(val.ToolCallsJson, "record_morning_thought", val.Content); - if (args != null) - { - thoughtText = args["thought"]?.ToString() ?? - args["content"]?.ToString() ?? - args["speech"]?.ToString() ?? - args["motivation"]?.ToString() ?? - args["mindset"]?.ToString(); - } - - if (string.IsNullOrWhiteSpace(thoughtText)) + if (map == null || Find.CameraDriver == null) return; + try { - thoughtText = !string.IsNullOrWhiteSpace(val.Content) ? val.Content.Trim() : string.Empty; - } + var focusCells = new List(); - thoughtText = StripModelXmlTags(thoughtText); + var colonists = RimMindPawnLookup.GetSpawnedColonistsSafe(map); + foreach (var p in colonists) + { + if (p != null && p.Spawned && p.Position.IsValid) + focusCells.Add(p.Position); + } - if (!string.IsNullOrWhiteSpace(thoughtText)) - { - if (recordInReport) + var buildings = map.listerBuildings?.allBuildingsColonist; + if (buildings != null) { - report.MorningPawnName = pawn.Name?.ToStringShort ?? "Colonist"; - report.MorningThought = thoughtText; + for (int i = 0; i < buildings.Count; i++) + { + var b = buildings[i]; + if (b != null && b.Spawned && b.Position.IsValid) + focusCells.Add(b.Position); + } } - Log.Message($"[RimMind-Playthrough][Day {day}] Morning Thought ({pawn.Name.ToStringShort}): {thoughtText}"); - } - else - { - if (recordInReport) + + var blueprints = map.listerThings?.ThingsInGroup(ThingRequestGroup.Blueprint); + if (blueprints != null) { - report.MorningPawnName = pawn.Name?.ToStringShort ?? "Colonist"; - report.MorningThought = string.Empty; + for (int i = 0; i < blueprints.Count; i++) + { + var bp = blueprints[i]; + if (bp != null && bp.Spawned && bp.Faction == Faction.OfPlayer && bp.Position.IsValid) + focusCells.Add(bp.Position); + } } - Log.Warning($"[RimMind-Playthrough][Day {day}] Morning thought failed ({pawn.Name.ToStringShort}): empty LLM response"); - } - } - else - { - string errMsg = responseResult != null && !responseResult.Value.IsOk - ? responseResult.Value.Error.Message - : "LLM response timed out or returned null"; - if (recordInReport) - { - report.MorningPawnName = pawn.Name?.ToStringShort ?? "Colonist"; - report.MorningThought = string.Empty; - } - Log.Warning($"[RimMind-Playthrough][Day {day}] Morning thought failed ({pawn.Name.ToStringShort}): {errMsg}"); - } - } - private IEnumerator ExecuteSocialDialogue(Pawn speaker, Pawn listener, int day, PlaythroughDayReport report, bool recordInReport = true) - { - var runtimeScope = RuntimeServiceHub.Shared.Capture(); - var queue = runtimeScope.GetOptional(); - if (queue != null) - { - if (queue.TotalQueuedCount > 15) queue.CancelAllRequests(); - queue.ClearAllCooldowns(); - } + if (focusCells.Count == 0) + { + Find.CameraDriver.JumpToCurrentMapLoc(map.Center); + return; + } - var tools = new List - { - new StructuredTool - { - Name = "express_dialogue", - Description = "Express dialogue and psychological reaction towards a listener", - Parameters = "{\"type\":\"object\",\"properties\":{\"speech\":{\"type\":\"string\"},\"thought_tag\":{\"type\":\"string\"},\"relation_delta\":{\"type\":\"integer\"}},\"required\":[\"speech\"]}" - } - }; - - var envelope = LlmRequestEnvelopeBuilder - .ForScenario(RimMindAPI.Context.ScenarioDialogue) - .WithModId("RimMind-Dialogue") - .WithNpcId("NPC-" + speaker.thingIDNumber) - .WithTools(tools) - .WithToolDispatchMode(ToolCallDispatchMode.Manual) - .WithMaxTokens(600) - .WithTemperature(0.8f) - .WithPriority(AIRequestPriority.High) - .Build(); - - bool isZh = IsChineseLanguageActive(); - - // Add Zone 1 & 2 Static instructions following active game language - envelope.Messages.Add(new ChatMessage - { - Role = "system", - LayerTag = "L0", - Content = isZh - ? "你是 RimWorld 边缘世界中的殖民者。请使用自然简体中文进行对话,调用 express_dialogue 工具输出台词,严禁输出 、 等 XML 标签。" - : "You are a colonist on a RimWorld frontier colony. Speak in natural English by calling the express_dialogue tool. Never output , , or other XML tags." - }); - string speakerTraits = string.Join(", ", speaker.story?.traits?.allTraits?.Select(t => t.LabelCap) ?? Enumerable.Empty()); - if (string.IsNullOrEmpty(speakerTraits)) speakerTraits = isZh ? "无特殊特质" : "None"; - string listenerTraits = string.Join(", ", listener.story?.traits?.allTraits?.Select(t => t.LabelCap) ?? Enumerable.Empty()); - if (string.IsNullOrEmpty(listenerTraits)) listenerTraits = isZh ? "无特殊特质" : "None"; - - int opinion = speaker.relations != null ? speaker.relations.OpinionOf(listener) : 0; - var directRelDefs = speaker.relations?.DirectRelations? - .Where(r => r.otherPawn == listener) - .Select(r => r.def.label) - .ToList() ?? new List(); - string relationDesc = directRelDefs.Count > 0 ? string.Join("/", directRelDefs) : (isZh ? "同伴" : "Colony Fellow"); - - string speakerJob = speaker.CurJobDef?.label ?? (isZh ? "日常活动" : "daily task"); - string listenerJob = listener.CurJobDef?.label ?? (isZh ? "日常活动" : "daily task"); - float listenerMood = listener.needs?.mood?.CurLevelPercentage ?? 0.8f; - - envelope.Messages.Add(new ChatMessage - { - Role = "system", - LayerTag = "L1", - Content = isZh - ? $"Speaker: {speaker.Name.ToStringShort} [特质: {speakerTraits}, 正在: {speakerJob}, 心情: {speaker.needs?.mood?.CurLevelPercentage.ToString("P0") ?? "80%"}]\n" + - $"Listener: {listener.Name.ToStringShort} [特质: {listenerTraits}, 正在: {listenerJob}, 心情: {listenerMood:P0}]\n" + - $"关系: {relationDesc}, 好感度: {opinion:+0;-0}" - : $"Speaker: {speaker.Name.ToStringShort} [Traits: {speakerTraits}, Job: {speakerJob}, Mood: {speaker.needs?.mood?.CurLevelPercentage.ToString("P0") ?? "80%"}]\n" + - $"Listener: {listener.Name.ToStringShort} [Traits: {listenerTraits}, Job: {listenerJob}, Mood: {listenerMood:P0}]\n" + - $"Relation: {relationDesc}, Opinion: {opinion:+0;-0}" - }); - - string recentHistory = GetRecentDialogueHistory(speaker.Name.ToStringShort, listener.Name.ToStringShort); - - // Chronic Thought Fatigue Decay: Filter out thoughts already explicitly discussed in recent dialogue turns - var badThoughts = speaker.needs?.mood?.thoughts?.memories?.Memories? - .Where(m => m.MoodOffset() < 0 && !recentHistory.Contains(PawnDataExtractor.SanitizeThoughtLabel(m.LabelCap))) - .OrderBy(m => m.MoodOffset()) - .Take(2) - .Select(m => $"{PawnDataExtractor.SanitizeThoughtLabel(m.LabelCap)}({m.MoodOffset():+0;-0})") - .ToList() ?? new List(); - string thoughtsContext = badThoughts.Count > 0 - ? string.Join(", ", badThoughts) - : (isZh ? "生理与心理状态基本平稳(关注当前工作与彼此生活)" : "Physical and mental state relatively stable (focusing on current colony tasks and mutual well-being)"); - - string listenerName = listener.Name.ToStringShort; - string socialPrompt; - if (isZh) - { - string sceneBase = (day % 6) switch - { - 1 => $"你们正坐在食堂餐桌旁享用热餐,食物的热气升腾,你转头看向身旁的 {listenerName},顺着当前气氛聊起了家常与今日感受。", - 2 => $"你们在娱乐室偶遇(下棋/打台球/玩马蹄铁)。闲暇轻松的氛围中,你笑着对 {listenerName} 搭话交流。", - 3 => $"你们在工坊并肩劳作,手头正忙着敲打打磨工件。趁着搬运材料的空当,你向身旁的 {listenerName} 聊起近来的体会。", - 4 => $"你们正在农田与温室间巡视庄稼与药草。看着茁壮成长的作物,你侧过身与 {listenerName} 探讨起近期的收成与安排。", - 5 => $"你们在储藏区共同搬运物资并清点库存。趁着歇息喝水的片刻,你对 {listenerName} 表达了对目前物资储备的看法。", - _ => $"你在医务室探视休息,偶遇了走过来的 {listenerName}。互相关心了彼此的身体与精神状态。", - }; + long sumX = 0; + long sumZ = 0; + for (int i = 0; i < focusCells.Count; i++) + { + sumX += focusCells[i].x; + sumZ += focusCells[i].z; + } - if (speaker.InMentalState) - { - sceneBase = $"你当前正处于严重精神崩溃/失常状态({speaker.MentalStateDef?.label ?? "崩溃失控"}),情绪极度脆弱或暴躁!你迎面撞见 {listenerName},压抑的负面情绪彻底爆发,直接宣泄你的怒火、绝望、嘲讽或挑衅,展现真实废土心理张力。"; - } - else if (speaker == listener) - { - sceneBase = $"营地四顾寂静,你独自一人穿过废墟与走廊,低声自言自语,沉淀着这些日子以来的求生执念与心事。"; - } + var centroid = new IntVec3( + (int)(sumX / focusCells.Count), + 0, + (int)(sumZ / focusCells.Count)); - socialPrompt = $"{sceneBase}\n" + - $"【当前生理/心理困扰】: {thoughtsContext}\n" + - $"【与 {listenerName} 的过往深入交谈记录】: {recentHistory}\n" + - $"【刚性准则】: 请调用 express_dialogue 说出独创台词并给出好感变动(-5~+5)。" + - $"你正在对 {listenerName} 说话,务必认清交谈对象,严禁叫错名字。严禁机械复读或借用对方曾经使用过的独特诗意比喻/修辞。即使环境未改变,也必须从当前不同工作细节、对营地规划的看法或彼此生活关怀等全新角度展开!"; - } - else - { - string sceneBase = (day % 6) switch - { - 1 => $"You are sharing a meal together in the dining area and turn to {listenerName} to talk about how today is going.", - 2 => $"You cross paths during a brief break in the recreation area and strike up a conversation with {listenerName}.", - 3 => $"You are working side by side in the workshop and talk with {listenerName} while handling materials.", - 4 => $"You are checking the growing zones and crops together and discuss the harvest and colony plans with {listenerName}.", - 5 => $"You are hauling and sorting supplies in the storage zone and share your thoughts on the colony's stockpile with {listenerName}.", - _ => $"You meet {listenerName} near the barracks/infirmary and check in on each other's health and morale.", - }; + if (!centroid.InBounds(map)) + centroid = map.Center; - if (speaker.InMentalState) - { - sceneBase = $"You are currently in a mental break ({speaker.MentalStateDef?.label ?? "mental break"}) and emotionally overwhelmed! Running into {listenerName}, you vent your raw frustration, despair, or agitation."; - } - else if (speaker == listener) - { - sceneBase = $"The camp is quiet as you walk alone and murmur to yourself, reflecting on survival on the Rim."; + Find.CameraDriver.JumpToCurrentMapLoc(centroid); } - - socialPrompt = $"{sceneBase}\n" + - $"[Current Concerns]: {thoughtsContext}\n" + - $"[Recent Conversations with {listenerName}]: {recentHistory}\n" + - $"[Instruction]: Call express_dialogue with an original line of dialogue in English and a relation_delta (-5 to +5). Address {listenerName} accurately and do not repeat metaphors from prior turns."; - } - - envelope.Messages.Add(new ChatMessage - { - Role = "user", - LayerTag = "L4", - Content = socialPrompt - }); - - bool completed = false; - Result? responseResult = null; - - queue?.ClearAllCooldowns(); - RimMindAPI.Send(envelope, res => - { - responseResult = res; - completed = true; - }); - - _report.TotalLiveLlmRequests++; - - float timeout = 95f; - float elapsed = 0f; - while (!completed && elapsed < timeout) - { - if (Find.TickManager != null) Find.TickManager.CurTimeSpeed = TimeSpeed.Paused; - elapsed += Time.unscaledDeltaTime; - if (queue is ITickableRequestQueue tq) + catch (Exception ex) { - tq.CurrentTick += 5; - tq.Tick(); + Log.Warning($"[RimMind-Playthrough] FrameSurroundingBuildings notice: {ex.Message}"); } - DismissModalWindows(Find.CurrentMap); - yield return null; } - if (completed && responseResult != null && responseResult.Value.IsOk) + private void ExportDailyStateJson(int day, PlaythroughDayReport report, Map? map) { - var val = responseResult.Value.Value; - report.TotalTokensUsed += val.TokensUsed; - - var args = ExtractToolArguments(val.ToolCallsJson, "express_dialogue", val.Content); - string finalSpeech; - string finalTag; - int finalRelDelta; - - if (args != null) - { - string? speech = args["speech"]?.ToString() ?? - args["reply"]?.ToString() ?? - args["dialogue"]?.ToString() ?? - args["text"]?.ToString() ?? - args["content"]?.ToString(); - - finalSpeech = !string.IsNullOrWhiteSpace(speech) ? speech!.Trim() : (!string.IsNullOrWhiteSpace(val.Content) ? val.Content.Trim() : string.Empty); - finalTag = SanitizeThoughtTag(args["thought_tag"]?.ToString()); - int relDelta = args["relation_delta"]?.Value() ?? 1; - finalRelDelta = Mathf.Clamp(relDelta, -5, 5); - } - else - { - finalSpeech = !string.IsNullOrWhiteSpace(val.Content) ? val.Content.Trim() : string.Empty; - finalTag = "FRIENDLY"; - finalRelDelta = 1; - } - - // Defensive JSON extraction: unwrap if finalSpeech contains or is wrapped in raw JSON object - if (finalSpeech.Contains("{") && finalSpeech.Contains("}")) + try { - try + int woodCount = map?.resourceCounter?.GetCount(ThingDefOf.WoodLog) ?? 0; + int steelCount = map?.resourceCounter?.GetCount(ThingDefOf.Steel) ?? 0; + int mealsCount = (map?.resourceCounter?.GetCount(ThingDefOf.MealSimple) ?? 0) + + (map?.resourceCounter?.GetCount(ThingDefOf.MealFine) ?? 0) + + (map?.resourceCounter?.GetCount(ThingDefOf.MealSurvivalPack) ?? 0); + float totalNutrition = map?.resourceCounter?.TotalHumanEdibleNutrition ?? 0f; + if (map?.listerThings != null && (mealsCount == 0 || totalNutrition <= 0.01f)) { - int sIdx = finalSpeech.IndexOf('{'); - int eIdx = finalSpeech.LastIndexOf('}'); - if (sIdx >= 0 && eIdx > sIdx) + var edibles = map.listerThings.ThingsInGroup(ThingRequestGroup.FoodSourceNotPlantOrTree); + if (edibles != null) { - string jsonCandidate = finalSpeech.Substring(sIdx, eIdx - sIdx + 1); - while (jsonCandidate.StartsWith("{{") && jsonCandidate.EndsWith("}}")) - { - jsonCandidate = jsonCandidate.Substring(1, jsonCandidate.Length - 2).Trim(); - } - try + int mapMeals = 0; + float mapNut = 0f; + for (int i = 0; i < edibles.Count; i++) { - var jObj = JObject.Parse(jsonCandidate); - string? inner = jObj["speech"]?.ToString() - ?? jObj["reply"]?.ToString() - ?? jObj["dialogue"]?.ToString() - ?? jObj["content"]?.ToString() - ?? jObj["text"]?.ToString(); - if (!string.IsNullOrWhiteSpace(inner)) - { - finalSpeech = inner!.Trim(); - } - if (string.IsNullOrEmpty(finalTag) || finalTag == "FRIENDLY") + var item = edibles[i]; + if (item == null || item.Destroyed || !item.Spawned || item is Corpse || item is Pawn) + continue; + if (item.Position.Fogged(map) || item.IsForbidden(Faction.OfPlayer)) + continue; + if (item.def?.ingestible == null || !item.def.IsNutritionGivingIngestible || !item.def.ingestible.HumanEdible) + continue; + if (item.def.ingestible.drugCategory != DrugCategory.None || item.def.ingestible.preferability < FoodPreferability.RawBad) + continue; + + float nutPerUnit = item.GetStatValue(StatDefOf.Nutrition); + if (nutPerUnit > 0f) { - var innerTag = jObj["thought_tag"]?.ToString(); - if (!string.IsNullOrWhiteSpace(innerTag)) finalTag = SanitizeThoughtTag(innerTag); + mapNut += nutPerUnit * Math.Max(1, item.stackCount); } - if (finalRelDelta == 1 && jObj["relation_delta"] != null) + if (item.def == ThingDefOf.MealSimple || item.def == ThingDefOf.MealFine || item.def == ThingDefOf.MealSurvivalPack) { - finalRelDelta = Mathf.Clamp(jObj["relation_delta"].Value(), -5, 5); - } - } - catch - { - var m = Regex.Match(jsonCandidate, @"""(?:speech|reply|dialogue|content|text)""\s*:\s*""(?(?:\\.|[^""\\])*)"""); - if (m.Success) - { - string unescaped = Regex.Unescape(m.Groups["val"].Value); - if (!string.IsNullOrWhiteSpace(unescaped)) - { - finalSpeech = unescaped.Trim(); - } + mapMeals += Math.Max(1, item.stackCount); } } + if (mapMeals > mealsCount) mealsCount = mapMeals; + if (mapNut > totalNutrition) totalNutrition = mapNut; } } - catch { } - } - - finalSpeech = StripModelXmlTags(finalSpeech); - - if (string.IsNullOrWhiteSpace(finalSpeech)) - { - if (recordInReport) - { - report.DialogueSpeaker = speaker.Name?.ToStringShort ?? "Speaker"; - report.DialogueListener = listener.Name?.ToStringShort ?? "Listener"; - report.DialogueSpeech = string.Empty; - report.DialogueThoughtTag = string.Empty; - report.DialogueRelationDelta = 0; - } - Log.Warning($"[RimMind-Playthrough][Day {day}] Dialogue failed ({speaker.Name.ToStringShort} -> {listener.Name.ToStringShort}): empty LLM response"); - } - else - { - RecordPlaythroughDialogue(speaker.Name.ToStringShort, listener.Name.ToStringShort, finalSpeech); + int blueprintsCount = map?.listerThings?.ThingsInGroup(ThingRequestGroup.Blueprint)?.Count ?? 0; + int framesCount = map?.listerThings?.ThingsInGroup(ThingRequestGroup.BuildingFrame)?.Count ?? 0; + int buildingsCount = map?.listerBuildings?.allBuildingsColonist?.Count ?? 0; + + var statePayload = new + { + day = day, + date = report.DateString, + startTick = report.StartTick, + endTick = report.EndTick, + colonists = PlaythroughPlayerSimulation.BuildColonistVitals(map, report.Colonists), + llmCalls = report.LlmCallsCount, + successfulLlmCalls = report.SuccessfulLlmCallsCount, + tokensUsed = report.TotalTokensUsed, + prefixTokens = report.PrefixTokens, + cacheHitRatio = report.CacheHitRatio, + llmCallsBySource = report.LlmCallsBySource, + agentActionsExecuted = report.AgentActionsExecutedCount, + agentActions = report.AgentActions, + dialogue = new + { + count = report.DialogueCount, + speaker = report.DialogueSpeaker, + listener = report.DialogueListener, + speech = report.DialogueSpeech, + thoughtTag = report.DialogueThoughtTag + }, + personality = new + { + pawn = report.MorningPawnName, + thought = report.MorningThought + }, + advisor = new + { + proposal = report.AdvisorProposal, + approved = report.AdvisorApproved + }, + memory = new + { + active = report.ActiveMemories, + archive = report.ArchiveMemories, + dark = report.DarkMemories + }, + mapStats = new + { + weather = map?.weatherManager?.curWeather?.label ?? "Clear", + outdoorTemp = Mathf.RoundToInt(map?.mapTemperature?.OutdoorTemp ?? 21f), + woodCount = woodCount, + steelCount = steelCount, + mealsCount = mealsCount, + foodNutrition = Mathf.Round(totalNutrition * 10f) / 10f, + unstockpiledFoodNutrition = Mathf.Round(PlaythroughPlayerSimulation.CountUnstockpiledNutrition(map) * 10f) / 10f, + totalAvailableNutrition = Mathf.Round(totalNutrition * 10f) / 10f, + medicineCount = PlaythroughPlayerSimulation.CountMedicine(map), + activeAlerts = PlaythroughPlayerSimulation.CollectActiveAlerts(), + openWindows = PlaythroughPlayerSimulation.CollectOpenWindows(), + colonistBuildingsCount = buildingsCount, + pendingConstructionCount = blueprintsCount + framesCount + }, + screenshot = Path.GetFileName(report.ScreenshotPath) + }; - if (recordInReport) - { - report.DialogueSpeaker = speaker.Name?.ToStringShort ?? "Speaker"; - report.DialogueListener = listener.Name?.ToStringShort ?? "Listener"; - report.DialogueSpeech = finalSpeech; - report.DialogueThoughtTag = finalTag; - report.DialogueRelationDelta = finalRelDelta; - } + string json = JsonConvert.SerializeObject(statePayload, Formatting.Indented); + string stateFilePath = Path.Combine(_outputDir, $"day-{day:D2}-state.json"); + File.WriteAllText(stateFilePath, json, Encoding.UTF8); - Log.Message($"[RimMind-Playthrough][Day {day}] Dialogue: {speaker.Name.ToStringShort} -> {listener.Name.ToStringShort}: \"{finalSpeech}\" (Tag: {finalTag}, Rel: {finalRelDelta})"); + MirrorFileIfDistinct(stateFilePath, Path.Combine(_legacyRunOutputDir, $"day-{day:D2}-state.json")); + MirrorFileIfDistinct(stateFilePath, Path.Combine(_bridgeDir, $"state_day_{day:D2}.json")); } - } - else - { - string errMsg = responseResult != null && !responseResult.Value.IsOk - ? responseResult.Value.Error.Message - : "LLM response timed out or returned null"; - if (recordInReport) + catch (Exception ex) { - report.DialogueSpeaker = speaker.Name?.ToStringShort ?? "Speaker"; - report.DialogueListener = listener.Name?.ToStringShort ?? "Listener"; - report.DialogueSpeech = string.Empty; - report.DialogueThoughtTag = string.Empty; - report.DialogueRelationDelta = 0; + Log.Warning($"[RimMind-Playthrough][Day {day}] ExportDailyStateJson notice: {ex.Message}"); } - Log.Warning($"[RimMind-Playthrough][Day {day}] Dialogue failed ({speaker.Name.ToStringShort} -> {listener.Name.ToStringShort}): {errMsg}"); - } - } - - private IEnumerator ExecuteAutonomousAgentAction(Pawn agentPawn, int day, PlaythroughDayReport report, bool recordInReport = true) - { - var runtimeScope = RuntimeServiceHub.Shared.Capture(); - var queue = runtimeScope.GetOptional(); - if (queue != null) - { - if (queue.TotalQueuedCount > 15) queue.CancelAllRequests(); - queue.ClearAllCooldowns(); } - RimMind.Presentation.Api.RimMindPawnLookup.CachePawn(agentPawn); - var agentComp = CompPawnAgent.GetComp(agentPawn); - if (agentComp != null) + private void SaveReportCheckpoint() { - agentComp.EnsureAgentCreated(); - bool anyOtherActive = GetLivingColonists().Any(c => - !ReferenceEquals(c, agentPawn) && CompPawnAgent.GetComp(c)?.Agent?.State == AgentState.Active); - if (!anyOtherActive && agentComp.Agent != null && agentComp.Agent.State != AgentState.Active) + try { - agentComp.Agent.TransitionTo(AgentState.Active); - } - } + string json = JsonConvert.SerializeObject(_report, Formatting.Indented); + string primaryName = $"playthrough-{_totalDays}days-report.json"; + string primaryPath = Path.Combine(_outputDir, primaryName); + File.WriteAllText(primaryPath, json, Encoding.UTF8); + MirrorFileIfDistinct(primaryPath, Path.Combine(_legacyRunOutputDir, primaryName)); - var tools = new List - { - new StructuredTool - { - Name = "prioritize_work", - Description = "Prioritize a critical colony labor task (e.g. Firefighting, Doctor, Warden, Growing, Crafting, Construction, Hauling, Cleaning)", - Parameters = "{\"type\":\"object\",\"properties\":{\"work_type\":{\"type\":\"string\"},\"reason\":{\"type\":\"string\"}},\"required\":[\"work_type\",\"reason\"]}" - }, - new StructuredTool - { - Name = "take_job", - Description = "Directly assign an immediate action job (e.g. HaulToStorage, CleanFilth, TendPatient, RepairBuilding, CutPlants)", - Parameters = "{\"type\":\"object\",\"properties\":{\"job_type\":{\"type\":\"string\"},\"target\":{\"type\":\"string\"},\"reason\":{\"type\":\"string\"}},\"required\":[\"job_type\",\"reason\"]}" - }, - new StructuredTool - { - Name = "place_blueprint", - Description = "Directly spawn a construction blueprint on the colony map to address urgent survival, cooling, housing, or logistics needs (e.g. Bed, PassiveCooler, Cooler, Campfire, SolarGenerator, Battery, Wall, Door, TableButcher, HandTailoringBench)", - Parameters = "{\"type\":\"object\",\"properties\":{\"building_def\":{\"type\":\"string\"},\"offset_x\":{\"type\":\"integer\"},\"offset_z\":{\"type\":\"integer\"},\"stuff_def\":{\"type\":\"string\"},\"reason\":{\"type\":\"string\"}},\"required\":[\"building_def\",\"reason\"]}" - }, - new StructuredTool - { - Name = "designate_map_order", - Description = "Directly designate harvesting, foraging, mining, or hauling orders on the map to resolve resource shortages or crises", - Parameters = "{\"type\":\"object\",\"properties\":{\"order_type\":{\"type\":\"string\",\"enum\":[\"Harvest\",\"Mine\",\"CutPlants\",\"Haul\"]},\"target\":{\"type\":\"string\"},\"reason\":{\"type\":\"string\"}},\"required\":[\"order_type\",\"reason\"]}" - }, - new StructuredTool - { - Name = "actions_query_buildable_structures", - Description = "Query catalog of available structures and furniture in colony with build cost and tech prerequisites (category: Furniture, Temperature, Structure, Production, Power)", - Parameters = "{\"type\":\"object\",\"properties\":{\"category\":{\"type\":\"string\"},\"search_keyword\":{\"type\":\"string\"}},\"required\":[]}" - }, - new StructuredTool - { - Name = "query_tool_help", - Description = "Query detailed usage instructions, schema and examples for a specific tool or composite mechanism", - Parameters = "{\"type\":\"object\",\"properties\":{\"tool_name\":{\"type\":\"string\"}},\"required\":[\"tool_name\"]}" - }, - new StructuredTool - { - Name = "eat_and_recreation", - Description = "Composite mechanism: satisfy urgent nourishment needs and enjoy social recreation to restore morale", - Parameters = "{\"type\":\"object\",\"properties\":{\"reason\":{\"type\":\"string\"}},\"required\":[\"reason\"]}" - }, - new StructuredTool - { - Name = "stabilize_rest", - Description = "Composite mechanism: find the nearest safe medical bed, bandage wounds, and rest to recover stamina", - Parameters = "{\"type\":\"object\",\"properties\":{\"reason\":{\"type\":\"string\"}},\"required\":[\"reason\"]}" - }, - new StructuredTool - { - Name = "actions_add_worktable_bill", - Description = "Add a production bill (e.g. CookMealSimple, CookMealFine, ButcherCorpseFlesh, Make_StoneBlocks, Make_Apparel_Parka) to an available colony worktable (Stove, Butcher table, Tailoring bench, Stonecutter table)", - Parameters = "{\"type\":\"object\",\"properties\":{\"recipe_def\":{\"type\":\"string\",\"description\":\"DefName of the recipe (e.g. CookMealSimple, CookMealFine, ButcherCorpseFlesh, Make_StoneBlocks, Make_Apparel_Parka)\"},\"target_count\":{\"type\":\"integer\",\"description\":\"Target stock or repeat count (default: 10)\"},\"reason\":{\"type\":\"string\"}},\"required\":[\"recipe_def\",\"reason\"]}" - }, - new StructuredTool - { - Name = "actions_manage_equipment", - Description = "Autonomously direct colonist to equip protective gear, weapon, or thermal apparel from storage for survival and safety", - Parameters = "{\"type\":\"object\",\"properties\":{\"purpose\":{\"type\":\"string\",\"enum\":[\"Thermal\",\"Armor\",\"Auto\"]},\"target_apparel_def\":{\"type\":\"string\",\"description\":\"Optional specific apparel/weapon defName to equip (e.g. Apparel_Parka, Apparel_Tuque, Apparel_FlakVest, Gun_BoltActionRifle)\"},\"reason\":{\"type\":\"string\"}},\"required\":[\"reason\"]}" - } - }; - - var envelope = LlmRequestEnvelopeBuilder - .ForScenario(RimMindAPI.Context.ScenarioDecision) - .WithModId("RimMind-Actions") - .WithNpcId("NPC-" + agentPawn.thingIDNumber) - .WithTools(tools) - .WithToolDispatchMode(ToolCallDispatchMode.Manual) - .WithMaxTokens(800) - .WithTemperature(0.6f) - .WithPriority(AIRequestPriority.High) - .Build(); - - envelope.Messages.Add(new ChatMessage - { - Role = "system", - LayerTag = "L0", - Content = "You are the autonomous colonist AI agent in RimWorld. You must choose ONE tool from [prioritize_work, take_job, place_blueprint, actions_add_worktable_bill, actions_manage_equipment, actions_query_buildable_structures, query_tool_help, designate_map_order, eat_and_recreation, stabilize_rest] to direct your next action." - }); - Map pawnMap = agentPawn.Map ?? Find.CurrentMap; - int woodCount = CountAvailableMapResource(pawnMap, ThingDefOf.WoodLog); - int steelCount = CountAvailableMapResource(pawnMap, ThingDefOf.Steel); - var compDef = DefDatabase.GetNamedSilentFail("ComponentIndustrial") - ?? DefDatabase.GetNamedSilentFail("ComponentsIndustrial"); - int compCount = CountAvailableMapResource(pawnMap, compDef); - int mealCount = CountAvailableMapResource(pawnMap, ThingDefOf.MealSimple) - + CountAvailableMapResource(pawnMap, ThingDefOf.MealFine) - + CountAvailableMapResource(pawnMap, ThingDefOf.MealSurvivalPack); - int pendingBlueprints = pawnMap?.listerThings?.ThingsInGroup(ThingRequestGroup.Blueprint)?.Count ?? 0; - int pendingFrames = pawnMap?.listerThings?.ThingsInGroup(ThingRequestGroup.BuildingFrame)?.Count ?? 0; - int pendingConstructionCount = pendingBlueprints + pendingFrames; - bool canPlaceMoreBlueprints = pendingConstructionCount < 2 && woodCount >= 115; - - bool hasHarvestablePlants = pawnMap?.listerThings?.AllThings? - .OfType() - .Any(p => p.Spawned && !p.Destroyed && !p.Position.Fogged(pawnMap) && - p.def?.plant != null && !p.def.plant.IsTree && p.def.plant.Harvestable && - (p.HarvestableNow || p.Growth >= 0.7f) && - pawnMap.designationManager.DesignationOn(p, DesignationDefOf.HarvestPlant) == null) ?? false; - - bool isZh = IsChineseLanguageActive(); - string agentTraits = string.Join(", ", agentPawn.story?.traits?.allTraits?.Select(t => t.LabelCap) ?? Enumerable.Empty()); - if (string.IsNullOrEmpty(agentTraits)) agentTraits = isZh ? "普通" : "None"; - int constructSkill = agentPawn.skills?.GetSkill(SkillDefOf.Construction)?.Level ?? 0; - int plantsSkill = agentPawn.skills?.GetSkill(SkillDefOf.Plants)?.Level ?? 0; - int miningSkill = agentPawn.skills?.GetSkill(SkillDefOf.Mining)?.Level ?? 0; - int cookingSkill = agentPawn.skills?.GetSkill(SkillDefOf.Cooking)?.Level ?? 0; - bool canConstruct = !agentPawn.WorkTagIsDisabled(WorkTags.ManualSkilled); - bool canCook = !agentPawn.WorkTagIsDisabled(WorkTags.Cooking); - bool hasBed = agentPawn.ownership?.OwnedBed != null; - var disabledWorkDefs = DefDatabase.AllDefsListForReading - .Where(w => agentPawn.WorkTypeIsDisabled(w)) - .Select(w => w.defName) - .ToList(); - string disabledWorkSummary = disabledWorkDefs.Count > 0 - ? string.Join(", ", disabledWorkDefs) - : (isZh ? "无" : "None"); - - envelope.Messages.Add(new ChatMessage - { - Role = "system", - LayerTag = "L1", - Content = isZh - ? $"Pawn: {agentPawn.Name.ToStringShort} [特质: {agentTraits}, 当前: {agentPawn.CurJobDef?.defName ?? "Idle"}, 心情: {agentPawn.needs?.mood?.CurLevelPercentage.ToString("P0") ?? "80%"}, 健康: {agentPawn.health?.summaryHealth?.SummaryHealthPercent.ToString("P0") ?? "100%"}]\n" + - $"技能等级: 建造({constructSkill}{(canConstruct ? "" : "-禁用")}), 烹饪({cookingSkill}{(canCook ? "" : "-禁用")}), 种植({plantsSkill}), 采掘({miningSkill}) | 禁用工作(严禁prioritize_work选择): {disabledWorkSummary}\n" + - $"营地物资库存: 木材 {woodCount} (安全底线: 80), 钢铁 {steelCount}, 零部件 {compCount}, 口粮 {mealCount} 份\n" + - $"施工队列: 待建蓝图/框架 {pendingConstructionCount} 个 (并发上限: 2) | 野外可采浆果/成熟作物: {(hasHarvestablePlants ? "有" : "无")}\n" + - $"居住现状: {(hasBed ? "已有固定床位" : "无专属床位(露宿泥地)")}" - : $"Pawn: {agentPawn.Name.ToStringShort} [Traits: {agentTraits}, Job: {agentPawn.CurJobDef?.defName ?? "Idle"}, Mood: {agentPawn.needs?.mood?.CurLevelPercentage.ToString("P0") ?? "80%"}, Health: {agentPawn.health?.summaryHealth?.SummaryHealthPercent.ToString("P0") ?? "100%"}]\n" + - $"Skills: Construction({constructSkill}{(canConstruct ? "" : "-Disabled")}), Cooking({cookingSkill}{(canCook ? "" : "-Disabled")}), Plants({plantsSkill}), Mining({miningSkill}) | Disabled WorkTypes (DO NOT pick in prioritize_work): {disabledWorkSummary}\n" + - $"Colony Stockpile: Wood {woodCount} (safety reserve: 80), Steel {steelCount}, Components {compCount}, Meals {mealCount}\n" + - $"Construction Queue: Pending blueprints/frames {pendingConstructionCount} (concurrency cap: 2) | Harvestable wild berries/mature crops: {(hasHarvestablePlants ? "Yes" : "No")}\n" + - $"Housing Status: {(hasBed ? "Has assigned bed" : "No bed (sleeping on ground)")}" - }); - - float outdoorTemp = pawnMap != null ? pawnMap.mapTemperature.OutdoorTemp : 21f; - float foodLevel = agentPawn.needs?.food?.CurLevelPercentage ?? 1f; - float moodLevel = agentPawn.needs?.mood?.CurLevelPercentage ?? 0.8f; - bool isIdle = agentPawn.CurJobDef == null || agentPawn.CurJobDef == JobDefOf.Wait_Wander || agentPawn.CurJobDef == JobDefOf.GotoWander; - - bool sleptOnGround = agentPawn.needs?.mood?.thoughts?.memories?.Memories? - .Any(m => m.def.defName.Contains("SleptOnGround")) == true && !hasBed; - - string statusContext; - if (isZh) - { - if ((sleptOnGround || !hasBed) && canPlaceMoreBlueprints) - { - statusContext = $"你正露宿在冰冷泥地上(缺少床铺,严重损害身心健康与心情;当前营地存有木材 {woodCount},待建蓝图 {pendingConstructionCount}/2)。你可调用 actions_query_buildable_structures 查询营地可用家具,或调用 place_blueprint 规划木床(Bed,需35木材),或调用 prioritize_work 优先建造作业。"; - } - else if (sleptOnGround || !hasBed) - { - string buildBlockReason = pendingConstructionCount >= 2 - ? $"当前已有 {pendingConstructionCount} 个待建蓝图/框架(已达并发上限 2,严禁调用 place_blueprint)" - : $"当前入库木材 {woodCount}(低于安全储备线+造价 115,严禁调用 place_blueprint)"; - statusContext = $"你尚未拥有专属床铺,但{buildBlockReason}!请调用 prioritize_work(work_type: \"Construction\") 推进现有蓝图施工,或调用 take_job(job_type: \"HaulToStorage\") 搬运木材,或调用 designate_map_order(order_type: \"CutPlants\", target: \"Tree\") 砍树补充木材。"; - } - else if (outdoorTemp > 35f) - { - statusContext = canPlaceMoreBlueprints - ? $"当前户外气温高达 {outdoorTemp:F0}°C,酷暑炙热。你可调用 place_blueprint 规划被动制冷器(PassiveCooler,需50木材),或调用 stabilize_rest 避暑休整。" - : $"当前户外气温高达 {outdoorTemp:F0}°C,酷暑炙热(待建蓝图 {pendingConstructionCount}/2,请勿新增蓝图)。请调用 stabilize_rest 避暑休整,或调用 prioritize_work(work_type: \"Construction\") 完成现有降温设施。"; - } - else if (outdoorTemp < 2f) - { - statusContext = canPlaceMoreBlueprints - ? $"当前户外严寒冰冻({outdoorTemp:F0}°C)。你可调用 place_blueprint 放置营火(Campfire,需20木材),或调用 prioritize_work 优先室内作业。" - : $"当前户外严寒冰冻({outdoorTemp:F0}°C,待建蓝图 {pendingConstructionCount}/2 或木材不足,严禁调用 place_blueprint)。请调用 prioritize_work(work_type: \"Construction\") 完成现有建筑,或调用 stabilize_rest / eat_and_recreation 在室内休整。"; - } - else if (foodLevel < 0.25f) - { - statusContext = hasHarvestablePlants - ? $"你感到胃部极度饥饿(饱腹度 {foodLevel:P0},营地现有存粮 {mealCount} 份)。你可调用 eat_and_recreation 进餐,或调用 designate_map_order(order_type: \"Harvest\") 圈定收割成熟作物/采摘浆果。" - : $"你感到胃部极度饥饿(饱腹度 {foodLevel:P0},营地现有存粮 {mealCount} 份)。请调用 eat_and_recreation 进餐与恢复心情,或调用 prioritize_work(work_type: \"Hauling\") 搬运散落食物。"; - } - else if (isIdle) - { - string skillHints = ""; - if (plantsSkill >= 4) skillHints += $",或利用植物专长(Lv.{plantsSkill})调用 designate_map_order(order_type: \"CutPlants\", target: \"Tree\") 伐木"; - if (miningSkill >= 4) skillHints += $",或利用采矿专长(Lv.{miningSkill})调用 designate_map_order(order_type: \"Mine\") 开采矿石"; - if (constructSkill >= 3 && canConstruct && canPlaceMoreBlueprints) skillHints += $",或规划餐桌/凳子/火把基础设施"; - statusContext = $"你当前处于空闲状态(营地存有木材 {woodCount},钢铁 {steelCount},待建蓝图 {pendingConstructionCount}/2)。你可调用 prioritize_work / take_job 推进营地作业{skillHints}。"; - } - else - { - statusContext = $"当前是殖民地第 {day} 天。你正处于日常活动中(营地存有木材 {woodCount},钢铁 {steelCount},待建蓝图 {pendingConstructionCount}/2),请权衡自身特长与营地建设需求,调用最适工具做出行动决策。"; - } - } - else - { - if ((sleptOnGround || !hasBed) && canPlaceMoreBlueprints) - { - statusContext = $"You are sleeping on the ground without a bed (Wood: {woodCount}, pending blueprints: {pendingConstructionCount}/2). You may call actions_query_buildable_structures, place_blueprint for a Bed (35 wood), or prioritize_work for Construction."; - } - else if (sleptOnGround || !hasBed) - { - string buildBlockReason = pendingConstructionCount >= 2 - ? $"there are already {pendingConstructionCount} pending blueprints/frames (cap: 2, do NOT call place_blueprint)" - : $"stockpiled wood is {woodCount} (below reserve threshold 115, do NOT call place_blueprint)"; - statusContext = $"You do not have an assigned bed yet, but {buildBlockReason}! Call prioritize_work(work_type: \"Construction\"), take_job(job_type: \"HaulToStorage\"), or designate_map_order(order_type: \"CutPlants\", target: \"Tree\") to chop wood."; - } - else if (outdoorTemp > 35f) - { - statusContext = canPlaceMoreBlueprints - ? $"Outdoor temperature is {outdoorTemp:F0}°C (extreme heat). You may call place_blueprint for a PassiveCooler (50 wood) or stabilize_rest." - : $"Outdoor temperature is {outdoorTemp:F0}°C (pending blueprints {pendingConstructionCount}/2, do not place new blueprints). Call stabilize_rest or prioritize_work(work_type: \"Construction\")."; - } - else if (outdoorTemp < 2f) - { - statusContext = canPlaceMoreBlueprints - ? $"Outdoor temperature is freezing ({outdoorTemp:F0}°C). You may call place_blueprint for a Campfire (20 wood) or prioritize_work." - : $"Outdoor temperature is freezing ({outdoorTemp:F0}°C, pending blueprints {pendingConstructionCount}/2 or low wood, do not call place_blueprint). Call prioritize_work(work_type: \"Construction\"), stabilize_rest, or eat_and_recreation."; - } - else if (foodLevel < 0.25f) - { - statusContext = hasHarvestablePlants - ? $"You are very hungry (Food: {foodLevel:P0}, Meals: {mealCount}). Call eat_and_recreation or designate_map_order(order_type: \"Harvest\") to harvest mature crops/berries." - : $"You are very hungry (Food: {foodLevel:P0}, Meals: {mealCount}). Call eat_and_recreation or prioritize_work(work_type: \"Hauling\")."; - } - else if (isIdle) - { - string skillHints = ""; - if (plantsSkill >= 4) skillHints += $", or use Plants(Lv.{plantsSkill}) with designate_map_order(order_type: \"CutPlants\", target: \"Tree\")"; - if (miningSkill >= 4) skillHints += $", or use Mining(Lv.{miningSkill}) with designate_map_order(order_type: \"Mine\")"; - if (constructSkill >= 3 && canConstruct && canPlaceMoreBlueprints) skillHints += $", or place basic furniture blueprints"; - statusContext = $"You are currently idle (Wood: {woodCount}, Steel: {steelCount}, pending blueprints: {pendingConstructionCount}/2). Call prioritize_work or take_job to advance colony work{skillHints}."; + if (_totalDays != 10) + { + string compatPath = Path.Combine(_outputDir, "playthrough-10days-report.json"); + File.WriteAllText(compatPath, json, Encoding.UTF8); + MirrorFileIfDistinct(compatPath, Path.Combine(_legacyRunOutputDir, "playthrough-10days-report.json")); + } + + GeneratePlaythroughChronicle(); } - else + catch (Exception ex) { - statusContext = $"It is Colony Day {day} (Wood: {woodCount}, Steel: {steelCount}, pending blueprints: {pendingConstructionCount}/2). Choose the most appropriate tool for your skills and colony needs."; + Log.Warning("[RimMind-Playthrough] Failed to save report checkpoint: " + ex.Message); } } - var stoveTables = pawnMap?.listerBuildings?.allBuildingsColonist? - .OfType() - .Where(w => w != null && !w.Destroyed && (w.def.defName.Contains("Stove") || w.def.defName.Contains("Campfire"))) - .ToList() ?? new List(); - bool hasStove = stoveTables.Count > 0; - bool hasCookBill = stoveTables.Any(w => w.billStack?.Bills?.Any(b => b != null && !b.suspended && b.recipe?.defName != null && b.recipe.defName.IndexOf("CookMeal", StringComparison.OrdinalIgnoreCase) >= 0) == true); - bool anyStoveHasFuel = stoveTables.Any(w => - { - var refuel = w.GetComp(); - return refuel == null || refuel.HasFuel; - }); - - if (!hasStove) { statusContext += isZh ? " 当前营地尚未建成料理台或篝火(严禁调用 actions_add_worktable_bill 挂单烹饪!),请先推进现有建造或采集。" : " Note: No stove or campfire is built on the map yet (do NOT call actions_add_worktable_bill for cooking!)."; } else if (mealCount < 10 && hasStove) + private void GeneratePlaythroughChronicle() { - var rawCat = DefDatabase.GetNamedSilentFail("FoodRaw"); - var rawFoodCount = (rawCat != null && pawnMap?.resourceCounter != null) ? pawnMap.resourceCounter.GetCountIn(rawCat) : 0; - if (rawFoodCount <= 0 && rawCat != null && pawnMap?.listerThings != null) - { - rawFoodCount = pawnMap.listerThings.ThingsInGroup(ThingRequestGroup.FoodSourceNotPlantOrTree) - .Where(t => t != null && t.Spawned && !t.IsForbidden(Faction.OfPlayer) && t.def?.thingCategories != null && t.def.thingCategories.Contains(rawCat)) - .Sum(t => t.stackCount); - } - if (rawFoodCount <= 0) + try { - if (hasHarvestablePlants) - { - statusContext += isZh - ? $" 营地熟食紧缺且生食材匮乏(严禁调用 actions_add_worktable_bill),当前地图有成熟野生植物/作物,请优先调用 designate_map_order(order_type: \"Harvest\") 圈定收割采集!" - : $" Meals and raw ingredients are scarce (do NOT call actions_add_worktable_bill); mature plants/crops are available on the map, so prioritize designate_map_order(order_type: \"Harvest\")!"; - } - else - { - statusContext += isZh - ? $" 营地生食材匮乏且当前季节无野生浆果/成熟作物可收割(严禁调用 actions_add_worktable_bill 或 designate_map_order(Harvest)),请调用 prioritize_work、take_job 或 designate_map_order(order_type: \"CutPlants\", target: \"Tree\") 维持营地运转!" - : $" Raw ingredients are scarce and no harvestable crops/berries are ready (do NOT call actions_add_worktable_bill or designate_map_order(Harvest)); call prioritize_work, take_job, or designate_map_order(order_type: \"CutPlants\", target: \"Tree\")!"; + var sb = new StringBuilder(); + sb.AppendLine($"# RimMind {_totalDays}-Day Genuine In-Game AI Playthrough Chronicle"); + sb.AppendLine(); + sb.AppendLine($"> **Run ID**: `{_report.RunId}`"); + sb.AppendLine($"> **Endpoint / Model**: `{_report.Endpoint}` (`{_report.Model}`)"); + sb.AppendLine($"> **Elapsed**: {_report.TotalDurationMs / 1000f:F1}s | **Total Ticks**: {_report.TotalTicksElapsed:N0} ({_report.TotalDaysCompleted}/{_totalDays} days)"); + sb.AppendLine($"> **Real LLM Calls**: {_report.TotalLiveLlmRequests} ({_report.SuccessfulLiveLlmRequests} succeeded) | **Total Tokens**: {_report.TotalTokensConsumed:N0} | **Prefix Tokens**: {_report.TotalPrefixTokens:N0} (`{_report.CacheHitRatio:F1}%` cache hit)"); + if (_report.LlmCallsBySource.Count > 0) + { + string bySource = string.Join(", ", _report.LlmCallsBySource.Select(kv => $"`{kv.Key}`: {kv.Value}")); + sb.AppendLine($"> **Calls By Subsystem**: {bySource}"); } - } - else if (hasCookBill) - { - if (!anyStoveHasFuel && woodCount <= 0) + sb.AppendLine(); + sb.AppendLine("---"); + sb.AppendLine(); + + foreach (var d in _report.Days) { - statusContext += isZh - ? $" 料理台已存在 CookMealSimple 烹饪清单(严禁重复调用 actions_add_worktable_bill!),但当前料理台缺乏木材燃料(木材=0),请优先调用 designate_map_order(order_type: \"Harvest\", target: \"Tree\") 砍伐树木补充燃料或调用 prioritize_work 推进搬运/烹饪!" - : $" Stove already has a CookMealSimple bill (do NOT call actions_add_worktable_bill!), but lacks wood fuel (Wood=0); call designate_map_order(order_type: \"Harvest\", target: \"Tree\") or prioritize_work!"; + sb.AppendLine($"## Day {d.DayNumber} · {d.DateString} (Ticks {d.StartTick}–{d.EndTick})"); + sb.AppendLine(); + sb.AppendLine($"- **LLM Requests Today**: {d.LlmCallsCount} ({d.SuccessfulLlmCallsCount} succeeded) | **Tokens**: {d.TotalTokensUsed} (Prefix: {d.PrefixTokens}, CacheHit: `{d.CacheHitRatio:F1}%`) | **Duration**: {d.DayComputeDurationMs}ms"); + sb.AppendLine($"- **Personality ({d.MorningPawnName})**: {d.MorningThought}"); + sb.AppendLine($"- **PawnAgent Actions ({d.AgentActionsExecutedCount})**: {d.AgentActionDetail}"); + if (!string.IsNullOrWhiteSpace(d.DialogueSpeech)) + { + sb.AppendLine($"- **Dialogue ({d.DialogueCount})**: **{d.DialogueSpeaker}** → **{d.DialogueListener}**: *\"{d.DialogueSpeech}\"* (`{d.DialogueThoughtTag}`)"); + } + else + { + sb.AppendLine("- **Dialogue**: No dialogue recorded today"); + } + sb.AppendLine($"- **Advisor**: {d.AdvisorProposal} (Approved: {d.AdvisorApproved})"); + sb.AppendLine($"- **Memory Store**: Active={d.ActiveMemories}, Archive={d.ArchiveMemories}, Dark={d.DarkMemories}"); + if (!string.IsNullOrWhiteSpace(d.ScreenshotPath)) + { + sb.AppendLine($"- **Screenshot**: `{Path.GetFileName(d.ScreenshotPath)}`"); + } + sb.AppendLine(); } - else + + string content = sb.ToString(); + string primaryName = $"playthrough-{_totalDays}days-chronicle.md"; + string primaryPath = Path.Combine(_outputDir, primaryName); + File.WriteAllText(primaryPath, content, Encoding.UTF8); + MirrorFileIfDistinct(primaryPath, Path.Combine(_legacyRunOutputDir, primaryName)); + + if (_totalDays != 10) { - statusContext += isZh - ? $" 料理台已存在 CookMealSimple 烹饪清单(严禁重复调用 actions_add_worktable_bill!),请调用 prioritize_work(work_type: \"Cooking\" 或 \"Hauling\") 或 take_job 推进营地作业!" - : $" Stove already has a CookMealSimple bill (do NOT call actions_add_worktable_bill!); call prioritize_work(work_type: \"Cooking\" or \"Hauling\") or take_job!"; + string compatPath = Path.Combine(_outputDir, "playthrough-10days-chronicle.md"); + File.WriteAllText(compatPath, content, Encoding.UTF8); + MirrorFileIfDistinct(compatPath, Path.Combine(_legacyRunOutputDir, "playthrough-10days-chronicle.md")); } } - else if (!anyStoveHasFuel && woodCount <= 0) - { - statusContext += isZh - ? $" 营地料理台当前缺乏木材燃料(木材=0,严禁调用 actions_add_worktable_bill),请先调用 designate_map_order(order_type: \"Harvest\", target: \"Tree\") 砍伐树木获取燃料!" - : $" Stove currently lacks wood fuel (Wood=0, do NOT call actions_add_worktable_bill); call designate_map_order(order_type: \"Harvest\", target: \"Tree\") first!"; - } - else + catch (Exception ex) { - statusContext += isZh - ? $" 【最高优先级任务】营地熟食口粮紧缺(存粮 {mealCount},生料存有 {rawFoodCount}),已建造料理台且尚无烹饪清单。请立即优先调用 actions_add_worktable_bill(recipe_def: \"CookMealSimple\", target_count: 10) 挂单制作简单食物!" - : $" [CRITICAL PRIORITY] Meals are low (Meals: {mealCount}, Raw food: {rawFoodCount}) and the built stove has no active cook bill. Immediately call actions_add_worktable_bill(recipe_def: \"CookMealSimple\", target_count: 10) to start cooking meals!"; + Log.Warning("[RimMind-Playthrough] Failed to generate chronicle: " + ex.Message); } } - string failureHint = ""; - if (_recentActionFailures.TryGetValue(agentPawn.thingIDNumber, out var lastFail) && !string.IsNullOrEmpty(lastFail)) - { - failureHint = isZh - ? $" 【动作失败经验反思】你此前尝试的行动未成功: {lastFail}。请在本次决策中吸取教训,避免重复失败,选择切实可行、资源充足的动作。" - : $" [Prior Action Failure Reflection] Your previous action failed: {lastFail}. Choose a feasible action with sufficient resources instead."; - } - - string afternoonPrompt = isZh - ? $"【自主决策断点】{statusContext}{failureHint}" - : $"[Autonomous Decision Checkpoint] {statusContext}{failureHint}"; - - envelope.Messages.Add(new ChatMessage - { - Role = "user", - LayerTag = "L4", - Content = afternoonPrompt - }); - - bool completed = false; - Result? responseResult = null; - - queue?.ClearAllCooldowns(); - RimMindAPI.Send(envelope, res => + private static void MirrorFileIfDistinct(string sourcePath, string targetPath) { - responseResult = res; - completed = true; - }); + try + { + if (string.IsNullOrWhiteSpace(sourcePath) || string.IsNullOrWhiteSpace(targetPath)) return; + if (string.Equals(Path.GetFullPath(sourcePath), Path.GetFullPath(targetPath), StringComparison.OrdinalIgnoreCase)) + return; - _report.TotalLiveLlmRequests++; + string? dir = Path.GetDirectoryName(targetPath); + if (!string.IsNullOrWhiteSpace(dir) && !Directory.Exists(dir)) + Directory.CreateDirectory(dir); - float timeout = 95f; - float elapsed = 0f; - while (!completed && elapsed < timeout) - { - if (Find.TickManager != null) Find.TickManager.CurTimeSpeed = TimeSpeed.Paused; - elapsed += Time.unscaledDeltaTime; - if (queue is ITickableRequestQueue tq) - { - tq.CurrentTick += 5; - tq.Tick(); + File.Copy(sourcePath, targetPath, overwrite: true); } - DismissModalWindows(Find.CurrentMap); - yield return null; + catch { } } - if (completed && responseResult != null && responseResult.Value.IsOk) + private static void DismissExcessLetters() { - var val = responseResult.Value.Value; - report.TotalTokensUsed += val.TokensUsed; - - var extracted = ExtractToolCall(val.ToolCallsJson, val.Content); - var argsObj = extracted.Arguments; - string? toolName = extracted.ToolName; - string detail = ""; - string reason = !string.IsNullOrWhiteSpace(val.Content) ? val.Content.Trim() : ""; - - // Only infer toolName when an unambiguous parameter key is present; never fallback to a fake default tool - if (string.IsNullOrWhiteSpace(toolName) && argsObj != null) - { - if (argsObj.TryGetValue("building_def", StringComparison.OrdinalIgnoreCase, out _)) - toolName = "place_blueprint"; - else if (argsObj.TryGetValue("work_type", StringComparison.OrdinalIgnoreCase, out _)) - toolName = "prioritize_work"; - else if (argsObj.TryGetValue("job_type", StringComparison.OrdinalIgnoreCase, out _)) - toolName = "take_job"; - else if (argsObj.TryGetValue("order_type", StringComparison.OrdinalIgnoreCase, out _)) - toolName = "designate_map_order"; - else if (argsObj.TryGetValue("recipe_def", StringComparison.OrdinalIgnoreCase, out _)) - toolName = "actions_add_worktable_bill"; - else if (argsObj.TryGetValue("target_apparel_def", StringComparison.OrdinalIgnoreCase, out _)) - toolName = "actions_manage_equipment"; - else if (argsObj.TryGetValue("category", StringComparison.OrdinalIgnoreCase, out _)) - toolName = "actions_query_buildable_structures"; - else if (argsObj.TryGetValue("tool_name", StringComparison.OrdinalIgnoreCase, out _)) - toolName = "query_tool_help"; - } - - // Multi-turn Round 1 -> Round 2 when model invokes a sensory query tool - if (string.Equals(toolName, "actions_query_buildable_structures", StringComparison.OrdinalIgnoreCase)) + try { - string cat = argsObj != null && argsObj.TryGetValue("category", StringComparison.OrdinalIgnoreCase, out var cTok) ? cTok.ToString() : "All"; - string queryArgsJson = argsObj != null ? argsObj.ToString(Newtonsoft.Json.Formatting.None) : $"{{\"category\":\"{cat}\"}}"; + var letters = Find.LetterStack?.LettersListForReading; + if (letters == null) return; - string realQueryOutput = ""; - var registeredQueryTool = RimMindAPI.Tools.FindById("actions_query_buildable_structures"); - if (registeredQueryTool != null) - { - var toolCallArgs = new RimMind.Application.Common.Models.Tools.ToolCallArgs - { - ToolCallId = Guid.NewGuid().ToString("N"), - ToolName = "actions_query_buildable_structures", - ArgumentsJson = queryArgsJson, - PawnId = agentPawn.thingIDNumber, - Ct = System.Threading.CancellationToken.None - }; - var qExec = registeredQueryTool.ExecuteAsync(toolCallArgs, System.Threading.CancellationToken.None).GetAwaiter().GetResult(); - if (qExec.IsOk && !string.IsNullOrWhiteSpace(qExec.Value.Content)) - { - realQueryOutput = qExec.Value.Content!; - } - } - if (string.IsNullOrWhiteSpace(realQueryOutput)) + int safetyLimit = 200; + while (letters.Count > 5 && safetyLimit-- > 0) { - var buildables = GetBuildableStructuresForRunner(pawnMap, cat, woodCount, steelCount, compCount); - realQueryOutput = string.Join("\n", buildables); + Find.LetterStack!.RemoveLetter(letters[0]); } + } + catch { } + } - string r2ActionGuidance = isZh - ? (canPlaceMoreBlueprints - ? $"请根据当前小人的生存需求与营地储备(现有木材 {woodCount},待建蓝图 {pendingConstructionCount}/2),立即调用终端动作工具(如 place_blueprint, prioritize_work, take_job, stabilize_rest)执行物理落地动作!" - : $"注意:当前待建蓝图/框架已有 {pendingConstructionCount} 个(并发上限 2)或木材不足(现有 {woodCount},安全底线 80),严禁调用 place_blueprint!请立即调用 prioritize_work(work_type: \"Construction\")、take_job 或 designate_map_order(order_type: \"CutPlants\", target: \"Tree\") 执行物理落地动作!") - : (canPlaceMoreBlueprints - ? $"Based on this colonist's survival needs and colony reserves (Wood: {woodCount}, pending blueprints: {pendingConstructionCount}/2), immediately invoke a terminal action tool (such as place_blueprint, prioritize_work, take_job, stabilize_rest) to execute a physical action!" - : $"Note: There are already {pendingConstructionCount} pending blueprints/frames (max 2) or insufficient Wood ({woodCount}, safety floor 80) — DO NOT call place_blueprint! Immediately invoke prioritize_work(work_type: \"Construction\"), take_job, or designate_map_order(order_type: \"CutPlants\", target: \"Tree\") to execute a physical action!"); - - string queryObservation = isZh - ? $"[Tool Result: actions_query_buildable_structures]\n{realQueryOutput}\n【闭环指示】你已获取可用建筑与消耗清单。{r2ActionGuidance}" - : $"[Tool Result: actions_query_buildable_structures]\n{realQueryOutput}\n[Closed-Loop Instruction] You have retrieved the buildable structures and cost list. {r2ActionGuidance}"; - - var r2Envelope = LlmRequestEnvelopeBuilder - .ForScenario(RimMindAPI.Context.ScenarioDecision) - .WithModId("RimMind-Actions") - .WithNpcId("NPC-" + agentPawn.thingIDNumber) - .WithTools(tools) - .WithToolDispatchMode(ToolCallDispatchMode.Manual) - .WithMaxTokens(800) - .WithTemperature(0.5f) - .WithPriority(AIRequestPriority.High) - .Build(); - - foreach (var m in envelope.Messages) - { - r2Envelope.Messages.Add(m); - } - r2Envelope.Messages.Add(new ChatMessage - { - Role = "assistant", - LayerTag = "L4", - Content = !string.IsNullOrWhiteSpace(val.Content) - ? val.Content - : (isZh ? $"已调用 actions_query_buildable_structures(category: \"{cat}\")" : $"Invoked actions_query_buildable_structures(category: \"{cat}\")") - }); - r2Envelope.Messages.Add(new ChatMessage - { - Role = "user", - LayerTag = "L4", - Content = queryObservation - }); + private static void DismissModalWindows(Map? map) + { + try + { + DismissExcessLetters(); - bool r2Completed = false; - Result? r2Res = null; - if (queue != null) + if (Find.FactionManager?.OfPlayer != null && !Find.FactionManager.OfPlayer.HasName) { - if (queue.TotalQueuedCount > 15) queue.CancelAllRequests(); - queue.ClearAllCooldowns(); + NamePlayerFactionDialogUtility.Named("RimMind Federation"); } - RimMindAPI.Send(r2Envelope, res => - { - r2Res = res; - r2Completed = true; - }); - _report.TotalLiveLlmRequests++; - float r2Timeout = 65f; - float r2Elapsed = 0f; - while (!r2Completed && r2Elapsed < r2Timeout) + if (map?.info?.parent is RimWorld.Planet.Settlement playerSettlement) { - if (Find.TickManager != null) Find.TickManager.CurTimeSpeed = TimeSpeed.Paused; - r2Elapsed += Time.unscaledDeltaTime; - if (queue is ITickableRequestQueue tq) + if (!playerSettlement.HasName || !playerSettlement.namedByPlayer) { - tq.CurrentTick += 5; - tq.Tick(); + NamePlayerSettlementDialogUtility.Named(playerSettlement, playerSettlement.HasName ? playerSettlement.Name : "RimMind Prime"); } - DismissModalWindows(Find.CurrentMap); - yield return null; } - if (r2Completed && r2Res != null && r2Res.Value.IsOk) - { - var r2Val = r2Res.Value.Value; - report.TotalTokensUsed += r2Val.TokensUsed; - var r2Extracted = ExtractToolCall(r2Val.ToolCallsJson, r2Val.Content); - toolName = r2Extracted.ToolName; - argsObj = r2Extracted.Arguments; + if (Find.WindowStack?.Windows == null) return; - if (string.IsNullOrWhiteSpace(toolName) && argsObj != null) - { - if (argsObj.TryGetValue("building_def", StringComparison.OrdinalIgnoreCase, out _)) - toolName = "place_blueprint"; - else if (argsObj.TryGetValue("work_type", StringComparison.OrdinalIgnoreCase, out _)) - toolName = "prioritize_work"; - else if (argsObj.TryGetValue("job_type", StringComparison.OrdinalIgnoreCase, out _)) - toolName = "take_job"; - else if (argsObj.TryGetValue("order_type", StringComparison.OrdinalIgnoreCase, out _)) - toolName = "designate_map_order"; - else if (argsObj.TryGetValue("recipe_def", StringComparison.OrdinalIgnoreCase, out _)) - toolName = "actions_add_worktable_bill"; - else if (argsObj.TryGetValue("target_apparel_def", StringComparison.OrdinalIgnoreCase, out _)) - toolName = "actions_manage_equipment"; - } - - if (argsObj != null && argsObj.TryGetValue("reason", StringComparison.OrdinalIgnoreCase, out var rTok2)) - { - reason = $"[闭环决策] {rTok2}"; - } - else if (!string.IsNullOrWhiteSpace(r2Val.Content)) - { - reason = $"[闭环决策] {r2Val.Content.Trim()}"; - } - } - else - { - toolName = null; - } - } - - if (string.IsNullOrWhiteSpace(toolName)) - { - string noToolMsg = "LLM response did not contain a valid tool call"; - Log.Warning($"[RimMind-Playthrough][Day {day}] Agent Decision failed ({agentPawn.Name?.ToStringShort}): {noToolMsg}"); - _recentActionFailures[agentPawn.thingIDNumber] = noToolMsg; - if (recordInReport) - { - report.AgentActionPawn = agentPawn.Name?.ToStringShort ?? "Agent"; - report.AgentActionTool = "failed"; - report.AgentActionDetail = $"[No ToolCall] {noToolMsg}"; - report.AgentActionReason = reason; - } - yield break; - } - - if (argsObj != null && argsObj.TryGetValue("reason", StringComparison.OrdinalIgnoreCase, out var rTok) && !reason.StartsWith("[闭环决策]")) - { - reason = rTok.ToString(); - } - - if (string.Equals(toolName, "place_blueprint", StringComparison.OrdinalIgnoreCase)) - { - string bDef = argsObj != null && argsObj.TryGetValue("building_def", StringComparison.OrdinalIgnoreCase, out var bDefTok) ? bDefTok.ToString() : "Bed"; - int ox = argsObj != null && argsObj.TryGetValue("offset_x", StringComparison.OrdinalIgnoreCase, out var oxTok) && int.TryParse(oxTok.ToString(), out var parsedOx) ? parsedOx : 0; - int oz = argsObj != null && argsObj.TryGetValue("offset_z", StringComparison.OrdinalIgnoreCase, out var ozTok) && int.TryParse(ozTok.ToString(), out var parsedOz) ? parsedOz : 0; - IntVec3 targetCell = (pawnMap != null && !agentPawn.Position.InHorDistOf(pawnMap.Center, 28f) ? pawnMap.Center : agentPawn.Position) + new IntVec3(ox, 0, oz); - detail = isZh ? $"规划蓝图: {bDef} 于 ({targetCell.x}, {targetCell.z})" : $"Place blueprint: {bDef} at ({targetCell.x}, {targetCell.z})"; - } - else if (string.Equals(toolName, "prioritize_work", StringComparison.OrdinalIgnoreCase)) - { - string wt = argsObj != null && argsObj.TryGetValue("work_type", StringComparison.OrdinalIgnoreCase, out var wtTok) ? wtTok.ToString() : "Hauling"; - detail = isZh ? $"优先工种: {wt}" : $"Prioritize work: {wt}"; - } - else if (string.Equals(toolName, "take_job", StringComparison.OrdinalIgnoreCase)) - { - string jt = argsObj != null && argsObj.TryGetValue("job_type", StringComparison.OrdinalIgnoreCase, out var jtTok) ? jtTok.ToString() : "HaulToStorage"; - string target = argsObj != null && argsObj.TryGetValue("target", StringComparison.OrdinalIgnoreCase, out var tg) ? tg.ToString() : "Nearby"; - detail = isZh ? $"执行作业: {jt} ({target})" : $"Take job: {jt} ({target})"; - } - else if (string.Equals(toolName, "designate_map_order", StringComparison.OrdinalIgnoreCase)) - { - string ot = argsObj != null && argsObj.TryGetValue("order_type", StringComparison.OrdinalIgnoreCase, out var otTok) ? otTok.ToString() : "Harvest"; - string target = argsObj != null && argsObj.TryGetValue("target", StringComparison.OrdinalIgnoreCase, out var tgTok) ? tgTok.ToString() : "Nearby"; - detail = isZh ? $"下发地图指令: {ot} ({target})" : $"Designate map order: {ot} ({target})"; - } - else if (string.Equals(toolName, "eat_and_recreation", StringComparison.OrdinalIgnoreCase)) - { - detail = isZh ? "进餐与娱乐恢复(Actions Mechanism)" : "Eat and recreation recovery (Actions Mechanism)"; - } - else if (string.Equals(toolName, "stabilize_rest", StringComparison.OrdinalIgnoreCase)) - { - detail = isZh ? "就医与卧床休整(Actions Mechanism)" : "Stabilize and bed rest (Actions Mechanism)"; - } - else if (string.Equals(toolName, "actions_add_worktable_bill", StringComparison.OrdinalIgnoreCase)) - { - string rDef = argsObj != null && argsObj.TryGetValue("recipe_def", StringComparison.OrdinalIgnoreCase, out var rdTok) ? rdTok.ToString() : "CookMealSimple"; - int count = argsObj != null && argsObj.TryGetValue("target_count", StringComparison.OrdinalIgnoreCase, out var cTok) && int.TryParse(cTok.ToString(), out int parsedCount) ? parsedCount : 10; - detail = isZh ? $"工作台挂单: {rDef} (目标数: {count})" : $"Add worktable bill: {rDef} (target: {count})"; - } - else if (string.Equals(toolName, "actions_manage_equipment", StringComparison.OrdinalIgnoreCase)) - { - string targetGear = argsObj != null && argsObj.TryGetValue("target_apparel_def", StringComparison.OrdinalIgnoreCase, out var tgTok) ? tgTok.ToString() : "Auto"; - detail = isZh ? $"装备调配与穿戴: {targetGear}" : $"Manage apparel & equipment: {targetGear}"; - } - else - { - detail = isZh ? $"调用工具: {toolName}" : $"Invoke tool: {toolName}"; - } - - // Dispatch autonomous action strictly through the production PawnAgent pipeline (no inline duplicate execution) - bool execFailed = false; - string execErr = ""; - RimMind.Presentation.Api.RimMindPawnLookup.CachePawn(agentPawn); - if (agentComp?.Agent != null) - { - var payloadObj = argsObj != null - ? (Newtonsoft.Json.Linq.JObject)argsObj.DeepClone() - : new Newtonsoft.Json.Linq.JObject(); - if (payloadObj["pawn_id"] == null && payloadObj["npc_id"] == null) - { - payloadObj["pawn_id"] = "NPC-" + agentPawn.thingIDNumber; - } - string paramJson = payloadObj.ToString(Newtonsoft.Json.Formatting.None); - var decision = new AgentDecision( - toolName, - reason, - null, - paramJson); - var execOutcome = agentComp.Agent.ExecuteDecision(decision); - if (!execOutcome.IsOk) - { - execFailed = true; - execErr = execOutcome.Error.Message; - } - } - - if (execFailed) - { - _recentActionFailures[agentPawn.thingIDNumber] = execErr; - if (recordInReport) - { - report.AgentActionPawn = agentPawn.Name?.ToStringShort ?? "Agent"; - report.AgentActionTool = $"{toolName} (failed)"; - report.AgentActionDetail = $"[Physical Failed] {detail} -> {execErr}"; - report.AgentActionReason = reason; - } - Log.Warning($"[RimMind-Playthrough][Day {day}] Agent Physical Execution Failed ({agentPawn.Name?.ToStringShort}): [{toolName}] {execErr}"); - } - else - { - _recentActionFailures.Remove(agentPawn.thingIDNumber); - if (recordInReport) - { - report.AgentActionPawn = agentPawn.Name?.ToStringShort ?? "Agent"; - report.AgentActionTool = toolName; - report.AgentActionDetail = detail; - report.AgentActionReason = reason; - } - Log.Message($"[RimMind-Playthrough][Day {day}] Agent Decision ({agentPawn.Name?.ToStringShort}): [{toolName}] {detail} - \"{reason}\""); - } - } - else - { - string errMsg = responseResult != null && !responseResult.Value.IsOk ? responseResult.Value.Error.Message : "LLM response timed out or returned null"; - Log.Warning($"[RimMind-Playthrough][Day {day}] Agent Decision execution failed ({agentPawn.Name.ToStringShort}): {errMsg}"); - - _recentActionFailures[agentPawn.thingIDNumber] = errMsg; - - if (recordInReport) - { - report.AgentActionPawn = agentPawn.Name?.ToStringShort ?? "Agent"; - report.AgentActionTool = "failed"; - report.AgentActionDetail = $"[Execution Failed] {errMsg}"; - report.AgentActionReason = $"Physical execution failed: {errMsg}"; - } - - // Explicitly record physical failure to working memory for agent to learn and self-correct next round - try - { - RimMindAPI.Memory.AddPawnMemory( - $"[Action Failed] Autonomous action failed: {errMsg}", - RimMind.Application.Common.Models.Memory.MemoryKind.Event, - Find.TickManager.TicksGame, - 0.8f, - agentPawn.ThingID); - } - catch (Exception) { } - } - } - - private static List GetBuildableStructuresForRunner(Map? map, string category, int woodCount, int steelCount, int compCount) - { - bool zh = IsChineseLanguageActive(); - var list = new List(); - string catLower = category?.ToLowerInvariant() ?? "all"; - - if (catLower == "all" || catLower.Contains("furn") || catLower.Contains("bed")) - { - list.Add(zh - ? $"- Bed (木床): 需木材 35 (现有木材: {woodCount}) -> 解决露宿泥地严重减益" - : $"- Bed: requires 35 Wood (available Wood: {woodCount}) -> resolves sleeping on the ground debuff"); - list.Add(zh - ? $"- Table2x2c (木桌): 需木材 28 (现有木材: {woodCount}) -> 解决无桌进餐" - : $"- Table2x2c: requires 28 Wood (available Wood: {woodCount}) -> resolves ate without table debuff"); - list.Add(zh - ? $"- DiningChair (餐椅): 需木材 20 (现有木材: {woodCount}) -> 舒适进餐与休息" - : $"- DiningChair: requires 20 Wood (available Wood: {woodCount}) -> comfortable dining and seating"); - } - if (catLower == "all" || catLower.Contains("temp") || catLower.Contains("heat") || catLower.Contains("cool")) - { - list.Add(zh - ? $"- Campfire (营火): 需木材 20 (现有木材: {woodCount}) -> 严寒取暖与初级烹饪" - : $"- Campfire: requires 20 Wood (available Wood: {woodCount}) -> heating and basic cooking"); - list.Add(zh - ? $"- PassiveCooler (被动制冷器): 需木材 50 (现有木材: {woodCount}) -> 酷暑降温避险" - : $"- PassiveCooler: requires 50 Wood (available Wood: {woodCount}) -> heatwave cooling"); - list.Add(zh - ? $"- TorchLamp (火把): 需木材 20 (现有木材: {woodCount}) -> 区域照明防御黑暗" - : $"- TorchLamp: requires 20 Wood (available Wood: {woodCount}) -> indoor lighting"); - } - if (catLower == "all" || catLower.Contains("struct") || catLower.Contains("wall") || catLower.Contains("door")) - { - list.Add(zh - ? $"- Wall (木墙): 需木材 5 (现有木材: {woodCount}) -> 遮风挡雨与室内封闭" - : $"- Wall: requires 5 Wood (available Wood: {woodCount}) -> room enclosure"); - list.Add(zh - ? $"- Door (木门): 需木材 25 (现有木材: {woodCount}) -> 房间出入口" - : $"- Door: requires 25 Wood (available Wood: {woodCount}) -> room entrance"); - } - if (list.Count == 0) - { - list.Add(zh ? $"- Bed (木床): 需木材 35 (现有木材: {woodCount})" : $"- Bed: requires 35 Wood (available Wood: {woodCount})"); - list.Add(zh ? $"- Campfire (营火): 需木材 20 (现有木材: {woodCount})" : $"- Campfire: requires 20 Wood (available Wood: {woodCount})"); - list.Add(zh ? $"- TorchLamp (火把): 需木材 20 (现有木材: {woodCount})" : $"- TorchLamp: requires 20 Wood (available Wood: {woodCount})"); - } - return list; - } - - private static (string? ToolName, JObject? Arguments) ExtractToolCall(string? toolCallsJson, string? content = null, string? expectedToolName = null) - { - if (!string.IsNullOrWhiteSpace(toolCallsJson)) - { - try - { - string cleaned = toolCallsJson!.Trim(); - if (cleaned.StartsWith("```")) - { - int firstNewline = cleaned.IndexOf('\n'); - if (firstNewline >= 0) cleaned = cleaned.Substring(firstNewline + 1); - if (cleaned.EndsWith("```")) cleaned = cleaned.Substring(0, cleaned.Length - 3); - cleaned = cleaned.Trim(); - } - - JToken token = JToken.Parse(cleaned); - JArray? arr = token as JArray; - if (arr == null && token is JObject obj) - { - arr = new JArray { obj }; - } - - if (arr != null && arr.Count > 0) - { - foreach (var item in arr) - { - if (item is not JObject callObj) continue; - - string? name = null; - if (callObj.TryGetValue("name", StringComparison.OrdinalIgnoreCase, out var nToken)) - name = nToken.Value(); - else if (callObj.TryGetValue("function", StringComparison.OrdinalIgnoreCase, out var fnToken) && fnToken is JObject fnObj && fnObj.TryGetValue("name", StringComparison.OrdinalIgnoreCase, out var fnName)) - name = fnName.Value(); - - if (expectedToolName != null && !string.Equals(name, expectedToolName, StringComparison.OrdinalIgnoreCase)) - continue; - - JToken? argsToken = null; - if (callObj.TryGetValue("arguments", StringComparison.OrdinalIgnoreCase, out var directArgs)) - argsToken = directArgs; - else if (callObj.TryGetValue("function", StringComparison.OrdinalIgnoreCase, out var fn) && fn is JObject fnO && fnO.TryGetValue("arguments", StringComparison.OrdinalIgnoreCase, out var nestedArgs)) - argsToken = nestedArgs; - - if (argsToken == null) - { - if (callObj.ContainsKey("thought") || callObj.ContainsKey("speech") || callObj.ContainsKey("work_type") || callObj.ContainsKey("job_type") || callObj.ContainsKey("building_def") || callObj.ContainsKey("reason")) - return (name, callObj); - continue; - } - - if (argsToken.Type == JTokenType.Object && argsToken is JObject aObj) - return (name, aObj); - - if (argsToken.Type == JTokenType.String) - { - string raw = argsToken.Value()?.Trim() ?? string.Empty; - if (string.IsNullOrWhiteSpace(raw)) continue; - if (raw.StartsWith("```")) - { - int nl = raw.IndexOf('\n'); - if (nl >= 0) raw = raw.Substring(nl + 1); - if (raw.EndsWith("```")) raw = raw.Substring(0, raw.Length - 3); - raw = raw.Trim(); - } - try - { - var parsed = JToken.Parse(raw); - if (parsed is JObject jRes) return (name, jRes); - } - catch { } - } - } - - var first = arr[0] as JObject; - if (first != null) - { - string? fnName = null; - if (first.TryGetValue("name", StringComparison.OrdinalIgnoreCase, out var nTok)) fnName = nTok.Value(); - else if (first.TryGetValue("function", StringComparison.OrdinalIgnoreCase, out var fTok1) && fTok1 is JObject fO1 && fO1.TryGetValue("name", StringComparison.OrdinalIgnoreCase, out var nTok1)) fnName = nTok1.Value(); - - if (first.TryGetValue("arguments", StringComparison.OrdinalIgnoreCase, out var aTok)) - { - if (aTok is JObject aObj) return (fnName, aObj); - if (aTok.Type == JTokenType.String) - { - try { return (fnName, JObject.Parse(aTok.Value() ?? "{}")); } catch { } - } - } - if (first.TryGetValue("function", StringComparison.OrdinalIgnoreCase, out var fTok) && fTok is JObject fO && fO.TryGetValue("arguments", StringComparison.OrdinalIgnoreCase, out var fnArgsTok)) - { - if (fnArgsTok is JObject nObj) return (fnName, nObj); - if (fnArgsTok.Type == JTokenType.String) - { - try { return (fnName, JObject.Parse(fnArgsTok.Value() ?? "{}")); } catch { } - } - } - return (fnName, first); - } - } - } - catch { } - } - - // Fallback: Attempt to extract tool call JSON or pseudo-function-call embedded in text content - if (!string.IsNullOrWhiteSpace(content)) - { - try - { - string rawContent = content!.Trim(); - int startIdx = rawContent.IndexOf('{'); - int endIdx = rawContent.LastIndexOf('}'); - if (startIdx >= 0 && endIdx > startIdx) - { - string jsonBlock = rawContent.Substring(startIdx, endIdx - startIdx + 1); - var parsed = JObject.Parse(jsonBlock); - string? toolName = parsed.TryGetValue("tool", StringComparison.OrdinalIgnoreCase, out var tTok) ? tTok.ToString() - : (parsed.TryGetValue("name", StringComparison.OrdinalIgnoreCase, out var nTok) ? nTok.ToString() : null); - return (toolName, parsed); - } - } - catch { } - - try - { - var fnMatch = Regex.Match( - content!.Trim(), - @"\b(?[a-z_][a-z0-9_]*)\s*\((?[\s\S]+?)\)?\s*$", - RegexOptions.IgnoreCase); - if (fnMatch.Success) - { - string fnName = fnMatch.Groups["fn"].Value; - if (expectedToolName == null || string.Equals(fnName, expectedToolName, StringComparison.OrdinalIgnoreCase)) - { - string inner = fnMatch.Groups["inner"].Value.Trim(); - var keyMatches = Regex.Matches( - inner, - @"(?:^|,\s*)(?[a-z_][a-z0-9_]*)\)?\s*[:=]\s*", - RegexOptions.IgnoreCase); - if (keyMatches.Count > 0) - { - var jObj = new JObject(); - for (int i = 0; i < keyMatches.Count; i++) - { - string key = keyMatches[i].Groups["key"].Value; - int valStart = keyMatches[i].Index + keyMatches[i].Length; - int valEnd = (i + 1 < keyMatches.Count) ? keyMatches[i + 1].Index : inner.Length; - string rawVal = inner.Substring(valStart, valEnd - valStart).Trim(); - if ((rawVal.StartsWith("\"") && rawVal.EndsWith("\"") && rawVal.Length >= 2) || - (rawVal.StartsWith("'") && rawVal.EndsWith("'") && rawVal.Length >= 2) || - (rawVal.StartsWith("“") && rawVal.EndsWith("”") && rawVal.Length >= 2) || - (rawVal.StartsWith("(") && rawVal.EndsWith(")") && rawVal.Length >= 2)) - { - rawVal = rawVal.Substring(1, rawVal.Length - 2).Replace("\\\"", "\"").Trim(); - } - if (int.TryParse(rawVal, out int intVal)) - jObj[key] = intVal; - else - jObj[key] = rawVal; - } - return (fnName, jObj); - } - } - } - } - catch { } - } - - return (null, null); - } - - private static JObject? ExtractToolArguments(string? toolCallsJson, string? expectedToolName = null, string? content = null) - { - return ExtractToolCall(toolCallsJson, content, expectedToolName).Arguments; - } - - private IEnumerator ExecuteAdvisorProposal(List colonists, int day, PlaythroughDayReport report) - { - bool zh = IsChineseLanguageActive(); - Pawn pawn = colonists[0]; - int cycleDay = ((day - 1) % 60) + 1; - string yearPrefix = day > 60 - ? (zh ? $"[第 {(day - 1) / 60 + 1} 年深化建设] " : $"[Year {(day - 1) / 60 + 1} Expansion] ") - : ""; - string proposalText = zh ? (cycleDay switch - { - 1 => "建议规划 10x10 殖民地核心大厅与 3 间独立卧室,奠定营地聚居基础", - 2 => "建议勘探近处露天矿脉并开采钢铁,为早期基础设施储备金属", - 3 => "建议划定 8x8 农田开垦水稻作物,保障全员主食自给自足", - 4 => "建议采伐周边成熟林木,大量储备原木以备建筑与生活柴火之需", - 5 => "建议规划封闭冷库与食物储存区,安装制冷设备防止食物腐烂", - 6 => "建议部署太阳能发电机组并连接输电管线,搭建殖民地初级电网", - 7 => "建议建造蓄电池组并做好绝缘防潮,确保夜间供电与电网缓冲", - 8 => "建议部署烹饪料理台并规范卫生准则,制作熟食以避免食物中毒", - 9 => "建议建立独立屠宰隔间,高效分解猎物尸体并收集皮毛原料", - 10 => "建议在营地主入口部署尖刺陷阱阵与沙袋掩体,抵御早期袭扰", - 11 => "建议对主仓库推行物资分类管理,开辟建材与原料专用堆放区", - 12 => "建议设立基础科研台并指派专职研究员,启动边缘科技攀升", - 13 => "建议在各卧室内打造舒适木质单人床,提升殖民者睡眠与心情", - 14 => "建议在大厅部署下棋桌与休闲娱乐设施,缓解殖民者心理压力", - 15 => "建议划定药用马草种植区,培育本土草药以备伤病急救应急", - 16 => "建议深入勘探山体开采压缩机械零部件,储备电气与自动化构件", - 17 => "建议设立急救医务室并布置医用病床,提升创伤与疾病救治效率", - 18 => "建议建造手工裁缝台,采集毛皮与纤维为全员缝制耐磨御寒衣物", - 19 => "建议在外围开阔风道部署风力发电机,实现风光互补稳定供能", - 20 => "建议设立燃煤铁匠台,冶炼锻造金属近战兵器与实用农用工具", - 21 => "建议构筑花岗岩坚固石质外墙,封锁死角构建环形封闭防御圈", - 22 => "建议圈定畜牧围栏并树立牧业标桩,驯养野生禽畜发展畜牧业", - 23 => "建议在厚岩顶下方开辟辐射尘避难地窖,储备罐头与应急生存物资", - 24 => "建议在防御隘口布设自动化哨戒机枪,构建第一道自动火力交叉网", - 25 => "建议开垦棉花作物种植田,收获优质布料以生产医疗绷带与防尘风衣", - 26 => "建议勘测地热喷气孔并部署地热发电机组,获取全天候充沛高能电力", - 27 => "建议引入应急营养膏合成机,在食物匮乏或厨师伤病时保障口粮", - 28 => "建议设立切石工坊批量加工各类石材,全面淘汰易燃木质墙体", - 29 => "建议在核心电池间与工坊安装灭火泡沫发生器,阻断电涌火灾隐患", - 30 => "建议点燃中央篝火举办开拓满月庆典,聚餐庆祝殖民地生存稳固", - 31 => "建议在防线内侧设立独立军械武器架,实现枪械与防具快速着装", - 32 => "建议设立室内无土水培温室水槽,彻底摆脱严寒与有毒尘暴减产威胁", - 33 => "建议构筑迫击炮战术掩体并储备高爆炮弹,具备远程反攻压制能力", - 34 => "建议在医院与实验室全面铺设无菌地砖,杜绝手术感染与研发误差", - 35 => "建议在幽静庭院设置精神冥想点,助益灵能者专注凝神与心情恢复", - 36 => "建议在仓库前设立远征商队打包集结地,常态化组织对外贸易交流", - 37 => "建议建造生物精炼厂将有机多余作物提炼为化合燃料,供应动力设备", - 38 => "建议升级军工精密防具生产线,为作战人员量身打造防弹背心与头盔", - 39 => "建议在防御外围设置战术射击靶场,定期开展殖民者远距射击特训", - 40 => "建议锁定伴生金矿脉展开深度开采,储备珍贵黄金用于先进部件制造", - 41 => "建议落成工业级机械加工台,自主制造高精度枪械与工业零部件", - 42 => "建议架设轨道通讯台与贸易信标,联络过境轨道商船购入稀缺高精尖物资", - 43 => "建议沿全殖民地交通要道部署立式泛光灯,消除夜间行动与交火惩罚", - 44 => "建议完成主冷库双层保温扩建并增设双定制冷机,应对极端热浪挑战", - 45 => "建议建立高科技科研中心并接驳多元分析仪,冲刺前沿尖端科技", - 46 => "建议设立仿生义体工作台,为伤残同伴量身定制高机能仿生器官", - 47 => "建议在各核心出入口换装重型钢制自动防爆门,构筑气闸级防护隔离", - 48 => "建议引入深层地质钻井持续开采地下未探明富矿,告别表层资源枯竭", - 49 => "建议精装豪华贵宾客房与皇家大床,提升过往外宾与同盟势力友好度", - 50 => "建议在要塞前沿部署 EMP 电磁脉冲地雷阵,针对性防范机械族空投突击", - 51 => "建议贯通全基地智能控温通风管道网络,实现冬暖夏凉一体化调节", - 52 => "建议全力筹措玻璃钢与高级构件,启动全套精良动力装甲组装工程", - 53 => "建议设立艺术雕塑工坊雕刻宏伟丰碑巨作,大幅提升殖民地宜居印象", - 54 => "建议为突击近战队员定制个人能量护盾腰带,打造坚不可摧的前锋屏障", - 55 => "建议暗中开凿直穿后山峡谷的应急撤离坑道,确保遭遇灭顶之灾时全身而退", - 56 => "建议展开全殖民地物资总盘点与军备大检修,全面清理磨损装备与隐患", - 57 => "建议成立高级生化制药实验室,自主试制高效消炎药与高级急救药品", - 58 => "建议勘定飞船发射平台地基并铺设结构梁,迈向逃离边缘世界的终极筹备", - 59 => "建议全员动员巡检全部炮塔、迫击炮弹药与外墙耐久,进入最高特级战备", - 60 => $"建议在中心广场落成 {day} 日开拓胜利纪念碑,举行全员欢庆大丰收盛典!", - _ => "建议巡视殖民地安全状况并维护关键发电设备" - }) : $"Day {day} Advisor Proposal (Cycle {cycleDay}): inspect colony infrastructure, food reserves, and perimeter defenses."; - - var advScope = RuntimeServiceHub.Shared.Capture(); - var advQueue = advScope.GetOptional(); - if (advQueue != null) - { - if (advQueue.TotalQueuedCount > 15) advQueue.CancelAllRequests(); - advQueue.ClearAllCooldowns(); - } - - Map advMap = pawn.Map ?? Find.CurrentMap; - int advWood = CountAvailableMapResource(advMap, ThingDefOf.WoodLog); - int advSteel = CountAvailableMapResource(advMap, ThingDefOf.Steel); - int advMeals = CountAvailableMapResource(advMap, ThingDefOf.MealSimple) - + CountAvailableMapResource(advMap, ThingDefOf.MealFine) - + CountAvailableMapResource(advMap, ThingDefOf.MealSurvivalPack); - int advBlueprints = (advMap?.listerThings?.ThingsInGroup(ThingRequestGroup.Blueprint)?.Count ?? 0) - + (advMap?.listerThings?.ThingsInGroup(ThingRequestGroup.BuildingFrame)?.Count ?? 0); + LudeonTK.EditWindow_Log.wantsToOpen = false; - var advTools = new List - { - new StructuredTool - { - Name = "propose_colony_advice", - Description = "Submit a tactical colony advisor recommendation for player approval based on current colony vitals", - Parameters = "{\"type\":\"object\",\"properties\":{\"proposal\":{\"type\":\"string\"},\"priority_domain\":{\"type\":\"string\"}},\"required\":[\"proposal\"]}" - } - }; - - var advEnvelope = LlmRequestEnvelopeBuilder - .ForScenario(RimMindAPI.Context.ScenarioDecision) - .WithModId("RimMind-Advisor") - .WithNpcId("NPC-" + pawn.thingIDNumber) - .WithTools(advTools) - .WithToolDispatchMode(ToolCallDispatchMode.Manual) - .WithMaxTokens(500) - .WithTemperature(0.6f) - .WithPriority(AIRequestPriority.High) - .Build(); - - advEnvelope.Messages.Add(new ChatMessage - { - Role = "system", - LayerTag = "L0", - Content = zh - ? $"你是 RimWorld 殖民地战术顾问(发声代表:{pawn.Name.ToStringShort})。请根据当前营地状态调用 propose_colony_advice 提出一条简明扼要(30~60字)的今日发展或生存建议,不要输出 XML 标签。" - : $"You are the RimWorld Colony Tactical Advisor (represented by {pawn.Name.ToStringShort}). Call propose_colony_advice to submit a concise (1-2 sentences) strategic recommendation for the colony based on current vitals. Do not output XML tags." - }); - advEnvelope.Messages.Add(new ChatMessage - { - Role = "user", - LayerTag = "L4", - Content = zh - ? $"[殖民地第 {day} 天晚间顾问评估] 存活殖民者: {colonists.Count} 人, 木材: {advWood}, 钢铁: {advSteel}, 熟食口粮: {advMeals}, 待建工程: {advBlueprints}。请调用 propose_colony_advice 给出当前最关键的殖民地建议。" - : $"[Colony Day {day} Evening Advisor Review] Living colonists: {colonists.Count}, Wood: {advWood}, Steel: {advSteel}, Meals: {advMeals}, Pending construction: {advBlueprints}. Call propose_colony_advice with the top strategic recommendation right now." - }); - - bool advCompleted = false; - Result? advResponse = null; - RimMindAPI.Send(advEnvelope, res => - { - advResponse = res; - advCompleted = true; - }); - _report.TotalLiveLlmRequests++; - - float advTimeout = 65f; - float advElapsed = 0f; - while (!advCompleted && advElapsed < advTimeout) - { - if (Find.TickManager != null) Find.TickManager.CurTimeSpeed = TimeSpeed.Paused; - advElapsed += Time.unscaledDeltaTime; - if (advQueue is ITickableRequestQueue tq) - { - tq.CurrentTick += 5; - tq.Tick(); - } - DismissModalWindows(Find.CurrentMap); - yield return null; - } - - if (advCompleted && advResponse != null && advResponse.Value.IsOk) - { - var advVal = advResponse.Value.Value; - report.TotalTokensUsed += advVal.TokensUsed; - var advArgs = ExtractToolArguments(advVal.ToolCallsJson, "propose_colony_advice", advVal.Content); - string? liveProposal = advArgs?["proposal"]?.ToString() - ?? advArgs?["advice"]?.ToString() - ?? advArgs?["recommendation"]?.ToString(); - if (string.IsNullOrWhiteSpace(liveProposal) && !string.IsNullOrWhiteSpace(advVal.Content)) - { - liveProposal = advVal.Content.Trim(); - } - liveProposal = StripModelXmlTags(liveProposal); - if (!string.IsNullOrWhiteSpace(liveProposal)) - { - proposalText = liveProposal!; - } - } - else - { - Log.Warning($"[RimMind-Playthrough][Day {day}] Advisor proposal fallback: {advResponse?.Error.Message}"); - } - - report.AdvisorProposal = $"{pawn.Name.ToStringShort}: {yearPrefix}{proposalText}"; - - // Register to RequestOverlay - bool approved = false; - var req = new RequestEntry - { - title = zh ? "顾问决策建议" : "Advisor Recommendation", - description = report.AdvisorProposal, - options = new[] { "approve", "reject" }, - source = pawn.Name?.ToStringShort ?? "Advisor", - callback = choice => { if (choice == "approve") approved = true; } - }; - - RequestOverlay.Register(req); - yield return null; - - // Simulate player reviewing and approving the request - RequestOverlay.Resolve(req, "approve"); - report.AdvisorApproved = approved; - - Log.Message($"[RimMind-Playthrough][Day {day}] Advisor Proposal Approved: {report.AdvisorProposal}"); - } - - private void ExecuteNightReflection(PlaythroughDayReport report) - { - try - { - object? comp = Find.World?.components?.FirstOrDefault(c => c.GetType().Name == "RimMindMemoryWorldComponent") - ?? (object?)Current.Game?.components?.FirstOrDefault(c => c.GetType().Name == "RimMindMemoryWorldComponent"); - if (comp != null) - { - var map = Find.CurrentMap; - if (map?.mapPawns?.FreeColonistsSpawned != null) + var windows = Find.WindowStack.Windows.ToList(); + for (int i = 0; i < windows.Count; i++) { - int activeCount = 0; - int archiveCount = 0; - int darkCount = 0; - var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic; - var getStoreMethod = comp.GetType().GetMethod("GetOrCreatePawnStore", flags) - ?? comp.GetType().GetMethod("GetPawnStore", flags); - if (getStoreMethod != null) - { - foreach (var pawn in RimMind.Presentation.Api.RimMindPawnLookup.GetSpawnedColonistsSafe(map)) - { - var store = getStoreMethod.Invoke(comp, new object[] { pawn }); - if (store != null) - { - var activeProp = store.GetType().GetField("active", flags); - var archiveProp = store.GetType().GetField("archive", flags); - var darkProp = store.GetType().GetField("dark", flags); - var activeList = activeProp?.GetValue(store) as System.Collections.IList; - var archiveList = archiveProp?.GetValue(store) as System.Collections.IList; - var darkList = darkProp?.GetValue(store) as System.Collections.IList; - - if (activeList != null) - activeCount += activeList.Count; - if (archiveList != null) - archiveCount += archiveList.Count; - - // Consolidate episodic archive into semantic/dark memory when archive reaches threshold - if (darkList != null && archiveList != null && archiveList.Count > 0 && darkList.Count < (archiveList.Count + 2) / 3) - { - var sampleEntry = archiveList[archiveList.Count - 1]; - if (sampleEntry != null) - { - var entryType = sampleEntry.GetType(); - var factEntry = Activator.CreateInstance(entryType); - if (factEntry != null) - { - bool zh = IsChineseLanguageActive(); - entryType.GetField("id", flags)?.SetValue(factEntry, $"mem-dark-{report.DayNumber}-{pawn.thingIDNumber}"); - entryType.GetField("content", flags)?.SetValue( - factEntry, - zh - ? $"[长期记忆沉淀] {pawn.Name?.ToStringShort ?? "Colonist"} 累计经历 {archiveList.Count} 项殖民地事件,生存适应力稳步提升。" - : $"[Long-Term Memory Consolidation] {pawn.Name?.ToStringShort ?? "Colonist"} has experienced {archiveList.Count} colony events, steadily building survival resilience."); - entryType.GetField("tick", flags)?.SetValue(factEntry, Find.TickManager?.TicksGame ?? 0); - entryType.GetField("importance", flags)?.SetValue(factEntry, 0.85f); - entryType.GetField("isPinned", flags)?.SetValue(factEntry, true); - darkList.Add(factEntry); - } - } - } - - if (darkList != null) - darkCount += darkList.Count; - } - } - } + var w = windows[i]; + if (w == null) continue; + string typeName = w.GetType().Name; + if (typeName.IndexOf("Advisor", StringComparison.OrdinalIgnoreCase) >= 0) + continue; - var narratorProp = comp.GetType().GetProperty("NarratorStore", flags); - var narratorStore = narratorProp?.GetValue(comp); - if (narratorStore != null) + if (w is Dialog_GiveName || + w is Dialog_MessageBox || + w is Dialog_NodeTree || + w is FloatMenu || + w is LudeonTK.EditWindow_Log || + w.absorbInputAroundWindow || + typeName.IndexOf("EditWindow_Log", StringComparison.OrdinalIgnoreCase) >= 0 || + typeName.IndexOf("GiveName", StringComparison.OrdinalIgnoreCase) >= 0 || + typeName.IndexOf("Immediate", StringComparison.OrdinalIgnoreCase) >= 0 || + typeName.IndexOf("NodeTree", StringComparison.OrdinalIgnoreCase) >= 0 || + typeName.IndexOf("MessageBox", StringComparison.OrdinalIgnoreCase) >= 0) { - var narratorDarkField = narratorStore.GetType().GetField("dark", flags); - if (narratorDarkField?.GetValue(narratorStore) is System.Collections.IList narratorDarkList) - darkCount += narratorDarkList.Count; + Find.WindowStack.TryRemove(w, doCloseSound: false); } - - report.WorkingMemoryCount = activeCount; - report.EpisodicMemoryCount = archiveCount; - report.ColonyFactCount = darkCount; - return; } } - } - catch - { - // Fallback gracefully - } - report.WorkingMemoryCount = 0; - report.EpisodicMemoryCount = 0; - report.ColonyFactCount = 0; - } - - private static string StripModelXmlTags(string? input) - { - if (string.IsNullOrWhiteSpace(input)) - return string.Empty; - string s = input!.Trim(); - if (s.IndexOf("", StringComparison.OrdinalIgnoreCase) >= 0) - { - s = Regex.Replace(s, @"[\s\S]*?", string.Empty, RegexOptions.IgnoreCase).Trim(); - } - if (s.IndexOf('<') >= 0 && s.IndexOf('>') >= 0) - { - s = Regex.Replace( - s, - @"]*>", - string.Empty, - RegexOptions.IgnoreCase).Trim(); - } - return s; - } - - private static Blueprint? TryPlaceBlueprint(Map map, string defName, IntVec3 cell, Rot4? rot = null, string? stuffDefName = null) - { - if (map == null) return null; - if (defName == "TableStoveWood") defName = "FueledStove"; else if (defName == "ResearchBench") defName = "SimpleResearchBench"; BuildableDef? buildableDef = DefDatabase.GetNamedSilentFail(defName); - if (buildableDef == null) - { - buildableDef = DefDatabase.GetNamedSilentFail(defName); - } - if (buildableDef == null) return null; - - ThingDef? stuffDef = null; - if (buildableDef is ThingDef thingDef && thingDef.MadeFromStuff) - { - if (!string.IsNullOrEmpty(stuffDefName)) - { - stuffDef = DefDatabase.GetNamedSilentFail(stuffDefName); - } - if (stuffDef == null) + catch (Exception ex) { - stuffDef = GenStuff.DefaultStuffFor(thingDef) ?? ThingDefOf.WoodLog ?? ThingDefOf.Steel; + Log.Warning($"[RimMind-Playthrough] DismissModalWindows notice: {ex.Message}"); } } - if (!cell.InBounds(map)) - { - cell = CellFinder.StandableCellNear(map.Center, map, 15); - } - - try + private void OnDestroy() { - Rot4 chosenRot = rot ?? Rot4.North; - Rot4[] candidateRots = (buildableDef is ThingDef td && td.rotatable) - ? new[] { chosenRot, Rot4.North, Rot4.East, Rot4.South, Rot4.West } - : new[] { chosenRot }; - IntVec3 chosenCell = IntVec3.Invalid; - foreach (var r in candidateRots) - { - if (cell.InBounds(map) && !cell.Fogged(map) && GenConstruct.CanPlaceBlueprintAt(buildableDef, cell, r, map, false, null, null, stuffDef).Accepted) - { - chosenCell = cell; - chosenRot = r; - break; - } - } - if (!chosenCell.IsValid) + RestorePlayerSettings(); + if (_activeHost == this) { - IntVec3[] anchors = cell.InBounds(map) && cell != map.Center ? new[] { cell, map.Center } : new[] { map.Center }; - foreach (var anchor in anchors) - { - foreach (var c in GenRadial.RadialCellsAround(anchor, 25, true)) - { - if (!c.InBounds(map) || c.Fogged(map) || !c.Standable(map)) continue; - var room = c.GetRoom(map); - if (room != null && room.IsDoorway) continue; - foreach (var r in candidateRots) - { - if (GenConstruct.CanPlaceBlueprintAt(buildableDef, c, r, map, false, null, null, stuffDef).Accepted) - { - chosenCell = c; - chosenRot = r; - break; - } - } - if (chosenCell.IsValid) break; - } - if (chosenCell.IsValid) break; - } + _activeHost = null; } - if (!chosenCell.IsValid) chosenCell = cell; - return GenConstruct.PlaceBlueprintForBuild(buildableDef, chosenCell, map, chosenRot, Faction.OfPlayer, stuffDef); - } - catch (Exception ex) - { - Log.Warning($"[RimMind-Playthrough] PlaceBlueprint {defName} at {cell} notice: {ex.Message}"); - return null; } } - - private static bool AddDesignationSafe(Map map, IntVec3 cell, DesignationDef? desDef) - { - if (map == null || desDef == null || !cell.InBounds(map)) return false; - try - { - if (desDef.targetType == TargetType.Thing) - { - Thing? targetThing = null; - if (desDef == DesignationDefOf.HarvestPlant || desDef == DesignationDefOf.CutPlant) - { - targetThing = cell.GetPlant(map); - } - else if (desDef == DesignationDefOf.Haul) - { - targetThing = cell.GetFirstHaulable(map); - } - else - { - targetThing = cell.GetFirstThing(map); - } - - if (targetThing != null && map.designationManager.DesignationOn(targetThing, desDef) == null) - { - map.designationManager.AddDesignation(new Designation(targetThing, desDef)); - return true; - } - return false; - } - - if (map.designationManager.DesignationAt(cell, desDef) == null) - { - map.designationManager.AddDesignation(new Designation(cell, desDef)); - return true; - } - } - catch (Exception ex) - { - Log.Warning($"[RimMind-Playthrough] AddDesignation {desDef.defName} notice: {ex.Message}"); - } - return false; - } - - private static List CollectUnoccupiedZoneCells(Map map, IntVec3 origin, int width, int height, bool requireFertility) - { - var cells = new List(width * height); - for (int x = 0; x < width; x++) - { - for (int z = 0; z < height; z++) - { - var c = new IntVec3(origin.x + x, origin.y, origin.z + z); - if (!c.InBounds(map) || c.Fogged(map) || !c.Standable(map)) continue; - if (map.zoneManager.ZoneAt(c) != null) continue; - if (c.GetEdifice(map) != null) continue; - if (requireFertility && map.fertilityGrid != null && map.fertilityGrid.FertilityAt(c) < 0.7f) continue; - cells.Add(c); - } - } - return cells; - } - - private static Zone_Growing? CreateGrowingZoneSafe(Map map, IntVec3 start, int width, int height, string plantDefName) - { - if (map == null) return null; - try - { - var validCells = CollectUnoccupiedZoneCells(map, start, width, height, requireFertility: true); - if (validCells.Count < 4) - { - int[] offsets = { -16, -10, 10, 16, -22, 22 }; - foreach (int dx in offsets) - { - foreach (int dz in offsets) - { - var candidateCells = CollectUnoccupiedZoneCells(map, new IntVec3(start.x + dx, start.y, start.z + dz), width, height, requireFertility: true); - if (candidateCells.Count > validCells.Count) - validCells = candidateCells; - if (validCells.Count >= (width * height) / 2) - break; - } - if (validCells.Count >= (width * height) / 2) - break; - } - } - - if (validCells.Count == 0) - { - return map.zoneManager.AllZones.OfType().FirstOrDefault(); - } - - var zone = new Zone_Growing(map.zoneManager); - map.zoneManager.RegisterZone(zone); - for (int i = 0; i < validCells.Count; i++) - { - zone.AddCell(validCells[i]); - } - var plantDef = DefDatabase.GetNamedSilentFail(plantDefName); - if (plantDef != null) - { - zone.SetPlantDefToGrow(plantDef); - } - return zone; - } - catch (Exception ex) - { - Log.Warning($"[RimMind-Playthrough] CreateGrowingZone notice: {ex.Message}"); - return null; - } - } - - private static Zone_Stockpile? CreateStockpileZoneSafe(Map map, IntVec3 start, int width, int height, StorageSettingsPreset preset = StorageSettingsPreset.DefaultStockpile) - { - if (map == null) return null; - try - { - var validCells = CollectUnoccupiedZoneCells(map, start, width, height, requireFertility: false); - if (validCells.Count < 4) - { - int[] offsets = { -8, 8, -14, 14, -20, 20 }; - foreach (int dx in offsets) - { - foreach (int dz in offsets) - { - var candidateCells = CollectUnoccupiedZoneCells(map, new IntVec3(start.x + dx, start.y, start.z + dz), width, height, requireFertility: false); - if (candidateCells.Count > validCells.Count) - validCells = candidateCells; - if (validCells.Count >= (width * height) / 2) - break; - } - if (validCells.Count >= (width * height) / 2) - break; - } - } - - if (validCells.Count == 0) - { - return map.zoneManager.AllZones.OfType().FirstOrDefault(); - } - - var zone = new Zone_Stockpile(preset, map.zoneManager); - map.zoneManager.RegisterZone(zone); - for (int i = 0; i < validCells.Count; i++) - { - zone.AddCell(validCells[i]); - } - return zone; - } - catch (Exception ex) - { - Log.Warning($"[RimMind-Playthrough] CreateStockpileZone notice: {ex.Message}"); - return null; - } - } - - private static Thing? FindNearestMineable(Map map, IntVec3 center, string? specificDefName = null) - { - if (map == null) return null; - return map.listerThings.AllThings - .Where(t => t.Spawned && t.def != null && - (specificDefName != null - ? (t.def.defName.IndexOf(specificDefName, StringComparison.OrdinalIgnoreCase) >= 0 || - (t.def.label != null && t.def.label.IndexOf(specificDefName, StringComparison.OrdinalIgnoreCase) >= 0) || - (t.def.building?.mineableThing != null && t.def.building.mineableThing.defName.IndexOf(specificDefName, StringComparison.OrdinalIgnoreCase) >= 0)) - : (t.def.mineable || (t.def.building != null && t.def.building.isNaturalRock) || t.def.defName.Contains("Mineable")))) - .OrderBy(t => t.Position.DistanceToSquared(center)) - .FirstOrDefault(); - } - - private void ExportDailySnapshot(int day, PlaythroughDayReport report, Map? map, string ssPath) - { - try - { - var colonistsList = new List(); - var liveColonists = GetLivingColonists(); - foreach (var p in liveColonists) - { - if (p == null || p.Dead) continue; - var badThoughts = new List(); - if (p.needs?.mood?.thoughts != null) - { - var thoughts = new List(); - p.needs.mood.thoughts.GetAllMoodThoughts(thoughts); - foreach (var th in thoughts) - { - if (th != null && th.MoodOffset() < 0f) - { - badThoughts.Add($"{PawnDataExtractor.SanitizeThoughtLabel(th.LabelCap)} ({th.MoodOffset():F0})"); - } - } - } - - bool hasTendableHediff = p.health?.hediffSet?.HasTendableHediff() ?? false; - float bleedingRate = p.health?.hediffSet?.BleedRateTotal ?? 0f; - float pain = p.health?.hediffSet?.PainTotal ?? 0f; - bool isDowned = p.Downed; - string? mentalState = p.MentalStateDef?.defName; - string hpStr = p.health?.summaryHealth?.SummaryHealthPercent.ToString("P0") ?? "100%"; - string jobStr = p.CurJobDef?.defName ?? "Idle"; - - colonistsList.Add(new - { - name = p.Name?.ToStringShort ?? "Colonist", - mood = p.needs?.mood?.CurLevel ?? 0.5f, - rest = p.needs?.rest?.CurLevel ?? 1.0f, - food = p.needs?.food?.CurLevel ?? 1.0f, - health = hpStr, - healthSummary = hpStr, - hasTendableHediff = hasTendableHediff, - bleedingRate = bleedingRate, - pain = pain, - isDowned = isDowned, - mentalState = mentalState, - job = jobStr, - currentJob = jobStr, - badThoughts = badThoughts - }); - } - - // Map stats: food count, power, open windows list, active alerts - float foodNutrition = map?.resourceCounter?.TotalHumanEdibleNutrition ?? 0f; - int foodCount = 0; - float unstockpiledEdibleNutrition = 0f; - if (map != null) - { - var foodThings = map.listerThings.ThingsInGroup(ThingRequestGroup.FoodSourceNotPlantOrTree); - if (foodThings != null) - { - foodCount = foodThings.Count; - foreach (var t in foodThings) - { - if (t == null || !t.Spawned || t.def == null) continue; - if (t.IsForbidden(Faction.OfPlayer)) continue; - if (t.GetRotStage() != RotStage.Fresh) continue; - - float nut = (t.def.IsNutritionGivingIngestible ? t.def.GetStatValueAbstract(StatDefOf.Nutrition) * t.stackCount : 0f); - if (!t.IsInValidStorage()) - { - unstockpiledEdibleNutrition += nut; - } - } - } - } - float totalAvailableNutrition = foodNutrition + unstockpiledEdibleNutrition; - - float powerGain = 0f; - float powerStored = 0f; - if (map?.powerNetManager != null) - { - foreach (var net in map.powerNetManager.AllNetsListForReading) - { - if (net != null) - { - powerGain += net.CurrentEnergyGainRate() * 60000f; - powerStored += net.CurrentStoredEnergy(); - } - } - } - - var openWindows = new List(); - if (Find.WindowStack != null) - { - foreach (var w in Find.WindowStack.Windows) - { - if (w != null) - { - openWindows.Add(w.GetType().Name); - } - } - } - - var activeAlerts = new List(); - try - { - var alertsReadout = (Find.UIRoot as UIRoot_Play)?.alerts; - if (alertsReadout != null) - { - var field = typeof(AlertsReadout).GetField("activeAlerts", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); - if (field?.GetValue(alertsReadout) is List list) - { - foreach (var a in list) - { - if (a != null) - { - string label = a.Label; - if (string.IsNullOrWhiteSpace(label)) label = a.GetLabel(); - if (!string.IsNullOrWhiteSpace(label)) activeAlerts.Add(label); - } - } - } - } - } - catch - { - // Fallback or ignore reflection issues - } - - int woodCount = CountAvailableMapResource(map, ThingDefOf.WoodLog); - int steelCount = CountAvailableMapResource(map, ThingDefOf.Steel); - int mealsCount = CountAvailableMapResource(map, ThingDefOf.MealSimple) - + CountAvailableMapResource(map, ThingDefOf.MealFine) - + CountAvailableMapResource(map, ThingDefOf.MealSurvivalPack); - int medicineCount = 0; - var medItems = map?.listerThings?.ThingsInGroup(ThingRequestGroup.Medicine); - if (medItems != null) - { - for (int i = 0; i < medItems.Count; i++) - { - var t = medItems[i]; - if (t != null && t.Spawned && !t.IsForbidden(Faction.OfPlayer)) - medicineCount += t.stackCount; - } - } - int pendingBlueprints = map?.listerThings?.ThingsInGroup(ThingRequestGroup.Blueprint)?.Count ?? 0; - int pendingFrames = map?.listerThings?.ThingsInGroup(ThingRequestGroup.BuildingFrame)?.Count ?? 0; - int pendingConstructionCount = pendingBlueprints + pendingFrames; - string weatherLabel = map?.weatherManager?.curWeather?.label ?? "Clear"; - int outTemp = Mathf.RoundToInt(map?.mapTemperature?.OutdoorTemp ?? 21f); - int inTemp = Mathf.RoundToInt(liveColonists.FirstOrDefault()?.AmbientTemperature ?? (map?.mapTemperature?.OutdoorTemp ?? 21f)); - - var snapshot = new - { - day = day, - date = report.DateString, - colonists = colonistsList, - mapStats = new - { - weather = weatherLabel, - outdoorTemp = outTemp, - indoorTemp = inTemp, - mealsCount = mealsCount, - foodCount = foodCount, - foodNutrition = Mathf.Round(foodNutrition * 10f) / 10f, - unstockpiledFoodNutrition = Mathf.Round(unstockpiledEdibleNutrition * 10f) / 10f, - totalAvailableNutrition = Mathf.Round(totalAvailableNutrition * 10f) / 10f, - woodCount = woodCount, - steelCount = steelCount, - medicineCount = medicineCount, - pendingConstructionCount = pendingConstructionCount, - power = new - { - gainRate = Mathf.RoundToInt(powerGain), - stored = Mathf.RoundToInt(powerStored) - }, - openWindows = openWindows, - activeAlerts = activeAlerts - }, - screenshot = Path.GetFileName(ssPath) - }; - - string jsonPath = Path.Combine(_bridgeDir, $"state_day_{day:D2}.json"); - File.WriteAllText(jsonPath, JsonConvert.SerializeObject(snapshot, Formatting.Indented), Encoding.UTF8); - Log.Message($"[RimMind-Playthrough][Day {day}] Exported daily state snapshot to bridge: {jsonPath}"); - } - catch (Exception ex) - { - Log.Warning($"[RimMind-Playthrough][Day {day}] Failed to export daily snapshot: {ex.Message}"); - } - } - - private IEnumerator ExecuteDailyColonyOperationRoutine(int day, PlaythroughDayReport report) - { - var map = Find.CurrentMap; - - // 1. Captures morning screenshot into _bridgeDir as day-{day:D2}.png and sets report.ScreenshotPath - yield return new WaitForEndOfFrame(); - string ssFileName = $"day-{day:D2}.png"; - string ssPath = Path.Combine(_bridgeDir, ssFileName); - try - { - if (Find.CurrentMap != null && Find.CameraDriver != null) Find.CameraDriver.JumpToCurrentMapLoc(Find.CurrentMap.Center); Texture2D screenshot = ScreenCapture.CaptureScreenshotAsTexture(); - byte[] bytes = screenshot.EncodeToPNG(); - File.WriteAllBytes(ssPath, bytes); - UnityEngine.Object.Destroy(screenshot); - report.ScreenshotPath = ssPath; - Log.Message($"[RimMind-Playthrough][Day {day}] Bridge morning screenshot captured: {ssPath}"); - } - catch (Exception ex) - { - Log.Warning($"[RimMind-Playthrough][Day {day}] Failed to capture bridge screenshot: {ex.Message}"); - } - - // 2. Calls ExportDailySnapshot(day, report, map, ssPath) which writes state_day_{day:D2}.json to _bridgeDir - ExportDailySnapshot(day, report, map, ssPath); - - // 3. If _interactiveBridgeEnabled: waits for cmd_day_{day:D2}.json in _bridgeDir - if (_interactiveBridgeEnabled) - { - float timeoutLimit = 180f; - string? timeoutEnv = Environment.GetEnvironmentVariable("RIMMIND_BRIDGE_TIMEOUT"); - if (!string.IsNullOrEmpty(timeoutEnv) && float.TryParse(timeoutEnv, out float customTimeout) && customTimeout > 10f) - { - timeoutLimit = customTimeout; - } - - Log.Message($"[RimMind-Playthrough][Day {day}] Interactive Subagent Bridge active. Waiting up to {timeoutLimit}s for cmd_day_{day:D2}.json..."); - float waitStart = Time.realtimeSinceStartup; - string cmdFileName = $"cmd_day_{day:D2}.json"; - string cmdPath = Path.Combine(_bridgeDir, cmdFileName); - bool commandExecuted = false; - - while (Time.realtimeSinceStartup - waitStart < timeoutLimit) - { - if (Find.TickManager != null) Find.TickManager.CurTimeSpeed = TimeSpeed.Paused; - - if (File.Exists(cmdPath)) - { - ColonySubagentCommand? cmd = null; - try - { - string json = File.ReadAllText(cmdPath, Encoding.UTF8); - cmd = JsonConvert.DeserializeObject(json); - } - catch (Exception ex) - { - Log.Warning($"[RimMind-Playthrough][Day {day}] Error parsing {cmdFileName}: {ex.Message}"); - } - - if (cmd != null) - { - string donePath = Path.Combine(_bridgeDir, $"cmd_day_{day:D2}.done"); - try - { - if (File.Exists(donePath)) File.Delete(donePath); - File.Move(cmdPath, donePath); - } - catch (Exception ex) - { - Log.Warning($"[RimMind-Playthrough][Day {day}] Error renaming {cmdFileName} to done: {ex.Message}"); - } - - if (map != null) - { - ExecuteSubagentCommand(cmd, day, report, map); - } - else - { - report.ColonyOperationName = cmd.Action; - report.ColonyOperationDetail = cmd.Reason; - report.ColonyOperationSuccess = true; - } - - string ackPath = Path.Combine(_bridgeDir, $"ack_day_{day:D2}.json"); - try - { - var ackData = new - { - status = "OK", - day = day, - action = cmd.Action, - target = cmd.Target, - timestamp = DateTime.UtcNow.ToString("o") - }; - File.WriteAllText(ackPath, JsonConvert.SerializeObject(ackData, Formatting.Indented), Encoding.UTF8); - Log.Message($"[RimMind-Playthrough][Day {day}] Subagent command acknowledged: {ackPath}"); - } - catch (Exception ex) - { - Log.Warning($"[RimMind-Playthrough][Day {day}] Error writing ack file: {ex.Message}"); - } - - commandExecuted = true; - break; - } - } - - yield return new WaitForSecondsRealtime(0.15f); - } - - if (!commandExecuted) - { - Log.Message($"[RimMind-Playthrough][Day {day}] Interactive bridge wait timed out ({timeoutLimit}s). Falling back to default colony operation."); - ExecuteDailyColonyOperation(day, report); - } - } - else - { - ExecuteDailyColonyOperation(day, report); - } - } - - private void ExecuteSubagentCommand(ColonySubagentCommand cmd, int day, PlaythroughDayReport report, Map map) - { - string action = cmd.Action ?? string.Empty; - report.ColonyOperationName = action; - report.ColonyOperationDetail = cmd.Reason + (string.IsNullOrWhiteSpace(cmd.UxFinding) ? "" : " | 体验优化/发现问题: " + cmd.UxFinding); - report.ColonyOperationSuccess = true; - - var colonists = GetLivingColonists(); - IntVec3 basePos = map.Center; - if (!basePos.InBounds(map)) basePos = map.Center; - IntVec3 safeBase = CellFinder.StandableCellNear(basePos, map, 8); - if (!safeBase.InBounds(map)) safeBase = map.Center; - - IntVec3 Offset(int dx, int dz) - { - var c = new IntVec3(safeBase.x + dx, safeBase.y, safeBase.z + dz); - return c.InBounds(map) ? c : safeBase; - } - - try - { - switch (action.ToLowerInvariant().Trim()) - { - case "dismiss_window": - DismissModalWindows(map); - break; - - case "plan_housing": - for (int x = 0; x < 10; x++) - { - AddDesignationSafe(map, Offset(x, 0), DesignationDefOf.Plan); - AddDesignationSafe(map, Offset(x, 9), DesignationDefOf.Plan); - } - for (int z = 0; z < 10; z++) - { - AddDesignationSafe(map, Offset(0, z), DesignationDefOf.Plan); - AddDesignationSafe(map, Offset(9, z), DesignationDefOf.Plan); - } - for (int i = 0; i < 3; i++) - { - int offX = 10 + (i * 5); - for (int rx = 0; rx < 5; rx++) - { - AddDesignationSafe(map, Offset(offX + rx, 0), DesignationDefOf.Plan); - AddDesignationSafe(map, Offset(offX + rx, 4), DesignationDefOf.Plan); - } - for (int rz = 0; rz < 5; rz++) - { - AddDesignationSafe(map, Offset(offX + 4, rz), DesignationDefOf.Plan); - } - TryPlaceBlueprint(map, "Bed", Offset(offX + 2, 2), Rot4.South, "WoodLog"); - } - TryPlaceBlueprint(map, "Bed", Offset(2, 2), Rot4.South, "WoodLog"); - TryPlaceBlueprint(map, "Bed", Offset(2, 5), Rot4.South, "WoodLog"); - // Core communal hall dining facilities: prevent "Ate without table (-3)" debuff - TryPlaceBlueprint(map, "Table2x2c", Offset(5, 5), Rot4.North, "WoodLog"); - TryPlaceBlueprint(map, "Stool", Offset(5, 4), Rot4.North, "WoodLog"); - TryPlaceBlueprint(map, "Stool", Offset(5, 6), Rot4.South, "WoodLog"); - TryPlaceBlueprint(map, "TorchLamp", Offset(8, 8), Rot4.North, "WoodLog"); - break; - - case "mine": - string? targetDef = string.IsNullOrWhiteSpace(cmd.Target) ? null : cmd.Target.Trim(); - if (!string.IsNullOrEmpty(targetDef)) - { - if (targetDef.IndexOf("machinery", StringComparison.OrdinalIgnoreCase) >= 0 || - targetDef.IndexOf("component", StringComparison.OrdinalIgnoreCase) >= 0) - { - targetDef = "ComponentsIndustrial"; - } - else if (targetDef.IndexOf("steel", StringComparison.OrdinalIgnoreCase) >= 0) - { - targetDef = "Steel"; - } - } - var mineTarget = FindNearestMineable(map, safeBase, targetDef) ?? FindNearestMineable(map, safeBase, null); - if (mineTarget != null) - { - AddDesignationSafe(map, mineTarget.Position, DesignationDefOf.Mine); - for (int dx = -1; dx <= 1; dx++) - { - for (int dz = -1; dz <= 1; dz++) - { - var c = new IntVec3(mineTarget.Position.x + dx, mineTarget.Position.y, mineTarget.Position.z + dz); - if (c.InBounds(map)) - { - var thing = map.thingGrid.ThingAt(c, ThingCategory.Building); - if (thing != null && (thing.def.mineable || (thing.def.building != null && thing.def.building.isNaturalRock))) - { - AddDesignationSafe(map, c, DesignationDefOf.Mine); - } - } - } - } - } - break; - - case "grow": - string plant = !string.IsNullOrWhiteSpace(cmd.Target) ? cmd.Target.Trim() : "Plant_Rice"; - if (plant.Equals("Rice", StringComparison.OrdinalIgnoreCase) || plant.IndexOf("Rice", StringComparison.OrdinalIgnoreCase) >= 0) plant = "Plant_Rice"; - else if (plant.Equals("Potato", StringComparison.OrdinalIgnoreCase) || plant.IndexOf("Potato", StringComparison.OrdinalIgnoreCase) >= 0) plant = "Plant_Potato"; - else if (plant.Equals("Corn", StringComparison.OrdinalIgnoreCase) || plant.IndexOf("Corn", StringComparison.OrdinalIgnoreCase) >= 0) plant = "Plant_Corn"; - else if (plant.Equals("Healroot", StringComparison.OrdinalIgnoreCase) || plant.IndexOf("Healroot", StringComparison.OrdinalIgnoreCase) >= 0) plant = "Plant_Healroot"; - else if (plant.Equals("Cotton", StringComparison.OrdinalIgnoreCase) || plant.IndexOf("Cotton", StringComparison.OrdinalIgnoreCase) >= 0) plant = "Plant_Cotton"; - IntVec3 growPos = CellFinder.StandableCellNear(safeBase, map, 10); - CreateGrowingZoneSafe(map, growPos, 6, 6, plant); - break; - - case "build": - string target = (cmd.Target ?? string.Empty).ToLowerInvariant().Trim(); - if (target.Contains("bed")) - { - TryPlaceBlueprint(map, "Bed", Offset(2, 2), Rot4.South, "WoodLog"); - } - else if (target.Contains("stove") || target.Contains("fueledstove")) - { - var bp = TryPlaceBlueprint(map, "FueledStove", Offset(3, 4), Rot4.North, "WoodLog"); - if (bp == null) TryPlaceBlueprint(map, "TableStoveWood", Offset(3, 4), Rot4.North, "WoodLog"); - } - else if (target.Contains("butcher") || target.Contains("tablebutcher")) - { - TryPlaceBlueprint(map, "TableButcher", Offset(-8, -6), Rot4.North, "WoodLog"); - } - else if (target.Contains("passivecooler") || target.Contains("passive_cooler")) - { - TryPlaceBlueprint(map, "PassiveCooler", Offset(4, 5), Rot4.North, "WoodLog"); - } - else if (target.Contains("cooler")) - { - TryPlaceBlueprint(map, "Cooler", Offset(4, 5), Rot4.North, "Steel"); - } - else if (target.Contains("heater")) - { - TryPlaceBlueprint(map, "Heater", Offset(3, 2), Rot4.North, "Steel"); - } - else if (target.Contains("solar") || target.Contains("generator")) - { - TryPlaceBlueprint(map, "SolarGenerator", Offset(8, 8), Rot4.North, "Steel"); - } - else if (target.Contains("battery")) - { - TryPlaceBlueprint(map, "Battery", Offset(6, 6), Rot4.North, "Steel"); - } - else if (target.Contains("trap") || target.Contains("trapspike") || target.Contains("spike")) - { - TryPlaceBlueprint(map, "TrapSpike", Offset(0, 14), Rot4.North, "WoodLog"); - } - else if (target.Contains("grave")) - { - TryPlaceBlueprint(map, "Grave", Offset(-8, -8), Rot4.North); - TryPlaceBlueprint(map, "Grave", Offset(-8, -10), Rot4.North); - } - else if (target.Contains("torch") || target.Contains("torchlamp") || target.Contains("light")) - { - TryPlaceBlueprint(map, "TorchLamp", Offset(2, 3), Rot4.North, "WoodLog"); - } - else if (target.Contains("campfire") || target.Contains("fire")) - { - TryPlaceBlueprint(map, "Campfire", Offset(1, 4), Rot4.North, "WoodLog"); - } - else if (!string.IsNullOrWhiteSpace(cmd.Target)) - { - TryPlaceBlueprint(map, cmd.Target, Offset(4, 4), Rot4.North); - } - else - { - TryPlaceBlueprint(map, "Bed", Offset(2, 2), Rot4.South, "WoodLog"); - } - break; - - case "harvest_trees": - var trees = map.listerThings.AllThings - .Where(t => t.Spawned && t.def?.plant != null && (t.def.plant.IsTree || t.def.defName.Contains("Tree") || t.def.plant.harvestedThingDef == ThingDefOf.WoodLog)) - .OrderBy(t => t.Position.DistanceToSquared(safeBase)) - .Take(15); - foreach (var tree in trees) - { - var desDef = (tree is Plant p && p.HarvestableNow) ? DesignationDefOf.HarvestPlant : DesignationDefOf.CutPlant; - AddDesignationSafe(map, tree.Position, desDef ?? DesignationDefOf.CutPlant); - } - break; - - case "stockpile": - IntVec3 stockPos = IntVec3.Invalid; - for (int r = 2; r <= 16; r += 2) - { - var candidate = CellFinder.StandableCellNear(safeBase, map, r); - if (candidate.IsValid && candidate.InBounds(map)) - { - var room = candidate.GetRoom(map); - if (room != null && !room.PsychologicallyOutdoors) - { - stockPos = candidate; - break; - } - } - } - if (!stockPos.IsValid) - { - stockPos = CellFinder.StandableCellNear(safeBase, map, 6); - } - var stockZone = CreateStockpileZoneSafe(map, stockPos, 5, 5); - string stockTarget = (cmd.Target ?? string.Empty).ToLowerInvariant(); - bool isFoodOnlyStockpile = stockTarget.Contains("food") || stockTarget.Contains("meal") || stockTarget.Contains("meat") || stockTarget.Contains("freezer"); - if (stockZone != null && isFoodOnlyStockpile) - { - stockZone.settings.filter.SetDisallowAll(); - var meatCat = DefDatabase.GetNamedSilentFail("MeatRaw"); - if (meatCat != null) stockZone.settings.filter.SetAllow(meatCat, true); - var mealCat = DefDatabase.GetNamedSilentFail("FoodMeals"); - if (mealCat != null) stockZone.settings.filter.SetAllow(mealCat, true); - var foodsCat = DefDatabase.GetNamedSilentFail("FoodItems"); - if (foodsCat != null) stockZone.settings.filter.SetAllow(foodsCat, true); - } - break; - - case "clear_queue": - var runtimeScope = RuntimeServiceHub.Shared.Capture(); - var queue = runtimeScope.GetOptional(); - if (queue != null) - { - queue.CancelAllRequests(); - queue.ClearAllCooldowns(); - } - break; - - default: - ExecuteDailyColonyOperation(day, report); - break; - } - } - catch (Exception ex) - { - Log.Warning($"[RimMind-Playthrough][Day {day}] ExecuteSubagentCommand exception: {ex.Message}"); - ExecuteDailyColonyOperation(day, report); - } - - Log.Message($"[RimMind-Playthrough][Day {day}] Subagent Colony Command executed: [{report.ColonyOperationName}] {report.ColonyOperationDetail}"); - } - - private void ExecuteDailyColonyOperation(int day, PlaythroughDayReport report) - { - var map = Find.CurrentMap; - if (map == null) - { - report.ColonyOperationName = "营地例行巡视"; - report.ColonyOperationDetail = "未发现活动地图,执行状态保全"; - report.ColonyOperationSuccess = true; - Log.Message($"[RimMind-Playthrough][Day {day}] Colony Operation: [{report.ColonyOperationName}] {report.ColonyOperationDetail}"); - return; - } - - var colonists = GetLivingColonists(); - IntVec3 basePos = map.Center; - if (!basePos.InBounds(map)) basePos = map.Center; - IntVec3 safeBase = CellFinder.StandableCellNear(basePos, map, 8); - if (!safeBase.InBounds(map)) safeBase = map.Center; - - IntVec3 Offset(int dx, int dz) - { - var c = new IntVec3(safeBase.x + dx, safeBase.y, safeBase.z + dz); - return c.InBounds(map) ? c : safeBase; - } - - string opName; - string opDetail; - - try - { - switch (day) - { - case 1: - opName = "基地选址与建筑规划"; - opDetail = "下达 10x10 主集会大厅与 3 间 5x5 殖民者卧室建筑蓝图规划"; - for (int x = 0; x < 10; x++) - { - AddDesignationSafe(map, Offset(x, 0), DesignationDefOf.Plan); - AddDesignationSafe(map, Offset(x, 9), DesignationDefOf.Plan); - } - for (int z = 0; z < 10; z++) - { - AddDesignationSafe(map, Offset(0, z), DesignationDefOf.Plan); - AddDesignationSafe(map, Offset(9, z), DesignationDefOf.Plan); - } - for (int i = 0; i < 3; i++) - { - int offX = 10 + (i * 5); - for (int rx = 0; rx < 5; rx++) - { - AddDesignationSafe(map, Offset(offX + rx, 0), DesignationDefOf.Plan); - AddDesignationSafe(map, Offset(offX + rx, 4), DesignationDefOf.Plan); - } - } - break; - - case 2: - { - opName = "矿脉勘探与钢铁开采"; - opDetail = "勘探营地周边浅层矿脉,对附近可开采岩壁与钢铁矿石下达开采指令"; - var ores = map.listerThings.AllThings - .Where(t => t.Spawned && t.def != null && (t.def.mineable || (t.def.building != null && t.def.building.isNaturalRock) || t.def.defName.Contains("Mineable"))) - .OrderBy(t => t.Position.DistanceToSquared(safeBase)) - .Take(12); - foreach (var ore in ores) - { - AddDesignationSafe(map, ore.Position, DesignationDefOf.Mine); - } - } - break; - - case 3: - opName = "农业开垦与水稻种植"; - opDetail = "在肥沃土壤区划定 8x8 农田种植区,指定播种速生水稻作物"; - CreateGrowingZoneSafe(map, Offset(-12, 4), 8, 8, "Plant_Rice"); - break; - - case 4: - { - opName = "木料采伐与建材储备"; - opDetail = "标记殖民地外围成熟乔木进行木料砍伐,储备早期建筑与柴火资源"; - var trees = map.listerThings.ThingsInGroup(ThingRequestGroup.HarvestablePlant) - .Where(t => t.Spawned && t.def?.plant != null && t.def.plant.IsTree) - .OrderBy(t => t.Position.DistanceToSquared(safeBase)) - .Take(10); - foreach (var tr in trees) - { - AddDesignationSafe(map, tr.Position, DesignationDefOf.HarvestPlant); - } - } - break; - - case 5: - opName = "初级冷库与食品保鲜规划"; - opDetail = "规划 6x6 封闭低温冷库区域,设置专属食物保鲜储存区并放置保鲜规划"; - CreateStockpileZoneSafe(map, Offset(12, 10), 6, 6); - TryPlaceBlueprint(map, "Cooler", Offset(12, 9), Rot4.North, "Steel"); - break; - - case 6: - opName = "电力网络与太阳能建设"; - opDetail = "部署太阳能发电机组蓝图,并规划电力管线连接至核心生活区"; - TryPlaceBlueprint(map, "SolarGenerator", Offset(14, -6), Rot4.North, "Steel"); - TryPlaceBlueprint(map, "PowerConduit", Offset(12, -4), Rot4.North, "Steel"); - TryPlaceBlueprint(map, "PowerConduit", Offset(10, -2), Rot4.North, "Steel"); - break; - - case 7: - opName = "蓄电池组与电涌防护"; - opDetail = "在室内干燥区域放置蓄电池组蓝图,保障夜间供电与电网缓冲"; - TryPlaceBlueprint(map, "Battery", Offset(8, -4), Rot4.North, "Steel"); - break; - - case 8: - opName = "烹饪设施与食品卫生安全"; - opDetail = "设立殖民地配餐厨房,部署炉灶料理台蓝图保障饮食安全"; - TryPlaceBlueprint(map, "FueledStove", Offset(-4, -6), Rot4.North, "Steel"); - break; - - case 9: - opName = "屠宰台与生肉处理区"; - opDetail = "在厨房隔间部署木质屠宰台蓝图,开辟猎物解剖与皮毛处理专区"; - TryPlaceBlueprint(map, "TableButcher", Offset(-8, -6), Rot4.North, "WoodLog"); - break; - - case 10: - opName = "咽喉防线与木质尖刺陷阱阵"; - opDetail = "在营地出入口咽喉要道部署交错木刺陷阱与沙袋掩体构筑第一道防线"; - TryPlaceBlueprint(map, "TrapSpike", Offset(0, 14), Rot4.North, "WoodLog"); - TryPlaceBlueprint(map, "TrapSpike", Offset(2, 16), Rot4.North, "WoodLog"); - TryPlaceBlueprint(map, "TrapSpike", Offset(-2, 16), Rot4.North, "WoodLog"); - TryPlaceBlueprint(map, "Sandbags", Offset(0, 18), Rot4.North, "Steel"); - TryPlaceBlueprint(map, "Sandbags", Offset(1, 18), Rot4.North, "Steel"); - TryPlaceBlueprint(map, "Sandbags", Offset(-1, 18), Rot4.North, "Steel"); - break; - - case 11: - opName = "物资仓储细分与分类整理"; - opDetail = "细分主仓库存储策略,划分金属建材堆放区并下达物资分类归仓"; - CreateStockpileZoneSafe(map, Offset(6, 12), 7, 7); - break; - - case 12: - opName = "基础科研台建立与科技起步"; - opDetail = "在主营房设立研究区,部署简易基础科研台蓝图开启科技研发"; - TryPlaceBlueprint(map, "SimpleResearchBench", Offset(-4, 6), Rot4.North, "WoodLog"); - break; - - case 13: - opName = "舒适卧室建设与木质单人床"; - opDetail = "在已规划的 3 间独立卧室内分别部署木质舒适单人床蓝图"; - TryPlaceBlueprint(map, "Bed", Offset(11, 2), Rot4.North, "WoodLog"); - TryPlaceBlueprint(map, "Bed", Offset(16, 2), Rot4.North, "WoodLog"); - TryPlaceBlueprint(map, "Bed", Offset(21, 2), Rot4.North, "WoodLog"); - break; - - case 14: - opName = "娱乐活动中心与下棋休闲桌"; - opDetail = "在公共大厅部署下棋桌与休闲娱乐设施,保障殖民者精神娱乐与社交"; - TryPlaceBlueprint(map, "ChessTable", Offset(3, 4), Rot4.North, "WoodLog"); - break; - - case 15: - opName = "草药种植园与医疗物资储备"; - opDetail = "在避风沃土区划定 6x6 药草种植园,指定种植药用马草(草药)"; - CreateGrowingZoneSafe(map, Offset(-14, -6), 6, 6, "Plant_Healroot"); - break; - - case 16: - { - opName = "压缩机械零部件开采勘探"; - opDetail = "地质勘探发现压缩机械零部件矿脉,立即标记开采以备电气构件需求"; - var compRock = FindNearestMineable(map, safeBase, "ComponentsIndustrial") ?? FindNearestMineable(map, safeBase); - if (compRock != null) - { - AddDesignationSafe(map, compRock.Position, DesignationDefOf.Mine); - } - } - break; - - case 17: - opName = "殖民地急救医务室与医疗床"; - opDetail = "开辟干净封闭的殖民地急救医务室,部署专用医疗单人床蓝图"; - TryPlaceBlueprint(map, "Bed", Offset(-6, 2), Rot4.North, "WoodLog"); - break; - - case 18: - opName = "裁缝工坊与御寒衣物制作台"; - opDetail = "建设裁缝生产工坊,部署手工裁缝桌蓝图以制作防尘大衣与御寒衣物"; - TryPlaceBlueprint(map, "HandTailoringBench", Offset(4, -8), Rot4.North, "WoodLog"); - break; - - case 19: - opName = "风力发电机与清洁能源扩容"; - opDetail = "在空旷无障碍地带部署风力发电机蓝图,拓宽清洁可再生能源矩阵"; - TryPlaceBlueprint(map, "WindTurbine", Offset(18, -4), Rot4.East, "Steel"); - break; - - case 20: - opName = "铁匠锻造台与金属冷兵器工坊"; - opDetail = "建立金属冶炼锻造区,部署燃煤铁匠台蓝图以加工近战武器与金属工具"; - TryPlaceBlueprint(map, "FueledSmithy", Offset(8, -8), Rot4.North, "Steel"); - break; - - case 21: - opName = "外围花岗岩/石质防御城墙"; - opDetail = "规划并部署基地外围闭合防御城墙蓝图,阻断外来野兽与袭击者视线"; - for (int i = -3; i <= 3; i++) - { - TryPlaceBlueprint(map, "Wall", Offset(i, 20), Rot4.North, "Steel"); - } - break; - - case 22: - opName = "牲畜围栏与牧业畜牧标桩"; - opDetail = "规划 10x10 草地围栏区域,放置畜牧标桩并构筑围栏门保障禽畜养殖"; - TryPlaceBlueprint(map, "PenMarker", Offset(-16, 12), Rot4.North, "WoodLog"); - TryPlaceBlueprint(map, "FenceGate", Offset(-16, 10), Rot4.North, "WoodLog"); - break; - - case 23: - opName = "辐射尘应急避难地窖与储备规划"; - opDetail = "在山体岩层下方规划厚岩顶防辐射防空洞,设置紧急物资储备区"; - for (int x = 0; x < 5; x++) - { - for (int z = 0; z < 5; z++) - { - AddDesignationSafe(map, Offset(-18 + x, -12 + z), DesignationDefOf.Plan); - } - } - break; - - case 24: - opName = "自动化哨戒机枪与交叉火力网"; - opDetail = "在外围关键防御隘口部署自动化简易哨戒机枪蓝图,形成防御交叉火力"; - TryPlaceBlueprint(map, "Turret_MiniTurret", Offset(4, 19), Rot4.North, "Steel"); - TryPlaceBlueprint(map, "Turret_MiniTurret", Offset(-4, 19), Rot4.North, "Steel"); - break; - - case 25: - opName = "优质棉花种植与织物面料丰产"; - opDetail = "划定 8x8 农田种植高产棉花作物,为后续护甲衬里与高档服饰提供布料"; - CreateGrowingZoneSafe(map, Offset(-12, -14), 8, 8, "Plant_Cotton"); - break; - - case 26: - { - opName = "深层地热发电机组建设"; - opDetail = "探勘并锁定地图上的地热喷气孔,在上方精准部署重型地热发电机蓝图"; - var geyser = map.listerThings.AllThings.FirstOrDefault(t => t.Spawned && t.def?.defName == "SteamGeyser"); - IntVec3 geoPos = geyser != null ? geyser.Position : Offset(20, 15); - TryPlaceBlueprint(map, "GeothermalGenerator", geoPos, Rot4.North, "Steel"); - } - break; - - case 27: - opName = "营养膏合成机与应急口粮保障"; - opDetail = "在餐厅厨房交界处部署营养膏合成机与料斗蓝图,建立零烹饪中毒风险口粮保障"; - TryPlaceBlueprint(map, "NutrientPasteDispenser", Offset(-6, -9), Rot4.North, "Steel"); - TryPlaceBlueprint(map, "Hopper", Offset(-6, -8), Rot4.North, "Steel"); - break; - - case 28: - opName = "切石桌与石材块加工生产线"; - opDetail = "设立切石加工工坊,部署切石桌蓝图将天然巨石转化为防火坚固石块"; - TryPlaceBlueprint(map, "TableStonecutter", Offset(6, -10), Rot4.North, "WoodLog"); - break; - - case 29: - opName = "灭火泡沫发生器与防灾管线"; - opDetail = "在电池房与核心发电机房关键过热易燃点部署灭火泡沫发生器"; - TryPlaceBlueprint(map, "FirefoamPopper", Offset(8, -6), Rot4.North, "Steel"); - break; - - case 30: - opName = "月度开拓庆典与殖民地篝火晚会"; - opDetail = "在中心广场搭建中央篝火与长条聚餐桌,举办开拓满月庆典提振殖民者士气"; - TryPlaceBlueprint(map, "Campfire", Offset(0, 5), Rot4.North, "WoodLog"); - break; - - case 31: - opName = "专用军械架与枪械弹药库规划"; - opDetail = "在防线后方构筑室内军械库,部署双联储物架用于规范收纳枪械与备用防具"; - TryPlaceBlueprint(map, "Shelf", Offset(2, 12), Rot4.North, "WoodLog"); - TryPlaceBlueprint(map, "Shelf", Offset(-2, 12), Rot4.North, "WoodLog"); - break; - - case 32: - opName = "无土水培温室水培仓阵列"; - opDetail = "规划室内恒温无土水培农业室,部署水培水槽阵列与太阳灯蓝图"; - TryPlaceBlueprint(map, "HydroponicsBasin", Offset(-10, 16), Rot4.North, "Steel"); - TryPlaceBlueprint(map, "SunLamp", Offset(-8, 16), Rot4.North, "Steel"); - break; - - case 33: - opName = "迫击炮阵地与防空重型火炮"; - opDetail = "在安全内院构筑迫击炮掩体阵地,部署重型迫击炮蓝图以实施远程炮击压制"; - TryPlaceBlueprint(map, "Turret_Mortar", Offset(10, 18), Rot4.North, "Steel"); - break; - - case 34: - opName = "无菌地板与高标准手术室"; - opDetail = "在中央手术室与科研实验室地面规划无菌地砖蓝图,大幅降低术后感染率"; - for (int x = 0; x < 3; x++) - { - for (int z = 0; z < 3; z++) - { - TryPlaceBlueprint(map, "SterileTile", Offset(-6 + x, 2 + z)); - } - } - break; - - case 35: - opName = "精神冥想殿堂与自然冥想祭坛"; - opDetail = "在营地清幽角落设定精神冥想点与自然祭坛,供殖民者进行灵能与专注冥想"; - TryPlaceBlueprint(map, "MeditationSpot", Offset(15, 6)); - break; - - case 36: - opName = "远征商队打包点与行装整备区"; - opDetail = "在主仓库门口开阔区域划定商队打包集结地,方便物资装载与对外贸易远征"; - TryPlaceBlueprint(map, "CaravanPackingSpot", Offset(8, 16)); - break; - - case 37: - opName = "生物精炼厂与化合燃料提炼"; - opDetail = "设立生化精炼车间,部署生物化合燃料精炼器蓝图将有机物转化为燃油"; - TryPlaceBlueprint(map, "BiofuelRefinery", Offset(10, -10), Rot4.North, "Steel"); - break; - - case 38: - opName = "精密防具工作台与复合护甲锻造"; - opDetail = "筹建重型军工车间,规划防弹背心与强化复合装甲生产线"; - TryPlaceBlueprint(map, "TableMachining", Offset(12, -8), Rot4.North, "Steel"); - break; - - case 39: - opName = "殖民者战术训练假人与靶场"; - opDetail = "在防区侧翼开辟射击练习靶场,划定战术射击标靶区域以磨砺殖民者射击技能"; - TryPlaceBlueprint(map, "Sandbags", Offset(14, 18), Rot4.North, "Steel"); - AddDesignationSafe(map, Offset(14, 22), DesignationDefOf.Plan); - break; - - case 40: - { - opName = "深层金矿/贵金属地质探矿"; - opDetail = "地质勘探锁定高纯度伴生金矿脉,下达精准爆破与采金指令以备高科技组件"; - var gold = FindNearestMineable(map, safeBase, "Gold") ?? FindNearestMineable(map, safeBase); - if (gold != null) - { - AddDesignationSafe(map, gold.Position, DesignationDefOf.Mine); - } - } - break; - - case 41: - opName = "工业级精密机械加工台"; - opDetail = "在工坊核心区域部署精密机械加工台蓝图,开启工业机械构件自主生产"; - TryPlaceBlueprint(map, "TableMachining", Offset(6, -12), Rot4.North, "Steel"); - break; - - case 42: - opName = "轨道通讯台与远距离贸易信标"; - opDetail = "架设轨道通讯台与轨道贸易信标蓝图,建立与过境轨道商船的外交贸易航线"; - TryPlaceBlueprint(map, "CommsConsole", Offset(-2, 8), Rot4.North, "Steel"); - TryPlaceBlueprint(map, "OrbitalTradeBeacon", Offset(8, 14), Rot4.North, "Steel"); - break; - - case 43: - opName = "全基地室外照明与泛光灯布局"; - opDetail = "在主通道与防御哨塔沿线部署室外立式泛光灯,消除黑暗射击惩罚与移动减速"; - TryPlaceBlueprint(map, "StandingLamp", Offset(0, 10), Rot4.North, "Steel"); - TryPlaceBlueprint(map, "StandingLamp", Offset(5, 5), Rot4.North, "Steel"); - TryPlaceBlueprint(map, "StandingLamp", Offset(-5, 5), Rot4.North, "Steel"); - break; - - case 44: - opName = "双联重型深冷库与冻肉保鲜升级"; - opDetail = "扩建第二主冷库,部署双联空调制冷机并铺设双层隔热岩棉墙"; - CreateStockpileZoneSafe(map, Offset(16, 12), 6, 6); - TryPlaceBlueprint(map, "Cooler", Offset(16, 11), Rot4.North, "Steel"); - break; - - case 45: - opName = "高科技研究台与多元科技分析仪"; - opDetail = "落成高科技科研中心,部署高科技研究台与多元分析仪蓝图冲刺顶尖科技"; - TryPlaceBlueprint(map, "HiTechResearchBench", Offset(-6, 8), Rot4.North, "Steel"); - TryPlaceBlueprint(map, "MultiAnalyzer", Offset(-8, 8), Rot4.North, "Steel"); - break; - - case 46: - opName = "仿生器官制造与义体升级工坊"; - opDetail = "设立义体与仿生医疗工坊,规划仿生眼与仿生臂高级组装生产线"; - TryPlaceBlueprint(map, "FabricationBench", Offset(14, -10), Rot4.North, "Steel"); - break; - - case 47: - opName = "重型防爆装甲门与气闸防线"; - opDetail = "将外围木门替换为厚重钢制自动防爆门,构筑内外双层安全气闸仓"; - TryPlaceBlueprint(map, "Autodoor", Offset(0, 19), Rot4.North, "Steel"); - break; - - case 48: - opName = "深钻井与地下矿床深层探测"; - opDetail = "在地下矿藏扫描点部署深层钻井蓝图,持续开采地底深埋的大规模金属与原石矿"; - TryPlaceBlueprint(map, "DeepDrill", Offset(16, 4), Rot4.North, "Steel"); - break; - - case 49: - opName = "外交宾客客房与豪华招待套房"; - opDetail = "装潢独立贵宾套房,部署豪华皇家大床与高档艺术品蓝图以接待外来同盟势力"; - TryPlaceBlueprint(map, "RoyalBed", Offset(22, 6), Rot4.North, "WoodLog"); - break; - - case 50: - opName = "电磁脉冲 EMP 陷阱阵与机械族防御"; - opDetail = "在外围防御通道布设感应式 EMP 电磁脉冲陷阱阵列,严阵以待机械族突袭"; - TryPlaceBlueprint(map, "TrapIED_EMP", Offset(2, 17), Rot4.North, "Steel"); - TryPlaceBlueprint(map, "TrapIED_EMP", Offset(-2, 17), Rot4.North, "Steel"); - break; - - case 51: - opName = "全基地智能通风管道与温控网络"; - opDetail = "在所有卧室与公共房间墙体部署温控通风口蓝图,实现全殖民地热对流均匀平衡"; - TryPlaceBlueprint(map, "Vent", Offset(10, 3), Rot4.North, "Steel"); - TryPlaceBlueprint(map, "Vent", Offset(15, 3), Rot4.North, "Steel"); - break; - - case 52: - opName = "动力装甲与精良动力头盔锻造规划"; - opDetail = "启动终极动力装甲装配计划,在制造工坊锁定玻璃钢与高级零部件配额"; - for (int x = 0; x < 3; x++) - { - AddDesignationSafe(map, Offset(14 + x, -12), DesignationDefOf.Plan); - } - break; - - case 53: - opName = "艺术雕刻台与宏伟殖民地雕塑"; - opDetail = "设立艺术创作画廊,部署大型雕刻台蓝图以雕琢宏伟巨型雕塑美化殖民地环境"; - TryPlaceBlueprint(map, "TableSculpting", Offset(4, 8), Rot4.North, "WoodLog"); - break; - - case 54: - opName = "个人能量护盾与护盾发生器工坊"; - opDetail = "规划高能防护装备车间,安排精细加工线筹备个人护盾核心发生器"; - TryPlaceBlueprint(map, "Shelf", Offset(4, 14), Rot4.North, "Steel"); - break; - - case 55: - { - opName = "基地地下紧急逃生暗道与撤离路线"; - opDetail = "对基地背靠后山下达暗道开凿指定,打通直穿后山峡谷的紧急撤离逃生暗道"; - var rearRock = FindNearestMineable(map, Offset(0, -20)) ?? FindNearestMineable(map, safeBase); - IntVec3 tunnelStart = rearRock != null ? rearRock.Position : Offset(0, -22); - for (int i = 0; i < 6; i++) - { - AddDesignationSafe(map, new IntVec3(tunnelStart.x, tunnelStart.y, tunnelStart.z - i), DesignationDefOf.Mine); - } - } - break; - - case 56: - { - opName = "全殖民地物资总盘点与军备清查"; - opDetail = "开展第 56 日全殖民地物资大清查,下达全图散落资源搬运归仓与耐久检修"; - var haulables = map.listerThings.ThingsInGroup(ThingRequestGroup.HaulableAlways) - .Where(t => t.Spawned) - .OrderBy(t => t.Position.DistanceToSquared(safeBase)) - .Take(15); - foreach (var h in haulables) - { - AddDesignationSafe(map, h.Position, DesignationDefOf.Haul); - } - } - break; - - case 57: - opName = "药剂合成台与高级生化药物试制"; - opDetail = "设立高级生化制药实验室,部署制药台蓝图以调配消炎药、抗菌素与闪耀世界药剂替代品"; - TryPlaceBlueprint(map, "DrugLab", Offset(-8, 4), Rot4.North, "Steel"); - break; - - case 58: - opName = "飞船结构核心与深空引擎研发筹备"; - opDetail = "划定飞船发射升空平台规划区,部署飞船结构梁与低温休眠舱实验蓝图"; - for (int x = 0; x < 6; x++) - { - for (int z = 0; z < 6; z++) - { - AddDesignationSafe(map, Offset(20 + x, -18 + z), DesignationDefOf.Plan); - } - } - break; - - case 59: - opName = "全殖民地要塞全武备战备检查"; - opDetail = "巡视全基地外围防线、重型迫击炮与防御机枪阵地,执行全面战备修缮与弹药填装"; - TryPlaceBlueprint(map, "Sandbags", Offset(3, 19), Rot4.North, "Steel"); - TryPlaceBlueprint(map, "Sandbags", Offset(-3, 19), Rot4.North, "Steel"); - break; - - case 60: - { - opName = "六十日终极丰收大庆典与胜利荣耀纪念碑"; - opDetail = "在中心广场落成 60 日宏伟胜利开拓纪念碑蓝图,开启殖民地终极大丰收全员狂欢庆典!"; - TryPlaceBlueprint(map, "SculptureGrand", Offset(0, 2), Rot4.North, "WoodLog"); - TryPlaceBlueprint(map, "Campfire", Offset(0, 0), Rot4.North, "WoodLog"); - var allCrops = map.listerThings.ThingsInGroup(ThingRequestGroup.HarvestablePlant) - .Where(t => t.Spawned) - .Take(20); - foreach (var cr in allCrops) - { - AddDesignationSafe(map, cr.Position, DesignationDefOf.HarvestPlant); - } - } - break; - - default: - opName = "殖民地例行巡视与维护"; - opDetail = "对殖民地核心设备与防御工事进行例行状态巡检"; - break; - } - - report.ColonyOperationName = opName; - report.ColonyOperationDetail = opDetail; - report.ColonyOperationSuccess = true; - } - catch (Exception ex) - { - report.ColonyOperationName = $"第 {day} 日开拓作业"; - report.ColonyOperationDetail = $"操作遇环境调整容灾完成: {ex.Message}"; - report.ColonyOperationSuccess = true; - } - - Log.Message($"[RimMind-Playthrough][Day {day}] Colony Operation: [{report.ColonyOperationName}] {report.ColonyOperationDetail}"); - } - - private IEnumerator CaptureDayScreenshot(int day, PlaythroughDayReport report) - { - yield return new WaitForEndOfFrame(); - - string fileName = $"day-{day:D2}.png"; - string filePath = Path.Combine(_outputDir, fileName); - - try - { - if (Find.CurrentMap != null && Find.CameraDriver != null) Find.CameraDriver.JumpToCurrentMapLoc(Find.CurrentMap.Center); Texture2D screenshot = ScreenCapture.CaptureScreenshotAsTexture(); - byte[] bytes = screenshot.EncodeToPNG(); - File.WriteAllBytes(filePath, bytes); - UnityEngine.Object.Destroy(screenshot); - report.ScreenshotPath = filePath; - Log.Message($"[RimMind-Playthrough][Day {day}] Saved screenshot to: {filePath}"); - } - catch (Exception ex) - { - Log.Warning($"[RimMind-Playthrough][Day {day}] Failed to capture screenshot: {ex.Message}"); - } - } - - private void SaveReportCheckpoint() - { - try - { - string json = JsonConvert.SerializeObject(_report, Formatting.Indented); - string reportPath = Path.Combine(_outputDir, $"playthrough-{_totalDays}days-report.json"); - File.WriteAllText(reportPath, json, Encoding.UTF8); - // Also write default name for compatibility with monitoring scripts - File.WriteAllText(Path.Combine(_outputDir, "playthrough-10days-report.json"), json, Encoding.UTF8); - GeneratePlaythroughChronicle(); - } - catch (Exception ex) - { - Log.Warning("[RimMind-Playthrough] Failed to save report checkpoint: " + ex.Message); - } - } - - private void GeneratePlaythroughChronicle() - { - try - { - var sb = new StringBuilder(); - sb.AppendLine($"# RimMind 殖民地 {_totalDays} 日实机生存编年史与玩法分析报告"); - sb.AppendLine(); - sb.AppendLine($"> **推演运行 ID**: `{_report.RunId}`"); - sb.AppendLine($"> **模型端点**: `{_report.Endpoint}` ({_report.Model})"); - sb.AppendLine($"> **推演总耗时**: {_report.TotalDurationMs / 1000f:F1} 秒 | **总 Ticks**: {_report.TotalTicksElapsed:N0} ({_totalDays} 个游戏日)"); - sb.AppendLine($"> **真实 LLM 请求数**: {_report.TotalLiveLlmRequests} 次 | **Token 消耗**: {_report.TotalTokensConsumed:N0} tokens"); - sb.AppendLine($"> **平均 KV-Cache 命中率**: **{_report.AverageCacheHitRatio:F1}%** (4-Zone 架构保真)"); - sb.AppendLine(); - sb.AppendLine("---"); - sb.AppendLine(); - - foreach (var d in _report.Days) - { - sb.AppendLine($"## 第 {d.DayNumber} 天 · {d.DateString}"); - sb.AppendLine(); - sb.AppendLine($"### 1. 殖民者晨间心智 ({d.MorningPawnName})"); - sb.AppendLine($"> *\"{d.MorningThought}\"*"); - sb.AppendLine(); - if (!string.IsNullOrWhiteSpace(d.ColonyOperationName)) - { - sb.AppendLine($"### 2. 殖民地经营与建设行动 (`{d.ColonyOperationName}`)"); - sb.AppendLine($"- **执行事项**: {d.ColonyOperationDetail}"); - sb.AppendLine($"- **执行状态**: {(d.ColonyOperationSuccess ? "✅ 规划部署成功" : "⚠️ 异常已妥善处理")}"); - sb.AppendLine(); - } - if (!string.IsNullOrWhiteSpace(d.DialogueSpeech)) - { - sb.AppendLine($"### 3. 社交交谈与关系变动 (`express_dialogue`)"); - sb.AppendLine($"- **交谈**: **{d.DialogueSpeaker}** 对 **{d.DialogueListener}** 说:"); - sb.AppendLine($" > *\"{d.DialogueSpeech}\"*"); - sb.AppendLine($"- **心情标签**: `{d.DialogueThoughtTag}` | **好感度变动**: `{(d.DialogueRelationDelta >= 0 ? "+" : "")}{d.DialogueRelationDelta}`"); - sb.AppendLine(); - } - - if (!string.IsNullOrWhiteSpace(d.AgentActionTool)) - { - sb.AppendLine($"### 4. 午后智能体自主决策 (`{d.AgentActionTool}`)"); - sb.AppendLine($"- **殖民者**: **{d.AgentActionPawn}**"); - sb.AppendLine($"- **行动决策**: `{d.AgentActionDetail}`"); - sb.AppendLine($"- **决策动机**: *\"{d.AgentActionReason}\"*"); - sb.AppendLine(); - } - sb.AppendLine($"### 5. 顾问决策建议与审批"); - sb.AppendLine($"- **建议事项**: {d.AdvisorProposal}"); - sb.AppendLine($"- **审批状态**: {(d.AdvisorApproved ? "✅ 已批准执行" : "❌ 已驳回")}"); - sb.AppendLine(); - sb.AppendLine($"### 6. 运行时指标"); - sb.AppendLine($"- **Prompt Caching 估算命中率**: **{d.CacheHitRatio:F1}%** (前缀 {d.PrefixTokens} tokens)"); - sb.AppendLine($"- **Token 消耗**: {d.TotalTokensUsed} tokens | **计算耗时**: {d.DayComputeDurationMs}ms"); - if (!string.IsNullOrWhiteSpace(d.ScreenshotPath)) - { - sb.AppendLine($"- **截帧存档**: `{Path.GetFileName(d.ScreenshotPath)}`"); - } - sb.AppendLine(); - sb.AppendLine("---"); - sb.AppendLine(); - } - - string chroniclePath = Path.Combine(_outputDir, $"playthrough-{_totalDays}days-chronicle.md"); - File.WriteAllText(chroniclePath, sb.ToString(), Encoding.UTF8); - File.WriteAllText(Path.Combine(_outputDir, "playthrough-10days-chronicle.md"), sb.ToString(), Encoding.UTF8); - if (_report.OverallStatus == "COMPLETED") - { - Log.Message($"[RimMind-Playthrough] Chronicle generated at: {chroniclePath}"); - } - } - catch (Exception ex) - { - Log.Warning("[RimMind-Playthrough] Failed to generate chronicle: " + ex.Message); - } - } - - private void OnDestroy() - { - RestorePlayerSettings(); - if (_active == this) _active = null; - } } } diff --git a/Source/Infrastructure/UI/DebugCenter/DebugCenterNavigation.cs b/Source/Infrastructure/UI/DebugCenter/DebugCenterNavigation.cs index f64d8ec..96ed5b1 100644 --- a/Source/Infrastructure/UI/DebugCenter/DebugCenterNavigation.cs +++ b/Source/Infrastructure/UI/DebugCenter/DebugCenterNavigation.cs @@ -1,12 +1,24 @@ +using System; + namespace RimMind.Infrastructure.UI.DebugCenter { public sealed class DebugCenterNavigation { public string? RequestedPageId { get; private set; } + public string? RequestedSubTabId { get; private set; } + + public void GoTo(string pageId, string? subTabId = null) + { + ResolveRoute(pageId, out string resolvedPageId, out string? resolvedSubTabId); + RequestedPageId = resolvedPageId; + RequestedSubTabId = !string.IsNullOrWhiteSpace(subTabId) + ? subTabId!.Trim() + : resolvedSubTabId; + } - public void GoTo(string pageId) + public void SetRequestedSubTab(string? subTabId) { - RequestedPageId = pageId; + RequestedSubTabId = string.IsNullOrWhiteSpace(subTabId) ? null : subTabId!.Trim(); } public string? ConsumeRequestedPageId() @@ -15,5 +27,62 @@ public void GoTo(string pageId) RequestedPageId = null; return requestedPageId; } + + public string? ConsumeRequestedSubTabId() + { + string? requestedSubTabId = RequestedSubTabId; + RequestedSubTabId = null; + return requestedSubTabId; + } + + public static void ResolveRoute(string? rawRoute, out string pageId, out string? subTabId) + { + if (string.IsNullOrWhiteSpace(rawRoute)) + { + pageId = string.Empty; + subTabId = null; + return; + } + + string trimmed = rawRoute!.Trim(); + int colonIndex = trimmed.IndexOf(':'); + if (colonIndex > 0) + { + pageId = trimmed.Substring(0, colonIndex).Trim(); + string rawSub = trimmed.Substring(colonIndex + 1).Trim(); + subTabId = rawSub.Length > 0 ? rawSub : null; + return; + } + + switch (trimmed.ToLowerInvariant()) + { + case "tool_calls": + pageId = "capabilities"; + subTabId = "tool_calls"; + return; + case "mechanisms": + pageId = "capabilities"; + subTabId = "mechanisms"; + return; + case "context_keys": + pageId = "capabilities"; + subTabId = "context_keys"; + return; + case "rollout": + case "rollouts": + pageId = "ai_requests"; + subTabId = "rollout"; + return; + case "ephemeral": + case "ephemeral_requests": + pageId = "ai_requests"; + subTabId = "ephemeral"; + return; + default: + pageId = trimmed; + subTabId = null; + return; + } + } } } diff --git a/Source/Infrastructure/UI/DebugCenter/DebugCenterPageRegistry.cs b/Source/Infrastructure/UI/DebugCenter/DebugCenterPageRegistry.cs index 363671e..60bff90 100644 --- a/Source/Infrastructure/UI/DebugCenter/DebugCenterPageRegistry.cs +++ b/Source/Infrastructure/UI/DebugCenter/DebugCenterPageRegistry.cs @@ -50,31 +50,17 @@ private static void RegisterBuiltInPages() Register(new DebugCenterPageDescriptor( "ai_requests", - "RimMind.UI.Hub.Tab.AIRequests", + "RimMind.UI.Hub.Tab.Traces", 20, IsDefault: false, OwnerModId: RimMindOwnerConsts.CoreModId), () => new AIRequestsDebugCenterPageDrawer(log: null)); Register(new DebugCenterPageDescriptor( - "tool_calls", - "RimMind.UI.Hub.Tab.ToolCalls", + "capabilities", + "RimMind.UI.Hub.Tab.Capabilities", 30, IsDefault: false, - OwnerModId: RimMindOwnerConsts.CoreModId), () => new ToolCallsDebugCenterPageDrawer(new ToolCallsDebugTableModelBuilder())); - - Register(new DebugCenterPageDescriptor( - "mechanisms", - "RimMind.UI.Hub.Tab.Mechanisms", - 40, - IsDefault: false, - OwnerModId: RimMindOwnerConsts.CoreModId), () => new MechanismsDebugCenterPageDrawer(new MechanismsDebugTableModelBuilder())); - - Register(new DebugCenterPageDescriptor( - "context_keys", - "RimMind.UI.Hub.Tab.ContextKeys", - 50, - IsDefault: false, - OwnerModId: RimMindOwnerConsts.CoreModId), () => new ContextKeysDebugCenterPageDrawer(new ContextKeysDebugTableModelBuilder())); + OwnerModId: RimMindOwnerConsts.CoreModId), () => new CapabilitiesDebugCenterPageDrawer()); Register(new DebugCenterPageDescriptor( "settings", diff --git a/Source/Infrastructure/UI/DebugCenter/Pages/AIRequestsDebugCenterPageDrawer.cs b/Source/Infrastructure/UI/DebugCenter/Pages/AIRequestsDebugCenterPageDrawer.cs index 62c4359..78ecd87 100644 --- a/Source/Infrastructure/UI/DebugCenter/Pages/AIRequestsDebugCenterPageDrawer.cs +++ b/Source/Infrastructure/UI/DebugCenter/Pages/AIRequestsDebugCenterPageDrawer.cs @@ -1,13 +1,15 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text; using RimMind.Application.Common.Interfaces.Internal; using RimMind.Application.Common.Models.Debug; using RimMind.Infrastructure.UI.DebugTables; using RimMind.Infrastructure.UI.Framework; +using RimMind.Presentation.Api; +using RimMind.Presentation.Runtime.Services; using RimMind.Presentation.UI.Framework; using RimMind.Presentation.UI.Layout; -using RimMind.Presentation.Runtime.Services; using UnityEngine; using Verse; @@ -15,27 +17,54 @@ namespace RimMind.Infrastructure.UI.DebugCenter.Pages { public sealed class AIRequestsDebugCenterPageDrawer : IRuntimeBoundDebugCenterPageDrawer { + private const string SubTabRollout = "rollout"; + private const string SubTabEphemeral = "ephemeral"; + + private readonly RimMindTabbedPageHostDrawer _tabDrawer = new(); private readonly RimMindTableDrawer _tableDrawer = new(); + private IAIRequestTraceLog? _log; - private string? _selectedRequestId; private long _cachedRevision = long.MinValue; private long _cachedGeneration = long.MinValue; - private IReadOnlyList _cachedEntries = System.Array.Empty(); - private DebugTableModel? _cachedModel; + private IReadOnlyList _cachedEntries = Array.Empty(); + private IReadOnlyList _cachedRollouts = Array.Empty(); + private IReadOnlyList? _displaySnapshot; + + private string _activeSubTab = SubTabRollout; + private bool _subTabPinnedByUser; + private string? _selectedRolloutId; + private string? _selectedRequestId; + + private string _rolloutActorFilter = string.Empty; + private AIRequestTraceState? _rolloutStateFilter; + private string _rolloutSearchQuery = string.Empty; + + private string _ephemeralModFilter = string.Empty; + private string _ephemeralScenarioFilter = string.Empty; + private string _ephemeralActorFilter = string.Empty; + private AIRequestTraceState? _ephemeralStateFilter; + private string _ephemeralSearchQuery = string.Empty; + private bool _includeRolloutTurnsInEphemeral; + + private readonly HashSet _expandedLayers = new(StringComparer.OrdinalIgnoreCase) { "L4", "User" }; + private readonly HashSet _expandedPromptSections = new(StringComparer.OrdinalIgnoreCase); + private Vector2 _tableScrollPosition; private Vector2 _detailScrollPosition; - private IReadOnlyList? _displaySnapshot; // Local display-only data: never published to the live trace log or request queue. - internal void UseDisplaySnapshot(IReadOnlyList entries) => _displaySnapshot = entries; + internal void UseDisplaySnapshot(IReadOnlyList entries) + { + _displaySnapshot = entries; + _subTabPinnedByUser = false; + } + internal void ScrollToBottom() { _tableScrollPosition = new Vector2(0, 100000f); _detailScrollPosition = new Vector2(0, 100000f); } - private sealed record DetailSection(string Title, string Body); - public AIRequestsDebugCenterPageDrawer(IAIRequestTraceLog? log = null) { _log = log; @@ -48,162 +77,836 @@ public AIRequestsDebugCenterPageDrawer(IAIRequestTraceLog? log = null) { _log = log; _selectedRequestId = null; + _selectedRolloutId = null; _cachedGeneration = scope.Generation; _cachedRevision = long.MinValue; _cachedEntries = Array.Empty(); - _cachedModel = null; + _cachedRollouts = Array.Empty(); } + return null; } public void Draw(Rect rect, DebugCenterPageContext context, RimMindLayoutScope scope) { + ApplyRequestedSubTab(context.Navigation.ConsumeRequestedSubTabId()); + if (_log == null && _displaySnapshot == null) { - DrawEmptyTable(rect, "RimMind.UI.AIRequestsPage.TraceUnavailable".Translate(), scope); + DrawEmptyTable(rect, SafeTranslate("RimMind.UI.AIRequestsPage.TraceUnavailable", "AI trace log unavailable."), scope); return; } RefreshSnapshot(); - IReadOnlyList entries = _cachedEntries; - DebugTableModel model = _cachedModel!; - if (entries.Count == 0) + if (!_subTabPinnedByUser && _displaySnapshot != null && _cachedRollouts.Count == 0 && _cachedEntries.Count > 0) + _activeSubTab = SubTabEphemeral; + + var ephemeralBaseline = AgentRolloutModelBuilder.FilterEphemeral( + _cachedEntries, + new EphemeralTraceFilter(IncludeRolloutTurns: false), + ResolveActorDisplayName); + + var tabs = BuildTabs(_cachedRollouts.Count, ephemeralBaseline.Count); + TabbedPageLayoutResult tabLayout = TabbedPageLayout.Calculate(rect, tabs); + string nextTab = _tabDrawer.DrawTabs(tabLayout, tabs, _activeSubTab, scope); + if (!string.Equals(nextTab, _activeSubTab, StringComparison.Ordinal)) + { + _activeSubTab = nextTab; + _subTabPinnedByUser = true; + _detailScrollPosition = Vector2.zero; + } + + if (_activeSubTab == SubTabEphemeral) + DrawEphemeralView(tabLayout.Content, scope); + else + DrawRolloutView(tabLayout.Content, scope); + } + + private void ApplyRequestedSubTab(string? requested) + { + if (string.IsNullOrWhiteSpace(requested)) + return; + + string normalized = requested!.Trim().ToLowerInvariant(); + if (normalized is SubTabRollout or SubTabEphemeral) + { + _activeSubTab = normalized; + _subTabPinnedByUser = true; + } + } + + private List BuildTabs(int rolloutCount, int ephemeralCount) + { + string rolloutLabel = $"{SafeTranslate("RimMind.UI.Traces.SubTab.Rollout", "Agent Rollout")} ({rolloutCount})"; + string ephemeralLabel = $"{SafeTranslate("RimMind.UI.Traces.SubTab.Ephemeral", "One-Off Requests")} ({ephemeralCount})"; + return new List + { + new TabbedPageTabModel( + SubTabRollout, + rolloutLabel, + "RimMind.UI.Traces.SubTab.Rollout", + _activeSubTab == SubTabRollout, + enabled: true, + tooltipKey: "RimMind.UI.Traces.SubTab.RolloutTip"), + new TabbedPageTabModel( + SubTabEphemeral, + ephemeralLabel, + "RimMind.UI.Traces.SubTab.Ephemeral", + _activeSubTab == SubTabEphemeral, + enabled: true, + tooltipKey: "RimMind.UI.Traces.SubTab.EphemeralTip") + }; + } + + private void DrawRolloutView(Rect rect, RimMindLayoutScope scope) + { + const float filterHeight = 28f; + Rect filterRect = new Rect(rect.x, rect.y, rect.width, filterHeight); + DrawRolloutFilterBar(filterRect, scope); + + Rect bodyRect = new Rect( + rect.x, + filterRect.yMax + RimMindUiMetrics.SectionGap, + rect.width, + Mathf.Max(1f, rect.height - filterHeight - RimMindUiMetrics.SectionGap)); + + IReadOnlyList rollouts = AgentRolloutModelBuilder.BuildRollouts( + _cachedEntries, + _rolloutActorFilter, + _rolloutStateFilter, + _rolloutSearchQuery, + ResolveActorDisplayName); + + if (rollouts.Count == 0) { - _tableDrawer.Draw(rect, model, ref _tableScrollPosition, scope); + RimMindUI.DrawEmptyState( + bodyRect, + SafeTranslate("RimMind.UI.Traces.Rollout.Empty", "No agent rollout trajectories match the current filter.")); return; } - SplitPageLayoutResult split = SplitPageLayout.Calculate(rect, 0.4f, 240f, 300f, 320f); - AIRequestTraceEntry selectedEntry = ResolveSelectedEntry(entries); + SplitPageLayoutResult split = SplitPageLayout.Calculate(bodyRect, 0.37f, 230f, 320f, 340f); + scope.Record(split.List, "Rollout:EpisodeList"); + scope.Record(split.Detail, "Rollout:TrajectoryDetail"); + + AgentRolloutEpisode selected = rollouts.FirstOrDefault(e => e.RolloutId == _selectedRolloutId) ?? rollouts[0]; + _selectedRolloutId = selected.RolloutId; + + DrawRolloutList(split.List, rollouts); + DrawRolloutDetail(split.Detail, selected); + } + + private void DrawRolloutFilterBar(Rect rect, RimMindLayoutScope scope) + { + scope.Record(rect, "Rollout:FilterBar"); + float x = rect.x; + const float gap = 6f; + + float actorW = Mathf.Min(150f, rect.width * 0.24f); + Rect actorRect = new Rect(x, rect.y, actorW, rect.height); + string actorLabel = string.IsNullOrWhiteSpace(_rolloutActorFilter) + ? SafeTranslate("RimMind.UI.Traces.Filter.ActorAll", "Actor: All") + : _rolloutActorFilter; + if (Widgets.ButtonText(actorRect, actorLabel)) + { + var actors = AgentRolloutModelBuilder.GetDistinctActors(_cachedEntries, ResolveActorDisplayName); + var opts = new List + { + new FloatMenuOption(SafeTranslate("RimMind.UI.Traces.Filter.All", "All"), () => _rolloutActorFilter = string.Empty) + }; + opts.AddRange(actors.Select(a => new FloatMenuOption(a, () => _rolloutActorFilter = a))); + Find.WindowStack.Add(new FloatMenu(opts)); + } + TooltipHandler.TipRegion(actorRect, SafeTranslate("RimMind.UI.Traces.Filter.ActorTip", "Filter trajectories by colonist or actor.")); + x = actorRect.xMax + gap; + + float stateW = Mathf.Min(120f, rect.width * 0.18f); + Rect stateRect = new Rect(x, rect.y, stateW, rect.height); + string stateLabel = _rolloutStateFilter.HasValue + ? StateLabelFor(_rolloutStateFilter.Value) + : SafeTranslate("RimMind.UI.Traces.Filter.StateAll", "State: All"); + if (Widgets.ButtonText(stateRect, stateLabel)) + { + var opts = new List + { + new FloatMenuOption(SafeTranslate("RimMind.UI.Traces.Filter.All", "All"), () => _rolloutStateFilter = null), + new FloatMenuOption(StateLabelFor(AIRequestTraceState.Running), () => _rolloutStateFilter = AIRequestTraceState.Running), + new FloatMenuOption(StateLabelFor(AIRequestTraceState.Completed), () => _rolloutStateFilter = AIRequestTraceState.Completed), + new FloatMenuOption(StateLabelFor(AIRequestTraceState.Failed), () => _rolloutStateFilter = AIRequestTraceState.Failed) + }; + Find.WindowStack.Add(new FloatMenu(opts)); + } + x = stateRect.xMax + gap; + + const float resetW = 64f; + float searchW = Mathf.Max(80f, rect.xMax - x - resetW - gap); + Rect searchRect = new Rect(x, rect.y, searchW, rect.height); + _rolloutSearchQuery = Widgets.TextField(searchRect, _rolloutSearchQuery ?? string.Empty); + TooltipHandler.TipRegion(searchRect, SafeTranslate("RimMind.UI.Traces.Filter.SearchTip", "Search prompts, thoughts, tool names, JSON arguments, or outcomes.")); + x = searchRect.xMax + gap; + + Rect resetRect = new Rect(x, rect.y, Mathf.Max(40f, rect.xMax - x), rect.height); + if (Widgets.ButtonText(resetRect, SafeTranslate("RimMind.UI.Traces.Filter.Reset", "Reset"))) + { + _rolloutActorFilter = string.Empty; + _rolloutStateFilter = null; + _rolloutSearchQuery = string.Empty; + } + } + + private void DrawRolloutList(Rect rect, IReadOnlyList rollouts) + { + Widgets.DrawBoxSolid(rect, RimMindUI.ColorSectionBg); + Rect inner = rect.ContractedBy(4f); + const float rowH = 66f; + const float rowGap = 4f; + float contentW = Mathf.Max(1f, inner.width - RimMindUiMetrics.ScrollBarWidth); + float viewH = Mathf.Max(inner.height + 1f, rollouts.Count * (rowH + rowGap)); + Rect view = new Rect(0f, 0f, contentW, viewH); + + Widgets.BeginScrollView(inner, ref _tableScrollPosition, view); + float y = 0f; + for (int i = 0; i < rollouts.Count; i++) + { + AgentRolloutEpisode ep = rollouts[i]; + Rect card = new Rect(0f, y, contentW, rowH); + bool selected = ep.RolloutId == _selectedRolloutId; + Widgets.DrawBoxSolid(card, selected ? RimMindUI.ColorTabActive : RimMindUI.ColorCardBg); + if (Widgets.ButtonInvisible(card)) + { + _selectedRolloutId = ep.RolloutId; + _detailScrollPosition = Vector2.zero; + } + + Rect pad = card.ContractedBy(6f); + Rect titleRect = new Rect(pad.x, pad.y, pad.width - 78f, 20f); + Rect stateRect = new Rect(pad.xMax - 76f, pad.y, 76f, 20f); + GUI.color = RimMindUI.ColorHeader; + Widgets.LabelEllipses(titleRect, $"{ep.ActorLabel} ({ep.TurnCount}T)"); + GUI.color = ColorForState(ep.TerminalState); + Text.Anchor = TextAnchor.UpperRight; + Widgets.Label(stateRect, StateLabelFor(ep.TerminalState)); + Text.Anchor = TextAnchor.UpperLeft; + GUI.color = RimMindUI.ColorMuted; + + string outcomeTag = ep.FinalOutcome != null + ? (ep.FinalOutcome.Succeeded ? $"OK:{ep.FinalOutcome.ActionIntent}" : $"ERR:{ep.FinalOutcome.ActionIntent}") + : ep.ScenarioId; + string line2 = $"Tools:{ep.TotalToolCalls}{(ep.FailedToolCalls > 0 ? $" ({ep.FailedToolCalls}!)" : string.Empty)} Tok:{ep.TotalTokens} Reuse:{ep.PrefixReuseRatio:P0} {ep.TotalElapsedMs}ms"; + Widgets.LabelEllipses(new Rect(pad.x, pad.y + 20f, pad.width, 18f), line2); + Widgets.LabelEllipses(new Rect(pad.x, pad.y + 38f, pad.width, 18f), outcomeTag); + GUI.color = Color.white; + + y += rowH + rowGap; + } + Widgets.EndScrollView(); + } + + private void DrawRolloutDetail(Rect rect, AgentRolloutEpisode episode) + { + Widgets.DrawBoxSolid(rect, RimMindUI.ColorCardBg); + Rect inner = rect.ContractedBy(RimMindUiMetrics.Padding); + float contentW = Mathf.Max(1f, inner.width - RimMindUiMetrics.ScrollBarWidth); + + var blocks = BuildRolloutDetailBlocks(episode); + float totalH = MeasureBlocksHeight(blocks, contentW); + Rect view = new Rect(0f, 0f, contentW, Mathf.Max(inner.height + 1f, totalH)); + Widgets.BeginScrollView(inner, ref _detailScrollPosition, view); + DrawDetailBlocks(blocks, contentW); + Widgets.EndScrollView(); + } + + private List BuildRolloutDetailBlocks(AgentRolloutEpisode episode) + { + var blocks = new List(); + + string headerMeta = + $"Rollout: {episode.RolloutId}\n" + + $"Actor: {episode.ActorLabel} ({episode.ActorId}) | Mod: {episode.ModId} | Scenario: {episode.ScenarioId}\n" + + $"Turns: {episode.TurnCount} | ToolCalls: {episode.TotalToolCalls} (Failed: {episode.FailedToolCalls}) | Elapsed: {episode.TotalElapsedMs} ms\n" + + $"Tokens: total={episode.TotalTokens} (prompt={episode.PromptTokens}, completion={episode.CompletionTokens}, cached={episode.CachedTokens}, reuse={episode.PrefixReuseRatio:P1})"; + blocks.Add(new DetailBlock( + $"rollout:{episode.RolloutId}:meta", + SafeTranslate("RimMind.UI.Traces.Rollout.SummaryHeader", "Rollout Summary"), + headerMeta, + RimMindUI.ColorHeader, + Collapsible: false, + DefaultExpanded: true)); + + if (episode.FinalOutcome != null) + { + var o = episode.FinalOutcome; + string outcomeBody = + $"Status: {(o.Succeeded ? SafeTranslate("RimMind.UI.Traces.Outcome.Succeeded", "Succeeded") : SafeTranslate("RimMind.UI.Traces.Outcome.Failed", "Failed"))}\n" + + $"Action: {o.ActionIntent}\n" + + (string.IsNullOrWhiteSpace(o.ParamPreview) ? string.Empty : $"Params: {o.ParamPreview}\n") + + $"Detail: {o.Detail ?? "-"}"; + blocks.Add(new DetailBlock( + $"rollout:{episode.RolloutId}:outcome", + SafeTranslate("RimMind.UI.Traces.Outcome.Title", "In-Game Action Outcome"), + outcomeBody.TrimEnd(), + o.Succeeded ? RimMindUI.ColorActive : RimMindUI.ColorError, + Collapsible: false, + DefaultExpanded: true)); + } + + AIRequestTraceEntry lastTurn = episode.Turns[episode.Turns.Count - 1]; + if (lastTurn.Layers.Count > 0) + { + for (int i = 0; i < lastTurn.Layers.Count; i++) + { + AIRequestLayerTrace layer = lastTurn.Layers[i]; + string reuseTag = layer.IsPrefixReused ? " [Prefix Reused]" : string.Empty; + string title = $"[{layer.LayerTag}] {layer.Role} ({layer.CharCount} chars){reuseTag}"; + string key = $"layer:{layer.LayerTag}:{i}"; + blocks.Add(new DetailBlock( + key, + title, + TraceContentFormatter.FormatStructuredText(layer.Content, 12000), + layer.IsPrefixReused ? RimMindUI.ColorActive : RimMindUI.ColorHeader, + Collapsible: true, + DefaultExpanded: _expandedLayers.Contains(layer.LayerTag))); + } + } + else + { + if (!string.IsNullOrWhiteSpace(lastTurn.SystemPrompt)) + { + blocks.Add(new DetailBlock( + "layer:L0", + "[L0] system", + TraceContentFormatter.FormatStructuredText(lastTurn.SystemPrompt, 12000), + RimMindUI.ColorHeader, + Collapsible: true, + DefaultExpanded: false)); + } + if (!string.IsNullOrWhiteSpace(lastTurn.UserPrompt)) + { + blocks.Add(new DetailBlock( + "layer:L4", + "[L4] user", + TraceContentFormatter.FormatStructuredText(lastTurn.UserPrompt, 12000), + RimMindUI.ColorHeader, + Collapsible: true, + DefaultExpanded: true)); + } + } + + for (int t = 0; t < episode.Turns.Count; t++) + { + AIRequestTraceEntry turn = episode.Turns[t]; + string turnTitle = $"Turn {t + 1}/{episode.Turns.Count} — {turn.Model} | {StateLabelFor(turn.State)} | {turn.ElapsedMs}ms | tok={turn.TokensUsed} (cached={turn.CachedTokens})"; + var sb = new StringBuilder(); + if (!string.IsNullOrWhiteSpace(turn.UserPrompt)) + { + sb.AppendLine("[Input / Perception]"); + sb.AppendLine(TraceContentFormatter.FormatStructuredText(turn.UserPrompt, 3500)); + sb.AppendLine(); + } + + if (!string.IsNullOrWhiteSpace(turn.ReasoningContent)) + { + sb.AppendLine("[Reasoning]"); + sb.AppendLine(TraceContentFormatter.FormatStructuredText(turn.ReasoningContent, 6000)); + sb.AppendLine(); + } + + if (!string.IsNullOrWhiteSpace(turn.Response)) + { + sb.AppendLine("[Response]"); + sb.AppendLine(TraceContentFormatter.FormatStructuredText(turn.Response, 6000)); + sb.AppendLine(); + } + + if (turn.ToolCalls.Count > 0) + { + sb.AppendLine($"[ToolCalls ({turn.ToolCalls.Count})]"); + for (int c = 0; c < turn.ToolCalls.Count; c++) + { + AIRequestToolCallTrace tc = turn.ToolCalls[c]; + sb.AppendLine($"• {tc.ToolName} [{(tc.Succeeded ? "OK" : "ERR")}]"); + if (!string.IsNullOrWhiteSpace(tc.ArgumentsJson)) + sb.AppendLine(" Args: " + TraceContentFormatter.FormatToolArguments(tc.ArgumentsJson, 2500).Replace("\n", "\n ")); + if (!string.IsNullOrWhiteSpace(tc.ResultContent)) + sb.AppendLine(" Result: " + TraceContentFormatter.FormatStructuredText(tc.ResultContent, 2500).Replace("\n", "\n ")); + if (!string.IsNullOrWhiteSpace(tc.Error)) + sb.AppendLine(" Error: " + tc.Error); + } + sb.AppendLine(); + } + + if (!string.IsNullOrWhiteSpace(turn.Error)) + sb.AppendLine("[Error] " + turn.Error); + + if (turn.ActionOutcome != null) + { + sb.AppendLine($"[Outcome] {(turn.ActionOutcome.Succeeded ? "OK" : "ERR")} {turn.ActionOutcome.ActionIntent}: {turn.ActionOutcome.Detail}"); + } + + blocks.Add(new DetailBlock( + $"turn:{episode.RolloutId}:{t}", + turnTitle, + sb.ToString().TrimEnd(), + ColorForState(turn.State), + Collapsible: true, + DefaultExpanded: true)); + } + + return blocks; + } + + private void DrawEphemeralView(Rect rect, RimMindLayoutScope scope) + { + const float filterBarH = 58f; + Rect filterRect = new Rect(rect.x, rect.y, rect.width, filterBarH); + DrawEphemeralFilterBar(filterRect, scope); + + Rect bodyRect = new Rect( + rect.x, + filterRect.yMax + RimMindUiMetrics.SectionGap, + rect.width, + Mathf.Max(1f, rect.height - filterBarH - RimMindUiMetrics.SectionGap)); + + var filter = new EphemeralTraceFilter( + _ephemeralModFilter, + _ephemeralScenarioFilter, + _ephemeralActorFilter, + _ephemeralStateFilter, + _ephemeralSearchQuery, + _includeRolloutTurnsInEphemeral); + + IReadOnlyList filtered = AgentRolloutModelBuilder.FilterEphemeral( + _cachedEntries, + filter, + ResolveActorDisplayName); + DebugTableModel model = AIRequestsDebugTableModelBuilder.Build(filtered); + + if (filtered.Count == 0) + { + _tableDrawer.Draw(bodyRect, model, ref _tableScrollPosition, scope); + return; + } + + SplitPageLayoutResult split = SplitPageLayout.Calculate(bodyRect, 0.4f, 240f, 320f, 320f); _selectedRequestId = _tableDrawer.DrawSelectableCompact( split.List, model, _selectedRequestId, ref _tableScrollPosition, scope); - selectedEntry = ResolveSelectedEntry(entries); + + AIRequestTraceEntry selected = filtered.FirstOrDefault(e => e.RequestId == _selectedRequestId) ?? filtered[0]; + _selectedRequestId = selected.RequestId; scope.Record(split.Detail, "AIRequests:Detail"); - DrawDetail(split.Detail, selectedEntry); + DrawEphemeralDetail(split.Detail, selected); } - private void RefreshSnapshot() + private void DrawEphemeralFilterBar(Rect rect, RimMindLayoutScope scope) { - if (_displaySnapshot != null) + scope.Record(rect, "Ephemeral:FilterBar"); + const float gap = 6f; + const float rowH = 26f; + Rect row1 = new Rect(rect.x, rect.y, rect.width, rowH); + Rect row2 = new Rect(rect.x, rect.y + rowH + 6f, rect.width, rowH); + + float x = row1.x; + float dropW = Mathf.Min(135f, (row1.width - 70f - gap * 4f) / 4f); + + Rect modRect = new Rect(x, row1.y, dropW, rowH); + string modLabel = string.IsNullOrWhiteSpace(_ephemeralModFilter) + ? SafeTranslate("RimMind.UI.Traces.Filter.ModAll", "Mod: All") + : _ephemeralModFilter; + if (Widgets.ButtonText(modRect, modLabel)) { - if (!ReferenceEquals(_cachedEntries, _displaySnapshot) || _cachedModel == null) + var mods = AgentRolloutModelBuilder.GetDistinctMods(_cachedEntries); + var opts = new List { - _cachedEntries = _displaySnapshot; - _cachedModel = AIRequestsDebugTableModelBuilder.Build(_cachedEntries); - } - return; + new FloatMenuOption(SafeTranslate("RimMind.UI.Traces.Filter.All", "All"), () => _ephemeralModFilter = string.Empty) + }; + opts.AddRange(mods.Select(m => new FloatMenuOption(m, () => _ephemeralModFilter = m))); + Find.WindowStack.Add(new FloatMenu(opts)); } - if (_log == null) - return; + x = modRect.xMax + gap; - long revision = _log.Revision; - if (_cachedModel != null && revision == _cachedRevision) - return; + Rect scenRect = new Rect(x, row1.y, dropW, rowH); + string scenLabel = string.IsNullOrWhiteSpace(_ephemeralScenarioFilter) + ? SafeTranslate("RimMind.UI.Traces.Filter.ScenarioAll", "Scenario: All") + : _ephemeralScenarioFilter; + if (Widgets.ButtonText(scenRect, scenLabel)) + { + var scenarios = AgentRolloutModelBuilder.GetDistinctScenarios(_cachedEntries); + var opts = new List + { + new FloatMenuOption(SafeTranslate("RimMind.UI.Traces.Filter.All", "All"), () => _ephemeralScenarioFilter = string.Empty) + }; + opts.AddRange(scenarios.Select(s => new FloatMenuOption(s, () => _ephemeralScenarioFilter = s))); + Find.WindowStack.Add(new FloatMenu(opts)); + } + x = scenRect.xMax + gap; - _cachedEntries = _log.Entries; - _cachedModel = AIRequestsDebugTableModelBuilder.Build(_cachedEntries); - _cachedRevision = revision; - } + Rect actorRect = new Rect(x, row1.y, dropW, rowH); + string actorLabel = string.IsNullOrWhiteSpace(_ephemeralActorFilter) + ? SafeTranslate("RimMind.UI.Traces.Filter.ActorAll", "Actor: All") + : _ephemeralActorFilter; + if (Widgets.ButtonText(actorRect, actorLabel)) + { + var actors = AgentRolloutModelBuilder.GetDistinctActors(_cachedEntries, ResolveActorDisplayName); + var opts = new List + { + new FloatMenuOption(SafeTranslate("RimMind.UI.Traces.Filter.All", "All"), () => _ephemeralActorFilter = string.Empty) + }; + opts.AddRange(actors.Select(a => new FloatMenuOption(a, () => _ephemeralActorFilter = a))); + Find.WindowStack.Add(new FloatMenu(opts)); + } + x = actorRect.xMax + gap; - private void DrawEmptyTable(Rect rect, string title, RimMindLayoutScope scope) - { - DebugTableModel model = new DebugTableModel(title, System.Array.Empty()); - _tableDrawer.Draw(rect, model, ref _tableScrollPosition, scope); + Rect stateRect = new Rect(x, row1.y, dropW, rowH); + string stateLabel = _ephemeralStateFilter.HasValue + ? StateLabelFor(_ephemeralStateFilter.Value) + : SafeTranslate("RimMind.UI.Traces.Filter.StateAll", "State: All"); + if (Widgets.ButtonText(stateRect, stateLabel)) + { + var opts = new List + { + new FloatMenuOption(SafeTranslate("RimMind.UI.Traces.Filter.All", "All"), () => _ephemeralStateFilter = null), + new FloatMenuOption(StateLabelFor(AIRequestTraceState.Running), () => _ephemeralStateFilter = AIRequestTraceState.Running), + new FloatMenuOption(StateLabelFor(AIRequestTraceState.Completed), () => _ephemeralStateFilter = AIRequestTraceState.Completed), + new FloatMenuOption(StateLabelFor(AIRequestTraceState.Failed), () => _ephemeralStateFilter = AIRequestTraceState.Failed) + }; + Find.WindowStack.Add(new FloatMenu(opts)); + } + x = stateRect.xMax + gap; + + Rect resetRect = new Rect(x, row1.y, Mathf.Max(50f, row1.xMax - x), rowH); + if (Widgets.ButtonText(resetRect, SafeTranslate("RimMind.UI.Traces.Filter.Reset", "Reset"))) + { + _ephemeralModFilter = string.Empty; + _ephemeralScenarioFilter = string.Empty; + _ephemeralActorFilter = string.Empty; + _ephemeralStateFilter = null; + _ephemeralSearchQuery = string.Empty; + _includeRolloutTurnsInEphemeral = false; + } + + const float toggleW = 190f; + float searchW = Mathf.Max(100f, row2.width - toggleW - gap); + Rect searchRect = new Rect(row2.x, row2.y, searchW, rowH); + _ephemeralSearchQuery = Widgets.TextField(searchRect, _ephemeralSearchQuery ?? string.Empty); + TooltipHandler.TipRegion(searchRect, SafeTranslate("RimMind.UI.Traces.Filter.SearchTip", "Search prompts, thoughts, tool names, JSON arguments, or outcomes.")); + + Rect toggleRect = new Rect(searchRect.xMax + gap, row2.y, toggleW, rowH); + Widgets.CheckboxLabeled( + toggleRect, + SafeTranslate("RimMind.UI.Traces.Filter.IncludeRollout", "Include Rollout Turns"), + ref _includeRolloutTurnsInEphemeral); + TooltipHandler.TipRegion(toggleRect, SafeTranslate("RimMind.UI.Traces.Filter.IncludeRolloutTip", "When unchecked, only non-agent one-off requests (dialogue, personality, storyteller, etc.) are listed.")); } - private AIRequestTraceEntry ResolveSelectedEntry(IReadOnlyList entries) + private void DrawEphemeralDetail(Rect rect, AIRequestTraceEntry entry) { - AIRequestTraceEntry? selectedEntry = entries.FirstOrDefault(e => e.RequestId == _selectedRequestId); - if (selectedEntry != null) - return selectedEntry; + Widgets.DrawBoxSolid(rect, RimMindUI.ColorCardBg); + Rect inner = rect.ContractedBy(RimMindUiMetrics.Padding); + float contentW = Mathf.Max(1f, inner.width - RimMindUiMetrics.ScrollBarWidth); - selectedEntry = entries[0]; - _selectedRequestId = selectedEntry.RequestId; - return selectedEntry; + var blocks = BuildEphemeralDetailBlocks(entry); + float totalH = MeasureBlocksHeight(blocks, contentW); + Rect view = new Rect(0f, 0f, contentW, Mathf.Max(inner.height + 1f, totalH)); + Widgets.BeginScrollView(inner, ref _detailScrollPosition, view); + DrawDetailBlocks(blocks, contentW); + Widgets.EndScrollView(); } - private void DrawDetail(Rect rect, AIRequestTraceEntry entry) + private List BuildEphemeralDetailBlocks(AIRequestTraceEntry entry) { - var sections = BuildDetailSections(entry); - float contentWidth = Mathf.Max(1f, rect.width - RimMindUiMetrics.ScrollBarWidth); - float viewHeight = Mathf.Max(rect.height + 1f, CalculateDetailViewHeight(sections, contentWidth)); - Rect view = new Rect(rect.x, rect.y, contentWidth, viewHeight); - Widgets.BeginScrollView(rect, ref _detailScrollPosition, view); + string mod = AgentRolloutModelBuilder.ResolveModId(entry); + string scen = AgentRolloutModelBuilder.ResolveScenarioId(entry); + string actor = AgentRolloutModelBuilder.ResolveActorLabel(entry, ResolveActorDisplayName); - float y = view.y; - foreach (var section in sections) - y = DrawSection(view, y, section.Title, section.Body); + var blocks = new List + { + new DetailBlock( + $"ephem:{entry.RequestId}:meta", + SafeTranslate("RimMind.UI.AIRequestsPage.Detail.Meta", "Metadata"), + $"RequestId: {entry.RequestId}\n" + + $"TraceId: {entry.TraceId}\n" + + $"State: {StateLabelFor(entry.State)} | Elapsed: {entry.ElapsedMs} ms\n" + + $"Mod: {(string.IsNullOrEmpty(mod) ? "-" : mod)} | Scenario: {(string.IsNullOrEmpty(scen) ? "-" : scen)} | Actor: {actor}\n" + + $"Model: {entry.Model}\n" + + $"Tokens: total={entry.TokensUsed} (prompt={entry.PromptTokens}, completion={entry.CompletionTokens}, cached={entry.CachedTokens})\n" + + $"Source: {entry.Source}", + ColorForState(entry.State), + Collapsible: false, + DefaultExpanded: true), + new DetailBlock( + "ephem:system", + SafeTranslate("RimMind.UI.AIRequestsPage.Detail.System", "System Prompt"), + FormatOrEmpty(entry.SystemPrompt), + RimMindUI.ColorHeader, + Collapsible: true, + DefaultExpanded: false), + new DetailBlock( + "ephem:user", + SafeTranslate("RimMind.UI.AIRequestsPage.Detail.User", "User Prompt"), + FormatOrEmpty(entry.UserPrompt), + RimMindUI.ColorHeader, + Collapsible: true, + DefaultExpanded: true) + }; - Widgets.EndScrollView(); + if (!string.IsNullOrWhiteSpace(entry.ReasoningContent)) + { + blocks.Add(new DetailBlock( + $"ephem:{entry.RequestId}:reasoning", + SafeTranslate("RimMind.UI.Traces.Detail.Reasoning", "Reasoning"), + TraceContentFormatter.FormatStructuredText(entry.ReasoningContent, 8000), + RimMindUI.ColorHeader, + Collapsible: true, + DefaultExpanded: true)); + } + + blocks.Add(new DetailBlock( + $"ephem:{entry.RequestId}:response", + SafeTranslate("RimMind.UI.AIRequestsPage.Detail.Response", "Response"), + FormatOrEmpty(entry.Response), + RimMindUI.ColorHeader, + Collapsible: false, + DefaultExpanded: true)); + + if (entry.ToolCalls.Count > 0) + { + var sb = new StringBuilder(); + foreach (var tc in entry.ToolCalls) + { + sb.AppendLine($"• {tc.ToolName} [{(tc.Succeeded ? "OK" : "ERR")}]"); + if (!string.IsNullOrWhiteSpace(tc.ArgumentsJson)) + sb.AppendLine(" Args: " + TraceContentFormatter.FormatToolArguments(tc.ArgumentsJson, 2500).Replace("\n", "\n ")); + if (!string.IsNullOrWhiteSpace(tc.ResultContent)) + sb.AppendLine(" Result: " + TraceContentFormatter.FormatStructuredText(tc.ResultContent, 2500).Replace("\n", "\n ")); + if (!string.IsNullOrWhiteSpace(tc.Error)) + sb.AppendLine(" Error: " + tc.Error); + } + + blocks.Add(new DetailBlock( + $"ephem:{entry.RequestId}:tools", + SafeTranslate("RimMind.UI.AIRequestsPage.Detail.ToolCalls", "Tool Calls"), + sb.ToString().TrimEnd(), + RimMindUI.ColorHeader, + Collapsible: false, + DefaultExpanded: true)); + } + + if (entry.ActionOutcome != null) + { + var o = entry.ActionOutcome; + blocks.Add(new DetailBlock( + $"ephem:{entry.RequestId}:outcome", + SafeTranslate("RimMind.UI.Traces.Outcome.Title", "In-Game Action Outcome"), + $"{(o.Succeeded ? "Succeeded" : "Failed")}: {o.ActionIntent}\n{o.ParamPreview}\n{o.Detail}".Trim(), + o.Succeeded ? RimMindUI.ColorActive : RimMindUI.ColorError, + Collapsible: false, + DefaultExpanded: true)); + } + + if (!string.IsNullOrWhiteSpace(entry.Error)) + { + blocks.Add(new DetailBlock( + $"ephem:{entry.RequestId}:error", + SafeTranslate("RimMind.UI.AIRequestsPage.Detail.Error", "Error"), + entry.Error!, + RimMindUI.ColorError, + Collapsible: false, + DefaultExpanded: true)); + } + + return blocks; } - private static List BuildDetailSections(AIRequestTraceEntry entry) + private float MeasureBlocksHeight(IReadOnlyList blocks, float width) { - return new List + Text.Font = GameFont.Small; + float y = 0f; + for (int i = 0; i < blocks.Count; i++) { - new DetailSection("RimMind.UI.AIRequestsPage.Detail.Meta".Translate(), - $"{entry.RequestId}\n{StateLabelFor(entry.State)}\n{entry.Source}\n{entry.Model}\n{entry.ElapsedMs} ms\n{entry.TokensUsed} tokens"), - new DetailSection("RimMind.UI.AIRequestsPage.Detail.System".Translate(), entry.SystemPrompt), - new DetailSection("RimMind.UI.AIRequestsPage.Detail.User".Translate(), entry.UserPrompt), - new DetailSection("RimMind.UI.AIRequestsPage.Detail.Assistant".Translate(), entry.AssistantPrompt), - new DetailSection("RimMind.UI.AIRequestsPage.Detail.Response".Translate(), entry.Response), - new DetailSection("RimMind.UI.AIRequestsPage.Detail.Error".Translate(), entry.Error ?? string.Empty), - new DetailSection("RimMind.UI.AIRequestsPage.Detail.ToolCalls".Translate(), FormatToolCalls(entry)) - }; + DetailBlock b = blocks[i]; + y += 24f; + bool expanded = IsExpanded(b); + if (expanded) + { + float bodyH = Mathf.Max(22f, Text.CalcHeight(b.Body, Mathf.Max(20f, width - 8f))); + y += bodyH + 10f; + } + y += 6f; + } + return Mathf.Max(1f, y + 12f); } - private static float CalculateDetailViewHeight(IReadOnlyList sections, float width) + private void DrawDetailBlocks(IReadOnlyList blocks, float width) { Text.Font = GameFont.Small; float y = 0f; - foreach (var section in sections) + for (int i = 0; i < blocks.Count; i++) { + DetailBlock b = blocks[i]; + bool expanded = IsExpanded(b); + Rect headerRect = new Rect(0f, y, width, 24f); + Widgets.DrawBoxSolid(headerRect, RimMindUI.ColorSectionBg); + + string prefix = b.Collapsible ? (expanded ? "[-] " : "[+] ") : string.Empty; + GUI.color = b.AccentColor; + Widgets.LabelEllipses(new Rect(headerRect.x + 6f, headerRect.y + 2f, headerRect.width - 12f, 20f), prefix + b.Title); + GUI.color = Color.white; + + if (b.Collapsible && Widgets.ButtonInvisible(headerRect)) + ToggleExpanded(b); + y += 24f; - y += Mathf.Max(32f, Text.CalcHeight(ResolveSectionBody(section.Body), width)); - y += 12f; + + if (expanded) + { + float bodyW = Mathf.Max(20f, width - 8f); + float bodyH = Mathf.Max(22f, Text.CalcHeight(b.Body, bodyW)); + Rect bodyRect = new Rect(4f, y + 2f, bodyW, bodyH); + Widgets.Label(bodyRect, b.Body); + y += bodyH + 10f; + } + + y += 6f; } + } + + private bool IsExpanded(DetailBlock block) + { + if (!block.Collapsible) + return true; + + if (_expandedPromptSections.TryGetValue(block.Key, out _)) + return true; - return Mathf.Max(1f, y + 16f); + if (block.Key.StartsWith("layer:", StringComparison.OrdinalIgnoreCase)) + { + string tag = ExtractLayerTag(block.Key); + return _expandedLayers.Contains(tag); + } + + return block.DefaultExpanded && !_hiddenSections.Contains(block.Key); } - private static float DrawSection(Rect view, float y, string title, string body) + private readonly HashSet _hiddenSections = new(StringComparer.OrdinalIgnoreCase); + + private void ToggleExpanded(DetailBlock block) { - Text.Font = GameFont.Small; - Widgets.Label(new Rect(view.x, y, view.width, 24f), title); - y += 24f; + if (block.Key.StartsWith("layer:", StringComparison.OrdinalIgnoreCase)) + { + string tag = ExtractLayerTag(block.Key); + if (!_expandedLayers.Add(tag)) + _expandedLayers.Remove(tag); + return; + } - string text = ResolveSectionBody(body); - float height = Mathf.Max(32f, Text.CalcHeight(text, view.width)); - Widgets.Label(new Rect(view.x, y, view.width, height), text); - return y + height + 12f; + if (block.DefaultExpanded) + { + if (!_hiddenSections.Add(block.Key)) + _hiddenSections.Remove(block.Key); + } + else + { + if (!_expandedPromptSections.Add(block.Key)) + _expandedPromptSections.Remove(block.Key); + } } - private static string ResolveSectionBody(string body) - => string.IsNullOrWhiteSpace(body) - ? "RimMind.UI.AIRequestsPage.Detail.EmptySection".Translate() - : body; + private static string ExtractLayerTag(string key) + { + // key format: layer: or layer:: + int first = key.IndexOf(':'); + if (first < 0) return key; + int second = key.IndexOf(':', first + 1); + return second > first + ? key.Substring(first + 1, second - first - 1) + : key.Substring(first + 1); + } - private static string FormatToolCalls(AIRequestTraceEntry entry) + private void RefreshSnapshot() { - if (entry.ToolCalls.Count == 0) + if (_displaySnapshot != null) + { + if (!ReferenceEquals(_cachedEntries, _displaySnapshot)) + { + _cachedEntries = _displaySnapshot; + _cachedRollouts = AgentRolloutModelBuilder.BuildRollouts(_cachedEntries, actorNameResolver: ResolveActorDisplayName); + } + return; + } + + if (_log == null) + return; + + long revision = _log.Revision; + if (revision == _cachedRevision) + return; + + _cachedEntries = _log.Entries; + _cachedRollouts = AgentRolloutModelBuilder.BuildRollouts(_cachedEntries, actorNameResolver: ResolveActorDisplayName); + _cachedRevision = revision; + } + + private void DrawEmptyTable(Rect rect, string title, RimMindLayoutScope scope) + { + DebugTableModel model = new DebugTableModel(title, Array.Empty()); + _tableDrawer.Draw(rect, model, ref _tableScrollPosition, scope); + } + + private string FormatOrEmpty(string? raw) + => string.IsNullOrWhiteSpace(raw) + ? SafeTranslate("RimMind.UI.AIRequestsPage.Detail.EmptySection", "(empty)") + : TraceContentFormatter.FormatStructuredText(raw, 12000); + + private static string ResolveActorDisplayName(string actorId) + { + if (string.IsNullOrWhiteSpace(actorId)) return string.Empty; - return string.Join("\n", entry.ToolCalls.Select(t => - $"{t.ToolName} [{(t.Succeeded ? "ok" : "error")}] {t.Error ?? string.Empty}")); + try + { + Pawn? pawn = RimMindPawnLookup.FindPawnById(actorId); + if (pawn != null && !string.IsNullOrWhiteSpace(pawn.LabelShortCap)) + return pawn.LabelShortCap; + } + catch + { + // Ignore in test/non-main-thread environments + } + + return actorId; } + private static Color ColorForState(AIRequestTraceState state) => state switch + { + AIRequestTraceState.Running => RimMindUI.ColorPending, + AIRequestTraceState.Completed => RimMindUI.ColorActive, + AIRequestTraceState.Failed => RimMindUI.ColorError, + _ => Color.white + }; + private static string StateLabelFor(AIRequestTraceState state) => state switch { - AIRequestTraceState.Running => "RimMind.UI.AIRequestsPage.State.Running".Translate(), - AIRequestTraceState.Completed => "RimMind.UI.AIRequestsPage.State.Completed".Translate(), - AIRequestTraceState.Failed => "RimMind.UI.AIRequestsPage.State.Failed".Translate(), + AIRequestTraceState.Running => SafeTranslate("RimMind.UI.AIRequestsPage.State.Running", "Running"), + AIRequestTraceState.Completed => SafeTranslate("RimMind.UI.AIRequestsPage.State.Completed", "Completed"), + AIRequestTraceState.Failed => SafeTranslate("RimMind.UI.AIRequestsPage.State.Failed", "Failed"), _ => state.ToString() }; + + private static string SafeTranslate(string key, string fallback) + => key.CanTranslate() ? key.Translate().ToString() : fallback; + + private sealed record DetailBlock( + string Key, + string Title, + string Body, + Color AccentColor, + bool Collapsible, + bool DefaultExpanded); } } diff --git a/Source/Infrastructure/UI/DebugCenter/Pages/CapabilitiesDebugCenterPageDrawer.cs b/Source/Infrastructure/UI/DebugCenter/Pages/CapabilitiesDebugCenterPageDrawer.cs new file mode 100644 index 0000000..f0e9e4d --- /dev/null +++ b/Source/Infrastructure/UI/DebugCenter/Pages/CapabilitiesDebugCenterPageDrawer.cs @@ -0,0 +1,320 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RimMind.Application.Common.Interfaces.Tools; +using RimMind.Application.Common.Models.Debug; +using RimMind.Application.Common.Models.Tools; +using RimMind.Infrastructure.UI.DebugTables; +using RimMind.Infrastructure.UI.Framework; +using RimMind.Presentation.Api; +using RimMind.Presentation.Runtime.Services; +using RimMind.Presentation.UI.Framework; +using RimMind.Presentation.UI.Layout; +using UnityEngine; +using Verse; + +namespace RimMind.Infrastructure.UI.DebugCenter.Pages +{ + public sealed class CapabilitiesDebugCenterPageDrawer : IRuntimeBoundDebugCenterPageDrawer + { + private const string SubTabToolCalls = "tool_calls"; + private const string SubTabMechanisms = "mechanisms"; + private const string SubTabContextKeys = "context_keys"; + + private readonly RimMindTabbedPageHostDrawer _tabDrawer = new(); + private readonly RimMindTableDrawer _tableDrawer = new(); + private readonly ToolRegistryDebugTableModelBuilder _toolRegistryBuilder = new(); + private readonly MechanismsDebugCenterPageDrawer _mechanismsDrawer = new(new MechanismsDebugTableModelBuilder()); + private readonly ContextKeysDebugCenterPageDrawer _contextKeysDrawer = new(new ContextKeysDebugTableModelBuilder()); + + private IToolRegistry? _toolRegistry; + private string _activeSubTab = SubTabToolCalls; + private string _selectedCategory = "All"; + private string _searchQuery = string.Empty; + private string? _selectedToolId; + private Vector2 _toolTableScroll; + private Vector2 _toolDetailScroll; + + internal void ScrollToBottom() + { + _toolTableScroll = new Vector2(0, 100000f); + _toolDetailScroll = new Vector2(0, 100000f); + _mechanismsDrawer.ScrollToBottom(); + _contextKeysDrawer.ScrollToBottom(); + } + + public IDisposable? Bind(RuntimeServiceScope scope) + { + _toolRegistry = scope.GetOptional(); + _toolRegistryBuilder.Bind(_toolRegistry, scope.Generation); + + IDisposable? mechLease = _mechanismsDrawer.Bind(scope); + IDisposable? ctxLease = _contextKeysDrawer.Bind(scope); + if (mechLease == null && ctxLease == null) + return null; + + return new CompositeDisposable(mechLease, ctxLease); + } + + public void Draw(Rect rect, DebugCenterPageContext context, RimMindLayoutScope scope) + { + ApplyRequestedSubTab(context.Navigation.ConsumeRequestedSubTabId()); + + var tabs = BuildTabs(); + TabbedPageLayoutResult layout = TabbedPageLayout.Calculate(rect, tabs); + _activeSubTab = _tabDrawer.DrawTabs(layout, tabs, _activeSubTab, scope); + + switch (_activeSubTab) + { + case SubTabMechanisms: + _mechanismsDrawer.Draw(layout.Content, context, scope); + break; + case SubTabContextKeys: + _contextKeysDrawer.Draw(layout.Content, context, scope); + break; + default: + DrawToolCatalog(layout.Content, scope); + break; + } + } + + private void ApplyRequestedSubTab(string? requested) + { + if (string.IsNullOrWhiteSpace(requested)) + return; + + string normalized = requested!.Trim().ToLowerInvariant(); + if (normalized is SubTabToolCalls or SubTabMechanisms or SubTabContextKeys) + _activeSubTab = normalized; + } + + private List BuildTabs() + { + return new List + { + new TabbedPageTabModel( + SubTabToolCalls, + SafeTranslate("RimMind.UI.Hub.Tab.ToolCalls", "ToolCalls"), + "RimMind.UI.Hub.Tab.ToolCalls", + _activeSubTab == SubTabToolCalls, + enabled: true, + tooltipKey: "RimMind.UI.Capabilities.Tip.ToolCalls"), + new TabbedPageTabModel( + SubTabMechanisms, + SafeTranslate("RimMind.UI.Hub.Tab.Mechanisms", "Mechanisms"), + "RimMind.UI.Hub.Tab.Mechanisms", + _activeSubTab == SubTabMechanisms, + enabled: true, + tooltipKey: "RimMind.UI.Capabilities.Tip.Mechanisms"), + new TabbedPageTabModel( + SubTabContextKeys, + SafeTranslate("RimMind.UI.Hub.Tab.ContextKeys", "Context Keys"), + "RimMind.UI.Hub.Tab.ContextKeys", + _activeSubTab == SubTabContextKeys, + enabled: true, + tooltipKey: "RimMind.UI.Capabilities.Tip.ContextKeys") + }; + } + + private void DrawToolCatalog(Rect rect, RimMindLayoutScope scope) + { + IToolRegistry? registry = _toolRegistry ?? TryResolveGlobalTools(); + IReadOnlyList allDefs = registry?.GetAllDefinitions() ?? Array.Empty(); + + const float filterBarHeight = 28f; + Rect filterRect = new Rect(rect.x, rect.y, rect.width, filterBarHeight); + DrawToolFilterBar(filterRect, allDefs, scope); + + Rect bodyRect = new Rect( + rect.x, + filterRect.yMax + RimMindUiMetrics.SectionGap, + rect.width, + Mathf.Max(1f, rect.height - filterBarHeight - RimMindUiMetrics.SectionGap)); + + IReadOnlyList filtered = ToolRegistryDebugTableModelBuilder.FilterDefinitions( + allDefs, + _selectedCategory, + _searchQuery); + DebugTableModel model = ToolRegistryDebugTableModelBuilder.Build( + registry, + _selectedCategory, + _searchQuery); + + if (filtered.Count == 0) + { + _tableDrawer.Draw(bodyRect, model, ref _toolTableScroll, scope); + return; + } + + SplitPageLayoutResult split = SplitPageLayout.Calculate(bodyRect, 0.44f, 240f, 360f, 300f); + _selectedToolId = _tableDrawer.DrawSelectableCompact( + split.List, + model, + _selectedToolId, + ref _toolTableScroll, + scope); + + ToolDefinition selectedDef = filtered.FirstOrDefault(d => string.Equals(d.Id, _selectedToolId, StringComparison.OrdinalIgnoreCase)) + ?? filtered[0]; + _selectedToolId = selectedDef.Id; + + scope.Record(split.Detail, "Capabilities:ToolDetail"); + DrawToolDetail(split.Detail, selectedDef); + } + + private void DrawToolFilterBar(Rect rect, IReadOnlyList allDefs, RimMindLayoutScope scope) + { + scope.Record(rect, "Capabilities:FilterBar"); + float x = rect.x; + const float gap = 6f; + + float catWidth = Mathf.Min(150f, rect.width * 0.28f); + Rect catRect = new Rect(x, rect.y, catWidth, rect.height); + string catLabel = _selectedCategory == "All" + ? SafeTranslate("RimMind.UI.Capabilities.CategoryAll", "Category: All") + : $"{SafeTranslate("RimMind.UI.Capabilities.CategoryPrefix", "Category")}: {_selectedCategory}"; + if (Widgets.ButtonText(catRect, catLabel)) + { + var categories = new List { "All" }; + categories.AddRange(allDefs + .Select(d => d.Category) + .Where(c => !string.IsNullOrWhiteSpace(c)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .OrderBy(c => c, StringComparer.OrdinalIgnoreCase)); + + var options = categories.Select(cat => new FloatMenuOption( + cat == "All" ? SafeTranslate("RimMind.UI.Traces.Filter.All", "All") : cat, + () => _selectedCategory = cat)).ToList(); + Find.WindowStack.Add(new FloatMenu(options)); + } + TooltipHandler.TipRegion(catRect, SafeTranslate("RimMind.UI.Capabilities.FilterCategoryTip", "Filter registered AI tools by category.")); + x = catRect.xMax + gap; + + const float resetW = 64f; + float countW = 72f; + float searchW = Mathf.Max(80f, rect.xMax - x - resetW - countW - gap * 2f); + Rect searchRect = new Rect(x, rect.y, searchW, rect.height); + _searchQuery = Widgets.TextField(searchRect, _searchQuery ?? string.Empty); + TooltipHandler.TipRegion(searchRect, SafeTranslate("RimMind.UI.Capabilities.SearchTip", "Search tool ID, display name, mod, domain, or schema keywords.")); + x = searchRect.xMax + gap; + + Rect resetRect = new Rect(x, rect.y, resetW, rect.height); + if (Widgets.ButtonText(resetRect, SafeTranslate("RimMind.UI.Traces.Filter.Reset", "Reset"))) + { + _selectedCategory = "All"; + _searchQuery = string.Empty; + } + x = resetRect.xMax + gap; + + Rect countRect = new Rect(x, rect.y, Mathf.Max(20f, rect.xMax - x), rect.height); + Text.Anchor = TextAnchor.MiddleRight; + GUI.color = RimMindUI.ColorMuted; + Widgets.Label(countRect, $"{allDefs.Count}"); + GUI.color = Color.white; + Text.Anchor = TextAnchor.UpperLeft; + } + + private void DrawToolDetail(Rect rect, ToolDefinition def) + { + Widgets.DrawBoxSolid(rect, RimMindUI.ColorCardBg); + Rect inner = rect.ContractedBy(RimMindUiMetrics.Padding); + ToolManifest? manifest = def.Manifest; + + string title = manifest != null && !string.IsNullOrWhiteSpace(manifest.DisplayName) + ? $"{manifest.DisplayName} ({def.Id})" + : def.Id; + + var blocks = new List<(string Header, string Body, bool IsTitle)> + { + (title, string.Empty, true), + (SafeTranslate("RimMind.UI.Capabilities.MetaHeader", "Manifest & Policy"), + $"ID: {def.Id}\n" + + $"Category: {def.Category ?? "-"}\n" + + $"OwnerMod: {manifest?.OwnerModId ?? "-"}\n" + + $"Kind: {manifest?.Kind.ToString() ?? "-"}\n" + + $"DefaultDomain: {manifest?.DefaultDomain?.ToString() ?? "-"}\n" + + $"Risk: {manifest?.RiskLevel.ToString() ?? "-"}\n" + + $"RequiresApproval: {manifest?.RequiresApproval ?? false}", + false), + (SafeTranslate("RimMind.UI.Capabilities.DescriptionHeader", "Description"), + string.IsNullOrWhiteSpace(def.Description) ? "-" : def.Description, + false), + (SafeTranslate("RimMind.UI.Capabilities.SchemaHeader", "Parameters Schema (JSON)"), + TraceContentFormatter.FormatStructuredText(def.ParametersSchema, maxChars: 12000), + false) + }; + + float contentWidth = Mathf.Max(1f, inner.width - RimMindUiMetrics.ScrollBarWidth); + Text.Font = GameFont.Small; + float totalHeight = 8f; + foreach (var b in blocks) + { + totalHeight += b.IsTitle ? 28f : 22f; + if (!string.IsNullOrEmpty(b.Body)) + totalHeight += Mathf.Max(24f, Text.CalcHeight(b.Body, contentWidth)) + 10f; + } + + Rect view = new Rect(0f, 0f, contentWidth, Mathf.Max(inner.height + 1f, totalHeight)); + Widgets.BeginScrollView(inner, ref _toolDetailScroll, view); + + float y = 0f; + foreach (var b in blocks) + { + if (b.IsTitle) + { + Text.Font = GameFont.Medium; + GUI.color = RimMindUI.ColorHeader; + Widgets.LabelEllipses(new Rect(0f, y, contentWidth, 26f), b.Header); + GUI.color = Color.white; + Text.Font = GameFont.Small; + y += 28f; + continue; + } + + GUI.color = RimMindUI.ColorHeader; + Widgets.Label(new Rect(0f, y, contentWidth, 20f), b.Header); + GUI.color = Color.white; + y += 22f; + + float bodyH = Mathf.Max(24f, Text.CalcHeight(b.Body, contentWidth)); + Widgets.Label(new Rect(0f, y, contentWidth, bodyH), b.Body); + y += bodyH + 10f; + } + + Widgets.EndScrollView(); + } + + private static IToolRegistry? TryResolveGlobalTools() + { + try + { + return RimMindAPI.Tools; + } + catch + { + return null; + } + } + + private static string SafeTranslate(string key, string fallback) + => key.CanTranslate() ? key.Translate().ToString() : fallback; + + private sealed class CompositeDisposable : IDisposable + { + private readonly IDisposable? _a; + private readonly IDisposable? _b; + + public CompositeDisposable(IDisposable? a, IDisposable? b) + { + _a = a; + _b = b; + } + + public void Dispose() + { + _a?.Dispose(); + _b?.Dispose(); + } + } + } +} diff --git a/Source/Infrastructure/UI/DebugCenter/Pages/OverviewDebugCenterPageDrawer.cs b/Source/Infrastructure/UI/DebugCenter/Pages/OverviewDebugCenterPageDrawer.cs index 136cd13..dfa3507 100644 --- a/Source/Infrastructure/UI/DebugCenter/Pages/OverviewDebugCenterPageDrawer.cs +++ b/Source/Infrastructure/UI/DebugCenter/Pages/OverviewDebugCenterPageDrawer.cs @@ -341,7 +341,8 @@ private static float DrawSettingsTunerSection( Widgets.Label(freqLabelRect, freqTitle); TooltipHandler.TipRegion(freqLabelRect, freqTip); - float freqSliderW = cardW - 150f - 190f - 32f; + const float freqValW = 255f; + float freqSliderW = Mathf.Max(120f, cardW - 150f - freqValW - 32f); Rect freqSliderRect = new Rect(freqLabelRect.xMax + 4f, rY, freqSliderW, 22f); float newFreq = Widgets.HorizontalSlider(freqSliderRect, curFreq, 0.1f, 3.5f, roundTo: 0.1f); if (Mathf.Abs(newFreq - curFreq) > 0.05f) @@ -351,7 +352,7 @@ private static float DrawSettingsTunerSection( } TooltipHandler.TipRegion(freqSliderRect, freqTip); - Rect freqValRect = new Rect(freqSliderRect.xMax + 6f, rY, 190f, 22f); + Rect freqValRect = new Rect(freqSliderRect.xMax + 6f, rY, freqValW, 22f); GUI.color = new Color(0.4f, 0.8f, 1.0f); string freqDesc = ApiTabDrawer.GetActivityFrequencyDescription(curFreq); Widgets.Label(freqValRect, $"{freqDesc} ({curFreq:F1}x)"); @@ -431,7 +432,7 @@ private static float DrawColonistInspectorSection( Rect pSelectBtn = new Rect(pLabelRect.xMax + 8f, pY, pSelectW, 26f); if (Widgets.ButtonText(pSelectBtn, "RimMind.UI.Hub.SelectColonist".Translate())) { - var colonists = Find.CurrentMap?.mapPawns?.FreeColonists?.Where(p => !p.Dead).ToList(); + var colonists = RimMind.Presentation.Api.RimMindPawnLookup.GetEligibleColonists(Find.CurrentMap).ToList(); if (colonists != null && colonists.Count > 0) { var options = colonists.Select(p => new FloatMenuOption(p.LabelShortCap, () => @@ -555,22 +556,28 @@ private static void DrawQuickNavigationSection( context.Navigation.GoTo("agents"); Rect nav2 = new Rect(nav1.xMax + 8f, row1Y, btnW, btnH); - if (Widgets.ButtonText(nav2, "RimMind.UI.Hub.Tab.AIRequests".Translate())) - context.Navigation.GoTo("ai_requests"); + string rolloutBtnLabel = "RimMind.UI.Traces.SubTab.Rollout".CanTranslate() + ? "RimMind.UI.Traces.SubTab.Rollout".Translate().ToString() + : "Agent Rollout"; + if (Widgets.ButtonText(nav2, rolloutBtnLabel)) + context.Navigation.GoTo("ai_requests", "rollout"); Rect nav3 = new Rect(nav2.xMax + 8f, row1Y, btnW, btnH); - if (Widgets.ButtonText(nav3, "RimMind.UI.Hub.Tab.ToolCalls".Translate())) - context.Navigation.GoTo("tool_calls"); + string ephemeralBtnLabel = "RimMind.UI.Traces.SubTab.Ephemeral".CanTranslate() + ? "RimMind.UI.Traces.SubTab.Ephemeral".Translate().ToString() + : "One-Off Requests"; + if (Widgets.ButtonText(nav3, ephemeralBtnLabel)) + context.Navigation.GoTo("ai_requests", "ephemeral"); float row2Y = row1Y + btnH + 6f; Rect nav4 = new Rect(4f, row2Y, btnW, btnH); - if (Widgets.ButtonText(nav4, "RimMind.UI.Hub.Tab.Mechanisms".Translate())) - context.Navigation.GoTo("mechanisms"); + if (Widgets.ButtonText(nav4, "RimMind.UI.Hub.Tab.ToolCalls".Translate())) + context.Navigation.GoTo("capabilities", "tool_calls"); Rect nav5 = new Rect(nav4.xMax + 8f, row2Y, btnW, btnH); - if (Widgets.ButtonText(nav5, "RimMind.UI.Hub.Tab.ContextKeys".Translate())) - context.Navigation.GoTo("context_keys"); + if (Widgets.ButtonText(nav5, "RimMind.UI.Hub.Tab.Mechanisms".Translate())) + context.Navigation.GoTo("capabilities", "mechanisms"); Rect nav6 = new Rect(nav5.xMax + 8f, row2Y, btnW, btnH); if (Widgets.ButtonText(nav6, "RimMind.UI.Hub.OpenSettings".Translate())) diff --git a/Source/Infrastructure/UI/DebugTables/ContextKeysDebugTableModelBuilder.cs b/Source/Infrastructure/UI/DebugTables/ContextKeysDebugTableModelBuilder.cs index cf94062..7084e95 100644 --- a/Source/Infrastructure/UI/DebugTables/ContextKeysDebugTableModelBuilder.cs +++ b/Source/Infrastructure/UI/DebugTables/ContextKeysDebugTableModelBuilder.cs @@ -9,6 +9,18 @@ namespace RimMind.Infrastructure.UI.DebugTables { public sealed class ContextKeysDebugTableModelBuilder : IDebugTableModelBuilder { + private static readonly string[] Headers = + { + "RimMind.UI.DebugTable.Header.Id", + "RimMind.UI.DebugTable.Header.Status", + "RimMind.UI.DebugTable.Header.Score", + "RimMind.UI.DebugTable.Header.Layer", + "RimMind.UI.DebugTable.Header.OwnerMod", + "RimMind.UI.DebugTable.Header.CacheScope", + "RimMind.UI.DebugTable.Header.Category", + "RimMind.UI.DebugTable.Header.Summary" + }; + private IContextKeyRegistry? _registry; private long _cachedGeneration = long.MinValue; private DebugTableModel? _cachedModel; @@ -34,13 +46,15 @@ public static DebugTableModel Build(IReadOnlyList keys) { return new DebugTableModel( "RimMind.UI.Hub.Tab.ContextKeys".Translate(), - keys.Select(ToRow)); + keys.Select(ToRow), + Headers); } private static DebugTableRow ToRow(KeyMeta key) { string priority = key.Priority.ToString("0.###", CultureInfo.InvariantCulture); string effectivePriority = key.GetEffectivePriority().ToString("0.###", CultureInfo.InvariantCulture); + string scoreText = key.CurrentScore.ToString("0.###", CultureInfo.InvariantCulture); string summary = "RimMind.UI.DebugTable.ContextKeys.Priority".Translate(priority).ToString() + " | " + "RimMind.UI.DebugTable.ContextKeys.Effective".Translate(effectivePriority).ToString() + " | " + "RimMind.UI.DebugTable.ContextKeys.UpdateCount".Translate(key.UpdateCount).ToString(); @@ -48,14 +62,14 @@ private static DebugTableRow ToRow(KeyMeta key) return DebugTableRow.Create( key.Key, DebugTableStatus.Completed, - string.Empty, + scoreText, DebugTableEnumLabels.For(key.Layer), key.OwnerMod ?? string.Empty, DebugTableEnumLabels.For(key.CacheScope), "RimMind.UI.DebugTable.ContextKeys.Model".Translate().ToString(), summary, "RimMind.UI.DebugTable.ContextKeys.Score" - .Translate(key.CurrentScore.ToString("0.###", CultureInfo.InvariantCulture)) + .Translate(scoreText) .ToString()); } } diff --git a/Source/Infrastructure/UI/DebugTables/DebugTableModels.cs b/Source/Infrastructure/UI/DebugTables/DebugTableModels.cs index 374850e..87e296c 100644 --- a/Source/Infrastructure/UI/DebugTables/DebugTableModels.cs +++ b/Source/Infrastructure/UI/DebugTables/DebugTableModels.cs @@ -87,14 +87,29 @@ private static string ResolveStatusColorName(DebugTableStatus status) public sealed class DebugTableModel { public DebugTableModel(string title, IEnumerable rows) + : this(title, rows, null, null) + { + } + + public DebugTableModel( + string title, + IEnumerable rows, + IReadOnlyList? headerKeys, + IReadOnlyList? compactHeaderKeys = null) { Title = title; Rows = new ReadOnlyCollection(new List(rows ?? Array.Empty())); + HeaderKeys = headerKeys; + CompactHeaderKeys = compactHeaderKeys; } public string Title { get; } public ReadOnlyCollection Rows { get; } + + public IReadOnlyList? HeaderKeys { get; } + + public IReadOnlyList? CompactHeaderKeys { get; } } public static class DebugTableText @@ -127,10 +142,10 @@ public static DebugTableModel MixedRequests() "AI Requests", new[] { - DebugTableRow.Create("req-001", DebugTableStatus.Waiting, "10:00", "Pawn", "Nickie", "chat", "deepseek-v4-flash", "Queued for context build", "0ms"), + DebugTableRow.Create("req-001", DebugTableStatus.Waiting, "10:00", "Pawn", "Nickie", "chat", "deepseek-flash", "Queued for context build", "0ms"), DebugTableRow.Create("req-002", DebugTableStatus.Streaming, "10:01", "Pawn", "Tynan", "advisor", "gpt-4.1-mini", "Streaming 3 chunks", "1.2s"), - DebugTableRow.Create("req-003", DebugTableStatus.Completed, "10:02", "Colony", "Workbench", "memory", "deepseek-v4-flash", "Completed ToolCall summary: choose_repair_target", "2.4s"), - DebugTableRow.Create("req-004", DebugTableStatus.Failed, "10:03", "Pawn", "Maya", "chat", "deepseek-v4-flash", "HTTP timeout after retry", "5s") + DebugTableRow.Create("req-003", DebugTableStatus.Completed, "10:02", "Colony", "Workbench", "memory", "deepseek-flash", "Completed ToolCall summary: choose_repair_target", "2.4s"), + DebugTableRow.Create("req-004", DebugTableStatus.Failed, "10:03", "Pawn", "Maya", "chat", "deepseek-flash", "HTTP timeout after retry", "5s") }); } diff --git a/Source/Infrastructure/UI/DebugTables/MechanismsDebugTableModelBuilder.cs b/Source/Infrastructure/UI/DebugTables/MechanismsDebugTableModelBuilder.cs index 74df47f..57ff1f0 100644 --- a/Source/Infrastructure/UI/DebugTables/MechanismsDebugTableModelBuilder.cs +++ b/Source/Infrastructure/UI/DebugTables/MechanismsDebugTableModelBuilder.cs @@ -7,6 +7,18 @@ namespace RimMind.Infrastructure.UI.DebugTables { public sealed class MechanismsDebugTableModelBuilder : IDebugTableModelBuilder { + private static readonly string[] Headers = + { + "RimMind.UI.DebugTable.Header.Id", + "RimMind.UI.DebugTable.Header.Status", + "RimMind.UI.DebugTable.Header.OpCount", + "RimMind.UI.DebugTable.Header.Scope", + "RimMind.UI.DebugTable.Header.OwnerMod", + "RimMind.UI.DebugTable.Header.Operations", + "RimMind.UI.DebugTable.Header.Risk", + "RimMind.UI.DebugTable.Header.Summary" + }; + private IGameMechanismRegistry? _registry; private long _cachedGeneration = long.MinValue; private DebugTableModel? _cachedModel; @@ -32,7 +44,8 @@ public static DebugTableModel Build(IReadOnlyList mechanisms) { return new DebugTableModel( "RimMind.UI.Hub.Tab.Mechanisms".Translate(), - mechanisms.Select(ToRow)); + mechanisms.Select(ToRow), + Headers); } private static DebugTableRow ToRow(IGameMechanism mechanism) @@ -40,17 +53,18 @@ private static DebugTableRow ToRow(IGameMechanism mechanism) string operations = mechanism.SupportedOperations.Count > 0 ? string.Join(", ", mechanism.SupportedOperations.Select(DebugTableEnumLabels.For)) : "RimMind.UI.DebugTable.Mechanisms.NoOperations".Translate().ToString(); + string opCount = "RimMind.UI.DebugTable.Mechanisms.OperationCount".Translate(mechanism.SupportedOperations.Count).ToString(); return DebugTableRow.Create( mechanism.MechanismId, DebugTableStatus.Completed, - string.Empty, + opCount, DebugTableEnumLabels.For(mechanism.Scope), mechanism.OwnerModId ?? string.Empty, operations, DebugTableEnumLabels.For(mechanism.Risk), mechanism.Docs.Summary, - "RimMind.UI.DebugTable.Mechanisms.OperationCount".Translate(mechanism.SupportedOperations.Count).ToString()); + opCount); } } } diff --git a/Source/Infrastructure/UI/DebugTables/ToolRegistryDebugTableModelBuilder.cs b/Source/Infrastructure/UI/DebugTables/ToolRegistryDebugTableModelBuilder.cs new file mode 100644 index 0000000..dd6df1a --- /dev/null +++ b/Source/Infrastructure/UI/DebugTables/ToolRegistryDebugTableModelBuilder.cs @@ -0,0 +1,146 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RimMind.Application.Common.Interfaces.Tools; +using RimMind.Application.Common.Models.Tools; +using Verse; + +namespace RimMind.Infrastructure.UI.DebugTables +{ + public sealed class ToolRegistryDebugTableModelBuilder : IDebugTableModelBuilder + { + private static readonly string[] FullHeaders = + { + "RimMind.UI.DebugTable.Header.Id", + "RimMind.UI.DebugTable.Header.Status", + "RimMind.UI.DebugTable.Header.Category", + "RimMind.UI.DebugTable.Header.OwnerMod", + "RimMind.UI.DebugTable.Header.Kind", + "RimMind.UI.DebugTable.Header.Title", + "RimMind.UI.DebugTable.Header.Domain", + "RimMind.UI.DebugTable.Header.Summary" + }; + + private static readonly string[] CompactHeaders = + { + "RimMind.UI.DebugTable.Header.Tool", + "RimMind.UI.DebugTable.Header.Summary" + }; + + private IToolRegistry? _registry; + private long _cachedGeneration = long.MinValue; + private int _cachedCount = -1; + private DebugTableModel? _cachedModel; + + public ToolRegistryDebugTableModelBuilder(IToolRegistry? registry = null) + { + _registry = registry; + } + + public void Bind(IToolRegistry? registry, long generation) + { + if (_cachedGeneration == generation && ReferenceEquals(_registry, registry)) + return; + + _registry = registry; + _cachedGeneration = generation; + _cachedCount = -1; + _cachedModel = null; + } + + public DebugTableModel Build() + { + int currentCount = _registry?.All.Count ?? 0; + if (_cachedModel != null && _cachedCount == currentCount) + return _cachedModel; + + _cachedModel = Build(_registry); + _cachedCount = currentCount; + return _cachedModel; + } + + public static IReadOnlyList FilterDefinitions( + IReadOnlyList? definitions, + string? categoryFilter = null, + string? searchQuery = null) + { + if (definitions == null || definitions.Count == 0) + return Array.Empty(); + + IEnumerable query = definitions.Where(d => d != null); + + if (!string.IsNullOrWhiteSpace(categoryFilter) + && !string.Equals(categoryFilter, "All", StringComparison.OrdinalIgnoreCase)) + { + string cat = categoryFilter!.Trim(); + query = query.Where(d => + string.Equals(d.Category, cat, StringComparison.OrdinalIgnoreCase) + || (d.Manifest != null && string.Equals(d.Manifest.Kind.ToString(), cat, StringComparison.OrdinalIgnoreCase))); + } + + if (!string.IsNullOrWhiteSpace(searchQuery)) + { + string q = searchQuery!.Trim(); + query = query.Where(d => + ContainsIgnoreCase(d.Id, q) + || ContainsIgnoreCase(d.Category, q) + || ContainsIgnoreCase(d.Description, q) + || ContainsIgnoreCase(d.ParametersSchema, q) + || ContainsIgnoreCase(d.Manifest?.DisplayName, q) + || ContainsIgnoreCase(d.Manifest?.OwnerModId, q) + || ContainsIgnoreCase(d.Manifest?.DefaultDomain?.ToString(), q)); + } + + return query + .OrderBy(d => d.Category ?? string.Empty, StringComparer.OrdinalIgnoreCase) + .ThenBy(d => d.Id ?? string.Empty, StringComparer.OrdinalIgnoreCase) + .ToList(); + } + + public static DebugTableModel Build( + IToolRegistry? registry, + string? categoryFilter = null, + string? searchQuery = null) + { + string title = "RimMind.UI.Hub.Tab.ToolCalls".CanTranslate() + ? "RimMind.UI.Hub.Tab.ToolCalls".Translate().ToString() + : "Tool Calls"; + + if (registry == null) + return new DebugTableModel(title, Array.Empty(), FullHeaders, CompactHeaders); + + IReadOnlyList defs = FilterDefinitions( + registry.GetAllDefinitions(), + categoryFilter, + searchQuery); + + return new DebugTableModel(title, defs.Select(ToRow), FullHeaders, CompactHeaders); + } + + private static DebugTableRow ToRow(ToolDefinition def) + { + ToolManifest? manifest = def.Manifest; + string title = manifest != null && !string.IsNullOrWhiteSpace(manifest.DisplayName) + ? $"{manifest.DisplayName} ({def.Id})" + : def.Id; + string domain = manifest?.DefaultDomain?.ToString() ?? "-"; + string risk = manifest != null + ? (manifest.RequiresApproval ? $"{manifest.RiskLevel}*" : manifest.RiskLevel.ToString()) + : "-"; + + return DebugTableRow.Create( + def.Id, + DebugTableStatus.Completed, + def.Category ?? string.Empty, + manifest?.OwnerModId ?? string.Empty, + manifest != null ? manifest.Kind.ToString() : string.Empty, + DebugTableText.Preview(title), + domain, + DebugTableText.Preview(def.Description ?? string.Empty), + risk); + } + + private static bool ContainsIgnoreCase(string? source, string value) + => !string.IsNullOrEmpty(source) && source!.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0; + } +} diff --git a/Source/Infrastructure/UI/Framework/RimMindTableDrawer.cs b/Source/Infrastructure/UI/Framework/RimMindTableDrawer.cs index e7339ab..c8619b1 100644 --- a/Source/Infrastructure/UI/Framework/RimMindTableDrawer.cs +++ b/Source/Infrastructure/UI/Framework/RimMindTableDrawer.cs @@ -41,15 +41,16 @@ public void Draw(Rect rect, DebugTableModel model, ref Vector2 scroll, RimMindLa scope.Record(layout.BottomBar, "Table:BottomBar"); DrawToolbar(layout.Toolbar, model.Title); + IReadOnlyList headers = model.HeaderKeys ?? DebugTableHeaderKeys; if (model.Rows.Count == 0) { DrawEmptyTableBody(layout.Body); - DrawDebugHeaders(layout, scroll.x); + DrawHeaders(layout, headers, scroll.x); return; } DrawDebugRows(layout, model.Rows, ref scroll); - DrawDebugHeaders(layout, scroll.x); + DrawHeaders(layout, headers, scroll.x); } public string? DrawSelectable(Rect rect, DebugTableModel model, string? selectedId, ref Vector2 scroll, RimMindLayoutScope scope) @@ -61,15 +62,16 @@ public void Draw(Rect rect, DebugTableModel model, ref Vector2 scroll, RimMindLa scope.Record(layout.BottomBar, "Table:BottomBar"); DrawToolbar(layout.Toolbar, model.Title); + IReadOnlyList headers = model.HeaderKeys ?? DebugTableHeaderKeys; if (model.Rows.Count == 0) { DrawEmptyTableBody(layout.Body); - DrawDebugHeaders(layout, scroll.x); + DrawHeaders(layout, headers, scroll.x); return null; } string? nextSelectedId = DrawSelectableDebugRows(layout, model.Rows, selectedId, ref scroll); - DrawDebugHeaders(layout, scroll.x); + DrawHeaders(layout, headers, scroll.x); return nextSelectedId; } @@ -90,10 +92,11 @@ public void Draw(Rect rect, DebugTableModel model, ref Vector2 scroll, RimMindLa scope.Record(layout.BottomBar, "Table:BottomBar"); DrawToolbar(layout.Toolbar, model.Title); + IReadOnlyList compactHeaders = model.CompactHeaderKeys ?? CompactListHeaderKeys; if (model.Rows.Count == 0) { DrawEmptyTableBody(layout.Body); - DrawHeaders(layout, CompactListHeaderKeys, scroll.x); + DrawHeaders(layout, compactHeaders, scroll.x); return null; } @@ -102,7 +105,7 @@ public void Draw(Rect rect, DebugTableModel model, ref Vector2 scroll, RimMindLa model.Rows, selectedId, ref scroll); - DrawHeaders(layout, CompactListHeaderKeys, scroll.x); + DrawHeaders(layout, compactHeaders, scroll.x); return nextSelectedId; } diff --git a/Source/Infrastructure/UI/Layout/LayoutAutotestRunner.cs b/Source/Infrastructure/UI/Layout/LayoutAutotestRunner.cs index 71897b6..accac7f 100644 --- a/Source/Infrastructure/UI/Layout/LayoutAutotestRunner.cs +++ b/Source/Infrastructure/UI/Layout/LayoutAutotestRunner.cs @@ -1,6 +1,8 @@ using System; +using System.Collections; using System.Linq; using RimMind.Presentation.UI.Layout; +using UnityEngine; using Verse; namespace RimMind.Infrastructure.UI.Layout @@ -19,25 +21,66 @@ public static void Run(Window[] windows, Action report bool prevTracing = LayoutConflictStore.TracingEnabled; LayoutConflictStore.TracingEnabled = true; - LongEventHandler.ExecuteWhenFinished(() => + if (Current.Root != null && Current.Root.gameObject != null) { + var verifier = Current.Root.gameObject.AddComponent(); + verifier.Begin(windows, prevTracing, reportResult); + return; + } + + LongEventHandler.ExecuteWhenFinished(() => EvaluateAndClose(windows, prevTracing, reportResult)); + } + + private static void EvaluateAndClose( + Window[] windows, + bool prevTracing, + Action reportResult) + { + try + { + LayoutAutotestEvaluation evaluation = LayoutAutotestEvaluator.Evaluate( + windows.Select(window => window.GetType().Name), + windowName => LayoutConflictStore.TryGet(windowName, out LayoutReport? layoutReport) + ? layoutReport + : null); + + LogEvaluation(evaluation); + reportResult(evaluation); + } + finally + { + LayoutConflictStore.TracingEnabled = prevTracing; + CloseWindows(windows); + } + } + + private sealed class DeferredLayoutVerifier : MonoBehaviour + { + public void Begin( + Window[] windows, + bool prevTracing, + Action reportResult) + { + StartCoroutine(WaitAndEvaluateRoutine(windows, prevTracing, reportResult)); + } + + private IEnumerator WaitAndEvaluateRoutine( + Window[] windows, + bool prevTracing, + Action reportResult) + { + for (int i = 0; i < 3; i++) + yield return new WaitForEndOfFrame(); + try { - LayoutAutotestEvaluation evaluation = LayoutAutotestEvaluator.Evaluate( - windows.Select(window => window.GetType().Name), - windowName => LayoutConflictStore.TryGet(windowName, out LayoutReport? layoutReport) - ? layoutReport - : null); - - LogEvaluation(evaluation); - reportResult(evaluation); + EvaluateAndClose(windows, prevTracing, reportResult); } finally { - LayoutConflictStore.TracingEnabled = prevTracing; - CloseWindows(windows); + Destroy(this); } - }); + } } private static void LogEvaluation(LayoutAutotestEvaluation evaluation) diff --git a/Source/Infrastructure/UI/Layout/UiCaptureRunner.cs b/Source/Infrastructure/UI/Layout/UiCaptureRunner.cs index 6d6d728..3d9009c 100644 --- a/Source/Infrastructure/UI/Layout/UiCaptureRunner.cs +++ b/Source/Infrastructure/UI/Layout/UiCaptureRunner.cs @@ -4,6 +4,7 @@ using System.Diagnostics; using System.IO; using System.Linq; +using System.Reflection; using System.Threading.Tasks; using Newtonsoft.Json; using RimMind.Presentation.Runtime.Services; @@ -16,8 +17,14 @@ namespace RimMind.Infrastructure.UI.Layout // Opt-in, short-lived MonoBehaviour: Update supplies the watchdog even if end-of-frame stalls. internal sealed class UiCaptureRunner : MonoBehaviour { + private static readonly PropertyInfo? UiScalePreferenceProperty = + typeof(Prefs).GetProperty("UIScalePreference", BindingFlags.Public | BindingFlags.Static); + private static UiCaptureRunner? _active; private static bool _startupChecked; + + private static float GetConfiguredUiScale() + => UiScalePreferenceProperty?.GetValue(null) is float pref ? pref : Prefs.UIScale; private readonly Stopwatch _clock = new(); private UiCaptureSequence _sequence = null!; private UiCaptureArtifacts _artifacts = null!; @@ -72,7 +79,7 @@ private void Initialize(string runId) RunId = runId, CoreAssemblyMvid = typeof(UiCaptureRunner).Assembly.ManifestModule.ModuleVersionId.ToString(), GameAssemblyMvid = typeof(Game).Assembly.ManifestModule.ModuleVersionId.ToString(), GameVersion = VersionControl.CurrentVersionStringWithRev, Width = Screen.width, Height = Screen.height, - UiScale = Prefs.UIScale, Language = LanguageDatabase.activeLanguage.folderName, + UiScale = GetConfiguredUiScale(), Language = LanguageDatabase.activeLanguage.folderName, ExpectedSceneIds = _scenes.Select(s => s.Id).ToArray() }; Log.Message("[RimMind-Core] UI capture started: " + _artifacts.DirectoryPath); @@ -174,7 +181,7 @@ private bool ValidateWindow(UiCaptureScene scene) int index = windows.IndexOf(_window); if (index < 0 || windows.Skip(index + 1).Any(w => w.windowRect.Overlaps(_window.windowRect))) { Abort("window-occluded"); return false; } - if (Screen.width != _manifest.Width || Screen.height != _manifest.Height || Prefs.UIScale != _manifest.UiScale) + if (Screen.width != _manifest.Width || Screen.height != _manifest.Height || GetConfiguredUiScale() != _manifest.UiScale) { Abort("display-changed"); return false; } return true; } diff --git a/Source/Infrastructure/UI/Layout/UiCaptureScenes.cs b/Source/Infrastructure/UI/Layout/UiCaptureScenes.cs index ee5e386..94ce68e 100644 --- a/Source/Infrastructure/UI/Layout/UiCaptureScenes.cs +++ b/Source/Infrastructure/UI/Layout/UiCaptureScenes.cs @@ -44,6 +44,12 @@ public static IReadOnlyList Create() scenes.Add(new UiCaptureScene("requests-empty", "ai_requests", () => Requests(false, false))); scenes.Add(new UiCaptureScene("requests-long-top", "ai_requests", () => Requests(true, false))); scenes.Add(new UiCaptureScene("requests-long-bottom", "ai_requests", () => Requests(true, true))); + scenes.Add(new UiCaptureScene("hub-capabilities-mechanisms-top", "capabilities", () => Hub("capabilities:mechanisms"))); + scenes.Add(new UiCaptureScene("hub-capabilities-mechanisms-bottom", "capabilities", () => Hub("capabilities:mechanisms", bottom: true))); + scenes.Add(new UiCaptureScene("hub-capabilities-context_keys-top", "capabilities", () => Hub("capabilities:context_keys"))); + scenes.Add(new UiCaptureScene("hub-capabilities-context_keys-bottom", "capabilities", () => Hub("capabilities:context_keys", bottom: true))); + scenes.Add(new UiCaptureScene("requests-rollout-top", "ai_requests", () => RolloutRequests(false))); + scenes.Add(new UiCaptureScene("requests-rollout-bottom", "ai_requests", () => RolloutRequests(true))); scenes.Add(new UiCaptureScene("settings-queue-top", "queue", () => new Window_RimMindSettings(false))); scenes.Add(new UiCaptureScene("settings-queue-bottom", "queue", () => new Window_RimMindSettings(true))); return scenes; @@ -63,6 +69,7 @@ private static Window_RimMindHub Hub(string page, Pawn? pawn = null, bool bottom case OverviewDebugCenterPageDrawer overview: overview.ScrollToBottom(); break; case DebugTablePageBase table: table.ScrollToBottom(); break; case AIRequestsDebugCenterPageDrawer requests: requests.ScrollToBottom(); break; + case CapabilitiesDebugCenterPageDrawer capabilities: capabilities.ScrollToBottom(); break; case AgentsDebugCenterPageDrawer agents: agents.ScrollToBottom(); break; } } @@ -87,5 +94,105 @@ private static Window_RimMindHub Requests(bool longText, bool bottom) ((AIRequestsDebugCenterPageDrawer)window.CurrentDrawer).UseDisplaySnapshot(entries); return window; } + + private static Window_RimMindHub RolloutRequests(bool bottom) + { + var window = Hub("ai_requests:rollout", bottom: bottom); + Pawn pawn = SelectedPawn(); + string npcId = !string.IsNullOrWhiteSpace(pawn.ThingID) ? pawn.ThingID : $"NPC-{pawn.thingIDNumber}"; + DateTime baseTime = new DateTime(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc); + + var turn1 = new AIRequestTraceEntry + { + RequestId = "ui-capture-rollout-t1", + TraceId = "ui-capture-rollout-ep1", + RolloutId = "ui-capture-rollout-ep1", + TurnIndex = 1, + IsAgentRollout = true, + ModId = "RimMind.Core", + ScenarioId = "agent.decision", + NpcId = npcId, + Source = "PawnThinker", + Model = "offline-fixture", + State = AIRequestTraceState.Completed, + PromptTokens = 845, + CompletionTokens = 92, + CachedTokens = 0, + TokensUsed = 937, + ElapsedMs = 640, + StartedAtUtc = baseTime, + FinishedAtUtc = baseTime.AddMilliseconds(640), + SystemPrompt = "\nCore rules\n\n\nIdentity\n\n\nPerception: Colonist needs indoor bed.\n", + UserPrompt = "Evaluate sleeping quarters and available structures.", + ReasoningContent = "Querying colony spatial snapshot and buildable furniture first.", + Response = "{\"thought\":\"Checking buildable beds and room topology.\"}", + ToolCalls = + { + new AIRequestToolCallTrace( + "call_1", + "query_buildable_structures", + true, + null, + "{\"category\":\"furniture\"}", + "{\"status\":\"ok\",\"colony_anchor\":{\"x\":118,\"z\":122,\"has_base\":true},\"rooms\":[{\"room_id\":12,\"role\":\"Bedroom\",\"beds\":1}]}") + }, + Layers = + { + new AIRequestLayerTrace("system", "L0", "Core safety and runtime rules.", 320, false), + new AIRequestLayerTrace("system", "L1", "Colonist identity and traits.", 180, false), + new AIRequestLayerTrace("user", "L4", "Current needs and bedroom shortage.", 110, false) + } + }; + + var turn2 = new AIRequestTraceEntry + { + RequestId = "ui-capture-rollout-t2", + TraceId = "ui-capture-rollout-ep1", + RolloutId = "ui-capture-rollout-ep1", + TurnIndex = 2, + IsAgentRollout = true, + ModId = "RimMind.Core", + ScenarioId = "agent.decision", + NpcId = npcId, + Source = "PawnThinker", + Model = "offline-fixture", + State = AIRequestTraceState.Completed, + PromptTokens = 960, + CompletionTokens = 108, + CachedTokens = 790, + TokensUsed = 1068, + ElapsedMs = 580, + StartedAtUtc = baseTime.AddSeconds(1), + FinishedAtUtc = baseTime.AddSeconds(1).AddMilliseconds(580), + SystemPrompt = "\nCore rules\n\n\nIdentity\n\n\nTool observation received.\n", + UserPrompt = "Place bed inside existing Bedroom cluster.", + ReasoningContent = "Bedroom #12 has space next to existing bed; placing wooden Bed blueprint.", + Response = "{\"thought\":\"Placing wooden bed in Bedroom #12.\"}", + ToolCalls = + { + new AIRequestToolCallTrace( + "call_2", + "place_blueprint", + true, + null, + "{\"building_def\":\"Bed\",\"location_hint\":\"indoor\"}", + "{\"status\":\"placed\",\"room_role\":\"Bedroom\",\"cluster_reason\":\"peer_bed_room_cluster\"}") + }, + Layers = + { + new AIRequestLayerTrace("system", "L0", "Core safety and runtime rules.", 320, true), + new AIRequestLayerTrace("system", "L1", "Colonist identity and traits.", 180, true), + new AIRequestLayerTrace("user", "L4", "Tool observation: Bedroom #12 open tiles.", 225, false) + }, + ActionOutcome = new AIRequestActionOutcomeTrace( + "place_blueprint", + true, + "Placed wooden Bed blueprint in Bedroom #12.", + "Bed | indoor") + }; + + ((AIRequestsDebugCenterPageDrawer)window.CurrentDrawer).UseDisplaySnapshot(new[] { turn1, turn2 }); + return window; + } } } diff --git a/Source/Infrastructure/UI/Layout/UiInteractionDriver.cs b/Source/Infrastructure/UI/Layout/UiInteractionDriver.cs index a1445ca..3fb0ca9 100644 --- a/Source/Infrastructure/UI/Layout/UiInteractionDriver.cs +++ b/Source/Infrastructure/UI/Layout/UiInteractionDriver.cs @@ -6,6 +6,7 @@ using RimMind.Application.Common.Interfaces.Extension; using RimMind.Application.Common.Interfaces.Internal; using RimMind.Application.Common.Models.UI; +using RimMind.Domain.Agent.Policies; using RimMind.Infrastructure.Verse; using RimMind.Presentation; using RimMind.Presentation.Runtime.Services; @@ -252,7 +253,7 @@ public static IEnumerator RunInteractionSuite(string outputDir, BehaviorAutotest yield return new WaitForEndOfFrame(); SaveFrame(clicksDir, "07-hub-overview.png"); - string[] targetTabs = new[] { "agents", "ai_requests", "tool_calls", "mechanisms", "context_keys", "settings" }; + string[] targetTabs = new[] { "agents", "ai_requests", "capabilities", "settings" }; int tabsNavigated = 1; // overview is already visited foreach (var tabId in targetTabs) { @@ -266,6 +267,18 @@ public static IEnumerator RunInteractionSuite(string outputDir, BehaviorAutotest } } + hub.SelectPage("ai_requests:ephemeral"); + yield return new WaitForEndOfFrame(); + SaveFrame(clicksDir, "07b-hub-ai_requests-ephemeral.png"); + + hub.SelectPage("capabilities:mechanisms"); + yield return new WaitForEndOfFrame(); + SaveFrame(clicksDir, "07c-hub-capabilities-mechanisms.png"); + + hub.SelectPage("capabilities:context_keys"); + yield return new WaitForEndOfFrame(); + SaveFrame(clicksDir, "07d-hub-capabilities-context_keys.png"); + if (hub.IsOpen) hub.Close(doCloseSound: false); if (tabsNavigated == targetTabs.Length + 1) @@ -357,7 +370,7 @@ public static IEnumerator RunInteractionSuite(string outputDir, BehaviorAutotest // ============================================================ // 10. PawnAgent Colonist Gizmo Click & Hub Opening // ============================================================ - var colonistPawn = Find.CurrentMap?.mapPawns?.FreeColonists?.FirstOrDefault(); + var colonistPawn = RimMind.Presentation.Api.RimMindPawnLookup.GetEligibleColonists(Find.CurrentMap).FirstOrDefault(); if (colonistPawn != null) { var comp = CompPawnAgent.GetComp(colonistPawn); @@ -377,6 +390,43 @@ public static IEnumerator RunInteractionSuite(string outputDir, BehaviorAutotest { checksPassed++; result.Details.Add($"[PASS] Real Click: PawnAgent Gizmo clicked on colonist [{colonistPawn.Name?.ToStringShort}] -> Hub Agents page focused and rendered"); + if (comp.AutonomyPolicy != null) + { + try + { + comp.AutonomyPolicy.ApplyWorkOnlyNoBlueprintsPreset(); + if (comp.AutonomyPolicy.GetLevel(AutonomyDomain.BlueprintPlacement) == AutonomyLevel.Disabled && + comp.AutonomyPolicy.GetLevel(AutonomyDomain.WorkPriorityModification) == AutonomyLevel.Disabled) + { + yield return new WaitForEndOfFrame(); + SaveFrame(clicksDir, "10b-pawn-permissions-workonly.png"); + checksPassed++; + result.Details.Add("[PASS] Real UI State: Agent Permissions preset [Work Only] applied (Blueprints=Off, WorkTab=Off)"); + } + else + { + throw new InvalidOperationException("WorkOnly preset did not disable BlueprintPlacement and WorkPriorityModification"); + } + + comp.AutonomyPolicy.ApplyFullAutonomousPreset(); + if (comp.AutonomyPolicy.GetLevel(AutonomyDomain.BlueprintPlacement) == AutonomyLevel.FullAutonomous && + comp.AutonomyPolicy.GetLevel(AutonomyDomain.WorkPriorityModification) == AutonomyLevel.FullAutonomous) + { + yield return new WaitForEndOfFrame(); + SaveFrame(clicksDir, "10c-pawn-permissions-fullauto.png"); + checksPassed++; + result.Details.Add("[PASS] Real UI State: Agent Permissions preset [Full Auto] applied (Blueprints=Auto, WorkTab=Auto)"); + } + else + { + throw new InvalidOperationException("FullAuto preset did not enable BlueprintPlacement and WorkPriorityModification"); + } + } + finally + { + comp.AutonomyPolicy.SetDefaultPreset(); + } + } openedHub.Close(false); } else diff --git a/Source/Infrastructure/UI/MainTabWindow_RimMindHub.cs b/Source/Infrastructure/UI/MainTabWindow_RimMindHub.cs index ee3e292..d9888a5 100644 --- a/Source/Infrastructure/UI/MainTabWindow_RimMindHub.cs +++ b/Source/Infrastructure/UI/MainTabWindow_RimMindHub.cs @@ -21,7 +21,7 @@ public class Window_RimMindHub : RimMindWindowBase private readonly RimMindTabbedPageHostDrawer _tabDrawer = new(); private readonly RuntimeBinding _runtimeBinding = new(); - public override Vector2 InitialSize => new Vector2(780f, 580f); + public override Vector2 InitialSize => new Vector2(900f, 620f); public Window_RimMindHub() : this(DebugCenterPageRegistry.DefaultPageId, selectedPawn: null) @@ -33,8 +33,11 @@ internal Window_RimMindHub(string initialPageId, Pawn? selectedPawn) _pages = DebugCenterPageRegistry.CreateAllRegistrations(); foreach (DebugCenterPageRegistration page in _pages) _drawerCache[page.Descriptor.Id] = page.CreateDrawer(); - _pageId = ResolvePageId(initialPageId); + DebugCenterNavigation.ResolveRoute(initialPageId, out string resolvedPageId, out string? resolvedSubTabId); + _pageId = ResolvePageId(resolvedPageId); _context = new DebugCenterPageContext(selectedPawn, _navigation); + if (!string.IsNullOrWhiteSpace(resolvedSubTabId)) + _navigation.SetRequestedSubTab(resolvedSubTabId); forcePause = false; closeOnClickedOutside = true; absorbInputAroundWindow = false; @@ -49,7 +52,13 @@ public static Window_RimMindHub OpenAIRequests() internal string CurrentPageId => _pageId; internal IDebugCenterPageDrawer CurrentDrawer => _drawerCache[_pageId]; - internal void SelectPage(string pageId) => _pageId = ResolvePageId(pageId); + internal void SelectPage(string pageId) + { + DebugCenterNavigation.ResolveRoute(pageId, out string resolvedPageId, out string? resolvedSubTabId); + _pageId = ResolvePageId(resolvedPageId); + if (!string.IsNullOrWhiteSpace(resolvedSubTabId)) + _navigation.SetRequestedSubTab(resolvedSubTabId); + } protected override void DrawContents(Rect inRect, RimMindLayoutScope scope) { @@ -149,7 +158,8 @@ public void Dispose() private static string ResolvePageId(string pageId) { - return DebugCenterPageRegistry.Find(pageId)?.Id + DebugCenterNavigation.ResolveRoute(pageId, out string resolvedPageId, out _); + return DebugCenterPageRegistry.Find(resolvedPageId)?.Id ?? DebugCenterPageRegistry.DefaultPageId; } } diff --git a/Source/Infrastructure/UI/Window_AgentFlowLab.cs b/Source/Infrastructure/UI/Window_AgentFlowLab.cs index b1af88b..ed9f6e6 100644 --- a/Source/Infrastructure/UI/Window_AgentFlowLab.cs +++ b/Source/Infrastructure/UI/Window_AgentFlowLab.cs @@ -74,15 +74,12 @@ protected override void DrawContents(Rect inRect, RimMindLayoutScope scope) float contentH = CalcTotalContentHeight(); Rect viewRect = new Rect(0f, 0f, inRect.width - 16f, contentH); - Widgets.BeginScrollView(inRect, ref _scrollPos, viewRect); scope.Record(inRect, "ScrollView:FlowLabOuter"); - scope.Record(viewRect, "ScrollView:FlowLabContent"); + Widgets.BeginScrollView(inRect, ref _scrollPos, viewRect); float y = 0f; float w = viewRect.width; - Rect titleRect = new Rect(0f, y, w, LineH + 4f); - scope.Record(titleRect, "Header:Title"); DrawSectionHeader(ref y, w, "RimMind.UI.AgentFlowLab.Title"); DrawOfflineModeToggle(ref y, w); DrawScopeSelector(ref y, w); diff --git a/Source/Infrastructure/UI/Window_AgentModeDebug.cs b/Source/Infrastructure/UI/Window_AgentModeDebug.cs index 9e313a7..76ffe82 100644 --- a/Source/Infrastructure/UI/Window_AgentModeDebug.cs +++ b/Source/Infrastructure/UI/Window_AgentModeDebug.cs @@ -101,9 +101,8 @@ private void DrawPawnList(Rect rect, RimMindLayoutScope scope) float contentH = _cachedPawns.Count * RimMindUI.LineHeight; Rect viewRect = new Rect(listRect.x, listRect.y, listRect.width - 16f, contentH); - Widgets.BeginScrollView(listRect, ref _pawnListScrollPos, viewRect); scope.Record(listRect, "ScrollView:PawnListOuter"); - scope.Record(viewRect, "ScrollView:PawnListContent"); + Widgets.BeginScrollView(listRect, ref _pawnListScrollPos, viewRect); float rowY = listRect.y; for (int i = 0; i < _cachedPawns.Count; i++) @@ -116,7 +115,6 @@ private void DrawPawnList(Rect rect, RimMindLayoutScope scope) string label = $"{pawn.Name?.ToStringShort ?? pawn.LabelShort}"; Rect rowRect = new Rect(viewRect.x, rowY, viewRect.width, RimMindUI.LineHeight); - scope.Record(rowRect, $"PawnRow:{i}"); if (i == _selectedPawnIndex) Widgets.DrawBoxSolid(rowRect, RimMindUI.ColorTabActive); @@ -162,9 +160,8 @@ private void DrawDetailPanel(Rect rect, RimMindLayoutScope scope) float contentH = CalculateDetailContentHeight(agent, currentMode, rect.width); Rect viewRect = new Rect(rect.x, rect.y, rect.width - 16f, contentH); - Widgets.BeginScrollView(rect, ref _detailScrollPos, viewRect); scope.Record(rect, "ScrollView:DetailOuter"); - scope.Record(viewRect, "ScrollView:DetailContent"); + Widgets.BeginScrollView(rect, ref _detailScrollPos, viewRect); float y = viewRect.y; diff --git a/Source/Infrastructure/UI/Window_AgentProgressFloat.cs b/Source/Infrastructure/UI/Window_AgentProgressFloat.cs index 6ab4ef3..79d3121 100644 --- a/Source/Infrastructure/UI/Window_AgentProgressFloat.cs +++ b/Source/Infrastructure/UI/Window_AgentProgressFloat.cs @@ -156,9 +156,8 @@ private void DrawAgentList(Rect rect, RimMindLayoutScope scope) { float contentH = _cachedEntries.Count * (EntryH + Padding) + Padding; Rect viewRect = new Rect(rect.x, rect.y, rect.width - 16f, contentH); - Widgets.BeginScrollView(rect, ref _scrollPos, viewRect); scope.Record(rect, "ScrollView:Outer"); - scope.Record(viewRect, "ScrollView:Content"); + Widgets.BeginScrollView(rect, ref _scrollPos, viewRect); float y = viewRect.y + Padding; float entryW = viewRect.width - Padding * 2; @@ -167,7 +166,6 @@ private void DrawAgentList(Rect rect, RimMindLayoutScope scope) { var entry = _cachedEntries[i]; Rect entryRect = new Rect(viewRect.x + Padding, y, entryW, EntryH); - scope.Record(entryRect, $"AgentEntry:{i}"); DrawAgentEntry(entryRect, entry, scope); @@ -228,7 +226,6 @@ private void DrawAgentEntry(Rect rect, AgentProgressEntry entry, RimMindLayoutSc float btnX = rect.xMax - 76f; Rect detailBtn = new Rect(btnX, rect.y + (rect.height - BtnHeight) / 2f, 72f, BtnHeight); - scope.Record(detailBtn, "Button:Details"); if (Widgets.ButtonText(detailBtn, "RimMind.UI.AgentProgressFloat.Details".Translate())) { if (entry.IsScopedAgent && entry.AgentControl != null) diff --git a/Source/Infrastructure/UI/Window_AgentStateDebug.cs b/Source/Infrastructure/UI/Window_AgentStateDebug.cs index f55dfb8..59d6c00 100644 --- a/Source/Infrastructure/UI/Window_AgentStateDebug.cs +++ b/Source/Infrastructure/UI/Window_AgentStateDebug.cs @@ -92,9 +92,8 @@ private void DrawScopedAgentDetail(Rect rect, IScopedAgent scopedAgent, RimMindL { float contentH = CalculateScopedContentHeight(scopedAgent, rect.width); Rect viewRect = new Rect(rect.x, rect.y, rect.width - 16f, contentH); - Widgets.BeginScrollView(rect, ref _scrollPos, viewRect); scope.Record(rect, "ScrollView:ScopedOuter"); - scope.Record(viewRect, "ScrollView:ScopedContent"); + Widgets.BeginScrollView(rect, ref _scrollPos, viewRect); float y = viewRect.y + RimMindUI.Padding; float x = viewRect.x + RimMindUI.Padding; @@ -229,14 +228,12 @@ private float DrawScopedAgentButtons(float x, float y, float labelW, IScopedAgen float btnW = 160f; Rect forceThinkBtn = new Rect(x, y, btnW, RimMindUI.BtnHeight); - scope.Record(forceThinkBtn, "Button:ForceThink"); if (Widgets.ButtonText(forceThinkBtn, "RimMind.UI.AgentStateDebug.SendTestRequest".Translate())) { scopedAgent.ForceThink(); } Rect requestLogBtn = new Rect(x + btnW + RimMindUI.Padding, y, btnW, RimMindUI.BtnHeight); - scope.Record(requestLogBtn, "Button:RequestLog"); if (Widgets.ButtonText(requestLogBtn, "RimMind.UI.AgentStateDebug.OpenRequestLog".Translate())) { Find.WindowStack.Add(new Window_RequestLog()); @@ -244,14 +241,12 @@ private float DrawScopedAgentButtons(float x, float y, float labelW, IScopedAgen y += RimMindUI.BtnHeight + RimMindUI.Padding; Rect toolCallBtn = new Rect(x, y, btnW, RimMindUI.BtnHeight); - scope.Record(toolCallBtn, "Button:ToolCallDebug"); if (Widgets.ButtonText(toolCallBtn, "RimMind.UI.AgentStateDebug.OpenToolCallDebug".Translate())) { Find.WindowStack.Add(new Window_ToolCallDebug()); } Rect mechanismBtn = new Rect(x + btnW + RimMindUI.Padding, y, btnW, RimMindUI.BtnHeight); - scope.Record(mechanismBtn, "Button:MechanismStatus"); if (Widgets.ButtonText(mechanismBtn, "RimMind.UI.AgentStateDebug.OpenMechanismStatus".Translate())) { Find.WindowStack.Add(new Window_MechanismStatus()); @@ -259,7 +254,6 @@ private float DrawScopedAgentButtons(float x, float y, float labelW, IScopedAgen y += RimMindUI.BtnHeight + RimMindUI.Padding; Rect destroyBtn = new Rect(x, y, btnW, RimMindUI.BtnHeight); - scope.Record(destroyBtn, "Button:DestroyScopedAgent"); if (Widgets.ButtonText(destroyBtn, "RimMind.UI.AgentStateDebug.DestroyScopedAgent".Translate())) { var manager = RuntimeServiceHub.Shared.Capture().GetOptional(); @@ -304,9 +298,8 @@ private void DrawPawnDetail(Rect rect, Pawn pawn, RimMindLayoutScope scope) IPawnAgentVerse? agent = CompPawnAgent.GetComp(pawn)?.ResolveCurrentAgent(runtimeScope); float contentH = CalculatePawnContentHeight(agent, rect.width); Rect viewRect = new Rect(rect.x, rect.y, rect.width - 16f, contentH); - Widgets.BeginScrollView(rect, ref _scrollPos, viewRect); scope.Record(rect, "ScrollView:PawnOuter"); - scope.Record(viewRect, "ScrollView:PawnContent"); + Widgets.BeginScrollView(rect, ref _scrollPos, viewRect); float y = viewRect.y + RimMindUI.Padding; @@ -447,7 +440,6 @@ private float DrawButtons(float x, float y, float labelW, Pawn pawn, RimMindLayo float btnW = 160f; Rect createAgentBtn = new Rect(x, y, btnW, RimMindUI.BtnHeight); - scope.Record(createAgentBtn, "Button:CreateAgent"); if (Widgets.ButtonText(createAgentBtn, "RimMind.UI.AgentStateDebug.CreateAgent".Translate())) { RuntimeServiceScope runtimeScope = RuntimeServiceHub.Shared.Capture(); @@ -466,7 +458,6 @@ private float DrawButtons(float x, float y, float labelW, Pawn pawn, RimMindLayo } Rect buildContextBtn = new Rect(x + btnW + RimMindUI.Padding, y, btnW, RimMindUI.BtnHeight); - scope.Record(buildContextBtn, "Button:BuildContext"); if (Widgets.ButtonText(buildContextBtn, "RimMind.UI.AgentStateDebug.BuildContext".Translate())) { string npcId = $"NPC-{pawn.thingIDNumber}"; @@ -487,7 +478,6 @@ private float DrawButtons(float x, float y, float labelW, Pawn pawn, RimMindLayo y += RimMindUI.BtnHeight + RimMindUI.Padding; Rect testThinkBtn = new Rect(x, y, btnW, RimMindUI.BtnHeight); - scope.Record(testThinkBtn, "Button:SendTestRequest"); if (Widgets.ButtonText(testThinkBtn, "RimMind.UI.AgentStateDebug.SendTestRequest".Translate())) { RuntimeServiceScope runtimeScope = RuntimeServiceHub.Shared.Capture(); @@ -495,7 +485,6 @@ private float DrawButtons(float x, float y, float labelW, Pawn pawn, RimMindLayo } Rect requestLogBtn = new Rect(x + btnW + RimMindUI.Padding, y, btnW, RimMindUI.BtnHeight); - scope.Record(requestLogBtn, "Button:RequestLog"); if (Widgets.ButtonText(requestLogBtn, "RimMind.UI.AgentStateDebug.OpenRequestLog".Translate())) { Find.WindowStack.Add(new Window_RequestLog()); @@ -503,14 +492,12 @@ private float DrawButtons(float x, float y, float labelW, Pawn pawn, RimMindLayo y += RimMindUI.BtnHeight + RimMindUI.Padding; Rect toolCallBtn = new Rect(x, y, btnW, RimMindUI.BtnHeight); - scope.Record(toolCallBtn, "Button:ToolCallDebug"); if (Widgets.ButtonText(toolCallBtn, "RimMind.UI.AgentStateDebug.OpenToolCallDebug".Translate())) { Find.WindowStack.Add(new Window_ToolCallDebug()); } Rect mechanismBtn = new Rect(x + btnW + RimMindUI.Padding, y, btnW, RimMindUI.BtnHeight); - scope.Record(mechanismBtn, "Button:MechanismStatus"); if (Widgets.ButtonText(mechanismBtn, "RimMind.UI.AgentStateDebug.OpenMechanismStatus".Translate())) { Find.WindowStack.Add(new Window_MechanismStatus()); diff --git a/Source/Infrastructure/UI/Window_ContextKeyDebug.cs b/Source/Infrastructure/UI/Window_ContextKeyDebug.cs index 2a7b246..13756e8 100644 --- a/Source/Infrastructure/UI/Window_ContextKeyDebug.cs +++ b/Source/Infrastructure/UI/Window_ContextKeyDebug.cs @@ -232,9 +232,8 @@ private void DrawKeyList(Rect rect, IReadOnlyList keys, RimMindLayoutSc } Rect viewRect = new Rect(rect.x, rect.y, rect.width - 16f, contentH); - Widgets.BeginScrollView(rect, ref _scrollPos, viewRect); scope.Record(rect, "ScrollView:KeyListOuter"); - scope.Record(viewRect, "ScrollView:KeyListContent"); + Widgets.BeginScrollView(rect, ref _scrollPos, viewRect); float y = viewRect.y; foreach (var group in grouped) @@ -249,7 +248,6 @@ private void DrawKeyList(Rect rect, IReadOnlyList keys, RimMindLayoutSc foreach (var key in group) { Rect entryRect = new Rect(viewRect.x, y, viewRect.width, LineH); - scope.Record(entryRect, $"KeyEntry:{key.Key}"); bool selected = _selectedKeyDetail == key.Key; if (selected) Widgets.DrawBoxSolid(entryRect, new Color(0.25f, 0.35f, 0.55f, 0.6f)); diff --git a/Source/Infrastructure/UI/Window_MechanismStatus.cs b/Source/Infrastructure/UI/Window_MechanismStatus.cs index 28c9c14..3de27a3 100644 --- a/Source/Infrastructure/UI/Window_MechanismStatus.cs +++ b/Source/Infrastructure/UI/Window_MechanismStatus.cs @@ -165,9 +165,8 @@ private void DrawContent(Rect rect, RimMindLayoutScope scope) } Rect viewRect = new Rect(rect.x, rect.y, rect.width - 16f, contentH); - Widgets.BeginScrollView(rect, ref _scrollPos, viewRect); scope.Record(rect, "ScrollView:Outer"); - scope.Record(viewRect, "ScrollView:Content"); + Widgets.BeginScrollView(rect, ref _scrollPos, viewRect); float y = rect.y; for (int i = 0; i < filtered.Count; i++) @@ -176,7 +175,6 @@ private void DrawContent(Rect rect, RimMindLayoutScope scope) float entryH = heights[i]; Rect entryRect = new Rect(viewRect.x, y, viewRect.width, entryH); - scope.Record(entryRect, $"MechanismEntry:{mech.MechanismId}"); Widgets.DrawBoxSolid(entryRect, new Color(0.12f, 0.12f, 0.16f, 0.7f)); DrawMechanismEntry(entryRect, mech, tools); diff --git a/Source/Infrastructure/UI/Window_RequestLog.cs b/Source/Infrastructure/UI/Window_RequestLog.cs index 2182d02..d8f5b0d 100644 --- a/Source/Infrastructure/UI/Window_RequestLog.cs +++ b/Source/Infrastructure/UI/Window_RequestLog.cs @@ -113,9 +113,8 @@ private void DrawContent( } Rect viewRect = new Rect(rect.x, rect.y, rect.width - 16f, contentH); - Widgets.BeginScrollView(rect, ref _scrollPos, viewRect); scope?.Record(rect, "ScrollView:Outer"); - scope?.Record(viewRect, "ScrollView:Content"); + Widgets.BeginScrollView(rect, ref _scrollPos, viewRect); float y = rect.y; for (int i = 0; i < pending.Count; i++) @@ -124,7 +123,6 @@ private void DrawContent( float entryH = heights[i]; var entryRect = new Rect(viewRect.x, y, viewRect.width, entryH); - scope?.Record(entryRect, $"Entry:{i}"); Widgets.DrawBoxSolid(entryRect, new Color(0.12f, 0.12f, 0.16f, 0.7f)); string header = entry.systemBlocked diff --git a/Source/Infrastructure/UI/Window_ToolCallDebug.cs b/Source/Infrastructure/UI/Window_ToolCallDebug.cs index 2c596ae..244c33c 100644 --- a/Source/Infrastructure/UI/Window_ToolCallDebug.cs +++ b/Source/Infrastructure/UI/Window_ToolCallDebug.cs @@ -123,9 +123,8 @@ private void DrawToolList(Rect rect, IReadOnlyList defs, RimMind } Rect viewRect = new Rect(rect.x, rect.y, rect.width - 16f, contentH); - Widgets.BeginScrollView(rect, ref _scrollPos, viewRect); scope.Record(rect, "ScrollView:ToolListOuter"); - scope.Record(viewRect, "ScrollView:ToolListContent"); + Widgets.BeginScrollView(rect, ref _scrollPos, viewRect); float y = viewRect.y; foreach (var group in grouped) @@ -140,7 +139,6 @@ private void DrawToolList(Rect rect, IReadOnlyList defs, RimMind foreach (var def in group) { Rect entryRect = new Rect(viewRect.x, y, viewRect.width, EntryH); - scope.Record(entryRect, $"ToolEntry:{def.Id}"); bool selected = _selectedToolId == def.Id; if (selected) Widgets.DrawBoxSolid(entryRect, new Color(0.25f, 0.35f, 0.55f, 0.6f)); diff --git a/Source/Infrastructure/Verse/AIRequestTraceLog.cs b/Source/Infrastructure/Verse/AIRequestTraceLog.cs index ff13cfe..247d0d7 100644 --- a/Source/Infrastructure/Verse/AIRequestTraceLog.cs +++ b/Source/Infrastructure/Verse/AIRequestTraceLog.cs @@ -13,6 +13,7 @@ public sealed class AIRequestTraceLog : IAIRequestTraceLog private readonly object _lock = new(); private readonly List _entries = new(); private readonly Dictionary _byId = new(System.StringComparer.Ordinal); + private readonly Dictionary _lastLayerHashByScopeAndTag = new(System.StringComparer.Ordinal); private long _revision; private long _entriesSnapshotCount; @@ -82,6 +83,9 @@ public static bool MatchesActor( if (string.IsNullOrWhiteSpace(npcId) && string.IsNullOrWhiteSpace(fallbackPawnId)) return true; + if (!string.IsNullOrWhiteSpace(entry.NpcId)) + return MatchesId(entry.NpcId!.Trim(), npcId, fallbackPawnId); + string source = entry.Source ?? string.Empty; int npcIdx = source.IndexOf("npc:", System.StringComparison.OrdinalIgnoreCase); if (npcIdx >= 0) @@ -129,13 +133,19 @@ public void StartRequest(string requestId, string source, string model, string s existing.UserPrompt = userPrompt; existing.AssistantPrompt = assistantPrompt; existing.Response = string.Empty; + existing.ReasoningContent = null; existing.Error = null; existing.TokensUsed = 0; + existing.PromptTokens = 0; + existing.CompletionTokens = 0; + existing.CachedTokens = 0; existing.ElapsedMs = 0; existing.StartedAtUtc = System.DateTime.UtcNow; existing.FinishedAtUtc = null; existing.State = AIRequestTraceState.Running; existing.ToolCalls.Clear(); + existing.Layers.Clear(); + existing.ActionOutcome = null; _revision++; return; } @@ -159,13 +169,100 @@ public void StartRequest(string requestId, string source, string model, string s } } + public void UpdateRequestMetadata( + string requestId, + string traceId, + string rolloutId, + int turnIndex, + string modId, + string scenarioId, + string? npcId, + bool isAgentRollout) + { + lock (_lock) + { + var entry = FindOrCreate(requestId); + entry.TraceId = traceId ?? string.Empty; + entry.RolloutId = rolloutId ?? string.Empty; + entry.TurnIndex = turnIndex; + entry.ModId = modId ?? string.Empty; + entry.ScenarioId = scenarioId ?? string.Empty; + entry.NpcId = string.IsNullOrWhiteSpace(npcId) ? null : npcId; + entry.IsAgentRollout = isAgentRollout; + _revision++; + } + } + + public void UpdateRequestLayers(string requestId, IReadOnlyList layers) + { + if (layers == null) + return; + + lock (_lock) + { + var entry = FindOrCreate(requestId); + entry.Layers.Clear(); + string scope = !string.IsNullOrWhiteSpace(entry.NpcId) + ? entry.NpcId! + : (!string.IsNullOrWhiteSpace(entry.ModId) ? entry.ModId : entry.Source); + + foreach (var layer in layers) + { + if (layer == null) continue; + string content = layer.Content ?? string.Empty; + string hashKey = $"{scope}|{layer.Role}|{layer.LayerTag}"; + var sig = (content.Length, System.StringComparer.Ordinal.GetHashCode(content)); + bool isStableSystemLayer = string.Equals(layer.Role, "system", System.StringComparison.OrdinalIgnoreCase) + || layer.LayerTag.StartsWith("L0", System.StringComparison.OrdinalIgnoreCase) + || layer.LayerTag.StartsWith("L1", System.StringComparison.OrdinalIgnoreCase) + || layer.LayerTag.StartsWith("L2", System.StringComparison.OrdinalIgnoreCase) + || layer.LayerTag.StartsWith("L3", System.StringComparison.OrdinalIgnoreCase); + + bool reused = layer.IsPrefixReused; + if (isStableSystemLayer + && _lastLayerHashByScopeAndTag.TryGetValue(hashKey, out var prev) + && prev.Length == sig.Length + && prev.Hash == sig.Item2) + { + reused = true; + } + if (isStableSystemLayer) + _lastLayerHashByScopeAndTag[hashKey] = sig; + + entry.Layers.Add(new AIRequestLayerTrace( + layer.Role, + layer.LayerTag, + content, + content.Length, + reused)); + } + _revision++; + } + } + public void CompleteRequest(string requestId, string response, int tokensUsed, int elapsedMs) + => CompleteRequestDetailed(requestId, response, reasoningContent: null, tokensUsed, promptTokens: 0, completionTokens: 0, cachedTokens: 0, elapsedMs); + + public void CompleteRequestDetailed( + string requestId, + string response, + string? reasoningContent, + int tokensUsed, + int promptTokens, + int completionTokens, + int cachedTokens, + int elapsedMs) { lock (_lock) { var entry = FindOrCreate(requestId); entry.Response = response; + if (!string.IsNullOrWhiteSpace(reasoningContent)) + entry.ReasoningContent = reasoningContent; entry.TokensUsed = tokensUsed; + entry.PromptTokens = promptTokens; + entry.CompletionTokens = completionTokens; + entry.CachedTokens = cachedTokens; entry.ElapsedMs = elapsedMs; entry.FinishedAtUtc = System.DateTime.UtcNow; entry.State = AIRequestTraceState.Completed; @@ -202,6 +299,16 @@ public void UpdateRequestPrompts(string requestId, string systemPrompt, string u } public void AddToolCall(string requestId, string toolCallId, string toolName, bool succeeded, string? error) + => AddToolCallDetailed(requestId, toolCallId, toolName, succeeded, error, argumentsJson: null, resultContent: null); + + public void AddToolCallDetailed( + string requestId, + string toolCallId, + string toolName, + bool succeeded, + string? error, + string? argumentsJson, + string? resultContent) { lock (_lock) { @@ -209,13 +316,76 @@ public void AddToolCall(string requestId, string toolCallId, string toolName, bo int existingIdx = entry.ToolCalls.FindIndex(t => t.ToolCallId == toolCallId); if (existingIdx >= 0) { + var existing = entry.ToolCalls[existingIdx]; entry.ToolCalls[existingIdx] = new AIRequestToolCallTrace( - toolCallId, toolName, succeeded, error); + toolCallId, + toolName, + succeeded, + error, + argumentsJson ?? existing.ArgumentsJson, + resultContent ?? existing.ResultContent); } else { entry.ToolCalls.Add(new AIRequestToolCallTrace( - toolCallId, toolName, succeeded, error)); + toolCallId, + toolName, + succeeded, + error, + argumentsJson, + resultContent)); + } + _revision++; + } + } + + internal bool HasToolCall(string requestId, string toolCallId) + { + lock (_lock) + { + if (string.IsNullOrEmpty(requestId) || !_byId.TryGetValue(requestId, out var entry)) + return false; + return entry.ToolCalls.Any(t => t.ToolCallId == toolCallId); + } + } + + public void RecordActionOutcome( + string requestId, + string actionIntent, + bool succeeded, + string? detail = null, + string? paramPreview = null) + { + if (string.IsNullOrWhiteSpace(requestId)) + return; + + lock (_lock) + { + if (!_byId.TryGetValue(requestId, out var entry)) + return; + + entry.ActionOutcome = new AIRequestActionOutcomeTrace( + actionIntent ?? string.Empty, + succeeded, + detail, + paramPreview); + + // Sync final terminal action outcome back onto any matching declared write-tool trace + // that had ResultContent == null (i.e. deferred from ToolCallDispatchMiddleware to DecisionProcessor). + for (int i = entry.ToolCalls.Count - 1; i >= 0; i--) + { + var tc = entry.ToolCalls[i]; + if (tc.ResultContent == null + && (string.Equals(tc.ToolName, actionIntent, System.StringComparison.OrdinalIgnoreCase) + || entry.ToolCalls.Count == 1)) + { + entry.ToolCalls[i] = tc with + { + Succeeded = succeeded, + Error = succeeded ? null : (detail ?? tc.Error ?? "Action failed") + }; + break; + } } _revision++; } @@ -227,6 +397,7 @@ public void Clear() { _entries.Clear(); _byId.Clear(); + _lastLayerHashByScopeAndTag.Clear(); _revision++; } } @@ -268,25 +439,41 @@ private static AIRequestTraceEntry CloneEntry(AIRequestTraceEntry entry) var snapshot = new AIRequestTraceEntry { RequestId = entry.RequestId, + TraceId = entry.TraceId, + RolloutId = entry.RolloutId, + TurnIndex = entry.TurnIndex, + ModId = entry.ModId, + ScenarioId = entry.ScenarioId, + NpcId = entry.NpcId, + IsAgentRollout = entry.IsAgentRollout, Source = entry.Source, Model = entry.Model, SystemPrompt = entry.SystemPrompt, UserPrompt = entry.UserPrompt, AssistantPrompt = entry.AssistantPrompt, Response = entry.Response, + ReasoningContent = entry.ReasoningContent, Error = entry.Error, TokensUsed = entry.TokensUsed, + PromptTokens = entry.PromptTokens, + CompletionTokens = entry.CompletionTokens, + CachedTokens = entry.CachedTokens, ElapsedMs = entry.ElapsedMs, StartedAtUtc = entry.StartedAtUtc, FinishedAtUtc = entry.FinishedAtUtc, - State = entry.State + State = entry.State, + ActionOutcome = entry.ActionOutcome }; snapshot.ToolCalls.AddRange(entry.ToolCalls.Select(toolCall => new AIRequestToolCallTrace( toolCall.ToolCallId, toolCall.ToolName, toolCall.Succeeded, - toolCall.Error))); + toolCall.Error, + toolCall.ArgumentsJson, + toolCall.ResultContent))); + + snapshot.Layers.AddRange(entry.Layers); return snapshot; } diff --git a/Source/Infrastructure/Verse/CompPawnAgent.cs b/Source/Infrastructure/Verse/CompPawnAgent.cs index 56eb941..d78d108 100644 --- a/Source/Infrastructure/Verse/CompPawnAgent.cs +++ b/Source/Infrastructure/Verse/CompPawnAgent.cs @@ -56,7 +56,7 @@ internal set private Texture2D? _agentIcon; private Texture2D? _agentDevIcon; - private Pawn Pawn => (Pawn)parent; + private Pawn? PawnOrNull => parent as Pawn; public override void CompTick() { @@ -196,8 +196,11 @@ public override void PostDestroy(DestroyMode mode, Map previousMap) public override void PostExposeData() { base.PostExposeData(); + if (!(parent is Pawn p)) + return; + bool skipSavingAgent = Scribe.mode == LoadSaveMode.Saving - && (_agent == null || !(parent is Pawn p) || !RimMind.Presentation.Api.RimMindPawnLookup.IsActiveSpawnedColonist(p)); + && (_agent == null || !RimMind.Presentation.Api.RimMindPawnLookup.IsActiveSpawnedColonist(p)); if (!skipSavingAgent) { EnsureServicesCached(); @@ -231,6 +234,9 @@ public override void PostExposeData() public override IEnumerable CompGetGizmosExtra() { + if (!(parent is Pawn pawn)) + yield break; + yield return new Command_Action { defaultLabel = "RimMind.Agent.Gizmo.Control".Translate(), @@ -238,7 +244,7 @@ public override IEnumerable CompGetGizmosExtra() icon = AgentIcon, action = () => { - Find.WindowStack.Add(Window_RimMindHub.OpenAgentsForPawn(Pawn)); + Find.WindowStack.Add(Window_RimMindHub.OpenAgentsForPawn(pawn)); }, }; @@ -251,7 +257,7 @@ public override IEnumerable CompGetGizmosExtra() icon = AgentDevIcon, action = () => { - Log.Message($"[RimMind-Core] {Pawn.Name?.ToStringShort}\n{Agent.GetDebugInfo()}"); + Log.Message($"[RimMind-Core] {pawn.Name?.ToStringShort}\n{Agent.GetDebugInfo()}"); }, }; } @@ -286,10 +292,12 @@ public bool HasActiveIntentSession { get { + var pawn = PawnOrNull; + if (pawn == null) return false; var session = ActiveIntentSession; if (session == null) return false; int currentTick = Find.TickManager?.TicksGame ?? 0; - if (!session.IsActive(Pawn, currentTick)) + if (!session.IsActive(pawn, currentTick)) { ClearIntentSession(); return false; @@ -374,6 +382,5 @@ private void EnsureCurrentAgent(IPawnAgentFactoryVerse? factory, IAgentBus? agen Agent = factory.Create(pawn, agentBus) as IPawnAgentVerse; _agentRuntimeGeneration = generation; } - } } diff --git a/Source/Infrastructure/Verse/ITab_Pawn_Agent.cs b/Source/Infrastructure/Verse/ITab_Pawn_Agent.cs index c0ec157..3975bda 100644 --- a/Source/Infrastructure/Verse/ITab_Pawn_Agent.cs +++ b/Source/Infrastructure/Verse/ITab_Pawn_Agent.cs @@ -47,9 +47,8 @@ protected override void FillTabContents(Rect inRect, RimMindLayoutScope scope) float contentH = CalculateContentHeight(agent, rect.width); var contentRect = new Rect(0f, 0f, rect.width - 16f, contentH); - Widgets.BeginScrollView(rect, ref _scrollPosition, contentRect); scope.Record(rect, "ScrollView:Outer"); - scope.Record(contentRect, "ScrollView:Content"); + Widgets.BeginScrollView(rect, ref _scrollPosition, contentRect); float curY = 0f; diff --git a/Source/Presentation/Agent/MapContextBuilder.cs b/Source/Presentation/Agent/MapContextBuilder.cs index 94236bf..909591f 100644 --- a/Source/Presentation/Agent/MapContextBuilder.cs +++ b/Source/Presentation/Agent/MapContextBuilder.cs @@ -214,7 +214,7 @@ public List BuildMapContextEntries(Map map, bool brief = false) float foodNutrition = 0f; try { - foodNutrition = map.resourceCounter?.TotalHumanEdibleNutrition ?? 0f; + foodNutrition = CountAvailableMapFoodNutrition(map); } catch (Exception ex) { WarnRateLimited("FoodNutrition", ex); } otherSb.AppendLine(Tr("RimMind.Prompt.FoodStorage", $"{foodNutrition:F0}")); @@ -259,6 +259,7 @@ public List BuildMapContextEntries(Map map, bool brief = false) if (!brief && map.listerBuildings != null) { + AppendColonyRoomsSummary(map, otherSb); var worktables = new List(); try { @@ -450,6 +451,128 @@ private string ThreatLabel(float wealth) }; } + private static float CountAvailableMapFoodNutrition(Map? map) + { + if (map == null) return 0f; + float counted = 0f; + try + { + counted = map.resourceCounter?.TotalHumanEdibleNutrition ?? 0f; + var foodThings = map.listerThings?.ThingsInGroup(ThingRequestGroup.FoodSourceNotPlantOrTree); + if (foodThings != null && foodThings.Count > 0) + { + float unforbiddenTotal = 0f; + for (int i = 0; i < foodThings.Count; i++) + { + var t = foodThings[i]; + if (t == null || !t.Spawned || t.Destroyed || t is Corpse || t is Pawn) + continue; + if (t.Position.Fogged(map) || t.IsForbidden(Faction.OfPlayer)) + continue; + var ingestible = t.def?.ingestible; + if (ingestible == null || !t.def!.IsNutritionGivingIngestible || !ingestible.HumanEdible) + continue; + if (ingestible.drugCategory != DrugCategory.None || ingestible.preferability < FoodPreferability.RawBad) + continue; + + float nut = t.GetStatValue(StatDefOf.Nutrition); + if (nut > 0f) + { + unforbiddenTotal += nut * Math.Max(1, t.stackCount); + } + } + if (unforbiddenTotal > counted) + counted = unforbiddenTotal; + } + } + catch (Exception ex) { WarnRateLimited("CountAvailableMapFoodNutrition", ex); } + return counted; + } + + private static void AppendColonyRoomsSummary(Map map, StringBuilder sb) + { + if (map == null || sb == null) return; + try + { + var buildings = map.listerBuildings?.allBuildingsColonist; + if (buildings == null || buildings.Count == 0) return; + + var stats = new Dictionary(); + int limit = Math.Min(buildings.Count, 200); + int wallProbes = 0; + + for (int i = 0; i < limit; i++) + { + var b = buildings[i]; + if (b == null || !b.Spawned || b.Destroyed) continue; + + if (b.def != null && b.def.passability == Traversability.Impassable) + { + if (wallProbes < 48) + { + wallProbes++; + for (int d = 0; d < 4; d++) + { + IntVec3 nCell = b.Position + GenAdj.CardinalDirections[d]; + if (!nCell.InBounds(map) || nCell.Fogged(map)) continue; + Room? nRoom = nCell.GetRoom(map); + if (nRoom == null || nRoom.PsychologicallyOutdoors || nRoom.TouchesMapEdge || nRoom.CellCount <= 0) continue; + if (!stats.TryGetValue(nRoom.ID, out var cur)) + cur = (nRoom.CellCount, 0, 0, 0, 0, 0, 0); + stats[nRoom.ID] = (cur.Cells, cur.Beds, cur.Work, cur.Tables, cur.SumX + nCell.x, cur.SumZ + nCell.z, cur.Samples + 1); + } + } + continue; + } + + Room? room = b.Position.InBounds(map) ? b.Position.GetRoom(map) : null; + if (room == null || room.PsychologicallyOutdoors || room.TouchesMapEdge || room.CellCount <= 0) continue; + + if (!stats.TryGetValue(room.ID, out var entry)) + entry = (room.CellCount, 0, 0, 0, 0, 0, 0); + + int addBeds = b is Building_Bed ? 1 : 0; + int addWork = b is Building_WorkTable ? 1 : 0; + int addTable = b.def?.surfaceType == SurfaceType.Eat ? 1 : 0; + stats[room.ID] = ( + entry.Cells, + entry.Beds + addBeds, + entry.Work + addWork, + entry.Tables + addTable, + entry.SumX + b.Position.x, + entry.SumZ + b.Position.z, + entry.Samples + 1); + } + + if (stats.Count == 0) return; + + var ordered = stats + .OrderByDescending(kv => kv.Value.Beds + kv.Value.Work + kv.Value.Tables) + .ThenByDescending(kv => kv.Value.Cells) + .Take(6) + .Select(kv => + { + var v = kv.Value; + int cx = v.Samples > 0 ? (int)(v.SumX / v.Samples) : 0; + int cz = v.Samples > 0 ? (int)(v.SumZ / v.Samples) : 0; + string role = v.Beds > 1 ? "Barracks" + : v.Beds == 1 ? "Bedroom" + : v.Work > 0 ? "Workshop" + : v.Tables > 0 ? "Dining" + : "Indoor"; + return $"{role}@({cx},{cz},cells={v.Cells},beds={v.Beds},work={v.Work})"; + }) + .ToList(); + + string summaryList = string.Join("; ", ordered); + string key = "RimMind.Prompt.ColonyRooms"; + sb.AppendLine(key.CanTranslate() + ? Tr(key, summaryList) + : $"ColonyRooms: [{summaryList}]"); + } + catch (Exception ex) { WarnRateLimited("AppendColonyRoomsSummary", ex); } + } + private static int CountAvailableMapResource(Map? map, ThingDef? def) { if (map == null || def == null) return 0; diff --git a/Source/Presentation/Agent/PawnAgent.cs b/Source/Presentation/Agent/PawnAgent.cs index 15915d8..8bca13b 100644 --- a/Source/Presentation/Agent/PawnAgent.cs +++ b/Source/Presentation/Agent/PawnAgent.cs @@ -164,7 +164,9 @@ public void Tick() { case AgentWorkflowPhase.Idle: _perceiver.Tick(); - if (_thinker.ShouldThink()) + // An in-flight request or pending callback must keep the thinker ticking, + // otherwise the callback is never consumed and the agent deadlocks. + if (_thinker.IsThinking || _thinker.ShouldThink()) TransitionWorkflow(AgentWorkflowPhase.Thinking); break; diff --git a/Source/Presentation/Agent/PawnContextBuilder.Extract.cs b/Source/Presentation/Agent/PawnContextBuilder.Extract.cs index d2a376a..dc64849 100644 --- a/Source/Presentation/Agent/PawnContextBuilder.Extract.cs +++ b/Source/Presentation/Agent/PawnContextBuilder.Extract.cs @@ -17,7 +17,7 @@ public string ExtractPawnBaseInfo(Pawn pawn) if (pawn == null) return ""; var data = PawnDataExtractor.Extract(pawn, _logSink); var parts = new List(); - parts.Add(data.Name); + parts.Add(pawn.thingIDNumber > 0 ? $"{data.Name} (pawn_id: {pawn.thingIDNumber})" : data.Name); parts.Add($"{data.Age}yo"); parts.Add(data.GenderLabel); parts.Add(data.RaceLabel); @@ -100,7 +100,10 @@ public string ExtractColonyStatus(Pawn pawn) if (pawn == null) return ""; var data = PawnDataExtractor.Extract(pawn, _logSink); if (!data.HasMap) return ""; - return Tr("RimMind.Prompt.Colony.Status", data.ColonistCount, $"{data.ColonyWealth:F0}", data.ThreatCount); + string status = Tr("RimMind.Prompt.Colony.Status", data.ColonistCount, $"{data.ColonyWealth:F0}", data.ThreatCount); + if (!string.IsNullOrEmpty(data.ThreatSummary)) + status += " " + Tr("RimMind.Prompt.Colony.ActiveThreats", data.ThreatSummary); + return status; } public string ExtractHealth(Pawn pawn) diff --git a/Source/Presentation/Agent/PawnDataExtractor.cs b/Source/Presentation/Agent/PawnDataExtractor.cs index a0cbd57..f1c8a58 100644 --- a/Source/Presentation/Agent/PawnDataExtractor.cs +++ b/Source/Presentation/Agent/PawnDataExtractor.cs @@ -106,7 +106,7 @@ public static PawnExtractedData Extract(Pawn pawn, ILogSink? logSink) { string n = other.Name?.ToStringShort ?? other.LabelShort ?? ""; if (!string.IsNullOrEmpty(n)) - nearby.Add(n); + nearby.Add(other.thingIDNumber > 0 ? $"{n} (pawn_id: {other.thingIDNumber})" : n); } } if (nearby.Count > 0) @@ -138,6 +138,18 @@ public static PawnExtractedData Extract(Pawn pawn, ILogSink? logSink) } catch { result.ColonyWealth = 0f; } result.ThreatCount = 0; + try + { + // Active hostiles near the colony (raiders, manhunters, mad animals). Main thread only: + // mapPawns is not safe to enumerate from the background context builder. + if (pawn.Map != null && UnityData.IsInMainThread) + { + var threats = ThreatScanner.FindNearbyThreats(pawn, 200f); + result.ThreatCount = threats.Count; + result.ThreatSummary = ThreatScanner.Describe(pawn, threats); + } + } + catch (System.Exception ex) { logSink?.Warning($"PawnDataExtractor: threat scan failed for {pawn.Name}: {ex.Message}"); } result.Hediffs = new List(); result.InMentalState = pawn.MentalStateDef != null; result.MentalStateInspectLine = pawn.MentalStateDef != null ? (pawn.MentalStateDef.label ?? pawn.MentalStateDef.defName) : ""; diff --git a/Source/Presentation/Agent/PawnPerceiver.cs b/Source/Presentation/Agent/PawnPerceiver.cs index 3218b48..17936aa 100644 --- a/Source/Presentation/Agent/PawnPerceiver.cs +++ b/Source/Presentation/Agent/PawnPerceiver.cs @@ -162,6 +162,18 @@ private void SenseInline() } } + var nearbyThreats = ThreatScanner.FindNearbyThreats(pawn); + if (nearbyThreats.Count > 0) + { + _agent.PerceptionBuffer.Add(new PerceptionBufferEntry + { + PerceptionType = "combat", + Content = $"DANGER: hostile nearby - {ThreatScanner.Describe(pawn, nearbyThreats)}. Draft to fight (pawn.draft), flee indoors, or keep away.", + Importance = CombatImportance, + Tick = Find.TickManager.TicksGame + }); + } + if (pawn.Drafted) { _agent.PerceptionBuffer.Add(new PerceptionBufferEntry diff --git a/Source/Presentation/Agent/PawnThinker.cs b/Source/Presentation/Agent/PawnThinker.cs index efbf06c..9aa7241 100644 --- a/Source/Presentation/Agent/PawnThinker.cs +++ b/Source/Presentation/Agent/PawnThinker.cs @@ -17,11 +17,14 @@ using RimMind.Application.Features.Agent; using RimMind.Application.Features.Agent.InnerVoice; using ThinkContextEnricher = RimMind.Application.Features.Agent.ThinkContextEnricher; +using RimMind.Domain.Agent.Policies; using RimMind.Domain.Common; using RimMind.Domain.Enums; using RimMind.Domain.Llm; using RimMind.Domain.ValueObjects; using RimMind.Presentation.Api; +using RimMind.Presentation.Runtime; +using RimMind.Presentation.Runtime.Services; using Verse; namespace RimMind.Presentation.Agent @@ -53,6 +56,8 @@ public class PawnThinker : IPawnThinker private IReadOnlyList? _pendingAvailableTools; private int _pendingToolCallRound; private string? _pendingTraceId; + private string? _activeRolloutId; + private string? _activeTraceId; private ICompletionFence? _pendingCompletionFence; private CancellationToken _pendingGenerationToken; @@ -94,7 +99,8 @@ internal PawnThinker( phase => agent.TransitionWorkflow(phase), decision => agent.ExecuteDecision(decision), () => agent.Pawn?.thingIDNumber ?? -1, log, - loopService: new AgenticLoopService(tickSettings.MaxToolCallDepth)); + loopService: new AgenticLoopService(tickSettings.MaxToolCallDepth), + recordTraceOutcome: RecordTraceOutcome); } public bool IsThinking => _thinking; @@ -115,6 +121,8 @@ public void ResetThinking() _requestSentUtc = default; _cachedPerceptions = Array.Empty(); _pendingTraceId = null; + _activeRolloutId = null; + _activeTraceId = null; _pendingCompletionFence = null; _pendingGenerationToken = default; } @@ -122,7 +130,12 @@ public void ResetThinking() public void Tick() { if (_agent.State != AgentState.Active) return; - if (_hasPendingCallback) { _hasPendingCallback = false; ProcessPendingCallback(); } + if (_hasPendingCallback) + { + _hasPendingCallback = false; + ProcessPendingCallback(); + return; + } if (_thinking && _requestSentUtc != default) { var elapsedSec = (DateTime.UtcNow - _requestSentUtc).TotalSeconds; @@ -130,7 +143,12 @@ public void Tick() { _log?.Warning($"[RimMind.Thinker] action=ThinkTimeout npcId={_agent.Identity.NpcId} modeId={_agent.CurrentModeId.Value} elapsedSec={elapsedSec:F1}"); _thinking = false; _requestSentTick = 0; _requestSentUtc = default; + _lastThinkTick = Find.TickManager.TicksGame; _cachedPerceptions = Array.Empty(); + _activeRolloutId = null; + _activeTraceId = null; + _agent.TransitionWorkflow(AgentWorkflowPhase.Idle); + return; } } if (_thinking) return; @@ -145,12 +163,15 @@ private void Think() try { var pawn = _agent.Pawn; - if (pawn == null || pawn.Dead) { _thinking = false; return; } + if (pawn == null || pawn.Dead) { _thinking = false; _agent.TransitionWorkflow(AgentWorkflowPhase.Idle); return; } + // Pawn liveness policy: a downed or mentally broken pawn cannot act on any decision, + // so do not spend an LLM request on it (avoids fake "success" actions while incapacitated). + if (IsIncapacitated(pawn)) { _thinking = false; _agent.TransitionWorkflow(AgentWorkflowPhase.Idle); return; } RimMindPawnLookup.CachePawn(pawn); var entries = _agent.PerceptionBuffer.Flush(); _cachedPerceptions = entries; var mode = _agent.CurrentMode; - if (!mode.ShouldThink(_agent, entries)) { _thinking = false; return; } + if (!mode.ShouldThink(_agent, entries)) { _thinking = false; _agent.TransitionWorkflow(AgentWorkflowPhase.Idle); return; } var pawnId = pawn.thingIDNumber; var voiceText = _contextEnricher.ConsumeInnerVoice(_agent.Identity.NpcId); _contextEnricher.CheckPsychology(_agent, pawnId); @@ -158,7 +179,11 @@ private void Think() var strategy = mode.GetThinkStrategy(); var allowedToolIds = mode.AllowedToolIds(RimMindAPI.Tools); var availableTools = RimMindAPI.Tools.GetAllDefinitions() - .Where(d => allowedToolIds.Contains(d.Id)).ToList(); + .Where(d => allowedToolIds.Contains(d.Id)) + .Where(d => !IsToolDisabledForPawn(pawn, d)) + .ToList(); + _activeTraceId = Guid.NewGuid().ToString("N"); + _activeRolloutId = $"rollout-{_agent.Identity.NpcId}-{Find.TickManager?.TicksGame ?? 0}-{Guid.NewGuid().ToString("N").Substring(0, 6)}"; var envelope = strategy.BuildEnvelope(_agent, entries, availableTools); EnrichEnvelope(envelope, voiceText); _requestSentTick = Find.TickManager.TicksGame; @@ -168,6 +193,9 @@ private void Think() catch (Exception ex) { _thinking = false; + _activeRolloutId = null; + _activeTraceId = null; + _agent.TransitionWorkflow(AgentWorkflowPhase.Idle); _log?.Error($"[RimMind.Thinker] action=UnexpectedError npcId={_agent.Identity.NpcId} modeId={_agent.CurrentModeId.Value} error={ex}"); } } @@ -192,12 +220,20 @@ private void SendThinkRequest(LlmRequestEnvelope envelope, IThinkStrategy strate if (_completionFence.CancellationToken.IsCancellationRequested) { ResetThinkingState(); return; } + var trackedEnvelope = envelope.WithTraceAndHints( + _activeTraceId ?? envelope.TraceId, + new Dictionary + { + ["rollout_id"] = _activeRolloutId ?? string.Empty, + ["turn_index"] = toolCallRound.ToString() + }); + _pendingStrategy = strategy; _pendingAvailableTools = availableTools; _pendingToolCallRound = toolCallRound; - _pendingTraceId = envelope.TraceId; + _pendingTraceId = trackedEnvelope.TraceId; var modeId = _agent.CurrentModeId; - RimMindAPI.Request.Send(envelope, (result, ctx) => + RimMindAPI.Request.Send(trackedEnvelope, (result, ctx) => { if (!_completionFence.TryAcceptCompletion()) return; _pendingResult = result; @@ -224,6 +260,14 @@ private void ProcessPendingCallback() var traceScope = _pendingTraceId != null ? TraceContext.BeginScope(_pendingTraceId) : null; try { + var actor = _agent.Pawn; + if (actor != null && (actor.Dead || IsIncapacitated(actor))) + { + // The pawn went down (or died / broke) while the request was in flight: drop the decision. + _log?.Message($"[RimMind.Thinker] action=DecisionDroppedIncapacitated npcId={_agent.Identity.NpcId}"); + ResetThinkingState(); + return; + } _decisionProcessor.ProcessResult(_pendingResult, _pendingContext, _pendingStrategy!, _pendingAvailableTools!, _pendingToolCallRound); } catch (Exception ex) @@ -257,7 +301,35 @@ private void RequestFollowUpThink() private void ResetThinkingState() { _thinking = false; + _lastThinkTick = _tickProvider.TicksGame; _cachedPerceptions = Array.Empty(); + _activeRolloutId = null; + _activeTraceId = null; + if (_agent.WorkflowPhase == AgentWorkflowPhase.Thinking) + _agent.TransitionWorkflow(AgentWorkflowPhase.Idle); + } + + private static bool IsToolDisabledForPawn(Verse.Pawn pawn, ToolDefinition def) + { + if (def?.Manifest?.DefaultDomain is AutonomyDomain domain) + return RimMindAPI.Autonomy.IsDisabled(pawn, domain); + if (!string.IsNullOrWhiteSpace(def?.Manifest?.AutonomyDomainId) + && Enum.TryParse(def!.Manifest.AutonomyDomainId, ignoreCase: true, out var parsed)) + return RimMindAPI.Autonomy.IsDisabled(pawn, parsed); + return false; + } + + private static void RecordTraceOutcome( + string requestId, + string actionIntent, + bool succeeded, + string? detail, + string? paramPreview) + { + if (string.IsNullOrWhiteSpace(requestId)) + return; + RuntimeServiceHub.Shared.Capture().GetOptional()? + .RecordActionOutcome(requestId, actionIntent, succeeded, detail, paramPreview); } private static IExtensionRegistry? TryGetThinkContributorRegistry() @@ -272,6 +344,8 @@ private void ResetThinkingState() } } + private static bool IsIncapacitated(Verse.Pawn pawn) => pawn.Downed || pawn.InMentalState; + public void ForceThink() => _lastThinkTick = 0; internal void RestoreLastThinkTick(int tick) => _lastThinkTick = tick; diff --git a/Source/Presentation/Agent/Perception/CombatPerceptionSource.cs b/Source/Presentation/Agent/Perception/CombatPerceptionSource.cs index 7e7e366..5f5f44f 100644 --- a/Source/Presentation/Agent/Perception/CombatPerceptionSource.cs +++ b/Source/Presentation/Agent/Perception/CombatPerceptionSource.cs @@ -24,6 +24,20 @@ public IReadOnlyList Sense(IAgentInfo agent) if (agent is IPawnAgentVerse pawnAgent) { var pawn = pawnAgent.Pawn; + if (pawn != null && !pawn.Dead) + { + var threats = ThreatScanner.FindNearbyThreats(pawn); + if (threats.Count > 0) + { + entries.Add(new PerceptionBufferEntry + { + PerceptionType = "combat", + Content = $"DANGER: hostile nearby - {ThreatScanner.Describe(pawn, threats)}. Draft to fight (pawn.draft), flee indoors, or keep away.", + Importance = RimMindDefaults.PerceptionCriticalThreshold, + Tick = Find.TickManager.TicksGame + }); + } + } if (pawn?.Drafted == true) { entries.Add(new PerceptionBufferEntry diff --git a/Source/Presentation/Agent/ThreatScanner.cs b/Source/Presentation/Agent/ThreatScanner.cs new file mode 100644 index 0000000..c04e57a --- /dev/null +++ b/Source/Presentation/Agent/ThreatScanner.cs @@ -0,0 +1,49 @@ +using System.Collections.Generic; +using System.Linq; +using RimWorld; +using Verse; + +namespace RimMind.Presentation.Agent +{ + /// + /// Shared scan for active hostiles near a pawn (raiders, manhunters, mad/berserk creatures). + /// Main thread only: enumerates mapPawns. + /// + public static class ThreatScanner + { + public const float DefaultRadius = 45f; + + public static List FindNearbyThreats(Pawn pawn, float radius = DefaultRadius) + { + var result = new List(); + var map = pawn?.Map; + if (pawn == null || map?.mapPawns == null || !UnityData.IsInMainThread) return result; + + float radiusSq = radius * radius; + foreach (var p in map.mapPawns.AllPawnsSpawned) + { + if (p == null || p == pawn || p.Dead || p.Downed) continue; + if (p.Position.Fogged(map)) continue; + if (!(p.InAggroMentalState || (p.Faction != null && p.HostileTo(Faction.OfPlayer)))) continue; + if (p.Position.DistanceToSquared(pawn.Position) > radiusSq) continue; + result.Add(p); + } + result.Sort((a, b) => a.Position.DistanceToSquared(pawn.Position).CompareTo(b.Position.DistanceToSquared(pawn.Position))); + return result; + } + + /// Compact description, e.g. "manhunter dromedary (12 tiles), raider x3 (40 tiles)". + public static string Describe(Pawn pawn, IReadOnlyList threats, int maxGroups = 4) + { + if (pawn == null || threats == null || threats.Count == 0) return string.Empty; + return string.Join(", ", threats + .GroupBy(p => ((p.InAggroMentalState ? (p.MentalStateDef?.label ?? string.Empty) + " " : string.Empty) + p.KindLabel).Trim()) + .Take(maxGroups) + .Select(g => + { + int dist = (int)g.Min(p => p.Position.DistanceTo(pawn.Position)); + return g.Count() > 1 ? $"{g.Key} x{g.Count()} ({dist} tiles)" : $"{g.Key} ({dist} tiles)"; + })); + } + } +} diff --git a/Source/Presentation/Runtime/RimMindCompositionRoot.cs b/Source/Presentation/Runtime/RimMindCompositionRoot.cs index 5bc2dee..7ab2cf3 100644 --- a/Source/Presentation/Runtime/RimMindCompositionRoot.cs +++ b/Source/Presentation/Runtime/RimMindCompositionRoot.cs @@ -147,6 +147,8 @@ public RuntimeComposition Compose( var infraBag = Infrastructure.DependencyInjection.AddInfrastructureServices( appBag.ToolRegistry, appBag.JsonExtractor, resolvedSettings); SettingsComposition.ComposeInfrastructureServices(services, infraBag); + Infrastructure.Mechanisms.MechanismToolHandler.PawnExistsPredicate = + id => Api.RimMindPawnLookup.FindPawnByNumber(id) != null; var logSink = infraBag.LogSink; var tickProvider = infraBag.TickProvider; diff --git a/Source/Presentation/Settings/RimMindCoreSettings.cs b/Source/Presentation/Settings/RimMindCoreSettings.cs index ba179c7..1b6c36c 100644 --- a/Source/Presentation/Settings/RimMindCoreSettings.cs +++ b/Source/Presentation/Settings/RimMindCoreSettings.cs @@ -14,7 +14,7 @@ namespace RimMind.Presentation.Settings public class RimMindCoreSettings : ModSettings, IOpenAISettings { public const string DefaultApiEndpoint = "https://api.deepseek.com/v1"; - public const string DefaultModelName = "deepseek-v4-flash"; + public const string DefaultModelName = "deepseek-flash"; public string? SavedModVersion; diff --git a/Source/Presentation/UI/ApiTabDrawer.cs b/Source/Presentation/UI/ApiTabDrawer.cs index e0bcf42..4381c2e 100644 --- a/Source/Presentation/UI/ApiTabDrawer.cs +++ b/Source/Presentation/UI/ApiTabDrawer.cs @@ -277,7 +277,7 @@ private static void OpenProviderSelectionMenu( // 2. DeepSeek (标准 OpenAI 兼容端点) options.Add(new FloatMenuOption(UiText.Get("RimMind.Settings.Provider.DeepSeek"), () => { - ApplyProviderPreset(s, "openai", "https://api.deepseek.com/v1", "deepseek-chat", "DeepSeek"); + ApplyProviderPreset(s, "openai", "https://api.deepseek.com/v1", "deepseek-flash", "DeepSeek"); })); // 3. Player2 (本地/云端) @@ -638,7 +638,7 @@ private static void DrawBackupEndpointsSection(Listing_Standard listing, ISettin name = $"Backup #{list.Count + 1}", provider = "openai", apiEndpoint = "https://api.deepseek.com/v1", - modelName = "deepseek-chat", + modelName = "deepseek-flash", apiKey = string.Empty, enabled = true }); diff --git a/Tests/Contracts/AgentAutonomyPolicyContracts.cs b/Tests/Contracts/AgentAutonomyPolicyContracts.cs index b1b3b50..2a7a854 100644 --- a/Tests/Contracts/AgentAutonomyPolicyContracts.cs +++ b/Tests/Contracts/AgentAutonomyPolicyContracts.cs @@ -23,10 +23,34 @@ public void AgentAutonomyPolicy_defaults_and_custom_levels_behave_correctly() Assert.Equal(AutonomyLevel.RequireApproval, policy.GetLevel(AutonomyDomain.WorktableBills)); Assert.Equal(AutonomyLevel.RequireApproval, policy.GetLevel(AutonomyDomain.BlueprintPlacement)); Assert.Equal(AutonomyLevel.RequireApproval, policy.GetLevel(AutonomyDomain.HighRiskOperations)); + Assert.Equal(AutonomyLevel.Disabled, policy.GetLevel(AutonomyDomain.WorkPriorityModification)); Assert.True(policy.CanExecuteAutonomous(AutonomyDomain.EmergencySurvival)); Assert.True(policy.RequiresApproval(AutonomyDomain.BlueprintPlacement)); Assert.False(policy.IsDisabled(AutonomyDomain.WorktableBills)); + Assert.True(policy.IsDisabled(AutonomyDomain.WorkPriorityModification)); + }), + ("work-only and full-auto presets plus CopyFrom apply cleanly", () => + { + var policy = AgentAutonomyPolicy.CreateDefault(); + policy.ApplyWorkOnlyNoBlueprintsPreset(); + + Assert.Equal(AutonomyLevel.FullAutonomous, policy.GetLevel(AutonomyDomain.EmergencySurvival)); + Assert.Equal(AutonomyLevel.FullAutonomous, policy.GetLevel(AutonomyDomain.ResourceMarking)); + Assert.Equal(AutonomyLevel.FullAutonomous, policy.GetLevel(AutonomyDomain.WorktableBills)); + Assert.Equal(AutonomyLevel.Disabled, policy.GetLevel(AutonomyDomain.BlueprintPlacement)); + Assert.Equal(AutonomyLevel.RequireApproval, policy.GetLevel(AutonomyDomain.HighRiskOperations)); + Assert.Equal(AutonomyLevel.Disabled, policy.GetLevel(AutonomyDomain.WorkPriorityModification)); + + var peer = AgentAutonomyPolicy.CreateDefault(); + peer.ApplyFullAutonomousPreset(); + Assert.Equal(AutonomyLevel.FullAutonomous, peer.GetLevel(AutonomyDomain.BlueprintPlacement)); + Assert.Equal(AutonomyLevel.FullAutonomous, peer.GetLevel(AutonomyDomain.WorkPriorityModification)); + Assert.Equal(AutonomyLevel.RequireApproval, peer.GetLevel(AutonomyDomain.HighRiskOperations)); + + peer.CopyFrom(policy); + Assert.Equal(AutonomyLevel.Disabled, peer.GetLevel(AutonomyDomain.BlueprintPlacement)); + Assert.Equal(AutonomyLevel.Disabled, peer.GetLevel(AutonomyDomain.WorkPriorityModification)); }), ("custom level overrides take effect immediately and clone works independently", () => { diff --git a/Tests/Contracts/AgentDecisionParamAdaptationContracts.cs b/Tests/Contracts/AgentDecisionParamAdaptationContracts.cs new file mode 100644 index 0000000..520a583 --- /dev/null +++ b/Tests/Contracts/AgentDecisionParamAdaptationContracts.cs @@ -0,0 +1,97 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Newtonsoft.Json.Linq; +using RimMind.Application.Common.Interfaces.Tools; +using RimMind.Application.Common.Models.Tools; +using RimMind.Application.Features.Registry; +using RimMind.Application.Features.Tools; +using RimMind.Domain.Agent.Modes; +using RimMind.Domain.ValueObjects; +using RimMind.Infrastructure.Agent; +using RimMind.Infrastructure.Mechanisms; +using Xunit; + +namespace RimMind.Tests.Contracts +{ + /// + /// Regression: LLM decisions with plain-text Param (e.g. "param":"Construction") were silently + /// replaced with {} so pawn.work.set failed with "Invalid def name ''". + /// + public sealed class AgentDecisionParamAdaptationContracts + { + [Fact] + public void PlainTextParam_IsForwardedAsWorkTarget_ForWorkSetTool() + { + var tools = new ToolRegistry(); + var workTool = new RecordingToolHandler("pawn.work.set"); + tools.Register(workTool); + var executor = new MechanismActionExecutor(new GameMechanismRegistry(), tools, () => Array.Empty()); + + var result = executor.ExecuteDecision( + new AgentDecision(ActionIntent: "pawn.work.set", Reason: "build shelter", Param: "Construction"), + pawnId: 42); + + Assert.True(result.IsOk); + var args = JObject.Parse(workTool.LastArgumentsJson!); + Assert.Equal("Construction", args.Value("def_name")); + Assert.Equal("Construction", args.Value("work_type")); + Assert.Equal(1, args.Value("priority")); + Assert.Equal(42, args.Value("pawn_id")); + } + + [Fact] + public void PlainTextParam_DoesNotForceAssignWork_ForJobSetTool() + { + var tools = new ToolRegistry(); + var jobTool = new RecordingToolHandler("pawn.job.set"); + tools.Register(jobTool); + var executor = new MechanismActionExecutor(new GameMechanismRegistry(), tools, () => Array.Empty()); + + var result = executor.ExecuteDecision( + new AgentDecision(ActionIntent: "pawn.job.set", Reason: "starving", Param: "eat a meal"), + pawnId: 7); + + Assert.True(result.IsOk); + var args = JObject.Parse(jobTool.LastArgumentsJson!); + Assert.Equal("eat_food", args.Value("action")); + Assert.Null(args["def_name"]); + } + + [Fact] + public void ArgumentlessJobSet_IsNotSilentlyTurnedIntoForceRest() + { + // Live playthrough: 65 argument-less pawn_job_set calls became force_rest and kept + // colonists lying down instead of eating, tending or working. + var tools = new ToolRegistry(); + var jobTool = new RecordingToolHandler("pawn_job_set"); + tools.Register(jobTool); + var executor = new MechanismActionExecutor(new GameMechanismRegistry(), tools, () => Array.Empty()); + + executor.ExecuteDecision(new AgentDecision(ActionIntent: "pawn_job_set", Reason: "", Param: "{}"), pawnId: 5); + + var args = JObject.Parse(jobTool.LastArgumentsJson!); + Assert.NotEqual("force_rest", args.Value("action")); + } + + private sealed class RecordingToolHandler : IToolHandler + { + public RecordingToolHandler(string id) + { + Id = id; + Definition = new ToolDefinition { Id = id, Description = id, ParametersSchema = "{}" }; + } + + public string Id { get; } + public string OwnerModId => "test"; + public ToolDefinition Definition { get; } + public string? LastArgumentsJson { get; private set; } + + public Task> ExecuteAsync(ToolCallArgs args, CancellationToken ct) + { + LastArgumentsJson = args.ArgumentsJson; + return Task.FromResult(Result.Ok(new ToolResult { ToolCallId = args.ToolCallId, Content = "ok" })); + } + } + } +} diff --git a/Tests/Contracts/AgentRolloutAndTraceFormattingContracts.cs b/Tests/Contracts/AgentRolloutAndTraceFormattingContracts.cs new file mode 100644 index 0000000..431a878 --- /dev/null +++ b/Tests/Contracts/AgentRolloutAndTraceFormattingContracts.cs @@ -0,0 +1,237 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using RimMind.Application.Common.Interfaces.Tools; +using RimMind.Application.Common.Models.Agent; +using RimMind.Application.Common.Models.Debug; +using RimMind.Application.Common.Models.Tools; +using RimMind.Application.Features.Tools; +using RimMind.Domain.Agent.Policies; +using RimMind.Domain.Enums; +using RimMind.Domain.ValueObjects; +using RimMind.Infrastructure.UI.DebugCenter; +using RimMind.Infrastructure.UI.DebugTables; +using RimMind.Infrastructure.Verse; +using RimMind.Testing; +using Xunit; + +namespace RimMind.Tests.Contracts +{ + public sealed class AgentRolloutAndTraceFormattingContracts + { + [Fact] + public void DebugCenterNavigation_resolves_consolidated_5_tab_routes_and_legacy_aliases() + { + ContractCaseRunner.Run( + ("legacy capability routes resolve into capabilities sub-tabs", () => + { + DebugCenterNavigation.ResolveRoute("tool_calls", out string p1, out string? s1); + Assert.Equal("capabilities", p1); + Assert.Equal("tool_calls", s1); + + DebugCenterNavigation.ResolveRoute("mechanisms", out string p2, out string? s2); + Assert.Equal("capabilities", p2); + Assert.Equal("mechanisms", s2); + + DebugCenterNavigation.ResolveRoute("context_keys", out string p3, out string? s3); + Assert.Equal("capabilities", p3); + Assert.Equal("context_keys", s3); + }), + ("legacy trace and explicit colon routes resolve into ai_requests or target sub-tabs", () => + { + DebugCenterNavigation.ResolveRoute("rollouts", out string p1, out string? s1); + Assert.Equal("ai_requests", p1); + Assert.Equal("rollout", s1); + + DebugCenterNavigation.ResolveRoute("ephemeral_requests", out string p2, out string? s2); + Assert.Equal("ai_requests", p2); + Assert.Equal("ephemeral", s2); + + DebugCenterNavigation.ResolveRoute("capabilities:mechanisms", out string p3, out string? s3); + Assert.Equal("capabilities", p3); + Assert.Equal("mechanisms", s3); + + var nav = new DebugCenterNavigation(); + nav.GoTo("mechanisms"); + Assert.Equal("capabilities", nav.ConsumeRequestedPageId()); + Assert.Equal("mechanisms", nav.ConsumeRequestedSubTabId()); + }) + ); + } + + [Fact] + public void AIRequestTraceLog_tracks_layer_prefix_reuse_and_deferred_action_outcomes() + { + ContractCaseRunner.Run( + ("consecutive turns for same agent mark matching L0-L2 system layers as prefix-reused and L4 user layer as uncached", () => + { + var log = new AIRequestTraceLog(); + + log.StartRequest("req-1", "Decision", "deepseek-chat", "sys", "turn1-user", ""); + log.UpdateRequestMetadata("req-1", "trace-1", "rollout-1", 0, "RimMind.Agent", "Decision", "Pawn_42", isAgentRollout: true); + log.UpdateRequestLayers("req-1", new[] + { + new AIRequestLayerTrace("system", "L0", "System Rules v1", 15, IsPrefixReused: false), + new AIRequestLayerTrace("system", "L1", "Static Identity Alice", 21, IsPrefixReused: false), + new AIRequestLayerTrace("system", "L2", "Tools Schema", 12, IsPrefixReused: false), + new AIRequestLayerTrace("user", "L4", "Perception Frame 1", 18, IsPrefixReused: false) + }); + log.CompleteRequestDetailed("req-1", "need tool", "reasoning turn 1", 120, 90, 30, 0, 200); + + log.StartRequest("req-2", "Decision", "deepseek-chat", "sys", "turn2-user", ""); + log.UpdateRequestMetadata("req-2", "trace-1", "rollout-1", 1, "RimMind.Agent", "Decision", "Pawn_42", isAgentRollout: true); + log.UpdateRequestLayers("req-2", new[] + { + new AIRequestLayerTrace("system", "L0", "System Rules v1", 15, IsPrefixReused: false), + new AIRequestLayerTrace("system", "L1", "Static Identity Alice", 21, IsPrefixReused: false), + new AIRequestLayerTrace("system", "L2", "Tools Schema", 12, IsPrefixReused: false), + new AIRequestLayerTrace("user", "L4", "Perception Frame 2 + tool_results", 33, IsPrefixReused: false) + }); + log.AddToolCallDetailed("req-2", "tc-decision", "Decision", succeeded: true, error: null, "{\"action\":\"assign_work\"}", null); + log.RecordActionOutcome("req-2", "assign_work", succeeded: false, detail: "Target unreachable", paramPreview: "Construction"); + + var entries = log.Entries; + Assert.Equal(2, entries.Count); + + var turn2 = entries[1]; + Assert.Equal(4, turn2.Layers.Count); + Assert.True(turn2.Layers[0].IsPrefixReused); + Assert.True(turn2.Layers[1].IsPrefixReused); + Assert.True(turn2.Layers[2].IsPrefixReused); + Assert.False(turn2.Layers[3].IsPrefixReused); + + Assert.NotNull(turn2.ActionOutcome); + Assert.False(turn2.ActionOutcome!.Succeeded); + Assert.Equal("Target unreachable", turn2.ActionOutcome.Detail); + Assert.Single(turn2.ToolCalls); + Assert.False(turn2.ToolCalls[0].Succeeded); + Assert.Equal("Target unreachable", turn2.ToolCalls[0].Error); + }) + ); + } + + [Fact] + public void AgentRolloutModelBuilder_separates_rollouts_from_ephemeral_and_applies_filters() + { + ContractCaseRunner.Run( + ("groups multi-turn rollout trajectories separately from ephemeral one-off requests and filters accurately", () => + { + var log = new AIRequestTraceLog(); + + log.StartRequest("r1-t0", "Decision", "deepseek-reasoner", "sys", "perc0", ""); + log.UpdateRequestMetadata("r1-t0", "tr1", "roll-A", 0, "RimMind.Agent", "Decision", "Pawn_7", isAgentRollout: true); + log.UpdateRequestLayers("r1-t0", new[] + { + new AIRequestLayerTrace("system", "L0", "Rules", 5, IsPrefixReused: false), + new AIRequestLayerTrace("user", "L4", "Frame0", 6, IsPrefixReused: false) + }); + log.CompleteRequestDetailed("r1-t0", "{\"query\":\"food\"}", "think0", 100, 80, 20, 0, 150); + + log.StartRequest("r1-t1", "Decision", "deepseek-reasoner", "sys", "perc1", ""); + log.UpdateRequestMetadata("r1-t1", "tr1", "roll-A", 1, "RimMind.Agent", "Decision", "Pawn_7", isAgentRollout: true); + log.UpdateRequestLayers("r1-t1", new[] + { + new AIRequestLayerTrace("system", "L0", "Rules", 5, IsPrefixReused: false), + new AIRequestLayerTrace("user", "L4", "Frame1", 6, IsPrefixReused: false) + }); + log.CompleteRequestDetailed("r1-t1", "{\"action\":\"eat_food\"}", "think1", 90, 70, 20, 50, 110); + log.RecordActionOutcome("r1-t1", "eat_food", succeeded: true, detail: "Eating meal", paramPreview: "SimpleMeal"); + + log.StartRequest("ephem-1", "Dialogue", "gpt-4o-mini", "sys", "greet player", ""); + log.UpdateRequestMetadata("ephem-1", "tr2", "", 0, "RimMind.Dialogue", "Chitchat", "Pawn_8", isAgentRollout: false); + log.CompleteRequest("ephem-1", "Hello friend!", 40, 80); + + log.StartRequest("ephem-2", "Personality", "gpt-4o-mini", "sys", "mood shift", ""); + log.UpdateRequestMetadata("ephem-2", "tr3", "", 0, "RimMind.Personality", "Eval", "Pawn_7", isAgentRollout: false); + log.FailRequest("ephem-2", "timeout", 5000); + + var all = log.Entries; + IReadOnlyList rollouts = AgentRolloutModelBuilder.BuildRollouts(all); + Assert.Single(rollouts); + Assert.Equal("roll-A", rollouts[0].RolloutId); + Assert.Equal(2, rollouts[0].TurnCount); + Assert.True(rollouts[0].PrefixReuseRatio > 0.0); + Assert.NotNull(rollouts[0].FinalOutcome); + Assert.True(rollouts[0].FinalOutcome!.Succeeded); + + IReadOnlyList ephemeralOnly = AgentRolloutModelBuilder.FilterEphemeral(all); + Assert.Equal(2, ephemeralOnly.Count); + Assert.DoesNotContain(ephemeralOnly, e => e.RolloutId == "roll-A"); + + IReadOnlyList filteredModFailed = AgentRolloutModelBuilder.FilterEphemeral( + all, + new EphemeralTraceFilter(ModId: "RimMind.Personality", State: AIRequestTraceState.Failed)); + Assert.Single(filteredModFailed); + Assert.Equal("ephem-2", filteredModFailed[0].RequestId); + + IReadOnlyList withRollouts = AgentRolloutModelBuilder.FilterEphemeral( + all, + new EphemeralTraceFilter(IncludeRolloutTurns: true, SearchQuery: "SimpleMeal")); + Assert.Single(withRollouts); + Assert.Equal("r1-t1", withRollouts[0].RequestId); + }) + ); + } + + [Fact] + public void TraceContentFormatter_and_ToolRegistryDebugTableModelBuilder_format_and_filter_cleanly() + { + ContractCaseRunner.Run( + ("formats compact JSON and XML-tagged agent replies and filters tool definitions cleanly", () => + { + string prettyJson = TraceContentFormatter.FormatStructuredText("{\"action\":\"place_blueprint\",\"def\":\"Bed\"}"); + Assert.Contains("\n", prettyJson); + Assert.Contains("\"action\": \"place_blueprint\"", prettyJson); + + string prettyXml = TraceContentFormatter.FormatStructuredText( + "build bed{\"def\":\"Bed\"}"); + Assert.Contains("\n", prettyXml); + + var registry = new ToolRegistry(); + registry.Register(new StubToolHandler("actions_place_blueprint", "Actions", AutonomyDomain.BlueprintPlacement)); + registry.Register(new StubToolHandler("pawn_job", "Mechanisms", AutonomyDomain.EmergencySurvival)); + + IReadOnlyList filtered = ToolRegistryDebugTableModelBuilder.FilterDefinitions( + registry.GetAllDefinitions(), + categoryFilter: "Actions", + searchQuery: "blueprint"); + Assert.Single(filtered); + Assert.Equal("actions_place_blueprint", filtered[0].Id); + + DebugTableModel table = ToolRegistryDebugTableModelBuilder.Build(registry, "Actions", "blueprint"); + Assert.Single(table.Rows); + }) + ); + } + + private sealed class StubToolHandler : IToolHandler + { + public StubToolHandler(string id, string category, AutonomyDomain domain) + { + Definition = new ToolDefinition + { + Id = id, + Category = category, + Description = $"{id} description", + ParametersSchema = "{\"type\":\"object\"}", + Manifest = new ToolManifest + { + OwnerModId = "RimMind.Test", + Kind = ToolKind.Mutation, + DefaultDomain = domain, + RiskLevel = RiskLevel.Medium, + DisplayName = id + } + }; + } + + public string Id => Definition.Id; + public string OwnerModId => Definition.Manifest.OwnerModId; + public ToolDefinition Definition { get; } + + public Task> ExecuteAsync(ToolCallArgs args, CancellationToken ct) + => Task.FromResult(Result.Ok(ToolResult.Ok("ok"))); + } + } +} diff --git a/Tests/Contracts/DomainApplicationContracts.cs b/Tests/Contracts/DomainApplicationContracts.cs index ea95b69..ca7ad93 100644 --- a/Tests/Contracts/DomainApplicationContracts.cs +++ b/Tests/Contracts/DomainApplicationContracts.cs @@ -386,6 +386,51 @@ public void Decision_response_parsing_degrades_to_dialogue() Assert.Equal("actions_query_buildable_structures", parsed.Value.ActionIntent); Assert.Equal("call_q1", parsed.Value.ToolCallId); Assert.True(parsed.Value.WantsMoreToolCalls); + }), + ("suffix _query and .query tools set WantsMoreToolCalls true", () => + { + Assert.True(ThinkStrategyHelper.IsQueryToolName("map_wealth_query")); + Assert.True(ThinkStrategyHelper.IsQueryToolName("pawn_draft_query")); + Assert.True(ThinkStrategyHelper.IsQueryToolName("pawn_health_query")); + Assert.True(ThinkStrategyHelper.IsQueryToolName("pawn.health.query")); + + var parsed = ThinkStrategyHelper.ParseDecisionCore(new LlmResponse + { + Content = "", + ToolCallsJson = "[{\"id\":\"call_q2\",\"function\":{\"name\":\"map_wealth_query\",\"arguments\":\"{}\"}}]" + }); + Assert.True(parsed.IsOk); + Assert.Equal("map_wealth_query", parsed.Value.ActionIntent); + Assert.True(parsed.Value.WantsMoreToolCalls); + }), + ("truncated JSON recovers intended action via JsonRepairer instead of falling back to dialogue.free", () => + { + var parsed = ThinkStrategyHelper.ParseDecisionCore(new LlmResponse + { + Content = "{\"action\":\"place_blueprint\",\"reason\":\"Building a wooden bed for colonist" + }); + Assert.True(parsed.IsOk); + Assert.Equal("place_blueprint", parsed.Value.ActionIntent); + Assert.Equal("Building a wooden bed for colonist", parsed.Value.Reason); + }), + ("raw JSON tool object and to= commentary are extracted as tool calls", () => + { + var rawJsonParsed = ThinkStrategyHelper.ParseDecisionCore(new LlmResponse + { + Content = "{\"name\": \"actions_eat_and_recreation\", \"parameters\": {\"reason\": \"Need food\"}}" + }); + Assert.True(rawJsonParsed.IsOk); + Assert.Equal("actions_eat_and_recreation", rawJsonParsed.Value.ActionIntent); + Assert.Equal("Need food", rawJsonParsed.Value.Reason); + Assert.Contains("\"reason\":\"Need food\"", rawJsonParsed.Value.Param, StringComparison.Ordinal); + + var toCommentaryParsed = ThinkStrategyHelper.ParseDecisionCore(new LlmResponse + { + Content = "Checking current work assignment to=pawn_job_query" + }); + Assert.True(toCommentaryParsed.IsOk); + Assert.Equal("pawn_job_query", toCommentaryParsed.Value.ActionIntent); + Assert.True(toCommentaryParsed.Value.WantsMoreToolCalls); })); } diff --git a/Tests/Contracts/EndpointInvariantAndAudioContracts.cs b/Tests/Contracts/EndpointInvariantAndAudioContracts.cs new file mode 100644 index 0000000..46c1af0 --- /dev/null +++ b/Tests/Contracts/EndpointInvariantAndAudioContracts.cs @@ -0,0 +1,382 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using RimMind.Application.Common.Interfaces.Abstractions; +using RimMind.Application.Common.Interfaces.Audio; +using RimMind.Application.Common.Interfaces.Client; +using RimMind.Application.Common.Interfaces.Internal; +using RimMind.Application.Common.Models.Client; +using RimMind.Application.Common.Models.Pipeline; +using RimMind.Application.Features.Llm; +using RimMind.Application.Features.Pipeline.Unified; +using RimMind.Application.Features.Registry; +using RimMind.Domain.Audio; +using RimMind.Domain.Common; +using RimMind.Domain.Llm; +using RimMind.Domain.ValueObjects; +using RimMind.Infrastructure.Services.Clients.OpenAI; +using RimMind.Testing; +using Xunit; + +namespace RimMind.Tests.Contracts +{ + public sealed class EndpointInvariantAndAudioContracts + { + private sealed class FakeOpenAISettings : IOpenAISettings + { + public string ApiEndpoint { get; set; } = "https://primary.example/v1"; + public string ApiKey { get; set; } = "test-primary-key"; + public string ModelName { get; set; } = "deepseek-flash"; + public int MaxTokens { get; set; } = 512; + public float DefaultTemperature { get; set; } = 0.7f; + public bool ForceJsonMode { get; set; } + public bool DebugLogging { get; set; } + public int RequestTimeoutSeconds { get; set; } = 30; + public IReadOnlyList? BackupEndpoints { get; set; } + public bool IsConfigured() => !string.IsNullOrWhiteSpace(ApiKey); + } + + private sealed class StubCircuitBreakerSettings : ICircuitBreakerSettings + { + public int CircuitBreakerFailureThreshold { get; } + public int CircuitBreakerOpenDurationSec { get; } + + public StubCircuitBreakerSettings(int threshold, int openDurationSec) + { + CircuitBreakerFailureThreshold = threshold; + CircuitBreakerOpenDurationSec = openDurationSec; + } + } + + private sealed class FakeSpeechSynthesizer : ISpeechSynthesizer + { + public string Id => "test_tts"; + public string OwnerModId => "RimMind.Tests"; + public string DisplayLabel => "Test TTS"; + public bool IsConfigured() => true; + + public Task> SynthesizeAsync(SpeechSynthesisRequest request) => + Task.FromResult(Result.Ok(new SpeechSynthesisResult + { + AudioBytes = new byte[] { 1, 2, 3, 4 }, + Format = request.PreferredFormat, + ProviderId = Id + })); + } + + private sealed class FakeSpeechRecognizer : ISpeechRecognizer + { + public string Id => "test_asr"; + public string OwnerModId => "RimMind.Tests"; + public string DisplayLabel => "Test ASR"; + public bool IsConfigured() => true; + + public Task> TranscribeAsync(SpeechRecognitionRequest request) => + Task.FromResult(Result.Ok(new SpeechRecognitionResult + { + RequestId = "req-asr-1", + Text = request.VocabularyHints ?? "transcribed", + DurationMs = 350, + ProviderId = Id + })); + } + + [Fact] + public void ReasoningEffort_is_preserved_across_builder_clone_and_trace_hints() + { + var defaultEnvelope = LlmRequestEnvelopeBuilder + .ForNpc("pawn-0") + .ForScenarioId("RimMind.Test") + .Build(); + Assert.Equal(ReasoningEffort.Auto, defaultEnvelope.ReasoningEffort); + + var built = LlmRequestEnvelopeBuilder + .ForNpc("pawn-1") + .ForScenarioId("RimMind.Dialogue") + .WithReasoningEffort(ReasoningEffort.None) + .Build(); + Assert.Equal(ReasoningEffort.None, built.ReasoningEffort); + + using var cts = new CancellationTokenSource(); + var cloned = built.Clone(cts.Token); + Assert.Equal(ReasoningEffort.None, cloned.ReasoningEffort); + Assert.Equal(cts.Token, cloned.Ct); + + var traced = LlmRequestEnvelopeBuilder + .ForNpc("pawn-2") + .ForScenarioId("RimMind.Test") + .WithReasoningEffort(ReasoningEffort.Max) + .Build() + .WithTraceAndHints("trace-99", new Dictionary { ["k"] = "v" }); + Assert.Equal(ReasoningEffort.Max, traced.ReasoningEffort); + Assert.Equal("trace-99", traced.TraceId); + } + + [Fact] + public async Task ContentFiltered_and_quota_errors_do_not_trip_circuit_breaker_or_retry() + { + await ContractCaseRunner.RunAsync( + ("CircuitBreaker ignores ContentFiltered across repeated requests", async () => + { + var cb = new CircuitBreakerMiddleware(new StubCircuitBreakerSettings(threshold: 2, openDurationSec: 30)); + for (int i = 0; i < 4; i++) + { + var ctx = new LlmRequestContext(new LlmRequestEnvelope + { + RequestId = $"req-mod-{i}", + ModId = "RimMind.Tests" + }); + await cb.InvokeAsync(ctx, c => + { + c.Result = Result.Err(RimMindErrors.ContentFiltered("Content Exists Risk")); + return Task.CompletedTask; + }); + Assert.Equal(0, cb.ConsecutiveFailuresCount); + Assert.Equal("Closed", cb.CurrentStateName); + } + }), + ("RetryMiddleware stops immediately on ContentFiltered and ClientQuotaOrAuthFailure", async () => + { + var retry = new RetryMiddleware(maxRetries: 3, delay: TimeSpan.FromMilliseconds(1)); + + int filteredCalls = 0; + var ctxFiltered = new LlmRequestContext(new LlmRequestEnvelope { RequestId = "r-cf", ModId = "Tests" }); + await retry.InvokeAsync(ctxFiltered, c => + { + filteredCalls++; + c.Result = Result.Err(RimMindErrors.ContentFiltered("blocked")); + return Task.CompletedTask; + }); + Assert.Equal(1, filteredCalls); + Assert.Equal(RimMindErrorCode.ContentFiltered, ctxFiltered.Result!.Value.Error.Code); + + int quotaCalls = 0; + var ctxQuota = new LlmRequestContext(new LlmRequestEnvelope { RequestId = "r-quota", ModId = "Tests" }); + await retry.InvokeAsync(ctxQuota, c => + { + quotaCalls++; + c.Result = Result.Err(RimMindErrors.ClientQuotaOrAuth("402 Insufficient Balance")); + return Task.CompletedTask; + }); + Assert.Equal(1, quotaCalls); + Assert.Equal(RimMindErrorCode.ClientQuotaOrAuthFailure, ctxQuota.Result!.Value.Error.Code); + + int transientCalls = 0; + var ctxTransient = new LlmRequestContext(new LlmRequestEnvelope { RequestId = "r-tr", ModId = "Tests" }); + await retry.InvokeAsync(ctxTransient, c => + { + transientCalls++; + c.Result = Result.Err(RimMindErrors.ClientTransient("503")); + return Task.CompletedTask; + }); + Assert.Equal(4, transientCalls); + })); + } + + [Fact] + public async Task OpenAIClient_content_moderation_returns_immediately_without_downgrade_or_failover() + { + await ContractCaseRunner.RunAsync( + ("HTTP 400 Content Exists Risk skips json_schema downgrade and backup failover", async () => + { + OpenAIClient.InvalidateFormatCache(); + int callCount = 0; + + var settings = new FakeOpenAISettings + { + BackupEndpoints = new[] + { + new BackupEndpointNode + { + Name = "Backup", + ApiEndpoint = "https://backup.example/v1", + ModelName = "gpt-4o-mini", + ApiKey = "backup-key", + Enabled = true + } + } + }; + + using var client = new OpenAIClient(settings, null, (url, body, auth, hn, hv, to, ct) => + { + callCount++; + return Task.FromResult(("{\"error\":{\"message\":\"Content Exists Risk\",\"type\":\"invalid_request_error\"}}", 400L)); + }); + + var env = new LlmRequestEnvelope + { + RequestId = "req-400-risk", + JsonSchema = "{\"type\":\"object\"}", + Messages = new List { new ChatMessage { Role = "user", Content = "hi" } } + }; + + var result = await client.SendAsync(env); + Assert.True(result.IsErr); + Assert.Equal(RimMindErrorCode.ContentFiltered, result.Error.Code); + Assert.Equal(1, callCount); + }), + ("HTTP 200 finish_reason=content_filter stops immediately without failing over to backup", async () => + { + OpenAIClient.InvalidateFormatCache(); + int callCount = 0; + + var settings = new FakeOpenAISettings + { + BackupEndpoints = new[] + { + new BackupEndpointNode + { + Name = "Backup", + ApiEndpoint = "https://backup.example/v1", + ModelName = "gpt-4o-mini", + ApiKey = "backup-key", + Enabled = true + } + } + }; + + using var client = new OpenAIClient(settings, null, (url, body, auth, hn, hv, to, ct) => + { + callCount++; + return Task.FromResult(("{\"id\":\"cmpl-1\",\"choices\":[{\"finish_reason\":\"content_filter\",\"message\":{\"role\":\"assistant\",\"content\":\"\"}}]}", 200L)); + }); + + var env = new LlmRequestEnvelope + { + RequestId = "req-200-cf", + Messages = new List { new ChatMessage { Role = "user", Content = "hi" } } + }; + + var result = await client.SendAsync(env); + Assert.True(result.IsErr); + Assert.Equal(RimMindErrorCode.ContentFiltered, result.Error.Code); + Assert.Equal(1, callCount); + })); + } + + [Fact] + public async Task OpenAIClient_fails_over_on_insufficient_system_resource_and_whitespace_trap_and_reads_prompt_cache_hit_tokens() + { + await ContractCaseRunner.RunAsync( + ("finish_reason=insufficient_system_resource fails over to backup and extracts prompt_cache_hit_tokens", async () => + { + OpenAIClient.InvalidateFormatCache(); + int callCount = 0; + + var settings = new FakeOpenAISettings + { + BackupEndpoints = new[] + { + new BackupEndpointNode + { + Name = "Backup", + ApiEndpoint = "https://backup.example/v1", + ModelName = "deepseek-flash", + ApiKey = "backup-key", + Enabled = true + } + } + }; + + using var client = new OpenAIClient(settings, null, (url, body, auth, hn, hv, to, ct) => + { + callCount++; + if (callCount == 1) + { + return Task.FromResult(("{\"id\":\"cmpl-1\",\"choices\":[{\"finish_reason\":\"insufficient_system_resource\",\"message\":{\"role\":\"assistant\",\"content\":\"\"}}]}", 200L)); + } + return Task.FromResult(("{\"id\":\"cmpl-2\",\"choices\":[{\"finish_reason\":\"stop\",\"message\":{\"role\":\"assistant\",\"content\":\"Recovered\"}}],\"usage\":{\"prompt_tokens\":100,\"completion_tokens\":10,\"total_tokens\":110,\"prompt_cache_hit_tokens\":80}}", 200L)); + }); + + var env = new LlmRequestEnvelope + { + RequestId = "req-isr", + Messages = new List { new ChatMessage { Role = "user", Content = "status" } } + }; + + var result = await client.SendAsync(env); + Assert.True(result.IsOk); + Assert.Equal(2, callCount); + Assert.Equal("Recovered", result.Value.Content); + Assert.Equal(80, result.Value.CachedTokens); + }), + ("whitespace-only content trap fails over to backup node", async () => + { + OpenAIClient.InvalidateFormatCache(); + int callCount = 0; + + var settings = new FakeOpenAISettings + { + BackupEndpoints = new[] + { + new BackupEndpointNode + { + Name = "Backup", + ApiEndpoint = "https://backup.example/v1", + ModelName = "deepseek-flash", + ApiKey = "backup-key", + Enabled = true + } + } + }; + + using var client = new OpenAIClient(settings, null, (url, body, auth, hn, hv, to, ct) => + { + callCount++; + if (callCount == 1) + { + return Task.FromResult(("{\"id\":\"cmpl-ws\",\"choices\":[{\"finish_reason\":\"stop\",\"message\":{\"role\":\"assistant\",\"content\":\" \"}}]}", 200L)); + } + return Task.FromResult(("{\"id\":\"cmpl-ok\",\"choices\":[{\"finish_reason\":\"stop\",\"message\":{\"role\":\"assistant\",\"content\":\"{\\\"ok\\\":true}\"}}],\"usage\":{\"total_tokens\":20}}", 200L)); + }); + + var env = new LlmRequestEnvelope + { + RequestId = "req-ws", + Messages = new List { new ChatMessage { Role = "user", Content = "json please" } } + }; + + var result = await client.SendAsync(env); + Assert.True(result.IsOk); + Assert.Equal(2, callCount); + Assert.Equal("{\"ok\":true}", result.Value.Content); + })); + } + + [Fact] + public async Task Speech_synthesizer_and_recognizer_extension_ports_register_and_execute() + { + var ttsRegistry = new ExtensionRegistry(); + var asrRegistry = new ExtensionRegistry(); + + ttsRegistry.Register(new FakeSpeechSynthesizer()); + asrRegistry.Register(new FakeSpeechRecognizer()); + + var tts = ttsRegistry.FindById("test_tts"); + var asr = asrRegistry.FindById("test_asr"); + Assert.NotNull(tts); + Assert.NotNull(asr); + Assert.True(tts!.IsConfigured()); + Assert.True(asr!.IsConfigured()); + + var synthResult = await tts.SynthesizeAsync(new SpeechSynthesisRequest + { + Text = "Colony alert!", + PreferredFormat = AudioContainerFormat.Mp3 + }); + Assert.True(synthResult.IsOk); + Assert.Equal(AudioContainerFormat.Mp3, synthResult.Value.Format); + Assert.Equal("test_tts", synthResult.Value.ProviderId); + + var recResult = await asr.TranscribeAsync(new SpeechRecognitionRequest + { + AudioBytes = new byte[] { 10, 20 }, + VocabularyHints = "Cassandra,RimMind" + }); + Assert.True(recResult.IsOk); + Assert.Equal("Cassandra,RimMind", recResult.Value.Text); + Assert.Equal("test_asr", recResult.Value.ProviderId); + } + } +} diff --git a/Tests/Contracts/P5UiAndHarnessContracts.cs b/Tests/Contracts/P5UiAndHarnessContracts.cs index 423e374..43ead07 100644 --- a/Tests/Contracts/P5UiAndHarnessContracts.cs +++ b/Tests/Contracts/P5UiAndHarnessContracts.cs @@ -26,11 +26,11 @@ public void DebugCenterPageRegistry_supports_custom_registration_ordering_owner_ DebugCenterPageRegistry.ResetToDefaults(); var defaults = DebugCenterPageRegistry.GetAll(); - Assert.Equal(7, defaults.Count); + Assert.Equal(5, defaults.Count); Assert.Equal("overview", DebugCenterPageRegistry.DefaultPageId); Assert.All(defaults, d => Assert.Equal(RimMindOwnerConsts.CoreModId, d.OwnerModId)); Assert.Equal( - new[] { "overview", "agents", "ai_requests", "tool_calls", "mechanisms", "context_keys", "settings" }, + new[] { "overview", "agents", "ai_requests", "capabilities", "settings" }, defaults.Select(d => d.Id).ToArray()); }), ("custom pages register in order, can be unregistered by OwnerModId, and ResetToDefaults restores built-ins", () => @@ -58,12 +58,12 @@ public void DebugCenterPageRegistry_supports_custom_registration_ordering_owner_ () => new ProbeDebugCenterPageDrawer("storyteller")); var allAfterRegister = DebugCenterPageRegistry.GetAll(); - Assert.Equal(9, allAfterRegister.Count); + Assert.Equal(7, allAfterRegister.Count); int aiRequestsIdx = allAfterRegister.Select((d, i) => (d.Id, i)).First(x => x.Id == "ai_requests").i; int advisorIdx = allAfterRegister.Select((d, i) => (d.Id, i)).First(x => x.Id == "advisor_diagnostics").i; - int toolCallsIdx = allAfterRegister.Select((d, i) => (d.Id, i)).First(x => x.Id == "tool_calls").i; - Assert.True(aiRequestsIdx < advisorIdx && advisorIdx < toolCallsIdx); + int capabilitiesIdx = allAfterRegister.Select((d, i) => (d.Id, i)).First(x => x.Id == "capabilities").i; + Assert.True(aiRequestsIdx < advisorIdx && advisorIdx < capabilitiesIdx); var createdDrawer = Assert.IsType(DebugCenterPageRegistry.Create("advisor_diagnostics")); Assert.Equal("advisor", createdDrawer.Tag); @@ -72,11 +72,11 @@ public void DebugCenterPageRegistry_supports_custom_registration_ordering_owner_ Assert.Equal(1, removedAdvisor); Assert.Null(DebugCenterPageRegistry.Find("advisor_diagnostics")); Assert.NotNull(DebugCenterPageRegistry.Find("storyteller_timeline")); - Assert.Equal(8, DebugCenterPageRegistry.GetAll().Count); + Assert.Equal(6, DebugCenterPageRegistry.GetAll().Count); DebugCenterPageRegistry.ResetToDefaults(); Assert.Null(DebugCenterPageRegistry.Find("storyteller_timeline")); - Assert.Equal(7, DebugCenterPageRegistry.GetAll().Count); + Assert.Equal(5, DebugCenterPageRegistry.GetAll().Count); } finally { @@ -85,7 +85,7 @@ public void DebugCenterPageRegistry_supports_custom_registration_ordering_owner_ }), ("RimMindAPI.UI exposes DebugPages and UI registration surface", () => { - string apiUiSource = ReadSource("Presentation/Api/RimMindAPI.UI.cs"); + string apiUiSource = ReadSource("Presentation/Api/RimMindAPI.UI.cs"); Assert.Contains("public static class DebugPages", apiUiSource, StringComparison.Ordinal); Assert.Contains("DebugCenterPageRegistry.Register", apiUiSource, StringComparison.Ordinal); Assert.Contains("DebugCenterPageRegistry.UnregisterByOwner", apiUiSource, StringComparison.Ordinal); @@ -158,7 +158,7 @@ public void AIProviderRegistry_resolves_self_describing_descriptor_metadata_with public void TenDayPlaythroughRunner_does_not_fabricate_fallback_prose_or_hardcode_memory_package_id() { ContractCaseRunner.Run( - ("TenDayPlaythroughRunner does not contain fabricated morning thought or social dialogue fallback generators", () => + ("TenDayPlaythroughRunner does not contain fabricated prompts, fallback generators, scripted base building, or survival cheats", () => { string runnerSource = ReadSource("Infrastructure/UI/DebugActions/TenDayPlaythroughRunner.cs"); @@ -166,15 +166,18 @@ public void TenDayPlaythroughRunner_does_not_fabricate_fallback_prose_or_hardcod Assert.DoesNotContain("GenerateDynamicSocialDialogueFallback", runnerSource, StringComparison.Ordinal); Assert.DoesNotContain("PickNonRepeatingFallback", runnerSource, StringComparison.Ordinal); Assert.DoesNotContain("seasonalMorningThoughts", runnerSource, StringComparison.Ordinal); - Assert.Contains("Morning thought failed", runnerSource, StringComparison.Ordinal); - Assert.Contains("Dialogue failed", runnerSource, StringComparison.Ordinal); + Assert.DoesNotContain("ExecuteMorningThought", runnerSource, StringComparison.Ordinal); + Assert.DoesNotContain("ExecuteSocialDialogue", runnerSource, StringComparison.Ordinal); + Assert.DoesNotContain("ExecuteAutonomousAgentAction", runnerSource, StringComparison.Ordinal); + Assert.DoesNotContain("ExecuteAdvisorProposal", runnerSource, StringComparison.Ordinal); + Assert.DoesNotContain("ExecuteDailyColonyOperation", runnerSource, StringComparison.Ordinal); + Assert.DoesNotContain("EnsureColonistSustenance", runnerSource, StringComparison.Ordinal); }), ("TenDayPlaythroughRunner does not hardcode mcocdaa.RimMindMemory package check", () => { string runnerSource = ReadSource("Infrastructure/UI/DebugActions/TenDayPlaythroughRunner.cs"); Assert.DoesNotContain("mcocdaa.RimMindMemory", runnerSource, StringComparison.OrdinalIgnoreCase); - Assert.Contains("RimMindAPI.Memory.AddPawnMemory", runnerSource, StringComparison.Ordinal); })); } diff --git a/Tests/Contracts/ThreatScannerContracts.cs b/Tests/Contracts/ThreatScannerContracts.cs new file mode 100644 index 0000000..f7ec110 --- /dev/null +++ b/Tests/Contracts/ThreatScannerContracts.cs @@ -0,0 +1,49 @@ +using System.Linq; +using RimMind.Presentation.Agent; +using RimWorld; +using Verse; +using Xunit; + +namespace RimMind.Tests.Contracts +{ + /// + /// Regression: PawnAgent never perceived hostiles (ThreatCount was hard-coded to 0), so a mad + /// gazelle / mad dromedary wiped colonies in live playthroughs without any draft or flee decision. + /// + public sealed class ThreatScannerContracts + { + [Fact] + public void FindsAggroAnimalsAndHostileFactionPawns_IgnoresFriendlyDownedAndFar() + { + var map = new Map(); + var self = new Pawn { thingIDNumber = 1, Position = new IntVec3(10, 0, 10), Map = map }; + var raiderFaction = new Faction { HostileToPlayer = true }; + + var madAnimal = new Pawn { thingIDNumber = 2, Position = new IntVec3(15, 0, 10), Map = map, Faction = null, InAggroMentalState = true, KindLabel = "dromedary" }; + var raider = new Pawn { thingIDNumber = 3, Position = new IntVec3(30, 0, 10), Map = map, Faction = raiderFaction, KindLabel = "raider" }; + var friend = new Pawn { thingIDNumber = 4, Position = new IntVec3(11, 0, 10), Map = map }; + var downedRaider = new Pawn { thingIDNumber = 5, Position = new IntVec3(12, 0, 10), Map = map, Faction = raiderFaction, Downed = true }; + var farRaider = new Pawn { thingIDNumber = 6, Position = new IntVec3(200, 0, 10), Map = map, Faction = raiderFaction }; + + map.mapPawns.AllPawnsSpawned.AddRange(new[] { self, madAnimal, raider, friend, downedRaider, farRaider }); + + var threats = ThreatScanner.FindNearbyThreats(self); + + Assert.Equal(new[] { 2, 3 }, threats.Select(t => t.thingIDNumber).ToArray()); + var text = ThreatScanner.Describe(self, threats); + Assert.Contains("dromedary (5 tiles)", text); + Assert.Contains("raider (20 tiles)", text); + } + + [Fact] + public void NoThreats_YieldsEmptyDescription() + { + var map = new Map(); + var self = new Pawn { thingIDNumber = 1, Map = map }; + map.mapPawns.AllPawnsSpawned.Add(self); + + Assert.Empty(ThreatScanner.FindNearbyThreats(self)); + Assert.Equal(string.Empty, ThreatScanner.Describe(self, ThreatScanner.FindNearbyThreats(self))); + } + } +} diff --git a/Tests/Contracts/ToolCallDepthContract.cs b/Tests/Contracts/ToolCallDepthContract.cs index 672f590..bbf02cb 100644 --- a/Tests/Contracts/ToolCallDepthContract.cs +++ b/Tests/Contracts/ToolCallDepthContract.cs @@ -22,13 +22,17 @@ public void Configured_tool_call_depth_controls_the_agent_loop() Assert.True(loop.ShouldContinue(requestMoreTools, currentDepth: 0)); Assert.False(loop.ShouldContinue(requestMoreTools, currentDepth: 1)); }), - ("pawn thinker wires tick settings into the real loop", () => + ("pawn thinker wires tick settings into the real loop and resets workflow phase on early exit/timeout", () => { var thinker = ReadSource("Presentation/Agent/PawnThinker.cs"); Assert.Contains( "new AgenticLoopService(tickSettings.MaxToolCallDepth)", thinker, StringComparison.Ordinal); + Assert.Contains( + "if (_agent.WorkflowPhase == AgentWorkflowPhase.Thinking)", + thinker, + StringComparison.Ordinal); }), ("single-dispatch middleware and runtime expose no fake depth state", () => { diff --git a/Tests/Infrastructure/UI/DebugCenter/DebugCenterPageDrawerStubs.cs b/Tests/Infrastructure/UI/DebugCenter/DebugCenterPageDrawerStubs.cs index 4f064e7..6217114 100644 --- a/Tests/Infrastructure/UI/DebugCenter/DebugCenterPageDrawerStubs.cs +++ b/Tests/Infrastructure/UI/DebugCenter/DebugCenterPageDrawerStubs.cs @@ -35,6 +35,10 @@ internal sealed class ContextKeysDebugCenterPageDrawer : TestDebugCenterPageDraw public ContextKeysDebugCenterPageDrawer(ContextKeysDebugTableModelBuilder modelBuilder) { } } +internal sealed class CapabilitiesDebugCenterPageDrawer : TestDebugCenterPageDrawer +{ +} + internal abstract class TestDebugCenterPageDrawer : IDebugCenterPageDrawer { public void Draw(Rect rect, DebugCenterPageContext context, RimMindLayoutScope scope) diff --git a/Tests/RimMindCore.Tests.csproj b/Tests/RimMindCore.Tests.csproj index d18035c..5f15169 100644 --- a/Tests/RimMindCore.Tests.csproj +++ b/Tests/RimMindCore.Tests.csproj @@ -36,6 +36,7 @@ + diff --git a/Tests/VerseStubs.cs b/Tests/VerseStubs.cs index a61af40..84de9f8 100644 --- a/Tests/VerseStubs.cs +++ b/Tests/VerseStubs.cs @@ -112,6 +112,7 @@ public class MainTabWindow : Verse.Window { } public class Faction { public static Faction OfPlayer = new(); + public bool HostileToPlayer; } public static class KidnapAIUtility @@ -181,6 +182,11 @@ public class Pawn : ThingWithComps public Pawn_RelationsTracker? relations; public object jobs = new(); public RaceProperties RaceProps = new(); + public bool InAggroMentalState; + public MentalStateDef? MentalStateDef; + public string KindLabel = "creature"; + public bool HostileTo(RimWorld.Faction? other) + => Faction != null && other != null && !ReferenceEquals(Faction, other) && (Faction.HostileToPlayer || other.HostileToPlayer); public T? GetComp() where T : ThingComp { @@ -213,6 +219,15 @@ public struct IntVec3 public IntVec3(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public float DistanceTo(IntVec3 other) => (float)Math.Sqrt((x - other.x) * (x - other.x) + (z - other.z) * (z - other.z)); + public int DistanceToSquared(IntVec3 other) + => (x - other.x) * (x - other.x) + (z - other.z) * (z - other.z); + } + + public class MentalStateDef : Def { } + + public static class GridsUtility + { + public static bool Fogged(this IntVec3 c, Map? map) => false; } public class Def