briyah 2.0.3 → 2.0.5

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 (391) hide show
  1. package/README.md +55 -8
  2. package/data/common/config/LICENSE-model-prices.md +65 -0
  3. package/data/common/config/markup +1 -1
  4. package/data/common/config/model_prices.json +47443 -46295
  5. package/data/common/config/story_models.json +3 -3
  6. package/data/common/prompts/illustrator/describe_scene.prompt +4 -4
  7. package/data/common/prompts/narrator/create_story.prompt +2 -0
  8. package/data/common/prompts/perceive.prompt +1 -1
  9. package/data/packs/dnd5e/prompts/battle_master/perceive.prompt +1 -1
  10. package/data/packs/dnd5e/prompts/campaign_designer/perceive.prompt +1 -1
  11. package/data/packs/dnd5e/prompts/character_creator/perceive.prompt +795 -787
  12. package/data/packs/dnd5e/prompts/dungeon_master/defaults_config.json +2 -1
  13. package/data/packs/dnd5e/prompts/dungeon_master/perceive.prompt +1 -1
  14. package/data/packs/dnd5e/rooms/campaign.json +18 -15
  15. package/data/packs/dnd5e/rooms/table.json +17 -16
  16. package/dist-sdk/server/src/ai/LLM/anthropic.service.d.ts +103 -0
  17. package/dist-sdk/server/src/ai/LLM/anthropic.service.js +174 -3
  18. package/dist-sdk/server/src/ai/LLM/base-ai.service.d.ts +194 -3
  19. package/dist-sdk/server/src/ai/LLM/base-ai.service.js +299 -19
  20. package/dist-sdk/server/src/ai/LLM/blank-image.d.ts +36 -0
  21. package/dist-sdk/server/src/ai/LLM/blank-image.js +80 -0
  22. package/dist-sdk/server/src/ai/LLM/comfyui-client.d.ts +26 -0
  23. package/dist-sdk/server/src/ai/LLM/comfyui-client.js +25 -0
  24. package/dist-sdk/server/src/ai/LLM/comfyui-workflow.d.ts +54 -0
  25. package/dist-sdk/server/src/ai/LLM/comfyui-workflow.js +59 -1
  26. package/dist-sdk/server/src/ai/LLM/comfyui.service.d.ts +21 -1
  27. package/dist-sdk/server/src/ai/LLM/comfyui.service.js +25 -1
  28. package/dist-sdk/server/src/ai/LLM/deepseek.service.d.ts +52 -0
  29. package/dist-sdk/server/src/ai/LLM/deepseek.service.js +103 -4
  30. package/dist-sdk/server/src/ai/LLM/fal.service.d.ts +25 -0
  31. package/dist-sdk/server/src/ai/LLM/fal.service.js +56 -2
  32. package/dist-sdk/server/src/ai/LLM/googleai.service.d.ts +19 -0
  33. package/dist-sdk/server/src/ai/LLM/googleai.service.js +43 -2
  34. package/dist-sdk/server/src/ai/LLM/grok.service.d.ts +22 -0
  35. package/dist-sdk/server/src/ai/LLM/grok.service.js +55 -3
  36. package/dist-sdk/server/src/ai/LLM/mock.service.js +31 -4
  37. package/dist-sdk/server/src/ai/LLM/openai.service.d.ts +30 -0
  38. package/dist-sdk/server/src/ai/LLM/openai.service.js +81 -3
  39. package/dist-sdk/server/src/ai/LLM/self-hosted.service.d.ts +21 -0
  40. package/dist-sdk/server/src/ai/LLM/self-hosted.service.js +45 -3
  41. package/dist-sdk/server/src/ai/LLM/together.service.d.ts +30 -0
  42. package/dist-sdk/server/src/ai/LLM/together.service.js +61 -3
  43. package/dist-sdk/server/src/ai/agent-config.d.ts +15 -1
  44. package/dist-sdk/server/src/ai/agent-factory.d.ts +16 -0
  45. package/dist-sdk/server/src/ai/agent-factory.js +20 -0
  46. package/dist-sdk/server/src/ai/agent-message.service.d.ts +30 -0
  47. package/dist-sdk/server/src/ai/agent-message.service.js +30 -0
  48. package/dist-sdk/server/src/ai/agent-store.service.d.ts +80 -0
  49. package/dist-sdk/server/src/ai/agent-store.service.js +166 -7
  50. package/dist-sdk/server/src/ai/agent.d.ts +197 -2
  51. package/dist-sdk/server/src/ai/agent.js +225 -14
  52. package/dist-sdk/server/src/ai/ai-debug-logger.d.ts +18 -0
  53. package/dist-sdk/server/src/ai/ai-debug-logger.js +19 -0
  54. package/dist-sdk/server/src/ai/ai-factory.service.d.ts +9 -0
  55. package/dist-sdk/server/src/ai/ai-factory.service.js +9 -0
  56. package/dist-sdk/server/src/ai/artifact.service.d.ts +131 -0
  57. package/dist-sdk/server/src/ai/artifact.service.js +148 -3
  58. package/dist-sdk/server/src/ai/attached-file.service.d.ts +87 -0
  59. package/dist-sdk/server/src/ai/attached-file.service.js +105 -0
  60. package/dist-sdk/server/src/ai/model_prices.d.ts +30 -0
  61. package/dist-sdk/server/src/ai/model_prices.js +91 -5
  62. package/dist-sdk/server/src/ai/pack-artifacts.d.ts +84 -0
  63. package/dist-sdk/server/src/ai/pack-artifacts.js +168 -0
  64. package/dist-sdk/server/src/ai/published-agents.service.d.ts +25 -0
  65. package/dist-sdk/server/src/ai/published-agents.service.js +30 -3
  66. package/dist-sdk/server/src/app/balance-message.service.d.ts +24 -0
  67. package/dist-sdk/server/src/app/balance-message.service.js +24 -0
  68. package/dist-sdk/server/src/app/balance.module.d.ts +4 -0
  69. package/dist-sdk/server/src/app/balance.module.js +4 -0
  70. package/dist-sdk/server/src/app/balance.service.d.ts +37 -0
  71. package/dist-sdk/server/src/app/balance.service.js +54 -0
  72. package/dist-sdk/server/src/app/stripe.controller.d.ts +21 -0
  73. package/dist-sdk/server/src/app/stripe.controller.js +35 -0
  74. package/dist-sdk/server/src/app/stripe.service.d.ts +43 -0
  75. package/dist-sdk/server/src/app/stripe.service.js +62 -0
  76. package/dist-sdk/server/src/app/transaction.service.d.ts +27 -0
  77. package/dist-sdk/server/src/app/transaction.service.js +36 -0
  78. package/dist-sdk/server/src/app/user-service-factory.d.ts +8 -0
  79. package/dist-sdk/server/src/app/user-service-factory.js +46 -3
  80. package/dist-sdk/server/src/app/user-service-manager.d.ts +27 -0
  81. package/dist-sdk/server/src/app/user-service-manager.js +43 -0
  82. package/dist-sdk/server/src/app.controller.d.ts +120 -0
  83. package/dist-sdk/server/src/app.controller.js +365 -14
  84. package/dist-sdk/server/src/app.module.js +28 -6
  85. package/dist-sdk/server/src/app.service.d.ts +1710 -4
  86. package/dist-sdk/server/src/app.service.js +1938 -20
  87. package/dist-sdk/server/src/auth/agent-access.decorator.d.ts +17 -0
  88. package/dist-sdk/server/src/auth/agent-access.decorator.js +17 -0
  89. package/dist-sdk/server/src/auth/auth.controller.js +46 -0
  90. package/dist-sdk/server/src/auth/auth.module.js +3 -2
  91. package/dist-sdk/server/src/auth/auth.service.d.ts +33 -0
  92. package/dist-sdk/server/src/auth/auth.service.js +39 -3
  93. package/dist-sdk/server/src/auth/jwt-auth.guard.js +44 -0
  94. package/dist-sdk/server/src/auth/jwt.strategy.js +2 -2
  95. package/dist-sdk/server/src/auth/owner-only.decorator.d.ts +9 -0
  96. package/dist-sdk/server/src/auth/owner-only.decorator.js +9 -0
  97. package/dist-sdk/server/src/auth/phone-validation.service.d.ts +25 -0
  98. package/dist-sdk/server/src/auth/phone-validation.service.js +30 -0
  99. package/dist-sdk/server/src/auth/rate-limit.service.d.ts +19 -0
  100. package/dist-sdk/server/src/auth/rate-limit.service.js +24 -0
  101. package/dist-sdk/server/src/auth/room-access.decorator.d.ts +8 -0
  102. package/dist-sdk/server/src/auth/room-access.decorator.js +8 -0
  103. package/dist-sdk/server/src/auth/scopes.decorator.d.ts +7 -0
  104. package/dist-sdk/server/src/auth/scopes.decorator.js +7 -0
  105. package/dist-sdk/server/src/auth/scopes.guard.d.ts +16 -0
  106. package/dist-sdk/server/src/auth/scopes.guard.js +30 -0
  107. package/dist-sdk/server/src/auth/session.guard.d.ts +4 -0
  108. package/dist-sdk/server/src/auth/session.guard.js +8 -0
  109. package/dist-sdk/server/src/auth/twilio.service.d.ts +27 -0
  110. package/dist-sdk/server/src/auth/twilio.service.js +30 -4
  111. package/dist-sdk/server/src/auth/users.service.d.ts +30 -0
  112. package/dist-sdk/server/src/auth/users.service.js +42 -0
  113. package/dist-sdk/server/src/common/errors.d.ts +20 -0
  114. package/dist-sdk/server/src/common/errors.js +21 -0
  115. package/dist-sdk/server/src/config/env-config.d.ts +7 -0
  116. package/dist-sdk/server/src/config/prompt-resolver.d.ts +180 -0
  117. package/dist-sdk/server/src/config/prompt-resolver.js +182 -0
  118. package/dist-sdk/server/src/config/user-config.service.d.ts +59 -0
  119. package/dist-sdk/server/src/config/user-config.service.js +57 -0
  120. package/dist-sdk/server/src/config/user-paths.service.d.ts +61 -0
  121. package/dist-sdk/server/src/config/user-paths.service.js +67 -0
  122. package/dist-sdk/server/src/documents/pdf-conversion.d.ts +121 -1
  123. package/dist-sdk/server/src/documents/pdf-conversion.js +94 -0
  124. package/dist-sdk/server/src/packs/pack-instantiation.service.d.ts +98 -0
  125. package/dist-sdk/server/src/packs/pack-instantiation.service.js +104 -0
  126. package/dist-sdk/server/src/packs/pack-manifest.d.ts +114 -0
  127. package/dist-sdk/server/src/packs/pack-manifest.js +69 -0
  128. package/dist-sdk/server/src/packs/pack.service.d.ts +99 -1
  129. package/dist-sdk/server/src/packs/pack.service.js +98 -1
  130. package/dist-sdk/server/src/room/artifact-store.service.d.ts +27 -0
  131. package/dist-sdk/server/src/room/artifact-store.service.js +49 -3
  132. package/dist-sdk/server/src/room/artifact.d.ts +18 -0
  133. package/dist-sdk/server/src/room/illustration/illustration.service.d.ts +211 -0
  134. package/dist-sdk/server/src/room/illustration/illustration.service.js +771 -0
  135. package/dist-sdk/server/src/room/illustration/illustration.types.d.ts +101 -0
  136. package/dist-sdk/server/src/room/illustration/illustration.types.js +2 -0
  137. package/dist-sdk/server/src/room/message.d.ts +64 -0
  138. package/dist-sdk/server/src/room/message.js +77 -2
  139. package/dist-sdk/server/src/room/nickname.d.ts +26 -0
  140. package/dist-sdk/server/src/room/nickname.js +26 -0
  141. package/dist-sdk/server/src/room/published-rooms.service.js +2 -0
  142. package/dist-sdk/server/src/room/room-config.d.ts +84 -1
  143. package/dist-sdk/server/src/room/room-config.js +19 -0
  144. package/dist-sdk/server/src/room/room-factory.d.ts +20 -0
  145. package/dist-sdk/server/src/room/room-factory.js +25 -0
  146. package/dist-sdk/server/src/room/room-message.service.d.ts +28 -0
  147. package/dist-sdk/server/src/room/room-message.service.js +28 -0
  148. package/dist-sdk/server/src/room/room-store.service.d.ts +184 -0
  149. package/dist-sdk/server/src/room/room-store.service.js +280 -6
  150. package/dist-sdk/server/src/room/room.d.ts +981 -1
  151. package/dist-sdk/server/src/room/room.js +1531 -27
  152. package/dist-sdk/server/src/rpg/rpg-models.d.ts +50 -0
  153. package/dist-sdk/server/src/rpg/rpg-models.js +53 -0
  154. package/dist-sdk/server/src/rpg/rpg-roster.d.ts +37 -0
  155. package/dist-sdk/server/src/rpg/rpg-roster.js +37 -0
  156. package/dist-sdk/server/src/rpg/rpg.service.d.ts +87 -0
  157. package/dist-sdk/server/src/rpg/rpg.service.js +108 -1
  158. package/dist-sdk/server/src/sdk/briyah-config.d.ts +57 -0
  159. package/dist-sdk/server/src/sdk/briyah-config.js +17 -0
  160. package/dist-sdk/server/src/sdk/briyah.d.ts +228 -0
  161. package/dist-sdk/server/src/sdk/briyah.js +285 -7
  162. package/dist-sdk/server/src/sdk/index.js +23 -0
  163. package/dist-sdk/server/src/shared/shared.module.d.ts +8 -0
  164. package/dist-sdk/server/src/shared/shared.module.js +13 -5
  165. package/dist-sdk/server/src/story/story-message.service.d.ts +43 -0
  166. package/dist-sdk/server/src/story/story-message.service.js +43 -0
  167. package/dist-sdk/server/src/story/story-progress.service.d.ts +23 -0
  168. package/dist-sdk/server/src/story/story-progress.service.js +23 -0
  169. package/dist-sdk/server/src/story/story-store.service.d.ts +92 -0
  170. package/dist-sdk/server/src/story/story-store.service.js +136 -1
  171. package/dist-sdk/server/src/story/story.service.d.ts +366 -9
  172. package/dist-sdk/server/src/story/story.service.js +825 -374
  173. package/dist-sdk/server/src/tools/core/illustrate.tool.d.ts +14 -0
  174. package/dist-sdk/server/src/tools/core/illustrate.tool.js +80 -0
  175. package/dist-sdk/server/src/tools/core/index.d.ts +22 -0
  176. package/dist-sdk/server/src/tools/core/index.js +24 -1
  177. package/dist-sdk/server/src/tools/core/rename.tool.d.ts +8 -0
  178. package/dist-sdk/server/src/tools/core/rename.tool.js +11 -0
  179. package/dist-sdk/server/src/tools/native-tool-registry.service.d.ts +22 -0
  180. package/dist-sdk/server/src/tools/native-tool-registry.service.js +22 -0
  181. package/dist-sdk/server/src/tools/native-tool.types.d.ts +266 -0
  182. package/dist-sdk/server/src/tools/packs/dnd5e/data/backgrounds.d.ts +29 -0
  183. package/dist-sdk/server/src/tools/packs/dnd5e/data/backgrounds.js +29 -0
  184. package/dist-sdk/server/src/tools/packs/dnd5e/data/cantrips.d.ts +46 -0
  185. package/dist-sdk/server/src/tools/packs/dnd5e/data/cantrips.js +40 -0
  186. package/dist-sdk/server/src/tools/packs/dnd5e/data/feats.d.ts +33 -0
  187. package/dist-sdk/server/src/tools/packs/dnd5e/data/feats.js +19 -0
  188. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.d.ts +37 -0
  189. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.generated.d.ts +17 -0
  190. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.generated.js +17 -0
  191. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.js +27 -0
  192. package/dist-sdk/server/src/tools/packs/dnd5e/data/kits.d.ts +36 -0
  193. package/dist-sdk/server/src/tools/packs/dnd5e/data/kits.js +32 -0
  194. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.d.ts +32 -0
  195. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.generated.d.ts +13 -0
  196. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.generated.js +13 -0
  197. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.js +18 -0
  198. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.d.ts +54 -0
  199. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.generated.d.ts +13 -0
  200. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.generated.js +13 -0
  201. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.js +20 -0
  202. package/dist-sdk/server/src/tools/packs/dnd5e/data/races.d.ts +36 -0
  203. package/dist-sdk/server/src/tools/packs/dnd5e/data/races.js +18 -0
  204. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.d.ts +29 -0
  205. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.generated.d.ts +13 -0
  206. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.generated.js +13 -0
  207. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.js +21 -0
  208. package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.d.ts +95 -0
  209. package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.js +66 -2
  210. package/dist-sdk/server/src/tools/packs/dnd5e/data/weapons.d.ts +50 -0
  211. package/dist-sdk/server/src/tools/packs/dnd5e/data/weapons.js +28 -0
  212. package/dist-sdk/server/src/tools/packs/dnd5e/engine/bestiary.d.ts +92 -0
  213. package/dist-sdk/server/src/tools/packs/dnd5e/engine/bestiary.js +152 -0
  214. package/dist-sdk/server/src/tools/packs/dnd5e/engine/campaign-items.d.ts +28 -0
  215. package/dist-sdk/server/src/tools/packs/dnd5e/engine/campaign-items.js +29 -0
  216. package/dist-sdk/server/src/tools/packs/dnd5e/engine/cantrips.d.ts +31 -0
  217. package/dist-sdk/server/src/tools/packs/dnd5e/engine/cantrips.js +36 -2
  218. package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.d.ts +261 -0
  219. package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.js +401 -0
  220. package/dist-sdk/server/src/tools/packs/dnd5e/engine/coerce.d.ts +11 -0
  221. package/dist-sdk/server/src/tools/packs/dnd5e/engine/coerce.js +11 -0
  222. package/dist-sdk/server/src/tools/packs/dnd5e/engine/dice.d.ts +65 -0
  223. package/dist-sdk/server/src/tools/packs/dnd5e/engine/dice.js +67 -0
  224. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encounter.d.ts +73 -0
  225. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encounter.js +63 -0
  226. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encumbrance.d.ts +66 -0
  227. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encumbrance.js +59 -0
  228. package/dist-sdk/server/src/tools/packs/dnd5e/engine/feats.d.ts +54 -0
  229. package/dist-sdk/server/src/tools/packs/dnd5e/engine/feats.js +49 -0
  230. package/dist-sdk/server/src/tools/packs/dnd5e/engine/foes.d.ts +42 -0
  231. package/dist-sdk/server/src/tools/packs/dnd5e/engine/foes.js +59 -0
  232. package/dist-sdk/server/src/tools/packs/dnd5e/engine/guides.d.ts +72 -0
  233. package/dist-sdk/server/src/tools/packs/dnd5e/engine/guides.js +63 -0
  234. package/dist-sdk/server/src/tools/packs/dnd5e/engine/items.d.ts +57 -0
  235. package/dist-sdk/server/src/tools/packs/dnd5e/engine/items.js +54 -0
  236. package/dist-sdk/server/src/tools/packs/dnd5e/engine/kits.d.ts +81 -0
  237. package/dist-sdk/server/src/tools/packs/dnd5e/engine/kits.js +85 -0
  238. package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.d.ts +60 -0
  239. package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.js +64 -0
  240. package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.d.ts +169 -0
  241. package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.js +203 -0
  242. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.d.ts +201 -0
  243. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.js +149 -0
  244. package/dist-sdk/server/src/tools/packs/dnd5e/engine/spells.d.ts +56 -0
  245. package/dist-sdk/server/src/tools/packs/dnd5e/engine/spells.js +54 -0
  246. package/dist-sdk/server/src/tools/packs/dnd5e/engine/weapons.d.ts +65 -0
  247. package/dist-sdk/server/src/tools/packs/dnd5e/engine/weapons.js +73 -0
  248. package/dist-sdk/server/src/tools/packs/dnd5e/index.d.ts +18 -0
  249. package/dist-sdk/server/src/tools/packs/dnd5e/index.js +18 -0
  250. package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.d.ts +4 -0
  251. package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.js +116 -1
  252. package/dist-sdk/server/src/tools/packs/dnd5e/tools/class.tool.d.ts +14 -0
  253. package/dist-sdk/server/src/tools/packs/dnd5e/tools/class.tool.js +17 -0
  254. package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.d.ts +1 -0
  255. package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.js +35 -1
  256. package/dist-sdk/server/src/tools/packs/dnd5e/tools/encounter.tool.d.ts +6 -0
  257. package/dist-sdk/server/src/tools/packs/dnd5e/tools/encounter.tool.js +25 -0
  258. package/dist-sdk/server/src/tools/packs/dnd5e/tools/item.tool.d.ts +7 -0
  259. package/dist-sdk/server/src/tools/packs/dnd5e/tools/item.tool.js +13 -0
  260. package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.d.ts +8 -0
  261. package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.js +55 -0
  262. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.d.ts +194 -0
  263. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.js +263 -1
  264. package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.d.ts +1 -0
  265. package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.js +127 -2
  266. package/dist-sdk/server/src/tools/packs/dnd5e/tools/spell.tool.d.ts +13 -0
  267. package/dist-sdk/server/src/tools/packs/dnd5e/tools/spell.tool.js +18 -0
  268. package/dist-sdk/server/src/tools/packs/dnd5e/tools/state.tools.d.ts +1 -0
  269. package/dist-sdk/server/src/tools/packs/dnd5e/tools/state.tools.js +23 -0
  270. package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.d.ts +1 -0
  271. package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.js +35 -0
  272. package/dist-sdk/server/src/tools/packs/index.d.ts +49 -0
  273. package/dist-sdk/server/src/tools/packs/index.js +66 -0
  274. package/dist-sdk/server/src/tools/shared/coerce.d.ts +95 -0
  275. package/dist-sdk/server/src/tools/shared/coerce.js +98 -0
  276. package/dist-sdk/server/src/tools/tool-execution.service.d.ts +107 -3
  277. package/dist-sdk/server/src/tools/tool-execution.service.js +163 -19
  278. package/dist-sdk/server/src/tools/tool-store.service.d.ts +11 -0
  279. package/dist-sdk/server/src/tools/tool-store.service.js +13 -1
  280. package/dist-sdk/shared/types/app.types.d.ts +328 -13
  281. package/dist-sdk/shared/types/app.types.js +18 -1
  282. package/package.json +167 -168
  283. package/data/common/config/random_words.txt +0 -2241
  284. package/data/common/story_ideas/biblical.json +0 -122
  285. package/data/common/story_ideas/fantasy.json +0 -82
  286. package/data/common/story_ideas/historical_fiction.json +0 -82
  287. package/data/common/story_ideas/science_fiction.json +0 -82
  288. package/docs/.nojekyll +0 -1
  289. package/docs/assets/hierarchy.js +0 -1
  290. package/docs/assets/highlight.css +0 -113
  291. package/docs/assets/icons.js +0 -18
  292. package/docs/assets/icons.svg +0 -1
  293. package/docs/assets/main.js +0 -60
  294. package/docs/assets/navigation.js +0 -1
  295. package/docs/assets/search.js +0 -1
  296. package/docs/assets/style.css +0 -1648
  297. package/docs/classes/Agent.html +0 -801
  298. package/docs/classes/Briyah.html +0 -296
  299. package/docs/classes/BriyahConfigService.html +0 -119
  300. package/docs/classes/NativeToolRegistry.html +0 -166
  301. package/docs/classes/PackInstantiationService.html +0 -157
  302. package/docs/classes/PackService.html +0 -247
  303. package/docs/classes/Room.html +0 -1434
  304. package/docs/classes/RoomMessage.html +0 -290
  305. package/docs/enums/MessageAction.html +0 -136
  306. package/docs/functions/availableToolPacks.html +0 -41
  307. package/docs/functions/buildMarkdown.html +0 -54
  308. package/docs/functions/dnd5eTools.html +0 -44
  309. package/docs/functions/installToolPacks.html +0 -51
  310. package/docs/functions/pageMarker.html +0 -45
  311. package/docs/functions/registerToolPacks.html +0 -54
  312. package/docs/functions/splitMarkdownIntoPages.html +0 -51
  313. package/docs/functions/stripWrappingFence.html +0 -52
  314. package/docs/hierarchy.html +0 -46
  315. package/docs/index.html +0 -595
  316. package/docs/interfaces/AgentCreationOptions.html +0 -125
  317. package/docs/interfaces/AgentInfo.html +0 -218
  318. package/docs/interfaces/AgentMessagesResponse.html +0 -74
  319. package/docs/interfaces/AppService.html +0 -3340
  320. package/docs/interfaces/Artifact.html +0 -95
  321. package/docs/interfaces/ArtifactMetadata.html +0 -112
  322. package/docs/interfaces/ArtifactWriteOptions.html +0 -90
  323. package/docs/interfaces/AttachDocumentResponse.html +0 -62
  324. package/docs/interfaces/BriyahConfigOptions.html +0 -124
  325. package/docs/interfaces/ChapterInfo.html +0 -62
  326. package/docs/interfaces/Character.html +0 -86
  327. package/docs/interfaces/ConversionAgent.html +0 -78
  328. package/docs/interfaces/CreateAgentResponse.html +0 -56
  329. package/docs/interfaces/CreateRoomResponse.html +0 -62
  330. package/docs/interfaces/CreateStoryResponse.html +0 -56
  331. package/docs/interfaces/FileList.html +0 -56
  332. package/docs/interfaces/FileMetadata.html +0 -89
  333. package/docs/interfaces/IConfigService.html +0 -79
  334. package/docs/interfaces/InstantiateModels.html +0 -64
  335. package/docs/interfaces/InstantiateRoomResult.html +0 -70
  336. package/docs/interfaces/LoadedPack.html +0 -131
  337. package/docs/interfaces/LoggingOptions.html +0 -92
  338. package/docs/interfaces/Message.html +0 -84
  339. package/docs/interfaces/ModelChoice.html +0 -73
  340. package/docs/interfaces/ModelInfo.html +0 -74
  341. package/docs/interfaces/NativeToolDefinition.html +0 -107
  342. package/docs/interfaces/PackAgentTemplate.html +0 -101
  343. package/docs/interfaces/PackRoomTemplate.html +0 -108
  344. package/docs/interfaces/PackView.html +0 -172
  345. package/docs/interfaces/PdfConversionOptions.html +0 -102
  346. package/docs/interfaces/PdfConversionResult.html +0 -97
  347. package/docs/interfaces/PdfMarkdownOptions.html +0 -198
  348. package/docs/interfaces/PdfMarkdownResult.html +0 -106
  349. package/docs/interfaces/PdfPageMarkdown.html +0 -94
  350. package/docs/interfaces/PreparedPromptResponse.html +0 -62
  351. package/docs/interfaces/ProcessTextResponse.html +0 -86
  352. package/docs/interfaces/PromptFile.html +0 -70
  353. package/docs/interfaces/PromptFileContent.html +0 -76
  354. package/docs/interfaces/PromptFilesResponse.html +0 -56
  355. package/docs/interfaces/PromptFolder.html +0 -80
  356. package/docs/interfaces/PromptFolderDefaults.html +0 -155
  357. package/docs/interfaces/PromptFolderDefaultsResponse.html +0 -79
  358. package/docs/interfaces/PromptFoldersResponse.html +0 -56
  359. package/docs/interfaces/RoomDetails.html +0 -151
  360. package/docs/interfaces/RoomErrorUpdate.html +0 -82
  361. package/docs/interfaces/RoomInfo.html +0 -88
  362. package/docs/interfaces/RoomMessageUpdate.html +0 -113
  363. package/docs/interfaces/RoomMessagesResponse.html +0 -62
  364. package/docs/interfaces/SendMessageResult.html +0 -62
  365. package/docs/interfaces/StoryErrorEvent.html +0 -84
  366. package/docs/interfaces/StoryIdea.html +0 -74
  367. package/docs/interfaces/StoryInfo.html +0 -198
  368. package/docs/interfaces/StoryIntroduceCharacterEvent.html +0 -79
  369. package/docs/interfaces/StoryProgressChapterEvent.html +0 -72
  370. package/docs/interfaces/StoryState.html +0 -108
  371. package/docs/interfaces/StoryStateEvent.html +0 -76
  372. package/docs/interfaces/ToolArtifact.html +0 -85
  373. package/docs/interfaces/ToolCaller.html +0 -77
  374. package/docs/interfaces/ToolDefinition.html +0 -80
  375. package/docs/interfaces/ToolHelpers.html +0 -105
  376. package/docs/interfaces/ToolPackDocuments.html +0 -100
  377. package/docs/interfaces/ToolParameter.html +0 -74
  378. package/docs/interfaces/ToolRoomAccess.html +0 -260
  379. package/docs/interfaces/ToolSummary.html +0 -74
  380. package/docs/interfaces/ToolsResponse.html +0 -68
  381. package/docs/interfaces/Transaction.html +0 -104
  382. package/docs/interfaces/TransactionHistoryResponse.html +0 -62
  383. package/docs/modules.html +0 -53
  384. package/docs/types/PackOrigin.html +0 -34
  385. package/docs/types/PromptScope.html +0 -34
  386. package/docs/types/RoomTurnMode.html +0 -42
  387. package/docs/types/RoomUpdate.html +0 -36
  388. package/docs/types/RosterOverrides.html +0 -42
  389. package/docs/types/ToolContext.html +0 -40
  390. package/docs/types/ToolRunResult.html +0 -34
  391. package/src/tools/packs/dnd5e/README.md +0 -867
