briyah 2.0.3 → 2.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (391) hide show
  1. package/README.md +55 -8
  2. package/data/common/config/LICENSE-model-prices.md +65 -0
  3. package/data/common/config/markup +1 -1
  4. package/data/common/config/model_prices.json +47443 -46295
  5. package/data/common/config/story_models.json +3 -3
  6. package/data/common/prompts/illustrator/describe_scene.prompt +4 -4
  7. package/data/common/prompts/narrator/create_story.prompt +2 -0
  8. package/data/common/prompts/perceive.prompt +1 -1
  9. package/data/packs/dnd5e/prompts/battle_master/perceive.prompt +1 -1
  10. package/data/packs/dnd5e/prompts/campaign_designer/perceive.prompt +1 -1
  11. package/data/packs/dnd5e/prompts/character_creator/perceive.prompt +795 -787
  12. package/data/packs/dnd5e/prompts/dungeon_master/defaults_config.json +2 -1
  13. package/data/packs/dnd5e/prompts/dungeon_master/perceive.prompt +1 -1
  14. package/data/packs/dnd5e/rooms/campaign.json +18 -15
  15. package/data/packs/dnd5e/rooms/table.json +17 -16
  16. package/dist-sdk/server/src/ai/LLM/anthropic.service.d.ts +103 -0
  17. package/dist-sdk/server/src/ai/LLM/anthropic.service.js +174 -3
  18. package/dist-sdk/server/src/ai/LLM/base-ai.service.d.ts +194 -3
  19. package/dist-sdk/server/src/ai/LLM/base-ai.service.js +299 -19
  20. package/dist-sdk/server/src/ai/LLM/blank-image.d.ts +36 -0
  21. package/dist-sdk/server/src/ai/LLM/blank-image.js +80 -0
  22. package/dist-sdk/server/src/ai/LLM/comfyui-client.d.ts +26 -0
  23. package/dist-sdk/server/src/ai/LLM/comfyui-client.js +25 -0
  24. package/dist-sdk/server/src/ai/LLM/comfyui-workflow.d.ts +54 -0
  25. package/dist-sdk/server/src/ai/LLM/comfyui-workflow.js +59 -1
  26. package/dist-sdk/server/src/ai/LLM/comfyui.service.d.ts +21 -1
  27. package/dist-sdk/server/src/ai/LLM/comfyui.service.js +25 -1
  28. package/dist-sdk/server/src/ai/LLM/deepseek.service.d.ts +52 -0
  29. package/dist-sdk/server/src/ai/LLM/deepseek.service.js +103 -4
  30. package/dist-sdk/server/src/ai/LLM/fal.service.d.ts +25 -0
  31. package/dist-sdk/server/src/ai/LLM/fal.service.js +56 -2
  32. package/dist-sdk/server/src/ai/LLM/googleai.service.d.ts +19 -0
  33. package/dist-sdk/server/src/ai/LLM/googleai.service.js +43 -2
  34. package/dist-sdk/server/src/ai/LLM/grok.service.d.ts +22 -0
  35. package/dist-sdk/server/src/ai/LLM/grok.service.js +55 -3
  36. package/dist-sdk/server/src/ai/LLM/mock.service.js +31 -4
  37. package/dist-sdk/server/src/ai/LLM/openai.service.d.ts +30 -0
  38. package/dist-sdk/server/src/ai/LLM/openai.service.js +81 -3
  39. package/dist-sdk/server/src/ai/LLM/self-hosted.service.d.ts +21 -0
  40. package/dist-sdk/server/src/ai/LLM/self-hosted.service.js +45 -3
  41. package/dist-sdk/server/src/ai/LLM/together.service.d.ts +30 -0
  42. package/dist-sdk/server/src/ai/LLM/together.service.js +61 -3
  43. package/dist-sdk/server/src/ai/agent-config.d.ts +15 -1
  44. package/dist-sdk/server/src/ai/agent-factory.d.ts +16 -0
  45. package/dist-sdk/server/src/ai/agent-factory.js +20 -0
  46. package/dist-sdk/server/src/ai/agent-message.service.d.ts +30 -0
  47. package/dist-sdk/server/src/ai/agent-message.service.js +30 -0
  48. package/dist-sdk/server/src/ai/agent-store.service.d.ts +80 -0
  49. package/dist-sdk/server/src/ai/agent-store.service.js +166 -7
  50. package/dist-sdk/server/src/ai/agent.d.ts +197 -2
  51. package/dist-sdk/server/src/ai/agent.js +225 -14
  52. package/dist-sdk/server/src/ai/ai-debug-logger.d.ts +18 -0
  53. package/dist-sdk/server/src/ai/ai-debug-logger.js +19 -0
  54. package/dist-sdk/server/src/ai/ai-factory.service.d.ts +9 -0
  55. package/dist-sdk/server/src/ai/ai-factory.service.js +9 -0
  56. package/dist-sdk/server/src/ai/artifact.service.d.ts +131 -0
  57. package/dist-sdk/server/src/ai/artifact.service.js +148 -3
  58. package/dist-sdk/server/src/ai/attached-file.service.d.ts +87 -0
  59. package/dist-sdk/server/src/ai/attached-file.service.js +105 -0
  60. package/dist-sdk/server/src/ai/model_prices.d.ts +30 -0
  61. package/dist-sdk/server/src/ai/model_prices.js +91 -5
  62. package/dist-sdk/server/src/ai/pack-artifacts.d.ts +84 -0
  63. package/dist-sdk/server/src/ai/pack-artifacts.js +168 -0
  64. package/dist-sdk/server/src/ai/published-agents.service.d.ts +25 -0
  65. package/dist-sdk/server/src/ai/published-agents.service.js +30 -3
  66. package/dist-sdk/server/src/app/balance-message.service.d.ts +24 -0
  67. package/dist-sdk/server/src/app/balance-message.service.js +24 -0
  68. package/dist-sdk/server/src/app/balance.module.d.ts +4 -0
  69. package/dist-sdk/server/src/app/balance.module.js +4 -0
  70. package/dist-sdk/server/src/app/balance.service.d.ts +37 -0
  71. package/dist-sdk/server/src/app/balance.service.js +54 -0
  72. package/dist-sdk/server/src/app/stripe.controller.d.ts +21 -0
  73. package/dist-sdk/server/src/app/stripe.controller.js +35 -0
  74. package/dist-sdk/server/src/app/stripe.service.d.ts +43 -0
  75. package/dist-sdk/server/src/app/stripe.service.js +62 -0
  76. package/dist-sdk/server/src/app/transaction.service.d.ts +27 -0
  77. package/dist-sdk/server/src/app/transaction.service.js +36 -0
  78. package/dist-sdk/server/src/app/user-service-factory.d.ts +8 -0
  79. package/dist-sdk/server/src/app/user-service-factory.js +46 -3
  80. package/dist-sdk/server/src/app/user-service-manager.d.ts +27 -0
  81. package/dist-sdk/server/src/app/user-service-manager.js +43 -0
  82. package/dist-sdk/server/src/app.controller.d.ts +120 -0
  83. package/dist-sdk/server/src/app.controller.js +365 -14
  84. package/dist-sdk/server/src/app.module.js +28 -6
  85. package/dist-sdk/server/src/app.service.d.ts +1710 -4
  86. package/dist-sdk/server/src/app.service.js +1938 -20
  87. package/dist-sdk/server/src/auth/agent-access.decorator.d.ts +17 -0
  88. package/dist-sdk/server/src/auth/agent-access.decorator.js +17 -0
  89. package/dist-sdk/server/src/auth/auth.controller.js +46 -0
  90. package/dist-sdk/server/src/auth/auth.module.js +3 -2
  91. package/dist-sdk/server/src/auth/auth.service.d.ts +33 -0
  92. package/dist-sdk/server/src/auth/auth.service.js +39 -3
  93. package/dist-sdk/server/src/auth/jwt-auth.guard.js +44 -0
  94. package/dist-sdk/server/src/auth/jwt.strategy.js +2 -2
  95. package/dist-sdk/server/src/auth/owner-only.decorator.d.ts +9 -0
  96. package/dist-sdk/server/src/auth/owner-only.decorator.js +9 -0
  97. package/dist-sdk/server/src/auth/phone-validation.service.d.ts +25 -0
  98. package/dist-sdk/server/src/auth/phone-validation.service.js +30 -0
  99. package/dist-sdk/server/src/auth/rate-limit.service.d.ts +19 -0
  100. package/dist-sdk/server/src/auth/rate-limit.service.js +24 -0
  101. package/dist-sdk/server/src/auth/room-access.decorator.d.ts +8 -0
  102. package/dist-sdk/server/src/auth/room-access.decorator.js +8 -0
  103. package/dist-sdk/server/src/auth/scopes.decorator.d.ts +7 -0
  104. package/dist-sdk/server/src/auth/scopes.decorator.js +7 -0
  105. package/dist-sdk/server/src/auth/scopes.guard.d.ts +16 -0
  106. package/dist-sdk/server/src/auth/scopes.guard.js +30 -0
  107. package/dist-sdk/server/src/auth/session.guard.d.ts +4 -0
  108. package/dist-sdk/server/src/auth/session.guard.js +8 -0
  109. package/dist-sdk/server/src/auth/twilio.service.d.ts +27 -0
  110. package/dist-sdk/server/src/auth/twilio.service.js +30 -4
  111. package/dist-sdk/server/src/auth/users.service.d.ts +30 -0
  112. package/dist-sdk/server/src/auth/users.service.js +42 -0
  113. package/dist-sdk/server/src/common/errors.d.ts +20 -0
  114. package/dist-sdk/server/src/common/errors.js +21 -0
  115. package/dist-sdk/server/src/config/env-config.d.ts +7 -0
  116. package/dist-sdk/server/src/config/prompt-resolver.d.ts +180 -0
  117. package/dist-sdk/server/src/config/prompt-resolver.js +182 -0
  118. package/dist-sdk/server/src/config/user-config.service.d.ts +59 -0
  119. package/dist-sdk/server/src/config/user-config.service.js +57 -0
  120. package/dist-sdk/server/src/config/user-paths.service.d.ts +61 -0
  121. package/dist-sdk/server/src/config/user-paths.service.js +67 -0
  122. package/dist-sdk/server/src/documents/pdf-conversion.d.ts +121 -1
  123. package/dist-sdk/server/src/documents/pdf-conversion.js +94 -0
  124. package/dist-sdk/server/src/packs/pack-instantiation.service.d.ts +98 -0
  125. package/dist-sdk/server/src/packs/pack-instantiation.service.js +104 -0
  126. package/dist-sdk/server/src/packs/pack-manifest.d.ts +114 -0
  127. package/dist-sdk/server/src/packs/pack-manifest.js +69 -0
  128. package/dist-sdk/server/src/packs/pack.service.d.ts +99 -1
  129. package/dist-sdk/server/src/packs/pack.service.js +98 -1
  130. package/dist-sdk/server/src/room/artifact-store.service.d.ts +27 -0
  131. package/dist-sdk/server/src/room/artifact-store.service.js +49 -3
  132. package/dist-sdk/server/src/room/artifact.d.ts +18 -0
  133. package/dist-sdk/server/src/room/illustration/illustration.service.d.ts +211 -0
  134. package/dist-sdk/server/src/room/illustration/illustration.service.js +771 -0
  135. package/dist-sdk/server/src/room/illustration/illustration.types.d.ts +101 -0
  136. package/dist-sdk/server/src/room/illustration/illustration.types.js +2 -0
  137. package/dist-sdk/server/src/room/message.d.ts +64 -0
  138. package/dist-sdk/server/src/room/message.js +77 -2
  139. package/dist-sdk/server/src/room/nickname.d.ts +26 -0
  140. package/dist-sdk/server/src/room/nickname.js +26 -0
  141. package/dist-sdk/server/src/room/published-rooms.service.js +2 -0
  142. package/dist-sdk/server/src/room/room-config.d.ts +84 -1
  143. package/dist-sdk/server/src/room/room-config.js +19 -0
  144. package/dist-sdk/server/src/room/room-factory.d.ts +20 -0
  145. package/dist-sdk/server/src/room/room-factory.js +25 -0
  146. package/dist-sdk/server/src/room/room-message.service.d.ts +28 -0
  147. package/dist-sdk/server/src/room/room-message.service.js +28 -0
  148. package/dist-sdk/server/src/room/room-store.service.d.ts +184 -0
  149. package/dist-sdk/server/src/room/room-store.service.js +280 -6
  150. package/dist-sdk/server/src/room/room.d.ts +981 -1
  151. package/dist-sdk/server/src/room/room.js +1531 -27
  152. package/dist-sdk/server/src/rpg/rpg-models.d.ts +50 -0
  153. package/dist-sdk/server/src/rpg/rpg-models.js +53 -0
  154. package/dist-sdk/server/src/rpg/rpg-roster.d.ts +37 -0
  155. package/dist-sdk/server/src/rpg/rpg-roster.js +37 -0
  156. package/dist-sdk/server/src/rpg/rpg.service.d.ts +87 -0
  157. package/dist-sdk/server/src/rpg/rpg.service.js +108 -1
  158. package/dist-sdk/server/src/sdk/briyah-config.d.ts +57 -0
  159. package/dist-sdk/server/src/sdk/briyah-config.js +17 -0
  160. package/dist-sdk/server/src/sdk/briyah.d.ts +228 -0
  161. package/dist-sdk/server/src/sdk/briyah.js +285 -7
  162. package/dist-sdk/server/src/sdk/index.js +23 -0
  163. package/dist-sdk/server/src/shared/shared.module.d.ts +8 -0
  164. package/dist-sdk/server/src/shared/shared.module.js +13 -5
  165. package/dist-sdk/server/src/story/story-message.service.d.ts +43 -0
  166. package/dist-sdk/server/src/story/story-message.service.js +43 -0
  167. package/dist-sdk/server/src/story/story-progress.service.d.ts +23 -0
  168. package/dist-sdk/server/src/story/story-progress.service.js +23 -0
  169. package/dist-sdk/server/src/story/story-store.service.d.ts +92 -0
  170. package/dist-sdk/server/src/story/story-store.service.js +136 -1
  171. package/dist-sdk/server/src/story/story.service.d.ts +366 -9
  172. package/dist-sdk/server/src/story/story.service.js +825 -374
  173. package/dist-sdk/server/src/tools/core/illustrate.tool.d.ts +14 -0
  174. package/dist-sdk/server/src/tools/core/illustrate.tool.js +80 -0
  175. package/dist-sdk/server/src/tools/core/index.d.ts +22 -0
  176. package/dist-sdk/server/src/tools/core/index.js +24 -1
  177. package/dist-sdk/server/src/tools/core/rename.tool.d.ts +8 -0
  178. package/dist-sdk/server/src/tools/core/rename.tool.js +11 -0
  179. package/dist-sdk/server/src/tools/native-tool-registry.service.d.ts +22 -0
  180. package/dist-sdk/server/src/tools/native-tool-registry.service.js +22 -0
  181. package/dist-sdk/server/src/tools/native-tool.types.d.ts +266 -0
  182. package/dist-sdk/server/src/tools/packs/dnd5e/data/backgrounds.d.ts +29 -0
  183. package/dist-sdk/server/src/tools/packs/dnd5e/data/backgrounds.js +29 -0
  184. package/dist-sdk/server/src/tools/packs/dnd5e/data/cantrips.d.ts +46 -0
  185. package/dist-sdk/server/src/tools/packs/dnd5e/data/cantrips.js +40 -0
  186. package/dist-sdk/server/src/tools/packs/dnd5e/data/feats.d.ts +33 -0
  187. package/dist-sdk/server/src/tools/packs/dnd5e/data/feats.js +19 -0
  188. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.d.ts +37 -0
  189. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.generated.d.ts +17 -0
  190. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.generated.js +17 -0
  191. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.js +27 -0
  192. package/dist-sdk/server/src/tools/packs/dnd5e/data/kits.d.ts +36 -0
  193. package/dist-sdk/server/src/tools/packs/dnd5e/data/kits.js +32 -0
  194. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.d.ts +32 -0
  195. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.generated.d.ts +13 -0
  196. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.generated.js +13 -0
  197. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.js +18 -0
  198. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.d.ts +54 -0
  199. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.generated.d.ts +13 -0
  200. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.generated.js +13 -0
  201. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.js +20 -0
  202. package/dist-sdk/server/src/tools/packs/dnd5e/data/races.d.ts +36 -0
  203. package/dist-sdk/server/src/tools/packs/dnd5e/data/races.js +18 -0
  204. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.d.ts +29 -0
  205. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.generated.d.ts +13 -0
  206. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.generated.js +13 -0
  207. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.js +21 -0
  208. package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.d.ts +95 -0
  209. package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.js +66 -2
  210. package/dist-sdk/server/src/tools/packs/dnd5e/data/weapons.d.ts +50 -0
  211. package/dist-sdk/server/src/tools/packs/dnd5e/data/weapons.js +28 -0
  212. package/dist-sdk/server/src/tools/packs/dnd5e/engine/bestiary.d.ts +92 -0
  213. package/dist-sdk/server/src/tools/packs/dnd5e/engine/bestiary.js +152 -0
  214. package/dist-sdk/server/src/tools/packs/dnd5e/engine/campaign-items.d.ts +28 -0
  215. package/dist-sdk/server/src/tools/packs/dnd5e/engine/campaign-items.js +29 -0
  216. package/dist-sdk/server/src/tools/packs/dnd5e/engine/cantrips.d.ts +31 -0
  217. package/dist-sdk/server/src/tools/packs/dnd5e/engine/cantrips.js +36 -2
  218. package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.d.ts +261 -0
  219. package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.js +401 -0
  220. package/dist-sdk/server/src/tools/packs/dnd5e/engine/coerce.d.ts +11 -0
  221. package/dist-sdk/server/src/tools/packs/dnd5e/engine/coerce.js +11 -0
  222. package/dist-sdk/server/src/tools/packs/dnd5e/engine/dice.d.ts +65 -0
  223. package/dist-sdk/server/src/tools/packs/dnd5e/engine/dice.js +67 -0
  224. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encounter.d.ts +73 -0
  225. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encounter.js +63 -0
  226. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encumbrance.d.ts +66 -0
  227. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encumbrance.js +59 -0
  228. package/dist-sdk/server/src/tools/packs/dnd5e/engine/feats.d.ts +54 -0
  229. package/dist-sdk/server/src/tools/packs/dnd5e/engine/feats.js +49 -0
  230. package/dist-sdk/server/src/tools/packs/dnd5e/engine/foes.d.ts +42 -0
  231. package/dist-sdk/server/src/tools/packs/dnd5e/engine/foes.js +59 -0
  232. package/dist-sdk/server/src/tools/packs/dnd5e/engine/guides.d.ts +72 -0
  233. package/dist-sdk/server/src/tools/packs/dnd5e/engine/guides.js +63 -0
  234. package/dist-sdk/server/src/tools/packs/dnd5e/engine/items.d.ts +57 -0
  235. package/dist-sdk/server/src/tools/packs/dnd5e/engine/items.js +54 -0
  236. package/dist-sdk/server/src/tools/packs/dnd5e/engine/kits.d.ts +81 -0
  237. package/dist-sdk/server/src/tools/packs/dnd5e/engine/kits.js +85 -0
  238. package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.d.ts +60 -0
  239. package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.js +64 -0
  240. package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.d.ts +169 -0
  241. package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.js +203 -0
  242. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.d.ts +201 -0
  243. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.js +149 -0
  244. package/dist-sdk/server/src/tools/packs/dnd5e/engine/spells.d.ts +56 -0
  245. package/dist-sdk/server/src/tools/packs/dnd5e/engine/spells.js +54 -0
  246. package/dist-sdk/server/src/tools/packs/dnd5e/engine/weapons.d.ts +65 -0
  247. package/dist-sdk/server/src/tools/packs/dnd5e/engine/weapons.js +73 -0
  248. package/dist-sdk/server/src/tools/packs/dnd5e/index.d.ts +18 -0
  249. package/dist-sdk/server/src/tools/packs/dnd5e/index.js +18 -0
  250. package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.d.ts +4 -0
  251. package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.js +116 -1
  252. package/dist-sdk/server/src/tools/packs/dnd5e/tools/class.tool.d.ts +14 -0
  253. package/dist-sdk/server/src/tools/packs/dnd5e/tools/class.tool.js +17 -0
  254. package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.d.ts +1 -0
  255. package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.js +35 -1
  256. package/dist-sdk/server/src/tools/packs/dnd5e/tools/encounter.tool.d.ts +6 -0
  257. package/dist-sdk/server/src/tools/packs/dnd5e/tools/encounter.tool.js +25 -0
  258. package/dist-sdk/server/src/tools/packs/dnd5e/tools/item.tool.d.ts +7 -0
  259. package/dist-sdk/server/src/tools/packs/dnd5e/tools/item.tool.js +13 -0
  260. package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.d.ts +8 -0
  261. package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.js +55 -0
  262. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.d.ts +194 -0
  263. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.js +263 -1
  264. package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.d.ts +1 -0
  265. package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.js +127 -2
  266. package/dist-sdk/server/src/tools/packs/dnd5e/tools/spell.tool.d.ts +13 -0
  267. package/dist-sdk/server/src/tools/packs/dnd5e/tools/spell.tool.js +18 -0
  268. package/dist-sdk/server/src/tools/packs/dnd5e/tools/state.tools.d.ts +1 -0
  269. package/dist-sdk/server/src/tools/packs/dnd5e/tools/state.tools.js +23 -0
  270. package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.d.ts +1 -0
  271. package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.js +35 -0
  272. package/dist-sdk/server/src/tools/packs/index.d.ts +49 -0
  273. package/dist-sdk/server/src/tools/packs/index.js +66 -0
  274. package/dist-sdk/server/src/tools/shared/coerce.d.ts +95 -0
  275. package/dist-sdk/server/src/tools/shared/coerce.js +98 -0
  276. package/dist-sdk/server/src/tools/tool-execution.service.d.ts +107 -3
  277. package/dist-sdk/server/src/tools/tool-execution.service.js +163 -19
  278. package/dist-sdk/server/src/tools/tool-store.service.d.ts +11 -0
  279. package/dist-sdk/server/src/tools/tool-store.service.js +13 -1
  280. package/dist-sdk/shared/types/app.types.d.ts +328 -13
  281. package/dist-sdk/shared/types/app.types.js +18 -1
  282. package/package.json +167 -168
  283. package/data/common/config/random_words.txt +0 -2241
  284. package/data/common/story_ideas/biblical.json +0 -122
  285. package/data/common/story_ideas/fantasy.json +0 -82
  286. package/data/common/story_ideas/historical_fiction.json +0 -82
  287. package/data/common/story_ideas/science_fiction.json +0 -82
  288. package/docs/.nojekyll +0 -1
  289. package/docs/assets/hierarchy.js +0 -1
  290. package/docs/assets/highlight.css +0 -113
  291. package/docs/assets/icons.js +0 -18
  292. package/docs/assets/icons.svg +0 -1
  293. package/docs/assets/main.js +0 -60
  294. package/docs/assets/navigation.js +0 -1
  295. package/docs/assets/search.js +0 -1
  296. package/docs/assets/style.css +0 -1648
  297. package/docs/classes/Agent.html +0 -801
  298. package/docs/classes/Briyah.html +0 -296
  299. package/docs/classes/BriyahConfigService.html +0 -119
  300. package/docs/classes/NativeToolRegistry.html +0 -166
  301. package/docs/classes/PackInstantiationService.html +0 -157
  302. package/docs/classes/PackService.html +0 -247
  303. package/docs/classes/Room.html +0 -1434
  304. package/docs/classes/RoomMessage.html +0 -290
  305. package/docs/enums/MessageAction.html +0 -136
  306. package/docs/functions/availableToolPacks.html +0 -41
  307. package/docs/functions/buildMarkdown.html +0 -54
  308. package/docs/functions/dnd5eTools.html +0 -44
  309. package/docs/functions/installToolPacks.html +0 -51
  310. package/docs/functions/pageMarker.html +0 -45
  311. package/docs/functions/registerToolPacks.html +0 -54
  312. package/docs/functions/splitMarkdownIntoPages.html +0 -51
  313. package/docs/functions/stripWrappingFence.html +0 -52
  314. package/docs/hierarchy.html +0 -46
  315. package/docs/index.html +0 -595
  316. package/docs/interfaces/AgentCreationOptions.html +0 -125
  317. package/docs/interfaces/AgentInfo.html +0 -218
  318. package/docs/interfaces/AgentMessagesResponse.html +0 -74
  319. package/docs/interfaces/AppService.html +0 -3340
  320. package/docs/interfaces/Artifact.html +0 -95
  321. package/docs/interfaces/ArtifactMetadata.html +0 -112
  322. package/docs/interfaces/ArtifactWriteOptions.html +0 -90
  323. package/docs/interfaces/AttachDocumentResponse.html +0 -62
  324. package/docs/interfaces/BriyahConfigOptions.html +0 -124
  325. package/docs/interfaces/ChapterInfo.html +0 -62
  326. package/docs/interfaces/Character.html +0 -86
  327. package/docs/interfaces/ConversionAgent.html +0 -78
  328. package/docs/interfaces/CreateAgentResponse.html +0 -56
  329. package/docs/interfaces/CreateRoomResponse.html +0 -62
  330. package/docs/interfaces/CreateStoryResponse.html +0 -56
  331. package/docs/interfaces/FileList.html +0 -56
  332. package/docs/interfaces/FileMetadata.html +0 -89
  333. package/docs/interfaces/IConfigService.html +0 -79
  334. package/docs/interfaces/InstantiateModels.html +0 -64
  335. package/docs/interfaces/InstantiateRoomResult.html +0 -70
  336. package/docs/interfaces/LoadedPack.html +0 -131
  337. package/docs/interfaces/LoggingOptions.html +0 -92
  338. package/docs/interfaces/Message.html +0 -84
  339. package/docs/interfaces/ModelChoice.html +0 -73
  340. package/docs/interfaces/ModelInfo.html +0 -74
  341. package/docs/interfaces/NativeToolDefinition.html +0 -107
  342. package/docs/interfaces/PackAgentTemplate.html +0 -101
  343. package/docs/interfaces/PackRoomTemplate.html +0 -108
  344. package/docs/interfaces/PackView.html +0 -172
  345. package/docs/interfaces/PdfConversionOptions.html +0 -102
  346. package/docs/interfaces/PdfConversionResult.html +0 -97
  347. package/docs/interfaces/PdfMarkdownOptions.html +0 -198
  348. package/docs/interfaces/PdfMarkdownResult.html +0 -106
  349. package/docs/interfaces/PdfPageMarkdown.html +0 -94
  350. package/docs/interfaces/PreparedPromptResponse.html +0 -62
  351. package/docs/interfaces/ProcessTextResponse.html +0 -86
  352. package/docs/interfaces/PromptFile.html +0 -70
  353. package/docs/interfaces/PromptFileContent.html +0 -76
  354. package/docs/interfaces/PromptFilesResponse.html +0 -56
  355. package/docs/interfaces/PromptFolder.html +0 -80
  356. package/docs/interfaces/PromptFolderDefaults.html +0 -155
  357. package/docs/interfaces/PromptFolderDefaultsResponse.html +0 -79
  358. package/docs/interfaces/PromptFoldersResponse.html +0 -56
  359. package/docs/interfaces/RoomDetails.html +0 -151
  360. package/docs/interfaces/RoomErrorUpdate.html +0 -82
  361. package/docs/interfaces/RoomInfo.html +0 -88
  362. package/docs/interfaces/RoomMessageUpdate.html +0 -113
  363. package/docs/interfaces/RoomMessagesResponse.html +0 -62
  364. package/docs/interfaces/SendMessageResult.html +0 -62
  365. package/docs/interfaces/StoryErrorEvent.html +0 -84
  366. package/docs/interfaces/StoryIdea.html +0 -74
  367. package/docs/interfaces/StoryInfo.html +0 -198
  368. package/docs/interfaces/StoryIntroduceCharacterEvent.html +0 -79
  369. package/docs/interfaces/StoryProgressChapterEvent.html +0 -72
  370. package/docs/interfaces/StoryState.html +0 -108
  371. package/docs/interfaces/StoryStateEvent.html +0 -76
  372. package/docs/interfaces/ToolArtifact.html +0 -85
  373. package/docs/interfaces/ToolCaller.html +0 -77
  374. package/docs/interfaces/ToolDefinition.html +0 -80
  375. package/docs/interfaces/ToolHelpers.html +0 -105
  376. package/docs/interfaces/ToolPackDocuments.html +0 -100
  377. package/docs/interfaces/ToolParameter.html +0 -74
  378. package/docs/interfaces/ToolRoomAccess.html +0 -260
  379. package/docs/interfaces/ToolSummary.html +0 -74
  380. package/docs/interfaces/ToolsResponse.html +0 -68
  381. package/docs/interfaces/Transaction.html +0 -104
  382. package/docs/interfaces/TransactionHistoryResponse.html +0 -62
  383. package/docs/modules.html +0 -53
  384. package/docs/types/PackOrigin.html +0 -34
  385. package/docs/types/PromptScope.html +0 -34
  386. package/docs/types/RoomTurnMode.html +0 -42
  387. package/docs/types/RoomUpdate.html +0 -36
  388. package/docs/types/RosterOverrides.html +0 -42
  389. package/docs/types/ToolContext.html +0 -40
  390. package/docs/types/ToolRunResult.html +0 -34
  391. package/src/tools/packs/dnd5e/README.md +0 -867
