dsh-dungeon-master 0.5.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/CHANGELOG.md +7 -2
  2. package/CHANGELOG_EN.md +7 -2
  3. package/README.md +200 -198
  4. package/README_EN.md +200 -198
  5. package/cordis.patch.yml +32 -32
  6. package/cordis.yml +112 -112
  7. package/dist/commands/dnd.js +1 -1
  8. package/dist/commands/dnd.js.map +1 -1
  9. package/dist/config.d.ts +2 -0
  10. package/dist/config.d.ts.map +1 -1
  11. package/dist/config.js +2 -0
  12. package/dist/config.js.map +1 -1
  13. package/dist/dnd/battle-image.d.ts +3 -0
  14. package/dist/dnd/battle-image.d.ts.map +1 -1
  15. package/dist/dnd/battle-image.js +3 -0
  16. package/dist/dnd/battle-image.js.map +1 -1
  17. package/dist/dnd/battlefield.d.ts +6 -0
  18. package/dist/dnd/battlefield.d.ts.map +1 -1
  19. package/dist/dnd/battlefield.js +75 -16
  20. package/dist/dnd/battlefield.js.map +1 -1
  21. package/dist/dnd/campaign.d.ts +131 -13
  22. package/dist/dnd/campaign.d.ts.map +1 -1
  23. package/dist/dnd/campaign.js +399 -71
  24. package/dist/dnd/campaign.js.map +1 -1
  25. package/dist/dnd/combat-agent.d.ts +26 -3
  26. package/dist/dnd/combat-agent.d.ts.map +1 -1
  27. package/dist/dnd/combat-agent.js +377 -59
  28. package/dist/dnd/combat-agent.js.map +1 -1
  29. package/dist/dnd/combat-context.d.ts +68 -2
  30. package/dist/dnd/combat-context.d.ts.map +1 -1
  31. package/dist/dnd/combat-context.js +58 -21
  32. package/dist/dnd/combat-context.js.map +1 -1
  33. package/dist/dnd/conditions.d.ts +157 -0
  34. package/dist/dnd/conditions.d.ts.map +1 -0
  35. package/dist/dnd/conditions.js +703 -0
  36. package/dist/dnd/conditions.js.map +1 -0
  37. package/dist/dnd/dice.d.ts +5 -1
  38. package/dist/dnd/dice.d.ts.map +1 -1
  39. package/dist/dnd/dice.js +4 -3
  40. package/dist/dnd/dice.js.map +1 -1
  41. package/dist/dnd/dnd-service.js +5 -5
  42. package/dist/dnd/dnd-service.js.map +1 -1
  43. package/dist/dnd/map-view.d.ts.map +1 -1
  44. package/dist/dnd/map-view.js +17 -6
  45. package/dist/dnd/map-view.js.map +1 -1
  46. package/dist/dnd/movement.d.ts.map +1 -1
  47. package/dist/dnd/movement.js +9 -4
  48. package/dist/dnd/movement.js.map +1 -1
  49. package/dist/dnd/pending-attack.d.ts +23 -13
  50. package/dist/dnd/pending-attack.d.ts.map +1 -1
  51. package/dist/dnd/pending-attack.js +198 -27
  52. package/dist/dnd/pending-attack.js.map +1 -1
  53. package/dist/dnd/save-effect.d.ts +4 -0
  54. package/dist/dnd/save-effect.d.ts.map +1 -1
  55. package/dist/dnd/save-effect.js +43 -6
  56. package/dist/dnd/save-effect.js.map +1 -1
  57. package/dist/dnd/spell-links.d.ts +32 -11
  58. package/dist/dnd/spell-links.d.ts.map +1 -1
  59. package/dist/dnd/spell-links.js +105 -20
  60. package/dist/dnd/spell-links.js.map +1 -1
  61. package/dist/dnd/tool-views.js +4 -4
  62. package/dist/dnd/tool-views.js.map +1 -1
  63. package/dist/dnd/tools/character.d.ts.map +1 -1
  64. package/dist/dnd/tools/character.js +167 -20
  65. package/dist/dnd/tools/character.js.map +1 -1
  66. package/dist/dnd/tools/combat.d.ts.map +1 -1
  67. package/dist/dnd/tools/combat.js +112 -16
  68. package/dist/dnd/tools/combat.js.map +1 -1
  69. package/dist/dnd/tools/dice.d.ts.map +1 -1
  70. package/dist/dnd/tools/dice.js +263 -44
  71. package/dist/dnd/tools/dice.js.map +1 -1
  72. package/dist/dnd/tools/saves.d.ts.map +1 -1
  73. package/dist/dnd/tools/saves.js +23 -6
  74. package/dist/dnd/tools/saves.js.map +1 -1
  75. package/dist/dnd/tools/shared.d.ts +2 -0
  76. package/dist/dnd/tools/shared.d.ts.map +1 -1
  77. package/dist/dnd/tools/shared.js +144 -34
  78. package/dist/dnd/tools/shared.js.map +1 -1
  79. package/dist/dnd/turn-buttons.d.ts +4 -0
  80. package/dist/dnd/turn-buttons.d.ts.map +1 -1
  81. package/dist/dnd/turn-buttons.js +47 -23
  82. package/dist/dnd/turn-buttons.js.map +1 -1
  83. package/dist/features/button-utils.d.ts +2 -1
  84. package/dist/features/button-utils.d.ts.map +1 -1
  85. package/dist/features/button-utils.js.map +1 -1
  86. package/dist/features/note-judge.d.ts +24 -7
  87. package/dist/features/note-judge.d.ts.map +1 -1
  88. package/dist/features/note-judge.js +112 -24
  89. package/dist/features/note-judge.js.map +1 -1
  90. package/dist/features/reply-judge.d.ts.map +1 -1
  91. package/dist/features/reply-judge.js +22 -4
  92. package/dist/features/reply-judge.js.map +1 -1
  93. package/dist/gateway/bootstrap.d.ts.map +1 -1
  94. package/dist/gateway/bootstrap.js +19 -1
  95. package/dist/gateway/bootstrap.js.map +1 -1
  96. package/dist/gateway/middleware-setup.d.ts +3 -1
  97. package/dist/gateway/middleware-setup.d.ts.map +1 -1
  98. package/dist/gateway/middleware-setup.js +24 -5
  99. package/dist/gateway/middleware-setup.js.map +1 -1
  100. package/dist/middleware/reply-decider.d.ts +8 -1
  101. package/dist/middleware/reply-decider.d.ts.map +1 -1
  102. package/dist/middleware/reply-decider.js +22 -8
  103. package/dist/middleware/reply-decider.js.map +1 -1
  104. package/dist/middleware/serial-merge.d.ts +7 -3
  105. package/dist/middleware/serial-merge.d.ts.map +1 -1
  106. package/dist/middleware/serial-merge.js +125 -9
  107. package/dist/middleware/serial-merge.js.map +1 -1
  108. package/dist/session/index.d.ts +1 -1
  109. package/dist/session/index.d.ts.map +1 -1
  110. package/dist/session/index.js.map +1 -1
  111. package/dist/session/session-manager.d.ts +11 -2
  112. package/dist/session/session-manager.d.ts.map +1 -1
  113. package/dist/session/session-manager.js +108 -11
  114. package/dist/session/session-manager.js.map +1 -1
  115. package/dist/session/types.d.ts +7 -0
  116. package/dist/session/types.d.ts.map +1 -1
  117. package/dist/setup/bind-routes.d.ts.map +1 -1
  118. package/dist/setup/bind-routes.js +2 -1
  119. package/dist/setup/bind-routes.js.map +1 -1
  120. package/dist/transport/agent-turn.d.ts +7 -3
  121. package/dist/transport/agent-turn.d.ts.map +1 -1
  122. package/dist/transport/agent-turn.js +20 -2
  123. package/dist/transport/agent-turn.js.map +1 -1
  124. package/dist/transport/events.d.ts +6 -1
  125. package/dist/transport/events.d.ts.map +1 -1
  126. package/dist/transport/events.js +1 -0
  127. package/dist/transport/events.js.map +1 -1
  128. package/dist/transport/inbound.d.ts +6 -0
  129. package/dist/transport/inbound.d.ts.map +1 -1
  130. package/dist/transport/inbound.js +62 -10
  131. package/dist/transport/inbound.js.map +1 -1
  132. package/dist/transport/outbound-buffer.d.ts +6 -0
  133. package/dist/transport/outbound-buffer.d.ts.map +1 -1
  134. package/dist/transport/outbound-buffer.js +13 -0
  135. package/dist/transport/outbound-buffer.js.map +1 -1
  136. package/dist/transport/outbound.d.ts.map +1 -1
  137. package/dist/transport/outbound.js +95 -21
  138. package/dist/transport/outbound.js.map +1 -1
  139. package/dist/transport/turn-steer.d.ts +70 -0
  140. package/dist/transport/turn-steer.d.ts.map +1 -0
  141. package/dist/transport/turn-steer.js +206 -0
  142. package/dist/transport/turn-steer.js.map +1 -0
  143. package/lib/client.js +10 -0
  144. package/lib/client.js.map +1 -1
  145. package/package.json +138 -137
  146. package/skills/dnd-module-authoring/SKILL.md +91 -0
  147. package/skills/dnd-module-authoring/guide.md +76 -47
