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
@@ -43,8 +43,16 @@ const core_1 = require("./tools/core");
43
43
  const app_types_1 = require("../../shared/types/app.types");
44
44
  const pdf_lib_1 = require("pdf-lib");
45
45
  const pdf_conversion_1 = require("./documents/pdf-conversion");
46
+ const app_types_2 = require("../../shared/types/app.types");
46
47
  const message_1 = require("./room/message");
47
48
  const logger_1 = require("./common/logger");
49
+ /**
50
+ * Up to this many pages, a PDF is converted in one request instead of page by page.
51
+ *
52
+ * Short documents read better whole — a heading and the table under it stay
53
+ * together — and cost one call rather than ten. Past it, page-level retry and
54
+ * partial success matter more than continuity.
55
+ */
48
56
  const WHOLE_PDF_PAGE_LIMIT = 10;
49
57
  class AppService {
50
58
  aiFactoryService;
@@ -67,9 +75,10 @@ class AppService {
67
75
  toolStore;
68
76
  toolExecution;
69
77
  packService;
78
+ illustration;
70
79
  aiServices;
71
80
  userPreferencesFile = 'user-preferences.json';
72
- constructor(aiFactoryService, agentStore, agentMessageService, roomStore, roomMessageService, userPaths, attachedFileService, artifactService, storyStore, storyService, publishedAgentsService, publishedRoomsService, balanceService, balanceMessageService, transactionService, agentFactory, roomFactory, toolStore, toolExecution, packService) {
81
+ constructor(aiFactoryService, agentStore, agentMessageService, roomStore, roomMessageService, userPaths, attachedFileService, artifactService, storyStore, storyService, publishedAgentsService, publishedRoomsService, balanceService, balanceMessageService, transactionService, agentFactory, roomFactory, toolStore, toolExecution, packService, illustration) {
73
82
  this.aiFactoryService = aiFactoryService;
74
83
  this.agentStore = agentStore;
75
84
  this.agentMessageService = agentMessageService;
@@ -90,15 +99,24 @@ class AppService {
90
99
  this.toolStore = toolStore;
91
100
  this.toolExecution = toolExecution;
92
101
  this.packService = packService;
102
+ this.illustration = illustration;
93
103
  this.aiServices = this.aiFactoryService.getAllAiServices();
94
104
  }
105
+ /** Packs, as this user sees them. */
95
106
  get packs() {
96
107
  return this.packService;
97
108
  }
98
109
  packInstantiationService;
110
+ /**
111
+ * Supplies the service that builds agents and rooms from pack templates.
112
+ *
113
+ * Set after construction rather than injected: it drives this service, so it
114
+ * cannot also be one of its constructor arguments.
115
+ */
99
116
  setPackInstantiation(service) {
100
117
  this.packInstantiationService = service;
101
118
  }
119
+ /** Builds agents and rooms from pack templates. */
102
120
  get packInstantiation() {
103
121
  if (!this.packInstantiationService) {
104
122
  throw new Error('Pack instantiation service is not set');
@@ -106,32 +124,79 @@ class AppService {
106
124
  return this.packInstantiationService;
107
125
  }
108
126
  rpgCampaignService;
127
+ /**
128
+ * Supplies the service that builds and reads campaigns.
129
+ *
130
+ * Set after construction for the same reason pack instantiation is: it drives
131
+ * this service, so it cannot also be one of its constructor arguments.
132
+ */
109
133
  setRpg(service) {
110
134
  this.rpgCampaignService = service;
111
135
  }
136
+ /** Campaigns: the streamlined D&D surface, built on packs and published rooms. */
112
137
  get rpg() {
113
138
  if (!this.rpgCampaignService) {
114
139
  throw new Error('RPG service is not set');
115
140
  }
116
141
  return this.rpgCampaignService;
117
142
  }
143
+ /**
144
+ * The packs this user has enabled, as a thunk.
145
+ *
146
+ * Handed to the prompt resolver and to every agent this service creates. A
147
+ * thunk rather than an array because both outlive a toggle — see
148
+ * {@link Agent.enabledPacks}.
149
+ */
118
150
  enabledPacks = () => this.packService.enabledPacks();
151
+ /**
152
+ * Returns the names of all available AI service providers.
153
+ *
154
+ * Only providers that have a configured API key are included.
155
+ *
156
+ * @returns Array of provider names (e.g. `'Anthropic'`, `'OpenAI'`, `'GoogleAI'`)
157
+ */
119
158
  getAiServiceNames() {
120
159
  return this.aiServices.filter((s) => s.isAvailable).map((s) => s.getServiceName());
121
160
  }
161
+ /**
162
+ * Returns the AI service instance for the given provider name.
163
+ *
164
+ * @internal Returns a framework-level service; SDK consumers should use
165
+ * {@link listAiModels} or higher-level methods rather than handling
166
+ * `BaseAiService` directly.
167
+ * @param serviceName - Provider name as returned by {@link getAiServiceNames}
168
+ * @returns The corresponding AI service instance
169
+ * @throws {Error} If the service name is not recognized
170
+ */
122
171
  getAiServiceFromServiceName(serviceName) {
123
172
  return this.aiFactoryService.createAiService(serviceName);
124
173
  }
174
+ /**
175
+ * Fetches available models from the specified AI service provider.
176
+ *
177
+ * @param aiServiceName - Provider name as returned by {@link getAiServiceNames}
178
+ * @returns Array of model descriptors including name, description, and service
179
+ */
125
180
  async listAiModels(aiServiceName) {
126
181
  let service = this.getAiServiceFromServiceName(aiServiceName);
127
182
  return service.listModels();
128
183
  }
184
+ /**
185
+ * Returns models available for image generation, as configured in
186
+ * `common/config/image_models.json`.
187
+ *
188
+ * @returns Array of model descriptors. Returns an empty array if the config file is missing.
189
+ */
129
190
  async listImageModels() {
130
191
  const imageModelsPath = path.join(this.userPaths.getCommonConfigDir(), 'image_models.json');
131
192
  try {
132
193
  const entries = JSON.parse(fs.readFileSync(imageModelsPath, 'utf8'));
194
+ // The dialog presents one image-model dropdown. Each consolidated entry
195
+ // carries its own generation and editing models server-side, so the client
196
+ // only needs the name and description. "No images" is offered as a fixed
197
+ // option in the dialog itself, so it is excluded here.
133
198
  return entries
134
- .filter((entry) => entry.name && entry.name !== 'No images')
199
+ .filter((entry) => entry.name && entry.name !== app_types_2.NO_IMAGES)
135
200
  .map((entry) => ({ name: entry.name, description: entry.description ?? '' }));
136
201
  }
137
202
  catch (error) {
@@ -139,6 +204,12 @@ class AppService {
139
204
  return [];
140
205
  }
141
206
  }
207
+ /**
208
+ * Returns models available for story generation, as configured in
209
+ * `common/config/story_models.json`.
210
+ *
211
+ * @returns Array of model descriptors. Returns an empty array if the config file is missing.
212
+ */
142
213
  async listStoryModels() {
143
214
  const storyModelsPath = path.join(this.userPaths.getCommonConfigDir(), 'story_models.json');
144
215
  try {
@@ -149,6 +220,14 @@ class AppService {
149
220
  return [];
150
221
  }
151
222
  }
223
+ /**
224
+ * Returns the available story genre names.
225
+ *
226
+ * Genres are read from `common/story_ideas/` - each `.json` file corresponds to a genre.
227
+ * Pass a genre name to {@link getRandomStoryIdeaByGenre} to get a story idea.
228
+ *
229
+ * @returns Array of genre names (e.g. `['fantasy', 'sci-fi', 'mystery']`)
230
+ */
152
231
  listStoryGenres() {
153
232
  const storyIdeasPath = path.join(this.userPaths.getDataDir(), 'common', 'story_ideas');
154
233
  try {
@@ -165,6 +244,14 @@ class AppService {
165
244
  return [];
166
245
  }
167
246
  }
247
+ /**
248
+ * Returns a random story idea from the specified genre.
249
+ *
250
+ * @param genreName - Genre name as returned by {@link listStoryGenres} (e.g. `'fantasy'`)
251
+ * @returns A random `StoryIdea` object, or `null` if the genre file is empty
252
+ * @throws {NotFoundError} If the genre does not exist
253
+ * @throws {OperationFailedError} If the genre file cannot be read
254
+ */
168
255
  getRandomStoryIdeaByGenre(genreName) {
169
256
  const storyIdeasPath = path.join(this.userPaths.getDataDir(), 'common', 'story_ideas', `${genreName}.json`);
170
257
  try {
@@ -175,6 +262,7 @@ class AppService {
175
262
  if (ideas.length === 0) {
176
263
  return null;
177
264
  }
265
+ // Return random idea from the array
178
266
  const randomIndex = Math.floor(Math.random() * ideas.length);
179
267
  return ideas[randomIndex];
180
268
  }
@@ -186,33 +274,82 @@ class AppService {
186
274
  throw new errors_1.OperationFailedError('Failed to read story ideas');
187
275
  }
188
276
  }
277
+ /**
278
+ * Returns a random story idea from a randomly selected genre.
279
+ *
280
+ * @returns A random `StoryIdea` object, or `null` if no genres/ideas are available
281
+ */
189
282
  getRandomStoryIdea() {
190
283
  const genres = this.listStoryGenres();
191
284
  if (genres.length === 0) {
192
285
  return null;
193
286
  }
287
+ // Pick random genre
194
288
  const randomGenre = genres[Math.floor(Math.random() * genres.length)];
289
+ // Get random idea from that genre
195
290
  return this.getRandomStoryIdeaByGenre(randomGenre);
196
291
  }
292
+ /**
293
+ * Creates a new AI agent and registers it in memory.
294
+ *
295
+ * The agent is immediately findable by ID but **not** persisted to disk.
296
+ * Call `agent.save()` when you want to write it to storage.
297
+ *
298
+ * @param aiServiceName - Provider name (e.g. `'Anthropic'`, `'OpenAI'`). Use {@link getAiServiceNames} for valid values.
299
+ * @param agentName - Full name of the agent (used in conversation logs and file storage)
300
+ * @param agentNickname - Short display name shown in the UI
301
+ * @param description - Brief description of the agent's role or personality
302
+ * @param aiModel - Model identifier (e.g. `'claude-haiku-4-5'`, `'gpt-4o'`)
303
+ * @param promptName - Prompt folder under `data/prompts/` that provides the agent's system instruction. Defaults to `'default'`.
304
+ * @param controlledByHuman - If `true`, the agent's responses are driven by a human rather than the AI. Defaults to `false`.
305
+ * @param reasoningEffort - Extended-thinking effort level for models that support it (e.g. Claude 3.7 Sonnet, o1/o3). Pass `null` to disable. Defaults to `undefined` (model default).
306
+ * @param maxOutputTokens - Override the model's default maximum output token limit
307
+ * @param beginInstruction - Optional prompt stored with the agent and sent when the host app triggers a "Begin" action (e.g. `'Begin by reading the attached documents and asking the user the first question.'`)
308
+ * @param options - Everything else an agent can be created with: tool grants, private context, prompt cache TTL, search, the history window and the small-model override. Add new settings here rather than as further positional parameters.
309
+ * @returns The newly created {@link Agent} instance
310
+ *
311
+ * @example
312
+ * ```typescript
313
+ * const agent = appService.createAgent(
314
+ * 'Anthropic',
315
+ * 'AI Assistant',
316
+ * 'James',
317
+ * 'A helpful AI assistant',
318
+ * 'claude-haiku-4-5',
319
+ * );
320
+ * if (!agent.id) throw new Error('Agent creation failed');
321
+ * agent.save(); // persist to disk
322
+ * ```
323
+ */
197
324
  createAgent(aiServiceName, agentName, agentNickname, description, aiModel, promptName = 'default', controlledByHuman, reasoningEffort, maxOutputTokens, beginInstruction, options) {
325
+ // A folder that reaches nothing is not an error here — the agent still runs,
326
+ // on the shared root prompts — but it is never what the caller meant, and
327
+ // the only symptom is a generic agent several LLM calls later.
198
328
  if (!this.promptFolderExists(promptName)) {
199
329
  logger_1.logger.warn(`Agent "${agentNickname}" names the prompt folder "${promptName}", which does not exist. ` +
200
330
  `It will fall back to the shared root prompts and behave generically. ` +
201
331
  `A pack's folder is named "<pack>:${promptName}" unless the pack is enabled for this user.`);
202
332
  }
203
333
  const agent = this.agentFactory.createAgent(aiServiceName, agentName, agentNickname, description, promptName, aiModel);
334
+ // Set the controlledByHuman property
204
335
  if (controlledByHuman !== undefined) {
205
336
  agent.isControlledByHuman = controlledByHuman;
206
337
  }
338
+ // Set the reasoningEffort property
207
339
  if (reasoningEffort !== undefined) {
208
340
  agent.reasoningEffort = reasoningEffort;
209
341
  }
342
+ // Set the reasoningEffort property
210
343
  if (maxOutputTokens !== undefined) {
211
344
  agent.maxOutputTokens = maxOutputTokens;
212
345
  }
346
+ // Set the beginInstruction property
213
347
  if (beginInstruction !== undefined) {
214
348
  agent.beginInstruction = beginInstruction;
215
349
  }
350
+ // Everything without a positional slot. New settings go here rather than
351
+ // lengthening the parameter list, and every one of them is also settable
352
+ // through updateAgent, so nothing is create-only or edit-only.
216
353
  if (options) {
217
354
  if (options.allowSearch !== undefined)
218
355
  agent.allowSearch = options.allowSearch;
@@ -231,15 +368,72 @@ class AppService {
231
368
  if (options.ownerRoomId !== undefined)
232
369
  agent.ownerRoomId = options.ownerRoomId;
233
370
  }
371
+ // Set up SSE callback for this agent
234
372
  this.setupAgentStateCallback(agent);
373
+ // Register in memory so the agent is immediately findable by ID,
374
+ // without writing to disk (call agent.save() to persist).
235
375
  this.agentStore.registerAgent(agent);
236
376
  return agent;
237
377
  }
378
+ /**
379
+ * Creates an agent from a prompt folder, applying everything that folder declares.
380
+ *
381
+ * A folder's `defaults_config.json` names the role: what it is called, which tools
382
+ * it needs, which documents it carries. {@link createAgent} takes none of that —
383
+ * it takes eleven positional arguments and an options object, and leaves the
384
+ * mapping to the caller. Every caller then writes the same mapping: the web
385
+ * client's create-agent dialog, and every SDK host after it. Hard-coding the
386
+ * result instead is worse, because a pack's tool and document lists change and a
387
+ * transcribed copy does not.
388
+ *
389
+ * Differences from {@link createAgent}, each deliberate:
390
+ *
391
+ * - **It saves.** A convenience constructor that leaves the agent in memory only
392
+ * loses it on restart, which is not what a caller reaching for one expects.
393
+ * - **It attaches the folder's documents**, unless `attachDocuments` is false.
394
+ * {@link PromptFolderDefaults.documentIds} describes them as a pre-tick that
395
+ * stays the user's choice, which is right for a dialog where somebody can untick
396
+ * a box; headless there is nobody to untick, and a character creator without its
397
+ * class documents builds sheets with no spells and no class features.
398
+ * - **It is async**, only because attaching is.
399
+ *
400
+ * @param options.folder Prompt folder name, e.g. `'dungeon_master'`
401
+ * @param options.aiServiceName Provider name, e.g. `'Anthropic'`
402
+ * @param options.aiModel Model id for this agent
403
+ * @param options.overrides Fields to override the folder's declared defaults;
404
+ * the same shape, so `{agentNickname: 'Homer', controlledByHuman: true}` is all
405
+ * a human-controlled player needs
406
+ * @param options.attachDocuments Attach the folder's `documentIds` (default true)
407
+ * @returns The created, saved agent
408
+ * @throws {NotFoundError} If the folder does not exist. Unlike {@link createAgent},
409
+ * which warns and carries on, this refuses: the whole point of the call is the
410
+ * folder's recipe, and a folder that is not there has none — the agent would come
411
+ * out with no tools, no documents and the shared root prompts
412
+ * @throws {Error} If the agent could not be created
413
+ *
414
+ * @example
415
+ * ```typescript
416
+ * const dm = await appService.createAgentFromFolder({
417
+ * folder: 'dungeon_master',
418
+ * aiServiceName: 'Anthropic',
419
+ * aiModel: 'claude-sonnet-5',
420
+ * });
421
+ * const you = await appService.createAgentFromFolder({
422
+ * folder: 'dnd_player',
423
+ * aiServiceName: 'Anthropic',
424
+ * aiModel: 'claude-haiku-4-5',
425
+ * overrides: { agentNickname: 'Homer', controlledByHuman: true },
426
+ * });
427
+ * ```
428
+ */
238
429
  async createAgentFromFolder(options) {
239
430
  this.requirePromptFolder(options.folder);
240
431
  const { defaults } = this.getPromptFolderDefaults(options.folder);
241
432
  const settings = { ...defaults, ...options.overrides };
242
- const agent = this.createAgent(options.aiServiceName, settings.agentName ?? options.folder, settings.agentNickname ?? settings.agentName ?? options.folder, settings.description ?? '', options.aiModel, options.folder, settings.controlledByHuman, settings.reasoningEffort ?? null, undefined, settings.beginInstruction, {
433
+ const agent = this.createAgent(options.aiServiceName,
434
+ // A folder that names neither falls back to its own name, which is at
435
+ // least addressable — an agent with an empty nickname is not.
436
+ settings.agentName ?? options.folder, settings.agentNickname ?? settings.agentName ?? options.folder, settings.description ?? '', options.aiModel, options.folder, settings.controlledByHuman, settings.reasoningEffort ?? null, undefined, settings.beginInstruction, {
243
437
  toolNames: settings.toolNames ?? [],
244
438
  allowSearch: settings.allowSearch,
245
439
  useModerator: settings.useModerator,
@@ -259,14 +453,37 @@ class AppService {
259
453
  }
260
454
  return agent;
261
455
  }
456
+ /**
457
+ * Sends a text prompt to an agent and returns its response.
458
+ *
459
+ * The exchange is added to the agent's conversation history and persisted to disk.
460
+ *
461
+ * @param agentId - The agent's ID (from {@link createAgent} or {@link listAgents})
462
+ * @param text - The prompt text to send
463
+ * @returns Object containing the agent's reply text (`result`), the latest formatted
464
+ * message, its index in the history, and cumulative token counts and cost
465
+ * @throws {NotFoundError} If no agent with the given ID exists
466
+ *
467
+ * @example
468
+ * ```typescript
469
+ * const result = await appService.processText(agent.id, 'What is the capital of France?');
470
+ * console.log(result.result); // 'Paris'
471
+ * console.log(result.totalCost); // e.g. 0.000023
472
+ * ```
473
+ */
262
474
  async processText(agentId, text) {
475
+ // Retrieve the agent from the store
263
476
  const agent = await this.agentStore.getAgent(agentId);
264
477
  if (!agent) {
265
478
  throw new errors_1.NotFoundError(`Agent with ID ${agentId} not found`);
266
479
  }
480
+ // Set up SSE callback for this agent (if not already set)
267
481
  this.setupAgentStateCallback(agent);
482
+ // Process the text using the agent context
268
483
  const result = await agent.textPrompt(text, null, true, null, true);
484
+ // Save agent state to persist history changes and trigger SSE update
269
485
  agent.save();
486
+ // Return latest message and its index
270
487
  const messages = agent.getFormattedMessages();
271
488
  return {
272
489
  result,
@@ -277,22 +494,64 @@ class AppService {
277
494
  totalCost: agent.totalCost,
278
495
  };
279
496
  }
497
+ /**
498
+ * Attaches a document to an agent so it can reference the file's contents in prompts.
499
+ *
500
+ * The file is stored on disk and uploaded to the AI provider if required
501
+ * (e.g. OpenAI file uploads, Grok file uploads). The agent state is persisted after attachment.
502
+ *
503
+ * @param agentId - The agent's ID
504
+ * @param fileName - File name including extension (e.g. `'report.pdf'`)
505
+ * @param fileData - Raw file bytes as a `Buffer`
506
+ * @returns Object containing a `documentId` that can be used with {@link deleteAttachedFileById}
507
+ * @throws {Error} If no agent with the given ID exists
508
+ */
280
509
  async attachDocument(agentId, fileName, fileData) {
281
510
  let agent = await this.agentStore.getAgent(agentId);
282
511
  if (!agent)
283
512
  throw new Error(`Agent with ID ${agentId} not found`);
513
+ // Store the file using the AttachedFileService
284
514
  const fileId = this.attachedFileService.storeFile(agentId, fileName, new Uint8Array(fileData));
515
+ // Get the file metadata and add it to the agent's attachedFiles array
285
516
  const fileMetadata = this.attachedFileService.getFileMetadataByName(agentId, fileName);
286
517
  if (fileMetadata && !agent.attachedFiles.some((f) => f.fileName === fileName)) {
287
518
  agent.attachedFiles.push(fileMetadata);
288
519
  }
520
+ // Process the document with the AI service
289
521
  await agent.attachDocument(fileName, new Uint8Array(fileData));
522
+ // Save agent to persist serviceMetadata added by AI service
290
523
  agent.save();
291
524
  return { documentId: fileId };
292
525
  }
526
+ /**
527
+ * Returns every prompt folder name this user can reach.
528
+ *
529
+ * Covers the common and user prompt directories plus the folders of any pack
530
+ * the user has enabled, which appear pack-qualified (`dnd5e:dungeon_master`).
531
+ * A folder in more than one directory appears once.
532
+ *
533
+ * @returns Sorted array of folder names
534
+ */
293
535
  listPromptFolders() {
294
536
  return (0, prompt_resolver_1.listPromptFolderRefs)(this.userPaths, { enabledPacks: this.enabledPacks }).map((folder) => folder.value);
295
537
  }
538
+ /**
539
+ * Returns prompt folder names annotated with where they came from.
540
+ *
541
+ * When the same folder name exists in both the user and common directories the
542
+ * user copy wins and the entry reports `scope: 'user'`. A pack's folder is a
543
+ * separate entry under its qualified name, so a pack shipping a `witness`
544
+ * folder does not collide with a `witness` folder the user wrote.
545
+ *
546
+ * Pack folders are listed only for enabled packs. That is the difference
547
+ * between listing and resolving: a disabled pack's folder still resolves when
548
+ * an agent names it, it just stops being offered.
549
+ *
550
+ * @param scope - Optional filter: `'common'` returns only system-provided folders
551
+ * (including packs', which are read-only in the same way), `'user'` returns only
552
+ * the user's own folders and their pack overlays, omit to return all
553
+ * @returns Object with a `folders` array, sorted by name
554
+ */
296
555
  listPromptFoldersWithScope(scope) {
297
556
  const folders = (0, prompt_resolver_1.listPromptFolderRefs)(this.userPaths, {
298
557
  enabledPacks: this.enabledPacks,
@@ -305,40 +564,85 @@ class AppService {
305
564
  }));
306
565
  return { folders };
307
566
  }
567
+ /**
568
+ * Returns all prepared prompt template names available to a specific agent.
569
+ *
570
+ * Merges prompts from the agent's own prompt folder and the root prompts directory,
571
+ * deduplicating across both. These names can be passed to {@link runPreparedPrompt}.
572
+ *
573
+ * @param agentId - The agent's ID
574
+ * @returns Array of prompt template names (without file extension)
575
+ * @throws {NotFoundError} If no agent with the given ID exists
576
+ */
308
577
  async listPrompts(agentId) {
578
+ // Retrieve the agent from the store
309
579
  const agent = await this.agentStore.getAgent(agentId);
310
580
  if (!agent) {
311
581
  throw new errors_1.NotFoundError(`Agent with ID ${agentId} not found`);
312
582
  }
583
+ // Get the prompt path from the agent
313
584
  let agentPromptsDir = path.join(this.userPaths.getPromptsDir(), agent.promptFolder);
314
585
  let promptFiles = [];
586
+ // Check if directory exists
315
587
  if (fs.existsSync(agentPromptsDir)) {
588
+ // Get all .prompt files in the agent's prompt folder
316
589
  promptFiles = fs
317
590
  .readdirSync(agentPromptsDir)
318
591
  .filter((file) => file.endsWith('.prompt') && file !== 'system_instruction.prompt')
319
592
  .map((file) => file.replace('.prompt', ''));
320
593
  }
594
+ // Also get prompts from the root prompts directory
321
595
  const rootPromptFiles = fs
322
596
  .readdirSync(this.userPaths.getPromptsDir())
323
597
  .filter((file) => file.endsWith('.prompt') && file !== 'system_instruction.prompt')
324
598
  .map((file) => file.replace('.prompt', ''));
599
+ // Combine the prompt files, avoiding duplicates
325
600
  promptFiles = [...new Set([...promptFiles, ...rootPromptFiles])];
326
601
  return promptFiles;
327
602
  }
603
+ /**
604
+ * Executes a named Handlebars prompt template against an agent.
605
+ *
606
+ * The template is loaded from the agent's prompt folder (with the standard 4-level
607
+ * fallback). `variables` are substituted into the template before sending.
608
+ *
609
+ * @param agentId - The agent's ID
610
+ * @param promptName - Template name returned by {@link listPrompts} (without extension)
611
+ * @param variables - Key-value pairs substituted into the template's `{{variable}}` placeholders
612
+ * @returns Object with a `result` string containing the agent's response
613
+ * @throws {NotFoundError} If no agent with the given ID exists
614
+ */
328
615
  async runPreparedPrompt(agentId, promptName, variables = {}) {
616
+ // Retrieve the agent from the store
329
617
  const agent = await this.agentStore.getAgent(agentId);
330
618
  if (!agent) {
331
619
  throw new errors_1.NotFoundError(`Agent with ID ${agentId} not found`);
332
620
  }
621
+ // Use Agent.preparedPrompt so cache config is computed via getCacheConfig()
622
+ // rather than left as the bare default - required by Anthropic's API.
333
623
  const result = await agent.preparedPrompt(promptName, variables || {}, true);
334
624
  return { result };
335
625
  }
626
+ /**
627
+ * Lists all top-level agents belonging to this user.
628
+ *
629
+ * Agents that are owned by a room or story are excluded - use
630
+ * {@link getRoomDetails} or story methods to access those agents.
631
+ *
632
+ * @param includeRoomAgents - Also return the agents owned by a room or story.
633
+ * Only for offering an existing agent as something to copy; the agent list a
634
+ * user manages is the default, unowned one.
635
+ * @returns Array of agent metadata objects
636
+ */
336
637
  async listAgents(includeRoomAgents = false) {
638
+ // Get all agent IDs from the store
337
639
  const agentIds = await this.agentStore.getAllAgentIds();
640
+ // Map each ID to an object with agent details
338
641
  const agentInfos = [];
339
642
  for (const id of agentIds) {
340
643
  const agent = await this.agentStore.getAgent(id);
341
644
  if (agent) {
645
+ // Don't show agents that belong to a cloned room (or a story)
342
646
  if (agent.ownerRoomId && !includeRoomAgents)
343
647
  continue;
344
648
  agentInfos.push({
@@ -367,6 +671,12 @@ class AppService {
367
671
  }
368
672
  return agentInfos;
369
673
  }
674
+ /**
675
+ * Returns detailed metadata for a specific agent.
676
+ *
677
+ * @param agentId - The agent's ID
678
+ * @returns Agent metadata object, or `null` if no agent with the given ID exists
679
+ */
370
680
  async getAgentDetails(agentId) {
371
681
  try {
372
682
  const agent = await this.agentStore.getAgent(agentId);
@@ -395,6 +705,8 @@ class AppService {
395
705
  canModerate: this.canAgentModerate(agent),
396
706
  privateContext: agent.privateContext,
397
707
  promptCacheTTL: agent.promptCacheTTL,
708
+ // The rest of what an agent is configured with, so copying one into
709
+ // a room reproduces it rather than a partly-defaulted lookalike.
398
710
  maxHistoryMessages: agent.maxHistoryMessages,
399
711
  smallModelName: agent.smallModelName,
400
712
  ownerRoomId: agent.ownerRoomId,
@@ -407,12 +719,65 @@ class AppService {
407
719
  return null;
408
720
  }
409
721
  }
722
+ /**
723
+ * Creates a new room and populates it with the specified agents.
724
+ *
725
+ * @param roomName - Display name for the room
726
+ * @param goal - Description of the room's purpose or objective, shared with all agents
727
+ * @param agentIds - IDs of the agents to add to the room. May be empty: a room
728
+ * is created before the agents that belong to it exist, and they are added
729
+ * afterwards with {@link createRoomAgent}.
730
+ * @param roomLeader - Nickname (or name) of the member agent to lead the room.
731
+ * Defaults to the first agent.
732
+ * @param turnMode - `'broadcast'` (default) prompts every agent for each message;
733
+ * `'directed'` prompts only the message's targets. See {@link RoomTurnMode}.
734
+ * @param moderator - Nickname of the agent that places messages the room cannot
735
+ * route mechanically. Only consulted in `'moderated'` mode.
736
+ * @returns Object containing the new `roomId`
737
+ * @throws {NotFoundError} If any agent ID does not exist
738
+ *
739
+ * @example
740
+ * ```typescript
741
+ * const { roomId } = await appService.createRoom(
742
+ * 'Research Session',
743
+ * 'Analyze the provided documents and produce a summary',
744
+ * [analystId, writerAgentId],
745
+ * );
746
+ * ```
747
+ */
748
+ /**
749
+ * Whether a prompt folder provides the `moderate.prompt` a moderator needs.
750
+ *
751
+ * The one definition of "could moderate", shared by the check that refuses a
752
+ * misconfigured room and the {@link AgentInfo.canModerate} the client picks a
753
+ * moderator with. Two definitions would eventually disagree, and the way they
754
+ * would show it is a room offering a moderator the server then rejects.
755
+ */
410
756
  folderProvidesModeratePrompt(promptFolder) {
411
757
  return !!this.getPromptFile(promptFolder, 'moderate.prompt').scope;
412
758
  }
759
+ /**
760
+ * Whether this agent could be a room's moderator.
761
+ *
762
+ * Both halves matter: moderating means answering a prompt, which a human agent
763
+ * never does, and it means having that prompt to answer.
764
+ */
413
765
  canAgentModerate(agent) {
414
766
  return !agent.isControlledByHuman && this.folderProvidesModeratePrompt(agent.promptFolder);
415
767
  }
768
+ /**
769
+ * Why the room cannot moderate, or null when it can.
770
+ *
771
+ * "Can" is deliberately stronger than "a moderator is named". A moderator whose
772
+ * prompt folder has no `moderate.prompt` fails in the worst possible way: the
773
+ * prompt lookup throws, {@link Room} swallows the throw, and the message
774
+ * disappears leaving only a log line. Catching that here is the difference
775
+ * between an error the user can act on and a room that quietly eats messages.
776
+ *
777
+ * @param roster The membership to resolve the moderator against, which is not
778
+ * always the room's current one — an agent being added is checked before it
779
+ * arrives.
780
+ */
416
781
  describeMissingModerator(room, roster) {
417
782
  const named = room.getModerator();
418
783
  if (!named?.trim()) {
@@ -430,6 +795,16 @@ class AppService {
430
795
  }
431
796
  return null;
432
797
  }
798
+ /**
799
+ * Refuses a configuration in which an agent that sends MODERATE messages has no
800
+ * moderator to route them.
801
+ *
802
+ * Checked when the combination can come into being — creating a room, adding an
803
+ * agent to one, changing a room's moderator, turning the flag on — and never on
804
+ * load, which would make an existing room unopenable rather than fixable.
805
+ *
806
+ * @param arriving An agent not yet in the room, checked as though it were.
807
+ */
433
808
  assertModeratorAvailable(room, arriving) {
434
809
  const roster = arriving ? [...room.getAgents(), arriving] : room.getAgents();
435
810
  const needsModerator = roster.filter((agent) => agent.useModerator);
@@ -442,18 +817,23 @@ class AppService {
442
817
  throw new errors_1.ValidationError(`${names} ${needsModerator.length === 1 ? 'uses' : 'use'} a moderator, ` +
443
818
  `so room "${room.getName()}" needs one. ${reason}`);
444
819
  }
445
- async createRoom(roomName, goal, agentIds, roomLeader, turnMode, moderator) {
820
+ async createRoom(roomName, goal, agentIds, roomLeader, turnMode, moderator, beginInstruction, imageModel, illustrationMode) {
821
+ // Validate that all agents exist before creating the room
446
822
  for (const agentId of agentIds) {
447
823
  const agent = await this.agentStore.getAgent(agentId);
448
824
  if (!agent) {
449
825
  throw new errors_1.NotFoundError(`Agent with ID ${agentId} not found`);
450
826
  }
451
827
  }
828
+ // Create a new room with the specified name and goal
452
829
  const room = this.roomFactory.createRoom(roomName, goal);
830
+ // Add each agent to the room
453
831
  for (const agentId of agentIds) {
454
832
  const agent = await this.agentStore.getAgent(agentId);
455
833
  room.arrive(agent);
456
834
  }
835
+ // Leader and turn mode are set after the roster so the leader can be
836
+ // validated against it.
457
837
  if (roomLeader !== undefined) {
458
838
  room.setRoomLeader(room_store_service_1.RoomStoreService.resolveLeaderNickname(room, roomLeader));
459
839
  }
@@ -463,24 +843,65 @@ class AppService {
463
843
  if (moderator !== undefined) {
464
844
  room.setModerator(moderator);
465
845
  }
846
+ if (beginInstruction !== undefined) {
847
+ room.setBeginInstruction(beginInstruction);
848
+ }
849
+ if (imageModel !== undefined) {
850
+ room.setImageModel(imageModel);
851
+ }
852
+ if (illustrationMode !== undefined) {
853
+ room.setIllustrationMode(illustrationMode);
854
+ }
855
+ // Before saveMetadata, so a room that cannot route its members' messages is
856
+ // never written to disk.
466
857
  this.assertModeratorAvailable(room);
467
858
  room.ready();
859
+ // Store the room and get its ID
468
860
  const roomId = room.saveMetadata();
861
+ // Set up SSE callback for real-time updates
469
862
  this.setupRoomStateCallback(room);
470
863
  return { roomId };
471
864
  }
472
- async editRoom(roomId, roomName, goal, baseRoomDir, agentIds, roomLeader, turnMode, moderator, pack) {
865
+ /**
866
+ * Updates the name, goal, and/or agent membership of an existing room.
867
+ *
868
+ * Published room instances cannot be edited - edit the template instead.
869
+ *
870
+ * @param roomId - The room's ID
871
+ * @param roomName - New display name
872
+ * @param goal - New goal description
873
+ * @param baseRoomDir - Optional override for the room's base storage directory
874
+ * @param agentIds - Replacement list of agent IDs (replaces current membership
875
+ * entirely). Omit to leave membership unchanged, which is what the client
876
+ * does: membership is managed through {@link createRoomAgent} and
877
+ * {@link removeRoomAgent}, not by re-sending the roster with every rename.
878
+ * @param roomLeader - Nickname (or name) of the member agent to lead the room.
879
+ * Omit to leave the current leader unchanged.
880
+ * @param turnMode - How the room chooses who responds. Omit to leave unchanged.
881
+ * See {@link RoomTurnMode}.
882
+ * @param moderator - Nickname of the moderator agent. Omit to leave unchanged.
883
+ * @param pack - The pack to file the room under. Empty string clears it.
884
+ * @param beginInstruction - What {@link beginRoom} sends to the leader. Empty
885
+ * string clears it, which withdraws the room's Begin. Omit to leave unchanged.
886
+ * @throws {NotFoundError} If the room does not exist
887
+ * @throws {OperationFailedError} If attempting to edit a published room instance
888
+ */
889
+ async editRoom(roomId, roomName, goal, baseRoomDir, agentIds, roomLeader, turnMode, moderator, pack, beginInstruction, imageModel, illustrationMode) {
890
+ // Get the existing room
473
891
  const room = await this.roomStore.getRoom(roomId);
474
892
  if (!room) {
475
893
  throw new errors_1.NotFoundError('Room not found');
476
894
  }
895
+ // Prevent editing published instances
477
896
  if (room.getIsPublished() && room.getTemplateRoomId()) {
478
897
  throw new errors_1.OperationFailedError('Cannot edit published room instances');
479
898
  }
899
+ // Update room properties
480
900
  const previousName = room.getName();
481
901
  room.setName(roomName);
482
902
  room.setGoal(goal);
483
903
  room.setBaseRoomDir(baseRoomDir || '');
904
+ // Update agents
484
905
  if (agentIds) {
485
906
  const newAgents = [];
486
907
  for (const agentId of agentIds) {
@@ -494,9 +915,14 @@ class AppService {
494
915
  }
495
916
  room.setAgents(newAgents);
496
917
  }
918
+ // A renamed room renames the agents it owns, whose names carry its name as
919
+ // a prefix. Without this the prefix records what the room was called when
920
+ // each agent was added, which is worse than no prefix at all.
497
921
  if (roomName !== previousName) {
498
922
  this.renameOwnedAgents(room, previousName, roomName);
499
923
  }
924
+ // After setAgents, so a leader is validated against the new membership
925
+ // rather than the roster it is replacing.
500
926
  if (roomLeader !== undefined) {
501
927
  room.setRoomLeader(room_store_service_1.RoomStoreService.resolveLeaderNickname(room, roomLeader));
502
928
  }
@@ -509,17 +935,48 @@ class AppService {
509
935
  if (pack !== undefined) {
510
936
  room.setPack(pack);
511
937
  }
938
+ if (beginInstruction !== undefined) {
939
+ room.setBeginInstruction(beginInstruction);
940
+ }
941
+ if (imageModel !== undefined) {
942
+ room.setImageModel(imageModel);
943
+ }
944
+ if (illustrationMode !== undefined) {
945
+ room.setIllustrationMode(illustrationMode);
946
+ }
947
+ // Catches clearing the moderator, or pointing it at an agent this edit just
948
+ // removed, while a member still needs one.
512
949
  this.assertModeratorAvailable(room);
950
+ // Save the updated room
513
951
  room.saveMetadata();
514
952
  }
953
+ /**
954
+ * Separates a room's name from the bare name of an agent that belongs to it.
955
+ */
515
956
  static ROOM_AGENT_SEPARATOR = ' - ';
957
+ /**
958
+ * The stored name of an agent that belongs to a room.
959
+ *
960
+ * Every agent lives inside exactly one room, so an unqualified "Narrator" says
961
+ * nothing about which table it sits at once there are three of them.
962
+ */
516
963
  static prefixedAgentName(roomName, bareName) {
517
964
  return `${roomName}${AppService.ROOM_AGENT_SEPARATOR}${bareName}`;
518
965
  }
966
+ /**
967
+ * Strips a room-name prefix from an agent name, leaving the bare name.
968
+ * An agent that does not carry the prefix is returned unchanged.
969
+ */
519
970
  static bareAgentName(roomName, agentName) {
520
971
  const prefix = roomName + AppService.ROOM_AGENT_SEPARATOR;
521
972
  return agentName.startsWith(prefix) ? agentName.slice(prefix.length) : agentName;
522
973
  }
974
+ /**
975
+ * Re-prefixes the agents a renamed room owns.
976
+ *
977
+ * Only the display name moves. The nickname is what every handoff, target and
978
+ * tool call addresses an agent by, so renaming the room must not touch it.
979
+ */
523
980
  renameOwnedAgents(room, previousName, roomName) {
524
981
  for (const agent of room.getAgents()) {
525
982
  if (agent.ownerRoomId !== room.getId())
@@ -529,6 +986,24 @@ class AppService {
529
986
  agent.save();
530
987
  }
531
988
  }
989
+ /**
990
+ * Creates an agent that belongs to a room and adds it to that room.
991
+ *
992
+ * This is the only way an agent joins a room. The agent is owned by it: it is
993
+ * left out of {@link listAgents} and deleted with the room, so a room is a
994
+ * self-contained cast rather than a set of references to a shared pool.
995
+ *
996
+ * `request.agentName` is the bare name. It is stored prefixed with the room's
997
+ * name, while the nickname is derived from the bare name — otherwise every
998
+ * agent in the room would be addressed by the room's first word.
999
+ *
1000
+ * @param roomId - The room the agent will belong to
1001
+ * @param request - The same fields {@link createAgent} takes
1002
+ * @returns Object containing the new `agentId`
1003
+ * @throws {NotFoundError} If the room does not exist
1004
+ * @throws {OperationFailedError} If the room is a published instance, or another
1005
+ * agent in the room already answers to the same nickname
1006
+ */
532
1007
  async createRoomAgent(roomId, request) {
533
1008
  const room = await this.roomStore.getRoom(roomId);
534
1009
  if (!room) {
@@ -538,7 +1013,11 @@ class AppService {
538
1013
  throw new errors_1.OperationFailedError('Cannot add agents to a published room instance');
539
1014
  }
540
1015
  const bareName = request.agentName.trim();
1016
+ // Mirrors Agent.generateNickname, but over the bare name: left to the
1017
+ // default the prefixed name would make every agent here "<RoomName>".
541
1018
  const nickname = request.agentNickname?.trim() || bareName.split(/\s+/)[0];
1019
+ // Checked against the request rather than the created agent, so a room with
1020
+ // no moderator refuses the agent instead of creating one and rolling it back.
542
1021
  if (request.useModerator) {
543
1022
  const reason = this.describeMissingModerator(room, room.getAgents());
544
1023
  if (reason) {
@@ -555,6 +1034,8 @@ class AppService {
555
1034
  smallModelName: request.smallModelName || undefined,
556
1035
  ownerRoomId: roomId,
557
1036
  });
1037
+ // arrive() refuses a nickname the room already uses. Take the agent back
1038
+ // out rather than leaving one behind that belongs to a room it never joined.
558
1039
  if (!room.arrive(agent)) {
559
1040
  this.agentStore.removeAgent(agent.id);
560
1041
  throw new errors_1.OperationFailedError(`An agent in this room is already addressed as "${nickname}"`);
@@ -563,10 +1044,37 @@ class AppService {
563
1044
  room.saveMetadata();
564
1045
  return { agentId: agent.id };
565
1046
  }
1047
+ /**
1048
+ * Adds an agent to a room, built from a prompt folder's declared defaults.
1049
+ *
1050
+ * The room-scoped counterpart to {@link createAgentFromFolder}, and the piece a
1051
+ * pack's room template is instantiated through. Everything a folder already
1052
+ * declares — name, nickname, description, tool grants, documents, cache TTL —
1053
+ * comes from its `defaults_config.json`, so a template only has to say what
1054
+ * differs.
1055
+ *
1056
+ * Routed through {@link createRoomAgent} rather than {@link createAgentFromFolder},
1057
+ * which does none of what a room member needs: the stored name is prefixed with
1058
+ * the room's, the nickname is derived from the bare name, `ownerRoomId` is set,
1059
+ * the moderator requirement is checked, and an agent whose nickname collides is
1060
+ * removed again instead of being left behind belonging to a room it never joined.
1061
+ *
1062
+ * @param roomId - The room to add to
1063
+ * @param options - The folder to build from, the model to use, and any overrides
1064
+ * @returns The new agent's id, its resolved nickname, and any document ids that
1065
+ * resolved to nothing — returned rather than swallowed, because a document that
1066
+ * silently fails to attach is a capability the agent appears to have and does not
1067
+ * @throws {NotFoundError} If the room does not exist, or the folder does not.
1068
+ * See {@link createAgentFromFolder} for why a missing folder is fatal here
1069
+ * @throws {ValidationError} If the agent needs a moderator the room does not have
1070
+ * @throws {OperationFailedError} If the nickname is already taken in the room
1071
+ */
566
1072
  async createRoomAgentFromFolder(roomId, options) {
567
1073
  this.requirePromptFolder(options.folder);
568
1074
  const { defaults } = this.getPromptFolderDefaults(options.folder);
569
1075
  const settings = { ...defaults, ...options.overrides };
1076
+ // A folder that names neither falls back to its own name, which is at least
1077
+ // addressable. Mirrors createAgentFromFolder.
570
1078
  const bareName = settings.agentName ?? options.folder;
571
1079
  const nickname = settings.agentNickname ?? bareName.split(/\s+/)[0];
572
1080
  const { agentId } = await this.createRoomAgent(roomId, {
@@ -607,6 +1115,16 @@ class AppService {
607
1115
  }
608
1116
  return { agentId, nickname, unresolvedDocumentIds };
609
1117
  }
1118
+ /**
1119
+ * Removes an agent from a room, and deletes it if the room owns it.
1120
+ *
1121
+ * @param roomId - The room's ID
1122
+ * @param agentId - The agent's ID
1123
+ * @throws {NotFoundError} If the room does not exist, or the agent is not in it
1124
+ * @throws {OperationFailedError} If the room is a published instance
1125
+ * @throws {ValidationError} If removing the moderator would leave an agent that
1126
+ * sends MODERATE messages with nothing to route them
1127
+ */
610
1128
  async removeRoomAgent(roomId, agentId) {
611
1129
  const room = await this.roomStore.getRoom(roomId);
612
1130
  if (!room) {
@@ -621,6 +1139,10 @@ class AppService {
621
1139
  throw new errors_1.NotFoundError('Agent is not in this room');
622
1140
  }
623
1141
  const remaining = agents.filter((a) => a.id !== agentId);
1142
+ // Removing the moderator is the one removal that can quietly break the room:
1143
+ // a message from an agent that sends MODERATE has nowhere to go, and the room
1144
+ // drops it with only a log line. Hand the role on where something can take it,
1145
+ // and refuse where nothing can, rather than leaving that behind.
624
1146
  if (room.getModerator() === departing.agentNickname) {
625
1147
  const heir = remaining.find((a) => this.canAgentModerate(a));
626
1148
  const stillNeeded = remaining.filter((a) => a.useModerator);
@@ -633,6 +1155,8 @@ class AppService {
633
1155
  room.setModerator(heir?.agentNickname ?? '');
634
1156
  }
635
1157
  room.setAgents(remaining);
1158
+ // A leader who has left would make getRoomLeader() name someone absent;
1159
+ // clearing it falls back to the first remaining agent.
636
1160
  if (room.getRoomLeader() === departing.agentNickname) {
637
1161
  room.setRoomLeader('');
638
1162
  }
@@ -641,15 +1165,31 @@ class AppService {
641
1165
  await this.deleteAgent(agentId);
642
1166
  }
643
1167
  }
1168
+ /**
1169
+ * Lists the rooms this user builds and owns.
1170
+ *
1171
+ * Published instances are excluded — use {@link getPublishedRoomInstances} for
1172
+ * those, which is also how the client reaches them.
1173
+ *
1174
+ * @returns Array of room summary objects (id, name, goal, agent count)
1175
+ */
644
1176
  async listRooms() {
645
1177
  return await this.roomStore.getTemplateRooms();
646
1178
  }
1179
+ /**
1180
+ * Returns full details for a room, including the metadata of each member agent.
1181
+ *
1182
+ * @param roomId - The room's ID
1183
+ * @returns Room details object, or `null` if no room with the given ID exists
1184
+ */
647
1185
  async getRoomDetails(roomId) {
648
1186
  const room = await this.roomStore.getRoom(roomId);
649
1187
  if (!room) {
650
1188
  return null;
651
1189
  }
1190
+ // Get all agents in the room
652
1191
  const roomAgents = room.getAgents();
1192
+ // Fetch detailed information for each agent
653
1193
  const agents = [];
654
1194
  for (const agent of roomAgents) {
655
1195
  const agentDetails = await this.getAgentDetails(agent.id);
@@ -666,6 +1206,9 @@ class AppService {
666
1206
  roomLeader: room.getRoomLeader(),
667
1207
  turnMode: room.getTurnMode(),
668
1208
  moderator: room.getModerator(),
1209
+ beginInstruction: room.getBeginInstruction(),
1210
+ imageModel: room.getImageModel(),
1211
+ illustrationMode: room.getIllustrationMode(),
669
1212
  baseRoomDir: room.getBaseRoomDir(),
670
1213
  pack: room.getPack(),
671
1214
  isPublished: room.getIsPublished(),
@@ -674,9 +1217,28 @@ class AppService {
674
1217
  processingInProgress: room.isProcessingInProgress(),
675
1218
  };
676
1219
  }
1220
+ /**
1221
+ * Returns the raw `Room` object for a given ID.
1222
+ *
1223
+ * Use {@link getRoomDetails} for a plain metadata object. This method exposes
1224
+ * the full `Room` instance, which is useful for advanced operations.
1225
+ *
1226
+ * @param roomId - The room's ID
1227
+ * @returns The `Room` instance, or `null` if not found
1228
+ */
677
1229
  async getRoomById(roomId) {
678
1230
  return await this.roomStore.getRoom(roomId);
679
1231
  }
1232
+ /**
1233
+ * Sets which agent leads the room's conversation and persists the change.
1234
+ *
1235
+ * The room leader is given conversational authority in the default room
1236
+ * prompts (other agents defer to it) and is consulted on adjournment.
1237
+ *
1238
+ * @param roomId - The room's ID
1239
+ * @param agentNickname - Nickname of the member agent to make leader
1240
+ * @throws {NotFoundError} If the room does not exist
1241
+ */
680
1242
  async setRoomLeader(roomId, agentNickname) {
681
1243
  const room = await this.roomStore.getRoom(roomId);
682
1244
  if (!room) {
@@ -685,6 +1247,19 @@ class AppService {
685
1247
  room.setRoomLeader(agentNickname);
686
1248
  room.saveMetadata();
687
1249
  }
1250
+ /**
1251
+ * Returns messages from a room's conversation log starting from a given index.
1252
+ *
1253
+ * Pass the index of the last message you received as `fromIndex` to poll for
1254
+ * new messages only.
1255
+ *
1256
+ * @param roomId - The room's ID
1257
+ * @param fromIndex - Zero-based index to start from (default `0` returns all messages)
1258
+ * @param includeThoughts - If `true`, includes `'think'` action messages which are
1259
+ * normally hidden (agents' internal reasoning). Default `false`.
1260
+ * @returns Object with the messages array and total cost across all agents.
1261
+ * Returns empty messages with zero cost if the room is not found.
1262
+ */
688
1263
  async getRoomMessages(roomId, fromIndex = 0, includeThoughts = false) {
689
1264
  const room = await this.roomStore.getRoom(roomId);
690
1265
  if (!room) {
@@ -693,16 +1268,25 @@ class AppService {
693
1268
  totalCost: 0,
694
1269
  };
695
1270
  }
1271
+ // Get messages from the specified index
696
1272
  const indexedMessages = room.getLatestRoomMessages(fromIndex, includeThoughts);
697
- const totalCost = room
698
- .getAgents()
699
- .map((a) => a.totalCost)
700
- .reduce((acc, v) => acc + v, 0);
1273
+ const totalCost = room.totalCost();
701
1274
  return {
702
1275
  messages: indexedMessages,
703
1276
  totalCost: totalCost,
704
1277
  };
705
1278
  }
1279
+ /**
1280
+ * Returns an agent's conversation history starting from a given index.
1281
+ *
1282
+ * Pass the `messageIndex` from a previous response as `fromIndex` to
1283
+ * retrieve only new messages since the last poll.
1284
+ *
1285
+ * @param agentId - The agent's ID
1286
+ * @param fromIndex - Zero-based index to start from (default `0` returns all messages)
1287
+ * @returns Object with the messages array and cumulative token/cost totals.
1288
+ * Returns empty messages with zero counts if the agent is not found.
1289
+ */
706
1290
  async getAgentMessages(agentId, fromIndex = 0) {
707
1291
  const agent = await this.agentStore.getAgent(agentId);
708
1292
  if (!agent) {
@@ -713,7 +1297,9 @@ class AppService {
713
1297
  totalCost: 0,
714
1298
  };
715
1299
  }
1300
+ // Set up SSE callback for this agent (if not already set)
716
1301
  this.setupAgentStateCallback(agent);
1302
+ // Use the agent's getFormattedMessages method
717
1303
  const formattedMessages = agent.getFormattedMessages(fromIndex);
718
1304
  return {
719
1305
  messages: formattedMessages,
@@ -722,6 +1308,12 @@ class AppService {
722
1308
  totalCost: agent.totalCost,
723
1309
  };
724
1310
  }
1311
+ /**
1312
+ * Gets messages from a story's room starting from a specific index
1313
+ * @param storyId The story ID
1314
+ * @param fromIndex The index to start from (0-based)
1315
+ * @returns Array of indexed messages and total story cost
1316
+ */
725
1317
  async getStoryMessages(storyId, fromIndex) {
726
1318
  const story = this.storyStore.getStory(storyId);
727
1319
  if (!story) {
@@ -735,11 +1327,48 @@ class AppService {
735
1327
  const totalCost = story.totalCost || 0;
736
1328
  return { messages, totalCost };
737
1329
  }
1330
+ /**
1331
+ * Adds a message to a room's pending queue to be processed by the agents.
1332
+ *
1333
+ * **Action values:**
1334
+ * - `'moderate'` *(default)* - routes the message through the room's moderator (story rooms only)
1335
+ * - `'speak'` - all agents hear the message; `targets` (if provided) restricts which agents may respond
1336
+ * - `'whisper'` - only agents listed in `targets` hear the message
1337
+ * - `'think'` - inaudible; stays only in the sender's history, not shown to other agents
1338
+ * - `'shout'` - overrides all other conversations; all agents hear and respond
1339
+ * - `'adjourn'` - signals intent to halt the conversation; the room adjourns once every agent agrees
1340
+ *
1341
+ * Anything else is sent as `'speak'`. To create an artifact use {@link publishArtifact}
1342
+ * rather than this method.
1343
+ *
1344
+ * @param roomId - The room's ID
1345
+ * @param content - The message text (or artifact body when `action` is `'publish'`)
1346
+ * @param sender - Display name of the sender (e.g. `'User'`, `'System'`)
1347
+ * @param action - Message action type (default `'moderate'`)
1348
+ * @param targets - Agent names to receive or respond to the message (behavior varies by action)
1349
+ * @param clearQueue - If `true`, clears any pending messages before adding this one. Default `false`.
1350
+ * @returns Whether the message was accepted. A human agent's message is rejected
1351
+ * (`accepted: false` with a `reason`) when it is not the human's turn to speak.
1352
+ * @throws {NotFoundError} If the room does not exist
1353
+ *
1354
+ * @example
1355
+ * ```typescript
1356
+ * // Broadcast a message that all agents can respond to
1357
+ * await appService.sendRoomMessage(roomId, 'Hello everyone!', 'User', 'speak');
1358
+ *
1359
+ * // Whisper to a specific agent
1360
+ * const result = await appService.sendRoomMessage(roomId, 'Just between us...', 'User', 'whisper', ['James']);
1361
+ * if (!result.accepted) {
1362
+ * console.log(result.reason); // e.g. "It is James's turn to speak"
1363
+ * }
1364
+ * ```
1365
+ */
738
1366
  async sendRoomMessage(roomId, content, sender, action = 'moderate', targets = [], clearQueue = false, context) {
739
1367
  const room = await this.roomStore.getRoom(roomId);
740
1368
  if (!room) {
741
1369
  throw new errors_1.NotFoundError('Room not found');
742
1370
  }
1371
+ // Map the action string to MessageAction enum
743
1372
  let messageAction;
744
1373
  switch (action.toLowerCase()) {
745
1374
  case 'moderate':
@@ -765,8 +1394,65 @@ class AppService {
765
1394
  messageAction = app_types_1.MessageAction.SPEAK;
766
1395
  }
767
1396
  room.ready();
1397
+ // Create a message from the system. `context` is an opaque, host-supplied
1398
+ // value threaded to any tool the resulting turn invokes (never persisted).
768
1399
  return room.addPendingMessage(new message_1.RoomMessage(sender, messageAction, content, targets), clearQueue, context);
769
1400
  }
1401
+ /**
1402
+ * Opens a room by sending its begin instruction to the room leader.
1403
+ *
1404
+ * A room is pull-driven: an agent is prompted only when a message arrives. So a
1405
+ * room nobody has spoken in never moves, however complete its configuration —
1406
+ * which for a turn-based table means the leader is waiting to be asked to lead.
1407
+ * This is the ask.
1408
+ *
1409
+ * Sent as `System` rather than as a person, and addressed by `targets` rather
1410
+ * than left for the room to place: in `broadcast` mode an untargeted message
1411
+ * prompts every agent, which for an opening move is one call per member to
1412
+ * decide one reply.
1413
+ *
1414
+ * The already-begun check is here rather than left to the client because a
1415
+ * published room is one link the whole party holds. Two people looking at the
1416
+ * same empty transcript both press Begin, and only a check the room makes
1417
+ * itself stops the leader being opened twice. `isProcessingInProgress()` is the
1418
+ * half of it that covers the window before the first message lands.
1419
+ *
1420
+ * @param roomId - The room's ID
1421
+ * @param context - Opaque host value threaded to any tool the turn invokes
1422
+ * @returns Whether the message was accepted, as {@link sendRoomMessage} reports it
1423
+ * @throws {NotFoundError} If the room does not exist
1424
+ * @throws {ValidationError} If the room has no begin instruction, or no agent to address
1425
+ * @throws {OperationFailedError} If the room has already begun
1426
+ */
1427
+ async beginRoom(roomId, context) {
1428
+ const room = await this.roomStore.getRoom(roomId);
1429
+ if (!room) {
1430
+ throw new errors_1.NotFoundError('Room not found');
1431
+ }
1432
+ const instruction = room.getBeginInstruction();
1433
+ if (!instruction) {
1434
+ throw new errors_1.ValidationError('This room has no begin instruction.');
1435
+ }
1436
+ if (room.getRoomMessageStats().numMessages > 0 || room.isProcessingInProgress()) {
1437
+ throw new errors_1.OperationFailedError('This room has already begun.');
1438
+ }
1439
+ // Falls back to the first agent, which is the room's convention everywhere
1440
+ // else. Only an empty room has nobody at all.
1441
+ const leader = room.getRoomLeader();
1442
+ if (!leader) {
1443
+ throw new errors_1.ValidationError('This room has no agents to address.');
1444
+ }
1445
+ logger_1.logger.log(`Beginning room "${room.getName()}" by addressing ${leader}`);
1446
+ return this.sendRoomMessage(roomId, instruction, 'System', 'speak', [leader], false, context);
1447
+ }
1448
+ /**
1449
+ * Pauses message processing in a room.
1450
+ *
1451
+ * Pending messages remain in the queue. Call {@link resumeRoom} to continue processing.
1452
+ *
1453
+ * @param roomId - The room's ID
1454
+ * @throws {NotFoundError} If the room does not exist
1455
+ */
770
1456
  async pauseRoom(roomId) {
771
1457
  const room = await this.roomStore.getRoom(roomId);
772
1458
  if (!room) {
@@ -774,6 +1460,12 @@ class AppService {
774
1460
  }
775
1461
  room.pause();
776
1462
  }
1463
+ /**
1464
+ * Resumes message processing in a room that was previously paused.
1465
+ *
1466
+ * @param roomId - The room's ID
1467
+ * @throws {NotFoundError} If the room does not exist
1468
+ */
777
1469
  async resumeRoom(roomId) {
778
1470
  const room = await this.roomStore.getRoom(roomId);
779
1471
  if (!room) {
@@ -781,29 +1473,64 @@ class AppService {
781
1473
  }
782
1474
  room.resume();
783
1475
  }
1476
+ /**
1477
+ * Permanently deletes an agent and all its stored data.
1478
+ *
1479
+ * If the agent is a published instance, its entry is also removed from the
1480
+ * published agents mapping.
1481
+ *
1482
+ * @param agentId - The agent's ID
1483
+ * @throws {NotFoundError} If no agent with the given ID exists
1484
+ */
784
1485
  async deleteAgent(agentId) {
785
1486
  const agent = await this.agentStore.getAgent(agentId);
786
1487
  if (!agent) {
787
1488
  throw new errors_1.NotFoundError('Agent not found');
788
1489
  }
1490
+ // If this is a published agent, remove it from the published agents mapping
789
1491
  if (agent.isPublished) {
790
1492
  this.publishedAgentsService.removePublishedAgent(agentId);
791
1493
  }
792
1494
  await agent.deleteAgent();
793
1495
  }
1496
+ /**
1497
+ * Creates a publicly accessible clone of a template agent.
1498
+ *
1499
+ * The new instance is independent of the template's conversation history.
1500
+ * Multiple instances can be created from a single template. Use
1501
+ * {@link resetPublishedInstance} to restore an instance to the template's
1502
+ * current state.
1503
+ *
1504
+ * @param templateId - ID of the template agent to clone
1505
+ * @param instanceName - Display name for the new instance
1506
+ * @returns Object with the new `instanceId` and the `publicUrl` path
1507
+ * @throws {NotFoundError} If the template agent does not exist
1508
+ * @see {@link getPublishedInstances}
1509
+ * @see {@link resetPublishedInstance}
1510
+ */
794
1511
  async publishAgentInstance(templateId, instanceName) {
1512
+ // Validate template exists
795
1513
  const template = await this.agentStore.getAgent(templateId);
796
1514
  if (!template) {
797
1515
  throw new errors_1.NotFoundError('Template agent not found');
798
1516
  }
1517
+ // Create the published instance
799
1518
  const userId = this.userPaths.getUserId();
800
1519
  const instanceId = await this.agentStore.cloneAgentAsPublished(templateId, instanceName, userId);
1520
+ // Add to published agents mapping
801
1521
  this.publishedAgentsService.addPublishedAgent(instanceId, userId);
802
1522
  return {
803
1523
  instanceId,
804
1524
  publicUrl: `/public/agents/${instanceId}`,
805
1525
  };
806
1526
  }
1527
+ /**
1528
+ * Returns all published instances created from a template agent.
1529
+ *
1530
+ * @param templateId - ID of the template agent
1531
+ * @returns Array of agent metadata objects for each published instance
1532
+ * @see {@link publishAgentInstance}
1533
+ */
807
1534
  async getPublishedInstances(templateId) {
808
1535
  const instances = await this.agentStore.getPublishedInstances(templateId);
809
1536
  return instances.map((agent) => ({
@@ -827,6 +1554,16 @@ class AppService {
827
1554
  useModerator: agent.useModerator,
828
1555
  }));
829
1556
  }
1557
+ /**
1558
+ * Resets a published agent instance to its template's current state.
1559
+ *
1560
+ * Clears the instance's conversation history and regenerates it from
1561
+ * the template agent. Does not affect the template itself.
1562
+ *
1563
+ * @param instanceId - ID of the published instance to reset
1564
+ * @throws {NotFoundError} If the instance does not exist
1565
+ * @throws {OperationFailedError} If the agent is not a published instance
1566
+ */
830
1567
  async resetPublishedInstance(instanceId) {
831
1568
  const instance = await this.agentStore.getAgent(instanceId);
832
1569
  if (!instance) {
@@ -837,11 +1574,22 @@ class AppService {
837
1574
  }
838
1575
  await this.agentStore.resetPublishedInstance(instanceId, instance.templateAgentId);
839
1576
  }
1577
+ /**
1578
+ * Lists all published agent instances belonging to this user.
1579
+ *
1580
+ * Published agents are clones of template agents that are accessible
1581
+ * via the public API (e.g. for end-users to chat with). Agents owned
1582
+ * by rooms are excluded from this list.
1583
+ *
1584
+ * @returns Array of agent metadata objects for all published instances
1585
+ * @see {@link publishAgentInstance}
1586
+ */
840
1587
  async listPublishedAgents() {
841
1588
  const agentIds = await this.agentStore.getAllAgentIds();
842
1589
  const agents = [];
843
1590
  for (const id of agentIds) {
844
1591
  const agent = await this.agentStore.getAgent(id);
1592
+ // Filter: only include agents that are published AND not owned by a room
845
1593
  if (agent && agent.isPublished && !agent.ownerRoomId) {
846
1594
  agents.push({
847
1595
  id: agent.id,
@@ -867,27 +1615,56 @@ class AppService {
867
1615
  }
868
1616
  return agents;
869
1617
  }
1618
+ /**
1619
+ * Permanently deletes a room and all its data.
1620
+ *
1621
+ * If the room is a template, all of its published instances are deleted first.
1622
+ * The agents the room owns, its attached files and its published room mapping
1623
+ * are also cleaned up.
1624
+ *
1625
+ * @param roomId - The room's ID
1626
+ * @throws {NotFoundError} If the room does not exist
1627
+ * @throws {OperationFailedError} If deletion fails
1628
+ */
870
1629
  async deleteRoom(roomId) {
1630
+ // Check if the room exists
871
1631
  const room = await this.roomStore.getRoom(roomId);
872
1632
  if (!room) {
873
1633
  throw new errors_1.NotFoundError('Room not found');
874
1634
  }
875
- const isTemplate = !room.getTemplateRoomId();
1635
+ const isTemplate = !room.getTemplateRoomId(); // No template ID means it's a template
1636
+ // If deleting a template, cascade delete all published instances first
876
1637
  if (isTemplate) {
877
1638
  const instances = await this.roomStore.getPublishedInstances(roomId);
878
1639
  for (const instance of instances) {
1640
+ // Recursively delete each published instance (which deletes their agents)
879
1641
  await this.deleteRoom(instance.getId());
880
1642
  }
881
1643
  }
1644
+ // Delete all attached files for this room
882
1645
  this.attachedFileService.deleteAllFiles(roomId);
1646
+ // Remove from published mapping if this is a published instance
883
1647
  if (room.getIsPublished()) {
884
1648
  this.publishedRoomsService.removePublishedRoom(roomId);
885
1649
  }
1650
+ // Remove the room from the store, along with the agents it owns
886
1651
  const removed = this.roomStore.removeRoom(roomId);
887
1652
  if (!removed) {
888
1653
  throw new errors_1.OperationFailedError('Failed to delete room');
889
1654
  }
890
1655
  }
1656
+ /**
1657
+ * Creates a publicly accessible clone of a template room.
1658
+ *
1659
+ * The instance is a full copy of the template including all agents.
1660
+ * Use {@link resetPublishedRoomInstance} to restore it to the template's state.
1661
+ *
1662
+ * @param templateId - ID of the template room to clone
1663
+ * @param publishedName - Display name for the instance (defaults to the template's name)
1664
+ * @param userId - The owning user's ID (used for public access mapping)
1665
+ * @returns The new instance's room ID
1666
+ * @throws {NotFoundError} If the template room does not exist
1667
+ */
891
1668
  async publishRoom(templateId, publishedName, userId) {
892
1669
  const template = await this.roomStore.getRoom(templateId);
893
1670
  if (!template) {
@@ -897,6 +1674,14 @@ class AppService {
897
1674
  this.publishedRoomsService.addPublishedRoom(instanceId, userId);
898
1675
  return instanceId;
899
1676
  }
1677
+ /**
1678
+ * Summarizes a room for a listing.
1679
+ *
1680
+ * The cost is summed from the room's agents rather than held on the room —
1681
+ * the same sum {@link getRoomMessages} reports, so the two never disagree.
1682
+ * @param room - The room to summarize
1683
+ * @returns The room's summary
1684
+ */
900
1685
  static toRoomInfo(room) {
901
1686
  return {
902
1687
  id: room.getId(),
@@ -904,20 +1689,44 @@ class AppService {
904
1689
  goal: room.getGoal(),
905
1690
  agentCount: room.getAgentCount(),
906
1691
  pack: room.getPack(),
907
- totalCost: room
908
- .getAgents()
909
- .map((agent) => agent.totalCost || 0)
910
- .reduce((total, cost) => total + cost, 0),
1692
+ totalCost: room.totalCost(),
911
1693
  };
912
1694
  }
1695
+ /**
1696
+ * Returns all published instances created from a template room.
1697
+ *
1698
+ * @param templateId - ID of the template room
1699
+ * @returns Array of room summary objects for each published instance
1700
+ * @see {@link publishRoom}
1701
+ */
913
1702
  async getPublishedRoomInstances(templateId) {
914
1703
  const instances = await this.roomStore.getPublishedInstances(templateId);
915
1704
  return instances.map(AppService.toRoomInfo);
916
1705
  }
1706
+ /**
1707
+ * Lists every published room instance this user owns.
1708
+ *
1709
+ * The room counterpart to {@link listPublishedAgents}, and the only view of
1710
+ * them that is not filtered by which template they came from — a published
1711
+ * room is a live public link, and the point of the list is seeing all of them
1712
+ * and what they have cost.
1713
+ *
1714
+ * @returns Array of room summary objects, one per published instance
1715
+ */
917
1716
  async listPublishedRooms() {
918
1717
  const instances = await this.roomStore.getAllPublishedInstances();
919
1718
  return instances.map(AppService.toRoomInfo);
920
1719
  }
1720
+ /**
1721
+ * Resets a published room instance to a clean state.
1722
+ *
1723
+ * Clears the instance's messages and artifacts, and resets all of its
1724
+ * cloned agents to their template state. Does not affect the template room.
1725
+ *
1726
+ * @param instanceId - ID of the published room instance to reset
1727
+ * @throws {NotFoundError} If the instance does not exist
1728
+ * @throws {OperationFailedError} If the room is not a published instance
1729
+ */
921
1730
  async resetPublishedRoomInstance(instanceId) {
922
1731
  const instance = await this.roomStore.getRoom(instanceId);
923
1732
  if (!instance) {
@@ -927,10 +1736,19 @@ class AppService {
927
1736
  if (!templateId) {
928
1737
  throw new errors_1.OperationFailedError('Not a published instance');
929
1738
  }
1739
+ // Clear messages and artifacts
930
1740
  this.roomStore.clearRoomMessages(instanceId);
931
1741
  const storageDir = this.roomStore.getDefaultStorageDir();
1742
+ // Deleted through the store, which works off the directory rather than
1743
+ // rebuilding each filename from the artifact's name. Rebuilding was wrong:
1744
+ // an artifact is written under a *sanitized* name, so "Sheet: Kerith" lives
1745
+ // in "Sheet_ Kerith.artifact" and the reconstructed path matched nothing.
1746
+ // The file survived while setArtifacts([]) dropped it from memory, so every
1747
+ // character sheet quietly came back the next time the room loaded — a reset
1748
+ // that reset everything except the thing the players had accumulated.
932
1749
  this.roomStore.deleteAllArtifactFiles(instanceId, storageDir);
933
1750
  instance.setArtifacts([]);
1751
+ // Reset all cloned agents
934
1752
  const instanceAgents = instance.getAgents();
935
1753
  for (const agent of instanceAgents) {
936
1754
  if (agent.templateAgentId) {
@@ -939,39 +1757,92 @@ class AppService {
939
1757
  }
940
1758
  instance.saveMetadata();
941
1759
  }
1760
+ /**
1761
+ * Returns the user's stored preferences object.
1762
+ *
1763
+ * Preferences are application-defined - Briyah stores and returns them as-is.
1764
+ * Returns `{}` if no preferences have been saved yet.
1765
+ *
1766
+ * @returns The preferences object previously written by {@link saveUserPreferences},
1767
+ * or an empty object if none exist
1768
+ */
942
1769
  getUserPreferences() {
1770
+ // Check if the file exists
943
1771
  if (!this.userPaths.exists(this.userPreferencesFile)) {
1772
+ // Return empty preferences if file doesn't exist
944
1773
  return {};
945
1774
  }
1775
+ // Read and parse the preferences file
946
1776
  const preferencesData = this.userPaths.load(this.userPreferencesFile);
947
1777
  return preferencesData ? JSON.parse(preferencesData) : {};
948
1778
  }
1779
+ /**
1780
+ * Persists the user's preferences object to disk.
1781
+ *
1782
+ * The shape of `preferences` is application-defined. Pass any serializable object;
1783
+ * it will be stored as JSON and returned verbatim by {@link getUserPreferences}.
1784
+ *
1785
+ * @param preferences - Serializable preferences object to store
1786
+ */
949
1787
  saveUserPreferences(preferences) {
1788
+ // Write the preferences to the file
950
1789
  this.userPaths.store(this.userPreferencesFile, JSON.stringify(preferences, null, 2));
951
1790
  }
1791
+ /**
1792
+ * Returns the names of all prompt files in a folder, merged from both the common
1793
+ * and user prompt directories.
1794
+ *
1795
+ * Pass `'shared'` as `folderName` to list files in the root prompts directory.
1796
+ * Files that exist in both directories appear once in the result.
1797
+ *
1798
+ * @param folderName - Folder to list, or `'shared'` for the root prompts directory
1799
+ * @returns Object with a `files` array of base names (no extension), sorted alphabetically
1800
+ */
952
1801
  listPromptFiles(folderName) {
953
1802
  const baseNames = new Set();
1803
+ // Helper function to scan a directory and add files
954
1804
  const scanDirectory = (baseDir) => {
955
1805
  let targetDir = baseDir;
1806
+ // If not 'shared', look in the specific folder
956
1807
  if (folderName !== 'shared') {
957
1808
  targetDir = path.join(baseDir, folderName);
958
1809
  }
1810
+ // Check if directory exists
959
1811
  if (!fs.existsSync(targetDir)) {
960
1812
  return;
961
1813
  }
1814
+ // Get all files in the directory
962
1815
  const allFiles = fs.readdirSync(targetDir);
1816
+ // Filter to only .prompt and .json files
963
1817
  const promptFiles = allFiles.filter((file) => file.endsWith('.prompt') || file.endsWith('.json'));
1818
+ // Extract base names without extensions
964
1819
  promptFiles.forEach((file) => {
965
1820
  const baseName = file.replace(/\.(prompt|json)$/, '');
966
1821
  baseNames.add(baseName);
967
1822
  });
968
1823
  };
1824
+ // Scan common prompts directory first
969
1825
  scanDirectory(this.userPaths.getCommonPromptsDir());
1826
+ // Scan user prompts directory (will add or override common files)
970
1827
  scanDirectory(this.userPaths.getUserPromptsDir());
971
1828
  return { files: Array.from(baseNames).sort() };
972
1829
  }
1830
+ /**
1831
+ * Returns prompt file names in a folder annotated with their origin scope.
1832
+ *
1833
+ * When the same file name exists in both the common and user directories,
1834
+ * the user copy wins and the entry is reported as `scope: 'user'`.
1835
+ * Pass `'shared'` as `folderName` to list files in the root prompts directory.
1836
+ *
1837
+ * @param folderName - Folder to list, or `'shared'` for the root prompts directory
1838
+ * @returns Object with a `files` array of `{ name, scope }` entries, sorted alphabetically
1839
+ */
973
1840
  listPromptFilesWithScope(folderName) {
974
1841
  const fileMap = new Map();
1842
+ // Lowest precedence first, so a higher tier's copy of the same file name
1843
+ // overwrites the entry and the reported scope is the one that would actually
1844
+ // be read. This is the same directory list the resolver searches, which is
1845
+ // why a pack folder's files appear here at all.
975
1846
  for (const { dir, scope, pack } of (0, prompt_resolver_1.promptFolderDirsLowestFirst)(this.userPaths, folderName, { enabledPacks: this.enabledPacks })) {
976
1847
  if (!fs.existsSync(dir))
977
1848
  continue;
@@ -984,7 +1855,26 @@ class AppService {
984
1855
  const files = [...fileMap.values()].sort((a, b) => a.name.localeCompare(b.name));
985
1856
  return { files };
986
1857
  }
1858
+ /**
1859
+ * Reads a prompt file, applying the shared lookup order (`prompt-resolver.ts`).
1860
+ *
1861
+ * For a bare folder that is the historical four levels — `user/{folder}`,
1862
+ * `user/root`, `common/{folder}`, `common/root` — plus the folders of any pack
1863
+ * this user has enabled. For a pack-qualified folder (`dnd5e:battle_master`) it
1864
+ * is the pack's own tiers, then the shared roots.
1865
+ *
1866
+ * The returned `scope` collapses the four tiers onto the two the client knows:
1867
+ * a pack overlay reports `'user'`, a pack's own file reports `'common'`. `pack`
1868
+ * and `tier` carry the detail, and are populated even when the reference was
1869
+ * bare. Returns `{ content: '' }` if the file does not exist in any location.
1870
+ *
1871
+ * @param folderName - Prompt folder name, `'shared'` for the root prompts directory,
1872
+ * or a pack-qualified name like `dnd5e:dungeon_master`
1873
+ * @param fileName - Base name of the prompt file (with or without `.prompt`/`.json` extension)
1874
+ * @returns `{ content, scope, pack, tier }` where all but `content` are omitted when not found
1875
+ */
987
1876
  getPromptFile(folderName, fileName) {
1877
+ // Determine file extension (.prompt or .json)
988
1878
  const fileExtension = fileName.endsWith('.prompt') || fileName.endsWith('.json') ? '' : '.prompt';
989
1879
  const found = (0, prompt_resolver_1.resolvePromptFile)(this.userPaths, folderName, fileName, fileExtension, {
990
1880
  enabledPacks: this.enabledPacks,
@@ -999,6 +1889,24 @@ class AppService {
999
1889
  ...(found.pack && { pack: found.pack }),
1000
1890
  };
1001
1891
  }
1892
+ /**
1893
+ * Reads a prompt folder's `defaults_config.json` — the agent settings the create-agent
1894
+ * form pre-fills when that folder is chosen.
1895
+ *
1896
+ * Resolved through the same 4-level fallback as any other prompt file, so a user copy
1897
+ * overrides the shipped one and a file at the prompts root supplies defaults for every
1898
+ * folder that has none of its own.
1899
+ *
1900
+ * A missing file and an unparseable one both return `{ defaults: {} }`: defaults are a
1901
+ * convenience, and a folder must stay usable when its config is broken. Unparseable is
1902
+ * logged; missing is not, since most folders have no config at all.
1903
+ *
1904
+ * Every field is coerced to its declared type and unknown keys are dropped, so a typo
1905
+ * in a hand-edited file cannot ride through to the create-agent request.
1906
+ *
1907
+ * @param folderName - Prompt folder name, or `'shared'` for the root prompts directory
1908
+ * @returns The declared defaults, and the scope the file was read from
1909
+ */
1002
1910
  getPromptFolderDefaults(folderName) {
1003
1911
  const exists = this.promptFolderExists(folderName);
1004
1912
  const file = this.getPromptFile(folderName, 'defaults_config.json');
@@ -1064,9 +1972,27 @@ class AppService {
1064
1972
  }
1065
1973
  return { defaults, scope: file.scope, exists };
1066
1974
  }
1975
+ /**
1976
+ * Whether a prompt folder reference reaches a folder that exists.
1977
+ *
1978
+ * The check every "build an agent from a folder" path makes before it builds
1979
+ * one: a reference that reaches nothing does not fail, it falls back to the
1980
+ * shared root prompts and produces a generic conversational agent. A bare name
1981
+ * for a pack this user has not enabled counts as not existing, because that is
1982
+ * how it will behave.
1983
+ *
1984
+ * @param folderName - Prompt folder name, bare or `pack:folder`
1985
+ * @returns True when the folder exists, or names the prompts root
1986
+ */
1067
1987
  promptFolderExists(folderName) {
1068
1988
  return (0, prompt_resolver_1.promptFolderExists)(this.userPaths, folderName, { enabledPacks: this.enabledPacks });
1069
1989
  }
1990
+ /**
1991
+ * Refuses a prompt folder that reaches nothing, naming the likely cause.
1992
+ *
1993
+ * @param folderName - The folder the caller asked for
1994
+ * @throws {NotFoundError} If no tier has the folder
1995
+ */
1070
1996
  requirePromptFolder(folderName) {
1071
1997
  if (this.promptFolderExists(folderName))
1072
1998
  return;
@@ -1076,22 +2002,54 @@ class AppService {
1076
2002
  : `A pack's folder must be named "<pack>:${folderName}", or the pack enabled for this user${enabled.length ? ` (enabled: ${enabled.join(', ')})` : ' (this user has none enabled)'}.`;
1077
2003
  throw new errors_1.NotFoundError(`No prompt folder "${folderName}". ${hint}`);
1078
2004
  }
2005
+ /**
2006
+ * Writes content to a prompt file in the user prompt directory.
2007
+ *
2008
+ * Always saves to the user directory - common prompt files are never overwritten.
2009
+ * If the target folder does not exist it is created automatically.
2010
+ * Passing `'shared'` as `folderName` writes to the root user prompts directory.
2011
+ *
2012
+ * Special case: passing an empty `content` for a `'json'` file deletes the file
2013
+ * rather than writing an empty document.
2014
+ *
2015
+ * @param folderName - Prompt folder name, or `'shared'` for the root user prompts directory
2016
+ * @param fileName - Base name of the file (without extension)
2017
+ * @param content - File content to write
2018
+ * @param fileType - `'prompt'` (writes a `.prompt` file) or `'json'` (writes a `.json` file)
2019
+ */
1079
2020
  savePromptFile(folderName, fileName, content, fileType) {
2021
+ // Never the directory the file was read from: a write goes to the user's own
2022
+ // tier, and for a pack-qualified folder that is a private overlay of the pack.
2023
+ // promptWriteDir also validates the name, which is the only thing standing
2024
+ // between a route parameter and path.join.
1080
2025
  const targetDir = (0, prompt_resolver_1.promptWriteDir)(this.userPaths, folderName);
1081
2026
  (0, prompt_resolver_1.assertPathSafe)(fileName);
2027
+ // Create directory if it doesn't exist
1082
2028
  if (!fs.existsSync(targetDir)) {
1083
2029
  fs.mkdirSync(targetDir, { recursive: true });
1084
2030
  }
2031
+ // Determine file extension
1085
2032
  const fileExtension = fileType === 'json' ? '.json' : '.prompt';
1086
2033
  const filePath = path.join(targetDir, fileName + fileExtension);
2034
+ // If content is empty and it's a JSON file, delete the file if it exists
1087
2035
  if (content.trim() === '' && fileType === 'json') {
1088
2036
  if (fs.existsSync(filePath)) {
1089
2037
  fs.unlinkSync(filePath);
1090
2038
  }
1091
2039
  return;
1092
2040
  }
2041
+ // Write content to file
1093
2042
  fs.writeFileSync(filePath, content);
1094
2043
  }
2044
+ /**
2045
+ * Deletes a prompt file from the user prompts directory.
2046
+ *
2047
+ * Removes both the `.prompt` and `.json` variants if they exist.
2048
+ * This is a no-op if neither file is present.
2049
+ *
2050
+ * @param folderName - Prompt folder name, or `'shared'` for the root prompts directory
2051
+ * @param fileName - Base name of the file to delete (without extension)
2052
+ */
1095
2053
  deletePromptFile(folderName, fileName) {
1096
2054
  const targetDir = (0, prompt_resolver_1.promptWriteDir)(this.userPaths, folderName);
1097
2055
  (0, prompt_resolver_1.assertPathSafe)(fileName);
@@ -1109,14 +2067,40 @@ class AppService {
1109
2067
  }
1110
2068
  }
1111
2069
  }
2070
+ /**
2071
+ * Returns all artifacts published in a room.
2072
+ *
2073
+ * Artifacts are collaborative documents created by agents via the `'publish'` action.
2074
+ *
2075
+ * @param roomId - The room's ID
2076
+ * @returns Object with an `artifacts` array. Returns `{ artifacts: [] }` if the room is not found.
2077
+ * @see {@link publishArtifact}
2078
+ */
1112
2079
  async getRoomArtifacts(roomId) {
2080
+ // Check if the room exists
1113
2081
  const room = await this.roomStore.getRoom(roomId);
1114
2082
  if (!room) {
1115
2083
  return { artifacts: [] };
1116
2084
  }
2085
+ // Get all artifacts from the room
1117
2086
  const artifacts = room.getArtifacts();
2087
+ // Return the artifacts
1118
2088
  return { artifacts };
1119
2089
  }
2090
+ /**
2091
+ * Programmatically publishes an artifact to a room.
2092
+ *
2093
+ * This is the imperative equivalent of an agent sending a `'publish'` action message.
2094
+ * Agents in the room can read and reference the artifact in subsequent prompts.
2095
+ *
2096
+ * @param roomId - The room's ID
2097
+ * @param name - Artifact name (unique within the room)
2098
+ * @param creator - Display name of the creator
2099
+ * @param body - The artifact's text content
2100
+ * @param viewers - Agent names that can view this artifact (empty array = all agents)
2101
+ * @throws {NotFoundError} If the room does not exist
2102
+ * @throws {OperationFailedError} If `name` is empty
2103
+ */
1120
2104
  async publishArtifact(roomId, name, creator, body, viewers = []) {
1121
2105
  const room = await this.roomStore.getRoom(roomId);
1122
2106
  if (!room)
@@ -1125,30 +2109,80 @@ class AppService {
1125
2109
  throw new errors_1.OperationFailedError('Artifact name is required');
1126
2110
  room.publishArtifact(name, creator, body, viewers);
1127
2111
  }
2112
+ /**
2113
+ * Creates a new prompt folder in the user prompts directory.
2114
+ *
2115
+ * An empty `system_instruction.prompt` file is created inside the folder so that
2116
+ * it is immediately usable as a prompt source for agents.
2117
+ *
2118
+ * @param folderName - Name of the folder to create
2119
+ * @throws {OperationFailedError} If a folder with that name already exists
2120
+ */
1128
2121
  createPromptFolder(folderName) {
1129
2122
  const targetDir = (0, prompt_resolver_1.promptWriteDir)(this.userPaths, folderName);
2123
+ // Check if folder already exists
1130
2124
  if (fs.existsSync(targetDir)) {
1131
2125
  throw new errors_1.OperationFailedError(`Folder ${folderName} already exists`);
1132
2126
  }
2127
+ // Create the folder
1133
2128
  fs.mkdirSync(targetDir, { recursive: true });
2129
+ // Create empty system_instruction.prompt file
1134
2130
  const systemInstructionPath = path.join(targetDir, 'system_instruction.prompt');
1135
2131
  fs.writeFileSync(systemInstructionPath, '');
1136
2132
  }
2133
+ /**
2134
+ * Deletes a prompt folder and all its contents from the user prompts directory.
2135
+ *
2136
+ * Only user-owned folders can be deleted; common folders are not affected.
2137
+ *
2138
+ * @param folderName - Name of the folder to delete
2139
+ * @throws {OperationFailedError} If `folderName` is `'shared'`
2140
+ * @throws {NotFoundError} If the folder does not exist in the user prompts directory
2141
+ */
1137
2142
  deletePromptFolder(folderName) {
2143
+ // Prevent deletion of the 'shared' folder
1138
2144
  if (folderName === 'shared') {
1139
2145
  throw new errors_1.OperationFailedError('Cannot delete the shared folder');
1140
2146
  }
2147
+ // Only ever the user's own copy. For a pack-qualified folder that is their
2148
+ // overlay, so deleting reverts their edits rather than removing the pack's.
1141
2149
  const targetDir = (0, prompt_resolver_1.promptWriteDir)(this.userPaths, folderName);
2150
+ // Check if folder exists
1142
2151
  if (!fs.existsSync(targetDir)) {
1143
2152
  throw new errors_1.NotFoundError(`Folder ${folderName} does not exist`);
1144
2153
  }
2154
+ // Delete the folder recursively
1145
2155
  fs.rmSync(targetDir, { recursive: true, force: true });
1146
2156
  }
2157
+ /**
2158
+ * Updates one or more properties of an existing agent and persists the changes.
2159
+ *
2160
+ * Only fields that are present in the `updates` object are changed;
2161
+ * omitted fields are left as-is.
2162
+ *
2163
+ * @param agentId - The agent's ID
2164
+ * @param updates - Fields to update:
2165
+ * - `agentNickname` - short display name
2166
+ * - `description` - role or personality description
2167
+ * - `modelName` - model identifier (e.g. `'claude-haiku-4-5'`)
2168
+ * - `reasoningEffort` - `'low' | 'medium' | 'high' | null`
2169
+ * - `isControlledByHuman` - whether a human drives this agent's responses
2170
+ * - `maxOutputTokens` - override the model's default output token limit
2171
+ * - `allowSearch` - enable web search capability (provider must support it)
2172
+ * - `beginInstruction` - prompt sent when the host app triggers a "Begin" action
2173
+ * @throws {NotFoundError} If no agent with the given ID exists
2174
+ */
1147
2175
  async updateAgent(agentId, updates) {
1148
2176
  const agent = await this.agentStore.getAgent(agentId);
1149
2177
  if (!agent) {
1150
2178
  throw new errors_1.NotFoundError('Agent not found');
1151
2179
  }
2180
+ // Turning moderated messaging on needs a moderator in the agent's room,
2181
+ // checked before anything is written. Only the transition is checked: an
2182
+ // agent that already has the flag must stay editable even if its room has
2183
+ // since lost its moderator, or the flag becomes impossible to turn back off.
2184
+ // Room-owned agents are the ones reachable from here; an agent that joined a
2185
+ // room some other way is covered by the checks in createRoom and editRoom.
1152
2186
  if (updates.useModerator === true && !agent.useModerator && agent.ownerRoomId) {
1153
2187
  const room = await this.roomStore.getRoom(agent.ownerRoomId);
1154
2188
  const reason = room ? this.describeMissingModerator(room, room.getAgents()) : null;
@@ -1157,6 +2191,7 @@ class AppService {
1157
2191
  `"${room.getName()}" needs one. ${reason}`);
1158
2192
  }
1159
2193
  }
2194
+ // Update only provided fields
1160
2195
  if (updates.agentNickname !== undefined) {
1161
2196
  await this.renameAgentEverywhere(agent, updates.agentNickname);
1162
2197
  }
@@ -1185,12 +2220,31 @@ class AppService {
1185
2220
  agent.privateContext = updates.privateContext;
1186
2221
  if (updates.promptCacheTTL !== undefined)
1187
2222
  agent.promptCacheTTL = updates.promptCacheTTL;
2223
+ // 0 and '' mean "no limit" and "no override", so they clear rather than set.
1188
2224
  if (updates.maxHistoryMessages !== undefined)
1189
2225
  agent.maxHistoryMessages = updates.maxHistoryMessages || undefined;
1190
2226
  if (updates.smallModelName !== undefined)
1191
2227
  agent.smallModelName = updates.smallModelName || undefined;
1192
- agent.save();
1193
- }
2228
+ agent.save(); // Persists all changes and triggers SSE updates
2229
+ }
2230
+ /**
2231
+ * Renames an agent, and repoints every room that named it.
2232
+ *
2233
+ * The manual counterpart to `ToolRoomAccess.renameAgent`. That one is
2234
+ * synchronous by contract and so fixes only the room it runs in, which is
2235
+ * complete for a room-owned agent; this path reaches an agent shared across
2236
+ * several rooms, where a rename would otherwise leave the other rooms pointing
2237
+ * at a nickname nobody answers to — including their leader, and the `viewers`
2238
+ * of every artifact the agent could read.
2239
+ *
2240
+ * Every room is checked before any is changed. A rename applied to two rooms
2241
+ * and refused by a third would leave the agent named one thing and half its
2242
+ * rooms naming another, which is worse than not renaming at all.
2243
+ *
2244
+ * @param agent The agent to rename
2245
+ * @param newName The new name; the routing nickname is its first word
2246
+ * @throws {ValidationError} If any room it sits in already has that name
2247
+ */
1194
2248
  async renameAgentEverywhere(agent, newName) {
1195
2249
  const previous = agent.agentNickname;
1196
2250
  const trimmed = (newName || '').trim();
@@ -1212,19 +2266,68 @@ class AppService {
1212
2266
  room.repointNickname(previous, trimmed);
1213
2267
  }
1214
2268
  }
2269
+ /**
2270
+ * Whether this deployment permits users to author and run their own tools.
2271
+ * Native (host-registered) tools are always available regardless.
2272
+ */
1215
2273
  get userAuthoredToolsEnabled() {
1216
2274
  return this.toolExecution.userAuthoredToolsEnabled;
1217
2275
  }
2276
+ /**
2277
+ * Lists user-authored tools (with code). Empty when authoring is disabled.
2278
+ *
2279
+ * @returns Array of user-authored tool definitions
2280
+ */
1218
2281
  async listTools() {
1219
2282
  if (!this.userAuthoredToolsEnabled)
1220
2283
  return [];
1221
2284
  return this.toolStore.listTools();
1222
2285
  }
2286
+ /**
2287
+ * Lists native (host-registered) tools as code-free summaries. These are
2288
+ * grantable to agents but not editable through the API.
2289
+ *
2290
+ * @returns Array of native tool summaries
2291
+ */
2292
+ /**
2293
+ * Keeps grants the client could not have seen when it built its list.
2294
+ *
2295
+ * The edit form sends the whole grant list, and it filters that list against the
2296
+ * tools it was offered. Those are only the tools of the packs this user has
2297
+ * enabled — so opening an agent whose pack is off and pressing Save would send a
2298
+ * list with every one of its grants missing, and the agent would lose them for
2299
+ * good with nothing said.
2300
+ *
2301
+ * The server cannot tell "the user removed it" from "the client never saw it" by
2302
+ * looking at the list, so it looks at the tool instead: a name the user could not
2303
+ * have been offered is kept, and a name they could have been offered is theirs to
2304
+ * remove. A grant for a tool nothing registers at all is also kept, since the
2305
+ * form drops those from its list too.
2306
+ *
2307
+ * @param current The agent's grants before the update
2308
+ * @param requested The grants the client sent
2309
+ * @returns The grants to store
2310
+ */
1223
2311
  preserveHiddenGrants(current, requested) {
1224
2312
  const offered = new Set(this.listNativeToolSummaries().map((tool) => tool.name));
1225
2313
  const kept = current.filter((name) => !offered.has(name) && !requested.includes(name));
1226
2314
  return kept.length > 0 ? [...requested, ...kept] : requested;
1227
2315
  }
2316
+ /**
2317
+ * Native tools this user may grant.
2318
+ *
2319
+ * Filtered to the packs they have enabled. Two kinds are always listed: a tool
2320
+ * with no `group`, registered by the host directly rather than by a pack, and a
2321
+ * **core** tool, which belongs to the engine rather than to a domain and so has
2322
+ * no pack to enable. Filtering core out would hide `rename_agent` from every
2323
+ * user permanently, since `core` never appears in anyone's enabled list.
2324
+ *
2325
+ * Listing only. {@link ToolExecutionService} and `Room.buildAvailableTools`
2326
+ * deliberately do not filter, so disabling a pack hides its tools from the
2327
+ * pickers without stopping an agent that already holds one from calling it.
2328
+ *
2329
+ * @returns Code-free summaries of the grantable native tools
2330
+ */
1228
2331
  listNativeToolSummaries() {
1229
2332
  const enabled = new Set(this.enabledPacks());
1230
2333
  return this.toolExecution
@@ -1237,6 +2340,13 @@ class AppService {
1237
2340
  group: t.group,
1238
2341
  }));
1239
2342
  }
2343
+ /**
2344
+ * Creates a new user-authored tool.
2345
+ *
2346
+ * @param tool - The tool definition to create
2347
+ * @returns The created tool definition
2348
+ * @throws {OperationFailedError} If authoring is disabled or the name already exists
2349
+ */
1240
2350
  async createTool(tool) {
1241
2351
  this.assertUserAuthoringAllowed();
1242
2352
  const existing = await this.toolStore.getTool(tool.name);
@@ -1245,6 +2355,15 @@ class AppService {
1245
2355
  }
1246
2356
  return this.toolStore.saveTool(tool);
1247
2357
  }
2358
+ /**
2359
+ * Updates an existing user-authored tool.
2360
+ *
2361
+ * @param name - The tool's name
2362
+ * @param tool - The updated tool definition
2363
+ * @returns The saved tool definition
2364
+ * @throws {NotFoundError} If the tool does not exist
2365
+ * @throws {OperationFailedError} If authoring is disabled
2366
+ */
1248
2367
  async updateTool(name, tool) {
1249
2368
  this.assertUserAuthoringAllowed();
1250
2369
  const existing = await this.toolStore.getTool(name);
@@ -1253,6 +2372,14 @@ class AppService {
1253
2372
  }
1254
2373
  return this.toolStore.saveTool({ ...tool, name });
1255
2374
  }
2375
+ /**
2376
+ * Deletes a user-authored tool. Agents granted the tool keep the (now dangling)
2377
+ * grant; the room silently drops missing tools from their prompts.
2378
+ *
2379
+ * @param name - The tool's name
2380
+ * @throws {NotFoundError} If the tool does not exist
2381
+ * @throws {OperationFailedError} If authoring is disabled
2382
+ */
1256
2383
  async deleteTool(name) {
1257
2384
  this.assertUserAuthoringAllowed();
1258
2385
  const deleted = await this.toolStore.deleteTool(name);
@@ -1265,30 +2392,70 @@ class AppService {
1265
2392
  throw new errors_1.OperationFailedError('User-authored tools are disabled on this deployment');
1266
2393
  }
1267
2394
  }
2395
+ /**
2396
+ * Runs a tool with the given arguments for testing from the Tools page.
2397
+ * Failures are returned in-band as `{ ok: false, error }`.
2398
+ *
2399
+ * @param name - The tool's name
2400
+ * @param args - Named arguments for the tool
2401
+ * @returns The tool run result
2402
+ */
1268
2403
  async testTool(name, args) {
1269
2404
  return this.toolExecution.test(name, args);
1270
2405
  }
2406
+ /**
2407
+ * Lists the files currently attached to an agent.
2408
+ *
2409
+ * @param agentId - The agent's ID
2410
+ * @returns Object with a `files` array of file names. Returns `{ files: [] }` if the agent is not found.
2411
+ */
1271
2412
  async listAttachedFiles(agentId) {
2413
+ // Check if the agent exists
1272
2414
  const agent = await this.agentStore.getAgent(agentId);
1273
2415
  if (!agent) {
1274
2416
  return { files: [] };
1275
2417
  }
2418
+ // Get the list of files from the AttachedFileService
1276
2419
  const files = this.attachedFileService.listFiles(agentId);
1277
2420
  return { files };
1278
2421
  }
2422
+ /**
2423
+ * Removes a file from an agent by its file name.
2424
+ *
2425
+ * Deletes the file from storage and updates the agent's metadata.
2426
+ * Use {@link deleteAttachedFileById} if you have the document ID instead.
2427
+ *
2428
+ * @param agentId - The agent's ID
2429
+ * @param fileName - Name of the file to remove (e.g. `'report.pdf'`)
2430
+ * @throws {NotFoundError} If the agent or file is not found
2431
+ */
1279
2432
  async deleteAttachedFile(agentId, fileName) {
2433
+ // Check if the agent exists
1280
2434
  const agent = await this.agentStore.getAgent(agentId);
1281
2435
  if (!agent) {
1282
2436
  throw new errors_1.NotFoundError('Agent not found');
1283
2437
  }
2438
+ // Delete the file
1284
2439
  const deleted = this.attachedFileService.deleteFileByName(agentId, fileName);
1285
2440
  if (!deleted) {
1286
2441
  throw new errors_1.NotFoundError(`File ${fileName} not found`);
1287
2442
  }
2443
+ // Update the agent's attachedFiles array
1288
2444
  agent.attachedFiles = agent.attachedFiles.filter((file) => file.fileName !== fileName);
1289
2445
  agent.save();
1290
2446
  }
2447
+ /**
2448
+ * Removes an attached file by its document ID (as returned by {@link attachDocument}).
2449
+ *
2450
+ * Searches all agents to locate the owner, removes the file from storage,
2451
+ * and updates the agent's metadata.
2452
+ *
2453
+ * @param documentId - The `documentId` returned by {@link attachDocument}
2454
+ * @throws {NotFoundError} If no file with the given ID exists
2455
+ * @throws {OperationFailedError} If deletion fails
2456
+ */
1291
2457
  async deleteAttachedFileById(documentId) {
2458
+ // Find the agent that owns this file
1292
2459
  const allAgentIds = await this.agentStore.getAllAgentIds();
1293
2460
  let ownerAgent = null;
1294
2461
  let fileMetadata = null;
@@ -1306,20 +2473,36 @@ class AppService {
1306
2473
  if (!ownerAgent || !fileMetadata) {
1307
2474
  throw new errors_1.NotFoundError('File not found');
1308
2475
  }
2476
+ // Delete the file using the attachedFileService
1309
2477
  const deleted = this.attachedFileService.deleteFile(ownerAgent.id, documentId);
1310
2478
  if (!deleted) {
1311
2479
  throw new errors_1.OperationFailedError('Failed to delete file');
1312
2480
  }
2481
+ // Update the agent's attachedFiles array
1313
2482
  ownerAgent.attachedFiles = ownerAgent.attachedFiles.filter((file) => file.fileId !== documentId);
1314
2483
  ownerAgent.save();
1315
2484
  }
2485
+ /**
2486
+ * Clears an agent's conversation history while preserving its configuration
2487
+ * and re-attaching any previously uploaded files.
2488
+ *
2489
+ * Useful for starting a fresh conversation without recreating the agent.
2490
+ * If the history begins with a summary block (from a prior compaction), only
2491
+ * messages after the summary are cleared.
2492
+ *
2493
+ * @param agentId - The agent's ID
2494
+ * @throws {NotFoundError} If no agent with the given ID exists
2495
+ */
1316
2496
  async reloadAgent(agentId) {
2497
+ // Check if the agent exists
1317
2498
  const agent = await this.agentStore.getAgent(agentId);
1318
2499
  if (!agent) {
1319
2500
  throw new errors_1.NotFoundError('Agent not found');
1320
2501
  }
2502
+ // Get the agent's service
1321
2503
  const serviceName = agent.serviceName;
1322
2504
  const aiService = this.getAiServiceFromServiceName(serviceName);
2505
+ // Create a new history array
1323
2506
  if (agent.history &&
1324
2507
  agent.history.length > 0 &&
1325
2508
  agent.history[0].content &&
@@ -1327,6 +2510,7 @@ class AppService {
1327
2510
  agent.history.splice(1);
1328
2511
  else
1329
2512
  agent.history = [];
2513
+ // Re-attach all files
1330
2514
  const fileMetadataList = agent.attachedFiles;
1331
2515
  for (const metadata of fileMetadataList) {
1332
2516
  const fileData = this.attachedFileService.getFile(agent.id, metadata.fileId);
@@ -1336,6 +2520,13 @@ class AppService {
1336
2520
  }
1337
2521
  agent.save();
1338
2522
  }
2523
+ /**
2524
+ * Compacts an agent's conversation history into a single summary message.
2525
+ * Uses the `compact_agent` prompt (role folder first, common-root as fallback).
2526
+ *
2527
+ * @param agentId - The agent's ID
2528
+ * @throws {NotFoundError} If no agent with the given ID exists
2529
+ */
1339
2530
  async compactAgentConversation(agentId) {
1340
2531
  const agent = await this.agentStore.getAgent(agentId);
1341
2532
  if (!agent) {
@@ -1343,54 +2534,85 @@ class AppService {
1343
2534
  }
1344
2535
  await agent.compact();
1345
2536
  }
2537
+ /**
2538
+ * Clears a room's message history and artifacts, and resets all member agents.
2539
+ *
2540
+ * Agent configurations (model, prompt, files) are preserved; only conversation
2541
+ * history and artifacts are removed.
2542
+ *
2543
+ * @param roomId - The room's ID
2544
+ * @throws {NotFoundError} If the room does not exist
2545
+ */
1346
2546
  async resetRoom(roomId) {
2547
+ // Get the room
1347
2548
  const room = await this.roomStore.getRoom(roomId);
1348
2549
  if (!room) {
1349
2550
  throw new errors_1.NotFoundError('Room not found');
1350
2551
  }
1351
2552
  const roomName = room.getName();
1352
2553
  const storageDir = room.getStorageDir() || this.roomStore.getDefaultStorageDir();
2554
+ // Clear room messages (both in-memory and on disk)
1353
2555
  this.roomStore.clearRoomMessages(roomId, storageDir);
2556
+ // Clear all artifacts (delete files and clear in-memory)
1354
2557
  this.roomStore.deleteAllArtifactFiles(roomId, storageDir);
1355
2558
  room.setArtifacts([]);
2559
+ // Reset each agent using the existing reloadAgent logic
1356
2560
  const warnings = [];
1357
2561
  for (const agent of room.getAgents()) {
1358
2562
  try {
2563
+ // Use existing reloadAgent functionality to clear history and re-attach files
1359
2564
  this.reloadAgent(agent.id);
1360
2565
  }
1361
2566
  catch (agentError) {
1362
2567
  warnings.push(`Failed to reset agent ${agent.agentName}: ${agentError.message}`);
1363
2568
  }
1364
2569
  }
2570
+ // Log warnings if any
1365
2571
  if (warnings.length > 0) {
1366
2572
  logger_1.logger.warn(`Room "${roomName}" reset with warnings:`, warnings);
1367
2573
  }
1368
2574
  }
2575
+ /**
2576
+ * Resets a story to the beginning while preserving artifacts and the opening scene.
2577
+ *
2578
+ * If a chapter 1 backup exists, agents are restored from it; otherwise their
2579
+ * conversation histories are cleared. The list of declined characters is also cleared.
2580
+ *
2581
+ * @param storyId - The story's ID
2582
+ * @throws {NotFoundError} If the story or its room does not exist
2583
+ */
1369
2584
  async resetStory(storyId) {
2585
+ // Get the story metadata
1370
2586
  const story = this.storyStore.getStory(storyId);
1371
2587
  if (!story || !story.roomId) {
1372
2588
  throw new errors_1.NotFoundError('Story not found');
1373
2589
  }
1374
2590
  const storyName = story.name;
2591
+ // Get the room
1375
2592
  const room = await this.roomStore.getRoom(story.roomId);
1376
2593
  if (!room) {
1377
2594
  throw new errors_1.NotFoundError('Story room not found');
1378
2595
  }
2596
+ // Find and preserve the Opening Scene message before clearing
1379
2597
  const roomMessages = room.getLatestRoomMessages();
1380
2598
  const openingSceneMessage = roomMessages.find((msg) => msg.sender === 'Opening Scene');
1381
2599
  const openingSceneText = openingSceneMessage?.content || '';
1382
2600
  const storageDir = room.getStorageDir() ||
1383
2601
  path.join(this.userPaths.getUserDataDir(), 'stories', storyId, 'rooms');
2602
+ // Clear room messages (both in-memory and on disk)
1384
2603
  this.roomStore.clearRoomMessages(story.roomId, storageDir);
1385
2604
  room.setRoomMessages([]);
2605
+ // Restore agents from chapter 1 backup instead of calling reloadAgent
1386
2606
  const chapters = this.storyStore.listChapters(storyId);
1387
2607
  const warnings = [];
1388
2608
  if (chapters.length > 0) {
2609
+ // Chapter 1 backup exists - restore agents from it
1389
2610
  logger_1.logger.log(`Restoring agents from chapter 1 backup for story ${storyId}`);
1390
2611
  const restoredAgentIds = await this.storyStore.restoreAgentsFromChapter(storyId, 1, this.agentStore);
1391
2612
  logger_1.logger.log(`Restored ${restoredAgentIds.length} agents from chapter 1 backup`);
1392
2613
  }
1393
2614
  else {
2615
+ // No chapter backup exists - fallback to reloadAgent (clear histories)
1394
2616
  logger_1.logger.warn(`No chapter 1 backup found for story ${storyId}, clearing agent histories`);
1395
2617
  for (const agent of room.getAgents()) {
1396
2618
  try {
@@ -1401,35 +2623,209 @@ class AppService {
1401
2623
  }
1402
2624
  }
1403
2625
  }
2626
+ // Re-add the opening scene message and populate agent histories
1404
2627
  if (openingSceneText) {
1405
2628
  this.storyService.populateStoryHistory(room, openingSceneText);
1406
2629
  }
2630
+ // Clear declined characters when resetting story
1407
2631
  if (story) {
1408
2632
  story.declinedCharacters = [];
1409
2633
  this.storyStore.updateStoryMetadata(storyId, story);
1410
2634
  }
2635
+ // Log warnings if any
1411
2636
  if (warnings.length > 0) {
1412
2637
  logger_1.logger.warn(`Story "${storyName}" reset with warnings:`, warnings);
1413
2638
  }
1414
2639
  }
2640
+ /**
2641
+ * Reverts the most recent chapter progression for a story. Restores room
2642
+ * messages, artifacts, and agent histories from the previous chapter
2643
+ * backup, then deletes that backup. Only valid when the current chapter
2644
+ * has not been played past the opening scene.
2645
+ *
2646
+ * @param storyId - The story's ID
2647
+ * @throws {NotFoundError} If the story or its room does not exist
2648
+ * @throws {OperationFailedError} If revert is not currently valid
2649
+ */
1415
2650
  async revertStoryChapter(storyId) {
1416
2651
  return this.storyService.revertStoryChapter(storyId);
1417
2652
  }
2653
+ /**
2654
+ * Creates a new interactive story with AI-driven characters.
2655
+ *
2656
+ * When this method returns, the story is **immediately playable**: brief character
2657
+ * backgrounds and the opening scene have already been generated. A background job
2658
+ * then generates the detailed plot plan and full character profiles; subscribe to
2659
+ * {@link getStoryProgressEmitter} to be notified when that finishes (`step === 'complete'`),
2660
+ * but there is no need to wait for it before letting the player interact.
2661
+ *
2662
+ * @param name - Display name for the story
2663
+ * @param idea - Brief premise or concept for the story
2664
+ * @param userCharacterDesc - Description of the character the human player will portray
2665
+ * @param otherCharactersDesc - Description of other prominent characters to generate
2666
+ * @param storyModel - Model identifier from `story_models.json` (e.g. `'claude-haiku-4-5'`). Defaults to the configured default.
2667
+ * @param isImport - Set `true` when reconstructing a story from exported data. Default `false`.
2668
+ * @param imageModelName - Optional image model name from image_models.json (supplies both the generation and editing models)
2669
+ * @param skipDetailedPlot - Set `true` to generate a simple plot scenario instead of a detailed plot plan with secrets, twists, and events. Default `false`.
2670
+ * @returns Story metadata including the new `id` - story is ready to play immediately
2671
+ *
2672
+ * @example
2673
+ * ```typescript
2674
+ * // Story is playable as soon as createStory returns
2675
+ * const story = await appService.createStory(
2676
+ * 'The Lost Kingdom',
2677
+ * 'A medieval fantasy adventure',
2678
+ * 'A young knight seeking redemption',
2679
+ * 'A wise wizard and a cunning rogue',
2680
+ * );
2681
+ *
2682
+ * // Optionally listen for background completion (plot plan + detailed profiles)
2683
+ * const emitter = appService.getStoryProgressEmitter(story.id);
2684
+ * emitter?.on('progress', ({ step, message }) => {
2685
+ * if (step === 'complete') console.log('Background setup finished');
2686
+ * });
2687
+ * ```
2688
+ */
1418
2689
  async createStory(name, idea, userCharacterDesc, otherCharactersDesc, illustrateStory, storyModel, isImport, imageModelName, skipDetailedPlot) {
2690
+ // Delegate to StoryService for business logic
1419
2691
  return this.storyService.createStory(name, idea, userCharacterDesc, otherCharactersDesc, illustrateStory, storyModel, isImport, imageModelName, skipDetailedPlot);
1420
2692
  }
2693
+ /**
2694
+ * Reconstructs a story from a previously exported zip archive.
2695
+ *
2696
+ * @param zipBuffer - Raw bytes of the zip file produced by {@link exportStoryData}
2697
+ * @returns Story metadata for the newly imported story
2698
+ */
1421
2699
  async importStoryFromZip(zipBuffer) {
1422
2700
  return this.storyService.importStoryFromZip(zipBuffer);
1423
2701
  }
2702
+ /**
2703
+ * Returns the `EventEmitter` for tracking background story work.
2704
+ *
2705
+ * Subscribe to the `'progress'` event. Each event payload is
2706
+ * `{ step: string, message: string, timestamp: number }`.
2707
+ *
2708
+ * **`step` values emitted after {@link createStory} returns:**
2709
+ *
2710
+ * The story is already playable when `createStory` returns. There is no `'ready'`
2711
+ * step for story creation - the storyId does not exist until `createStory` returns,
2712
+ * so the client cannot subscribe to the progress emitter until after that point.
2713
+ * These steps describe the optional background job (plot plan + detailed profiles)
2714
+ * that continues after the method returns:
2715
+ * - `'start'` - background job has begun
2716
+ * - `'profiles'` - generating detailed character profiles
2717
+ * - `'portraits'` - generating character portrait images (only if an image model is configured)
2718
+ * - `'complete'` - background job finished; detailed profiles and plot plan are now available
2719
+ * - `'error'` - background job failed; `message` contains the error text
2720
+ *
2721
+ * **`step` values emitted during {@link progressStory}:**
2722
+ *
2723
+ * `'ready'` fires just before `progressStory` returns, so the story is playable
2724
+ * as soon as the Promise resolves - no need to separately listen for `'ready'`.
2725
+ * The event is emitted for the benefit of SSE clients that want to update their UI
2726
+ * in real time. After `'ready'`, a background job continues:
2727
+ * - `'opening-scene'` - writing the new chapter's opening scene
2728
+ * - `'chapter-backup'` - saving chapter checkpoint data
2729
+ * - `'ready'` - chapter ready; fired just before `progressStory` resolves
2730
+ * - `'profiles'` - (background) recreating plot plan and character profiles
2731
+ * - `'complete'` - (background) all chapter work done
2732
+ * - `'error'` - progression failed
2733
+ *
2734
+ * The emitter is removed after the terminal step (`'complete'`, `'ready'`, or `'error'`),
2735
+ * so this method returns `undefined` once a terminal step has fired.
2736
+ *
2737
+ * @param storyId - The story's ID
2738
+ * @returns `EventEmitter` emitting `'progress'` events, or `undefined` if already complete
2739
+ */
1424
2740
  getStoryProgressEmitter(storyId) {
1425
2741
  return this.storyService.getProgressEmitter(storyId);
1426
2742
  }
2743
+ /**
2744
+ * Returns the `EventEmitter` for real-time story updates.
2745
+ *
2746
+ * The emitter fires four named events. Each payload includes a `timestamp` field.
2747
+ *
2748
+ * ---
2749
+ *
2750
+ * **`'story-state'`** - {@link StoryStateEvent}
2751
+ * Fires after every room turn with the complete updated game state.
2752
+ * ```typescript
2753
+ * emitter.on('story-state', (event: StoryStateEvent) => {
2754
+ * const myTurn = event.state.currentSpeaker === event.state.userAgentName;
2755
+ * });
2756
+ * ```
2757
+ * Use `state.currentSpeaker === state.userAgentName` to detect the player's turn.
2758
+ * Do **not** use `state.humanPrompt` for turn detection - it is a UI display string
2759
+ * (e.g. `"What does Elena do next?"`) present even when it is not the player's turn.
2760
+ *
2761
+ * ---
2762
+ *
2763
+ * **`'suggest-introduce-character'`** - {@link StoryIntroduceCharacterEvent}
2764
+ * Fires when the narrator wants to add a new character. The host app should surface
2765
+ * this to the player before acting.
2766
+ * - **Accept:** call {@link introduceCharacterToStory} with `fromNarratorSuggestion: true`
2767
+ * - **Reject:** call {@link declineCharacter}
2768
+ * ```typescript
2769
+ * emitter.on('suggest-introduce-character', (event: StoryIntroduceCharacterEvent) => {
2770
+ * // event.characterName is the narrator-chosen name
2771
+ * });
2772
+ * ```
2773
+ *
2774
+ * ---
2775
+ *
2776
+ * **`'suggest-progress-chapter'`** - {@link StoryProgressChapterEvent}
2777
+ * Fires when the narrator wants to advance to the next chapter. The host app should
2778
+ * surface this to the player before acting.
2779
+ * - **Accept:** call {@link progressStory}
2780
+ * - **Stay in current chapter:** ignore the event (no rejection call needed)
2781
+ *
2782
+ * ---
2783
+ *
2784
+ * **`'story-error'`** - {@link StoryErrorEvent}
2785
+ * Fires when the story engine encounters a fatal error during room processing.
2786
+ * Named `'story-error'` rather than `'error'` to avoid Node.js throwing an uncaught
2787
+ * exception when no listener is attached to `'error'`.
2788
+ * Check `event.errorType === 'InsufficientBalanceError'` for balance failures.
2789
+ *
2790
+ * ---
2791
+ *
2792
+ * @param storyId - The story's ID
2793
+ * @returns `EventEmitter` emitting `'story-state'`, `'suggest-introduce-character'`,
2794
+ * `'suggest-progress-chapter'`, and `'story-error'` events
2795
+ */
1427
2796
  getStoryMessageEmitter(storyId) {
1428
2797
  return this.storyService.getMessageEmitter(storyId);
1429
2798
  }
2799
+ /**
2800
+ * Returns a Node.js `EventEmitter` that fires whenever this agent's state changes
2801
+ * (new message, token count update, etc.).
2802
+ *
2803
+ * Useful for building real-time UIs. Subscribe to the `'update'` event to receive
2804
+ * agent state payloads without polling.
2805
+ *
2806
+ * @param agentId - The agent's ID
2807
+ * @returns `EventEmitter` that emits `'update'` events with agent state payloads
2808
+ *
2809
+ * @example
2810
+ * ```typescript
2811
+ * const emitter = appService.getAgentMessageEmitter(agent.id);
2812
+ * emitter.on('update', (state) => {
2813
+ * console.log('New message:', state.latestMessage);
2814
+ * });
2815
+ * ```
2816
+ */
1430
2817
  getAgentMessageEmitter(agentId) {
1431
2818
  return this.agentMessageService.getOrCreateEmitter(agentId);
1432
2819
  }
2820
+ /**
2821
+ * Ensures the real-time state callback is registered for an agent.
2822
+ *
2823
+ * Normally called automatically by {@link processText} and {@link getAgentMessages}.
2824
+ * Call this explicitly when connecting a new SSE client to an agent that was
2825
+ * loaded from disk (not yet touched in this session).
2826
+ *
2827
+ * @param agentId - The agent's ID
2828
+ */
1433
2829
  async ensureAgentStateCallback(agentId) {
1434
2830
  try {
1435
2831
  const agent = await this.agentStore.getAgent(agentId);
@@ -1441,12 +2837,17 @@ class AppService {
1441
2837
  logger_1.logger.warn(`Could not set up SSE callback for agent ${agentId}:`, error.message);
1442
2838
  }
1443
2839
  }
2840
+ /**
2841
+ * Sets up the state change callback for an agent to emit SSE updates
2842
+ * @param agent The agent to set up the callback for
2843
+ */
1444
2844
  setupAgentStateCallback(agent) {
1445
2845
  if (!agent.id) {
1446
2846
  logger_1.logger.warn('Cannot set up SSE callback for agent without ID');
1447
2847
  return;
1448
2848
  }
1449
2849
  agent.setOnStateChange(() => {
2850
+ // Get current agent state - send only latest message + index
1450
2851
  const messages = agent.getFormattedMessages();
1451
2852
  const agentState = {
1452
2853
  agentId: agent.id,
@@ -1456,15 +2857,42 @@ class AppService {
1456
2857
  totalOutputTokens: agent.totalOutputTokens,
1457
2858
  totalCost: agent.totalCost,
1458
2859
  };
2860
+ // Emit update to all connected SSE clients
1459
2861
  this.agentMessageService.emitUpdate(agent.id, agentState);
1460
2862
  });
1461
2863
  }
2864
+ /**
2865
+ * Returns a Node.js `EventEmitter` that fires whenever a new message arrives in the room.
2866
+ *
2867
+ * Subscribe to the `'update'` event to receive room message payloads in real time
2868
+ * without polling.
2869
+ *
2870
+ * @param roomId - The room's ID
2871
+ * @returns `EventEmitter` that emits `'update'` events with room message payloads
2872
+ */
1462
2873
  getRoomMessageEmitter(roomId) {
1463
2874
  return this.roomMessageService.getOrCreateEmitter(roomId);
1464
2875
  }
2876
+ /**
2877
+ * Returns a Node.js `EventEmitter` that fires whenever the user's balance changes.
2878
+ *
2879
+ * Subscribe to the `'update'` event to push real-time balance updates to a connected
2880
+ * client (e.g. via SSE) without polling.
2881
+ *
2882
+ * @param userId - The user's ID (typically the same ID used with `getAppService`)
2883
+ * @returns `EventEmitter` that emits `'update'` events with the new balance value
2884
+ */
1465
2885
  getBalanceMessageEmitter(userId) {
1466
2886
  return this.balanceMessageService.getOrCreateEmitter(userId);
1467
2887
  }
2888
+ /**
2889
+ * Ensures the real-time state callback is registered for a room.
2890
+ *
2891
+ * Normally called automatically. Call this explicitly when connecting a new
2892
+ * SSE client to a room that was loaded from disk (not yet touched in this session).
2893
+ *
2894
+ * @param roomId - The room's ID
2895
+ */
1468
2896
  async ensureRoomStateCallback(roomId) {
1469
2897
  try {
1470
2898
  const room = await this.roomStore.getRoom(roomId);
@@ -1482,20 +2910,35 @@ class AppService {
1482
2910
  logger_1.logger.warn('Cannot set up SSE callback for room without ID');
1483
2911
  return;
1484
2912
  }
2913
+ // Failures go down the same channel as everything else, as
2914
+ // `{type: 'error', errorType, message}`. Without this a turn that dies —
2915
+ // most importantly on a spent balance — simply stopped: no message, no
2916
+ // event, nothing to await. A host watching the room saw it go quiet and had
2917
+ // no way to learn why, which is the worst shape a paid API can fail in.
1485
2918
  room.setOnError('app-service', (error) => {
1486
2919
  this.roomMessageService.emitError(roomId, error);
1487
2920
  });
1488
2921
  room.setOnStateChange('app-service', () => {
2922
+ // Everything the room logged, thoughts and tool notices included, so
2923
+ // that this stream and a reader's own message list count in the same
2924
+ // space. Carrying only the audible ones meant the position published
2925
+ // here and the index on the message disagreed for any reader holding
2926
+ // thoughts, and disagreed by an amount neither number could express —
2927
+ // so the only way back in step was to refetch the whole transcript.
2928
+ // A consumer that does not want the internal traffic drops it on
2929
+ // `action`, which costs nothing and cannot fall out of step.
1489
2930
  const messages = room.getLatestRoomMessages(0, true);
1490
2931
  const latestMessage = messages.length > 0 ? messages[messages.length - 1] : undefined;
1491
- const totalCost = room
1492
- .getAgents()
1493
- .map((a) => a.totalCost)
1494
- .reduce((acc, v) => acc + v, 0);
2932
+ const totalCost = room.totalCost();
1495
2933
  const roomState = {
2934
+ // Both variants travel on the room's 'update' event, so a host that
2935
+ // narrows on `type` needs it present on the ordinary one too.
1496
2936
  type: 'state',
1497
2937
  roomId: roomId,
1498
2938
  latestMessage: latestMessage,
2939
+ // The message's own index, not its position in this array. They
2940
+ // are the same number for an unfiltered list, and saying which
2941
+ // one is meant is what keeps them the same.
1499
2942
  messageIndex: latestMessage?.index,
1500
2943
  totalCost: totalCost,
1501
2944
  isPaused: room.getPaused(),
@@ -1506,9 +2949,22 @@ class AppService {
1506
2949
  this.roomMessageService.emitUpdate(roomId, roomState);
1507
2950
  });
1508
2951
  }
2952
+ /**
2953
+ * Lists all stories belonging to this user.
2954
+ *
2955
+ * @returns Array of story metadata objects
2956
+ */
1509
2957
  listStories() {
1510
2958
  return this.storyStore.getAllStories();
1511
2959
  }
2960
+ /**
2961
+ * Resumes any stories that were paused due to insufficient balance.
2962
+ *
2963
+ * Call this after adding balance via {@link addBalance} to allow stories that
2964
+ * stalled mid-processing to continue from where they left off.
2965
+ *
2966
+ * @returns The number of stories that were resumed
2967
+ */
1512
2968
  async resumePausedStories() {
1513
2969
  const stories = this.storyStore.getAllStories();
1514
2970
  let resumedCount = 0;
@@ -1519,11 +2975,14 @@ class AppService {
1519
2975
  const room = await this.roomStore.getRoom(story.roomId);
1520
2976
  if (!room)
1521
2977
  continue;
2978
+ // Check if room is paused (not processing but has pending messages)
1522
2979
  const isPaused = !room.isProcessingInProgress() && room['pendingMessages']?.length > 0;
1523
2980
  if (isPaused) {
1524
2981
  logger_1.logger.log(`Resuming paused story: ${story.name} (${story.id})`);
2982
+ // Add a system message to notify about resumption
1525
2983
  const resumeMessage = new message_1.RoomMessage('System', app_types_1.MessageAction.SYSTEM, 'Balance added. Conversation resumed.', [], null, null);
1526
2984
  room.addRoomMessage(resumeMessage);
2985
+ // Resume processing by calling processPendingMessages
1527
2986
  room['processPendingMessages']();
1528
2987
  resumedCount++;
1529
2988
  }
@@ -1537,129 +2996,477 @@ class AppService {
1537
2996
  }
1538
2997
  return resumedCount;
1539
2998
  }
2999
+ /**
3000
+ * Permanently deletes a story, its room, all characters, chapters, and artifacts.
3001
+ *
3002
+ * @param storyId - The story's ID
3003
+ */
1540
3004
  async deleteStory(storyId) {
1541
3005
  await this.storyService.deleteStory(storyId);
1542
3006
  }
3007
+ /**
3008
+ * Summarizes and compresses agent conversation histories to reduce token usage.
3009
+ *
3010
+ * Uses story-specific prompts: the narrator summarizes plot events,
3011
+ * characters summarize their relationships and experiences. The original
3012
+ * messages are replaced with a compact summary block.
3013
+ *
3014
+ * @param storyId - The story's ID
3015
+ * @returns Object with `success` flag, optional `message`, and compaction `details`
3016
+ */
1543
3017
  async compactStory(storyId) {
1544
3018
  return this.storyService.compactStory(storyId);
1545
3019
  }
3020
+ /**
3021
+ * Advances the story to the next chapter.
3022
+ *
3023
+ * Creates a checkpoint of the current chapter state and rebuilds the opening scene.
3024
+ * The story is **immediately playable when this Promise resolves** - the `'ready'`
3025
+ * progress event fires just before the function returns, so awaiting this call is
3026
+ * sufficient; there is no need to separately wait for the event.
3027
+ *
3028
+ * After the function returns, a background job recreates the plot plan and character
3029
+ * profiles for the new chapter (`'profiles'` --> `'complete'`). Agent
3030
+ * conversation histories are **not** compacted here - each agent compacts
3031
+ * independently on demand when it individually reaches the compaction threshold
3032
+ * (see {@link compactStory} for manual compaction).
3033
+ *
3034
+ * @param storyId - The story's ID
3035
+ * @returns Object with the new `chapterIndex`
3036
+ */
1546
3037
  async progressStory(storyId) {
1547
3038
  return this.storyService.progressStoryToNextChapter(storyId);
1548
3039
  }
3040
+ /**
3041
+ * Returns the current runtime state of a story.
3042
+ *
3043
+ * Includes messages, pending message count, processing status, and story metadata.
3044
+ * Useful for restoring UI state after reconnecting.
3045
+ *
3046
+ * @param storyId - The story's ID
3047
+ * @returns Full story state object
3048
+ */
1549
3049
  async getStoryState(storyId) {
1550
3050
  return this.storyService.getStoryState(storyId);
1551
3051
  }
3052
+ /**
3053
+ * Returns metadata for a specific story.
3054
+ *
3055
+ * @param storyId - The story's ID
3056
+ * @returns Story metadata, or `undefined` if not found
3057
+ */
1552
3058
  async getStoryInfo(storyId) {
1553
3059
  return this.storyStore.getStory(storyId);
1554
3060
  }
3061
+ /**
3062
+ * Submits the human player's response to the story.
3063
+ *
3064
+ * Adds the content as a player message and triggers the AI characters
3065
+ * to continue the narrative.
3066
+ *
3067
+ * Pass the literal string `'PASS'` (case-insensitive) to skip the player's
3068
+ * turn and let the AI characters continue without player input.
3069
+ *
3070
+ * @param storyId - The story's ID
3071
+ * @param content - The player's message or action, or `'PASS'` to skip the turn
3072
+ */
1555
3073
  async respondToStory(storyId, content) {
1556
3074
  return this.storyService.respondToStory(storyId, content);
1557
3075
  }
3076
+ /**
3077
+ * Cancels any pending AI turns and forces the human's turn.
3078
+ *
3079
+ * Drops the room's pending message queue and pauses processing so the
3080
+ * human-controlled agent becomes the current speaker. Any in-flight LLM
3081
+ * calls (perceive or moderator) will discard their responses on return.
3082
+ *
3083
+ * @param storyId - The story's ID
3084
+ */
1558
3085
  async interruptStory(storyId) {
1559
3086
  return this.storyService.interruptStory(storyId);
1560
3087
  }
3088
+ /**
3089
+ * Adds a new AI character to an existing story.
3090
+ *
3091
+ * Creates a character agent and integrates it into the story's room.
3092
+ * The character profile is generated by the AI based on the provided description.
3093
+ *
3094
+ * When {@link getStoryMessageEmitter} fires a `'suggestion'` update with
3095
+ * `suggestion.type === 'introduce_character'`, pass `suggestion.characterName` as
3096
+ * `name` and set `fromNarratorSuggestion: true` to accept the suggestion.
3097
+ * To reject it instead, call {@link declineCharacter}.
3098
+ *
3099
+ * @param storyId - The story's ID
3100
+ * @param name - The character's name
3101
+ * @param description - Brief description of the character's personality and role
3102
+ * @param storyModel - Optional model override from `story_models.json`
3103
+ * @param fromNarratorSuggestion - Set `true` when accepting a narrator `'suggestion'` update. Default `false`.
3104
+ */
1561
3105
  async introduceCharacterToStory(storyId, name, description, storyModel, fromNarratorSuggestion) {
1562
3106
  await this.storyService.introduceCharacter(storyId, name, description, storyModel, fromNarratorSuggestion);
1563
3107
  }
3108
+ /**
3109
+ * Records that the player declined a narrator-suggested character introduction.
3110
+ *
3111
+ * Prevents the narrator from suggesting the same character again in this story.
3112
+ *
3113
+ * @param storyId - The story's ID
3114
+ * @param characterName - The character name that was declined
3115
+ */
1564
3116
  async declineCharacter(storyId, characterName) {
1565
3117
  await this.storyService.declineCharacter(storyId, characterName);
1566
3118
  }
3119
+ /**
3120
+ * Removes a character's agent from the story while preserving their profile file.
3121
+ *
3122
+ * The character can be reintroduced later via {@link introduceCharacterToStory}
3123
+ * and their profile will be available.
3124
+ *
3125
+ * @param storyId - The story's ID
3126
+ * @param characterName - The character's name
3127
+ */
1567
3128
  async deleteCharacterFromStory(storyId, characterName) {
1568
3129
  await this.storyService.deleteCharacter(storyId, characterName);
1569
3130
  }
3131
+ /**
3132
+ * Returns all chapter checkpoints for a story.
3133
+ *
3134
+ * Chapters are created by {@link progressStory} and can be read with {@link getChapter}.
3135
+ *
3136
+ * @param storyId - The story's ID
3137
+ * @returns Object with a `chapters` array of chapter info objects
3138
+ */
1570
3139
  listChapters(storyId) {
1571
3140
  const chapters = this.storyStore.listChapters(storyId);
1572
3141
  return { chapters };
1573
3142
  }
3143
+ /**
3144
+ * Returns the messages from a specific chapter checkpoint.
3145
+ *
3146
+ * @param storyId - The story's ID
3147
+ * @param chapterIndex - The chapter number (1-based, as returned by {@link listChapters})
3148
+ * @returns Array of room messages from that chapter
3149
+ */
1574
3150
  async getChapter(storyId, chapterIndex) {
1575
3151
  return await this.storyStore.getChapterContent(storyId, chapterIndex);
1576
3152
  }
3153
+ /**
3154
+ * Overwrites the content of a chapter checkpoint.
3155
+ *
3156
+ * @param storyId - The story's ID
3157
+ * @param chapterIndex - The chapter number to overwrite
3158
+ * @param content - The new chapter content
3159
+ * @throws {OperationFailedError} If the chapter cannot be saved
3160
+ */
1577
3161
  saveChapter(storyId, chapterIndex, content) {
1578
3162
  const saved = this.storyStore.saveChapterContent(storyId, chapterIndex, content);
1579
3163
  if (!saved) {
1580
3164
  throw new errors_1.OperationFailedError('Failed to save chapter');
1581
3165
  }
1582
3166
  }
3167
+ /**
3168
+ * Deletes a chapter checkpoint from a story.
3169
+ *
3170
+ * @param storyId - The story's ID
3171
+ * @param chapterIndex - The chapter number to delete
3172
+ * @throws {NotFoundError} If the chapter does not exist
3173
+ */
1583
3174
  deleteChapter(storyId, chapterIndex) {
1584
3175
  const deleted = this.storyStore.deleteChapter(storyId, chapterIndex);
1585
3176
  if (!deleted) {
1586
3177
  throw new errors_1.NotFoundError('Chapter not found');
1587
3178
  }
1588
3179
  }
3180
+ /**
3181
+ * Returns all current characters in a story.
3182
+ *
3183
+ * @param storyId - The story's ID
3184
+ * @returns Array of character objects (derived from the story's room agents)
3185
+ */
1589
3186
  async listCharacters(storyId) {
1590
3187
  return await this.storyService.listCharacters(storyId);
1591
3188
  }
3189
+ /**
3190
+ * Returns the profile for a specific character.
3191
+ *
3192
+ * @param storyId - The story's ID
3193
+ * @param characterName - The character's name
3194
+ * @returns Object with `content` containing the character profile markdown
3195
+ */
1592
3196
  async getCharacter(storyId, characterName) {
1593
3197
  const content = await this.storyService.getCharacter(storyId, characterName);
1594
3198
  return { content: content || '' };
1595
3199
  }
3200
+ /**
3201
+ * Saves a character's profile markdown.
3202
+ *
3203
+ * @param storyId - The story's ID
3204
+ * @param characterName - The character's name
3205
+ * @param content - Markdown content for the character profile
3206
+ */
1596
3207
  saveCharacter(storyId, characterName, content) {
1597
3208
  this.storyService.saveCharacter(storyId, characterName, content);
1598
3209
  }
3210
+ /**
3211
+ * Returns the inventory for a specific character.
3212
+ *
3213
+ * @param storyId - The story's ID
3214
+ * @param characterName - The character's name
3215
+ * @returns Object with `content` containing the inventory markdown
3216
+ */
1599
3217
  async getCharacterInventory(storyId, characterName) {
1600
3218
  const content = await this.storyService.getCharacterInventory(storyId, characterName);
1601
3219
  return { content: content || '' };
1602
3220
  }
3221
+ /**
3222
+ * Saves a character's inventory markdown.
3223
+ *
3224
+ * @param storyId - The story's ID
3225
+ * @param characterName - The character's name
3226
+ * @param content - Markdown content for the character inventory
3227
+ */
1603
3228
  async saveCharacterInventory(storyId, characterName, content) {
1604
3229
  await this.storyService.saveCharacterInventory(storyId, characterName, content);
1605
3230
  }
3231
+ /**
3232
+ * Returns the story's plot plan.
3233
+ *
3234
+ * The plot plan is a room artifact generated by the narrator at story creation
3235
+ * and updated as the story progresses.
3236
+ *
3237
+ * @param storyId - The story's ID
3238
+ * @returns Object with `content` containing the plot plan markdown
3239
+ */
1606
3240
  async getPlotPlan(storyId) {
1607
3241
  const content = await this.storyService.getPlotPlan(storyId);
1608
3242
  return { content: content || '' };
1609
3243
  }
3244
+ /**
3245
+ * Generates the full story as a single markdown document.
3246
+ *
3247
+ * Combines all chapters and room messages in narrative order.
3248
+ *
3249
+ * @param storyId - The story's ID
3250
+ * @returns The complete story formatted as markdown text
3251
+ */
1610
3252
  async downloadStoryMarkdown(storyId) {
1611
3253
  return await this.storyService.generateStoryMarkdown(storyId);
1612
3254
  }
3255
+ /**
3256
+ * Exports the complete story data as a downloadable zip archive.
3257
+ *
3258
+ * The archive can be re-imported via {@link importStoryFromZip}.
3259
+ *
3260
+ * @param storyId - The story's ID
3261
+ * @returns Object with a `stream` (readable zip stream) and `filename` for the download
3262
+ */
1613
3263
  async exportStoryData(storyId) {
1614
3264
  return await this.storyService.exportStoryData(storyId);
1615
3265
  }
3266
+ /**
3267
+ * Returns the formatted conversation history for a specific character in a story.
3268
+ *
3269
+ * @param storyId - The story's ID
3270
+ * @param agentId - The character agent's ID
3271
+ * @returns Object with `content` containing the formatted history text
3272
+ */
1616
3273
  async getAgentHistory(storyId, agentId) {
1617
3274
  const history = await this.storyService.getAgentHistory(storyId, agentId);
1618
3275
  return { content: history };
1619
3276
  }
3277
+ /**
3278
+ * Saves the story's plot plan.
3279
+ *
3280
+ * Persists the content as a room artifact via the publish mechanism.
3281
+ *
3282
+ * @param storyId - The story's ID
3283
+ * @param content - The plot plan markdown to save
3284
+ */
1620
3285
  async savePlotPlan(storyId, content) {
1621
3286
  await this.storyService.savePlotPlan(storyId, content);
1622
3287
  }
3288
+ /**
3289
+ * Returns the user's current credit balance in dollars.
3290
+ *
3291
+ * The balance is decremented automatically after each AI call based on token usage
3292
+ * and any configured markup. Calls that would exceed the balance throw
3293
+ * `InsufficientBalanceError` before the request is sent.
3294
+ *
3295
+ * @returns Current balance in dollars
3296
+ */
1623
3297
  getBalance() {
1624
3298
  return this.balanceService.getBalance();
1625
3299
  }
3300
+ /**
3301
+ * Adds funds to the user's balance.
3302
+ *
3303
+ * Use this to credit a user after a payment is processed by your application.
3304
+ *
3305
+ * @param amount - Dollar amount to add (must be positive)
3306
+ */
1626
3307
  addBalance(amount) {
1627
3308
  return this.balanceService.addBalance(amount);
1628
3309
  }
3310
+ /**
3311
+ * Records a new payment transaction.
3312
+ *
3313
+ * Call this when your payment provider confirms a payment has been initiated.
3314
+ * The `paymentId` should be the unique identifier issued by your payment provider
3315
+ * (e.g. a Stripe Payment Intent ID). Use {@link updateTransactionStatus} to update
3316
+ * the status once the provider confirms success or failure.
3317
+ *
3318
+ * @param amount - Dollar amount of the transaction
3319
+ * @param paymentId - Unique payment identifier from your payment provider
3320
+ * @param status - Initial status; defaults to `'pending'`
3321
+ * @returns The created `Transaction` record
3322
+ */
1629
3323
  async recordTransaction(amount, paymentId, status = 'pending') {
1630
3324
  return this.transactionService.recordTransaction(amount, paymentId, status);
1631
3325
  }
3326
+ /**
3327
+ * Updates the status of an existing transaction.
3328
+ *
3329
+ * Call this when your payment provider webhook confirms the final outcome of a payment.
3330
+ *
3331
+ * @param paymentId - The payment provider ID used when the transaction was recorded
3332
+ * @param status - New status (`'succeeded'`, `'failed'`, or `'cancelled'`)
3333
+ */
1632
3334
  async updateTransactionStatus(paymentId, status) {
1633
3335
  return this.transactionService.updateTransactionStatus(paymentId, status);
1634
3336
  }
3337
+ /**
3338
+ * Retrieves a single transaction by its payment provider ID.
3339
+ *
3340
+ * @param paymentId - The payment provider ID used when the transaction was recorded
3341
+ * @returns The matching `Transaction`, or `null` if not found
3342
+ */
1635
3343
  async getTransactionByPaymentId(paymentId) {
1636
3344
  return this.transactionService.getTransactionByPaymentId(paymentId);
1637
3345
  }
3346
+ /**
3347
+ * Returns paginated transaction history for this user, sorted newest-first.
3348
+ *
3349
+ * @param limit - Maximum number of records to return (default: 50)
3350
+ * @param offset - Number of records to skip for pagination (default: 0)
3351
+ * @returns Object with a `transactions` array and a `total` count
3352
+ */
1638
3353
  async getTransactions(limit = 50, offset = 0) {
1639
3354
  return this.transactionService.getTransactions(limit, offset);
1640
3355
  }
3356
+ // ==================== Artifact Management ====================
3357
+ /**
3358
+ * Returns metadata for all artifacts owned by this user.
3359
+ *
3360
+ * Artifacts are persistent named documents that can be attached to agents
3361
+ * (see {@link attachArtifactToAgent}) or shared with rooms via the `'publish'` action.
3362
+ * Use {@link getUserArtifact} to retrieve the actual content.
3363
+ *
3364
+ * @returns Array of artifact metadata objects (ID, name, creation date, etc.)
3365
+ */
1641
3366
  listUserArtifacts() {
1642
3367
  return this.artifactService.listArtifacts();
1643
3368
  }
3369
+ /**
3370
+ * Returns the content of a user artifact.
3371
+ *
3372
+ * Text artifacts are returned as `string`; binary artifacts (e.g. converted PDFs
3373
+ * in intermediate state) may be returned as `Buffer`.
3374
+ *
3375
+ * @param artifactId - The artifact's ID (from {@link listUserArtifacts})
3376
+ * @returns The artifact content, or `null` if no artifact with that ID exists
3377
+ */
1644
3378
  getUserArtifact(artifactId) {
1645
3379
  return this.artifactService.getArtifact(artifactId);
1646
3380
  }
3381
+ /**
3382
+ * Creates a new named artifact and returns its ID.
3383
+ *
3384
+ * The artifact is persisted immediately. Use the returned ID to attach it to
3385
+ * agents ({@link attachArtifactToAgent}) or reference it in room messages.
3386
+ *
3387
+ * @param name - Human-readable display name for the artifact
3388
+ * @param content - Initial text content (typically Markdown)
3389
+ * @returns The new artifact's ID
3390
+ */
1647
3391
  createUserArtifact(name, content) {
1648
3392
  return this.artifactService.storeArtifact(name, content);
1649
3393
  }
3394
+ /**
3395
+ * Replaces the content of an existing artifact.
3396
+ *
3397
+ * @param artifactId - The artifact's ID (from {@link listUserArtifacts})
3398
+ * @param content - New content to write
3399
+ * @returns `true` on success, `false` if no artifact with that ID exists
3400
+ */
1650
3401
  updateUserArtifact(artifactId, content) {
1651
3402
  return this.artifactService.updateArtifact(artifactId, content);
1652
3403
  }
3404
+ /**
3405
+ * Creates an artifact from a PDF by converting it to Markdown, running the
3406
+ * conversion in the background.
3407
+ *
3408
+ * Returns the artifact ID immediately with placeholder content. The artifact
3409
+ * content is replaced with the converted Markdown when the background job
3410
+ * finishes. If conversion fails, the artifact content is replaced with an
3411
+ * error message.
3412
+ *
3413
+ * Requires the `DOC_CONVERSION_AI_SERVICE` and `DOC_CONVERSION_AI_MODEL`
3414
+ * environment variables to be set to an AI service that supports PDF documents.
3415
+ *
3416
+ * A PDF over ten pages is converted page by page, at most
3417
+ * `PDF_CONVERT_CONCURRENCY` at a time, with each page retried before it is
3418
+ * given up on. A page that is given up on does not fail the document: the
3419
+ * artifact still lands, naming the pages that are missing from it so they can
3420
+ * be re-run. Only a conversion that produces nothing at all replaces the
3421
+ * artifact with an error.
3422
+ *
3423
+ * @param name - Display name for the artifact
3424
+ * @param pdfBuffer - Buffer containing the raw PDF data
3425
+ * @returns The new artifact's ID (content is a placeholder until conversion completes)
3426
+ */
1653
3427
  convertUserArtifact(name, pdfBuffer) {
3428
+ // 1. Create placeholder artifact immediately
1654
3429
  const placeholderContent = 'Converting PDF. This text will be replaced when the conversion is finished.';
1655
3430
  const artifactId = this.artifactService.storeArtifact(name, placeholderContent);
3431
+ // 2. Start async conversion (don't await)
1656
3432
  this.convertPdfInBackground(artifactId, name, pdfBuffer).catch((error) => {
1657
3433
  logger_1.logger.error(`Background PDF conversion failed for ${artifactId}:`, error);
3434
+ // Update artifact with error message
1658
3435
  const errorContent = `# Conversion Failed\n\nThe PDF conversion failed with the following error:\n\n${error.message}\n\nPlease try uploading the file again.`;
1659
3436
  this.artifactService.updateArtifact(artifactId, errorContent);
1660
3437
  });
3438
+ // 3. Return immediately
1661
3439
  return artifactId;
1662
3440
  }
3441
+ /**
3442
+ * Converts a PDF to Markdown a page at a time and returns the pages.
3443
+ *
3444
+ * The building block under {@link convertUserArtifact}, public because a host
3445
+ * embedding Briyah usually wants the pages and the cost rather than an
3446
+ * artifact — to extract records from each page, to cache the result under its
3447
+ * own key, or to show progress. Every page is converted by its own throwaway
3448
+ * agent, so nothing accumulates history and pages stay independent.
3449
+ *
3450
+ * Bounded, retried and non-fatal: at most {@link PdfMarkdownOptions.concurrency}
3451
+ * pages are in flight, each page is retried on an empty response, a thrown
3452
+ * error or a timeout, and a page that exhausts its attempts is reported in
3453
+ * `failedPages` rather than failing the document.
3454
+ *
3455
+ * @param pdfBuffer - The raw PDF
3456
+ * @param options - Models, prompt, hints and limits; every field has a default
3457
+ * @returns The pages, the assembled Markdown, what failed, and the cost
3458
+ * @throws {ValidationError} If no conversion service or model is configured
3459
+ *
3460
+ * @example
3461
+ * ```typescript
3462
+ * const result = await appService.convertPdfToMarkdownPages(buffer, {
3463
+ * concurrency: 8,
3464
+ * fidelityHints: 'chapter and verse numbers',
3465
+ * onProgress: (message) => console.log(message),
3466
+ * });
3467
+ * if (result.failedPages.length) console.warn('Re-run pages', result.failedPages);
3468
+ * ```
3469
+ */
1663
3470
  async convertPdfToMarkdownPages(pdfBuffer, options = {}) {
1664
3471
  const aiServiceName = options.aiServiceName || process.env.DOC_CONVERSION_AI_SERVICE;
1665
3472
  const aiModel = options.aiModel || process.env.DOC_CONVERSION_AI_MODEL;
@@ -1673,6 +3480,9 @@ class AppService {
1673
3480
  const promptFile = options.promptFile || 'convert_pdf_page';
1674
3481
  const finishAgents = options.finishAgents !== false;
1675
3482
  const renderPage = async (pageBuffer, pageNum, pageCount) => {
3483
+ // A fresh agent per attempt, not per page: a retry after an empty
3484
+ // response must not carry that empty response in its history, which is
3485
+ // exactly what makes the second ask worth making.
1676
3486
  const agent = this.agentFactory.createAgent(aiServiceName, options.agentName || 'PDF Converter', '', `Converts page ${pageNum} of ${pageCount} to Markdown`, promptFolder, aiModel);
1677
3487
  if (options.reasoningEffort !== undefined) {
1678
3488
  agent.reasoningEffort = options.reasoningEffort;
@@ -1682,6 +3492,8 @@ class AppService {
1682
3492
  await agent.attachDocument(fileName, pageBuffer);
1683
3493
  const response = await agent.preparedPrompt(promptFile, {
1684
3494
  fileName,
3495
+ // Both spellings, so a caller pointing at its own prompt
3496
+ // folder does not have to match Briyah's variable names.
1685
3497
  pageNum,
1686
3498
  pageNumber: pageNum,
1687
3499
  pageCount,
@@ -1705,6 +3517,13 @@ class AppService {
1705
3517
  const result = await (0, pdf_conversion_1.convertPdfToMarkdown)(pdfBuffer, renderPage, options);
1706
3518
  return result;
1707
3519
  }
3520
+ /**
3521
+ * Converts a whole PDF in one request, for a document short enough that page
3522
+ * continuity is worth more than page-level recovery.
3523
+ *
3524
+ * Retried on the same policy as a page, since an empty response here loses the
3525
+ * entire document rather than one page of it.
3526
+ */
1708
3527
  async convertWholePdf(name, pdfBuffer) {
1709
3528
  const limits = (0, pdf_conversion_1.conversionLimits)();
1710
3529
  let lastError = 'the conversion returned nothing';
@@ -1731,6 +3550,17 @@ class AppService {
1731
3550
  }
1732
3551
  throw new Error(`The PDF conversion produced no content after ${limits.attempts} attempts: ${lastError}`);
1733
3552
  }
3553
+ /**
3554
+ * Background conversion process - updates the artifact when complete.
3555
+ *
3556
+ * A document of more than ten pages is converted page-by-page, which is what
3557
+ * makes a partial failure survivable: the artifact still lands, carrying the
3558
+ * pages that converted and naming the ones that did not.
3559
+ *
3560
+ * @param artifactId The artifact ID to update
3561
+ * @param name The artifact name
3562
+ * @param pdfBuffer Buffer containing PDF data
3563
+ */
1734
3564
  async convertPdfInBackground(artifactId, name, pdfBuffer) {
1735
3565
  logger_1.logger.log(`Starting background PDF conversion for artifact ${artifactId}`);
1736
3566
  if (!process.env.DOC_CONVERSION_AI_SERVICE)
@@ -1756,23 +3586,90 @@ class AppService {
1756
3586
  `${result.failedPages.length} failed${result.failedPages.length ? `: ${result.failedPages.join(', ')}` : ''}), ` +
1757
3587
  `Output: ${result.markdown.length} chars (total cost: $${result.totalCost.toFixed(4)})`);
1758
3588
  }
3589
+ /**
3590
+ * Changes the display name of an artifact.
3591
+ *
3592
+ * @param artifactId - The artifact's ID (from {@link listUserArtifacts})
3593
+ * @param newName - New display name for the artifact
3594
+ * @returns `true` on success, `false` if no artifact with that ID exists
3595
+ */
1759
3596
  renameUserArtifact(artifactId, newName) {
1760
3597
  return this.artifactService.renameArtifact(artifactId, newName);
1761
3598
  }
3599
+ /**
3600
+ * Permanently deletes a user artifact.
3601
+ *
3602
+ * Any agents that have the artifact attached will lose access to it after deletion.
3603
+ *
3604
+ * @param artifactId - The artifact's ID (from {@link listUserArtifacts})
3605
+ * @returns `true` on success, `false` if no artifact with that ID exists
3606
+ */
1762
3607
  deleteUserArtifact(artifactId) {
1763
3608
  return this.artifactService.deleteArtifact(artifactId);
1764
3609
  }
3610
+ /**
3611
+ * Gets the artifact service for a story
3612
+ * @param storyId The story ID
3613
+ * @returns The story-specific artifact service
3614
+ */
1765
3615
  getStoryArtifactService(storyId) {
1766
3616
  return this.storyService.getStoryArtifactService(storyId);
1767
3617
  }
3618
+ /**
3619
+ * Returns all artifacts associated with a story.
3620
+ *
3621
+ * Story artifacts include the plot plan and any documents published by agents
3622
+ * during the narrative.
3623
+ *
3624
+ * @param storyId - The story's ID
3625
+ * @returns Array of artifact metadata objects
3626
+ */
1768
3627
  listStoryArtifacts(storyId) {
1769
3628
  const storyArtifactService = this.getStoryArtifactService(storyId);
1770
3629
  return storyArtifactService.listArtifacts();
1771
3630
  }
3631
+ /**
3632
+ * Returns the content of a specific story artifact.
3633
+ *
3634
+ * @param storyId - The story's ID
3635
+ * @param artifactId - The artifact's ID (from {@link listStoryArtifacts})
3636
+ * @returns The artifact content as a string or Buffer, or `null` if not found
3637
+ */
1772
3638
  getStoryArtifact(storyId, artifactId) {
1773
3639
  const storyArtifactService = this.getStoryArtifactService(storyId);
1774
3640
  return storyArtifactService.getArtifact(artifactId);
1775
3641
  }
3642
+ /**
3643
+ * Returns one of a room's generated images, with the metadata needed to serve
3644
+ * it. Rooms keep their images in their own directory, separate from the
3645
+ * `.artifact` text files, so this does not go through the artifact store.
3646
+ *
3647
+ * @param roomId - The room's ID
3648
+ * @param artifactId - The image's ID, as it appears in the message markdown
3649
+ * @returns The bytes and MIME type, or `null` when there is no such image
3650
+ */
3651
+ async getRoomImage(roomId, artifactId) {
3652
+ const room = await this.roomStore.getRoom(roomId);
3653
+ if (!room)
3654
+ return null;
3655
+ const artifacts = this.illustration.targetFor(room).artifacts;
3656
+ const metadata = artifacts.getArtifactMetadata(artifactId);
3657
+ const content = artifacts.getArtifact(artifactId);
3658
+ if (!metadata || !content)
3659
+ return null;
3660
+ return { content, mimeType: metadata.mimeType || 'application/octet-stream' };
3661
+ }
3662
+ /**
3663
+ * Returns metadata for all artifacts currently attached to an agent.
3664
+ *
3665
+ * Attached artifacts are included in the agent's context on every prompt, allowing
3666
+ * the agent to reference their content. Use {@link attachArtifactToAgent} and
3667
+ * {@link detachArtifactFromAgent} to manage attachments.
3668
+ *
3669
+ * @param agentId - The agent's ID
3670
+ * @returns Array of artifact metadata objects for the agent's attached artifacts
3671
+ * @throws {NotFoundError} If no agent with the given ID exists
3672
+ */
1776
3673
  async listAgentArtifacts(agentId) {
1777
3674
  const agent = await this.agentStore.getAgent(agentId);
1778
3675
  if (!agent) {
@@ -1782,11 +3679,22 @@ class AppService {
1782
3679
  const allArtifacts = this.artifactService.listArtifacts();
1783
3680
  return allArtifacts.filter((a) => artifactIds.includes(a.artifactId));
1784
3681
  }
3682
+ /**
3683
+ * Attaches a user artifact to an agent so the agent can read its content in prompts.
3684
+ *
3685
+ * The attachment is persisted immediately via `agent.save()`. The artifact content
3686
+ * is injected into the agent's context on each subsequent call.
3687
+ *
3688
+ * @param agentId - The agent's ID
3689
+ * @param artifactId - The artifact's ID (from {@link listUserArtifacts})
3690
+ * @throws {NotFoundError} If the agent or artifact does not exist
3691
+ */
1785
3692
  async attachArtifactToAgent(agentId, artifactId) {
1786
3693
  const agent = await this.agentStore.getAgent(agentId);
1787
3694
  if (!agent) {
1788
3695
  throw new errors_1.NotFoundError(`Agent ${agentId} not found`);
1789
3696
  }
3697
+ // Verify artifact exists
1790
3698
  const artifact = this.artifactService.getArtifactMetadata(artifactId);
1791
3699
  if (!artifact) {
1792
3700
  throw new errors_1.NotFoundError(`Artifact ${artifactId} not found`);
@@ -1794,6 +3702,16 @@ class AppService {
1794
3702
  agent.attachArtifact(artifactId);
1795
3703
  agent.save();
1796
3704
  }
3705
+ /**
3706
+ * Removes an artifact attachment from an agent.
3707
+ *
3708
+ * The artifact itself is not deleted - only the link between the agent and the artifact
3709
+ * is removed. Changes are persisted immediately via `agent.save()`.
3710
+ *
3711
+ * @param agentId - The agent's ID
3712
+ * @param artifactId - The artifact's ID to detach
3713
+ * @throws {NotFoundError} If no agent with the given ID exists
3714
+ */
1797
3715
  async detachArtifactFromAgent(agentId, artifactId) {
1798
3716
  const agent = await this.agentStore.getAgent(agentId);
1799
3717
  if (!agent) {