@@ -47,6 +47,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
47
47
  var AppController_1;
48
48
  Object.defineProperty(exports, "__esModule", { value: true });
49
49
  exports.AppController = void 0;
50
+ /// <reference types="multer" />
50
51
  const common_1 = require("@nestjs/common");
51
52
  const platform_express_1 = require("@nestjs/platform-express");
52
53
  const rxjs_1 = require("rxjs");
@@ -60,12 +61,33 @@ const published_rooms_service_1 = require("./room/published-rooms.service");
60
61
  const errors_1 = require("./common/errors");
61
62
  const path = __importStar(require("path"));
62
63
  const logger_1 = require("./common/logger");
64
+ /**
65
+ * How large an uploaded PDF may be, in bytes.
66
+ *
67
+ * Configurable because the ceiling is a judgement about this deployment rather
68
+ * than a property of the format: a scanned book is legitimately hundreds of
69
+ * megabytes. Raise it together with `PDF_CONVERT_CONCURRENCY` — the risk in a
70
+ * large document is not the upload but the conversion behind it, which holds the
71
+ * buffer, a parsed copy, and one extracted page per in-flight conversion in memory
72
+ * at once.
73
+ */
63
74
  const MAX_PDF_UPLOAD_BYTES = Math.max(1, Number(process.env.MAX_PDF_UPLOAD_MB) || 50) * 1024 * 1024;