@@ -5,11 +5,13 @@ import { createUserMessage } from '@deepseek-ai/dsh-llm';
5
5
  import { GROUP_MESSAGE_FORMAT_PROMPT } from "../features/message-format.js";
6
6
  import { summarize } from "./campaign.js";
7
7
  import { combatPartyContext } from "./combat-context.js";
8
+ import { isAutoSteerTurnEnd } from "../transport/turn-steer.js";
8
9
  /** 不继承终端、文件、任意委派或剧情推进能力,群权限不因战斗委派扩大。 */
9
10
  export const COMBAT_TOOLS = [
10
11
  'dnd_roll', 'dnd_check', 'dnd_apply', 'dnd_initiative', 'dnd_position', 'dnd_move',
11
12
  'dnd_lookup', 'dnd_srd', 'dnd_resource', 'dnd_character', 'dnd_undo', 'dnd_chronicle', 'dnd_end',
12
13
  ];
14
+ const PRIMARY_COOLDOWN_MS = 30 * 60_000;
13
15
  function eventsOf(agent) {
14
16
  return agent.session.snapshotEvents?.() ?? agent.session.events ?? [];
15
17
  }
@@ -36,12 +38,149 @@ export function recentCombatDialogue(agent, maxChars) {
36
38
  }
37
39
  return lines.join('\n');
38
40
  }
