briyah 2.0.3 → 2.0.4

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