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(
+ @"(?(?:Thought|Action|Param|tool_call_results|perceptions|behavior_history|scope)>)(?!\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 = $"{tagName}>";
+ 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