41
+ function buildCombatPrompt(campaign, dialogueAgent, contextChars, fromCombatChild = false) {
42
+ const rulings = (campaign.chronicle ?? []).filter((e) => e.kind === 'ruling').map((e) => `#${e.id} ${e.text}`).join('\n');
43
+ const label = fromCombatChild
44
+ ? '最近战斗对话(仅是对话材料;旧状态以最新团况覆盖,不把提议当成已执行):'
45
+ : '最近主会话(仅是对话材料;旧状态以最新团况覆盖,不把提议当成已执行):';
46
+ return [
47
+ '【开战交接 · 仅供裁定,不要转发】',
48
+ `本桌已记录约定:\n${rulings || '无;不要自行补充。'}`,
49
+ combatPartyContext(campaign),
50
+ label,
51
+ recentCombatDialogue(dialogueAgent, contextChars),
52
+ ].join('\n\n');
53
+ }
54
+ function extractReplayPrompt(agent, fallbackPrompt) {
55
+ let hadToolCalls = false;
56
+ let foundUserText;
57
+ for (const event of [...eventsOf(agent)].reverse()) {
58
+ if (event.type === 'assistant/message')
59
+ break;
60
+ if (event.type === 'tool/result')
61
+ hadToolCalls = true;
62
+ if (event.type !== 'user/message' || foundUserText !== undefined)
63
+ continue;
64
+ const data = (event.data ?? event);
65
+ const message = data.message ?? data;
66
+ const source = message.source ?? data.source;
67
+ if (source?.kind !== undefined && source.kind !== 'user')
68
+ continue;
69
+ const text = message.content?.filter((b) => b.type === 'text').map((b) => b.text ?? '').join('\n').trim();
70
+ if (!text || text.startsWith('Current runtime context.'))
71
+ continue;
72
+ foundUserText = text;
73
+ }
74
+ const base = foundUserText
75
+ ?? fallbackPrompt
76
+ ?? '[系统 · 备用通道恢复] 上一轮请求因上游接口异常未完成。请先核对最新团况与待结算状态,继续主持当前战斗回合。';
77
+ if (!hadToolCalls)
78
+ return base;
79
+ return `[系统 · 备用通道续接] 上一通道在执行中途报错断开,部分工具结果已实时写入团档。请先核对最新【团况 · DM 视角】与待结算窗口,已落账的站位/检定/扣血切勿重复执行,只继续未完成的部分:\n${base}`;
80
+ }
81
+ function partySnapshotItemsFromCharacters(characters) {
82
+ return characters.filter((ch) => ch.kind !== 'monster').map((ch) => ({
83
+ name: ch.name,
84
+ hp: ch.hp,
85
+ maxHp: ch.maxHp,
86
+ tempHp: ch.tempHp ?? 0,
87
+ conditions: [...(ch.conditions ?? [])],
88
+ ...(ch.resources !== undefined ? { resources: structuredClone(ch.resources) } : {}),
89
+ ...(ch.notes !== undefined ? { notes: ch.notes } : {}),
90
+ inventory: [...(ch.inventory ?? [])],
91
+ gp: ch.gp ?? 0,
92
+ ...(ch.room !== undefined ? { room: ch.room } : {}),
93
+ }));
94
+ }
39
95
  function partyState(c) {
40
- return JSON.stringify(c.characters.filter((ch) => ch.kind !== 'monster').map((ch) => ({
41
- name: ch.name, hp: ch.hp, maxHp: ch.maxHp, tempHp: ch.tempHp,
42
- conditions: ch.conditions, resources: ch.resources, notes: ch.notes,
43
- inventory: ch.inventory, gp: ch.gp, room: ch.room,
44
- })));
96
+ // 演练模式下 startInitiative 会在开战时把角色临时改成演练血量,交接基线应取真正的演练前快照
97
+ const source = c.initiative?.rehearsalSnapshot?.characters ?? c.characters;
98
+ return JSON.stringify(partySnapshotItemsFromCharacters(source));
99
+ }
100
+ function formatPartyDelta(beforeJson, c) {
101
+ let prevList;
102
+ try {
103
+ const parsed = JSON.parse(beforeJson);
104
+ if (Array.isArray(parsed))
105
+ prevList = parsed;
106
+ }
107
+ catch { /* fallback below */ }
108
+ const current = partySnapshotItemsFromCharacters(c.characters);
109
+ if (prevList === undefined) {
110
+ return current.map((ch) => `${ch.name} HP ${ch.hp}/${ch.maxHp}${ch.tempHp > 0 ? `(+${ch.tempHp})` : ''}${ch.conditions.length > 0 ? ` [${ch.conditions.join('、')}]` : ''}`).join(';') || '无角色';
111
+ }
112
+ const prevByName = new Map(prevList.map((p) => [p.name, p]));
113
+ const currNames = new Set(current.map((ch) => ch.name));
114
+ const lines = [];
115
+ for (const curr of current) {
116
+ const prev = prevByName.get(curr.name);
117
+ if (prev === undefined) {
118
+ lines.push(`- 新增同伴 ${curr.name}:HP ${curr.hp}/${curr.maxHp}${curr.conditions.length > 0 ? ` [${curr.conditions.join('、')}]` : ''}`);
119
+ continue;
120
+ }
121
+ const diffs = [];
122
+ if (prev.hp !== curr.hp || prev.maxHp !== curr.maxHp) {
123
+ diffs.push(`HP ${prev.hp}/${prev.maxHp}→${curr.hp}/${curr.maxHp}`);
124
+ }
125
+ if ((prev.tempHp ?? 0) !== (curr.tempHp ?? 0)) {
126
+ diffs.push(`临时HP ${prev.tempHp ?? 0}→${curr.tempHp ?? 0}`);
127
+ }
128
+ const prevCond = prev.conditions ?? [];
129
+ if (JSON.stringify(prevCond) !== JSON.stringify(curr.conditions)) {
130
+ diffs.push(`状态 [${prevCond.join('、') || '无'}]→[${curr.conditions.join('、') || '无'}]`);
131
+ }
132
+ const resKeys = new Set([...Object.keys(prev.resources ?? {}), ...Object.keys(curr.resources ?? {})]);
133
+ const resDiffs = [];
134
+ for (const key of resKeys) {
135
+ const pr = prev.resources?.[key];
136
+ const cr = curr.resources?.[key];
137
+ if (pr?.current !== cr?.current || pr?.max !== cr?.max) {
138
+ resDiffs.push(`${key} ${pr ? `${pr.current}/${pr.max}` : '无'}→${cr ? `${cr.current}/${cr.max}` : '移除'}`);
139
+ }
140
+ }
141
+ if (resDiffs.length > 0)
142
+ diffs.push(`资源 ${resDiffs.join('、')}`);
143
+ if ((prev.gp ?? 0) !== (curr.gp ?? 0))
144
+ diffs.push(`金币 ${prev.gp ?? 0}→${curr.gp ?? 0}`);
145
+ const prevInv = prev.inventory ?? [];
146
+ if (JSON.stringify(prevInv) !== JSON.stringify(curr.inventory)) {
147
+ const added = curr.inventory.filter((x) => !prevInv.includes(x));
148
+ const removed = prevInv.filter((x) => !curr.inventory.includes(x));
149
+ if (added.length > 0)
150
+ diffs.push(`新增物品 [${added.join('、')}]`);
151
+ if (removed.length > 0)
152
+ diffs.push(`消耗/移除物品 [${removed.join('、')}]`);
153
+ if (added.length === 0 && removed.length === 0)
154
+ diffs.push(`物品数量变化`);
155
+ }
156
+ if ((prev.room ?? '') !== (curr.room ?? ''))
157
+ diffs.push(`房间 ${prev.room ?? '随队'}→${curr.room ?? '随队'}`);
158
+ if ((prev.notes ?? '') !== (curr.notes ?? ''))
159
+ diffs.push(`备注更新:${(curr.notes ?? '(清空)').slice(0, 240)}`);
160
+ if (diffs.length > 0)
161
+ lines.push(`- ${curr.name}:${diffs.join(';')}`);
162
+ }
163
+ for (const prev of prevList) {
164
+ if (!currNames.has(prev.name))
165
+ lines.push(`- 已移除角色:${prev.name}`);
166
+ }
167
+ if (lines.length === 0) {
168
+ return c.lastCombat?.restored
169
+ ? '【演练已自动还原】所有角色 HP、资源、状态、物品及房间场地图已恢复到开战前快照,无永久损耗。'
170
+ : '队伍 HP、资源、状态与物品较开战前无净变化。';
171
+ }
172
+ return lines.join('\n');
173
+ }
174
+ function formatLedgerByRound(entries) {
175
+ const groups = new Map();
176
+ for (const entry of entries) {
177
+ const list = groups.get(entry.round) ?? [];
178
+ list.push(`${entry.seq !== undefined ? `[#R${entry.seq}] ` : ''}${entry.text}`);
179
+ groups.set(entry.round, list);
180
+ }
181
+ return [...groups.entries()]
182
+ .map(([round, list]) => `第 ${round} 轮:\n${list.map((line) => ` - ${line}`).join('\n')}`)
183
+ .join('\n');
45
184
  }
46
185
  function rowUsage(label, u) {
47
186
  return `${label}:${u.requests} 次请求|新输入 ${u.input}|缓存读取 ${u.cacheRead}|缓存写入 ${u.cacheWrite}|输出 ${u.output}`;
@@ -57,6 +196,7 @@ export class DndCombatAgents {
57
196
  syncTools;
58
197
  logger;
59
198
  directory;
199
+ fallback;
60
200
  active = new Map();
61
201
  locks = new Map();
62
202
  settling = new Map();
@@ -64,13 +204,65 @@ export class DndCombatAgents {
64
204
  failed = new Set();
65
205
  disposed = false;
66
206
  starting = new Set();
67
- constructor(agents, service, settings, syncTools, logger, directory = join(service.store.root, '..', 'combat-runs')) {
207
+ primaryCooldown;
208
+ constructor(agents, service, settings, syncTools, logger, directory = join(service.store.root, '..', 'combat-runs'), fallback) {
68
209
  this.agents = agents;
69
210
  this.service = service;
70
211
  this.settings = settings;
71
212
  this.syncTools = syncTools;
72
213
  this.logger = logger;
73
214
  this.directory = directory;
215
+ this.fallback = fallback;
216
+ }
217
+ resolveRoutes(configured) {
218
+ const fb = this.fallback?.();
219
+ const rawBackup = fb?.backup;
220
+ const backup = rawBackup && rawBackup.provider.trim() && rawBackup.model.trim()
221
+ && (rawBackup.provider !== configured.provider || rawBackup.model !== configured.model)
222
+ ? { provider: rawBackup.provider.trim(), model: rawBackup.model.trim() }
223
+ : undefined;
224
+ if (!backup)
225
+ return { initial: configured };
226
+ if (fb?.activeFailover && fb.activeFailover.provider === backup.provider && fb.activeFailover.model === backup.model) {
227
+ return { initial: backup, preSwitchReason: `${configured.provider}/${configured.model} (全局故障转移生效中)` };
228
+ }
229
+ const primaryKey = `${configured.provider}/${configured.model}`;
230
+ if (this.primaryCooldown && this.primaryCooldown.key === primaryKey && Date.now() < this.primaryCooldown.until) {
231
+ return { initial: backup, preSwitchReason: `${primaryKey} (近期报错冷却中: ${this.primaryCooldown.reason})` };
232
+ }
233
+ return { initial: configured, backup };
234
+ }
235
+ markPrimaryCooldown(route, reason) {
236
+ const config = this.settings();
237
+ if (!config)
238
+ return;
239
+ if (config.provider.trim() === route.provider && config.model.trim() === route.model) {
240
+ this.primaryCooldown = { key: `${route.provider}/${route.model}`, until: Date.now() + PRIMARY_COOLDOWN_MS, reason };
241
+ }
242
+ }
243
+ makeSetup(sessionKey, getPrompt) {
244
+ return (scope) => {
245
+ const tools = scope.get('tools');
246
+ const prompt = scope.get('systemPrompt');
247
+ if (!tools?.restrict || !tools.guard || !prompt?.section)
248
+ throw new Error('宿主不支持战斗代理的工具隔离或完整提示词');
249
+ tools.restrict({ allow: COMBAT_TOOLS });
250
+ tools.guard((exec) => {
251
+ if (!COMBAT_TOOLS.includes(exec.name))
252
+ return '战斗代理只能使用授权的跑团工具';
253
+ if (!this.service.active(sessionKey)?.campaign.initiative)
254
+ return '战斗已结束或暂停,等待主 DM 接手,不再执行战斗操作';
255
+ if (exec.name === 'dnd_initiative' && exec.arguments?.action === 'start')
256
+ return '这场战斗已有先攻表,不可重开战斗';
257
+ return undefined;
258
+ });
259
+ // runtime-context 每次团况变化都会重发整份快照,固定交接放在稳定前缀里,避免每次重复几千 token。
260
+ // 交接含玩家原话,不作模板插值;{{...}} 保持字面文本。
261
+ prompt.section({
262
+ name: 'qqbot:combat-agent', order: 0, complete: true, interpolate: false,
263
+ text: `${this.service.combatInstructions()}\n${GROUP_MESSAGE_FORMAT_PROMPT}\n\n${getPrompt()}`,
264
+ });
265
+ };
74
266
  }
75
267
  file(key) { return join(this.directory, `${key.replace(/[^a-zA-Z0-9_-]/g, '_')}.json`); }
76
268
  save(run) {
@@ -143,9 +335,19 @@ export class DndCombatAgents {
143
335
  }
144
336
  if (target.agent.status !== 'idle')
145
337
  return;
146
- target.agent.followup(createUserMessage({ content: [{ type: 'text', text: `[系统 · 战斗接管] 主 DM 已掷先攻并叙述开场。缺少场地图/站位时先按下列场地准备,不重掷先攻;随后只结算当前怪物回合,轮到 PC 或有反应就停。\n${field}` }], source: { kind: 'user' } }));
338
+ const handoffPrompt = `[系统 · 战斗接管] 主 DM 已掷先攻并叙述开场。缺少场地图/站位时先按下列场地准备,不重掷先攻;随后只结算当前怪物回合,轮到 PC 或有反应就停。\n${field}`;
339
+ const active = this.active.get(main.sessionKey);
340
+ if (active)
341
+ active.lastPrompt = handoffPrompt;
342
+ target.agent.followup(createUserMessage({ content: [{ type: 'text', text: handoffPrompt }], source: { kind: 'user' } }));
147
343
  await target.agent.whenIdle();
148
- return target;
344
+ await this.active.get(main.sessionKey)?.pendingTurnEnd;
345
+ const current = this.current(main.sessionKey);
346
+ if (current !== undefined && current !== target) {
347
+ await current.agent.whenIdle();
348
+ await this.active.get(main.sessionKey)?.pendingTurnEnd;
349
+ }
350
+ return this.current(main.sessionKey);
149
351
  }).finally(() => this.starting.delete(main.sessionKey));
150
352
  }
151
353
  isChild(agent) { return this.findAgent(agent) !== undefined; }
@@ -166,11 +368,11 @@ export class DndCombatAgents {
166
368
  const found = this.service.active(main.sessionKey);
167
369
  const config = this.settings();
168
370
  if (existing !== undefined) {
169
- if (existing.child.agent.status !== 'idle')
170
- return existing.child;
171
371
  existing.child.replyTarget = main.replyTarget;
172
372
  existing.child.lastActivity = main.lastActivity;
173
373
  existing.child.recentSenders = main.recentSenders;
374
+ if (existing.child.agent.status !== 'idle')
375
+ return existing.child;
174
376
  if (found?.campaign.initiative !== undefined && found.campaign.createdAt === existing.run.campaignCreatedAt && config?.enabled)
175
377
  return existing.child;
176
378
  await this.finish(existing, found === undefined ? 'paused' : found.campaign.initiative ? 'interrupted' : 'completed');
@@ -193,59 +395,60 @@ export class DndCombatAgents {
193
395
  this.logger.warn(`im-qqbot: 战斗代理 provider/model 为空,继续由主 DM 主持 key=${main.sessionKey}`);
194
396
  return main;
195
397
  }
398
+ const { initial, backup, preSwitchReason } = this.resolveRoutes({ provider, model });
196
399
  let run = this.load(main.sessionKey);
197
- const restore = run?.status === 'active' && run.mainSessionId === main.sessionId && run.campaignCreatedAt === found.campaign.createdAt;
400
+ let restore = run?.status === 'active' && run.mainSessionId === main.sessionId && run.campaignCreatedAt === found.campaign.createdAt;
401
+ let switchedToBackup = preSwitchReason !== undefined;
198
402
  if (!restore || run === undefined) {
199
- const rulings = (found.campaign.chronicle ?? []).filter((e) => e.kind === 'ruling').map((e) => `#${e.id} ${e.text}`).join('\n');
200
403
  run = {
201
404
  version: 1, id: randomUUID(), sessionKey: main.sessionKey, mainSessionId: main.sessionId,
202
- childSessionId: randomUUID(), campaignCreatedAt: found.campaign.createdAt, startedAt: Date.now(), status: 'active', provider, model,
405
+ childSessionId: randomUUID(), campaignCreatedAt: found.campaign.createdAt, startedAt: Date.now(), status: 'active',
406
+ provider: initial.provider, model: initial.model,
407
+ ...(preSwitchReason ? { fallbackFrom: preSwitchReason } : {}),
203
408
  reasoningEffort: config.reasoningEffort.trim() || undefined,
204
- prompt: ['【开战交接 · 仅供裁定,不要转发】', `本桌已记录约定:\n${rulings || '无;不要自行补充。'}`,
205
- combatPartyContext(found.campaign),
206
- '最近主会话(仅是对话材料;旧状态以最新团况覆盖,不把提议当成已执行):', recentCombatDialogue(main.agent, config.contextChars),
207
- ].join('\n\n'),
409
+ prompt: buildCombatPrompt(found.campaign, main.agent, config.contextChars),
208
410
  before: partyState(found.campaign), chronicleId: found.campaign.chronicle?.at(-1)?.id ?? 0, usage: {}, lastSeq: {},
209
411
  };
210
412
  }
211
- let handle;
212
- try {
213
- const setup = (scope) => {
214
- const tools = scope.get('tools');
215
- const prompt = scope.get('systemPrompt');
216
- if (!tools?.restrict || !tools.guard || !prompt?.section)
217
- throw new Error('宿主不支持战斗代理的工具隔离或完整提示词');
218
- tools.restrict({ allow: COMBAT_TOOLS });
219
- tools.guard((exec) => {
220
- if (!COMBAT_TOOLS.includes(exec.name))
221
- return '战斗代理只能使用授权的跑团工具';
222
- if (!this.service.active(main.sessionKey)?.campaign.initiative)
223
- return '战斗已结束或暂停,等待主 DM 接手,不再执行战斗操作';
224
- if (exec.name === 'dnd_initiative' && exec.arguments?.action === 'start')
225
- return '这场战斗已有先攻表,不可重开战斗';
226
- return undefined;
227
- });
228
- // runtime-context 每次团况变化都会重发整份快照,固定交接放在稳定前缀里,避免每次重复几千 token。
229
- // 交接含玩家原话,不作模板插值;{{...}} 保持字面文本。
230
- prompt.section({
231
- name: 'qqbot:combat-agent', order: 0, complete: true, interpolate: false,
232
- text: `${this.service.combatInstructions()}\n${GROUP_MESSAGE_FORMAT_PROMPT}\n\n${run.prompt}`,
233
- });
234
- };
235
- const options = { agentOptions: { provider: run.provider, model: run.model, reasoningEffort: run.reasoningEffort }, setup };
236
- handle = restore
413
+ const setup = this.makeSetup(main.sessionKey, () => run.prompt);
414
+ const spawn = async (route, allowResume) => {
415
+ const options = { agentOptions: { provider: route.provider, model: route.model, reasoningEffort: run.reasoningEffort }, setup };
416
+ return allowResume
237
417
  ? await this.agents.resume({ resumeSessionId: run.childSessionId, ...options })
238
418
  : await this.agents.create({ sessionId: run.childSessionId, meta: { parentSession: main.sessionId, cwd: main.agent.session.header?.cwd ?? process.cwd() }, ...options });
419
+ };
420
+ let handle;
421
+ try {
422
+ try {
423
+ handle = await spawn({ provider: run.provider, model: run.model }, restore);
424
+ }
425
+ catch (primaryErr) {
426
+ const errMsg = primaryErr instanceof Error ? primaryErr.message.slice(0, 200) : String(primaryErr).slice(0, 200);
427
+ this.markPrimaryCooldown({ provider: run.provider, model: run.model }, errMsg);
428
+ const canRetryBackup = backup !== undefined && !switchedToBackup
429
+ && (backup.provider !== run.provider || backup.model !== run.model);
430
+ if (!canRetryBackup)
431
+ throw primaryErr;
432
+ const prevLabel = `${run.provider}/${run.model}`;
433
+ this.logger.warn(`im-qqbot: 战斗代理主通道 ${prevLabel} 启动失败 (${errMsg}),切至备用通道 ${backup.provider}/${backup.model} key=${main.sessionKey}`);
434
+ run.fallbackFrom = `${prevLabel} (${errMsg})`;
435
+ run.provider = backup.provider;
436
+ run.model = backup.model;
437
+ run.childSessionId = randomUUID();
438
+ restore = false;
439
+ switchedToBackup = true;
440
+ handle = await spawn(backup, false);
441
+ }
239
442
  if (this.disposed || generation !== (this.generations.get(main.sessionKey) ?? 0)) {
240
443
  await handle.dispose();
241
444
  return main;
242
445
  }
243
446
  const child = { ...main, sessionId: run.childSessionId, agent: handle.agent, handle, agentPreset: undefined, contextTokens: undefined };
244
- this.active.set(main.sessionKey, { main, child, run });
447
+ this.active.set(main.sessionKey, { main, child, run, switchedToBackup });
245
448
  this.syncTools(main);
246
449
  this.syncTools(child);
247
450
  this.save(run);
248
- this.logger.info(`im-qqbot: 战斗代理${restore ? '恢复' : '接管'} key=${main.sessionKey} child=${child.sessionId} model=${run.provider}/${run.model}`);
451
+ this.logger.info(`im-qqbot: 战斗代理${restore ? '恢复' : '接管'} key=${main.sessionKey} child=${child.sessionId} model=${run.provider}/${run.model}${run.fallbackFrom ? ` (fallback from ${run.fallbackFrom})` : ''}`);
249
452
  return child;
250
453
  }
251
454
  catch (err) {
@@ -255,22 +458,28 @@ export class DndCombatAgents {
255
458
  this.syncTools(main);
256
459
  run.status = 'failed';
257
460
  run.endedAt = Date.now();
461
+ run.error = err instanceof Error ? err.message.slice(0, 300) : String(err).slice(0, 300);
258
462
  this.checkpoint(run);
259
463
  this.logger.warn(`im-qqbot: 战斗代理不可用,主 DM 继续 key=${main.sessionKey}: ${String(err)}`);
260
464
  return main;
261
465
  }
262
466
  });
263
467
  }
264
- /** 出站已按同一 SessionRecord 发到群;这里只记账并在安全的 idle 边界交回主 DM。 */
468
+ /**
469
+ * 出站已按同一 SessionRecord 发到群;这里只记账并在安全的 idle 边界交回主 DM 或切换备用通道。
470
+ * 返回 true 表示本次子代理 turn/end 报错已由战斗路由接管恢复(切备用模型或交回主 DM),出站层不必再向群内刷原始报错。
471
+ */
265
472
  observe(record, event) {
266
473
  const active = this.active.get(record.sessionKey);
267
474
  const settling = this.settling.get(record.sessionId);
268
475
  const run = active?.run ?? settling;
269
476
  if (!run)
270
- return;
477
+ return false;
271
478
  if (event.seq !== undefined) {
272
- if ((run.lastSeq[record.sessionId] ?? -1) >= event.seq)
273
- return;
479
+ if ((run.lastSeq[record.sessionId] ?? -1) >= event.seq) {
480
+ const dupReason = event.type === 'turn/end' ? event.data.reason : undefined;
481
+ return Boolean(active && record.agent === active.child.agent && (dupReason?.kind === 'error' || dupReason?.kind === 'failed'));
482
+ }
274
483
  run.lastSeq[record.sessionId] = event.seq;
275
484
  }
276
485
  if (event.type === 'assistant/message') {
@@ -287,10 +496,16 @@ export class DndCombatAgents {
287
496
  u.cacheRead += usage.cacheReadTokens ?? 0;
288
497
  u.cacheWrite += usage.cacheWriteTokens ?? 0;
289
498
  }
290
- if (lane === 'combat') {
499
+ if (lane === 'combat' && data.interrupted !== true) {
291
500
  const text = data.message?.content?.filter((b) => b.type === 'text').map((b) => b.text ?? '').join('\n').trim();
292
- if (text && text !== '。')
501
+ if (text && text !== '。') {
293
502
  run.lastNarration = text.slice(-2000);
503
+ const init = this.service.active(record.sessionKey)?.campaign.initiative;
504
+ if (init !== undefined) {
505
+ run.lastNarrationRound = init.round;
506
+ run.narratedLedgerCount = init.ledger?.length ?? 0;
507
+ }
508
+ }
294
509
  }
295
510
  this.checkpoint(run);
296
511
  }
@@ -300,18 +515,91 @@ export class DndCombatAgents {
300
515
  }
301
516
  if (event.type === 'turn/end' && active && record.agent === active.child.agent) {
302
517
  const reason = event.data.reason;
303
- void record.agent.whenIdle().then(() => this.serial(record.sessionKey, async () => {
518
+ if (isAutoSteerTurnEnd(reason))
519
+ return false;
520
+ const isFailure = reason?.kind === 'error' || reason?.kind === 'failed';
521
+ const task = record.agent.whenIdle().then(() => this.serial(record.sessionKey, async () => {
304
522
  if (this.disposed || this.active.get(record.sessionKey) !== active)
305
523
  return;
306
524
  const found = this.service.active(record.sessionKey);
307
- if (reason?.kind === 'error' || reason?.kind === 'failed')
525
+ if (isFailure) {
526
+ const errObj = reason?.error ?? reason?.failure;
527
+ const code = errObj?.code ? ` (${errObj.code})` : '';
528
+ const msg = (errObj?.message ?? reason?.message ?? '').trim();
529
+ const errText = `${reason.kind}${code}${msg ? `: ${msg.slice(0, 300)}` : ''}`;
530
+ this.markPrimaryCooldown({ provider: active.run.provider, model: active.run.model }, errText);
531
+ const rawBackup = this.fallback?.()?.backup;
532
+ const backup = rawBackup && rawBackup.provider.trim() && rawBackup.model.trim()
533
+ && (rawBackup.provider.trim() !== active.run.provider || rawBackup.model.trim() !== active.run.model)
534
+ ? { provider: rawBackup.provider.trim(), model: rawBackup.model.trim() }
535
+ : undefined;
536
+ if (found?.campaign.initiative && !active.switchedToBackup && backup !== undefined) {
537
+ try {
538
+ await this.switchToBackup(active, found.campaign, backup, errText);
539
+ return;
540
+ }
541
+ catch (switchErr) {
542
+ const switchMsg = switchErr instanceof Error ? switchErr.message.slice(0, 160) : String(switchErr).slice(0, 160);
543
+ active.run.error = `${errText};备用通道 ${backup.provider}/${backup.model} 启动失败: ${switchMsg}`;
544
+ await this.finish(active, 'failed');
545
+ return;
546
+ }
547
+ }
548
+ active.run.error = active.run.fallbackFrom
549
+ ? `主通道 ${active.run.fallbackFrom};备用通道 ${active.run.provider}/${active.run.model} ${errText}`
550
+ : errText;
308
551
  await this.finish(active, 'failed');
552
+ }
309
553
  else if (!found)
310
554
  await this.finish(active, 'paused');
311
555
  else if (!found.campaign.initiative)
312
556
  await this.finish(active, 'completed');
313
- })).catch((err) => this.logger.warn(`im-qqbot: 战斗交接失败: ${String(err)}`));
557
+ })).catch((err) => this.logger.warn(`im-qqbot: 战斗交接失败: ${String(err)}`))
558
+ .finally(() => { if (active.pendingTurnEnd === task)
559
+ active.pendingTurnEnd = undefined; });
560
+ active.pendingTurnEnd = task;
561
+ return isFailure;
314
562
  }
563
+ return false;
564
+ }
565
+ async switchToBackup(active, campaign, backup, errText) {
566
+ const oldChild = active.child;
567
+ const prevLabel = `${active.run.provider}/${active.run.model}`;
568
+ const replayPrompt = extractReplayPrompt(oldChild.agent, active.lastPrompt);
569
+ const hasChildDialogue = eventsOf(oldChild.agent).some((e) => e.type === 'assistant/message');
570
+ const contextChars = this.settings()?.contextChars ?? 8000;
571
+ active.run.prompt = buildCombatPrompt(campaign, hasChildDialogue ? oldChild.agent : active.main.agent, contextChars, hasChildDialogue);
572
+ active.run.fallbackFrom = `${prevLabel} (${errText})`;
573
+ active.run.provider = backup.provider;
574
+ active.run.model = backup.model;
575
+ active.run.childSessionId = randomUUID();
576
+ delete active.run.error;
577
+ const setup = this.makeSetup(active.run.sessionKey, () => active.run.prompt);
578
+ const handle = await this.agents.create({
579
+ sessionId: active.run.childSessionId,
580
+ meta: { parentSession: active.main.sessionId, cwd: active.main.agent.session.header?.cwd ?? process.cwd() },
581
+ agentOptions: { provider: backup.provider, model: backup.model, reasoningEffort: active.run.reasoningEffort },
582
+ setup,
583
+ });
584
+ const newChild = {
585
+ ...active.main,
586
+ replyTarget: oldChild.replyTarget,
587
+ lastActivity: oldChild.lastActivity,
588
+ recentSenders: oldChild.recentSenders,
589
+ sessionId: active.run.childSessionId,
590
+ agent: handle.agent,
591
+ handle,
592
+ agentPreset: undefined,
593
+ contextTokens: undefined,
594
+ };
595
+ active.child = newChild;
596
+ active.switchedToBackup = true;
597
+ active.lastPrompt = replayPrompt;
598
+ this.syncTools(newChild);
599
+ this.save(active.run);
600
+ await oldChild.handle.dispose().catch(() => { });
601
+ this.logger.warn(`im-qqbot: 战斗代理通道异常 (${errText}),已自动切至备用通道 ${backup.provider}/${backup.model} key=${active.run.sessionKey} child=${newChild.sessionId}`);
602
+ newChild.agent.followup(createUserMessage({ content: [{ type: 'text', text: replayPrompt }], source: { kind: 'user' } }));
315
603
  }
316
604
  async finish(active, status) {
317
605
  if (active.child.agent.status !== 'idle')
@@ -320,13 +608,41 @@ export class DndCombatAgents {
320
608
  const found = this.service.active(run.sessionKey) ?? this.service.saved(run.sessionKey);
321
609
  run.status = status;
322
610
  run.endedAt = Date.now();
611
+ const lastCombat = found?.campaign.lastCombat !== undefined && found.campaign.lastCombat.at >= run.startedAt
612
+ ? found.campaign.lastCombat
613
+ : undefined;
614
+ const fullLedger = lastCombat?.ledger ?? found?.campaign.initiative?.ledger ?? [];
615
+ const unreported = fullLedger.slice(Math.min(run.narratedLedgerCount ?? 0, fullLedger.length));
616
+ const outcomeBlock = lastCombat === undefined
617
+ ? undefined
618
+ : [
619
+ `【本场战斗结果摘要】共 ${lastCombat.rounds} 轮${lastCombat.rehearsal ? (lastCombat.restored ? '(梦境/演练模式,战后已自动还原真实状态与地图)' : '(演练模式,保留变更)') : ''}`,
620
+ `- 击败敌方:${lastCombat.defeated.join('、') || '无'}`,
621
+ `- 场上仍存活敌方(DM 机密数值,严禁向群内透露具体数字,只用伤势词描述):${lastCombat.survivingMonsters.map((m) => `${m.name} HP ${m.hp}/${m.maxHp}${m.conditions.length > 0 ? ` [${m.conditions.join('、')}]` : ''}`).join('、') || '无(敌方全灭)'}`,
622
+ `- 本场倒地/阵亡我方:${lastCombat.fallenParty.map((p) => `${p.name}(HP ${p.hp}/${p.maxHp}${p.conditions.length > 0 ? `,${p.conditions.join('、')}` : ''})`).join('、') || '无'}`,
623
+ ].join('\n');
624
+ const unreportedBlock = unreported.length === 0
625
+ ? undefined
626
+ : [
627
+ `【未向群内播报的战斗账本(共 ${unreported.length} 条;战斗代理已落账但尚未向玩家叙述)】`,
628
+ '接手后的第一条回复必须按下列真实账本补叙未播报回合的关键交锋、重击/倒地与最终胜负(怪物 AC/HP/DC 保密,不报具体剩余血量数字):',
629
+ formatLedgerByRound(unreported),
630
+ ].join('\n');
631
+ const newChronicle = found
632
+ ? (found.campaign.chronicle ?? []).filter((e) => e.id > run.chronicleId).map((e) => e.text).join('\n')
633
+ : '';
323
634
  run.handoff = [
324
635
  '【系统 · 战斗代理交回 · DM 私有】',
325
636
  ...(status === 'paused' ? ['团已暂停。只确认保存,不推进回合或剧情;未结束的战斗留待下次开团。'] : []),
326
- status === 'completed' ? '战斗已结束。机械结算已经实时写入同一份团档,禁止重复扣血、扣资源、掷骰或再发奖励。只接续战后剧情,没确认的战利品按模组查证。' : '战斗代理已停止。先核对最新团况与待结算窗口,不能重做已落账行动,也不能当作战斗已结束。',
327
- `交接前队伍:${run.before}`,
328
- found ? `最新团况:\n${summarize(found.campaign, found.adventure)}\n最新队伍明细:${partyState(found.campaign)}\n新增账本:\n${(found.campaign.chronicle ?? []).filter((e) => e.id > run.chronicleId).map((e) => e.text).join('\n')}` : '团档不可用,必须先核实,不能推断结局。',
329
- `战斗代理最后已发到群里的叙述(不必复述;叙述不覆盖团档):${run.lastNarration ?? '无'}`,
637
+ status === 'completed'
638
+ ? '战斗已结束。机械结算已经实时写入同一份团档,禁止重复扣血、扣资源、掷骰或再发奖励。只接续战后剧情,没确认的战利品按模组查证。'
639
+ : `战斗代理已停止${run.error ? `(原因:${run.error};此原因仅供 DM 知悉,勿把原始报错 JSON 发进群)` : ''}。先核对最新团况与待结算窗口,不能重做已落账行动,也不能当作战斗已结束。`,
640
+ ...(outcomeBlock !== undefined ? [outcomeBlock] : []),
641
+ found
642
+ ? `【战前→战后队伍变化】\n${formatPartyDelta(run.before, found.campaign)}\n最新团况:\n${summarize(found.campaign, found.adventure)}${newChronicle ? `\n新增账本:\n${newChronicle}` : ''}`
643
+ : `交接前队伍:${run.before}\n团档不可用,必须先核实,不能推断结局。`,
644
+ ...(unreportedBlock !== undefined ? [unreportedBlock] : []),
645
+ `战斗代理最后已发到群里的叙述${run.lastNarrationRound !== undefined ? `(第 ${run.lastNarrationRound} 轮)` : ''}(已播报内容不必复述;叙述不覆盖团档):${run.lastNarration ?? '无'}`,
330
646
  '怪物 AC、HP、DC 和 DM 机密仍不进群消息;不要替玩家选择下一步。',
331
647
  ].join('\n');
332
648
  this.checkpoint(run);
@@ -343,13 +659,15 @@ export class DndCombatAgents {
343
659
  this.settling.set(main.sessionId, run);
344
660
  main.agent.followup(createUserMessage({ content: [{ type: 'text', text: run.handoff }], source: { kind: 'user' } }));
345
661
  }
346
- this.logger.info(`im-qqbot: 战斗代理交回 key=${run.sessionKey} status=${status} ${Object.entries(run.usage).map(([k, u]) => rowUsage(k, u)).join(' | ')}`);
662
+ this.logger.info(`im-qqbot: 战斗代理交回 key=${run.sessionKey} status=${status}${run.error ? ` reason=${run.error}` : ''} ${Object.entries(run.usage).map(([k, u]) => rowUsage(k, u)).join(' | ')}`);
347
663
  }
348
664
  report(key) {
349
665
  const run = this.active.get(key)?.run ?? [...this.settling.values()].find((r) => r.sessionKey === key) ?? this.load(key);
350
666
  if (!run)
351
667
  return '还没有战斗代理记录。启用后,开战后的下一次玩家消息或回合按钮会交给战斗模型。';
352
668
  return [`战斗代理:${run.status}|${run.provider}/${run.model}`,
669
+ ...(run.fallbackFrom ? [`已回退自:${run.fallbackFrom}`] : []),
670
+ ...(run.error ? [`失败原因:${run.error}`] : []),
353
671
  `记录:${run.id.slice(0, 8)}|子会话 ${run.childSessionId.slice(0, 8)}`,
354
672
  ...Object.entries(run.usage).map(([label, usage]) => rowUsage(label, usage)),
355
673
  '包含战斗代理与战后主 DM 交接回复;不含开战前主会话,缓存单列,金额按渠道账单计算。',