75
+ /** How large uploaded or pasted Markdown may be, in bytes. */
64
76
  const MAX_MARKDOWN_BYTES = Math.max(1, Number(process.env.MAX_MARKDOWN_UPLOAD_MB) || 10) * 1024 * 1024;
77
+ /** For an error message: bytes as whole megabytes. */
65
78
  function asMegabytes(bytes) {
66
79
  return `${Math.round(bytes / (1024 * 1024))}MB`;
67
80
  }
81
+ /**
82
+ * Multer's own ceiling, applied to every upload route that takes a document.
83
+ *
84
+ * Set to the largest thing any of them accepts, so the per-route check below is
85
+ * what produces the specific message. Its job is to abort the *stream*: multer
86
+ * buffers in memory, so without this the whole file is resident before any handler
87
+ * runs and the check saves nothing. Nest maps `LIMIT_FILE_SIZE` to a 413.
88
+ */
68
89
  const UPLOAD_LIMITS = { limits: { fileSize: Math.max(MAX_PDF_UPLOAD_BYTES, MAX_MARKDOWN_BYTES) } };
90
+ /** Strips a pack down to what a listing needs, leaving its templates behind. */
69
91
  function toPackSummary(pack) {
70
92
  return {
71
93
  pack: pack.name,
@@ -93,24 +115,45 @@ let AppController = AppController_1 = class AppController {
93
115
  this.publishedAgentsService = publishedAgentsService;
94
116
  this.publishedRoomsService = publishedRoomsService;
95
117
  }
118
+ /**
119
+ * Helper method to get the user-specific AppService from the request
120
+ * @param req The Express request object (with authenticated user)
121
+ * @param agentId Optional agent ID for fallback lookup
122
+ * @param roomId Optional room ID for fallback lookup
123
+ * @returns The AppService instance for the authenticated user, agent owner, or room owner
124
+ */
96
125
  getAppService(req, agentId, roomId) {
97
126
  let userId;
98
127
  const authSource = req.user?.authSource;
128
+ // Primary: Get userId from JWT's sub field (works for user, agent-access, and room-access tokens)
99
129
  if (req.user && req.user.sub) {
100
130
  userId = req.user.sub;
101
- }
131
+ // Log header-based access for monitoring
132
+ // if (authSource === 'header') {
133
+ // logger.log(
134
+ // `[AUTH] Header-based access: userId=${userId}, agentId=${agentId}, roomId=${roomId}`,
135
+ // );
136
+ // } else if (authSource === 'sse-url') {
137
+ // logger.log(
138
+ // `[AUTH] SSE URL-based access: userId=${userId}, agentId=${agentId}, roomId=${roomId}`,
139
+ // );
140
+ // }
141
+ }
142
+ // Fallback: Agent-owned resources
102
143
  else if (agentId) {
103
144
  userId = this.publishedAgentsService.getUserId(agentId);
104
145
  if (!userId) {
105
146
  throw new common_1.NotFoundException(`Agent ${agentId} is not published or does not exist`);
106
147
  }
107
148
  }
149
+ // Fallback: Room-owned resources
108
150
  else if (roomId) {
109
151
  userId = this.publishedRoomsService.getUserId(roomId);
110
152
  if (!userId) {
111
153
  throw new common_1.NotFoundException(`Room ${roomId} is not published or does not exist`);
112
154
  }
113
155
  }
156
+ // Last resort fallback
114
157
  else if (req.user && req.user.username) {
115
158
  userId = req.user.username;
116
159
  }
@@ -153,6 +196,11 @@ let AppController = AppController_1 = class AppController {
153
196
  async listStoryModelDefaults(req) {
154
197
  const appService = this.getAppService(req);
155
198
  const imageModels = await appService.listImageModels();
199
+ // Resolve the configured default image-model name against the actual
200
+ // image_models.json options. The dialog's <select> only shows a default
201
+ // when the value exactly matches an option name, so we canonicalize
202
+ // case-insensitively and fall back to the first model when the env value
203
+ // is missing or doesn't match.
156
204
  const resolveImageDefault = (envName) => {
157
205
  const exact = imageModels.find((m) => m.name === envName);
158
206
  if (exact)
@@ -171,12 +219,15 @@ let AppController = AppController_1 = class AppController {
171
219
  };
172
220
  }
173
221
  async createAgent(req, body) {
222
+ // Validate required fields
174
223
  if (!body.aiServiceName || !body.aiModel || !body.agentName) {
175
224
  throw new common_1.BadRequestException('AI service name, AI Model, and agent name are required');
176
225
  }
226
+ // Validate non-empty after trimming
177
227
  if (!body.agentName?.trim()) {
178
228
  throw new common_1.BadRequestException('Agent name cannot be empty');
179
229
  }
230
+ // Validate length limits
180
231
  if (body.agentName.length > 200) {
181
232
  throw new common_1.BadRequestException('Agent name too long');
182
233
  }
@@ -205,6 +256,7 @@ let AppController = AppController_1 = class AppController {
205
256
  }
206
257
  try {
207
258
  const appService = this.getAppService(req, agentId);
259
+ // Verify published for agent-access tokens
208
260
  if (req.user.type === 'agent-access') {
209
261
  const agentDetails = await appService.getAgentDetails(agentId);
210
262
  if (!agentDetails || !agentDetails.isPublished) {
@@ -214,10 +266,12 @@ let AppController = AppController_1 = class AppController {
214
266
  return await appService.processText(agentId, body.text);
215
267
  }
216
268
  catch (error) {
269
+ // Re-throw HTTP exceptions as-is (except NotFoundError which we handle specially)
217
270
  if (error instanceof common_1.ForbiddenException || error instanceof common_1.BadRequestException) {
218
271
  throw error;
219
272
  }
220
273
  logger_1.logger.error(`[${req.user?.sub}] Error processing text for agent ${agentId}:`, error);
274
+ // For NotFoundError, return error message in result field with 201 status
221
275
  if (error instanceof errors_1.NotFoundError) {
222
276
  return {
223
277
  result: `Error: ${error.message}`,
@@ -239,13 +293,16 @@ let AppController = AppController_1 = class AppController {
239
293
  throw new common_1.HttpException(`File too large (max ${asMegabytes(MAX_PDF_UPLOAD_BYTES)})`, common_1.HttpStatus.PAYLOAD_TOO_LARGE);
240
294
  }
241
295
  const appService = this.getAppService(req);
296
+ // Use original filename or default
242
297
  let fileName = file?.originalname || 'attach_file';
243
298
  if (body.fileName && body.fileName !== '') {
244
299
  fileName = body.fileName;
245
300
  }
301
+ // Sanitize filename to prevent path traversal
246
302
  fileName = path.basename(fileName).replace(/[^a-zA-Z0-9._-]/g, '_');
247
303
  try {
248
304
  const result = await appService.attachDocument(agentId, fileName, file.buffer);
305
+ // Return both documentId and filename
249
306
  return {
250
307
  ...result,
251
308
  filename: fileName,
@@ -272,6 +329,7 @@ let AppController = AppController_1 = class AppController {
272
329
  return { files: [] };
273
330
  }
274
331
  }
332
+ // New RESTful prompt endpoints
275
333
  getPrompts(req, scope) {
276
334
  try {
277
335
  const appService = this.getAppService(req);
@@ -337,6 +395,9 @@ let AppController = AppController_1 = class AppController {
337
395
  }
338
396
  catch (error) {
339
397
  logger_1.logger.error(`[${req.user?.sub}] Error reading defaults for prompt folder ${folderName}:`, error);
398
+ // Defaults only pre-fill a form; a folder with none must still be selectable.
399
+ // `exists: false` because the read failed — the dialog should not claim a
400
+ // folder it could not look at is there.
340
401
  return { defaults: {}, exists: false };
341
402
  }
342
403
  }
@@ -416,6 +477,7 @@ let AppController = AppController_1 = class AppController {
416
477
  throw new common_1.HttpException('Failed to delete prompt file', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
417
478
  }
418
479
  }
480
+ // === TOOL ENDPOINTS — user-defined tools agents can EXECUTE ===
419
481
  async getTools(req) {
420
482
  try {
421
483
  const appService = this.getAppService(req);
@@ -482,6 +544,7 @@ let AppController = AppController_1 = class AppController {
482
544
  }
483
545
  }
484
546
  async testTool(req, name, body) {
547
+ // Tool failures are returned in-band ({ok:false,error}) so the UI can render them
485
548
  try {
486
549
  const appService = this.getAppService(req);
487
550
  return await appService.testTool(name, body?.args || {});
@@ -491,6 +554,11 @@ let AppController = AppController_1 = class AppController {
491
554
  return { ok: false, error: error.message || 'Tool test failed' };
492
555
  }
493
556
  }
557
+ // === PACK ENDPOINTS — a domain's prompts, documents, tools, agents and rooms ===
558
+ //
559
+ // A pack is installed for everyone (the host copies a directory into
560
+ // <data>/packs) and enabled per user. Enabling controls what a user is shown
561
+ // and may grant; it does not switch anything already configured off.
494
562
  getPacks(req) {
495
563
  try {
496
564
  const appService = this.getAppService(req);
@@ -614,6 +682,11 @@ let AppController = AppController_1 = class AppController {
614
682
  throw new common_1.HttpException(error.message || 'Failed to build the agent', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
615
683
  }
616
684
  }
685
+ // RPG endpoints
686
+ //
687
+ // A campaign is an ordinary room, so everything but creating and reading one goes
688
+ // through the room routes: DELETE rooms/:roomId removes a campaign and cascades to
689
+ // its published instance, and the party plays through the published-room routes.
617
690
  listRpgModels(req) {
618
691
  try {
619
692
  return this.getAppService(req).rpg.listModels();
@@ -662,6 +735,10 @@ let AppController = AppController_1 = class AppController {
662
735
  throw new common_1.HttpException(error.message || 'Failed to create the campaign', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
663
736
  }
664
737
  }
738
+ /**
739
+ * Gives a campaign a public link again, for one whose instance was deleted by hand.
740
+ * Creation publishes, so this is the repair path rather than the normal one.
741
+ */
665
742
  async republishRpgCampaign(req, campaignId) {
666
743
  try {
667
744
  return await this.getAppService(req).rpg.republishCampaign(campaignId);
@@ -677,6 +754,7 @@ let AppController = AppController_1 = class AppController {
677
754
  throw new common_1.HttpException(error.message || 'Failed to publish the campaign', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
678
755
  }
679
756
  }
757
+ // Deprecated - kept for backwards compatibility
680
758
  listPromptFolders(req) {
681
759
  try {
682
760
  const appService = this.getAppService(req);
@@ -722,9 +800,13 @@ let AppController = AppController_1 = class AppController {
722
800
  async listAgents(req, published, includeRoomAgents) {
723
801
  try {
724
802
  const appService = this.getAppService(req);
803
+ // Support ?published=true query parameter
725
804
  if (published === 'true') {
726
805
  return await appService.listPublishedAgents();
727
806
  }
807
+ // ?includeRoomAgents=true adds the agents that belong to a room, which
808
+ // the room dialog offers as something to copy. They are excluded by
809
+ // default: the agent list a user manages holds only unowned agents.
728
810
  return await appService.listAgents(includeRoomAgents === 'true');
729
811
  }
730
812
  catch (error) {
@@ -732,6 +814,20 @@ let AppController = AppController_1 = class AppController {
732
814
  return [];
733
815
  }
734
816
  }
817
+ /**
818
+ * Validates a request's turnMode so an unrecognized value is a 400 rather
819
+ * than silently becoming 'broadcast'.
820
+ * @param value The raw turnMode from the request body
821
+ * @returns The turn mode, or undefined when the field was omitted
822
+ */
823
+ /**
824
+ * Reads the models an instantiate request supplies.
825
+ *
826
+ * A pack's template names a *role* (`primary` or `economy`), never a model, so
827
+ * the caller has to say what each role means on this deployment. `economy`
828
+ * falls back to `primary` rather than erroring: a caller that offers only one
829
+ * model gets a working room, just not a cheap one.
830
+ */
735
831
  static parseInstantiateModels(body) {
736
832
  if (!body?.aiServiceName || !body?.aiModel) {
737
833
  throw new common_1.BadRequestException('aiServiceName and aiModel are required');
@@ -761,34 +857,51 @@ let AppController = AppController_1 = class AppController {
761
857
  }
762
858
  return value;
763
859
  }
860
+ static parseIllustrationMode(value) {
861
+ if (value === undefined)
862
+ return undefined;
863
+ if (value !== 'off' && value !== 'on-request' && value !== 'auto') {
864
+ throw new common_1.BadRequestException(`illustrationMode must be 'off', 'on-request' or 'auto'`);
865
+ }
866
+ return value;
867
+ }
764
868
  async createRoom(req, body) {
869
+ // Validate required fields. A room may start empty: the agents that belong
870
+ // to it are created through POST rooms/:roomId/agents once it exists.
765
871
  if (!body.roomName) {
766
872
  throw new common_1.BadRequestException('Room name is required');
767
873
  }
874
+ // Validate non-empty after trimming
768
875
  if (!body.roomName?.trim()) {
769
876
  throw new common_1.BadRequestException('Room name cannot be empty');
770
877
  }
878
+ // Validate length limits
771
879
  if (body.roomName.length > 200) {
772
880
  throw new common_1.BadRequestException('Room name too long');
773
881
  }
774
882
  const turnMode = AppController_1.parseTurnMode(body.turnMode);
883
+ const illustrationMode = AppController_1.parseIllustrationMode(body.illustrationMode);
775
884
  try {
776
885
  const appService = this.getAppService(req);
777
- return await appService.createRoom(body.roomName, body.roomGoal, body.agentIds ?? [], body.roomLeader, turnMode, body.moderator);
886
+ return await appService.createRoom(body.roomName, body.roomGoal, body.agentIds ?? [], body.roomLeader, turnMode, body.moderator, body.beginInstruction, body.imageModel, illustrationMode);
778
887
  }
779
888
  catch (error) {
780
889
  logger_1.logger.error(`[${req.user?.sub}] Error creating room ${body.roomName}:`, error);
781
890
  if (error instanceof errors_1.ValidationError) {
782
891
  throw new common_1.BadRequestException(error.message);
783
892
  }
893
+ // Return 500 for any errors during room creation (including NotFoundError)
784
894
  throw new common_1.HttpException(error.message || 'Failed to create room', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
785
895
  }
786
896
  }
787
897
  async editRoom(req, roomId, body) {
898
+ // Parsed before the try, like turnMode: a rejected value is a bad request,
899
+ // and inside the try the catch below would turn it into a 500.
788
900
  const turnMode = AppController_1.parseTurnMode(body.turnMode);
901
+ const illustrationMode = AppController_1.parseIllustrationMode(body.illustrationMode);
789
902
  try {
790
903
  const appService = this.getAppService(req);
791
- await appService.editRoom(roomId, body.roomName, body.roomGoal, body.baseRoomDir, body.agentIds, body.roomLeader, turnMode, body.moderator, body.pack);
904
+ await appService.editRoom(roomId, body.roomName, body.roomGoal, body.baseRoomDir, body.agentIds, body.roomLeader, turnMode, body.moderator, body.pack, body.beginInstruction, body.imageModel, illustrationMode);
792
905
  }
793
906
  catch (error) {
794
907
  logger_1.logger.error(`[${req.user?.sub}] Error editing room ${roomId}:`, error);
@@ -801,6 +914,13 @@ let AppController = AppController_1 = class AppController {
801
914
  throw new common_1.HttpException('Failed to edit room', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
802
915
  }
803
916
  }
917
+ /**
918
+ * Creates an agent that belongs to this room and adds it to it.
919
+ *
920
+ * The only way an agent joins a room. `agentName` is the bare name — the room's
921
+ * name is prefixed onto it server-side, so the client never has to assemble it
922
+ * (and cannot end up prefixing it twice).
923
+ */
804
924
  async createRoomAgent(req, roomId, body) {
805
925
  if (!body.aiServiceName || !body.aiModel || !body.agentName?.trim()) {
806
926
  throw new common_1.BadRequestException('AI service name, AI Model, and agent name are required');
@@ -823,6 +943,9 @@ let AppController = AppController_1 = class AppController {
823
943
  throw new common_1.HttpException('Failed to add agent to room', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
824
944
  }
825
945
  }
946
+ /**
947
+ * Removes an agent from a room, deleting it when the room owns it.
948
+ */
826
949
  async removeRoomAgent(req, roomId, agentId) {
827
950
  try {
828
951
  const appService = this.getAppService(req);
@@ -842,6 +965,8 @@ let AppController = AppController_1 = class AppController {
842
965
  async listRooms(req, published) {
843
966
  try {
844
967
  const appService = this.getAppService(req);
968
+ // ?published=true returns the published instances instead, which the
969
+ // default listing excludes. Mirrors GET /api/agents?published=true.
845
970
  if (published === 'true') {
846
971
  return await appService.listPublishedRooms();
847
972
  }
@@ -876,6 +1001,7 @@ let AppController = AppController_1 = class AppController {
876
1001
  if (!agentDetails) {
877
1002
  throw new common_1.NotFoundException('Agent not found');
878
1003
  }
1004
+ // Verify published for agent-access tokens
879
1005
  if (req.user.type === 'agent-access' && !agentDetails.isPublished) {
880
1006
  throw new common_1.ForbiddenException('Agent is not published');
881
1007
  }
@@ -904,6 +1030,7 @@ let AppController = AppController_1 = class AppController {
904
1030
  async getAgentMessages(req, agentId, fromIndex) {
905
1031
  try {
906
1032
  const appService = this.getAppService(req, agentId);
1033
+ // Verify published for agent-access tokens
907
1034
  if (req.user.type === 'agent-access') {
908
1035
  const agentDetails = await appService.getAgentDetails(agentId);
909
1036
  if (!agentDetails || !agentDetails.isPublished) {
@@ -1031,6 +1158,7 @@ let AppController = AppController_1 = class AppController {
1031
1158
  }
1032
1159
  }
1033
1160
  async sendRoomMessage(req, roomId, body) {
1161
+ // Validate message content
1034
1162
  if (!body.content?.trim()) {
1035
1163
  throw new common_1.BadRequestException('Message content cannot be empty');
1036
1164
  }
@@ -1039,6 +1167,9 @@ let AppController = AppController_1 = class AppController {
1039
1167
  }
1040
1168
  try {
1041
1169
  const appService = this.getAppService(req, undefined, roomId);
1170
+ // Returned rather than discarded: a human's message is rejected when it
1171
+ // is not their turn, and the client needs to say so instead of appearing
1172
+ // to have sent it.
1042
1173
  return await appService.sendRoomMessage(roomId, body.content, body.sender, body.action, body.targets, body.clearQueue || false);
1043
1174
  }
1044
1175
  catch (error) {
@@ -1055,6 +1186,37 @@ let AppController = AppController_1 = class AppController {
1055
1186
  throw new common_1.HttpException('Failed to send room message', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
1056
1187
  }
1057
1188
  }
1189
+ /**
1190
+ * Opens a room with its configured begin instruction.
1191
+ *
1192
+ * `RoomAccess` rather than `OwnerOnly`, and deliberately: the people who most
1193
+ * need to start a published room are the party holding its link, who have a
1194
+ * room-scoped token and nothing more. It is also a strictly narrower power than
1195
+ * the message endpoint beside it — the caller chooses nothing, since the
1196
+ * content, sender, action and target all come from the room's own settings.
1197
+ */
1198
+ async beginRoom(req, roomId) {
1199
+ try {
1200
+ const appService = this.getAppService(req, undefined, roomId);
1201
+ return await appService.beginRoom(roomId);
1202
+ }
1203
+ catch (error) {
1204
+ logger_1.logger.error(`[${req.user?.sub}] Error beginning room ${roomId}:`, error);
1205
+ if (error instanceof errors_1.NotFoundError) {
1206
+ throw new common_1.NotFoundException(error.message);
1207
+ }
1208
+ if (error instanceof errors_1.ValidationError) {
1209
+ throw new common_1.BadRequestException(error.message);
1210
+ }
1211
+ // A room that has already begun is a conflict rather than a bad request:
1212
+ // the same call would have worked a moment earlier, and the client's job
1213
+ // is to stop offering Begin, not to fix its payload.
1214
+ if (error instanceof errors_1.OperationFailedError) {
1215
+ throw new common_1.HttpException(error.message, common_1.HttpStatus.CONFLICT);
1216
+ }
1217
+ throw new common_1.HttpException('Failed to begin room', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
1218
+ }
1219
+ }
1058
1220
  async pauseRoom(req, roomId) {
1059
1221
  try {
1060
1222
  const appService = this.getAppService(req, undefined, roomId);
@@ -1090,7 +1252,7 @@ let AppController = AppController_1 = class AppController {
1090
1252
  }
1091
1253
  catch (error) {
1092
1254
  logger_1.logger.error(`[${req.user?.sub}] Error getting user preferences:`, error);
1093
- return {};
1255
+ return {}; // Return empty preferences on error
1094
1256
  }
1095
1257
  }
1096
1258
  async saveUserPreferences(req, preferences) {
@@ -1106,6 +1268,7 @@ let AppController = AppController_1 = class AppController {
1106
1268
  throw new common_1.HttpException('Failed to save user preferences', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
1107
1269
  }
1108
1270
  }
1271
+ // Deprecated - kept for backwards compatibility
1109
1272
  async listPromptFilesDeprecated(req, folderName) {
1110
1273
  try {
1111
1274
  const appService = this.getAppService(req);
@@ -1116,6 +1279,7 @@ let AppController = AppController_1 = class AppController {
1116
1279
  return { files: [] };
1117
1280
  }
1118
1281
  }
1282
+ // Deprecated - kept for backwards compatibility
1119
1283
  async getPromptFileDeprecated(req, folderName, fileName) {
1120
1284
  try {
1121
1285
  const appService = this.getAppService(req);
@@ -1126,6 +1290,7 @@ let AppController = AppController_1 = class AppController {
1126
1290
  return { content: '' };
1127
1291
  }
1128
1292
  }
1293
+ // Deprecated - kept for backwards compatibility
1129
1294
  async savePromptFileDeprecated(req, body) {
1130
1295
  try {
1131
1296
  const appService = this.getAppService(req);
@@ -1142,6 +1307,7 @@ let AppController = AppController_1 = class AppController {
1142
1307
  throw new common_1.HttpException('Failed to save prompt file', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
1143
1308
  }
1144
1309
  }
1310
+ // Deprecated - kept for backwards compatibility
1145
1311
  async deletePromptFileDeprecated(req, body) {
1146
1312
  try {
1147
1313
  const appService = this.getAppService(req);
@@ -1158,6 +1324,7 @@ let AppController = AppController_1 = class AppController {
1158
1324
  throw new common_1.HttpException('Failed to delete prompt file', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
1159
1325
  }
1160
1326
  }
1327
+ // Deprecated - kept for backwards compatibility
1161
1328
  async deletePromptFolderDeprecated(req, body) {
1162
1329
  try {
1163
1330
  const appService = this.getAppService(req);
@@ -1174,6 +1341,9 @@ let AppController = AppController_1 = class AppController {
1174
1341
  throw new common_1.HttpException('Failed to delete prompt folder', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
1175
1342
  }
1176
1343
  }
1344
+ // Owner-only, unlike the other agent mutations: rewriting an agent's model,
1345
+ // instructions or nickname is configuration, not use, and a published agent's
1346
+ // visitors hold a token that would otherwise reach it.
1177
1347
  async updateAgent(req, agentId, updateData) {
1178
1348
  try {
1179
1349
  const appService = this.getAppService(req);
@@ -1221,6 +1391,7 @@ let AppController = AppController_1 = class AppController {
1221
1391
  }
1222
1392
  try {
1223
1393
  const appService = this.getAppService(req, agentId);
1394
+ // Verify published for agent-access tokens
1224
1395
  if (req.user.type === 'agent-access') {
1225
1396
  const agentDetails = await appService.getAgentDetails(agentId);
1226
1397
  if (!agentDetails || !agentDetails.isPublished) {
@@ -1271,6 +1442,9 @@ let AppController = AppController_1 = class AppController {
1271
1442
  throw new common_1.HttpException('Failed to compact agent conversation', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
1272
1443
  }
1273
1444
  }
1445
+ // Reachable from a public room page, so it is scope-guarded: without
1446
+ // @RoomAccess a room-access header for one published room could reset any
1447
+ // other room belonging to that room's owner.
1274
1448
  async resetRoom(req, roomId) {
1275
1449
  if (!roomId) {
1276
1450
  throw new common_1.BadRequestException('Room ID is required');
@@ -1369,6 +1543,33 @@ let AppController = AppController_1 = class AppController {
1369
1543
  throw new common_1.HttpException('Failed to revert chapter', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
1370
1544
  }
1371
1545
  }
1546
+ /**
1547
+ * Serves a picture the room's illustrator drew.
1548
+ *
1549
+ * Read access rather than owner-only, because the whole point is that a
1550
+ * published campaign shows its images to the people playing it. The browser
1551
+ * fetches this as a subresource of a message, carrying neither the room header
1552
+ * nor a cookie, so `JwtAuthGuard` has a branch that resolves a published room
1553
+ * id straight from this URL — the same accommodation the SSE routes need.
1554
+ */
1555
+ async getRoomImage(req, roomId, artifactId, res) {
1556
+ try {
1557
+ const appService = this.getAppService(req, undefined, roomId);
1558
+ const image = await appService.getRoomImage(roomId, artifactId);
1559
+ if (!image) {
1560
+ throw new common_1.NotFoundException('Image not found');
1561
+ }
1562
+ res.setHeader('Content-Type', image.mimeType);
1563
+ res.send(image.content);
1564
+ }
1565
+ catch (error) {
1566
+ if (error instanceof common_1.NotFoundException) {
1567
+ throw error;
1568
+ }
1569
+ logger_1.logger.error(`Error getting image ${artifactId} for room ${roomId}:`, error);
1570
+ throw new common_1.HttpException('Failed to get image', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
1571
+ }
1572
+ }
1372
1573
  async getRoomArtifacts(req, roomId) {
1373
1574
  try {
1374
1575
  const appService = this.getAppService(req, undefined, roomId);
@@ -1376,7 +1577,7 @@ let AppController = AppController_1 = class AppController {
1376
1577
  }
1377
1578
  catch (error) {
1378
1579
  logger_1.logger.error(`[${req.user?.sub}] Error getting room artifacts for ${roomId}:`, error);
1379
- return { artifacts: [] };
1580
+ return { artifacts: [] }; // Return empty artifacts on error
1380
1581
  }
1381
1582
  }
1382
1583
  async publishArtifact(req, roomId, body) {
@@ -1398,6 +1599,7 @@ let AppController = AppController_1 = class AppController {
1398
1599
  throw new common_1.HttpException('Failed to publish artifact', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
1399
1600
  }
1400
1601
  }
1602
+ // Deprecated - kept for backwards compatibility
1401
1603
  async createPromptFolderDeprecated(req, body) {
1402
1604
  if (!body.folderName) {
1403
1605
  throw new common_1.BadRequestException('Folder name is required');
@@ -1421,9 +1623,13 @@ let AppController = AppController_1 = class AppController {
1421
1623
  }
1422
1624
  catch (error) {
1423
1625
  logger_1.logger.error(`[${req.user?.sub}] Error listing stories:`, error);
1424
- return [];
1626
+ return []; // Return empty list on error
1425
1627
  }
1426
1628
  }
1629
+ /**
1630
+ * List all available story genres
1631
+ * GET /api/stories/genres
1632
+ */
1427
1633
  listStoryGenres(req) {
1428
1634
  try {
1429
1635
  const appService = this.getAppService(req);
@@ -1434,6 +1640,10 @@ let AppController = AppController_1 = class AppController {
1434
1640
  return [];
1435
1641
  }
1436
1642
  }
1643
+ /**
1644
+ * Get a random story idea from any random genre
1645
+ * GET /api/stories/genres/random
1646
+ */
1437
1647
  async getRandomStoryIdea(req) {
1438
1648
  try {
1439
1649
  const appService = this.getAppService(req);
@@ -1444,6 +1654,10 @@ let AppController = AppController_1 = class AppController {
1444
1654
  throw new common_1.HttpException('Failed to get random story idea', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
1445
1655
  }
1446
1656
  }
1657
+ /**
1658
+ * Get a random story idea from a specific genre
1659
+ * GET /api/stories/genres/:genreName
1660
+ */
1447
1661
  async getStoryIdeasByGenre(req, genreName) {
1448
1662
  try {
1449
1663
  const appService = this.getAppService(req);
@@ -1474,6 +1688,7 @@ let AppController = AppController_1 = class AppController {
1474
1688
  if (!file) {
1475
1689
  throw new common_1.BadRequestException('No file uploaded');
1476
1690
  }
1691
+ // Validate file type
1477
1692
  const allowedMimeTypes = ['application/zip', 'application/x-zip-compressed'];
1478
1693
  if (!allowedMimeTypes.includes(file.mimetype) &&
1479
1694
  !file.originalname.toLowerCase().endsWith('.zip')) {
@@ -1487,6 +1702,7 @@ let AppController = AppController_1 = class AppController {
1487
1702
  }
1488
1703
  catch (error) {
1489
1704
  logger_1.logger.error(`[${req.user?.sub}] Error importing story from zip:`, error);
1705
+ // Return more specific error messages
1490
1706
  if (error.message.includes('Invalid story structure')) {
1491
1707
  throw new common_1.BadRequestException(error.message);
1492
1708
  }
@@ -1531,9 +1747,11 @@ let AppController = AppController_1 = class AppController {
1531
1747
  }
1532
1748
  catch (error) {
1533
1749
  logger_1.logger.error(`[${req.user?.sub}] Error compacting story ${storyId}:`, error);
1750
+ // If it's already an HTTP exception, re-throw it
1534
1751
  if (error instanceof common_1.HttpException) {
1535
1752
  throw error;
1536
1753
  }
1754
+ // Convert other errors to HTTP exceptions
1537
1755
  throw new common_1.HttpException(error.message || 'Failed to compact story', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
1538
1756
  }
1539
1757
  }
@@ -1547,9 +1765,11 @@ let AppController = AppController_1 = class AppController {
1547
1765
  }
1548
1766
  catch (error) {
1549
1767
  logger_1.logger.error(`[${req.user?.sub}] Error progressing story ${storyId}:`, error);
1768
+ // If it's already an HTTP exception, re-throw it
1550
1769
  if (error instanceof common_1.HttpException) {
1551
1770
  throw error;
1552
1771
  }
1772
+ // Convert other errors to HTTP exceptions
1553
1773
  throw new common_1.HttpException(error.message || 'Failed to progress story', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
1554
1774
  }
1555
1775
  }
@@ -1578,9 +1798,11 @@ let AppController = AppController_1 = class AppController {
1578
1798
  }
1579
1799
  catch (error) {
1580
1800
  logger_1.logger.error(`[${req.user?.sub}] Error responding to story ${storyId}:`, error);
1801
+ // If it's already an HTTP exception, re-throw it
1581
1802
  if (error instanceof common_1.HttpException) {
1582
1803
  throw error;
1583
1804
  }
1805
+ // Convert other errors to HTTP exceptions
1584
1806
  throw new common_1.HttpException(error.message || 'Failed to respond to story', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
1585
1807
  }
1586
1808
  }
@@ -1603,7 +1825,8 @@ let AppController = AppController_1 = class AppController {
1603
1825
  }
1604
1826
  try {
1605
1827
  const appService = this.getAppService(req);
1606
- await appService.introduceCharacterToStory(storyId, body.name, body.description || '', body.storyModel, body.fromNarratorSuggestion || false);
1828
+ await appService.introduceCharacterToStory(storyId, body.name, body.description || '', // Default to empty string if not provided
1829
+ body.storyModel, body.fromNarratorSuggestion || false);
1607
1830
  }
1608
1831
  catch (error) {
1609
1832
  logger_1.logger.error(`[${req.user?.sub}] Error introducing character ${body.name} to story ${storyId}:`, error);
@@ -1653,7 +1876,7 @@ let AppController = AppController_1 = class AppController {
1653
1876
  }
1654
1877
  catch (error) {
1655
1878
  logger_1.logger.error(`[${req.user?.sub}] Error listing chapters for story ${storyId}:`, error);
1656
- return { chapters: [] };
1879
+ return { chapters: [] }; // Return empty list on error
1657
1880
  }
1658
1881
  }
1659
1882
  async getChapter(req, storyId, chapterIndex) {
@@ -1710,14 +1933,18 @@ let AppController = AppController_1 = class AppController {
1710
1933
  async exportStoryMarkdown(req, storyId, res) {
1711
1934
  try {
1712
1935
  const appService = this.getAppService(req);
1936
+ // Generate markdown content
1713
1937
  const markdown = await appService.downloadStoryMarkdown(storyId);
1938
+ // Get story name for filename
1714
1939
  const story = await appService.getStoryInfo(storyId);
1715
1940
  if (!story) {
1716
1941
  throw new common_1.NotFoundException(`Story ${storyId} not found`);
1717
1942
  }
1718
1943
  const filename = `${story.name.replace(/[^a-z0-9]/gi, '_')}.md`;
1944
+ // Set headers for file download
1719
1945
  res.setHeader('Content-Type', 'text/markdown');
1720
1946
  res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
1947
+ // Send content
1721
1948
  res.send(markdown);
1722
1949
  }
1723
1950
  catch (error) {
@@ -1728,10 +1955,14 @@ let AppController = AppController_1 = class AppController {
1728
1955
  async exportStoryZip(req, storyId, res) {
1729
1956
  try {
1730
1957
  const appService = this.getAppService(req);
1958
+ // Generate zip stream and filename
1731
1959
  const { stream, filename } = await appService.exportStoryData(storyId);
1960
+ // Set headers for zip file download
1732
1961
  res.setHeader('Content-Type', 'application/zip');
1733
1962
  res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
1963
+ // Pipe the archive stream to the response
1734
1964
  stream.pipe(res);
1965
+ // Handle stream errors
1735
1966
  stream.on('error', (err) => {
1736
1967
  logger_1.logger.error(`[${req.user?.sub}] Stream error during story zip export:`, err);
1737
1968
  if (!res.headersSent) {
@@ -1753,7 +1984,7 @@ let AppController = AppController_1 = class AppController {
1753
1984
  }
1754
1985
  catch (error) {
1755
1986
  logger_1.logger.error(`[${req.user?.sub}] Error listing characters for story ${storyId}:`, error);
1756
- return [];
1987
+ return []; // Return empty list on error
1757
1988
  }
1758
1989
  }
1759
1990
  async getCharacter(req, storyId, characterName) {
@@ -1763,7 +1994,7 @@ let AppController = AppController_1 = class AppController {
1763
1994
  }
1764
1995
  catch (error) {
1765
1996
  logger_1.logger.error(`[${req.user?.sub}] Error getting character ${characterName} for story ${storyId}:`, error);
1766
- return { content: '' };
1997
+ return { content: '' }; // Return empty content on error
1767
1998
  }
1768
1999
  }
1769
2000
  async saveCharacter(req, storyId, characterName, body) {
@@ -1792,7 +2023,7 @@ let AppController = AppController_1 = class AppController {
1792
2023
  }
1793
2024
  catch (error) {
1794
2025
  logger_1.logger.error(`[${req.user?.sub}] Error getting inventory for character ${characterName} in story ${storyId}:`, error);
1795
- return { content: '' };
2026
+ return { content: '' }; // Return empty content on error
1796
2027
  }
1797
2028
  }
1798
2029
  async saveCharacterInventory(req, storyId, characterName, body) {
@@ -1821,7 +2052,7 @@ let AppController = AppController_1 = class AppController {
1821
2052
  }
1822
2053
  catch (error) {
1823
2054
  logger_1.logger.error(`[${req.user?.sub}] Error getting plot plan for story ${storyId}:`, error);
1824
- return { content: '' };
2055
+ return { content: '' }; // Return empty content on error
1825
2056
  }
1826
2057
  }
1827
2058
  async getAgentHistory(req, storyId, agentId) {
@@ -1831,7 +2062,7 @@ let AppController = AppController_1 = class AppController {
1831
2062
  }
1832
2063
  catch (error) {
1833
2064
  logger_1.logger.error(`[${req.user?.sub}] Error getting agent history for ${agentId} in story ${storyId}:`, error);
1834
- return { content: '' };
2065
+ return { content: '' }; // Return empty content on error
1835
2066
  }
1836
2067
  }
1837
2068
  async savePlotPlan(req, storyId, body) {
@@ -1853,6 +2084,9 @@ let AppController = AppController_1 = class AppController {
1853
2084
  throw new common_1.HttpException('Failed to save plot plan', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
1854
2085
  }
1855
2086
  }
2087
+ /**
2088
+ * List artifacts for a story
2089
+ */
1856
2090
  async listStoryArtifacts(req, storyId) {
1857
2091
  try {
1858
2092
  const appService = this.getAppService(req);
@@ -1863,21 +2097,28 @@ let AppController = AppController_1 = class AppController {
1863
2097
  return { artifacts: [] };
1864
2098
  }
1865
2099
  }
2100
+ /**
2101
+ * Get specific story artifact content
2102
+ */
1866
2103
  async getStoryArtifact(req, storyId, artifactId, res) {
1867
2104
  try {
1868
2105
  const appService = this.getAppService(req);
1869
2106
  const storyArtifactService = appService.getStoryArtifactService(storyId);
2107
+ // Get artifact metadata for MIME type
1870
2108
  const allArtifacts = storyArtifactService.listArtifacts();
1871
2109
  const artifactMetadata = allArtifacts.find((a) => a.artifactId === artifactId);
1872
2110
  if (!artifactMetadata) {
1873
2111
  throw new common_1.NotFoundException('Artifact not found');
1874
2112
  }
2113
+ // Get artifact content (string or Buffer)
1875
2114
  const content = appService.getStoryArtifact(storyId, artifactId);
1876
2115
  if (!content) {
1877
2116
  throw new common_1.NotFoundException('Artifact content not found');
1878
2117
  }
2118
+ // Set appropriate content-type
1879
2119
  const mimeType = artifactMetadata.mimeType || 'application/octet-stream';
1880
2120
  res.setHeader('Content-Type', mimeType);
2121
+ // Send content (handles both string and Buffer)
1881
2122
  res.send(content);
1882
2123
  }
1883
2124
  catch (error) {
@@ -1890,12 +2131,14 @@ let AppController = AppController_1 = class AppController {
1890
2131
  }
1891
2132
  storyProgress(req, storyId) {
1892
2133
  const appService = this.getAppService(req);
2134
+ // Validate story exists before establishing SSE connection
1893
2135
  const storyInfo = appService.listStories().find((s) => s.id === storyId);
1894
2136
  if (!storyInfo) {
1895
2137
  throw new common_1.NotFoundException(`Story ${storyId} not found`);
1896
2138
  }
1897
2139
  const emitter = appService.getStoryProgressEmitter(storyId);
1898
2140
  if (!emitter) {
2141
+ // Return an empty observable that completes immediately if no emitter exists
1899
2142
  return new rxjs_1.Observable((subscriber) => {
1900
2143
  subscriber.next({
1901
2144
  data: { step: 'error', message: 'Story progress not found' },
@@ -1909,20 +2152,27 @@ let AppController = AppController_1 = class AppController {
1909
2152
  const userId = req.user?.sub;
1910
2153
  try {
1911
2154
  const appService = this.getAppService(req);
2155
+ // Validate story exists before establishing SSE connection
1912
2156
  const storyInfo = appService.listStories().find((s) => s.id === storyId);
1913
2157
  if (!storyInfo) {
1914
2158
  logger_1.logger.log(`[SSE] Story ${storyId} not found for user ${userId}`);
1915
2159
  throw new common_1.NotFoundException(`Story ${storyId} not found`);
1916
2160
  }
2161
+ // Get or create the emitter for this story
1917
2162
  const emitter = appService.getStoryMessageEmitter(storyId);
1918
2163
  return new rxjs_1.Observable((subscriber) => {
1919
2164
  logger_1.logger.log(`[SSE] Observable subscribed for story ${storyId}`);
2165
+ // Send initial connected message to establish the stream
2166
+ // NestJS will automatically JSON.stringify the data
1920
2167
  subscriber.next({
1921
2168
  data: { type: 'connected', storyId },
1922
2169
  });
2170
+ // Replay any unacknowledged narrator suggestion so late-connecting
2171
+ // clients (tab switches, reconnects, server restarts) don't miss it
1923
2172
  if (storyInfo.pendingSuggestion) {
1924
2173
  subscriber.next({ data: storyInfo.pendingSuggestion });
1925
2174
  }
2175
+ // Listen for all story events and forward them to the SSE stream
1926
2176
  const updateHandler = (data) => {
1927
2177
  subscriber.next({ data });
1928
2178
  };
@@ -1930,6 +2180,7 @@ let AppController = AppController_1 = class AppController {
1930
2180
  emitter.on('suggest-introduce-character', updateHandler);
1931
2181
  emitter.on('suggest-progress-chapter', updateHandler);
1932
2182
  emitter.on('story-error', updateHandler);
2183
+ // Cleanup when client disconnects
1933
2184
  return () => {
1934
2185
  logger_1.logger.log(`[SSE] Cleanup for story ${storyId}`);
1935
2186
  emitter.off('story-state', updateHandler);
@@ -1945,23 +2196,30 @@ let AppController = AppController_1 = class AppController {
1945
2196
  }
1946
2197
  }
1947
2198
  async agentMessages(req, agentId) {
2199
+ // Ensure the state change callback is registered for this agent
2200
+ // This is necessary for agents loaded from disk that don't have callbacks yet
1948
2201
  const appService = this.getAppService(req, agentId);
2202
+ // Validate agent exists before establishing SSE connection
1949
2203
  const agentDetails = await appService.getAgentDetails(agentId);
1950
2204
  if (!agentDetails) {
1951
2205
  throw new common_1.NotFoundException(`Agent ${agentId} not found`);
1952
2206
  }
2207
+ // Verify published for agent-access tokens
1953
2208
  if (req.user.type === 'agent-access') {
1954
2209
  if (!agentDetails.isPublished) {
1955
2210
  throw new common_1.ForbiddenException('Agent is not published');
1956
2211
  }
1957
2212
  }
1958
2213
  appService.ensureAgentStateCallback(agentId);
2214
+ // Get or create the emitter for this agent
1959
2215
  const emitter = appService.getAgentMessageEmitter(agentId);
1960
2216
  return new rxjs_1.Observable((subscriber) => {
2217
+ // Listen for update events
1961
2218
  const updateHandler = (data) => {
1962
2219
  subscriber.next({ data });
1963
2220
  };
1964
2221
  emitter.on('update', updateHandler);
2222
+ // Cleanup when client disconnects
1965
2223
  return () => {
1966
2224
  emitter.off('update', updateHandler);
1967
2225
  };
@@ -1969,6 +2227,7 @@ let AppController = AppController_1 = class AppController {
1969
2227
  }
1970
2228
  async roomMessages(req, roomId) {
1971
2229
  const appService = this.getAppService(req, undefined, roomId);
2230
+ // Validate room exists before establishing SSE connection
1972
2231
  const roomDetails = await appService.getRoomDetails(roomId);
1973
2232
  if (!roomDetails) {
1974
2233
  throw new common_1.NotFoundException(`Room ${roomId} not found`);
@@ -1999,11 +2258,46 @@ let AppController = AppController_1 = class AppController {
1999
2258
  };
2000
2259
  });
2001
2260
  }
2261
+ /**
2262
+ * Get current user balance
2263
+ */
2002
2264
  async getBalance(req) {
2003
2265
  const appService = this.getAppService(req);
2004
2266
  const balance = await appService.getBalance();
2005
2267
  return { balance };
2006
2268
  }
2269
+ /**
2270
+ * Add funds to user balance
2271
+ */
2272
+ // @Post('add-balance')
2273
+ // async addBalance(
2274
+ // @Request() req: ExpressRequest,
2275
+ // @Body() body: { amount: number }
2276
+ // ): Promise<{ balance: number, success: boolean, message: string }> {
2277
+ // const appService = this.getAppService(req);
2278
+ //
2279
+ // // Validate amount
2280
+ // if (!body.amount || body.amount <= 0) {
2281
+ // return {
2282
+ // balance: await appService.getBalance(),
2283
+ // success: false,
2284
+ // message: 'Amount must be positive',
2285
+ // };
2286
+ // }
2287
+ //
2288
+ // await appService.addBalance(body.amount);
2289
+ // const newBalance = await appService.getBalance();
2290
+ //
2291
+ // return {
2292
+ // balance: newBalance,
2293
+ // success: true,
2294
+ // message: `Successfully added $${body.amount.toFixed(2)} to balance`,
2295
+ // };
2296
+ // }
2297
+ // ==================== Artifact Endpoints ====================
2298
+ /**
2299
+ * List all artifacts for the user
2300
+ */
2007
2301
  async listArtifacts(req) {
2008
2302
  try {
2009
2303
  const appService = this.getAppService(req);
@@ -2014,6 +2308,9 @@ let AppController = AppController_1 = class AppController {
2014
2308
  return { artifacts: [] };
2015
2309
  }
2016
2310
  }
2311
+ /**
2312
+ * Get specific artifact content
2313
+ */
2017
2314
  async getArtifact(req, artifactId) {
2018
2315
  try {
2019
2316
  const appService = this.getAppService(req);
@@ -2031,13 +2328,22 @@ let AppController = AppController_1 = class AppController {
2031
2328
  throw new common_1.HttpException('Failed to get artifact', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
2032
2329
  }
2033
2330
  }
2331
+ /**
2332
+ * Create new artifact (upload)
2333
+ */
2034
2334
  async createArtifact(req, body, file) {
2335
+ // Validate name first: it is required either way, and saying so before
2336
+ // complaining about the payload is the more useful order.
2035
2337
  if (!body.name || !body.name.trim()) {
2036
2338
  throw new common_1.BadRequestException('Artifact name is required');
2037
2339
  }
2038
2340
  if (body.name.length > 200) {
2039
2341
  throw new common_1.BadRequestException('Artifact name too long (max 200 characters)');
2040
2342
  }
2343
+ // Markdown supplied directly, with no file involved. The endpoint used to
2344
+ // be multipart-only, which meant an artifact could only come from a file
2345
+ // on disk through a native picker — no pasting a document into the page,
2346
+ // and nothing scriptable.
2041
2347
  if (!file) {
2042
2348
  if (typeof body.content !== 'string' || !body.content.trim()) {
2043
2349
  throw new common_1.BadRequestException('Provide either a .md/.pdf file or a non-empty "content" string');
@@ -2054,10 +2360,13 @@ let AppController = AppController_1 = class AppController {
2054
2360
  throw new common_1.HttpException('Failed to create artifact', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
2055
2361
  }
2056
2362
  }
2363
+ // Determine file extension
2057
2364
  const extension = file.originalname.toLowerCase().split('.').pop();
2365
+ // Validate file type - accept both .md and .pdf
2058
2366
  if (!['md', 'pdf'].includes(extension)) {
2059
2367
  throw new common_1.BadRequestException('Only .md and .pdf files are allowed');
2060
2368
  }
2369
+ // Check file size - different limits for different file types
2061
2370
  const maxSize = extension === 'pdf' ? MAX_PDF_UPLOAD_BYTES : MAX_MARKDOWN_BYTES;
2062
2371
  if (file.size > maxSize) {
2063
2372
  throw new common_1.HttpException(`File too large (max ${asMegabytes(maxSize)})`, common_1.HttpStatus.PAYLOAD_TOO_LARGE);
@@ -2066,22 +2375,28 @@ let AppController = AppController_1 = class AppController {
2066
2375
  const appService = this.getAppService(req);
2067
2376
  let artifactId;
2068
2377
  if (extension === 'md') {
2378
+ // Direct upload for markdown files
2069
2379
  const content = file.buffer.toString('utf8');
2070
2380
  artifactId = appService.createUserArtifact(body.name.trim(), content);
2071
2381
  }
2072
2382
  else {
2383
+ // PDF conversion - create placeholder immediately, convert in background
2073
2384
  artifactId = appService.convertUserArtifact(body.name.trim(), file.buffer);
2074
2385
  }
2075
2386
  return { artifactId };
2076
2387
  }
2077
2388
  catch (error) {
2078
2389
  logger_1.logger.error(`Error creating artifact:`, error);
2390
+ // Provide more specific error message for conversion failures
2079
2391
  if (error.message?.includes('conversion')) {
2080
2392
  throw new common_1.HttpException(`Failed to convert PDF: ${error.message}`, common_1.HttpStatus.INTERNAL_SERVER_ERROR);
2081
2393
  }
2082
2394
  throw new common_1.HttpException('Failed to create artifact', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
2083
2395
  }
2084
2396
  }
2397
+ /**
2398
+ * Update artifact content
2399
+ */
2085
2400
  async updateArtifact(req, artifactId, body) {
2086
2401
  if (!body.content) {
2087
2402
  throw new common_1.BadRequestException('Content is required');
@@ -2101,6 +2416,9 @@ let AppController = AppController_1 = class AppController {
2101
2416
  throw new common_1.HttpException('Failed to update artifact', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
2102
2417
  }
2103
2418
  }
2419
+ /**
2420
+ * Rename artifact
2421
+ */
2104
2422
  async renameArtifact(req, artifactId, body) {
2105
2423
  if (!body.name || !body.name.trim()) {
2106
2424
  throw new common_1.BadRequestException('Name is required');
@@ -2123,6 +2441,9 @@ let AppController = AppController_1 = class AppController {
2123
2441
  throw new common_1.HttpException('Failed to rename artifact', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
2124
2442
  }
2125
2443
  }
2444
+ /**
2445
+ * Delete artifact
2446
+ */
2126
2447
  async deleteArtifact(req, artifactId) {
2127
2448
  try {
2128
2449
  const appService = this.getAppService(req);
@@ -2139,6 +2460,9 @@ let AppController = AppController_1 = class AppController {
2139
2460
  throw new common_1.HttpException('Failed to delete artifact', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
2140
2461
  }
2141
2462
  }
2463
+ /**
2464
+ * List artifacts attached to agent
2465
+ */
2142
2466
  async listAgentArtifacts(req, agentId) {
2143
2467
  try {
2144
2468
  const appService = this.getAppService(req);
@@ -2149,6 +2473,9 @@ let AppController = AppController_1 = class AppController {
2149
2473
  return { artifacts: [] };
2150
2474
  }
2151
2475
  }
2476
+ /**
2477
+ * Attach artifact to agent
2478
+ */
2152
2479
  async attachArtifactToAgent(req, agentId, body) {
2153
2480
  if (!body.artifactId) {
2154
2481
  throw new common_1.BadRequestException('Artifact ID is required');
@@ -2165,6 +2492,9 @@ let AppController = AppController_1 = class AppController {
2165
2492
  throw new common_1.HttpException('Failed to attach artifact', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
2166
2493
  }
2167
2494
  }
2495
+ /**
2496
+ * Detach artifact from agent
2497
+ */
2168
2498
  async detachArtifactFromAgent(req, agentId, artifactId) {
2169
2499
  try {
2170
2500
  const appService = this.getAppService(req);
@@ -2718,6 +3048,16 @@ __decorate([
2718
3048
  __metadata("design:paramtypes", [Object, String, Object]),
2719
3049
  __metadata("design:returntype", Promise)
2720
3050
  ], AppController.prototype, "sendRoomMessage", null);
3051
+ __decorate([
3052
+ (0, room_access_decorator_1.RoomAccess)(),
3053
+ (0, common_1.Post)('rooms/:roomId/begin'),
3054
+ (0, common_1.HttpCode)(common_1.HttpStatus.CREATED),
3055
+ __param(0, (0, common_1.Request)()),
3056
+ __param(1, (0, common_1.Param)('roomId')),
3057
+ __metadata("design:type", Function),
3058
+ __metadata("design:paramtypes", [Object, String]),
3059
+ __metadata("design:returntype", Promise)
3060
+ ], AppController.prototype, "beginRoom", null);
2721
3061
  __decorate([
2722
3062
  (0, room_access_decorator_1.RoomAccess)(),
2723
3063
  (0, common_1.Post)('rooms/:roomId/pause'),
@@ -2907,6 +3247,17 @@ __decorate([
2907
3247
  __metadata("design:paramtypes", [Object, String]),
2908
3248
  __metadata("design:returntype", Promise)
2909
3249
  ], AppController.prototype, "revertStoryChapter", null);
3250
+ __decorate([
3251
+ (0, room_access_decorator_1.RoomReadAccess)(),
3252
+ (0, common_1.Get)('rooms/:roomId/images/:artifactId'),
3253
+ __param(0, (0, common_1.Request)()),
3254
+ __param(1, (0, common_1.Param)('roomId')),
3255
+ __param(2, (0, common_1.Param)('artifactId')),
3256
+ __param(3, (0, common_1.Res)()),
3257
+ __metadata("design:type", Function),
3258
+ __metadata("design:paramtypes", [Object, String, String, Object]),
3259
+ __metadata("design:returntype", Promise)
3260
+ ], AppController.prototype, "getRoomImage", null);
2910
3261
  __decorate([
2911
3262
  (0, room_access_decorator_1.RoomReadAccess)(),
2912
3263
  (0, common_1.Get)('rooms/:roomId/artifacts'),
@@ -2985,7 +3336,7 @@ __decorate([
2985
3336
  (0, common_1.Post)('stories/import'),
2986
3337
  (0, common_1.UseInterceptors)((0, platform_express_1.FileInterceptor)('file', {
2987
3338
  limits: {
2988
- fileSize: 100 * 1024 * 1024,
3339
+ fileSize: 100 * 1024 * 1024, // 100MB limit
2989
3340
  },
2990
3341
  })),
2991
3342
  (0, common_1.HttpCode)(common_1.HttpStatus.CREATED),