@@ -8,22 +8,88 @@ const nickname_1 = require("./nickname");
8
8
  const crypto_1 = require("crypto");
9
9
  const errors_1 = require("../common/errors");
10
10
  const logger_1 = require("../common/logger");
11
+ /**
12
+ * A Room that contains agents
13
+ */
14
+ /**
15
+ * Cap on a description written through {@link ToolRoomAccess.setDescription}. Every
16
+ * agent's description sits in every other agent's cached prompt, so this is a
17
+ * guard against one tool call inflating the whole room's per-turn cost.
18
+ */
11
19
  const MAX_DESCRIPTION_CHARS = 500;
20
+ /**
21
+ * Cap on a nickname set through {@link ToolRoomAccess.renameAgent}. Long enough for
22
+ * "Thorin Oakenshield" and short enough that it cannot be used to smuggle prose
23
+ * into the roster, which every agent carries.
24
+ */
12
25
  const MAX_NICKNAME_CHARS = 40;
13
26
  class Room {
27
+ /**
28
+ * Maximum EXECUTE/PUBLISH chain length within a single agent turn.
29
+ *
30
+ * A backstop against an agent looping on its tools forever, not a budget. Five
31
+ * was too tight for anything with real bookkeeping: a single round of combat runs
32
+ * a spell lookup, a resource spend, the attack and damage rolls, the hit point
33
+ * change and then the narration, and a character build runs create, read and
34
+ * patch before the hand-back. Half of one campaign's Dungeon Master turns hit the
35
+ * limit, and hitting it is expensive in its own right — the turn is re-prompted,
36
+ * the work is often redone, and a person has to notice and say "carry on".
37
+ *
38
+ * Raise it with `ROOM_MAX_TOOL_ITERATIONS`. Read per turn so it can be retuned on
39
+ * a running server, and floored at 1 so a nonsense value cannot stop every agent
40
+ * from acting.
41
+ *
42
+ * @returns The number of tool calls an agent may chain in one turn
43
+ */
14
44
  static maxToolIterations() {
15
45
  const configured = Number(process.env.ROOM_MAX_TOOL_ITERATIONS);
16
46
  return Number.isFinite(configured) && configured > 0 ? Math.floor(configured) : 30;
17
47
  }
48
+ /** What an agent is told when it is prompted again because it still holds the floor. */
18
49
  static CONTINUE_NOTE = 'From system: You still have the floor. Carry on from where you stopped, and address whoever should act next when you are ready to hand it on.';
50
+ /**
51
+ * How many times in a row an agent may be handed the floor back to itself.
52
+ *
53
+ * A self-loop normally means a stuck room, which is why both routing paths broke
54
+ * one unconditionally. But an agent sometimes genuinely still holds the floor: a
55
+ * Battle Master running consecutive monster turns has nobody to address — a
56
+ * monster's turn has no addressee — and when every player character is unconscious
57
+ * there is no player to hand to either. That is exactly where one campaign stalled,
58
+ * needing a person to type "Marshal, continue" seven times in one fight.
59
+ *
60
+ * So the loop is allowed, and bounded. Three is enough for a few rounds of a fight
61
+ * nobody is awake for, and short enough that a genuinely stuck agent is stopped
62
+ * before it costs much. Raise it with `ROOM_MAX_SELF_CONTINUES`.
63
+ *
64
+ * @returns The number of consecutive self-addressed turns permitted
65
+ */
19
66
  static maxSelfContinues() {
20
67
  const configured = Number(process.env.ROOM_MAX_SELF_CONTINUES);
21
68
  return Number.isFinite(configured) && configured >= 0 ? Math.floor(configured) : 3;
22
69
  }
70
+ /**
71
+ * How many stalled turns in a row the room may re-route before it gives up.
72
+ *
73
+ * Counted since the last word actually said, not since the room opened: any
74
+ * audible message resets it, so a table that stalls once an hour never runs out.
75
+ * The cap exists for the case where re-routing cannot help — every agent in turn
76
+ * declining the same message — and the room would otherwise pay a moderator call
77
+ * per attempt forever with nobody at the keyboard to stop it.
78
+ *
79
+ * Raise it with `ROOM_MAX_STALL_RECOVERIES`; zero switches recovery off.
80
+ *
81
+ * @returns The number of consecutive recoveries permitted
82
+ */
23
83
  static maxStallRecoveries() {
24
84
  const configured = Number(process.env.ROOM_MAX_STALL_RECOVERIES);
25
85
  return Number.isFinite(configured) && configured >= 0 ? Math.floor(configured) : 3;
26
86
  }
87
+ /**
88
+ * What the moderator is told when it is asked to re-route a stalled message.
89
+ * @param sender Who sent the message nobody answered
90
+ * @param declined Everyone that has already been asked to answer it
91
+ * @returns A note for the moderator's transient prompt
92
+ */
27
93
  static rerouteNote(sender, declined) {
28
94
  const names = Room.listNames(declined);
29
95
  return [
@@ -34,10 +100,27 @@ class Room {
34
100
  `Do not name ${sender}, and do not name ${names} again.`,
35
101
  ].join(' ');
36
102
  }
103
+ /**
104
+ * What the re-routed agent is told, so it can tell this from being handed a
105
+ * message it has already seen answered.
106
+ * @param sender Who sent the message
107
+ * @param declined Everyone that was asked before it
108
+ * @returns A system note for the agent's history
109
+ */
37
110
  static rerouteHandoffNote(sender, declined) {
38
111
  return (`From system: ${sender}'s message above was given to ${Room.listNames(declined)}, ` +
39
112
  `who did not answer it. It is meant for you. Answer it now.`);
40
113
  }
114
+ /**
115
+ * What the sender is told when its own unanswered message comes back to it.
116
+ *
117
+ * The last resort, and at a game table not a rare one: the leader is usually the
118
+ * one who addressed the wrong agent, so it is both the sender and the fallback.
119
+ * Being told to try again is a real recovery — it is the only agent that knows
120
+ * who the message was meant for.
121
+ * @param declined Everyone that was asked and did not answer
122
+ * @returns A system note for the sender's history
123
+ */
41
124
  static retryHandoffNote(declined) {
42
125
  return (`From system: your message above was given to ${Room.listNames(declined)}, who did ` +
43
126
  `not answer it, and nobody else here can take it. Carry on, and address whoever ` +
@@ -51,6 +134,16 @@ class Room {
51
134
  roomLeader;
52
135
  turnMode = 'broadcast';
53
136
  moderator = '';
137
+ /**
138
+ * Who heard the message the moderator routed last, told to the moderator on its
139
+ * next turn.
140
+ *
141
+ * What makes a conversation with a sub-group hold together: speak to three of six
142
+ * agents, and the follow-up should reach the same three rather than whoever the
143
+ * moderator reconstructs from a 16-message history. Kept in memory only — losing
144
+ * it across a restart costs one turn of continuity, which is not worth persisting
145
+ * for.
146
+ */
54
147
  lastModeratedAudience = [];
55
148
  roomMessages = [];
56
149
  pendingMessages;
@@ -60,27 +153,68 @@ class Room {
60
153
  isAdjourned = false;
61
154
  processingInProgress = true;
62
155
  isPaused = false;
63
- currentSpeaker = null;
156
+ currentSpeaker = null; // Track whose turn it is to speak
157
+ /** The agent currently keeping the floor by addressing itself, if any. */
64
158
  selfContinuingAgent = null;
159
+ /** How many turns in a row {@link selfContinuingAgent} has held it. */
65
160
  consecutiveSelfContinues = 0;
161
+ /**
162
+ * The last audible message this room asked somebody to answer, and who was
163
+ * asked. Read only by {@link recoverStalledFloor}. In memory only: a restart
164
+ * ends any turn that was in flight, so there is nothing left to re-route.
165
+ */
66
166
  lastDispatch = null;
167
+ /** Consecutive stalls re-routed since the last word said. See {@link maxStallRecoveries}. */
67
168
  stallRecoveries = 0;
68
169
  isPublished = false;
69
170
  isLoading = false;
70
171
  onStateChangeCallbacks = new Map();
71
172
  onErrorCallbacks = new Map();
72
- currentSituation = '';
73
- currentSituationTime = '';
74
- onSituationUpdate;
173
+ currentSituation = ''; // Current story situation (for story rooms with moderator)
174
+ currentSituationTime = ''; // Current in-story time (24-hour "HH:MM"), kept separate from the situation text
175
+ onSituationUpdate; // Callback for situation changes
75
176
  onModeratorResponseCallback;
76
- templateRoomId;
177
+ templateRoomId; // NEW: Links published instance to template
178
+ /** The pack this room is filed under. See {@link RoomConfig.pack}. */
77
179
  pack;
180
+ /** The pack template's key, when this room came from one. */
78
181
  packRoomKey;
182
+ /** What Begin sends to the leader. See {@link RoomConfig.beginInstruction}. */
183
+ beginInstruction = '';
184
+ /** Which image_models.json entry draws this room. See {@link RoomConfig.imageModel}. */
185
+ imageModel;
186
+ /** When the room illustrates itself. See {@link RoomConfig.illustrationMode}. */
187
+ illustrationMode = 'on-request';
188
+ /**
189
+ * Agents that work for this room but never take a turn in it: the illustrator
190
+ * and the two artists.
191
+ *
192
+ * Kept out of `agents` deliberately. In broadcast turn mode `selectResponders`
193
+ * returns every agent in the room, so a member illustrator would be prompted
194
+ * on every message. They are here only so their spend is counted — see
195
+ * {@link totalCost}.
196
+ */
197
+ attachedAgents = [];
198
+ // Persistence
79
199
  storageDir;
80
- roomStoreService;
200
+ roomStoreService; // Reference to RoomStoreService for self-persistence
201
+ // User-defined tools (set via setToolServices; absent in tests that construct Room directly)
81
202
  toolStoreService;
82
203
  toolExecutionService;
204
+ // Opaque, host-supplied context for the current interaction, threaded to any
205
+ // tool an agent invokes. In-memory only — never serialized to disk.
83
206
  currentToolContext = undefined;
207
+ // Draws this room's pictures. Absent in tests that construct Room directly, and
208
+ // in an SDK host that wired none.
209
+ illustrationService;
210
+ /**
211
+ * Images each agent has asked for during its current turn, keyed by nickname.
212
+ * An image costs real money and takes minutes, so an agent gets one per turn;
213
+ * `runAgentTurn` clears its entry as the turn begins.
214
+ */
215
+ imagesThisTurn = new Map();
216
+ /** One picture per agent per turn. */
217
+ static IMAGES_PER_TURN = 1;
84
218
  constructor(id, name, goal, baseRoomDir = '', storageDir = '', roomStoreService = null) {
85
219
  this.name = name;
86
220
  this.goal = goal;
@@ -88,7 +222,7 @@ class Room {
88
222
  this.storageDir = storageDir;
89
223
  this.roomStoreService = roomStoreService;
90
224
  this.createdAt = new Date();
91
- this.processingInProgress = true;
225
+ this.processingInProgress = true; // Call ready() when room is ready to use
92
226
  this.id = id ? id : (0, crypto_1.randomUUID)();
93
227
  this.isLoading = false;
94
228
  }
@@ -132,32 +266,109 @@ class Room {
132
266
  setTemplateRoomId(templateId) {
133
267
  this.templateRoomId = templateId;
134
268
  }
269
+ /** @returns The pack this room is filed under, or undefined when it is not filed */
135
270
  getPack() {
136
271
  return this.pack;
137
272
  }
273
+ /**
274
+ * Files this room under a pack, or clears it.
275
+ * @param pack The pack name; empty or undefined clears it
276
+ */
138
277
  setPack(pack) {
139
278
  this.pack = pack || undefined;
140
279
  }
280
+ /** @returns The pack template's key, when this room came from one */
141
281
  getPackRoomKey() {
142
282
  return this.packRoomKey;
143
283
  }
144
284
  setPackRoomKey(key) {
145
285
  this.packRoomKey = key || undefined;
146
286
  }
287
+ /** @returns What Begin sends, or '' when this room offers no Begin */
288
+ getBeginInstruction() {
289
+ return this.beginInstruction;
290
+ }
291
+ /**
292
+ * Sets what Begin sends to the room leader.
293
+ *
294
+ * Normalized to '' rather than left undefined, the same way `getModerator()`
295
+ * normalizes: a settings snapshot read from a room that was never given one
296
+ * must equal a snapshot of a room that was given a blank one, or the
297
+ * round-trip through {@link RoomStoreService.applyRoomSettings} is not one.
298
+ * @param instruction The instruction; empty or undefined clears it
299
+ */
300
+ setBeginInstruction(instruction) {
301
+ this.beginInstruction = instruction?.trim() || '';
302
+ }
303
+ /** @returns The image_models.json entry name, or undefined to use the env default */
304
+ getImageModel() {
305
+ return this.imageModel;
306
+ }
307
+ setImageModel(model) {
308
+ this.imageModel = model?.trim() || undefined;
309
+ }
310
+ /**
311
+ * @returns When this room illustrates itself. Normalized the way
312
+ * `getModerator()` and `getBeginInstruction()` are, so that a snapshot of a
313
+ * room never given one equals a snapshot of a room given the default.
314
+ */
315
+ getIllustrationMode() {
316
+ return this.illustrationMode;
317
+ }
318
+ setIllustrationMode(mode) {
319
+ this.illustrationMode = mode || 'on-request';
320
+ }
321
+ /**
322
+ * Registers an agent that works for this room without ever taking a turn.
323
+ * Idempotent, since the illustration service resolves its agents on every call.
324
+ * @param agent The off-roster agent whose spend belongs to this room
325
+ */
326
+ attachAgent(agent) {
327
+ if (!agent)
328
+ return;
329
+ if (this.attachedAgents.some((a) => a.id === agent.id))
330
+ return;
331
+ this.attachedAgents.push(agent);
332
+ }
333
+ /** @returns The off-roster agents, e.g. for cleanup when the room is deleted */
334
+ getAttachedAgents() {
335
+ return [...this.attachedAgents];
336
+ }
337
+ /**
338
+ * What this room has cost so far.
339
+ *
340
+ * The one place that knows the illustrator and artists are not in `agents`.
341
+ * Callers that used to reduce over `getAgents()` must use this instead, or
342
+ * image spend is invisible.
343
+ */
344
+ totalCost() {
345
+ return [...this.agents, ...this.attachedAgents].reduce((sum, agent) => sum + (agent.totalCost || 0), 0);
346
+ }
147
347
  clearRoomMessages() {
148
348
  this.roomMessages = [];
149
349
  this.roomStoreService.clearRoomMessages(this.id, this.storageDir);
150
350
  }
351
+ /**
352
+ * Adds an agent to the room
353
+ * @param agent The agent to add
354
+ * @returns True if the agent was added, false if it was already in the room
355
+ */
151
356
  arrive(agent) {
357
+ // Check if an agent with the same nickname is already in the room
152
358
  if (this.agents.some((a) => a.agentNickname === agent.agentNickname)) {
153
359
  return false;
154
360
  }
361
+ // Add the agent to the room
155
362
  this.agents.push(agent);
156
363
  return true;
157
364
  }
158
365
  getAgents() {
159
366
  return [...this.agents];
160
367
  }
368
+ /**
369
+ * Replaces all agents in the room with new agents
370
+ * @param newAgents Array of agents to set
371
+ */
161
372
  setAgents(newAgents) {
162
373
  this.agents = [];
163
374
  for (const agent of newAgents) {
@@ -173,6 +384,7 @@ class Room {
173
384
  getRoomLeader() {
174
385
  if (this.roomLeader)
175
386
  return this.roomLeader;
387
+ // Return empty string if no agents
176
388
  if (this.agents.length > 0 && this.agents[0]) {
177
389
  return this.agents[0].agentNickname || '';
178
390
  }
@@ -181,34 +393,74 @@ class Room {
181
393
  getTurnMode() {
182
394
  return this.turnMode;
183
395
  }
396
+ /**
397
+ * Sets how the room chooses who responds to a message. See {@link RoomTurnMode}.
398
+ * @param mode The turn mode; anything unrecognized falls back to 'broadcast'
399
+ */
184
400
  setTurnMode(mode) {
185
401
  this.turnMode = mode === 'directed' ? 'directed' : 'broadcast';
186
402
  }
403
+ /** @returns The configured moderator nickname, or '' when none is set */
187
404
  getModerator() {
188
405
  return this.moderator || '';
189
406
  }
407
+ /**
408
+ * Names the agent that places messages the room cannot route mechanically.
409
+ * @param agentNickname The moderator's nickname; empty clears it
410
+ */
190
411
  setModerator(agentNickname) {
191
412
  this.moderator = agentNickname || '';
192
413
  }
193
414
  getAgentCount() {
194
415
  return this.agents.length;
195
416
  }
417
+ // Allow messages processing in the room after creation or adjournment
196
418
  ready() {
197
419
  if (this.isAdjourned || this.processingInProgress) {
198
420
  this.isAdjourned = false;
421
+ // The human opens the conversation, so they start with the floor. With
422
+ // no human — including a room that has no agents yet — the floor is
423
+ // nobody's: an empty nickname is not null, and would be read as someone
424
+ // else holding it, refusing the first player to arrive.
199
425
  this.endTurn({ to: this.getHumanAgentName() || null });
200
426
  }
201
427
  }
428
+ // Get current speaker (whose turn it is)
202
429
  getCurrentSpeaker() {
203
430
  return this.currentSpeaker;
204
431
  }
432
+ // Set current speaker (called by moderator when routing messages)
205
433
  setCurrentSpeaker(agentNickname) {
206
434
  this.currentSpeaker = agentNickname;
207
435
  this.notifyStateChange();
208
436
  }
437
+ // Check if it's a specific agent's turn
209
438
  isAgentsTurn(agentNickname) {
210
439
  return this.currentSpeaker === agentNickname;
211
440
  }
441
+ /**
442
+ * Ends the room's turn: drops the processing lock, settles who holds the floor,
443
+ * and optionally keeps draining the queue.
444
+ *
445
+ * Every path that finishes a turn goes through here. It used to be open-coded
446
+ * at fifteen sites, and the omissions were the bug: the main responder loop
447
+ * released the lock without giving up the floor, so any turn that ended without
448
+ * producing a message pinned the floor to an agent forever and the human could
449
+ * never speak again. Two more sites had the same gap.
450
+ *
451
+ * The invariant it exists to hold: **once no turn is in flight, the floor is
452
+ * either nobody's or the human's.** An AI agent holding it with nothing running
453
+ * is a dead room.
454
+ *
455
+ * In a directed room that invariant is only half of it. The floor being nobody's
456
+ * with nothing queued is a dead room too, because in directed mode the floor is a
457
+ * baton: one agent is prompted, and the room only moves on if that agent's turn
458
+ * produces an audible message. {@link recoverStalledFloor} closes that half, and
459
+ * runs here so that every path ending a turn is covered rather than the handful
460
+ * anyone thought to guard.
461
+ * @param floor Who holds the floor now — see {@link FloorHandover}
462
+ * @param opts.drain True to keep processing anything queued
463
+ */
212
464
  endTurn(floor, opts = {}) {
213
465
  if (floor === 'release') {
214
466
  this.currentSpeaker = null;
@@ -217,12 +469,44 @@ class Room {
217
469
  this.currentSpeaker = floor.to ?? null;
218
470
  }
219
471
  this.processingInProgress = false;
472
+ // One notification, after both fields settle. The old code released the
473
+ // lock, notified, then set the speaker and notified again, which briefly
474
+ // published "no turn running" alongside a speaker that had already moved on.
220
475
  this.notifyStateChange();
221
476
  if (opts.drain && this.pendingMessages && this.pendingMessages.length > 0) {
222
477
  this.processPendingMessages();
223
478
  }
479
+ // After the drain, so a queue with anything left in it is not mistaken for a
480
+ // room with nothing to do.
224
481
  this.recoverStalledFloor();
225
482
  }
483
+ /**
484
+ * Puts the floor back in somebody's hands when a directed turn ended without a
485
+ * word said.
486
+ *
487
+ * The stall this exists for: a message is addressed to the wrong agent, that
488
+ * agent answers with a `think` — reasonably, since the message was not for it —
489
+ * and a thought prompts nobody. The turn ends, the floor is released, the queue
490
+ * is empty and the room sits there. A `think` is only the commonest way in; a
491
+ * turn that fails, returns nothing, or spends itself on tool calls leaves the
492
+ * room in exactly the same state, which is why this guards the state rather than
493
+ * the action that produced it.
494
+ *
495
+ * **In a directed room, an empty queue with the floor held by nobody is always a
496
+ * stall.** A message meant for a person hands them the floor by name, so a
497
+ * released floor is never "waiting for the human" — it is nobody's turn at all.
498
+ *
499
+ * Recovery is the moderator's existing job: it is handed the unanswered message
500
+ * and asked who should have answered it. Nothing about the stall reaches the
501
+ * transcript — the message has already been logged and heard once, and a second
502
+ * copy of it, or a note about the plumbing, is not part of the story.
503
+ *
504
+ * Needs a moderator that was actually configured. {@link getModeratorAgent} falls
505
+ * back to the first non-player agent, which at a game table is the Dungeon Master
506
+ * — asking it to route its own unanswered message is the confusion this is
507
+ * supposed to end, so a room without a moderator keeps the old behaviour and
508
+ * waits for a person.
509
+ */
226
510
  recoverStalledFloor() {
227
511
  if (this.turnMode !== 'directed')
228
512
  return;
@@ -246,6 +530,8 @@ class Room {
246
530
  }
247
531
  this.stallRecoveries += 1;
248
532
  logger_1.logger.warn(`Room ${this.name}: nobody answered ${dispatch.message.getSender()} and the room has gone quiet; asking ${moderator.agentNickname} to re-route (attempt ${this.stallRecoveries} of ${Room.maxStallRecoveries()})`);
533
+ // Held for the whole re-route, so a human message arriving mid-flight queues
534
+ // behind it instead of racing the moderator call.
249
535
  this.processingInProgress = true;
250
536
  this.notifyStateChange();
251
537
  void this.rerouteStalledTurn(dispatch, moderator).catch((error) => {
@@ -253,12 +539,30 @@ class Room {
253
539
  this.endTurn('release', { drain: true });
254
540
  });
255
541
  }
542
+ /**
543
+ * The moderator this room was configured with, and only that one.
544
+ *
545
+ * Unlike {@link getModeratorAgent} there is no fallback: a caller that needs a
546
+ * genuine moderator would rather have none than the room leader.
547
+ * @returns The configured moderator agent, or undefined
548
+ */
256
549
  configuredModerator() {
257
550
  if (!this.moderator)
258
551
  return undefined;
259
552
  return this.agents.find((a) => !a.isControlledByHuman &&
260
553
  this.checkAgentNicknameMatch(a.agentNickname, this.moderator));
261
554
  }
555
+ /**
556
+ * Asks the moderator who should have answered a message nobody did, then gives
557
+ * that agent the floor.
558
+ *
559
+ * The message itself is not re-logged and not re-delivered: everyone who could
560
+ * hear it already did, on its first pass. Only the chosen agent is touched, with
561
+ * a note saying why it is being asked — without one it cannot tell this from
562
+ * being handed something it has already watched somebody else answer.
563
+ * @param dispatch The unanswered message and everyone already asked
564
+ * @param moderator The room's configured moderator
565
+ */
262
566
  async rerouteStalledTurn(dispatch, moderator) {
263
567
  const stalled = dispatch.message;
264
568
  let named;
@@ -275,9 +579,13 @@ class Room {
275
579
  this.endTurn('release', { drain: true });
276
580
  return;
277
581
  }
582
+ // Only when it could not have heard the message the first time — a whisper it
583
+ // was not part of. Delivering one it already has would double it in history.
278
584
  if (!stalled.canHear(responder.agentNickname)) {
279
585
  this.deliverModerated(responder, stalled, stalled.getContent());
280
586
  }
587
+ // Remembered before the turn runs, so a responder that also declines is not
588
+ // asked again on the next recovery.
281
589
  this.lastDispatch = {
282
590
  message: stalled,
283
591
  responders: [...dispatch.responders, responder.agentNickname],
@@ -293,6 +601,8 @@ class Room {
293
601
  : Room.rerouteHandoffNote(stalled.getSender(), dispatch.responders), false);
294
602
  responder.save();
295
603
  this.setCurrentSpeaker(responder.agentNickname);
604
+ // Prompted directly rather than through `perceive`, which would record the
605
+ // message in its history a second time.
296
606
  this.getAgentAiResponse(responder, stalled, (message) => {
297
607
  if (this.isPaused) {
298
608
  this.endTurn('keep');
@@ -302,6 +612,23 @@ class Room {
302
612
  this.endTurn('release', { drain: true });
303
613
  });
304
614
  }
615
+ /**
616
+ * Picks the agent a re-routed message goes to.
617
+ *
618
+ * Three candidates, in order: whoever the moderator named, the room leader — the
619
+ * same contract {@link handleModeratorResponse} works to — and finally the sender
620
+ * itself, told to try again. Everyone that has already declined the message is
621
+ * skipped at each step, and so is the moderator, which never answers.
622
+ *
623
+ * The sender is last rather than excluded because at a game table it is usually
624
+ * also the leader: the Dungeon Master addresses the wrong player far more often
625
+ * than anyone else does, so excluding it would leave the commonest stall with
626
+ * nowhere to go.
627
+ * @param named The nickname the moderator answered with, if any
628
+ * @param dispatch The unanswered message and everyone already asked
629
+ * @param moderator The moderator that was consulted
630
+ * @returns The agent to give the floor to, or undefined if there is nobody left
631
+ */
305
632
  resolveRerouteResponder(named, dispatch, moderator) {
306
633
  const excluded = [moderator.agentNickname, ...dispatch.responders];
307
634
  const eligible = (agent) => !excluded.some((name) => this.checkAgentNicknameMatch(agent.agentNickname, name));
@@ -322,6 +649,15 @@ class Room {
322
649
  const author = this.agents.find((a) => this.checkAgentNicknameMatch(a.agentNickname, sender));
323
650
  return author && eligible(author) && !author.isControlledByHuman ? author : undefined;
324
651
  }
652
+ /**
653
+ * Files an agent's response from a turn that has just ended.
654
+ *
655
+ * A thought is nobody's message but its own, so it is logged and goes no further.
656
+ * A shout jumps the queue. Anything else joins the back of it — and, being an
657
+ * audible message, is the room making progress, which is what ends a run of
658
+ * stall recoveries.
659
+ * @param message The response, or null if the turn produced nothing
660
+ */
325
661
  queueAgentResponse(message) {
326
662
  if (message === null)
327
663
  return;
@@ -343,23 +679,31 @@ class Room {
343
679
  return { numMessages, numChars };
344
680
  }
345
681
  getLatestRoomMessages(fromIndex = 0, includeThoughts = false) {
682
+ // Filter messages based on fromIndex
346
683
  const messages = this.roomMessages.filter((msg) => msg.index >= fromIndex);
347
684
  if (!includeThoughts) {
685
+ // Hide internal activity: thoughts and tool-execution notices
348
686
  return messages.filter((msg) => msg.action !== app_types_1.MessageAction.THINK && msg.action !== app_types_1.MessageAction.TOOL);
349
687
  }
350
688
  return messages;
351
689
  }
352
690
  setRoomMessages(messages) {
691
+ // Convert string messages to indexed messages
353
692
  this.roomMessages = messages.map((m, idx) => {
354
693
  m.index = idx;
355
694
  return m;
356
695
  });
696
+ // Update the next message index
357
697
  this.nextMessageIndex = this.roomMessages.length;
358
698
  }
359
699
  addRoomMessage(message, options) {
360
700
  message.index = this.nextMessageIndex++;
361
701
  this.roomMessages.push(message);
702
+ // Save new messages to disk incrementally
362
703
  this.saveMessages([message]);
704
+ // Skip the situation callback when the caller has already processed this
705
+ // situation (e.g. the moderator-routing path processes the narrator's
706
+ // situation before moderation, then relays the same message here).
363
707
  if (message.situation && !options?.suppressSituationUpdate) {
364
708
  void this.handleSituationUpdate(message.situation);
365
709
  }
@@ -373,7 +717,9 @@ class Room {
373
717
  return m;
374
718
  });
375
719
  this.roomMessages = this.roomMessages.concat(indexedMessages);
720
+ // Save new messages to disk incrementally
376
721
  this.saveMessages(indexedMessages);
722
+ // Notify that state has changed
377
723
  this.notifyStateChange();
378
724
  }
379
725
  getCreatedAt() {
@@ -382,9 +728,39 @@ class Room {
382
728
  setCreatedAt(date) {
383
729
  this.createdAt = date;
384
730
  }
731
+ /**
732
+ * Gets all artifacts in the room
733
+ * @returns Array of artifacts
734
+ */
385
735
  getArtifacts() {
386
736
  return [...this.artifacts];
387
737
  }
738
+ /**
739
+ * Renames an agent, and everything in this room that named it.
740
+ *
741
+ * A room routes by nickname and nothing else, so an agent whose character is
742
+ * called something different gives every other agent two names for one person.
743
+ * The Dungeon Master addresses the character, the room has never heard of them,
744
+ * and the message falls through to the moderator — see
745
+ * {@link namesNobodyInADirectedRoom}, which exists to catch exactly that and
746
+ * once absorbed about a quarter of a campaign's calls. This is the fix that
747
+ * makes the workaround unnecessary: give the agent the character's name.
748
+ *
749
+ * Expensive in the same way {@link ToolRoomAccess.setDescription} is, and for
750
+ * the same reason: the roster sits in every agent's *cached* prompt prefix, so
751
+ * a rename throws away the whole room's cache. Character creation is the moment
752
+ * for it, because play has not started; mid-scene it is a real cost.
753
+ *
754
+ * **History is deliberately not rewritten.** Past messages are a record of what
755
+ * was said, and rewriting them would mean parsing and re-serializing every
756
+ * entry, with compaction summaries reachable only by regex. Instead every agent
757
+ * is told, once, that the name changed — which is what lets them reconcile a
758
+ * roster that says `Leah` with a history that says `StudentOne`.
759
+ *
760
+ * @param from The agent to rename, matched the way messages are routed
761
+ * @param to The new name — a character name, which may be longer than a nickname
762
+ * @returns What happened, including the reason when nothing did
763
+ */
388
764
  renameAgent(from, to) {
389
765
  const agent = this.agents.find((a) => this.checkAgentNicknameMatch(a.agentNickname, from));
390
766
  if (!agent)
@@ -392,11 +768,20 @@ class Room {
392
768
  const fullName = (to || '').trim().slice(0, MAX_NICKNAME_CHARS);
393
769
  if (!fullName)
394
770
  return { renamed: false, reason: 'invalid' };
771
+ // The room routes on the nickname, so derive it the same way agent creation
772
+ // does: "Leah bat Yosef" seats as `Leah` and keeps the whole thing as its
773
+ // name. Deriving rather than storing the character name whole is what keeps
774
+ // `targets` short enough for a model to spell reliably.
395
775
  const nickname = agent_1.Agent.generateNickname(fullName);
396
776
  const previous = agent.agentNickname;
397
777
  if (previous === nickname && agent.agentName === fullName) {
398
778
  return { renamed: false, reason: 'unchanged', from: previous, to: nickname };
399
779
  }
780
+ // Ambiguity rather than equality: routing matches a first word too, so
781
+ // `Thorin` would reach both "Thorin Oakenshield" and a second Thorin. A
782
+ // clash has to be refused rather than suffixed — a character name is what
783
+ // the player hears out loud, so seating them as "Leah 2" is worse than
784
+ // asking for another name.
400
785
  const clash = this.conflictingNickname(agent, nickname);
401
786
  if (clash) {
402
787
  return {
@@ -409,7 +794,7 @@ class Room {
409
794
  }
410
795
  agent.agentNickname = nickname;
411
796
  agent.agentName = fullName;
412
- agent.save();
797
+ agent.save(); // Persists and pushes the new roster to the client
413
798
  const artifactsUpdated = this.repointNickname(previous, nickname);
414
799
  return {
415
800
  renamed: true,
@@ -419,10 +804,33 @@ class Room {
419
804
  artifactsUpdated,
420
805
  };
421
806
  }
807
+ /**
808
+ * The agent this room would refuse to rename to `nickname`, if any.
809
+ *
810
+ * Separate from {@link renameAgent} so a caller renaming an agent that sits in
811
+ * more than one room can check them all before changing anything — a rename
812
+ * applied to two rooms and refused by a third would leave the agent named one
813
+ * thing and half the rooms pointing at another.
814
+ *
815
+ * @param agent The agent being renamed, excluded from its own check
816
+ * @param nickname The nickname it would take
817
+ * @returns The conflicting agent's nickname, or undefined
818
+ */
422
819
  conflictingNickname(agent, nickname) {
423
820
  const clash = this.agents.find((a) => a !== agent && (0, nickname_1.nicknamesAreAmbiguous)(a.agentNickname, nickname));
424
821
  return clash?.agentNickname;
425
822
  }
823
+ /**
824
+ * Repoints everything in *this room* that named an agent, and tells the room.
825
+ *
826
+ * The room-side half of a rename, split out because an agent may sit in more
827
+ * than one room while its own record is only mutated once. {@link renameAgent}
828
+ * is this plus the agent itself.
829
+ *
830
+ * @param previous The nickname being replaced
831
+ * @param nickname The nickname replacing it
832
+ * @returns How many artifacts changed
833
+ */
426
834
  repointNickname(previous, nickname) {
427
835
  if (!previous || previous === nickname)
428
836
  return 0;
@@ -435,6 +843,17 @@ class Room {
435
843
  this.announceRename(previous, nickname);
436
844
  return artifactsUpdated;
437
845
  }
846
+ /**
847
+ * Repoints every artifact that named the old nickname.
848
+ *
849
+ * `viewers` is the one that fails silently: an artifact keeps working, the agent
850
+ * simply stops being able to see it, so a player loses their own character sheet
851
+ * with nothing logged. `creator` decides attribution and counts as a viewer.
852
+ *
853
+ * @param previous The nickname being replaced
854
+ * @param nickname The nickname replacing it
855
+ * @returns How many artifacts changed
856
+ */
438
857
  renameInArtifacts(previous, nickname) {
439
858
  let changed = 0;
440
859
  for (const artifact of this.artifacts) {
@@ -456,18 +875,56 @@ class Room {
456
875
  }
457
876
  return changed;
458
877
  }
878
+ /**
879
+ * Tells every agent in the room that a name changed.
880
+ *
881
+ * One line each, and the reason the history can be left alone: without it an
882
+ * agent reads `Leah` in the roster and `StudentOne` in its own history with
883
+ * nothing joining the two, which is the confusion the rename exists to remove.
884
+ * The renamed agent is told as well — it is the one most likely to be unsure
885
+ * what it is called.
886
+ */
459
887
  announceRename(previous, nickname) {
460
888
  const note = `[Room] "${previous}" is now known as "${nickname}". Earlier messages use the old name.`;
461
889
  for (const agent of this.agents) {
462
890
  agent.addToConversationHistory(note, false);
463
891
  }
464
892
  }
893
+ /**
894
+ * Checks if the room is currently adjourned
895
+ * @returns True if the room is adjourned, false otherwise
896
+ */
465
897
  isRoomAdjourned() {
466
898
  return this.isAdjourned;
467
899
  }
900
+ /**
901
+ * Sets the room's artifacts (used when loading from storage)
902
+ * @param artifacts Array of artifacts to set
903
+ */
468
904
  setArtifacts(artifacts) {
469
905
  this.artifacts = [...artifacts];
470
906
  }
907
+ /**
908
+ * Whether a message names recipients but none of them is in this room.
909
+ *
910
+ * Only asked of a directed room, where a message is answered by the one agent it
911
+ * names. `selectResponders` cannot place such a message: no target matches, and
912
+ * the leader is skipped when it is the sender — which it is whenever the leader
913
+ * is the one who misnamed someone. What is left is a fallback that widens to
914
+ * *every* other agent, and a directed room exists precisely to avoid that. One
915
+ * campaign spent about a quarter of its calls there, because the Dungeon Master
916
+ * addressed a player by their character's name rather than the nickname the room
917
+ * knows them by.
918
+ *
919
+ * Moderating instead costs one cheap call and is the moderator's documented job:
920
+ * a message that "did not name a recipient the room could use" is routed from its
921
+ * content. A misnamed target is usually a non-player character anyway, and the
922
+ * moderator already knows to hand those to the room leader.
923
+ *
924
+ * @param action The message's normalized action
925
+ * @param targets The names the message was addressed to
926
+ * @returns True when the room should moderate rather than guess
927
+ */
471
928
  namesNobodyInADirectedRoom(action, targets) {
472
929
  if (this.turnMode !== 'directed')
473
930
  return false;
@@ -477,6 +934,12 @@ class Room {
477
934
  return false;
478
935
  return !targets.some((name) => this.agents.some((a) => this.checkAgentNicknameMatch(a.agentNickname, name)));
479
936
  }
937
+ /**
938
+ * Parses AI response into RoomMessage object (private helper moved from Agent)
939
+ * @param agent The agent that made the response
940
+ * @param response Raw AI response object
941
+ * @returns Parsed RoomMessage object
942
+ */
480
943
  parseAgentResponse(agent, response) {
481
944
  let needsModeration = false;
482
945
  let targets = [];
@@ -501,12 +964,19 @@ class Room {
501
964
  needsModeration = true;
502
965
  }
503
966
  else {
967
+ // Normalize action case. LLMs occasionally emit "THINK" / "Speak" etc.
968
+ // despite the schema specifying lowercase enum values; tolerate that
969
+ // rather than dropping the message through the downstream filters.
504
970
  normalizedAction = Room.coerceMessageAction(response.action);
505
971
  if (!normalizedAction) {
506
972
  logger_1.logger.error(`Agent ${agent.agentNickname} produced message with invalid action "${response.action}"; routing through moderator`);
507
973
  needsModeration = true;
508
974
  }
509
975
  else if (response.targets) {
976
+ // A model asked for a list of names sometimes hands back one bare
977
+ // name instead. Everything downstream — the directed-room check,
978
+ // responder selection, `targets.join` in a log line — assumes an
979
+ // array, so coerce here rather than at each of those.
510
980
  targets = Array.isArray(response.targets)
511
981
  ? response.targets
512
982
  : [response.targets];
@@ -519,9 +989,11 @@ class Room {
519
989
  }
520
990
  }
521
991
  }
992
+ // EXECUTE must name the tool to run
522
993
  if (normalizedAction === app_types_1.MessageAction.EXECUTE && (!response.name || !response.name.trim())) {
523
994
  needsModeration = true;
524
995
  }
996
+ // COMMISSION must name at least one target agent
525
997
  if (normalizedAction === app_types_1.MessageAction.COMMISSION && targets.length === 0) {
526
998
  needsModeration = true;
527
999
  }
@@ -531,16 +1003,27 @@ class Room {
531
1003
  }
532
1004
  }
533
1005
  if (needsModeration) {
1006
+ // A message routed to the moderator has to carry text, because a moderator
1007
+ // is going to read it. `content` is initialised from the response itself,
1008
+ // which is the response *object* whenever the reason for moderating was a
1009
+ // failed check on an otherwise well-formed object — and an object reaching
1010
+ // the moderator's string handling throws, which the caller's catch turns
1011
+ // into silence rather than an error.
534
1012
  const moderatedContent = response && typeof response === 'object'
535
1013
  ? (response.content ?? JSON.stringify(response))
536
1014
  : content;
537
1015
  return new message_1.RoomMessage(agent.agentNickname, app_types_1.MessageAction.MODERATE, moderatedContent, [], null, situation);
538
1016
  }
1017
+ // Capture situation if provided (usually from narrator)
539
1018
  situation = response.situation || undefined;
540
1019
  const msg = new message_1.RoomMessage(agent.agentNickname, normalizedAction, response.content, targets, response.name, situation);
541
1020
  if (response.changes && typeof response.changes === 'object') {
542
1021
  msg.changes = response.changes;
543
1022
  }
1023
+ // A moderator may name the action its relayed message should carry. Only
1024
+ // the audible actions are accepted: `think` is nobody's message but the
1025
+ // sender's, and the relay actions would just be the moderator's own answer
1026
+ // again. Anything else is ignored, which leaves the original behaviour.
544
1027
  if (response.relayAs) {
545
1028
  const relayAs = Room.coerceMessageAction(response.relayAs);
546
1029
  const relayable = [
@@ -557,11 +1040,29 @@ class Room {
557
1040
  }
558
1041
  return msg;
559
1042
  }
1043
+ /**
1044
+ * Extracts an opaque "preamble" block from the top of an agent response.
1045
+ *
1046
+ * A preamble is one or more consecutive `<tag>value</tag>` lines at the
1047
+ * very start of the response, terminated by a blank line or non-tag
1048
+ * content. The captured preamble is the verbatim text of those tag
1049
+ * lines, suitable for downstream parsing by whoever owns the semantic
1050
+ * interpretation (e.g. the story service for narrator responses).
1051
+ *
1052
+ * The Room itself never parses the preamble's contents. It just hands
1053
+ * the text to the situation callback so callers (story, debate, etc.)
1054
+ * can interpret it however they want.
1055
+ */
560
1056
  static extractPreamble(response) {
561
1057
  const lines = response.split('\n');
1058
+ // Skip leading blank lines without consuming them from the output.
562
1059
  let i = 0;
563
1060
  while (i < lines.length && lines[i].trim() === '')
564
1061
  i++;
1062
+ // Some providers (e.g. DeepSeek) wrap the whole response in a
1063
+ // ```...``` code fence. Skip a leading fence line so the preamble
1064
+ // detection still finds the tags on the next line. The matching
1065
+ // trailing fence is stripped from the content at the end.
565
1066
  const fenceRe = /^\s*```\w*\s*$/;
566
1067
  const hadLeadingFence = i < lines.length && fenceRe.test(lines[i]);
567
1068
  if (hadLeadingFence)
@@ -576,9 +1077,11 @@ class Room {
576
1077
  j++;
577
1078
  }
578
1079
  const preamble = preambleLines.join('\n');
1080
+ // Skip a single trailing blank line between preamble and content.
579
1081
  if (j < lines.length && lines[j].trim() === '')
580
1082
  j++;
581
1083
  let contentLines = lines.slice(j);
1084
+ // Drop a matching trailing code fence (and any trailing blanks after it).
582
1085
  if (hadLeadingFence) {
583
1086
  let k = contentLines.length - 1;
584
1087
  while (k >= 0 && contentLines[k].trim() === '')
@@ -590,6 +1093,11 @@ class Room {
590
1093
  const content = contentLines.join('\n').trimStart();
591
1094
  return { preamble, content };
592
1095
  }
1096
+ /**
1097
+ * Maps an arbitrary action string to a MessageAction enum value,
1098
+ * accepting any casing. Returns undefined if the value doesn't correspond
1099
+ * to a known action.
1100
+ */
593
1101
  static coerceMessageAction(raw) {
594
1102
  if (typeof raw !== 'string')
595
1103
  return undefined;
@@ -597,6 +1105,22 @@ class Room {
597
1105
  const values = Object.values(app_types_1.MessageAction);
598
1106
  return values.includes(lowered) ? lowered : undefined;
599
1107
  }
1108
+ /**
1109
+ * Determines which character agents are part of a message's audience, so a
1110
+ * perceiving agent can be shown (in the transient situation message) the
1111
+ * descriptions of only the characters it is currently interacting with.
1112
+ *
1113
+ * The audience is taken from the message's `targets` (the moderator fills these
1114
+ * with every agent who can hear the message) plus the message sender. Only
1115
+ * character agents (promptFolder === 'character') are returned; the narrator,
1116
+ * moderator and other support agents are excluded. The perceiving agent is never
1117
+ * included in its own list. When a message has no explicit targets (e.g. a plain
1118
+ * SPEAK broadcast in a non-story room) every character who can hear it is included.
1119
+ *
1120
+ * @param perceivingAgent The agent that will receive these descriptions
1121
+ * @param message The message being perceived
1122
+ * @returns Character agents in the message's audience, excluding the perceiver
1123
+ */
600
1124
  getPresentCharacters(perceivingAgent, message) {
601
1125
  const audienceNames = message.getTargets();
602
1126
  const senderName = message.getSender();
@@ -609,11 +1133,22 @@ class Room {
609
1133
  return true;
610
1134
  if (audienceNames.some((name) => this.checkAgentNicknameMatch(a.agentNickname, name)))
611
1135
  return true;
1136
+ // No explicit targets: fall back to anyone who can hear the message.
612
1137
  if (audienceNames.length === 0 && message.canHear(a.agentNickname))
613
1138
  return true;
614
1139
  return false;
615
1140
  });
616
1141
  }
1142
+ /**
1143
+ * Builds a digest of the other agents' private context (in stories, their
1144
+ * inventory and conditions), for the oversight agents — the moderator and the room
1145
+ * leader (the Narrator in stories) — who need to keep the world consistent. Other
1146
+ * agents never see this; each only sees its own private context. The leader's own
1147
+ * context is left out, since it already receives that directly. Returns an
1148
+ * empty string when nobody else has any private context.
1149
+ *
1150
+ * @returns A markdown block of per-agent private context, or '' if none
1151
+ */
617
1152
  buildCharacterPrivateContextDigest() {
618
1153
  const leader = this.getRoomLeader();
619
1154
  return this.agents
@@ -621,10 +1156,21 @@ class Room {
621
1156
  .map((a) => `### ${a.agentNickname}\n${a.privateContext}`)
622
1157
  .join('\n\n');
623
1158
  }
1159
+ /**
1160
+ * Builds the descriptors of the tools granted to an agent, for rendering into
1161
+ * its perceive prompt. Tool code is never exposed — only name, description and
1162
+ * parameters. Tools that were deleted after being granted are silently dropped.
1163
+ * @param agent The agent whose granted tools to describe
1164
+ * @returns Array of tool descriptors (empty when the agent has no usable tools)
1165
+ */
624
1166
  async buildAvailableTools(agent) {
625
1167
  if (!agent.toolNames || agent.toolNames.length === 0) {
626
1168
  return [];
627
1169
  }
1170
+ // Resolve each granted name native-first (native tools are always available),
1171
+ // then fall back to the user-authored store. Descriptors expose only
1172
+ // name/description/parameters — never handler or code. Names that resolve
1173
+ // to nothing (deleted tool, or authored tools while gated off) are dropped.
628
1174
  const nativeByName = new Map((this.toolExecutionService?.listNativeTools() || []).map((t) => [t.name, t]));
629
1175
  const tools = [];
630
1176
  for (const name of agent.toolNames) {
@@ -633,10 +1179,11 @@ class Room {
633
1179
  tools.push({
634
1180
  name: native.name,
635
1181
  description: native.description,
636
- parameters: native.parameters || [],
1182
+ parameters: Room.describeToolParameters(native.parameters),
637
1183
  });
638
1184
  continue;
639
1185
  }
1186
+ // Only surface authored tools when this deployment allows running them.
640
1187
  if (!this.toolStoreService || !this.toolExecutionService?.userAuthoredToolsEnabled) {
641
1188
  continue;
642
1189
  }
@@ -645,12 +1192,39 @@ class Room {
645
1192
  tools.push({
646
1193
  name: tool.name,
647
1194
  description: tool.description,
648
- parameters: tool.parameters || [],
1195
+ parameters: Room.describeToolParameters(tool.parameters),
649
1196
  });
650
1197
  }
651
1198
  }
652
1199
  return tools;
653
1200
  }
1201
+ /**
1202
+ * Prepares declared parameters for the perceive prompt, pre-joining any
1203
+ * `enum` so the template can render it. See {@link PromptToolParameter}.
1204
+ * @param parameters The tool's declared parameters
1205
+ * @returns The parameters, each with `enumText` when it declares an enum
1206
+ */
1207
+ static describeToolParameters(parameters) {
1208
+ return (parameters || []).map((param) => param.enum && param.enum.length > 0
1209
+ ? { ...param, enumText: param.enum.join(', ') }
1210
+ : param);
1211
+ }
1212
+ /**
1213
+ * Renders an artifact for a prompt, dropping any ```briyah-state fenced
1214
+ * block.
1215
+ *
1216
+ * That fence is the convention for machine state an artifact carries for the
1217
+ * tools that maintain it — a character sheet keeps its whole state object
1218
+ * there, below the human-readable summary. Tools read the artifact directly
1219
+ * and are unaffected; a model never needs it, and pasting a page of raw JSON
1220
+ * into a prompt full of JSON is how a small model loses track of which JSON
1221
+ * it is supposed to be producing.
1222
+ *
1223
+ * An unterminated fence drops everything after it, which is the right
1224
+ * reading: whatever follows an opening state fence is state too.
1225
+ * @param artifact The artifact to render
1226
+ * @returns The prompt-facing text
1227
+ */
654
1228
  static renderArtifactForPrompt(artifact) {
655
1229
  const kept = [];
656
1230
  let inState = false;
@@ -668,10 +1242,20 @@ class Room {
668
1242
  }
669
1243
  return kept.join('\n').replace(/\n{3,}/g, '\n\n').trim();
670
1244
  }
1245
+ /**
1246
+ * Builds the Handlebars variables for an agent's perceive prompt,
1247
+ * including artifacts and the agent's granted tools.
1248
+ * @param agent The agent generating a response
1249
+ * @returns The prompt variables
1250
+ */
671
1251
  async buildPerceiveVariables(agent) {
1252
+ // Prepare variables for the prompt, including artifacts
672
1253
  const visibleArtifacts = this.getVisibleArtifacts(agent.agentNickname)
673
1254
  .map((a) => `${a.name} (by ${a.creator}): ${Room.renderArtifactForPrompt(a)}`)
674
1255
  .join('\n\n');
1256
+ // Name the human-controlled characters. A room can have several players, so
1257
+ // the singular variable names the first for the prompts that assume one, and
1258
+ // the list names them all.
675
1259
  const humanCharacterNames = this.getHumanAgents().map((a) => a.agentNickname);
676
1260
  const humanCharacterName = humanCharacterNames[0] ?? 'Player';
677
1261
  const humanCharacterList = Room.listNames(humanCharacterNames);
@@ -683,18 +1267,36 @@ class Room {
683
1267
  otherAgents: this.agents.filter((a) => a.agentNickname !== agent.agentNickname),
684
1268
  roomLeader: this.getRoomLeader(),
685
1269
  roomGoal: this.getGoal(),
686
- scenario: this.getGoal(),
1270
+ scenario: this.getGoal(), // Alias for story rooms
687
1271
  situation: this.getSituation() || 'Story beginning',
688
1272
  visibleArtifacts: visibleArtifacts,
689
1273
  humanCharacterName: humanCharacterName,
690
- humanAgentName: humanCharacterName,
1274
+ humanAgentName: humanCharacterName, // Alias for moderator
691
1275
  humanCharacterNames: humanCharacterNames,
692
1276
  humanCharacterList: humanCharacterList,
693
- humanAgentList: humanCharacterList,
1277
+ humanAgentList: humanCharacterList, // Alias, as above
694
1278
  maxOutputChars: maxOutputChars,
695
1279
  availableTools: await this.buildAvailableTools(agent),
696
1280
  };
697
1281
  }
1282
+ /**
1283
+ * The names of the artifacts an agent cannot read.
1284
+ *
1285
+ * Volatile by nature: it changes whenever *any* artifact anywhere in the room is
1286
+ * created or deleted, for every agent that cannot read the new one. That put it in
1287
+ * the wrong half of the prompt for a long time. `transient` protects an artifact's
1288
+ * contents and nothing protected the roster, so placing four monsters at the start
1289
+ * of a fight rewrote this string for eight of nine agents and invalidated all eight
1290
+ * cached prefixes. Measured across one session it was 41.7% of the entire
1291
+ * cache-creation spend — and the Battle Master, the one agent that *could* read the
1292
+ * new artifacts, was the only one the fight cost nothing.
1293
+ *
1294
+ * Measured against what the agent can *read*, not against the cached block: a
1295
+ * transient artifact arrives in the per-turn prompt, so naming it here as one the
1296
+ * agent cannot see would be a lie.
1297
+ * @param nickname The agent the list is for
1298
+ * @returns A comma-separated list, or '' when the agent can read everything
1299
+ */
698
1300
  invisibleArtifactNames(nickname) {
699
1301
  const readable = this.getReadableArtifacts(nickname);
700
1302
  return this.getArtifacts()
@@ -702,6 +1304,24 @@ class Room {
702
1304
  .map((a) => a.name)
703
1305
  .join(', ');
704
1306
  }
1307
+ /**
1308
+ * Builds the transient (uncached) prompt message for an agent. It is sent
1309
+ * uncached and is not saved to the agent's history, which makes it the right
1310
+ * place to inject context that changes frequently, so a change never
1311
+ * invalidates the cached prompt instructions:
1312
+ * - the descriptions of the characters present in this message's audience
1313
+ * (each character sees how the others currently look without leaking
1314
+ * details about characters who are elsewhere), and
1315
+ * - the perceiving agent's own private context (e.g. its story inventory
1316
+ * and conditions), which only that agent may see.
1317
+ * The in-story time and situation text lead the transient prompt; the time
1318
+ * is on its own labeled line (see buildSituationHeader).
1319
+ * @param agent The agent that will receive this prompt
1320
+ * @param message The message being perceived, or null for follow-up prompts
1321
+ * within the same turn (e.g. after a tool result), where there is no new
1322
+ * message audience to describe
1323
+ * @returns The transient prompt, or null if there is nothing to inject
1324
+ */
705
1325
  buildTransientPrompt(agent, message) {
706
1326
  let prompt = this.buildSituationHeader() || null;
707
1327
  if (message) {
@@ -714,6 +1334,12 @@ class Room {
714
1334
  prompt = prompt ? `${prompt}\n\n${charactersPresent}` : charactersPresent;
715
1335
  }
716
1336
  }
1337
+ // Artifacts marked transient. They are re-sent whole on every turn and
1338
+ // never cached, which is why they are the right home for small state that
1339
+ // moves constantly — a character sheet whose hit points change each round
1340
+ // would otherwise throw away this agent's cached rule documents on every
1341
+ // write. Placed before the private context so the agent reads its own
1342
+ // state before whatever it privately knows.
717
1343
  const transientArtifacts = this.getTransientArtifacts(agent.agentNickname);
718
1344
  if (transientArtifacts.length > 0) {
719
1345
  const rendered = transientArtifacts
@@ -726,11 +1352,16 @@ class Room {
726
1352
  const privateBlock = `Your private context (known only to you):\n${agent.privateContext}`;
727
1353
  prompt = prompt ? `${prompt}\n\n${privateBlock}` : privateBlock;
728
1354
  }
1355
+ // Here rather than in the cached instructions — see invisibleArtifactNames.
729
1356
  const invisible = this.invisibleArtifactNames(agent.agentNickname);
730
1357
  if (invisible) {
731
1358
  const block = `Other documents in this room, which you cannot read:\n${invisible}`;
732
1359
  prompt = prompt ? `${prompt}\n\n${block}` : block;
733
1360
  }
1361
+ // The room leader (the Narrator in stories) has oversight of the world, so
1362
+ // it also receives every character's private context (inventory/conditions).
1363
+ // Like the moderator, this goes in the transient prompt rather than the
1364
+ // cached instructions so frequent inventory changes don't bust the cache.
734
1365
  if (agent.agentNickname === this.getRoomLeader()) {
735
1366
  const digest = this.buildCharacterPrivateContextDigest();
736
1367
  if (digest) {
@@ -740,14 +1371,43 @@ class Room {
740
1371
  }
741
1372
  return prompt;
742
1373
  }
1374
+ /**
1375
+ * Sends a single perceive prompt to an agent and parses the response.
1376
+ * The raw response is added to the agent's history. InsufficientBalanceError
1377
+ * (and any other error) propagates to the caller.
1378
+ * @param agent The agent generating a response
1379
+ * @param transientPrompt The uncached prompt message (see buildTransientPrompt)
1380
+ * @param variables The Handlebars variables (see buildPerceiveVariables)
1381
+ * @returns The agent's parsed response
1382
+ */
743
1383
  async promptAgentOnce(agent, transientPrompt, variables) {
744
- const response = await agent.instructedPrompt(transientPrompt, 'perceive', variables, false, true, variables.maxOutputChars);
1384
+ const response = await agent.instructedPrompt(transientPrompt, // uncached prompt message stored in the situation
1385
+ 'perceive', variables, false, true, variables.maxOutputChars);
745
1386
  const answer = this.parseAgentResponse(agent, response);
746
1387
  agent.addToConversationHistory(response, true);
747
1388
  agent.save();
748
1389
  return answer;
749
1390
  }
1391
+ /**
1392
+ * Runs an agent's full turn: an initial response to the heard message,
1393
+ * followed by a private research loop. EXECUTE and PUBLISH responses are
1394
+ * handled here — the tool result (or publish confirmation) is fed back into
1395
+ * the agent's history and the agent is re-prompted — until the agent emits
1396
+ * an audible action or the iteration cap is hit. The room's processing lock
1397
+ * is held by the caller for the duration, so other agents wait.
1398
+ * @param agent The agent taking its turn
1399
+ * @param heardMessage The message that triggered this turn (already in the
1400
+ * agent's history), or null when the trigger was fed to the history
1401
+ * directly (e.g. commission deliverables)
1402
+ * @param opts inCommission: the agent is a commission target; nested
1403
+ * commissions are rejected and DELIVER is the expected terminal action
1404
+ * @returns The agent's final audible message, or null if the room was
1405
+ * paused/adjourned mid-turn
1406
+ */
750
1407
  async runAgentTurn(agent, heardMessage, opts = {}) {
1408
+ // A turn is the unit the image cap is measured in, and it spans the whole
1409
+ // EXECUTE/PUBLISH chain below — so it resets here rather than per prompt.
1410
+ this.imagesThisTurn.delete(agent.agentNickname);
751
1411
  const variables = await this.buildPerceiveVariables(agent);
752
1412
  let response = await this.promptAgentOnce(agent, this.buildTransientPrompt(agent, heardMessage), variables);
753
1413
  const maxIterations = Room.maxToolIterations();
@@ -768,19 +1428,33 @@ class Room {
768
1428
  }
769
1429
  else {
770
1430
  if (!opts.inCommission && response.action === app_types_1.MessageAction.DELIVER) {
1431
+ // Stray DELIVER outside a commission: degrade to a normal SPEAK
771
1432
  response.action = app_types_1.MessageAction.SPEAK;
772
1433
  }
773
- return response;
1434
+ return response; // Audible action — the turn is complete
774
1435
  }
775
1436
  agent.addToConversationHistory(feedback, false);
776
1437
  agent.save();
777
1438
  response = await this.promptAgentOnce(agent, this.buildTransientPrompt(agent, null), variables);
778
1439
  }
1440
+ // Iteration cap hit: one corrective prompt, then coerce
779
1441
  if (this.isPaused || this.isAdjourned)
780
1442
  return null;
781
1443
  agent.addToConversationHistory(`From system: You have reached the tool-call limit for this turn. Respond now with an audible action (speak, whisper, think, ...).`, false);
782
1444
  agent.save();
783
1445
  response = await this.promptAgentOnce(agent, this.buildTransientPrompt(agent, null), variables);
1446
+ // Still reaching for a tool after being told to stop. The turn has to end, but
1447
+ // what the agent produced must not be thrown away silently, which is what
1448
+ // coercing it to a thought used to do:
1449
+ //
1450
+ // - A **PUBLISH** is a finished document. A campaign designer spent its whole
1451
+ // chain on research, published the campaign it had just written, and the
1452
+ // coercion turned four thousand characters of it into an inaudible thought.
1453
+ // Nobody noticed until the person at the table asked where the artifact was.
1454
+ // Publish it, then end the turn.
1455
+ // - An **EXECUTE** cannot be run — that is the limit doing its job — but say so
1456
+ // where a person can see it. Damage that was never applied and death saves
1457
+ // that were never rolled read exactly like a quiet turn otherwise.
784
1458
  if (response.action === app_types_1.MessageAction.PUBLISH && response.name) {
785
1459
  this.publishArtifact(response.name, agent.agentNickname, response.content, response.targets);
786
1460
  logger_1.logger.warn(`Room ${this.name}: ${agent.agentNickname} published "${response.name}" on its final tool call; publishing it and ending the turn`);
@@ -790,25 +1464,84 @@ class Room {
790
1464
  }
791
1465
  if (response.action === app_types_1.MessageAction.EXECUTE ||
792
1466
  response.action === app_types_1.MessageAction.PUBLISH) {
793
- response = new message_1.RoomMessage(agent.agentNickname, app_types_1.MessageAction.THINK, response.content, []);
1467
+ // A THINK is logged and goes no further — queueAgentResponse drops it, and
1468
+ // getLatestRoomMessages filters it out — so coercing to one ended the turn
1469
+ // with nothing for the person waiting: the host sees a stalled "working"
1470
+ // and no message ever arrives. Say what happened in the room, and let the
1471
+ // agent's own words through as speech so the turn is not silent.
1472
+ this.addRoomMessage(new message_1.RoomMessage('System', app_types_1.MessageAction.SYSTEM, response.action === app_types_1.MessageAction.EXECUTE
1473
+ ? `${agent.agentNickname} reached the tool-call limit for this turn; "${response.name}" was not run.`
1474
+ : `${agent.agentNickname} reached the tool-call limit for this turn.`, [], null, null));
1475
+ response = new message_1.RoomMessage(agent.agentNickname, app_types_1.MessageAction.SPEAK, response.content, []);
794
1476
  }
795
1477
  return response;
796
1478
  }
1479
+ /**
1480
+ * Runs a tool for an agent's EXECUTE message and returns the feedback string
1481
+ * to add to the agent's history. Also logs a TOOL notice to the room so
1482
+ * humans watching (with thoughts visible) can see the activity.
1483
+ * @param agent The agent that issued the EXECUTE
1484
+ * @param message The EXECUTE message (name = tool name, content = JSON args)
1485
+ * @returns The feedback string for the agent's history
1486
+ */
797
1487
  async executeToolForAgent(agent, message) {
798
1488
  const toolName = message.name;
799
1489
  const result = this.toolExecutionService
800
- ? await this.toolExecutionService.runForAgent(toolName, message.content, agent.toolNames || [], this.currentToolContext, this.buildToolRoomAccess(agent))
1490
+ ? await this.toolExecutionService.runForAgent(toolName, message.content, agent.toolNames || [], this.currentToolContext, this.buildToolRoomAccess(agent), this.buildToolIllustration(agent))
801
1491
  : { ok: false, error: 'Tool execution is not available in this room' };
802
1492
  const argsPreview = Room.previewForToolLog(message.content || '', Room.TOOL_LOG_ARGS_PREVIEW);
803
1493
  const statusText = 'error' in result ? `error: ${result.error}` : Room.describeToolResult(result.result);
804
1494
  this.addRoomMessage(new message_1.RoomMessage(agent.agentNickname, app_types_1.MessageAction.TOOL, `${toolName}(${argsPreview}) → ${statusText}`));
805
1495
  return `From system: Result of tool "${toolName}":\n${JSON.stringify(result)}`;
806
1496
  }
1497
+ /**
1498
+ * How much of a result a TOOL notice shows.
1499
+ *
1500
+ * Generous because the result is the half a person needs when something has gone
1501
+ * wrong, and a clipped one hides whether a call that reported success actually
1502
+ * changed anything.
1503
+ *
1504
+ * Most results never reach this: {@link describeToolResult} prefers a result's own
1505
+ * `detail` or `summary` one-liner, and the 5e tools all write one. It binds on the
1506
+ * results that have neither, which are the raw ones worth reading in full.
1507
+ */
807
1508
  static TOOL_LOG_PREVIEW = 2000;
1509
+ /**
1510
+ * How much of an EXECUTE's arguments the room's TOOL notice keeps.
1511
+ *
1512
+ * Far longer than the result's allowance because the arguments are the half a
1513
+ * person actually reads — what the agent asked the tool to do — and at 200
1514
+ * characters a `create_sheet` call was cut off inside its own spec, showing the
1515
+ * character's race and nothing after it. The bound is a sanity limit rather than
1516
+ * a budget: arguments are written by a model, so they are already short.
1517
+ *
1518
+ * A TOOL notice is heard by nobody and never enters an agent's history
1519
+ * (`RoomMessage.canHear` refuses TOOL), so none of this costs a token. It costs
1520
+ * bytes in the room log and on the update stream, which is the right trade for
1521
+ * being able to see what was run.
1522
+ */
808
1523
  static TOOL_LOG_ARGS_PREVIEW = 4000;
1524
+ /** Clips a preview so one tool call cannot fill the transcript. */
809
1525
  static previewForToolLog(text, limit = Room.TOOL_LOG_PREVIEW) {
810
1526
  return text.length > limit ? `${text.slice(0, limit)}...` : text;
811
1527
  }
1528
+ /**
1529
+ * Summarizes a successful tool result for the room log.
1530
+ *
1531
+ * `ok` on its own hid the only part anyone watching wanted: a check that
1532
+ * rolled 11 against DC 13 and failed was logged exactly like one that passed.
1533
+ * A result carrying its own one-line summary — `detail` or `summary`, the two
1534
+ * the 5e tools already write — is quoted; anything else is shown as a clipped
1535
+ * JSON preview, which at least says what came back.
1536
+ *
1537
+ * Deliberately no knowledge of any particular tool: these are conventional
1538
+ * field names, and a tool that uses neither still reads better than 'ok'.
1539
+ *
1540
+ * A TOOL notice is heard by nobody and never enters an agent's history, so
1541
+ * none of this costs a token — it is purely for the person reading the room.
1542
+ * @param value The `result` of a successful run
1543
+ * @returns A single line for the notice
1544
+ */
812
1545
  static describeToolResult(value) {
813
1546
  if (value === undefined || value === null)
814
1547
  return 'ok';
@@ -823,6 +1556,20 @@ class Room {
823
1556
  const rendered = typeof value === 'string' ? value : JSON.stringify(value);
824
1557
  return rendered ? Room.previewForToolLog(rendered) : 'ok';
825
1558
  }
1559
+ /**
1560
+ * Builds the room access a tool receives as `helpers.room`, scoped to the
1561
+ * agent that invoked it. Deliberately a closure rather than a class holding
1562
+ * a Room reference: {@link ToolRoomAccess} is part of the tool-facing
1563
+ * contract, and importing Room into it would pull the whole room graph into
1564
+ * the SDK's public types.
1565
+ *
1566
+ * The wrapper is not a pass-through to publishArtifact — it corrects three
1567
+ * behaviors that are right for an agent's PUBLISH but wrong for a tool:
1568
+ * publishArtifact credits the artifact to whoever wrote last, treats an
1569
+ * empty viewers list as creator-only, and deletes on an empty body.
1570
+ * @param agent The agent whose EXECUTE triggered the tool call
1571
+ * @returns The room accessor handed to the tool
1572
+ */
826
1573
  buildToolRoomAccess(agent) {
827
1574
  const toToolArtifact = (a) => a
828
1575
  ? {
@@ -838,6 +1585,11 @@ class Room {
838
1585
  throw new Error(`Refusing to write an empty body to artifact "${name}"; that would delete it`);
839
1586
  }
840
1587
  const existing = this.findArtifact(name);
1588
+ // Keep the original author so a tool call by another agent (e.g. the
1589
+ // room leader updating a document a player owns) doesn't reassign it.
1590
+ // On creation the tool may name the agent the artifact belongs to,
1591
+ // but only if that agent is actually here — crediting someone absent
1592
+ // would make the artifact unreadable to everyone.
841
1593
  let creator = agent.agentNickname;
842
1594
  if (existing) {
843
1595
  creator = existing.creator;
@@ -851,6 +1603,8 @@ class Room {
851
1603
  (existing && existing.viewers && existing.viewers.length > 0
852
1604
  ? existing.viewers
853
1605
  : this.agents.map((a) => a.agentNickname));
1606
+ // Like viewers and creator: undefined means "leave it as it is", so a
1607
+ // tool that updates a body does not have to restate how it is delivered.
854
1608
  return toToolArtifact(this.publishArtifact(name, creator, body, finalViewers, options?.transient));
855
1609
  };
856
1610
  return {
@@ -859,6 +1613,7 @@ class Room {
859
1613
  isHuman: !!agent.isControlledByHuman,
860
1614
  isLeader: agent.agentNickname === this.getRoomLeader(),
861
1615
  },
1616
+ // Snapshotted: the roster cannot change during a single tool call.
862
1617
  agentNicknames: this.agents.map((a) => a.agentNickname),
863
1618
  roomId: this.getId(),
864
1619
  roomName: this.getName(),
@@ -882,12 +1637,21 @@ class Room {
882
1637
  if (!target)
883
1638
  return false;
884
1639
  target.description = trimmed.slice(0, MAX_DESCRIPTION_CHARS);
885
- target.save();
1640
+ target.save(); // Persists and notifies the client
886
1641
  return true;
887
1642
  },
888
1643
  renameAgent: (nickname, newName) => this.renameAgent(nickname, newName),
889
1644
  };
890
1645
  }
1646
+ /**
1647
+ * Gets AI response for an agent (private helper moved from Agent).
1648
+ * Thin callback adapter around runAgentTurn: the callback does not fire
1649
+ * until the agent's whole turn (including any tool research loop) is done,
1650
+ * which is what holds the room's processing lock for the duration.
1651
+ * @param agent The agent generating response
1652
+ * @param message The message the agent is responding to
1653
+ * @param onResponse Callback with AI response
1654
+ */
891
1655
  getAgentAiResponse(agent, message, onResponse) {
892
1656
  this.runAgentTurn(agent, message)
893
1657
  .then(async (answer) => {
@@ -899,12 +1663,32 @@ class Room {
899
1663
  this.handleInsufficientBalance(e);
900
1664
  }
901
1665
  else {
1666
+ // Other errors remain internalized (existing behavior)
902
1667
  let internalizedError = `${agent.agentNickname} thinks: No one heard me because ${e.message}`;
903
1668
  agent.addToConversationHistory(internalizedError, true);
904
1669
  }
905
1670
  onResponse(null);
906
1671
  });
907
1672
  }
1673
+ /**
1674
+ * Summarises an agent's history when it has outgrown the compaction threshold.
1675
+ *
1676
+ * Called at the end of a turn rather than the start of one, which is the only
1677
+ * safe point: the turn's tool chain feeds results back into history and
1678
+ * re-prompts, so compacting part-way through would summarise away the tool call
1679
+ * whose result the agent is waiting on. By the time the turn returns, its own
1680
+ * response is already in history and the summary can cover it.
1681
+ *
1682
+ * It also runs *before* `onResponse`, which is what releases the room to process
1683
+ * the next message. Compacting afterwards would rewrite this agent's history
1684
+ * while the following turn was reading it.
1685
+ *
1686
+ * A failed summary is logged and swallowed. The agent keeps a too-long history
1687
+ * and the campaign carries on, which is strictly better than ending a turn that
1688
+ * already produced a good answer because a bookkeeping call failed.
1689
+ *
1690
+ * @param agent The agent whose turn has just finished
1691
+ */
908
1692
  async compactIfOversized(agent) {
909
1693
  if (!agent.needsCompaction())
910
1694
  return;
@@ -915,6 +1699,16 @@ class Room {
915
1699
  logger_1.logger.warn(`Could not compact ${agent.agentName}, continuing with full history: ${e.message}`);
916
1700
  }
917
1701
  }
1702
+ /**
1703
+ * Delivers a message into an agent's history without asking it to respond.
1704
+ * Split out of {@link perceive} so agents that are not responding this turn
1705
+ * still stay in sync with the conversation at no LLM cost. Callers that are
1706
+ * not counting this agent in their outstanding-response tally must use this
1707
+ * rather than `perceive`, which always invokes its callback.
1708
+ * @param agent The agent receiving the message
1709
+ * @param message The message being delivered
1710
+ * @returns True if the agent could hear the message and it was recorded
1711
+ */
918
1712
  hear(agent, message) {
919
1713
  if (!message.canHear(agent.agentNickname)) {
920
1714
  return false;
@@ -923,31 +1717,58 @@ class Room {
923
1717
  agent.save();
924
1718
  return true;
925
1719
  }
1720
+ /**
1721
+ * Allows an agent to perceive messages and generate a response (moved from Agent)
1722
+ * @param agent The agent that is perceiving
1723
+ * @param message
1724
+ * @param onResponse Callback with agent's response or null
1725
+ */
926
1726
  perceive(agent, message, onResponse, opts = {}) {
1727
+ // An agent keeping the floor is answering its own message, which is already in
1728
+ // its history because it wrote it — and `canHear` is false for your own
1729
+ // message, so the delivery gate below would drop the prompt and leave the room
1730
+ // with nobody acting at all. Prompt it directly, with a note saying why it is
1731
+ // being asked again: without one it cannot tell a continuation from being
1732
+ // handed back something it has already answered.
927
1733
  if (opts.continuing) {
928
1734
  agent.addToConversationHistory(Room.CONTINUE_NOTE, false);
929
1735
  agent.save();
930
1736
  this.getAgentAiResponse(agent, message, onResponse);
931
1737
  return;
932
1738
  }
1739
+ // Check if this agent can hear the message, and record it if so
933
1740
  if (!this.hear(agent, message)) {
934
1741
  onResponse(null);
935
1742
  return;
936
1743
  }
1744
+ // Check if should respond
937
1745
  if (!agent.canRespond(message)) {
938
1746
  onResponse(null);
939
1747
  return;
940
1748
  }
941
1749
  if (agent.isControlledByHuman) {
1750
+ // onResponse is not called. This prevents the agentsRemaining count from hitting zero and stops message processing
942
1751
  return;
943
1752
  }
1753
+ // AI-CONTROLLED AGENT: Query AI service and call callback with response
944
1754
  this.getAgentAiResponse(agent, message, onResponse);
945
1755
  }
1756
+ /**
1757
+ * Moderator agent evaluates and routes a message (moved from Agent)
1758
+ * @param moderatorAgent The moderator agent
1759
+ * @param message RoomMessage to moderate
1760
+ * @param onResponse Callback with routing decision
1761
+ * @param opts.note Extra instruction for this one routing decision, put in the
1762
+ * transient prompt so it never enters the moderator's cached prefix
1763
+ */
946
1764
  async moderate(moderatorAgent, message, onResponse, opts = {}) {
1765
+ // Name the human-controlled characters. The moderator routes to one of them
1766
+ // by name, so it needs the whole list, not just the first.
947
1767
  const humanAgents = this.getHumanAgents();
948
1768
  const humanAgent = humanAgents[0];
949
1769
  const humanAgentNames = humanAgents.map((a) => a.agentNickname);
950
1770
  const humanAgentName = humanAgentNames[0] ?? 'Player';
1771
+ // Build base variables
951
1772
  const visibleArtifacts = this.getVisibleArtifacts(moderatorAgent.agentNickname)
952
1773
  .map((a) => `${a.name} (by ${a.creator}): ${Room.renderArtifactForPrompt(a)}`)
953
1774
  .join('\n\n');
@@ -959,7 +1780,7 @@ class Room {
959
1780
  agents: this.getAgents(),
960
1781
  roomLeader: this.getRoomLeader(),
961
1782
  roomGoal: this.getGoal(),
962
- scenario: this.getGoal(),
1783
+ scenario: this.getGoal(), // Alias for story rooms
963
1784
  humanAgent: humanAgent,
964
1785
  humanAgentName: humanAgentName,
965
1786
  humanAgentNames: humanAgentNames,
@@ -971,16 +1792,31 @@ ${this.buildSituationHeader()}
971
1792
  Sender: ${message.getSender()}
972
1793
  Recent Message: ${message.getContent()}
973
1794
  `;
1795
+ // Adjacent to the message it changes the meaning of, rather than appended at
1796
+ // the end behind the inventories.
974
1797
  if (opts.note) {
975
1798
  prompt += `\n${opts.note}\n`;
976
1799
  }
1800
+ // Who heard the last routed message, so a conversation with a sub-group stays
1801
+ // with that sub-group. In the transient prompt rather than the instructions:
1802
+ // it changes every turn, and in the cached prefix it would invalidate the
1803
+ // moderator's cache on each one.
977
1804
  if (this.lastModeratedAudience.length > 0) {
978
1805
  prompt += `\nAudience of the previous message: ${this.lastModeratedAudience.join(', ')}\n`;
979
1806
  }
1807
+ // The document names tell the moderator what stage the table is at, which is
1808
+ // what it routes on. Transient for the same reason as the audience above: the
1809
+ // list changes whenever any artifact is created anywhere in the room, and
1810
+ // cached it invalidated the moderator's prefix every time one was.
980
1811
  const invisible = this.invisibleArtifactNames(moderatorAgent.agentNickname);
981
1812
  if (invisible) {
982
1813
  prompt += `\nDocuments at this table you cannot read: ${invisible}\n`;
983
1814
  }
1815
+ // The moderator needs every character's current inventory and conditions to
1816
+ // keep the story consistent and to emit update_inventory. Each character keeps
1817
+ // these in its private context. Inject them into the transient (uncached)
1818
+ // moderator prompt rather than the cached instructions, so a frequently-changing
1819
+ // inventory never invalidates the moderator's prompt cache.
984
1820
  const characterContexts = this.buildCharacterPrivateContextDigest();
985
1821
  if (characterContexts) {
986
1822
  prompt += `\nCharacter Inventories and Conditions:\n${characterContexts}\n`;
@@ -998,75 +1834,137 @@ Recent Message: ${message.getContent()}
998
1834
  this.handleInsufficientBalance(e, onResponse);
999
1835
  }
1000
1836
  else {
1837
+ // Other errors - rethrow
1001
1838
  throw e;
1002
1839
  }
1003
1840
  }
1004
1841
  }
1842
+ /**
1843
+ * Handles insufficient balance errors by pausing the conversation
1844
+ * @param error The insufficient balance error
1845
+ * @param onResponse Optional callback to call with null
1846
+ */
1005
1847
  handleInsufficientBalance(error, onResponse) {
1848
+ // Notify error callback (propagates to SSE clients)
1006
1849
  this.notifyError(error);
1850
+ // Add visible system message
1007
1851
  const balanceMessage = new message_1.RoomMessage('System', app_types_1.MessageAction.SYSTEM, `Conversation paused: ${error.message}`, [], null, null);
1008
1852
  this.addRoomMessage(balanceMessage);
1853
+ // Stop processing. 'keep' rather than 'release' so a pause that is already
1854
+ // holding the floor for the human keeps it; the caller's own callback
1855
+ // releases it on the paths where that is right.
1009
1856
  this.endTurn('keep');
1857
+ // Call callback with null if provided
1010
1858
  if (onResponse) {
1011
1859
  onResponse(null);
1012
1860
  }
1013
1861
  }
1862
+ /**
1863
+ * Gets an artifact by name
1864
+ * @param name The name of the artifact
1865
+ * @returns The artifact or undefined if not found
1866
+ */
1014
1867
  findArtifact(name) {
1015
1868
  return this.artifacts.find((a) => a.name === name);
1016
1869
  }
1870
+ /**
1871
+ * Creates or updates an artifact with PUBLISH action
1872
+ * If body is empty, deletes the artifact instead
1873
+ * @param name The name of the artifact
1874
+ * @param creator The name of the agent who created it
1875
+ * @param body The content of the artifact (empty body will delete the artifact)
1876
+ * @param viewers Array of agent names who can view the artifact
1877
+ * @returns The created or updated artifact, or null if deleted
1878
+ */
1017
1879
  publishArtifact(name, creator, body, viewers = [], transient) {
1880
+ // Empty body means delete the artifact
1018
1881
  if (!body || body.trim().length === 0) {
1019
1882
  this.deleteArtifact(name);
1020
1883
  return null;
1021
1884
  }
1885
+ // Check if an artifact with this name already exists
1022
1886
  const existingIndex = this.artifacts.findIndex((a) => a.name === name);
1023
1887
  let returnedArtifact;
1024
1888
  if (existingIndex >= 0) {
1889
+ // Update existing artifact
1025
1890
  this.artifacts[existingIndex].body = body;
1026
1891
  this.artifacts[existingIndex].creator = creator;
1027
1892
  this.artifacts[existingIndex].viewers = viewers.length > 0 ? viewers : [creator];
1893
+ // Undefined leaves it as it was, so an agent's PUBLISH over a
1894
+ // transient artifact cannot silently promote it into the cached block.
1028
1895
  if (transient !== undefined) {
1029
1896
  this.artifacts[existingIndex].transient = transient;
1030
1897
  }
1031
1898
  returnedArtifact = this.artifacts[existingIndex];
1032
1899
  }
1033
1900
  else {
1901
+ // Create new artifact
1034
1902
  const newArtifact = {
1035
1903
  name,
1036
1904
  creator,
1037
1905
  body,
1038
- viewers: viewers.length > 0 ? viewers : [creator],
1906
+ viewers: viewers.length > 0 ? viewers : [creator], // If no viewers specified, only creator can see
1039
1907
  ...(transient !== undefined && { transient }),
1040
1908
  };
1041
1909
  this.artifacts.push(newArtifact);
1042
1910
  returnedArtifact = newArtifact;
1043
1911
  }
1912
+ // Save individual artifact file
1044
1913
  if (this.roomStoreService && this.storageDir) {
1045
1914
  this.roomStoreService.saveArtifactFile(this.id, this.storageDir, returnedArtifact);
1046
1915
  }
1047
- this.saveMetadata();
1916
+ this.saveMetadata(); // Still save metadata for other room fields
1917
+ // Tools can write artifacts outside the message flow, so the client has
1918
+ // no other signal to refresh its artifact list.
1048
1919
  this.notifyStateChange();
1049
1920
  return returnedArtifact;
1050
1921
  }
1922
+ /**
1923
+ * Deletes an artifact from the room
1924
+ * @param name The name of the artifact to delete
1925
+ * @returns True if the artifact was found and deleted, false otherwise
1926
+ */
1051
1927
  deleteArtifact(name) {
1052
1928
  const index = this.artifacts.findIndex((a) => a.name === name);
1053
1929
  if (index === -1) {
1054
1930
  return false;
1055
1931
  }
1932
+ // Remove from in-memory array
1056
1933
  this.artifacts.splice(index, 1);
1934
+ // Delete artifact file
1057
1935
  if (this.roomStoreService && this.storageDir) {
1058
1936
  this.roomStoreService.deleteArtifactFile(this.id, this.storageDir, name);
1059
1937
  }
1060
1938
  return true;
1061
1939
  }
1940
+ /**
1941
+ * Gets the artifacts an agent may read, transient ones included.
1942
+ * @param agentNickname The name of the agent
1943
+ * @returns Array of artifacts readable by the agent
1944
+ */
1062
1945
  getReadableArtifacts(agentNickname) {
1063
1946
  return this.artifacts.filter((a) => a.creator === agentNickname ||
1064
1947
  (a.viewers && a.viewers.includes(agentNickname)) ||
1065
1948
  !a.viewers);
1066
1949
  }
1950
+ /**
1951
+ * Gets the artifacts rendered into an agent's **cached** prompt block.
1952
+ *
1953
+ * Transient artifacts are deliberately excluded: they go in the per-turn
1954
+ * prompt instead (see `buildTransientPrompt`), which is the whole point of
1955
+ * marking one transient. They are still readable — `getTransientArtifacts`
1956
+ * returns them, and a tool reads any artifact regardless.
1957
+ * @param agentNickname The name of the agent
1958
+ * @returns Array of artifacts visible to the agent
1959
+ */
1067
1960
  getVisibleArtifacts(agentNickname) {
1068
1961
  return this.getReadableArtifacts(agentNickname).filter((a) => !a.transient);
1069
1962
  }
1963
+ /**
1964
+ * Gets the artifacts delivered to an agent in the uncached per-turn prompt.
1965
+ * @param agentNickname The name of the agent
1966
+ * @returns Array of transient artifacts readable by the agent
1967
+ */
1070
1968
  getTransientArtifacts(agentNickname) {
1071
1969
  return this.getReadableArtifacts(agentNickname).filter((a) => a.transient);
1072
1970
  }
@@ -1088,22 +1986,122 @@ Recent Message: ${message.getContent()}
1088
1986
  setRoomStoreService(service) {
1089
1987
  this.roomStoreService = service;
1090
1988
  }
1989
+ /**
1990
+ * @internal Injects the user-scoped tool services so agents in this room can
1991
+ * EXECUTE user-defined tools. Called by RoomStoreService and RoomFactory at
1992
+ * every Room construction site; SDK consumers never call this directly.
1993
+ * @param toolStore The user's tool store
1994
+ * @param toolExecution The user's tool execution service
1995
+ */
1091
1996
  setToolServices(toolStore, toolExecution) {
1092
1997
  this.toolStoreService = toolStore;
1093
1998
  this.toolExecutionService = toolExecution;
1094
1999
  }
2000
+ /**
2001
+ * @internal Injects the shared illustration pipeline. Called wherever
2002
+ * {@link setToolServices} is; SDK consumers never call this directly.
2003
+ */
2004
+ setIllustrationService(illustration) {
2005
+ this.illustrationService = illustration;
2006
+ }
2007
+ /**
2008
+ * Builds the illustration capability a tool sees, for one calling agent.
2009
+ *
2010
+ * A closure rather than a class holding a Room, for the reason
2011
+ * {@link buildToolRoomAccess} is: `ToolIllustration` is part of the tool-facing
2012
+ * contract, and importing Room into it would drag the room graph into the SDK's
2013
+ * public types.
2014
+ *
2015
+ * `request` returns the moment the work is queued. Drawing takes minutes and a
2016
+ * tool call has at most 120 seconds, so waiting would guarantee a timeout; the
2017
+ * finished picture arrives as its own message instead.
2018
+ */
2019
+ buildToolIllustration(agent) {
2020
+ const illustration = this.illustrationService;
2021
+ if (!illustration)
2022
+ return undefined;
2023
+ const nickname = agent.agentNickname;
2024
+ const target = illustration.targetFor(this);
2025
+ const mode = this.getIllustrationMode();
2026
+ const available = mode !== 'off' && !!target.imageModelName();
2027
+ const counter = this.imagesThisTurn;
2028
+ return {
2029
+ available,
2030
+ get usedThisTurn() {
2031
+ return counter.get(nickname) ?? 0;
2032
+ },
2033
+ perTurnLimit: Room.IMAGES_PER_TURN,
2034
+ request: (brief, subjects) => {
2035
+ if (!available)
2036
+ return { accepted: false, reason: 'images_disabled' };
2037
+ const used = this.imagesThisTurn.get(nickname) ?? 0;
2038
+ if (used >= Room.IMAGES_PER_TURN) {
2039
+ return { accepted: false, reason: 'turn_limit' };
2040
+ }
2041
+ if (illustration.isBusy(target.key)) {
2042
+ return { accepted: false, reason: 'in_flight' };
2043
+ }
2044
+ // Counted on acceptance, not on completion: the point is to stop an
2045
+ // agent asking repeatedly within one turn, and the answer will not
2046
+ // arrive before the turn ends.
2047
+ this.imagesThisTurn.set(nickname, used + 1);
2048
+ void illustration
2049
+ .illustrate(this, target, {
2050
+ situation: this.getSituation() || this.getGoal(),
2051
+ situationTime: this.getSituationTime(),
2052
+ brief,
2053
+ subjects,
2054
+ requestedBy: nickname,
2055
+ sequence: this.roomMessages.length,
2056
+ allowReference: true,
2057
+ })
2058
+ .catch((error) => logger_1.logger.error('Illustration request failed:', error));
2059
+ return { accepted: true };
2060
+ },
2061
+ portrait: (characterName, profile) => {
2062
+ if (!available)
2063
+ return { accepted: false, reason: 'images_disabled' };
2064
+ const used = this.imagesThisTurn.get(nickname) ?? 0;
2065
+ if (used >= Room.IMAGES_PER_TURN) {
2066
+ return { accepted: false, reason: 'turn_limit' };
2067
+ }
2068
+ // Deliberately not gated on `isBusy`: that lock keeps overlapping
2069
+ // scenes from drawing a situation that has already moved on, and a
2070
+ // portrait has no situation. Seating a party would otherwise give a
2071
+ // face to whoever was created first and nobody else.
2072
+ this.imagesThisTurn.set(nickname, used + 1);
2073
+ const ready = illustration
2074
+ .portrait(target, characterName, profile, this)
2075
+ .then((artifactId) => (artifactId ? target.imageUrl(artifactId) : null))
2076
+ .catch((error) => {
2077
+ logger_1.logger.error(`Portrait request for ${characterName} failed:`, error);
2078
+ return null;
2079
+ });
2080
+ return { accepted: true, ready };
2081
+ },
2082
+ };
2083
+ }
2084
+ /**
2085
+ * Saves messages incrementally to disk
2086
+ * @param messages The new messages to append
2087
+ */
1095
2088
  saveMessages(messages) {
1096
2089
  if (!this.roomStoreService || !this.storageDir || !this.id) {
1097
- return;
2090
+ return; // Can't save if persistence not configured
1098
2091
  }
2092
+ // Append each new message to the messages file
1099
2093
  for (const message of messages) {
1100
2094
  this.roomStoreService.appendMessageToFile(this.id, message, this.storageDir);
1101
2095
  }
1102
2096
  }
2097
+ /**
2098
+ * Saves the room metadata to disk
2099
+ */
1103
2100
  saveMetadata() {
1104
2101
  if (!this.roomStoreService || !this.storageDir) {
1105
- return;
2102
+ return; // Can't save if persistence not configured
1106
2103
  }
2104
+ // Prevent saving during room loading to avoid saving incomplete state
1107
2105
  if (this.isLoading) {
1108
2106
  return;
1109
2107
  }
@@ -1111,9 +2109,21 @@ Recent Message: ${message.getContent()}
1111
2109
  this.notifyStateChange();
1112
2110
  return id;
1113
2111
  }
2112
+ /**
2113
+ * Registers a state-change listener under a stable key. Each key holds at most
2114
+ * one listener — re-registering with the same key replaces its callback.
2115
+ * Different keys can coexist so multiple subsystems (e.g. the rooms SSE endpoint
2116
+ * and the story service) both receive notifications without clobbering each other.
2117
+ * @param key Stable identifier for the subsystem (e.g. 'app-service', 'story')
2118
+ * @param callback Function to call on state changes
2119
+ */
1114
2120
  setOnStateChange(key, callback) {
1115
2121
  this.onStateChangeCallbacks.set(key, callback);
1116
2122
  }
2123
+ /**
2124
+ * Removes a previously-registered state-change listener.
2125
+ * @param key The key passed to {@link setOnStateChange}
2126
+ */
1117
2127
  removeOnStateChange(key) {
1118
2128
  this.onStateChangeCallbacks.delete(key);
1119
2129
  }
@@ -1122,9 +2132,25 @@ Recent Message: ${message.getContent()}
1122
2132
  callback();
1123
2133
  }
1124
2134
  }
2135
+ /**
2136
+ * Subscribes to errors raised while running a turn.
2137
+ *
2138
+ * Keyed like {@link setOnStateChange}, and for the same reason: more than one
2139
+ * thing wants to hear about a failed turn. A single-callback setter meant the
2140
+ * last caller silently replaced the first — the SDK's bridge onto the room's
2141
+ * update stream and a story's own handler could not both exist, and whichever
2142
+ * registered second won without any sign that it had taken the other's place.
2143
+ *
2144
+ * @param key Identifies the subscriber; registering the same key twice replaces it
2145
+ * @param callback Function to call on errors
2146
+ */
1125
2147
  setOnError(key, callback) {
1126
2148
  this.onErrorCallbacks.set(key, callback);
1127
2149
  }
2150
+ /**
2151
+ * Stops delivering errors to a subscriber.
2152
+ * @param key The key it registered with
2153
+ */
1128
2154
  clearOnError(key) {
1129
2155
  this.onErrorCallbacks.delete(key);
1130
2156
  }
@@ -1133,9 +2159,28 @@ Recent Message: ${message.getContent()}
1133
2159
  callback(error);
1134
2160
  }
1135
2161
  }
2162
+ /**
2163
+ * Every human-controlled agent in the room, in arrival order.
2164
+ *
2165
+ * A room may have more than one: several people can share a browser, and one
2166
+ * person can play several characters. Code that genuinely needs a single human
2167
+ * uses {@link getDefaultHumanAgent} — but anything reacting to a *message* must
2168
+ * resolve the human from its sender, because the sender is rarely the default.
2169
+ */
1136
2170
  getHumanAgents() {
1137
2171
  return this.agents.filter((agent) => agent.isControlledByHuman);
1138
2172
  }
2173
+ /**
2174
+ * Names as a prompt reads them aloud: `Rhys`, `Rhys and Mira`, `Rhys, Mira and Tor`.
2175
+ *
2176
+ * Handlebars has no `join`, and this codebase registers no helpers, so a template
2177
+ * wanting a list inline has to either be handed one or spell out an `{{#each}}`
2178
+ * with `{{#unless @last}}`. Handing it over is the difference between a prompt
2179
+ * that reads like a sentence and one every author gets subtly wrong — which is
2180
+ * how a table with two players came to have prompts that only ever named one.
2181
+ * @param names The names to list, in order
2182
+ * @returns The joined phrase, or an empty string for no names
2183
+ */
1139
2184
  static listNames(names) {
1140
2185
  if (names.length === 0)
1141
2186
  return '';
@@ -1143,17 +2188,38 @@ Recent Message: ${message.getContent()}
1143
2188
  return names[0];
1144
2189
  return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;
1145
2190
  }
2191
+ /**
2192
+ * The human the room falls back to when it has to pick one, which is whoever
2193
+ * arrived first. Used to open the conversation and to attribute a message that
2194
+ * arrives with no sender. Which one it is carries no meaning.
2195
+ */
1146
2196
  getDefaultHumanAgent() {
1147
2197
  return this.agents.find((agent) => agent.isControlledByHuman);
1148
2198
  }
2199
+ /**
2200
+ * The human-controlled agent a sender name refers to, matched the same way
2201
+ * message targets are, or undefined when no human answers to that name.
2202
+ */
1149
2203
  getHumanAgentByName(sender) {
1150
2204
  if (!sender)
1151
2205
  return undefined;
1152
2206
  return this.getHumanAgents().find((agent) => this.checkAgentNicknameMatch(agent.agentNickname, sender));
1153
2207
  }
2208
+ /** True when `nickname` names a human-controlled agent in this room. */
1154
2209
  isHumanNickname(nickname) {
1155
2210
  return !!nickname && !!this.getHumanAgentByName(nickname);
1156
2211
  }
2212
+ /**
2213
+ * True when a message is the players talking among themselves: a whisper whose
2214
+ * every target is a human-controlled agent.
2215
+ *
2216
+ * Such a message cannot reach the game. `canHear` restricts a whisper to its
2217
+ * targets, so no AI agent hears it; every target is human, so no agent is
2218
+ * prompted and nothing is spent. That is what lets the room take one **out of
2219
+ * turn** and leave the floor untouched — the players get to chat across the
2220
+ * table while an agent is mid-turn, and it still shows up in the transcript for
2221
+ * everyone at the table to read.
2222
+ */
1157
2223
  isPlayerAside(message) {
1158
2224
  if (message.getAction() !== app_types_1.MessageAction.WHISPER)
1159
2225
  return false;
@@ -1162,9 +2228,29 @@ Recent Message: ${message.getContent()}
1162
2228
  return false;
1163
2229
  return targets.every((target) => this.isHumanNickname(target));
1164
2230
  }
2231
+ /**
2232
+ * Gets the name of the default human-controlled agent
2233
+ * @returns The human agent's name or empty string if not found
2234
+ */
1165
2235
  getHumanAgentName() {
1166
2236
  return this.getDefaultHumanAgent()?.agentNickname ?? '';
1167
2237
  }
2238
+ /**
2239
+ * Gets the agent that places messages the room cannot route mechanically.
2240
+ *
2241
+ * Prefers the configured {@link setModerator} nickname. The fallback to the
2242
+ * first agent is how story rooms have always chosen theirs — the narrator is
2243
+ * added first — and is kept so they keep working, but it is a guess: in any
2244
+ * other room the first agent is whoever happened to be added first and has no
2245
+ * `moderate.prompt` at all. Name one explicitly.
2246
+ *
2247
+ * The fallback prefers an agent that actually has a `moderate.prompt`, because
2248
+ * one that does not fails in the worst way available: the prompt lookup throws,
2249
+ * the throw is swallowed, and the message disappears. Arrival order is only
2250
+ * consulted when nobody in the room can moderate, which keeps a room that was
2251
+ * working before this preference existed working now.
2252
+ * @returns The moderator agent or undefined if the room is empty
2253
+ */
1168
2254
  getModeratorAgent() {
1169
2255
  if (this.moderator) {
1170
2256
  const named = this.agents.find((a) => this.checkAgentNicknameMatch(a.agentNickname, this.moderator));
@@ -1172,18 +2258,43 @@ Recent Message: ${message.getContent()}
1172
2258
  return named;
1173
2259
  logger_1.logger.warn(`Room ${this.name}: configured moderator "${this.moderator}" is not in the room; falling back to the first agent`);
1174
2260
  }
2261
+ // Skip the players. Moderating means answering a prompt, which a human agent
2262
+ // never does — it would take the floor and hold it. With one player at the
2263
+ // table this was unlikely to bite; with several, the odds that the first
2264
+ // agent is one of them are much better.
1175
2265
  const candidates = this.agents.filter((a) => !a.isControlledByHuman);
1176
2266
  return candidates.find((a) => a.hasPrompt('moderate')) ?? candidates[0];
1177
2267
  }
2268
+ /**
2269
+ * Gets the current story situation
2270
+ * @returns The current situation string
2271
+ */
1178
2272
  getSituation() {
1179
2273
  return this.currentSituation;
1180
2274
  }
2275
+ /**
2276
+ * Gets the current in-story time (24-hour "HH:MM"), stored separately from the
2277
+ * situation text.
2278
+ * @returns The current time string, or '' if none is set
2279
+ */
1181
2280
  getSituationTime() {
1182
2281
  return this.currentSituationTime;
1183
2282
  }
2283
+ /**
2284
+ * Sets the current in-story time (24-hour "HH:MM").
2285
+ * @param time The time string to set
2286
+ */
1184
2287
  setSituationTime(time) {
1185
2288
  this.currentSituationTime = time || '';
1186
2289
  }
2290
+ /**
2291
+ * Builds the situation header shared by every agent's transient prompt: the
2292
+ * in-story time on its own labeled line (flagged as a 24-hour clock so a character
2293
+ * doesn't misread "10:30" as 10:30 PM), followed by the situation text. Either
2294
+ * line is omitted when its value is empty.
2295
+ *
2296
+ * @returns The time and situation lines, or '' if both are empty
2297
+ */
1187
2298
  buildSituationHeader() {
1188
2299
  const lines = [];
1189
2300
  if (this.currentSituationTime) {
@@ -1194,21 +2305,82 @@ Recent Message: ${message.getContent()}
1194
2305
  }
1195
2306
  return lines.join('\n');
1196
2307
  }
2308
+ /**
2309
+ * Sets the current story situation
2310
+ * @param situation The situation string to set
2311
+ */
1197
2312
  setSituation(situation) {
1198
2313
  this.currentSituation = situation;
1199
2314
  }
2315
+ /**
2316
+ * Sets a callback to be invoked whenever situation changes
2317
+ * @param callback Function to call with new situation
2318
+ */
1200
2319
  setOnSituationUpdate(callback) {
1201
2320
  this.onSituationUpdate = callback;
1202
2321
  }
1203
2322
  setOnModeratorResponse(callback) {
1204
2323
  this.onModeratorResponseCallback = callback;
1205
2324
  }
2325
+ /**
2326
+ * Handles situation update from an agent message
2327
+ * Updates internal state and notifies callback
2328
+ * @param situation The new situation string
2329
+ * @param messageBody Body of the message that produced this situation, for
2330
+ * consumers that need the triggering message but can't read it from the
2331
+ * room yet (it may not be logged at the time the callback fires).
2332
+ */
1206
2333
  async handleSituationUpdate(situation, messageBody) {
1207
2334
  logger_1.logger.log(`Situation updated: ${situation}`);
2335
+ const previous = this.currentSituation;
1208
2336
  this.currentSituation = situation;
2337
+ // Notify callback if registered. Awaited so callers that need the
2338
+ // situation fully processed before continuing can rely on it being done.
1209
2339
  if (this.onSituationUpdate) {
1210
2340
  await this.onSituationUpdate(situation, messageBody);
1211
2341
  }
2342
+ // After the callback, deliberately. A story rewrites `currentSituation` in
2343
+ // there — the room is handed the narrator's raw four-tag preamble and the
2344
+ // story replaces it with the parsed text — so reading it any earlier would
2345
+ // send the whole preamble to the illustrator.
2346
+ if (situation !== previous) {
2347
+ this.requestAutomaticIllustration(messageBody);
2348
+ }
2349
+ }
2350
+ /**
2351
+ * Draws the new scene, when the room is set to illustrate itself.
2352
+ *
2353
+ * Only in `auto`. The default is `on-request` for a reason: an agent may be
2354
+ * told to restate the situation on *every* response — the dnd5e Dungeon Master
2355
+ * is — so a room wired the way stories are would buy a picture several times a
2356
+ * turn. Stories are unaffected either way, because StoryService still issues
2357
+ * their illustrations itself, with the chapter and character branches this
2358
+ * cannot see.
2359
+ *
2360
+ * Fire-and-forget: drawing takes minutes and nothing is waiting on it.
2361
+ */
2362
+ requestAutomaticIllustration(narration) {
2363
+ if (this.illustrationMode !== 'auto')
2364
+ return;
2365
+ const illustration = this.illustrationService;
2366
+ if (!illustration)
2367
+ return;
2368
+ const target = illustration.targetFor(this);
2369
+ if (!target.imageModelName())
2370
+ return;
2371
+ // The service holds the authoritative lock; this only avoids the work of
2372
+ // building a request that would be dropped.
2373
+ if (illustration.isBusy(target.key))
2374
+ return;
2375
+ void illustration
2376
+ .illustrate(this, target, {
2377
+ situation: this.getSituation(),
2378
+ situationTime: this.getSituationTime(),
2379
+ narration,
2380
+ sequence: this.roomMessages.length,
2381
+ allowReference: true,
2382
+ })
2383
+ .catch((error) => logger_1.logger.error('Automatic illustration failed:', error));
1212
2384
  }
1213
2385
  handlePublishMessages(messages) {
1214
2386
  for (const message of messages) {
@@ -1216,21 +2388,27 @@ Recent Message: ${message.getContent()}
1216
2388
  const artifactName = message.name;
1217
2389
  const creator = message.sender;
1218
2390
  const body = message.content;
1219
- const viewers = message.targets;
2391
+ const viewers = message.targets; // targets are now viewers
1220
2392
  this.publishArtifact(artifactName, creator, body, viewers);
1221
2393
  }
1222
2394
  }
1223
2395
  }
1224
2396
  handleAdjournMessages(messages) {
2397
+ // If there are no adjourn messages, nothing to do
1225
2398
  if (messages.length === 0) {
1226
2399
  return;
1227
2400
  }
2401
+ // Get the names of agents who have sent adjourn messages
1228
2402
  const adjournedAgents = messages.map((m) => m.sender);
2403
+ // Get all agent names in the room
1229
2404
  const allAgentNames = this.agents.map((a) => a.agentNickname);
2405
+ // Check if all agents have adjourned
1230
2406
  const allAdjourned = allAgentNames.every((name) => adjournedAgents.includes(name));
1231
2407
  if (allAdjourned) {
2408
+ // All agents have adjourned, mark the room as adjourned
1232
2409
  this.isAdjourned = true;
1233
2410
  this.notifyStateChange();
2411
+ // Add a moderator message indicating the room has been adjourned
1234
2412
  this.addRoomMessage(new message_1.RoomMessage('system', app_types_1.MessageAction.SYSTEM, 'All agents have agreed to adjourn. The conversation has ended.'));
1235
2413
  this.pendingMessages = null;
1236
2414
  }
@@ -1245,9 +2423,14 @@ Recent Message: ${message.getContent()}
1245
2423
  }
1246
2424
  }
1247
2425
  addPendingMessage(message, clearQueue = false, context) {
2426
+ // Adopt the host's opaque tool context for the interaction this message
2427
+ // starts. Held in memory only (never persisted); because the room is
2428
+ // single-flight, it applies to the whole resulting cascade — including
2429
+ // agents reacting to each other and commissioned sub-agents.
1248
2430
  if (context !== undefined) {
1249
2431
  this.currentToolContext = context;
1250
2432
  }
2433
+ // Initialize pendingMessages if this is the first message (e.g., after reconnection)
1251
2434
  if (!this.pendingMessages) {
1252
2435
  this.pendingMessages = [];
1253
2436
  }
@@ -1257,15 +2440,32 @@ Recent Message: ${message.getContent()}
1257
2440
  if (!message.sender) {
1258
2441
  message.sender = 'system';
1259
2442
  }
2443
+ // Resolved from the sender, not from the room's default human: with several
2444
+ // players in the room, only one of them is the default, and matching against
2445
+ // it would leave every other player's message treated as a system message —
2446
+ // never added to their own agent's history, never clearing the floor.
1260
2447
  const humanAgent = this.getHumanAgentByName(message.sender);
1261
2448
  const isHumanMessage = !!humanAgent;
2449
+ // Somebody is at the keyboard, so the room is not stuck whatever came before.
1262
2450
  if (isHumanMessage)
1263
2451
  this.stallRecoveries = 0;
2452
+ // A player who uses the moderator is moderated whatever the message claimed.
2453
+ // Their composer stops offering an action at all, but this endpoint stays
2454
+ // reachable — from the published room page, from the API, from a bot — and
2455
+ // honouring a speak or a whisper there would route around the moderator the
2456
+ // room's prompts are written to expect.
2457
+ //
2458
+ // Players only. On an AI agent the flag is a declaration that it will emit
2459
+ // MODERATE itself, not an instruction to override what it chose to send.
1264
2460
  if (isHumanMessage && humanAgent.useModerator && message.action !== app_types_1.MessageAction.MODERATE) {
1265
2461
  logger_1.logger.log(`${humanAgent.agentNickname} uses the moderator; sending as moderate rather than ${message.action}`);
1266
2462
  message.action = app_types_1.MessageAction.MODERATE;
1267
2463
  message.targets = [];
1268
2464
  }
2465
+ // Players talking among themselves never enters the queue. Logging it and
2466
+ // delivering it to the other players is the whole job: nobody is prompted,
2467
+ // the turn order is not consulted, and the floor stays where it was. This is
2468
+ // the one message a player may send while an agent holds the floor.
1269
2469
  if (isHumanMessage && this.isPlayerAside(message)) {
1270
2470
  for (const target of message.getTargets()) {
1271
2471
  const player = this.getHumanAgentByName(target);
@@ -1277,16 +2477,29 @@ Recent Message: ${message.getContent()}
1277
2477
  this.addRoomMessage(message);
1278
2478
  return { accepted: true };
1279
2479
  }
2480
+ // Special handling for human messages when paused
1280
2481
  if (isHumanMessage && this.isPaused) {
1281
2482
  if (clearQueue) {
2483
+ // Clear all pending messages - human is interjecting
1282
2484
  this.pendingMessages = [];
1283
2485
  }
2486
+ // Add human's message to conversation history
1284
2487
  humanAgent.addToConversationHistory(message, true);
1285
2488
  humanAgent.save();
1286
2489
  this.pendingMessages.push(message);
2490
+ // Auto-resume processing
1287
2491
  this.resume();
1288
2492
  return { accepted: true };
1289
2493
  }
2494
+ // Validate a human can only send when the floor is a human's (non-paused state).
2495
+ //
2496
+ // The test is "any human", not "this human". The floor lands on a specific
2497
+ // player for two different reasons — an agent addressed that character, or
2498
+ // ready()/pause() handed it to the arbitrary default — and the room cannot
2499
+ // tell them apart. Enforcing it per-player would therefore lock every other
2500
+ // player out of a freshly opened or just-resumed room. So the players share
2501
+ // the floor between them and settle turn order at the table; what still gets
2502
+ // refused is speaking over an AI agent that is mid-turn.
1290
2503
  if (isHumanMessage) {
1291
2504
  if (this.currentSpeaker !== null && !this.isHumanNickname(this.currentSpeaker)) {
1292
2505
  logger_1.logger.warn(`Human agent ${humanAgent.agentNickname} tried to speak out of turn. Current speaker: ${this.currentSpeaker}`);
@@ -1297,9 +2510,11 @@ Recent Message: ${message.getContent()}
1297
2510
  }
1298
2511
  humanAgent.addToConversationHistory(message, true);
1299
2512
  humanAgent.save();
2513
+ // Clear current speaker when human responds
1300
2514
  this.setCurrentSpeaker(null);
1301
2515
  }
1302
2516
  this.pendingMessages.push(message);
2517
+ // Trigger processing if not already processing
1303
2518
  if (!this.processingInProgress) {
1304
2519
  this.processPendingMessages();
1305
2520
  }
@@ -1308,19 +2523,33 @@ Recent Message: ${message.getContent()}
1308
2523
  isProcessingInProgress() {
1309
2524
  return this.processingInProgress;
1310
2525
  }
2526
+ /**
2527
+ * True when the room is idle pending input from the human-controlled agent.
2528
+ *
2529
+ * This is distinct from `isProcessingInProgress()`: after an agent addresses
2530
+ * the human, the room intentionally leaves processing "in progress" while it
2531
+ * waits for the human's reply (the human's perceive never fires a response
2532
+ * callback). Hosts should use this flag — not `processingInProgress` — to
2533
+ * decide whether to show a typing indicator.
2534
+ */
1311
2535
  isWaitingForHuman() {
1312
2536
  if (this.getHumanAgents().length === 0) {
1313
2537
  return false;
1314
2538
  }
2539
+ // A human holds the floor (an agent addressed them, or the room is paused)
1315
2540
  if (this.isHumanNickname(this.currentSpeaker)) {
1316
2541
  return true;
1317
2542
  }
2543
+ // Idle room: nothing queued, nothing in flight, no speaker — the host's
2544
+ // next human message is what starts the conversation
1318
2545
  return (this.currentSpeaker === null &&
1319
2546
  !this.processingInProgress &&
1320
2547
  (!this.pendingMessages || this.pendingMessages.length === 0));
1321
2548
  }
1322
2549
  pause() {
1323
2550
  this.isPaused = true;
2551
+ // Give the floor to a human so they can send messages. Naming the default
2552
+ // is enough: a floor held by any human is open to all of them.
1324
2553
  const humanAgent = this.getDefaultHumanAgent();
1325
2554
  if (humanAgent) {
1326
2555
  this.currentSpeaker = humanAgent.agentNickname;
@@ -1330,6 +2559,7 @@ Recent Message: ${message.getContent()}
1330
2559
  resume() {
1331
2560
  this.isPaused = false;
1332
2561
  this.notifyStateChange();
2562
+ // Trigger processing if there are pending messages
1333
2563
  if (this.pendingMessages && this.pendingMessages.length > 0) {
1334
2564
  this.processPendingMessages();
1335
2565
  }
@@ -1339,15 +2569,37 @@ Recent Message: ${message.getContent()}
1339
2569
  this.pause();
1340
2570
  }
1341
2571
  checkAgentNicknameMatch(existingNickname, targetNickname) {
2572
+ // Nobody answers to no name. A moderator that cannot tell who should respond
2573
+ // is told to leave `name` empty, and a moderator answer that gets coerced back
2574
+ // to MODERATE arrives with a null name — so this is reached on the ordinary
2575
+ // path, not just a malformed one. Throwing here meant the caller's catch
2576
+ // swallowed the message and the room went quiet with one log line.
1342
2577
  if (!existingNickname || !targetNickname)
1343
2578
  return false;
2579
+ // Full nickname match (case-insensitive)
1344
2580
  if (existingNickname.toLowerCase() === targetNickname.toLowerCase())
1345
2581
  return true;
2582
+ // First word match (e.g., "Alex" matches "Alex Smith")
1346
2583
  const nicknameFirstWord = existingNickname.split(/\s+/)[0];
1347
2584
  if (nicknameFirstWord.toLowerCase() === targetNickname.toLowerCase())
1348
2585
  return true;
1349
2586
  return false;
1350
2587
  }
2588
+ /**
2589
+ * Hands a moderated message to one recipient in the shape that recipient needs.
2590
+ *
2591
+ * An AI agent gets the message itself, so a room whose agents answer in the JSON
2592
+ * protocol sees moderated messages in the same shape as every other one — half a
2593
+ * history in plain prose models the wrong output format, and a prose reply is
2594
+ * silently absorbed by parseAgentResponse rather than corrected, so the drift has
2595
+ * no back pressure.
2596
+ *
2597
+ * A human gets the readable form. Nothing prompts a human agent, so its history
2598
+ * is a record rather than a set of examples, and JSON is the wrong thing to keep.
2599
+ *
2600
+ * With no `relayAs` the two branches produce identical text, which is why story
2601
+ * rooms are unaffected by this distinction.
2602
+ */
1351
2603
  deliverModerated(recipient, message, content) {
1352
2604
  if (recipient.isControlledByHuman) {
1353
2605
  recipient.addToConversationHistory(`From: ${message.sender}\n${content}`, false);
@@ -1357,10 +2609,22 @@ Recent Message: ${message.getContent()}
1357
2609
  }
1358
2610
  recipient.save();
1359
2611
  }
2612
+ /**
2613
+ * Handles the moderator's routing response for a single message
2614
+ * @param moderatorMessage The routing response from the moderator
2615
+ * @param originalMessage The original message that needed routing
2616
+ */
1360
2617
  handleModeratorResponse(moderatorMessage, originalMessage) {
1361
2618
  try {
1362
2619
  let responderNickname = moderatorMessage.name;
1363
2620
  const roomLeaderName = this.getRoomLeader();
2621
+ // The moderator's audience, and nobody else. The room leader used to be
2622
+ // added to every moderated message here, which was a workaround for
2623
+ // weak models dropping the "always include the narrator" instruction —
2624
+ // the prompts now carry that rule where it belongs. Adding it in code
2625
+ // made a private exchange impossible: at a game table the party cannot
2626
+ // plan out of the leader's earshot, and an agent cannot convincingly
2627
+ // pretend not to know what is in its own history.
1364
2628
  const targets = [...(moderatorMessage.targets || [])];
1365
2629
  if (this.onModeratorResponseCallback) {
1366
2630
  this.onModeratorResponseCallback(moderatorMessage);
@@ -1370,9 +2634,19 @@ Recent Message: ${message.getContent()}
1370
2634
  content = originalMessage.getContent();
1371
2635
  if (originalMessage.content != content) {
1372
2636
  logger_1.logger.warn(`Moderator changed content:\n${originalMessage.content}\nto\n${content}`);
1373
- originalMessage.content = content;
2637
+ originalMessage.content = content; // In case the moderator changed the content
1374
2638
  }
1375
2639
  if (this.checkAgentNicknameMatch(originalMessage.sender, responderNickname)) {
2640
+ // The moderator named the sender as the next responder. Usually that is
2641
+ // a stall — the agent would talk to itself and the UI would wait forever
2642
+ // ("Waiting for Story") — but not always: an agent running consecutive
2643
+ // turns nobody else is part of has no one else to name, and this branch
2644
+ // used to overrule the moderator every time. In a played fight it did
2645
+ // exactly that, taking the floor off the Battle Master mid-round and
2646
+ // waking the Dungeon Master, whose own prompt tells it to stay out of
2647
+ // combat, so it said nothing and the room idled until a person stepped in.
2648
+ //
2649
+ // So the loop is allowed a bounded number of turns, and only then broken.
1376
2650
  if (this.mayContinueAlone(originalMessage.sender)) {
1377
2651
  logger_1.logger.log(`Moderator kept the floor with ${originalMessage.sender} (turn ${this.consecutiveSelfContinues} of ${Room.maxSelfContinues()})`);
1378
2652
  }
@@ -1386,6 +2660,12 @@ Recent Message: ${message.getContent()}
1386
2660
  else {
1387
2661
  this.clearSelfContinue();
1388
2662
  }
2663
+ // 1. Resolve the responder, before delivering to the audience, so the
2664
+ // agent that is about to be prompted is not also handed the message as
2665
+ // history. Falling back to the room leader is the established contract
2666
+ // for a moderator that names nobody — room_moderator's own prompt tells
2667
+ // it to leave `name` empty when it cannot tell, and something has to
2668
+ // take the floor or the room stalls.
1389
2669
  let responderAgent = this.agents.find((a) => this.checkAgentNicknameMatch(a.agentNickname, responderNickname));
1390
2670
  if (!responderAgent) {
1391
2671
  let roomLeaderAgent = this.agents.find((a) => a.agentNickname === roomLeaderName);
@@ -1395,42 +2675,80 @@ Recent Message: ${message.getContent()}
1395
2675
  responderAgent = roomLeaderAgent;
1396
2676
  responderNickname = roomLeaderAgent.agentNickname;
1397
2677
  }
2678
+ // An agent asked to answer a message it never heard is incoherent, so the
2679
+ // responder is always part of the audience. This narrow guarantee is what
2680
+ // replaced adding the room leader to every message: when the moderator
2681
+ // named nobody, the responder resolved above *is* the leader, so the
2682
+ // leader still hears what it is being asked to answer.
1398
2683
  if (!targets.some((target) => this.checkAgentNicknameMatch(responderAgent.agentNickname, target))) {
1399
2684
  targets.push(responderAgent.agentNickname);
1400
2685
  }
1401
2686
  logger_1.logger.log(`Moderator routing: sender=${originalMessage.sender} action=${moderatorMessage.action}${moderatorMessage.relayAs ? ` as ${moderatorMessage.relayAs}` : ''}, name=${responderNickname}, targets=${targets.join(', ')}`);
2687
+ // The message the room actually carries. `relayAs` turns it into an
2688
+ // ordinary room message — stored in the same shape as any other and
2689
+ // rendered with the right badge in the transcript. Without it the message
2690
+ // stays a MODERATE, which is the plain-prose form stories are built on.
1402
2691
  const relayed = new message_1.RoomMessage(originalMessage.sender, moderatorMessage.relayAs ?? originalMessage.action, content, targets, originalMessage.name, originalMessage.situation);
2692
+ // 2. Add the message to the room log ONLY if action is RELAY (not
2693
+ // RELAY_SILENT). RELAY_SILENT is internal processing that should not
2694
+ // appear in the room log.
1403
2695
  if (moderatorMessage.action === app_types_1.MessageAction.RELAY) {
1404
2696
  this.addRoomMessage(relayed, {
2697
+ // The situation was already processed before moderation
2698
+ // (see processPendingMessages); don't run it again here.
1405
2699
  suppressSituationUpdate: true,
1406
2700
  });
1407
2701
  }
2702
+ // 3. Give the message to the rest of the audience for awareness.
2703
+ //
2704
+ // The moderator's targets are authoritative rather than canHear(): a
2705
+ // `speak` is audible to the whole room, so delivering this through
2706
+ // hear() would broadcast a message the moderator deliberately addressed
2707
+ // to three of six agents, and sub-group conversation would be impossible.
1408
2708
  for (const recipientName of targets) {
2709
+ // The responder is prompted with it below rather than told about it.
1409
2710
  if (this.checkAgentNicknameMatch(responderAgent.agentNickname, recipientName)) {
1410
2711
  continue;
1411
2712
  }
2713
+ // The original sender already logged the message to their own history
1412
2714
  if (recipientName === originalMessage.sender)
1413
2715
  continue;
1414
2716
  const recipient = this.agents.find((a) => this.checkAgentNicknameMatch(a.agentNickname, recipientName));
1415
2717
  if (recipient)
1416
2718
  this.deliverModerated(recipient, relayed, content);
1417
2719
  }
2720
+ // Remembered for the next moderation prompt so a conversation with a
2721
+ // sub-group stays with that sub-group, instead of the moderator having to
2722
+ // reconstruct who was in it from its own short history.
1418
2723
  this.lastModeratedAudience = [...targets];
2724
+ // 4. If responder is human, just wait for their response via addPendingMessage
1419
2725
  if (responderAgent.isControlledByHuman) {
1420
2726
  logger_1.logger.log(`Waiting for human agent ${responderNickname} to respond`);
1421
2727
  this.deliverModerated(responderAgent, relayed, content);
2728
+ // Processing continues, but human has the turn. They will send their
2729
+ // message via addPendingMessage, which triggers processing again.
1422
2730
  this.endTurn({ to: responderNickname });
1423
2731
  return;
1424
2732
  }
2733
+ // 5. For AI agents, call perceive to get their response
2734
+ // Set current speaker to AI agent
1425
2735
  this.setCurrentSpeaker(responderNickname);
2736
+ // `relayed` carries the moderator's audience, so the responder sees the
2737
+ // descriptions of only the characters present for this message (see
2738
+ // getPresentCharacters).
1426
2739
  const continuing = this.checkAgentNicknameMatch(originalMessage.sender, responderAgent.agentNickname);
2740
+ // See the matching assignment in processPendingMessages: a moderated turn
2741
+ // that ends without a word said stalls the room the same way.
1427
2742
  this.lastDispatch = { message: relayed, responders: [responderAgent.agentNickname] };
1428
2743
  this.perceive(responderAgent, relayed, (response) => {
1429
2744
  if (this.isPaused) {
2745
+ // User interrupted while this perceive was in flight; drop the
2746
+ // response and leave currentSpeaker on the human (set by pause()).
1430
2747
  this.endTurn('keep');
1431
2748
  return;
1432
2749
  }
1433
2750
  if (response !== null) {
2751
+ // Add response to pending queue for next round of processing
1434
2752
  this.pendingMessages = [response, ...this.pendingMessages];
1435
2753
  if (response.action !== app_types_1.MessageAction.THINK)
1436
2754
  this.stallRecoveries = 0;
@@ -1441,14 +2759,26 @@ Recent Message: ${message.getContent()}
1441
2759
  catch (error) {
1442
2760
  logger_1.logger.error('Error parsing moderator response:', error);
1443
2761
  logger_1.logger.error('Moderator message content:', moderatorMessage.content);
2762
+ // Continue processing despite error. The floor is released because the
2763
+ // speaker was named just above, before the routing that threw — leaving
2764
+ // it set would pin the room on an agent whose turn never happened.
1444
2765
  this.endTurn('release', { drain: true });
1445
2766
  }
1446
2767
  }
2768
+ /**
2769
+ * Runs one commissioned agent's research turn and normalizes the result into
2770
+ * a DELIVER message. If the agent's terminal action isn't DELIVER it gets one
2771
+ * corrective re-prompt; a still-wrong action is coerced into a DELIVER so the
2772
+ * commissioner is never starved. Errors become a synthetic error DELIVER.
2773
+ * @param agent The commissioned agent
2774
+ * @param commission The COMMISSION message (already in the agent's history)
2775
+ * @returns The DELIVER message, or null if the room was paused/adjourned
2776
+ */
1447
2777
  async runDeliverTurn(agent, commission) {
1448
2778
  try {
1449
2779
  let response = await this.runAgentTurn(agent, commission, { inCommission: true });
1450
2780
  if (response === null)
1451
- return null;
2781
+ return null; // paused/adjourned mid-turn
1452
2782
  if (response.action !== app_types_1.MessageAction.DELIVER) {
1453
2783
  agent.addToConversationHistory(`From system: You were commissioned by ${commission.sender}. Respond now with action "deliver" targeting ${commission.sender}, containing your complete result.`, false);
1454
2784
  agent.save();
@@ -1456,6 +2786,7 @@ Recent Message: ${message.getContent()}
1456
2786
  response = await this.promptAgentOnce(agent, this.buildTransientPrompt(agent, null), variables);
1457
2787
  }
1458
2788
  if (response.action !== app_types_1.MessageAction.DELIVER) {
2789
+ // Coerce: wrap whatever the agent produced into a DELIVER
1459
2790
  return new message_1.RoomMessage(agent.agentNickname, app_types_1.MessageAction.DELIVER, response.content, [commission.sender]);
1460
2791
  }
1461
2792
  response.sender = agent.agentNickname;
@@ -1471,8 +2802,25 @@ Recent Message: ${message.getContent()}
1471
2802
  return new message_1.RoomMessage(agent.agentNickname, app_types_1.MessageAction.DELIVER, `(No deliverable: ${agent.agentNickname} encountered an error: ${e.message})`, [commission.sender]);
1472
2803
  }
1473
2804
  }
2805
+ /**
2806
+ * Orchestrates a COMMISSION message. Called from processPendingMessages with
2807
+ * the processing lock held; the lock stays held until the commissioner has
2808
+ * responded to the aggregated deliverables (or the room pauses/adjourns).
2809
+ *
2810
+ * Flow: every agent hears the commission (it is public, like SPEAK) → each AI
2811
+ * target concurrently runs its own research turn ending in a DELIVER → the
2812
+ * DELIVERs are logged and heard by the room → the commissioner receives the
2813
+ * concatenated deliverables and responds, re-entering normal processing.
2814
+ *
2815
+ * Human-controlled targets are skipped (waiting on a human while the lock is
2816
+ * held would deadlock the room) and noted in the aggregate. Nothing about an
2817
+ * in-flight commission is persisted: a server restart kills it, leaving only
2818
+ * the already-logged messages.
2819
+ * @param msg The COMMISSION message (already added to the room log)
2820
+ */
1474
2821
  async handleCommissionMessage(msg) {
1475
2822
  try {
2823
+ // 1. Resolve targets: dedupe, drop the sender, partition by kind
1476
2824
  const aiTargets = [];
1477
2825
  const humanTargetNames = [];
1478
2826
  const unknownNames = [];
@@ -1482,6 +2830,7 @@ Recent Message: ${message.getContent()}
1482
2830
  unknownNames.push(name);
1483
2831
  }
1484
2832
  else if (agent.agentNickname === msg.sender) {
2833
+ // Ignore self-targeting
1485
2834
  }
1486
2835
  else if (agent.isControlledByHuman) {
1487
2836
  humanTargetNames.push(agent.agentNickname);
@@ -1490,6 +2839,7 @@ Recent Message: ${message.getContent()}
1490
2839
  aiTargets.push(agent);
1491
2840
  }
1492
2841
  }
2842
+ // 2. Everyone but the sender hears the commission (public, like SPEAK)
1493
2843
  for (const agent of this.agents) {
1494
2844
  if (agent.agentNickname === msg.sender)
1495
2845
  continue;
@@ -1497,6 +2847,7 @@ Recent Message: ${message.getContent()}
1497
2847
  agent.save();
1498
2848
  }
1499
2849
  const commissioner = this.agents.find((a) => this.checkAgentNicknameMatch(a.agentNickname, msg.sender));
2850
+ // 3. No one to commission: tell the commissioner and let it respond
1500
2851
  if (aiTargets.length === 0) {
1501
2852
  const reasons = [];
1502
2853
  if (unknownNames.length > 0)
@@ -1507,8 +2858,13 @@ Recent Message: ${message.getContent()}
1507
2858
  await this.respondToCommissioner(commissioner, note);
1508
2859
  return;
1509
2860
  }
2861
+ // 4. All AI targets research concurrently, each ending in a DELIVER
1510
2862
  const settled = await Promise.allSettled(aiTargets.map((t) => this.runDeliverTurn(t, msg)));
2863
+ // 5. Bail if the room paused/adjourned mid-commission, or a balance
2864
+ // error already released the lock (see handleInsufficientBalance)
1511
2865
  if (this.isPaused || this.isAdjourned || !this.processingInProgress) {
2866
+ // 'keep' rather than 'release': if a pause got here first it owns the
2867
+ // floor, and if the lock is already down a balance error released it.
1512
2868
  if (this.processingInProgress)
1513
2869
  this.endTurn('keep');
1514
2870
  return;
@@ -1518,6 +2874,8 @@ Recent Message: ${message.getContent()}
1518
2874
  return result.value;
1519
2875
  return new message_1.RoomMessage(aiTargets[i].agentNickname, app_types_1.MessageAction.DELIVER, `(No deliverable: ${aiTargets[i].agentNickname} did not complete the commission)`, [msg.sender]);
1520
2876
  });
2877
+ // 6. Log each DELIVER; everyone but the commissioner (who gets the
2878
+ // aggregate next) and the deliverer hears it
1521
2879
  for (const deliver of delivers) {
1522
2880
  this.addRoomMessage(deliver);
1523
2881
  for (const agent of this.agents) {
@@ -1529,6 +2887,7 @@ Recent Message: ${message.getContent()}
1529
2887
  agent.save();
1530
2888
  }
1531
2889
  }
2890
+ // 7. Feed the aggregated deliverables to the commissioner
1532
2891
  const sections = delivers.map((d) => `## From ${d.sender}\n${d.content}`);
1533
2892
  if (humanTargetNames.length > 0) {
1534
2893
  sections.push(`(Skipped: ${humanTargetNames.join(', ')} — human-controlled agents cannot be commissioned)`);
@@ -1544,6 +2903,14 @@ Recent Message: ${message.getContent()}
1544
2903
  this.endTurn('release', { drain: true });
1545
2904
  }
1546
2905
  }
2906
+ /**
2907
+ * Delivers a system note (commission results or failure) to the commissioner,
2908
+ * lets it respond, queues that response, and releases the processing lock.
2909
+ * A human or missing commissioner just gets the note; the room then waits
2910
+ * for their next message as usual.
2911
+ * @param commissioner The commissioning agent, if found
2912
+ * @param note The system note to add to the commissioner's history
2913
+ */
1547
2914
  async respondToCommissioner(commissioner, note) {
1548
2915
  if (!commissioner) {
1549
2916
  logger_1.logger.warn('Commissioner not found in room; dropping commission results');
@@ -1552,6 +2919,7 @@ Recent Message: ${message.getContent()}
1552
2919
  commissioner.addToConversationHistory(note, false);
1553
2920
  commissioner.save();
1554
2921
  if (commissioner.isControlledByHuman) {
2922
+ // Surface the results in the room log and hand the turn to the human
1555
2923
  this.addRoomMessage(new message_1.RoomMessage('system', app_types_1.MessageAction.SYSTEM, note, [
1556
2924
  commissioner.agentNickname,
1557
2925
  ]));
@@ -1576,6 +2944,7 @@ Recent Message: ${message.getContent()}
1576
2944
  this.endTurn(this.isPaused ? 'keep' : 'release', { drain: true });
1577
2945
  }
1578
2946
  processPendingMessages() {
2947
+ // If paused, already processing, or no messages, skip
1579
2948
  if (this.isPaused ||
1580
2949
  this.processingInProgress ||
1581
2950
  !this.pendingMessages ||
@@ -1584,25 +2953,34 @@ Recent Message: ${message.getContent()}
1584
2953
  }
1585
2954
  this.processingInProgress = true;
1586
2955
  this.notifyStateChange();
2956
+ // Take current batch of messages to process
1587
2957
  const messages = [...this.pendingMessages];
1588
2958
  this.pendingMessages = [];
2959
+ // Handle special actions that bypass moderator
1589
2960
  this.handlePublishMessages(messages.filter((m) => m.getAction() === app_types_1.MessageAction.PUBLISH));
2961
+ // AI-issued EXECUTE messages are consumed inside the sender's turn
2962
+ // (see runAgentTurn); one arriving through the queue has no turn to
2963
+ // return its result to, so it is dropped.
1590
2964
  const strayExecuteMessages = messages.filter((m) => m.getAction() === app_types_1.MessageAction.EXECUTE);
1591
2965
  if (strayExecuteMessages.length > 0) {
1592
2966
  logger_1.logger.warn(`Dropping ${strayExecuteMessages.length} queued EXECUTE message(s); tool calls are handled within the sender's turn`);
1593
2967
  }
1594
2968
  this.handleAdjournMessages(messages.filter((m) => m.getAction() === app_types_1.MessageAction.ADJOURN));
2969
+ // If the room is adjourned, don't continue processing messages
1595
2970
  if (this.isAdjourned) {
1596
2971
  logger_1.logger.log(`Room ${this.name} has been adjourned. Message processing stopped.`);
1597
2972
  this.pendingMessages = null;
1598
2973
  this.endTurn('release');
1599
2974
  return;
1600
2975
  }
2976
+ // Separate MODERATE from regular messages
1601
2977
  const moderateMessages = messages.filter((m) => m.getAction() === app_types_1.MessageAction.MODERATE);
1602
2978
  let regularMessages = messages.filter((m) => m.getAction() !== app_types_1.MessageAction.MODERATE &&
1603
2979
  m.getAction() !== app_types_1.MessageAction.PUBLISH &&
1604
2980
  m.getAction() !== app_types_1.MessageAction.EXECUTE &&
1605
2981
  m.getAction() !== app_types_1.MessageAction.ADJOURN);
2982
+ // Process MODERATE messages through moderator
2983
+ // Process ONE message at a time so moderator can make routing decisions per message
1606
2984
  if (moderateMessages.length > 0) {
1607
2985
  const moderator = this.getModeratorAgent();
1608
2986
  if (!moderator) {
@@ -1610,16 +2988,26 @@ Recent Message: ${message.getContent()}
1610
2988
  this.endTurn('release');
1611
2989
  return;
1612
2990
  }
2991
+ // Take the first moderate message
1613
2992
  const originalMessage = moderateMessages[0];
2993
+ // Put any remaining moderate messages back in the queue
1614
2994
  if (moderateMessages.length > 1) {
1615
2995
  this.pendingMessages = [...moderateMessages.slice(1), ...this.pendingMessages];
1616
2996
  }
2997
+ // Process the sender's situation (if any) BEFORE moderation, and
2998
+ // wait for it to finish, so the moderator routes against the updated
2999
+ // situation and any roster changes the situation handler made. (In
3000
+ // stories, the situation handler can add a new agent to the room;
3001
+ // doing it first means the moderator won't route to an agent that
3002
+ // doesn't exist yet and bounce the message back to the room leader.)
1617
3003
  const dispatchToModerator = async () => {
1618
3004
  if (originalMessage.situation) {
1619
3005
  await this.handleSituationUpdate(originalMessage.situation, originalMessage.getContent());
1620
3006
  }
1621
3007
  await this.moderate(moderator, originalMessage, (response) => {
1622
3008
  if (this.isPaused) {
3009
+ // User interrupted while this moderate call was in flight;
3010
+ // drop the routing response and leave the room paused.
1623
3011
  this.endTurn('keep');
1624
3012
  return;
1625
3013
  }
@@ -1627,6 +3015,7 @@ Recent Message: ${message.getContent()}
1627
3015
  this.handleModeratorResponse(response, originalMessage);
1628
3016
  }
1629
3017
  else {
3018
+ // No response from moderator, continue processing
1630
3019
  this.endTurn('release', { drain: true });
1631
3020
  }
1632
3021
  });
@@ -1637,6 +3026,7 @@ Recent Message: ${message.getContent()}
1637
3026
  });
1638
3027
  return;
1639
3028
  }
3029
+ // Process regular messages (for non-story rooms or non-MODERATE messages)
1640
3030
  if (regularMessages.length === 0)
1641
3031
  return;
1642
3032
  let nextMessage;
@@ -1654,16 +3044,32 @@ Recent Message: ${message.getContent()}
1654
3044
  nextMessage = filteredMessage;
1655
3045
  }
1656
3046
  this.addRoomMessage(nextMessage);
3047
+ // COMMISSION messages get dedicated orchestration instead of the broadcast:
3048
+ // the targets run concurrent research turns ending in DELIVERs, then the
3049
+ // commissioner responds to the aggregated deliverables. The processing lock
3050
+ // stays held for the whole exchange.
1657
3051
  if (nextMessage.getAction() === app_types_1.MessageAction.COMMISSION) {
1658
3052
  void this.handleCommissionMessage(nextMessage);
1659
3053
  return;
1660
3054
  }
3055
+ // In 'directed' mode this is a single agent; in 'broadcast' it is everyone.
1661
3056
  const responders = this.selectResponders(nextMessage);
3057
+ // Everyone else still hears the message, at no LLM cost. This must use
3058
+ // hear() rather than perceive(): these agents are not counted in
3059
+ // agentsInProgress, and perceive() would fire a callback that decrements it.
1662
3060
  for (const agent of this.agents) {
1663
3061
  if (responders.includes(agent))
1664
3062
  continue;
1665
3063
  this.hear(agent, nextMessage);
1666
3064
  }
3065
+ // A human responder has no callback to release the lock (perceive returns
3066
+ // early for human agents), so a responder set with no AI agent in it would
3067
+ // hold the lock with nothing running. Hand the floor to a human instead —
3068
+ // the same thing handleModeratorResponse does when it routes to a human.
3069
+ //
3070
+ // With one human this is the single-responder case it has always handled.
3071
+ // With several it also covers the directed-mode widening fallback resolving
3072
+ // to two players, and a table where every agent is a player.
1667
3073
  const humanResponders = responders.filter((a) => a.isControlledByHuman);
1668
3074
  if (humanResponders.length > 0 && humanResponders.length === responders.length) {
1669
3075
  for (const human of humanResponders) {
@@ -1672,14 +3078,33 @@ Recent Message: ${message.getContent()}
1672
3078
  this.endTurn({ to: humanResponders[0].agentNickname });
1673
3079
  return;
1674
3080
  }
3081
+ // Name the agent that will actually answer. In broadcast mode that is
3082
+ // whoever the message targeted; in directed mode it is the resolved
3083
+ // responder, which also covers a message that named no target at all.
1675
3084
  this.setCurrentSpeaker(this.turnMode === 'directed' && responders.length > 0
1676
3085
  ? responders[0].agentNickname
1677
3086
  : nextMessage.targets[0]);
3087
+ // Counter to track how many agents have responded
1678
3088
  let agentsInProgress = responders.length;
3089
+ // Edge case: nobody to dispatch to (an empty room, or a directed message
3090
+ // that selected no responder). Release the lock here since no callback
3091
+ // will ever fire to do it, and keep draining the queue.
1679
3092
  if (agentsInProgress === 0) {
3093
+ // The floor was named just above and nobody is going to use it, so give
3094
+ // it up. A THINK or TOOL message selects no responder in directed mode,
3095
+ // and leaving the floor on its target — a name that need not even be an
3096
+ // agent — pinned the room exactly as a failed turn used to.
1680
3097
  this.endTurn('release', { drain: true });
1681
3098
  return;
1682
3099
  }
3100
+ // Call perceive on the responding agents with callback.
3101
+ // The lock is held until every one has responded (or declined to respond).
3102
+ // It is released inside the callback when agentsRemaining hits zero — do NOT
3103
+ // release it after this loop, since `perceive` is async and the loop returns
3104
+ // before agents have finished generating responses.
3105
+ // Remembered so a turn that ends without a word said can be re-routed rather
3106
+ // than leaving the room idle. Only audible messages reach here — a THINK or a
3107
+ // TOOL selects no responder — so this is always something worth answering.
1683
3108
  this.lastDispatch = {
1684
3109
  message: nextMessage,
1685
3110
  responders: responders.map((a) => a.agentNickname),
@@ -1689,13 +3114,49 @@ Recent Message: ${message.getContent()}
1689
3114
  const continuing = agent.agentNickname === nextMessage.getSender();
1690
3115
  this.perceive(agent, nextMessage, (message) => {
1691
3116
  agentsInProgress--;
3117
+ // Process the response immediately
1692
3118
  this.queueAgentResponse(message);
3119
+ // When all agents have responded, continue processing.
3120
+ //
3121
+ // Releasing the floor here is what stops a failed turn killing the
3122
+ // room: a turn that ends with no message queues nothing, so without
3123
+ // this no later round ever overwrites the speaker and every human
3124
+ // message is refused with "It is <Agent>'s turn to speak" forever.
3125
+ // 'keep' while paused, because pause() has already handed the floor
3126
+ // to the human and this callback must not take it back.
1693
3127
  if (agentsInProgress === 0) {
1694
3128
  this.endTurn(this.isPaused ? 'keep' : 'release', { drain: true });
1695
3129
  }
1696
3130
  }, { continuing });
1697
3131
  }
1698
3132
  }
3133
+ /**
3134
+ * Protects a specialist's history when the room leader hands it a task.
3135
+ *
3136
+ * A specialist runs on a short rolling window so it does not carry the last job
3137
+ * into the next one. That window is wrong *within* a job: a whole encounter or a
3138
+ * whole character interview can run longer than the window is wide. Pinning at
3139
+ * the handoff keeps everything from that message on, while the window still
3140
+ * drops what came before — so the second job forgets the first, and neither
3141
+ * forgets itself.
3142
+ *
3143
+ * Three conditions, all needed:
3144
+ *
3145
+ * - **the sender is the room leader**, because a handoff is the leader delegating;
3146
+ * - **the message names this agent**, so a general announcement is not a new task
3147
+ * and cannot re-pin one already running;
3148
+ * - **the agent has a window**, which makes this a no-op for everyone else. The
3149
+ * Dungeon Master keeps its whole campaign whether or not this runs.
3150
+ *
3151
+ * Called *before* {@link perceive}, so the handoff instruction itself is inside
3152
+ * the pin rather than the first casualty of the next trim.
3153
+ *
3154
+ * There is no unpin. Re-pinning ends the previous pin, so an abandoned task is
3155
+ * reclaimed by the next one and the worst a stale pin does is keep more history
3156
+ * than intended.
3157
+ * @param agent The agent about to be prompted
3158
+ * @param message The message being dispatched to it
3159
+ */
1699
3160
  pinHistoryOnHandoff(agent, message) {
1700
3161
  const leader = this.getRoomLeader();
1701
3162
  if (!leader || !this.checkAgentNicknameMatch(leader, message.getSender()))
@@ -1709,6 +3170,32 @@ Recent Message: ${message.getContent()}
1709
3170
  return;
1710
3171
  agent.pinHistory();
1711
3172
  }
3173
+ /**
3174
+ * Decides which agents are asked to respond to a message.
3175
+ *
3176
+ * In 'broadcast' mode every agent responds and {@link filterConcurrentMessages}
3177
+ * later keeps one reply, discarding the rest. In 'directed' mode exactly one
3178
+ * agent responds — the first target that resolves to an agent, or the room
3179
+ * leader when no target does — so a leader agent controls the order of play
3180
+ * and no work is paid for and thrown away. Agents that are not selected still
3181
+ * receive the message through {@link hear}.
3182
+ *
3183
+ * The sender is never selected: a self-loop would have the agent answer
3184
+ * itself and stall the room. If neither a target nor the leader resolves to
3185
+ * someone other than the sender, this widens to everyone else who can hear
3186
+ * the message, so a misaddressed message still gets a reply from somebody.
3187
+ * @param message The message being processed
3188
+ * @returns The agents to prompt, in the order they should be dispatched
3189
+ */
3190
+ /**
3191
+ * Whether an agent that has addressed itself may keep the floor.
3192
+ *
3193
+ * Counts consecutive turns rather than total ones: a run ends the moment anyone
3194
+ * else takes the floor, so an agent that legitimately keeps it twice during one
3195
+ * fight and twice more during the next is never penalised for the first pair.
3196
+ * @param sender The agent asking to answer itself
3197
+ * @returns True when it keeps the floor, false when the run has gone on too long
3198
+ */
1712
3199
  mayContinueAlone(sender) {
1713
3200
  if (this.selfContinuingAgent !== sender) {
1714
3201
  this.selfContinuingAgent = sender;
@@ -1722,6 +3209,7 @@ Recent Message: ${message.getContent()}
1722
3209
  this.consecutiveSelfContinues += 1;
1723
3210
  return true;
1724
3211
  }
3212
+ /** Ends a self-continue run, because the floor has gone to somebody else. */
1725
3213
  clearSelfContinue() {
1726
3214
  this.selfContinuingAgent = null;
1727
3215
  this.consecutiveSelfContinues = 0;
@@ -1730,6 +3218,7 @@ Recent Message: ${message.getContent()}
1730
3218
  if (this.turnMode !== 'directed') {
1731
3219
  return [...this.agents];
1732
3220
  }
3221
+ // Inaudible messages never prompt anyone.
1733
3222
  const action = message.getAction();
1734
3223
  if (action === app_types_1.MessageAction.THINK || action === app_types_1.MessageAction.TOOL) {
1735
3224
  return [];
@@ -1737,8 +3226,10 @@ Recent Message: ${message.getContent()}
1737
3226
  for (const name of message.getTargets() || []) {
1738
3227
  const target = this.agents.find((a) => this.checkAgentNicknameMatch(a.agentNickname, name));
1739
3228
  if (!target)
1740
- continue;
3229
+ continue; // Unknown name: try the next target
1741
3230
  if (target.agentNickname === message.getSender()) {
3231
+ // Addressing itself. Normally a stall, but it is also the only way an
3232
+ // agent can say "I am not finished" when there is nobody to hand to.
1742
3233
  if (!this.mayContinueAlone(message.getSender()))
1743
3234
  continue;
1744
3235
  return [target];
@@ -1755,6 +3246,12 @@ Recent Message: ${message.getContent()}
1755
3246
  logger_1.logger.warn(`Directed room ${this.name}: neither a target nor the leader could answer ${message.getSender()}; widening to ${others.length} other agent(s)`);
1756
3247
  return others;
1757
3248
  }
3249
+ /**
3250
+ * Filters concurrent messages to ensure only one message is processed
3251
+ * Priority: SHOUT > SPEAK > WHISPER, then by agent order in room
3252
+ * @param messages Array of messages to filter
3253
+ * @returns Single message (or original if <= 1)
3254
+ */
1758
3255
  filterConcurrentMessages(messages) {
1759
3256
  if (messages.length == 0)
1760
3257
  return null;
@@ -1766,27 +3263,33 @@ Recent Message: ${message.getContent()}
1766
3263
  if (systemMessages.length > 0) {
1767
3264
  return systemMessages[0];
1768
3265
  }
3266
+ // Step 1: Check for SHOUT - highest priority
1769
3267
  const shoutMessages = filtered.filter((m) => m.getAction() === app_types_1.MessageAction.SHOUT);
1770
3268
  if (shoutMessages.length > 0) {
1771
3269
  filtered = shoutMessages;
1772
3270
  }
3271
+ // Step 2: If still multiple, apply SPEAK/WHISPER rules
3272
+ // (COMMISSION competes at SPEAK priority)
1773
3273
  if (filtered.length > 1) {
1774
3274
  const speakMessages = filtered.filter((m) => m.getAction() === app_types_1.MessageAction.SPEAK ||
1775
3275
  m.getAction() === app_types_1.MessageAction.COMMISSION);
1776
3276
  const whisperMessages = filtered.filter((m) => m.getAction() === app_types_1.MessageAction.WHISPER);
1777
3277
  if (speakMessages.length > 0) {
3278
+ // If anyone speaks, remove all whispers
1778
3279
  filtered = speakMessages;
1779
3280
  }
1780
3281
  else {
1781
3282
  filtered = whisperMessages;
1782
3283
  }
1783
3284
  }
3285
+ // Step 3: If still multiple, check to see if one of them was targeted to speak next by the previous message
1784
3286
  if (filtered.length > 1) {
1785
3287
  const targetedMessages = filtered.filter((m) => m.getSender() === this.currentSpeaker);
1786
3288
  if (targetedMessages.length === 1) {
1787
3289
  filtered = targetedMessages;
1788
3290
  }
1789
3291
  }
3292
+ // Step 4: If still multiple, pick the first one in the room order
1790
3293
  if (filtered.length > 1) {
1791
3294
  let earliestMessage = null;
1792
3295
  let earliestIndex = Infinity;
@@ -1801,6 +3304,7 @@ Recent Message: ${message.getContent()}
1801
3304
  filtered = [earliestMessage];
1802
3305
  }
1803
3306
  else if (filtered.length > 0) {
3307
+ // Fallback: keep first message if no agent match found
1804
3308
  filtered = [filtered[0]];
1805
3309
  }
1806
3310
  }