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
@@ -65,6 +65,11 @@ const yauzl = __importStar(require("yauzl"));
65
65
  const message_1 = require("../room/message");
66
66
  const errors_1 = require("../common/errors");
67
67
  const logger_1 = require("../common/logger");
68
+ const illustration_service_1 = require("../room/illustration/illustration.service");
69
+ /**
70
+ * Service handling business logic for stories
71
+ * Works alongside StoryStoreService which handles persistence
72
+ */
68
73
  let StoryService = class StoryService {
69
74
  storyStore;
70
75
  agentStore;
@@ -74,9 +79,14 @@ let StoryService = class StoryService {
74
79
  userPaths;
75
80
  agentFactory;
76
81
  roomFactory;
82
+ illustration;
83
+ // Map to store story-specific artifact services
77
84
  storyArtifactServices = new Map();
85
+ // Tracks stories with an in-flight chapter progression so we can reject
86
+ // concurrent calls. The UI disables the Next Chapter button, but that
87
+ // protection is best-effort (double-click race, HTTP retry, multiple tabs).
78
88
  chaptersInProgress = new Set();
79
- constructor(storyStore, agentStore, roomStore, progressService, messageService, userPaths, agentFactory, roomFactory) {
89
+ constructor(storyStore, agentStore, roomStore, progressService, messageService, userPaths, agentFactory, roomFactory, illustration) {
80
90
  this.storyStore = storyStore;
81
91
  this.agentStore = agentStore;
82
92
  this.roomStore = roomStore;
@@ -85,28 +95,102 @@ let StoryService = class StoryService {
85
95
  this.userPaths = userPaths;
86
96
  this.agentFactory = agentFactory;
87
97
  this.roomFactory = roomFactory;
98
+ this.illustration = illustration;
99
+ }
100
+ /**
101
+ * Describes a story to the illustration pipeline.
102
+ *
103
+ * The indirection is what keeps existing stories untouched by the extraction:
104
+ * this reports the artifacts directory a story's images are already in and the
105
+ * `/api/stories/...` URL already baked into its saved message bodies, so
106
+ * nothing moves and no stored transcript goes stale.
107
+ */
108
+ illustrationTarget(storyId) {
109
+ const { agentsDir } = this.getStoryStorageDirs(storyId);
110
+ const artifacts = this.getStoryArtifactService(storyId);
111
+ const story = () => this.storyStore.getStory(storyId);
112
+ return {
113
+ key: storyId,
114
+ label: story()?.name ?? 'Story',
115
+ agentsDir,
116
+ artifacts,
117
+ imageUrl: (artifactId) => `/api/stories/${storyId}/artifacts/${artifactId}`,
118
+ imageName: (sequence) => `Story image - ${sequence}`,
119
+ scenario: () => story()?.scenario || '',
120
+ // A story is narrated, which is the wording describe_scene.prompt was
121
+ // written around; keeping this true renders it exactly as before.
122
+ narrated: true,
123
+ imageModelName: () => story()?.imageModelName,
124
+ agentIds: () => {
125
+ const s = story();
126
+ return {
127
+ illustratorAgentId: s?.illustratorAgentId,
128
+ artistAgentId: s?.artistAgentId,
129
+ artistEditAgentId: s?.artistEditAgentId,
130
+ };
131
+ },
132
+ saveAgentIds: (ids) => {
133
+ const s = story();
134
+ if (!s)
135
+ return;
136
+ s.illustratorAgentId = ids.illustratorAgentId;
137
+ s.artistAgentId = ids.artistAgentId;
138
+ s.artistEditAgentId = ids.artistEditAgentId;
139
+ this.storyStore.updateStoryMetadata(storyId, s);
140
+ },
141
+ };
88
142
  }
143
+ /**
144
+ * Gets the progress emitter for a story
145
+ * @param storyId The story ID
146
+ * @returns The event emitter or undefined
147
+ */
89
148
  getProgressEmitter(storyId) {
90
149
  return this.progressService.getProgressEmitter(storyId);
91
150
  }
151
+ /**
152
+ * Gets or creates the message emitter for a story
153
+ * @param storyId The story ID
154
+ * @returns The event emitter
155
+ */
92
156
  getMessageEmitter(storyId) {
93
157
  return this.messageService.getOrCreateEmitter(storyId);
94
158
  }
159
+ /**
160
+ * Cleans up the progress emitter for a story
161
+ * @param storyId The story ID
162
+ */
95
163
  cleanupProgressEmitter(storyId) {
96
164
  this.progressService.cleanup(storyId);
97
165
  }
166
+ /**
167
+ * Cleans up the message emitter for a story
168
+ * @param storyId The story ID
169
+ */
98
170
  cleanupMessageEmitter(storyId) {
99
171
  this.messageService.cleanup(storyId);
100
172
  }
173
+ /**
174
+ * Gets or creates the artifact service for a story
175
+ * @param storyId The story ID
176
+ * @returns The story-specific artifact service
177
+ */
101
178
  getStoryArtifactService(storyId) {
179
+ // Check if we already have an artifact service for this story
102
180
  let artifactService = this.storyArtifactServices.get(storyId);
103
181
  if (!artifactService) {
182
+ // Create new story-specific artifact service
104
183
  const { artifactsDir } = this.getStoryStorageDirs(storyId);
105
184
  artifactService = new artifact_service_1.ArtifactService(this.userPaths, artifactsDir);
106
185
  this.storyArtifactServices.set(storyId, artifactService);
107
186
  }
108
187
  return artifactService;
109
188
  }
189
+ /**
190
+ * Emits a story state update to connected SSE clients
191
+ * Called by room's onStateChange callback
192
+ * @param storyId The story ID
193
+ */
110
194
  async emitStoryStateUpdate(storyId) {
111
195
  try {
112
196
  let story = await this.ensureStoryLoaded(storyId);
@@ -119,17 +203,20 @@ let StoryService = class StoryService {
119
203
  logger_1.logger.error(`Room ${story.roomId} not found for story ${storyId}`);
120
204
  return;
121
205
  }
206
+ // Update story cost whenever state changes (after AI responses)
122
207
  await this.updateStoryCost(storyId);
123
- story = await this.getStoryInfo(storyId);
208
+ story = await this.getStoryInfo(storyId); // refresh storyInfo after updating cost
124
209
  const humanAgent = room.getAgents().find((agent) => agent.isControlledByHuman);
125
210
  if (!humanAgent) {
126
211
  logger_1.logger.error(`No human agent found for story ${storyId}`);
127
212
  return;
128
213
  }
214
+ // Get latest room message
129
215
  const roomMessages = room.getLatestRoomMessages(0, true);
130
216
  const latestMessage = roomMessages[roomMessages.length - 1];
131
217
  const currentSpeaker = room.getCurrentSpeaker();
132
218
  const humanPrompt = this.getHumanPrompt(room);
219
+ // Create incremental update with latest message only
133
220
  const stateUpdate = {
134
221
  storyId: story.id,
135
222
  latestRoomMessage: latestMessage,
@@ -140,41 +227,81 @@ let StoryService = class StoryService {
140
227
  totalInputTokens: story.totalInputTokens || 0,
141
228
  totalOutputTokens: story.totalOutputTokens || 0,
142
229
  };
230
+ // Emit SSE update (this service maintains the emitters)
143
231
  this.messageService.emitStoryState(storyId, stateUpdate);
144
232
  }
145
233
  catch (error) {
146
234
  logger_1.logger.error(`Error emitting story state update for ${storyId}:`, error);
147
235
  }
148
236
  }
237
+ // Get human prompt based on current speaker
149
238
  getHumanPrompt(room) {
150
239
  const humanAgent = room.getAgents().find((a) => a.isControlledByHuman);
151
240
  if (!humanAgent) {
152
241
  return '';
153
242
  }
154
243
  if (room.getCurrentSpeaker() === humanAgent.agentNickname) {
244
+ // It's the human's turn
155
245
  return `What does ${humanAgent.agentNickname} do or say next?`;
156
246
  }
157
247
  else if (room.getCurrentSpeaker() !== null) {
248
+ // It's another agent's turn
158
249
  return `Waiting for ${room.getCurrentSpeaker()}...`;
159
250
  }
160
251
  else if (room.isProcessingInProgress()) {
252
+ // System is processing
161
253
  return 'Processing...';
162
254
  }
163
255
  else {
256
+ // No current speaker and not processing
164
257
  return '';
165
258
  }
166
259
  }
260
+ /**
261
+ * Handles errors from room operations and emits them through SSE
262
+ * @param storyId The story ID
263
+ * @param error The error that occurred
264
+ */
167
265
  handleRoomError(storyId, error) {
168
266
  logger_1.logger.log(`Room error for story ${storyId}: ${error.name} - ${error.message}`);
169
267
  this.messageService.emitError(storyId, error);
170
268
  }
269
+ /**
270
+ * Picks a random word from the random words file, if there is one.
271
+ *
272
+ * The list is optional and is not published with the package, so an SDK host
273
+ * has no file to read. `create_story.prompt` offers the word as an aid rather
274
+ * than requiring it — "if you need random numbers or words, use these" — so a
275
+ * story created without one is a story the narrator had one fewer prompt from.
276
+ *
277
+ * Absent has to be handled here rather than left to throw: this runs inside
278
+ * {@link createStory}, so a missing file would fail every story creation
279
+ * outright rather than costing the narrator an idea.
280
+ * @returns A random word, or '' when no list is installed
281
+ */
171
282
  getRandomWord() {
172
283
  const randomWordsPath = path.join(this.userPaths.getCommonConfigDir(), 'random_words.txt');
173
- const content = fs.readFileSync(randomWordsPath, 'utf-8');
174
- const words = content.split('\n').filter((word) => word.trim().length > 0);
175
- const randomIndex = Math.floor(Math.random() * words.length);
176
- return words[randomIndex];
284
+ try {
285
+ if (!fs.existsSync(randomWordsPath))
286
+ return '';
287
+ const content = fs.readFileSync(randomWordsPath, 'utf-8');
288
+ const words = content.split('\n').filter((word) => word.trim().length > 0);
289
+ // An empty list used to index [0] of nothing and render the word
290
+ // "undefined" into the prompt.
291
+ if (words.length === 0)
292
+ return '';
293
+ return words[Math.floor(Math.random() * words.length)];
294
+ }
295
+ catch (error) {
296
+ logger_1.logger.warn(`Could not read ${randomWordsPath}: ${error.message}`);
297
+ return '';
298
+ }
177
299
  }
300
+ /**
301
+ * Gets the storage directories for a story
302
+ * @param storyId The story ID
303
+ * @returns Object with agentsDir, roomsDir, and artifactsDir paths
304
+ */
178
305
  getStoryStorageDirs(storyId) {
179
306
  const userStoriesDir = path.join(this.userPaths.getUserDataDir(), 'stories');
180
307
  return {
@@ -183,6 +310,11 @@ let StoryService = class StoryService {
183
310
  artifactsDir: path.join(userStoriesDir, storyId, 'artifacts'),
184
311
  };
185
312
  }
313
+ /**
314
+ * Looks up AI service and model from story_models.json using the model identifier
315
+ * @param storyModel The model identifier (e.g., "claude-sonnet-4-5")
316
+ * @returns Object with service and model, or null if not found
317
+ */
186
318
  getStoryModelConfig(storyModel) {
187
319
  const storyModelsPath = path.join(this.userPaths.getCommonConfigDir(), 'story_models.json');
188
320
  try {
@@ -193,6 +325,8 @@ let StoryService = class StoryService {
193
325
  service: modelConfig.service,
194
326
  model: modelConfig.model,
195
327
  smallModel: modelConfig.small_model,
328
+ // Moderator/illustrator service+model, falling back to the
329
+ // main story service+model when not specified in the entry.
196
330
  moderatorService: modelConfig.moderator_service || modelConfig.service,
197
331
  moderatorModel: modelConfig.moderator_model || modelConfig.model,
198
332
  };
@@ -206,42 +340,60 @@ let StoryService = class StoryService {
206
340
  }
207
341
  }
208
342
  async getStoryRoom(storyId) {
343
+ // Get the story metadata
209
344
  const story = await this.ensureStoryLoaded(storyId);
210
345
  if (!story) {
211
346
  throw new Error('Story not found');
212
347
  }
348
+ // Get the room
213
349
  const room = await this.roomStore.getRoom(story.roomId);
214
350
  if (!room) {
215
351
  throw new Error('Story room not found');
216
352
  }
217
353
  return room;
218
354
  }
355
+ /**
356
+ * Ensures a story's room and agents are loaded into memory
357
+ * Sets up the state change callback for event-driven updates
358
+ * @param storyId The story ID
359
+ */
219
360
  async ensureStoryLoaded(storyId) {
361
+ // Get the story metadata to check if it has a room
220
362
  const story = this.storyStore.getStory(storyId);
221
363
  if (!story)
222
- return null;
364
+ return null; // No room configured yet
223
365
  if (!story.roomId) {
224
366
  logger_1.logger.error(`Story ${storyId} has no roomId. Deleting story from storage...`);
225
367
  this.storyStore.removeStory(storyId);
226
368
  return null;
227
369
  }
370
+ // Check if the room is already loaded in memory
228
371
  let room = await this.roomStore.getRoom(story.roomId);
229
372
  if (room) {
230
- return story;
373
+ return story; // Room is already loaded, no need to reload
231
374
  }
375
+ // Room not loaded yet, load from directory
376
+ // Room not loaded yet, load from directory
232
377
  const { agentsDir, roomsDir } = this.getStoryStorageDirs(storyId);
233
378
  const storyArtifactService = this.getStoryArtifactService(storyId);
234
379
  await this.agentStore.loadAgentsFromDirectory(agentsDir, storyArtifactService);
235
380
  await this.roomStore.loadRoomsFromDirectory(roomsDir);
381
+ // Get the loaded room and set up callbacks
236
382
  room = await this.roomStore.getRoom(story.roomId);
237
383
  if (room) {
238
384
  room.setOnStateChange('story', () => {
239
385
  this.emitStoryStateUpdate(storyId);
240
386
  });
387
+ // Set up error callback
241
388
  room.setOnError('story', (error) => {
242
389
  this.handleRoomError(storyId, error);
243
390
  });
391
+ // Set up situation update callback (awaited by the room before it
392
+ // routes a narrator message, so an introduced character is created
393
+ // before moderation). latestMessage is the narration that triggered
394
+ // the update, passed through because it isn't logged to the room yet.
244
395
  room.setOnSituationUpdate((situation, latestMessage) => this.updateStorySituation(storyId, situation, latestMessage));
396
+ // Handle moderator-triggered portrait updates
245
397
  room.setOnModeratorResponse((message) => {
246
398
  const portraitsToUpdate = message.changes?.update_portrait ?? [];
247
399
  if (portraitsToUpdate.length) {
@@ -250,6 +402,9 @@ let StoryService = class StoryService {
250
402
  .getAgents()
251
403
  .find((a) => a.agentNickname === nickname);
252
404
  if (characterAgent) {
405
+ // updateDescription=true: the moderator flagged an
406
+ // appearance change, so refresh agent.description too
407
+ // (works even when images are disabled).
253
408
  this.updateCharacterPortrait(room, characterAgent, storyId, true).catch((e) => logger_1.logger.error(`Error updating appearance for ${nickname}:`, e));
254
409
  }
255
410
  else {
@@ -259,6 +414,7 @@ let StoryService = class StoryService {
259
414
  }
260
415
  this.applyInventoryUpdates(room, message);
261
416
  });
417
+ // Initialize room's situation from story metadata
262
418
  if (story.situation) {
263
419
  room.setSituation(story.situation);
264
420
  }
@@ -271,22 +427,41 @@ let StoryService = class StoryService {
271
427
  async getStoryInfo(storyId) {
272
428
  return this.storyStore.getStory(storyId);
273
429
  }
430
+ /**
431
+ * Creates a new story with business logic
432
+ * @param name The story name
433
+ * @param idea The story idea or existing story text (if isImport is true)
434
+ * @param userCharacterDesc Description of the character the user will play
435
+ * @param otherCharactersDesc Description of other prominent characters
436
+ * @param illustrateStory True if the story will be illustrated
437
+ * @param storyModel The model identifier (e.g., "claude-sonnet-4-5") from story_models.json
438
+ * @param isImport Flag indicating this is an imported existing story
439
+ * @param imageModelName Name of the image model in data/common/config/image_models.json. Each entry supplies both a generation model (portraits/scene references) and an editing model (story images with reference images).
440
+ * @param skipDetailedPlot When true, generate a simple plot scenario instead of a detailed plot plan with secrets, twists, and events
441
+ * @returns The story information including the generated ID
442
+ */
274
443
  async createStory(name, idea, userCharacterDesc, otherCharactersDesc, illustrateStory, storyModel, isImport = false, imageModelName, skipDetailedPlot = false) {
444
+ // Validate input
275
445
  if (!name || name.trim().length === 0) {
276
446
  throw new Error('Story name is required');
277
447
  }
448
+ // Create story directory structure and get ID
278
449
  const storyInfo = this.storyStore.createStory(name);
279
450
  storyInfo.turnNumber = 0;
280
451
  let storyTitle = name;
281
452
  try {
453
+ // Create progress emitter for this story
282
454
  this.progressService.createProgressEmitter(storyInfo.id);
283
455
  this.progressService.emitProgress(storyInfo.id, 'start', 'Starting story creation...');
456
+ // Get story-specific storage directories
284
457
  const { agentsDir: storyAgentsDir, roomsDir: storyRoomsDir } = this.getStoryStorageDirs(storyInfo.id);
458
+ // Get story-specific artifact service
285
459
  const storyArtifactService = this.getStoryArtifactService(storyInfo.id);
286
460
  let aiServiceName;
287
461
  let aiModelName;
288
462
  if (!storyModel || storyModel.trim().length === 0)
289
463
  storyModel = process.env.DEFAULT_STORY_MODEL;
464
+ // Look up service and model from story_models.json
290
465
  const modelConfig = this.getStoryModelConfig(storyModel);
291
466
  if (modelConfig) {
292
467
  aiServiceName = modelConfig.service;
@@ -294,14 +469,20 @@ let StoryService = class StoryService {
294
469
  }
295
470
  if (!aiServiceName || !aiModelName)
296
471
  throw new Error(`Failed to find model config for "${storyModel}"`);
297
- let moderator = this.agentFactory.createAgent(modelConfig.moderatorService, `${storyTitle} - Moderator`, 'Moderator', 'Story moderator responsible for message routing and conversation flow', 'story_moderator', modelConfig.moderatorModel, storyAgentsDir, storyArtifactService);
472
+ // PHASE 1: Create moderator agent (BEFORE narrator)
473
+ let moderator = this.agentFactory.createAgent(modelConfig.moderatorService, `${storyTitle} - Moderator`, // Agent name = "[story title] - [nickname]"
474
+ 'Moderator', 'Story moderator responsible for message routing and conversation flow', 'story_moderator', modelConfig.moderatorModel, storyAgentsDir, storyArtifactService);
475
+ // Set rolling window for moderator (keep only last 16 messages)
298
476
  moderator.maxHistoryMessages = 16;
299
477
  moderator.reasoningEffort = 'low';
300
- moderator.promptCacheTTL = 60;
478
+ moderator.promptCacheTTL = 60; // Cache prompts but don't auto refresh
301
479
  moderator.ownerRoomId = storyInfo.id;
302
- moderator.markupRate = 0;
480
+ moderator.markupRate = 0; // Don't markup the moderator
303
481
  moderator.save();
304
482
  logger_1.logger.log(`Created moderator agent: ${moderator.agentName}`);
483
+ // Resolve the image model - fall back to the env default when illustrateStory
484
+ // is set. A single consolidated entry supplies both the generation and
485
+ // editing models (see image_models.json).
305
486
  if (illustrateStory) {
306
487
  if (!imageModelName)
307
488
  imageModelName = process.env.DEFAULT_IMAGE_MODEL;
@@ -309,19 +490,43 @@ let StoryService = class StoryService {
309
490
  else {
310
491
  imageModelName = undefined;
311
492
  }
312
- const artist = this.createArtistAgent(storyInfo.id, storyAgentsDir, storyArtifactService, imageModelName, 'Artist', 'generation');
313
- const artistEdit = this.createArtistAgent(storyInfo.id, storyAgentsDir, storyArtifactService, imageModelName, 'Artist (Edit)', 'editing');
493
+ // Create artist agent (text-to-image: portraits and scene references) from
494
+ // the entry's generation model.
495
+ const artist = this.illustration.createArtistAgent({
496
+ label: storyInfo.name,
497
+ agentsDir: storyAgentsDir,
498
+ artifacts: storyArtifactService,
499
+ imageModelName,
500
+ nickname: 'Artist',
501
+ variant: 'generation',
502
+ });
503
+ // Create artist edit agent (image-to-image: story images with reference
504
+ // images) from the same entry's editing model.
505
+ const artistEdit = this.illustration.createArtistAgent({
506
+ label: storyInfo.name,
507
+ agentsDir: storyAgentsDir,
508
+ artifacts: storyArtifactService,
509
+ imageModelName,
510
+ nickname: 'Artist (Edit)',
511
+ variant: 'editing',
512
+ });
513
+ // Create illustrator agent (only if artist exists)
314
514
  let illustrator = null;
315
515
  if (artist) {
316
- illustrator = this.agentFactory.createAgent(modelConfig.moderatorService, `${storyTitle} - Illustrator`, 'Illustrator', 'Visual artist for generating scene illustrations', 'illustrator', modelConfig.moderatorModel, storyAgentsDir, storyArtifactService);
317
- illustrator.reasoningEffort = 'low';
318
- illustrator.maxHistoryMessages = 10;
319
- illustrator.promptCacheTTL = 60;
320
- illustrator.ownerRoomId = storyInfo.id;
321
- illustrator.save();
516
+ illustrator = this.illustration.createIllustratorAgent({
517
+ label: storyTitle,
518
+ agentsDir: storyAgentsDir,
519
+ artifacts: storyArtifactService,
520
+ service: modelConfig.moderatorService,
521
+ model: modelConfig.moderatorModel,
522
+ ownerRoomId: storyInfo.id,
523
+ });
322
524
  logger_1.logger.log(`Created illustrator agent: ${illustrator.agentName}`);
323
525
  }
324
- let narrator = this.agentFactory.createAgent(aiServiceName, `${storyTitle} - Narrator`, 'Narrator', 'Story narrator. Should receive all messages where a character wants to perform an action or PASS or INTRODUCE a new character. Responds to all dialog with characters not listed in Available Agents.', 'narrator', aiModelName, storyAgentsDir, storyArtifactService);
526
+ // PHASE 2: Create narrator agent
527
+ let narrator = this.agentFactory.createAgent(aiServiceName, `${storyTitle} - Narrator`, // Agent name = "[story title] - [nickname]"
528
+ 'Narrator', // Agent nickname
529
+ 'Story narrator. Should receive all messages where a character wants to perform an action or PASS or INTRODUCE a new character. Responds to all dialog with characters not listed in Available Agents.', 'narrator', aiModelName, storyAgentsDir, storyArtifactService);
325
530
  narrator.reasoningEffort = 'low';
326
531
  narrator.allowSearch = true;
327
532
  narrator.promptCacheTTL = 60;
@@ -329,9 +534,12 @@ let StoryService = class StoryService {
329
534
  narrator.smallModelName = modelConfig.smallModel;
330
535
  narrator.save();
331
536
  logger_1.logger.log(`Created narrator agent: ${narrator.agentName}`);
537
+ // Enable story creation flags (will be disabled after plot/profiles complete)
332
538
  narrator.disableMarkup = true;
333
539
  narrator.disableBalanceCheck = true;
334
540
  narrator.save();
541
+ // PHASE 2: Extract initial story framework (scenario and character names/descriptions)
542
+ // Generate ONLY the opening scene (quick LLM call)
335
543
  this.progressService.emitProgress(storyInfo.id, 'opening-scene', 'Generating opening scene...');
336
544
  const storyFrameworkPromptName = isImport ? 'import_story' : 'create_story';
337
545
  const storyFrameworkResponse = await narrator.preparedPrompt(storyFrameworkPromptName, {
@@ -352,13 +560,16 @@ let StoryService = class StoryService {
352
560
  importedStoryText = idea;
353
561
  }
354
562
  logger_1.logger.log(`Story framework extracted: ${otherCharactersInfo.length} other characters`);
563
+ // Build complete characters array including human character
355
564
  const characters = [
565
+ // Human character first
356
566
  {
357
567
  name: userCharacterInfo.name,
358
568
  sex: userCharacterInfo.sex,
359
569
  description: userCharacterInfo.description,
360
570
  isControlledByHuman: true,
361
571
  },
572
+ // Then AI characters
362
573
  ...otherCharactersInfo.map((char) => ({
363
574
  name: char.name,
364
575
  sex: char.sex,
@@ -366,24 +577,32 @@ let StoryService = class StoryService {
366
577
  isControlledByHuman: false,
367
578
  })),
368
579
  ];
580
+ // Update story metadata with extracted information
369
581
  storyInfo.scenario = scenario;
370
582
  storyInfo.characters = characters;
371
583
  storyInfo.aiService = aiServiceName;
372
584
  storyInfo.aiModel = aiModelName;
373
585
  storyInfo.isImport = isImport;
374
586
  storyInfo.skipDetailedPlot = skipDetailedPlot;
587
+ // Save the updated metadata
375
588
  this.storyStore.updateStoryMetadata(storyInfo.id, storyInfo);
589
+ // Save the initial creation parameters to a separate file for historical purposes
376
590
  this.storyStore.saveStoryCreationParameters(storyInfo.id, idea, userCharacterDesc, otherCharactersDesc);
591
+ // Create user character agent
377
592
  const userCharacterName = userCharacterInfo.name || 'Player';
593
+ // Generate nickname (first word of character name)
378
594
  const userNickname = userCharacterName.trim().split(/\s+/)[0];
379
595
  let userAgent = null;
380
596
  try {
381
- userAgent = this.agentFactory.createAgent(aiServiceName, `${name} - ${userNickname}`, userNickname, userCharacterInfo.description || userCharacterDesc, 'character', aiModelName, storyAgentsDir, storyArtifactService);
597
+ userAgent = this.agentFactory.createAgent(aiServiceName, `${name} - ${userNickname}`, // Agent name = "[story title] - [nickname]"
598
+ userNickname, // Agent nickname = character nickname
599
+ userCharacterInfo.description || userCharacterDesc, 'character', aiModelName, storyAgentsDir, storyArtifactService);
382
600
  userAgent.isControlledByHuman = true;
383
601
  userAgent.ownerRoomId = storyInfo.id;
384
602
  userAgent.smallModelName = modelConfig.smallModel;
385
603
  userAgent.save();
386
604
  logger_1.logger.log(`Created human-controlled character agent: ${userCharacterName}`);
605
+ // Enable story creation flags (will be disabled after character profile completes)
387
606
  userAgent.disableMarkup = true;
388
607
  userAgent.disableBalanceCheck = true;
389
608
  userAgent.save();
@@ -392,17 +611,23 @@ let StoryService = class StoryService {
392
611
  logger_1.logger.error('Error creating user character:', error);
393
612
  throw error;
394
613
  }
614
+ // Create other character agents sequentially
395
615
  const characterAgents = [];
396
616
  for (let i = 0; i < otherCharactersInfo.length; i++) {
397
617
  const charInfo = otherCharactersInfo[i];
618
+ // Generate nickname (first word of character name)
398
619
  const characterNickname = charInfo.name.trim().split(/\s+/)[0];
399
620
  try {
400
- const agent = this.agentFactory.createAgent(aiServiceName, `${name} - ${characterNickname}`, characterNickname, charInfo.description, 'character', aiModelName, storyAgentsDir, storyArtifactService);
621
+ const agent = this.agentFactory.createAgent(aiServiceName, `${name} - ${characterNickname}`, // Agent name = "[story title] - [nickname]"
622
+ characterNickname, // Agent nickname = character nickname
623
+ charInfo.description, 'character', aiModelName, storyAgentsDir, storyArtifactService);
401
624
  agent.promptCacheTTL = 60;
625
+ //agent.maxOutputTokens = 1000; // To limit responses to 4096 chars for Discord
402
626
  agent.ownerRoomId = storyInfo.id;
403
627
  agent.smallModelName = modelConfig.smallModel;
404
628
  agent.save();
405
629
  logger_1.logger.log(`Created character agent: ${charInfo.name}`);
630
+ // Enable story creation flags (will be disabled after character profile completes)
406
631
  agent.disableMarkup = true;
407
632
  agent.disableBalanceCheck = true;
408
633
  agent.save();
@@ -410,21 +635,29 @@ let StoryService = class StoryService {
410
635
  }
411
636
  catch (error) {
412
637
  logger_1.logger.error(`Error creating character ${charInfo.name}:`, error);
638
+ // Continue with other characters
413
639
  }
414
640
  }
415
641
  logger_1.logger.log(`Created ${characterAgents.length + (userAgent ? 1 : 0)} character agents`);
416
- const room = this.roomFactory.createRoom(`Story: ${name}`, scenario, '', storyRoomsDir);
642
+ const room = this.roomFactory.createRoom(`Story: ${name}`, scenario, '', // baseRoomDir
643
+ storyRoomsDir);
644
+ // Add moderator agent FIRST (makes it the first agent in room)
417
645
  room.arrive(moderator);
418
646
  room.arrive(narrator);
647
+ // Add user's character agent (human-controlled)
419
648
  if (userAgent) {
420
649
  room.arrive(userAgent);
421
650
  }
651
+ // Add all AI character agents to the room
422
652
  for (const characterAgent of characterAgents) {
423
653
  room.arrive(characterAgent);
424
654
  }
425
655
  room.setRoomLeader(narrator.agentNickname);
656
+ // Set Narrator as current speaker before generating opening scene
426
657
  room.setCurrentSpeaker(narrator.agentNickname);
658
+ // Initialize situation
427
659
  room.setSituation(scenario || 'Story beginning');
660
+ // Store the room in story-specific directory
428
661
  const roomId = room.saveMetadata();
429
662
  room.addRoomMessages([
430
663
  new message_1.RoomMessage(`${userCharacterName}'s Backstory`, app_types_1.MessageAction.SYSTEM, userCharacterBackstory),
@@ -432,16 +665,24 @@ let StoryService = class StoryService {
432
665
  this.populateStoryHistory(room, openingScene);
433
666
  const totalCharacters = (userAgent ? 1 : 0) + characterAgents.length;
434
667
  logger_1.logger.log(`Created story room: ${roomId} with moderator, narrator, and ${totalCharacters} character agents`);
668
+ // Set human agent as current speaker - story is ready for their response
435
669
  if (userAgent) {
436
670
  room.setCurrentSpeaker(userAgent.agentNickname);
437
671
  }
672
+ // Set up callbacks for event-driven updates
438
673
  room.setOnStateChange('story', () => {
439
674
  this.emitStoryStateUpdate(storyInfo.id);
440
675
  });
676
+ // Set up error callback
441
677
  room.setOnError('story', (error) => {
442
678
  this.handleRoomError(storyInfo.id, error);
443
679
  });
680
+ // Set up situation update callback (awaited by the room before it
681
+ // routes a narrator message, so an introduced character is created
682
+ // before moderation). latestMessage is the narration that triggered
683
+ // the update, passed through because it isn't logged to the room yet.
444
684
  room.setOnSituationUpdate((situation, latestMessage) => this.updateStorySituation(storyInfo.id, situation, latestMessage));
685
+ // Handle moderator-triggered portrait updates
445
686
  room.setOnModeratorResponse((message) => {
446
687
  const portraitsToUpdate = message.changes?.update_portrait ?? [];
447
688
  if (portraitsToUpdate.length) {
@@ -459,6 +700,7 @@ let StoryService = class StoryService {
459
700
  }
460
701
  this.applyInventoryUpdates(room, message);
461
702
  });
703
+ // Update story metadata
462
704
  storyInfo.roomId = roomId;
463
705
  storyInfo.moderatorAgentId = moderator.id;
464
706
  storyInfo.illustratorAgentId = illustrator?.id;
@@ -471,11 +713,14 @@ let StoryService = class StoryService {
471
713
  this.storyStore.updateStoryMetadata(storyInfo.id, storyInfo);
472
714
  await this.updateStoryCost(storyInfo.id);
473
715
  room.ready();
716
+ // Return the story ID immediately and do the heavy work in the background
717
+ // This allows the client to subscribe to SSE before progress events are emitted
474
718
  setImmediate(() => {
475
719
  this.createStoryAsync(storyInfo.id, name, importedStoryText, isImport, skipDetailedPlot).catch((error) => {
476
720
  logger_1.logger.error('Error in async story creation:', error);
477
721
  this.progressService.emitProgress(storyInfo.id, 'error', `Error: ${error.message}`);
478
722
  this.progressService.cleanup(storyInfo.id);
723
+ // Clean up partial story directory on async error
479
724
  this.deleteStory(storyInfo.id).catch((cleanupError) => {
480
725
  logger_1.logger.error('Error cleaning up story after async failure:', cleanupError);
481
726
  });
@@ -484,17 +729,26 @@ let StoryService = class StoryService {
484
729
  return storyInfo;
485
730
  }
486
731
  catch (error) {
732
+ // Clean up partially created story on error
487
733
  logger_1.logger.error('Error creating story:', error);
488
734
  this.progressService.emitProgress(storyInfo.id, 'error', `Error: ${error.message}`);
489
735
  this.progressService.cleanup(storyInfo.id);
736
+ // Delete the story directory and all its contents
490
737
  await this.deleteStory(storyInfo.id);
738
+ // Re-throw the error so the caller knows creation failed
491
739
  throw error;
492
740
  }
493
741
  }
742
+ /**
743
+ * Performs the actual story creation work asynchronously
744
+ * This runs in the background after returning the storyId to the client
745
+ */
494
746
  async createStoryAsync(storyId, name, importedStoryText, isImport, skipDetailedPlot = false) {
495
747
  try {
496
748
  const room = await this.getStoryRoom(storyId);
497
749
  const storyInfo = this.storyStore.getStory(storyId);
750
+ // The story creation dialog is closed and the opening scene is shown while we finish the profiles
751
+ // PHASE 5: Generate detailed profiles and plot in parallel, publishing each immediately
498
752
  const plotPromptName = isImport
499
753
  ? 'import_plot'
500
754
  : skipDetailedPlot
@@ -503,6 +757,7 @@ let StoryService = class StoryService {
503
757
  const userCharPromptName = isImport ? 'import_user_character' : 'create_user_character';
504
758
  const characterPromptName = isImport ? 'import_character' : 'create_character';
505
759
  this.progressService.emitProgress(storyInfo.id, 'profiles', 'Generating detailed profiles and plot...');
760
+ // Create all profile generation promises - each agent creates its own profile and publishes immediately
506
761
  const narrator = room.getAgents().find((a) => a.agentNickname === 'Narrator');
507
762
  const userAgent = room.getAgents().find((a) => a.isControlledByHuman === true);
508
763
  const userCharacter = storyInfo.characters.find((c) => c.isControlledByHuman === true);
@@ -510,6 +765,7 @@ let StoryService = class StoryService {
510
765
  .filter((c) => c.isControlledByHuman === false)
511
766
  .map((c) => `${c.name}: ${c.description}.`)
512
767
  .join('\n');
768
+ // Phase 1: plot plan only (opening scene image needs character profiles, generated in Phase 2)
513
769
  let plotPlan = '';
514
770
  const phase1Results = await Promise.all([
515
771
  narrator
@@ -522,7 +778,7 @@ let StoryService = class StoryService {
522
778
  .then((response) => {
523
779
  if (response) {
524
780
  const cleanedPlotPlan = this.extractMarkdownContent(response);
525
- plotPlan = cleanedPlotPlan;
781
+ plotPlan = cleanedPlotPlan; // Capture for use in Phase 2
526
782
  room.publishArtifact('Plot Plan', narrator.agentNickname, cleanedPlotPlan, [
527
783
  narrator.agentNickname,
528
784
  ]);
@@ -536,7 +792,9 @@ let StoryService = class StoryService {
536
792
  return { type: 'plot', success: false, error };
537
793
  }),
538
794
  ]);
795
+ // Phase 2: character profiles - run in parallel now that plotPlan is available
539
796
  const phase2Promises = [];
797
+ // 1. User character agent generates its own profile and publishes it
540
798
  if (userAgent) {
541
799
  phase2Promises.push(userAgent
542
800
  .preparedPrompt(userCharPromptName, {
@@ -566,6 +824,7 @@ let StoryService = class StoryService {
566
824
  return { type: 'userCharacter', success: false, error };
567
825
  }));
568
826
  }
827
+ // 2. Each AI character agent generates its own profile and publishes it
569
828
  for (let i = 0; i < storyInfo.characters.length; i++) {
570
829
  const charInfo = storyInfo.characters[i];
571
830
  if (charInfo.isControlledByHuman)
@@ -611,14 +870,18 @@ let StoryService = class StoryService {
611
870
  }));
612
871
  }
613
872
  const phase2Results = await Promise.all(phase2Promises);
873
+ // Phase 3: opening scene image - needs character profile artifacts created in Phase 2
614
874
  const openingSceneResult = await this.generateOpeningSceneImage(storyInfo, room);
615
875
  const profileResults = [...phase1Results, ...phase2Results, openingSceneResult];
876
+ // Check if any profiles failed
616
877
  const failedProfiles = profileResults.filter((r) => !r.success);
617
878
  if (failedProfiles.length > 0) {
618
879
  logger_1.logger.warn(`${failedProfiles.length} profile(s) failed to generate`);
619
880
  }
620
881
  narrator.allowSearch = false;
621
- narrator.save();
882
+ // narrator.maxOutputTokens = 1000; // To limit responses to 4096 chars for Discord (from here on out)
883
+ narrator.save(); // turn off search after creating the plot plan
884
+ // Disable story creation flags now that plot and profiles are complete
622
885
  const allAgents = room.getAgents();
623
886
  for (const agent of allAgents) {
624
887
  if (agent.disableMarkup || agent.disableBalanceCheck) {
@@ -637,6 +900,7 @@ let StoryService = class StoryService {
637
900
  this.progressService.emitProgress(storyId, 'error', `Error: ${error.message}`);
638
901
  }
639
902
  finally {
903
+ // CRITICAL: Always re-enable markup and balance checks, even on error
640
904
  try {
641
905
  const room = await this.getStoryRoom(storyId);
642
906
  if (room) {
@@ -650,6 +914,7 @@ let StoryService = class StoryService {
650
914
  }
651
915
  }
652
916
  generateCharacterPortraits(storyInfo, room) {
917
+ // Generate portraits for all characters (if artist exists)
653
918
  if (!storyInfo.artistAgentId) {
654
919
  logger_1.logger.log('Skipping character portrait generation: no artist agent');
655
920
  return [];
@@ -674,27 +939,39 @@ let StoryService = class StoryService {
674
939
  generateOpeningSceneImage(storyInfo, room) {
675
940
  return Promise.all(this.generateCharacterPortraits(storyInfo, room))
676
941
  .then(() => {
677
- return this.generateSceneIllustration(storyInfo.id, 'Opening Scene');
942
+ // The room holds the scenario as its situation at this point; the
943
+ // story's own copy is still empty, which is what used to reach the
944
+ // illustrator here.
945
+ return this.illustrateStorySituation(storyInfo.id, room, room.getSituation() || 'Opening Scene');
678
946
  })
679
947
  .then(() => {
680
948
  this.progressService.emitProgress(storyInfo.id, 'opening-scene', 'Generating opening scene image...');
681
949
  return { type: 'opening-scene', success: true };
682
950
  })
951
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
683
952
  .catch((_error) => {
684
953
  return Promise.resolve({ type: 'opening-scene', success: false });
685
954
  });
686
955
  }
956
+ /**
957
+ * Validates the structure of an imported story directory
958
+ * @param importDir The directory containing the extracted story files
959
+ * @returns Validation result with errors and metadata if valid
960
+ */
687
961
  async validateImportStructure(importDir) {
688
962
  const errors = [];
963
+ // Check metadata.json exists at root
689
964
  const metadataPath = path.join(importDir, 'metadata.json');
690
965
  if (!fs.existsSync(metadataPath)) {
691
966
  errors.push('metadata.json not found at root level');
692
967
  return { valid: false, errors };
693
968
  }
969
+ // Parse and validate metadata
694
970
  let metadata;
695
971
  try {
696
972
  const metadataContent = fs.readFileSync(metadataPath, 'utf-8');
697
973
  metadata = JSON.parse(metadataContent);
974
+ // Validate required fields
698
975
  if (!metadata.id || typeof metadata.id !== 'string') {
699
976
  errors.push("metadata.json missing or invalid 'id' field");
700
977
  }
@@ -717,11 +994,13 @@ let StoryService = class StoryService {
717
994
  errors.push(`Failed to parse metadata.json: ${error.message}`);
718
995
  return { valid: false, errors };
719
996
  }
997
+ // Check agents/ folder exists
720
998
  const agentsDir = path.join(importDir, 'agents');
721
999
  if (!fs.existsSync(agentsDir)) {
722
1000
  errors.push('agents/ folder not found');
723
1001
  }
724
1002
  else {
1003
+ // Collect referenced agent IDs
725
1004
  const referencedAgentIds = new Set();
726
1005
  if (metadata.moderatorAgentId)
727
1006
  referencedAgentIds.add(metadata.moderatorAgentId);
@@ -731,6 +1010,7 @@ let StoryService = class StoryService {
731
1010
  referencedAgentIds.add(metadata.artistAgentId);
732
1011
  if (metadata.userAgentId)
733
1012
  referencedAgentIds.add(metadata.userAgentId);
1013
+ // Validate agent files exist
734
1014
  for (const agentId of referencedAgentIds) {
735
1015
  const agentFile = path.join(agentsDir, `${agentId}.json`);
736
1016
  if (!fs.existsSync(agentFile)) {
@@ -738,11 +1018,13 @@ let StoryService = class StoryService {
738
1018
  }
739
1019
  }
740
1020
  }
1021
+ // Check rooms/ folder exists
741
1022
  const roomsDir = path.join(importDir, 'rooms');
742
1023
  if (!fs.existsSync(roomsDir)) {
743
1024
  errors.push('rooms/ folder not found');
744
1025
  }
745
1026
  else {
1027
+ // Validate exactly 1 room folder
746
1028
  const roomFolders = fs
747
1029
  .readdirSync(roomsDir)
748
1030
  .filter((f) => fs.statSync(path.join(roomsDir, f)).isDirectory());
@@ -750,16 +1032,19 @@ let StoryService = class StoryService {
750
1032
  errors.push(`Expected exactly 1 room folder, found ${roomFolders.length}`);
751
1033
  }
752
1034
  else {
1035
+ // Validate room folder name matches roomId
753
1036
  const roomFolderName = roomFolders[0];
754
1037
  if (roomFolderName !== metadata.roomId) {
755
1038
  errors.push(`Room folder name '${roomFolderName}' doesn't match roomId '${metadata.roomId}' in metadata`);
756
1039
  }
1040
+ // Check room metadata.json exists
757
1041
  const roomMetadataPath = path.join(roomsDir, roomFolderName, 'metadata.json');
758
1042
  if (!fs.existsSync(roomMetadataPath)) {
759
1043
  errors.push(`Room metadata.json not found at rooms/${roomFolderName}/metadata.json`);
760
1044
  }
761
1045
  }
762
1046
  }
1047
+ // Check story_creation.json exists (warn if missing, non-fatal)
763
1048
  const storyCreationPath = path.join(importDir, 'story_creation.json');
764
1049
  if (!fs.existsSync(storyCreationPath)) {
765
1050
  logger_1.logger.warn('story_creation.json not found (non-fatal)');
@@ -770,32 +1055,41 @@ let StoryService = class StoryService {
770
1055
  metadata: errors.length === 0 ? metadata : undefined,
771
1056
  };
772
1057
  }
1058
+ /**
1059
+ * Extracts a zip file to a target directory with security checks
1060
+ * @param zipBuffer The zip file buffer
1061
+ * @param targetDir The directory to extract to
1062
+ */
773
1063
  async extractZip(zipBuffer, targetDir) {
774
1064
  return new Promise((resolve, reject) => {
775
1065
  let totalSize = 0;
776
- const maxSize = 100 * 1024 * 1024;
1066
+ const maxSize = 100 * 1024 * 1024; // 100MB limit
777
1067
  yauzl.fromBuffer(zipBuffer, { lazyEntries: true }, (err, zipfile) => {
778
1068
  if (err) {
779
1069
  return reject(new Error(`Failed to read zip file: ${err.message}`));
780
1070
  }
781
1071
  zipfile.readEntry();
782
1072
  zipfile.on('entry', (entry) => {
1073
+ // Security: Check for path traversal
783
1074
  const entryPath = entry.fileName;
784
1075
  if (entryPath.includes('..') || path.isAbsolute(entryPath)) {
785
1076
  zipfile.close();
786
1077
  return reject(new Error(`Security: Invalid path in zip: ${entryPath}`));
787
1078
  }
788
1079
  const fullPath = path.join(targetDir, entryPath);
1080
+ // Directory entry
789
1081
  if (/\/$/.test(entryPath)) {
790
1082
  fs.mkdirSync(fullPath, { recursive: true });
791
1083
  zipfile.readEntry();
792
1084
  }
793
1085
  else {
1086
+ // File entry
794
1087
  zipfile.openReadStream(entry, (err, readStream) => {
795
1088
  if (err) {
796
1089
  zipfile.close();
797
1090
  return reject(new Error(`Failed to read entry ${entryPath}: ${err.message}`));
798
1091
  }
1092
+ // Ensure parent directory exists
799
1093
  fs.mkdirSync(path.dirname(fullPath), { recursive: true });
800
1094
  const writeStream = fs.createWriteStream(fullPath);
801
1095
  readStream.on('data', (chunk) => {
@@ -826,35 +1120,59 @@ let StoryService = class StoryService {
826
1120
  });
827
1121
  });
828
1122
  }
1123
+ /**
1124
+ * Imports a story from a zip file buffer
1125
+ * @param zipBuffer The zip file buffer to import
1126
+ * @returns The imported story metadata
1127
+ */
829
1128
  async importStoryFromZip(zipBuffer) {
830
1129
  const storiesDir = path.join(this.userPaths.getUserDataDir(), 'stories');
831
1130
  const importDir = path.join(storiesDir, 'import');
832
1131
  try {
1132
+ // 1. Clean import directory
833
1133
  if (fs.existsSync(importDir)) {
834
1134
  fs.rmSync(importDir, { recursive: true, force: true });
835
1135
  }
836
1136
  fs.mkdirSync(importDir, { recursive: true });
1137
+ // 2. Extract zip to import directory
837
1138
  await this.extractZip(zipBuffer, importDir);
1139
+ // 3. Validate structure
838
1140
  const validationResult = await this.validateImportStructure(importDir);
839
1141
  if (!validationResult.valid) {
840
1142
  throw new Error(`Invalid story structure:\n${validationResult.errors.join('\n')}`);
841
1143
  }
842
1144
  const metadata = validationResult.metadata;
1145
+ // 4. Check ID collision
843
1146
  const finalStoryPath = path.join(storiesDir, metadata.id);
844
1147
  if (fs.existsSync(finalStoryPath)) {
845
1148
  throw new Error(`Story with ID ${metadata.id} already exists (name: '${metadata.name}')`);
846
1149
  }
1150
+ // 5. Move to final location
847
1151
  fs.renameSync(importDir, finalStoryPath);
848
1152
  logger_1.logger.log(`Successfully imported story: ${metadata.name} (${metadata.id})`);
849
1153
  return metadata;
850
1154
  }
851
1155
  catch (error) {
1156
+ // Cleanup on failure
852
1157
  if (fs.existsSync(importDir)) {
853
1158
  fs.rmSync(importDir, { recursive: true, force: true });
854
1159
  }
855
1160
  throw error;
856
1161
  }
857
1162
  }
1163
+ /**
1164
+ * Populates agent conversation histories and room messages with imported story text
1165
+ *
1166
+ * @param room The story room
1167
+ * @param storyText The imported story text
1168
+ * @param audience Nicknames of the characters present for `storyText`. Characters
1169
+ * outside it do not hear it, which is how a chapter can open on a scene only some
1170
+ * of the cast are in. Non-character agents (narrator, moderator, illustrator,
1171
+ * artist) are always seeded - they work on the whole story, not a scene of it -
1172
+ * as is the player's own character, who is reading the text on screen either way.
1173
+ * Omit to seed everyone, which is right when the text opens the story and the
1174
+ * whole cast is new to it.
1175
+ */
858
1176
  populateStoryHistory(room, storyText, audience) {
859
1177
  try {
860
1178
  const storyMessage = {
@@ -880,19 +1198,34 @@ let StoryService = class StoryService {
880
1198
  throw error;
881
1199
  }
882
1200
  }
1201
+ /**
1202
+ * Sends a message to the story dialog and gets an AI response
1203
+ * @param storyId The story ID
1204
+ * @param message The user's message
1205
+ * @param action The action type ('say' or 'do')
1206
+ * @returns The AI assistant's response
1207
+ */
1208
+ /**
1209
+ * Gets the current state of a story including room messages and pending status
1210
+ * @param storyId The story ID
1211
+ * @returns Story state with room messages and pending status
1212
+ */
883
1213
  async getStoryState(storyId) {
884
1214
  const story = await this.ensureStoryLoaded(storyId);
885
1215
  if (!story) {
886
1216
  throw new Error('Story not found');
887
1217
  }
1218
+ // Get the room
888
1219
  const room = await this.roomStore.getRoom(story.roomId);
889
1220
  if (!room) {
890
1221
  throw new Error('Story room not found');
891
1222
  }
1223
+ // Find the human-controlled agent
892
1224
  const humanAgent = room.getAgents().find((agent) => agent.isControlledByHuman);
893
1225
  if (!humanAgent) {
894
1226
  throw new Error('No human-controlled agent found in story');
895
1227
  }
1228
+ // Get room messages to determine the latest index
896
1229
  const roomMessages = room.getLatestRoomMessages(0, true);
897
1230
  const latestMessageIndex = roomMessages.length > 0 ? roomMessages[roomMessages.length - 1].index : -1;
898
1231
  let latestRoomMessage = null;
@@ -912,9 +1245,15 @@ let StoryService = class StoryService {
912
1245
  };
913
1246
  return storyState;
914
1247
  }
1248
+ /**
1249
+ * Lists all characters in the story (excluding narrator)
1250
+ * @param storyId The story ID
1251
+ * @returns Array of character info
1252
+ */
915
1253
  async listCharacters(storyId) {
916
1254
  try {
917
1255
  const room = await this.getStoryRoom(storyId);
1256
+ // Get all character agents
918
1257
  const characters = room
919
1258
  .getAgents()
920
1259
  .filter((agent) => agent.promptFolder === 'character');
@@ -929,9 +1268,16 @@ let StoryService = class StoryService {
929
1268
  return [];
930
1269
  }
931
1270
  }
1271
+ /**
1272
+ * Gets a character profile artifact content
1273
+ * @param storyId The story ID
1274
+ * @param characterName The character name
1275
+ * @returns The character profile markdown content
1276
+ */
932
1277
  async getCharacter(storyId, characterName) {
933
1278
  try {
934
1279
  const room = await this.getStoryRoom(storyId);
1280
+ // Find the character profile artifact
935
1281
  const artifactName = `Character Profile - ${characterName}`;
936
1282
  const artifacts = room.getArtifacts();
937
1283
  const profileArtifact = artifacts.find((a) => a.name === artifactName);
@@ -939,11 +1285,13 @@ let StoryService = class StoryService {
939
1285
  return null;
940
1286
  }
941
1287
  let content = profileArtifact.body;
1288
+ // Find the character portrait artifact and prepend image markdown
942
1289
  const portraitName = `Portrait - ${characterName}`;
943
1290
  const storyArtifactService = this.getStoryArtifactService(storyId);
944
1291
  const allArtifacts = storyArtifactService.listArtifacts();
945
1292
  const portraitArtifact = allArtifacts.find((a) => a.name === portraitName);
946
1293
  if (portraitArtifact) {
1294
+ // Prepend image markdown to profile content
947
1295
  const imgUrl = `/api/stories/${storyId}/artifacts/${portraitArtifact.artifactId}`;
948
1296
  const imageMarkdown = `![Portrait of ${characterName}](${imgUrl})\n\n`;
949
1297
  content = imageMarkdown + content;
@@ -955,10 +1303,23 @@ let StoryService = class StoryService {
955
1303
  throw new Error(`Error getting character: ${error.message}`);
956
1304
  }
957
1305
  }
1306
+ /**
1307
+ * Saves a character profile (convenience wrapper for PUBLISH action)
1308
+ * @param storyId The story ID
1309
+ * @param characterName The character name
1310
+ * @param content The updated character profile markdown
1311
+ * @returns Success status
1312
+ */
958
1313
  saveCharacter(storyId, characterName, content) {
959
1314
  const artifactName = `Character Profile - ${characterName}`;
960
1315
  this.publishArtifact(storyId, artifactName, characterName, content, []);
961
1316
  }
1317
+ /**
1318
+ * Gets a character's inventory, stored in the owning agent's private context.
1319
+ * @param storyId The story ID
1320
+ * @param characterName The character name
1321
+ * @returns The inventory markdown content, or null if no inventory exists yet
1322
+ */
962
1323
  async getCharacterInventory(storyId, characterName) {
963
1324
  try {
964
1325
  const room = await this.getStoryRoom(storyId);
@@ -970,12 +1331,25 @@ let StoryService = class StoryService {
970
1331
  throw new Error(`Error getting character inventory: ${error.message}`);
971
1332
  }
972
1333
  }
1334
+ /**
1335
+ * Saves a character's inventory to the owning agent's private context. The
1336
+ * inventory stays visible only to the owning character and the Moderator.
1337
+ * @param storyId The story ID
1338
+ * @param characterName The character name
1339
+ * @param content The updated inventory markdown
1340
+ */
973
1341
  async saveCharacterInventory(storyId, characterName, content) {
974
1342
  const room = await this.getStoryRoom(storyId);
975
1343
  this.storeCharacterInventory(room, characterName, content);
976
1344
  }
1345
+ /**
1346
+ * Gets the plot plan artifact content
1347
+ * @param storyId The story ID
1348
+ * @returns The plot plan markdown content
1349
+ */
977
1350
  async getPlotPlan(storyId) {
978
1351
  const room = await this.getStoryRoom(storyId);
1352
+ // Find the plot plan artifact
979
1353
  const artifacts = room.getArtifacts();
980
1354
  const artifact = artifacts.find((a) => a.name === 'Plot Plan');
981
1355
  if (!artifact) {
@@ -983,52 +1357,82 @@ let StoryService = class StoryService {
983
1357
  }
984
1358
  return artifact.body;
985
1359
  }
1360
+ /**
1361
+ * Gets the formatted conversation history for an agent in the story
1362
+ * @param storyId The story ID
1363
+ * @param agentId The agent ID
1364
+ * @returns JSON string of the agent's conversation history
1365
+ */
986
1366
  async getAgentHistory(storyId, agentId) {
987
1367
  const room = await this.getStoryRoom(storyId);
1368
+ // Find the agent by ID
988
1369
  const agent = room.getAgents().find((a) => a.id === agentId);
989
1370
  if (!agent) {
990
1371
  throw new Error(`Agent not found: ${agentId}`);
991
1372
  }
1373
+ // Return the agent's history as JSON string
1374
+ // History is already in the format [{role, content}, ...]
992
1375
  return JSON.stringify(agent.history || []);
993
1376
  }
1377
+ /**
1378
+ * Saves the plot plan (convenience wrapper for PUBLISH action)
1379
+ * @param storyId The story ID
1380
+ * @param content The updated plot plan markdown
1381
+ * @returns Success status
1382
+ */
994
1383
  async savePlotPlan(storyId, content) {
995
1384
  const room = await this.getStoryRoom(storyId);
996
1385
  room.publishArtifact('Plot Plan', 'Narrator', content, []);
997
1386
  }
998
1387
  async publishArtifact(storyId, name, creator, body, viewers) {
1388
+ // Get the story metadata
999
1389
  const room = await this.getStoryRoom(storyId);
1000
1390
  room.publishArtifact(name, creator, body, viewers);
1001
1391
  }
1002
1392
  async respondToStory(storyId, content) {
1393
+ // Get the story metadata
1003
1394
  const room = await this.getStoryRoom(storyId);
1004
1395
  const trimmedContent = content?.trim();
1005
1396
  const isPassing = trimmedContent?.toUpperCase() === 'PASS';
1006
1397
  if (!trimmedContent && !isPassing) {
1007
1398
  throw new Error('No message content provided');
1008
1399
  }
1400
+ // Increment turn number
1009
1401
  const story = this.storyStore.getStory(storyId);
1010
1402
  if (story) {
1011
1403
  story.turnNumber = (story.turnNumber || 0) + 1;
1012
1404
  this.storyStore.updateStoryMetadata(storyId, story);
1013
1405
  }
1406
+ // Find the human-controlled agent
1014
1407
  const humanAgent = room.getAgents().find((agent) => agent.isControlledByHuman);
1015
1408
  if (!humanAgent) {
1016
1409
  throw new Error('No human-controlled agent found in story');
1017
1410
  }
1018
1411
  const responseMessage = new message_1.RoomMessage(humanAgent.agentNickname, app_types_1.MessageAction.MODERATE, content, [], null);
1412
+ // Add the message to the room's pending queue
1413
+ // This triggers processing whether there was an active callback or not
1019
1414
  room.addPendingMessage(responseMessage);
1020
1415
  }
1021
1416
  async interruptStory(storyId) {
1022
1417
  const room = await this.getStoryRoom(storyId);
1023
1418
  room.interrupt();
1024
1419
  }
1420
+ /**
1421
+ * Introduces a new character into an existing story
1422
+ * Creates character agent, updates profile, and notifies narrator
1423
+ * @param latestNarration When introduced by the narrator, the narration
1424
+ * prose that introduced this character. It isn't logged to the room yet,
1425
+ * so it's threaded in to seed the new character's first profile.
1426
+ */
1025
1427
  async introduceCharacter(storyId, characterName, characterDescription, storyModel, fromNarratorSuggestion, latestNarration) {
1428
+ // Load story and room
1026
1429
  const room = await this.getStoryRoom(storyId);
1027
1430
  if (!characterName)
1028
1431
  throw new Error('No character name provided');
1029
1432
  if (characterName === 'Narrator' || characterName === 'Moderator') {
1030
1433
  throw new Error('Cannot introduce a character named Narrator or Moderator');
1031
1434
  }
1435
+ // Check for duplicate name (use nickname for comparison)
1032
1436
  const existingAgent = room.getAgents().find((agent) => {
1033
1437
  const agentFirstNickname = agent.agentNickname.split(/\s+/)[0];
1034
1438
  return agent.agentNickname === characterName || agentFirstNickname === characterName;
@@ -1043,11 +1447,17 @@ let StoryService = class StoryService {
1043
1447
  ? this.getStoryModelConfig(storyModel)
1044
1448
  : null;
1045
1449
  if (explicitConfig) {
1450
+ // An explicit model was requested for this introduction.
1046
1451
  aiServiceName = explicitConfig.service;
1047
1452
  aiModelName = explicitConfig.model;
1048
1453
  aiSmallModelName = explicitConfig.smallModel;
1049
1454
  }
1050
1455
  else {
1456
+ // No explicit model: inherit the story's model from an existing cast member
1457
+ // (a character, or the narrator) so a mid-story introduction matches the
1458
+ // rest of the cast. Falling back to DEFAULT_STORY_MODEL here was wrong — it
1459
+ // is usually a smaller/cheaper model than the one the story was created with,
1460
+ // so narrator-introduced characters ended up running on the wrong model.
1051
1461
  const template = room.getAgents().find((a) => a.promptFolder === 'character') ??
1052
1462
  room.getAgents().find((a) => a.promptFolder === 'narrator');
1053
1463
  if (template) {
@@ -1056,6 +1466,7 @@ let StoryService = class StoryService {
1056
1466
  aiSmallModelName = template.smallModelName;
1057
1467
  }
1058
1468
  else {
1469
+ // Last resort (e.g., no cast loaded): use the default story model.
1059
1470
  const fallback = this.getStoryModelConfig(process.env.DEFAULT_STORY_MODEL);
1060
1471
  if (fallback) {
1061
1472
  aiServiceName = fallback.service;
@@ -1067,21 +1478,35 @@ let StoryService = class StoryService {
1067
1478
  if (!aiServiceName || !aiModelName) {
1068
1479
  throw new Error('Invalid story model provided');
1069
1480
  }
1481
+ // Nullify current speaker while introducing the character
1070
1482
  room.setCurrentSpeaker(null);
1483
+ // Create character agent
1071
1484
  const { agentsDir: storyAgentsDir } = this.getStoryStorageDirs(storyId);
1072
1485
  const storyArtifactService = this.getStoryArtifactService(storyId);
1486
+ // Get story title
1073
1487
  const story = this.storyStore.getStory(storyId);
1074
1488
  const storyTitle = story.name;
1489
+ // Generate nickname (first word of character name)
1075
1490
  const characterNickname = characterName.trim().split(/\s+/)[0];
1076
- const characterAgent = this.agentFactory.createAgent(aiServiceName, `${storyTitle} - ${characterNickname}`, characterNickname, characterDescription, 'character', aiModelName, storyAgentsDir, storyArtifactService);
1491
+ const characterAgent = this.agentFactory.createAgent(aiServiceName, `${storyTitle} - ${characterNickname}`, // Agent name = "[story title] - [nickname]"
1492
+ characterNickname, // Agent nickname = character nickname
1493
+ characterDescription, 'character', // promptFolder for character agents
1494
+ aiModelName, storyAgentsDir, storyArtifactService);
1077
1495
  characterAgent.promptCacheTTL = 60;
1078
1496
  characterAgent.smallModelName = aiSmallModelName;
1079
1497
  characterAgent.save();
1498
+ // Add agent to room
1080
1499
  room.arrive(characterAgent);
1500
+ // Retrieve plot plan so the new character's profile is informed by it
1081
1501
  const introducedCharArtifacts = room.getArtifacts();
1082
1502
  const introducedCharPlotPlanArtifact = introducedCharArtifacts.find((a) => a.name === 'Plot Plan');
1083
1503
  const introducedCharPlotPlan = introducedCharPlotPlanArtifact?.body || '';
1504
+ // Update character profile - this sets characterAgent.description from
1505
+ // the AI-generated profile, which is what we want to persist below.
1084
1506
  await this.updateCharacterProfiles(room, [characterAgent], introducedCharPlotPlan, latestNarration);
1507
+ // Persist the new character in story metadata now that the profile has
1508
+ // been generated (the runtime source of truth is the room's agents, but
1509
+ // metadata is used for markdown export, plot-plan prompts, etc.).
1085
1510
  if (!story.characters) {
1086
1511
  story.characters = [];
1087
1512
  }
@@ -1092,11 +1517,19 @@ let StoryService = class StoryService {
1092
1517
  isControlledByHuman: false,
1093
1518
  });
1094
1519
  }
1520
+ // Clear any pending narrator suggestion for this character
1095
1521
  if (story.pendingSuggestion?.type === 'suggest-introduce-character' &&
1096
1522
  story.pendingSuggestion.characterName === characterName) {
1097
1523
  story.pendingSuggestion = undefined;
1098
1524
  }
1099
1525
  this.storyStore.updateStoryMetadata(storyId, story);
1526
+ // Generate portrait for newly introduced character — but only as a
1527
+ // fallback. updateCharacterProfiles above already regenerates portraits
1528
+ // for characters whose profile changed, and a brand-new character's
1529
+ // profile always changes, so it normally produces the portrait here.
1530
+ // Generating again would create a second image (and double the cost).
1531
+ // Only generate from scratch if that path didn't leave a portrait
1532
+ // (e.g. the profile came back empty and the agent was filtered out).
1100
1533
  const portraitName = `Portrait - ${characterAgent.agentNickname}`;
1101
1534
  const portraitAlreadyExists = this.getStoryArtifactService(storyId)
1102
1535
  .listArtifacts()
@@ -1110,16 +1543,27 @@ let StoryService = class StoryService {
1110
1543
  }
1111
1544
  catch (error) {
1112
1545
  logger_1.logger.error(`Error generating portrait for introduced character ${characterName}:`, error);
1546
+ // Continue even if portrait generation fails
1113
1547
  }
1114
1548
  }
1549
+ // Only send INTRODUCE message if NOT from narrator suggestion
1115
1550
  if (!fromNarratorSuggestion) {
1551
+ // Send instruction to narrator - processing will happen naturally
1552
+ // The moderator will route to narrator, narrator will respond, then it's the human's turn
1116
1553
  room.addPendingMessage(new message_1.RoomMessage('system', app_types_1.MessageAction.MODERATE, `INTRODUCE ${characterName}`));
1117
1554
  }
1118
1555
  else {
1119
1556
  logger_1.logger.log(`Skipping INTRODUCE message for ${characterName} (already introduced by narrator)`);
1557
+ // The narrator already introduced this character, so no MODERATE message is sent.
1558
+ // We must restore currentSpeaker (nullified above) so the human can respond.
1120
1559
  room.setCurrentSpeaker(room.getHumanAgentName());
1121
1560
  }
1122
1561
  }
1562
+ /**
1563
+ * Records that user declined to introduce a character
1564
+ * @param storyId The story ID
1565
+ * @param characterName The character name that was declined
1566
+ */
1123
1567
  async declineCharacter(storyId, characterName) {
1124
1568
  const story = this.storyStore.getStory(storyId);
1125
1569
  if (!story) {
@@ -1138,10 +1582,17 @@ let StoryService = class StoryService {
1138
1582
  }
1139
1583
  this.storyStore.updateStoryMetadata(storyId, story);
1140
1584
  }
1585
+ /**
1586
+ * Deletes a character agent from a story but preserves the character profile artifact
1587
+ * @param storyId The story ID
1588
+ * @param characterName The character name to delete
1589
+ * @returns Success status and message
1590
+ */
1141
1591
  async deleteCharacter(storyId, characterName) {
1142
1592
  let room;
1143
1593
  try {
1144
1594
  room = await this.getStoryRoom(storyId);
1595
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1145
1596
  }
1146
1597
  catch (_error) {
1147
1598
  throw new errors_1.NotFoundError(`Story not found: ${storyId}`);
@@ -1149,20 +1600,27 @@ let StoryService = class StoryService {
1149
1600
  if (!room) {
1150
1601
  throw new errors_1.NotFoundError(`Story not found: ${storyId}`);
1151
1602
  }
1603
+ // Find the agent
1152
1604
  const agent = room.getAgents().find((a) => a.agentNickname === characterName);
1153
1605
  if (!agent) {
1154
1606
  throw new errors_1.NotFoundError(`Character agent not found: ${characterName}`);
1155
1607
  }
1608
+ // Prevent deletion of system agents
1156
1609
  if (characterName === 'Narrator' ||
1157
1610
  characterName === 'Moderator' ||
1158
1611
  agent.isControlledByHuman) {
1159
1612
  throw new errors_1.OperationFailedError(`Cannot delete ${characterName} - system agents and human-controlled characters cannot be removed`);
1160
1613
  }
1614
+ // Remove agent from room
1161
1615
  const agents = room.getAgents();
1162
1616
  const filteredAgents = agents.filter((a) => a.agentNickname !== characterName);
1163
1617
  room.setAgents(filteredAgents);
1164
1618
  room.saveMetadata();
1619
+ // Delete the agent file (removeAgent deletes from store and file)
1165
1620
  this.agentStore.removeAgent(agent.id);
1621
+ // Remove from story metadata characters array. Match on both full name
1622
+ // and nickname since introduced characters store full name while
1623
+ // deletion is keyed by nickname.
1166
1624
  const story = this.storyStore.getStory(storyId);
1167
1625
  if (story?.characters) {
1168
1626
  const filtered = story.characters.filter((c) => {
@@ -1174,14 +1632,19 @@ let StoryService = class StoryService {
1174
1632
  this.storyStore.updateStoryMetadata(storyId, story);
1175
1633
  }
1176
1634
  }
1635
+ // Note: We do NOT delete the character profile artifact - it's preserved
1636
+ // The character profile artifact remains in the artifacts and can be referenced
1177
1637
  }
1178
1638
  async deleteStory(storyId) {
1179
1639
  logger_1.logger.log(`Deleting story ${storyId}...`);
1640
+ // Get story info (may not exist if story creation failed early)
1180
1641
  const story = this.storyStore.getStory(storyId);
1642
+ // Try to clean up the room and its agents if they exist
1181
1643
  if (story?.roomId) {
1182
1644
  try {
1183
1645
  const room = await this.roomStore.getRoom(story.roomId);
1184
1646
  if (room) {
1647
+ // Delete all agents in the room
1185
1648
  const agents = room.getAgents();
1186
1649
  await Promise.all(agents.map(async (agent) => {
1187
1650
  try {
@@ -1205,6 +1668,7 @@ let StoryService = class StoryService {
1205
1668
  else {
1206
1669
  logger_1.logger.warn(`Story ${storyId} has no roomId, skipping room cleanup`);
1207
1670
  }
1671
+ // Try to clean up artist and illustrator agents if they exist
1208
1672
  if (story?.artistAgentId) {
1209
1673
  try {
1210
1674
  this.agentStore.removeAgent(story.artistAgentId);
@@ -1223,6 +1687,7 @@ let StoryService = class StoryService {
1223
1687
  logger_1.logger.warn(`Error deleting illustrator agent ${story.illustratorAgentId}:`, error);
1224
1688
  }
1225
1689
  }
1690
+ // Always clean up progress and message emitters
1226
1691
  try {
1227
1692
  this.cleanupProgressEmitter(storyId);
1228
1693
  this.cleanupMessageEmitter(storyId);
@@ -1230,6 +1695,7 @@ let StoryService = class StoryService {
1230
1695
  catch (error) {
1231
1696
  logger_1.logger.warn(`Error cleaning up emitters for story ${storyId}:`, error);
1232
1697
  }
1698
+ // Always try to remove the story from the store
1233
1699
  try {
1234
1700
  this.storyStore.removeStory(storyId);
1235
1701
  logger_1.logger.log(`Deleted story ${storyId} from store`);
@@ -1239,6 +1705,12 @@ let StoryService = class StoryService {
1239
1705
  }
1240
1706
  logger_1.logger.log(`Story ${storyId} deletion complete`);
1241
1707
  }
1708
+ /**
1709
+ * Helper function to disable markup and balance checks for story agents
1710
+ * Used during story creation, chapter progression, and compaction
1711
+ * @param agents Array of agents to disable flags for
1712
+ * @param reason Optional reason for logging (e.g., "story creation", "chapter progression")
1713
+ */
1242
1714
  disableStoryAgentFlags(agents, reason = 'operation') {
1243
1715
  for (const agent of agents) {
1244
1716
  if (agent && !agent.disableMarkup && !agent.disableBalanceCheck) {
@@ -1249,6 +1721,12 @@ let StoryService = class StoryService {
1249
1721
  }
1250
1722
  }
1251
1723
  }
1724
+ /**
1725
+ * Helper function to re-enable markup and balance checks for story agents
1726
+ * Used after story creation, chapter progression, and compaction complete
1727
+ * @param agents Array of agents to re-enable flags for
1728
+ * @param reason Optional reason for logging (e.g., "story creation", "chapter progression")
1729
+ */
1252
1730
  enableStoryAgentFlags(agents, reason = 'operation') {
1253
1731
  for (const agent of agents) {
1254
1732
  if (agent && (agent.disableMarkup || agent.disableBalanceCheck)) {
@@ -1259,17 +1737,27 @@ let StoryService = class StoryService {
1259
1737
  }
1260
1738
  }
1261
1739
  }
1740
+ /**
1741
+ * Compacts the conversation history for all agents in a story
1742
+ * Uses story-specific prompts tailored for narrator (plot events) and characters (relationships)
1743
+ * Processes all agents in parallel for better performance
1744
+ * @param storyId The story ID
1745
+ * @returns Success status, message, and details about compaction
1746
+ */
1262
1747
  async compactStory(storyId) {
1263
1748
  let agents = [];
1264
1749
  try {
1265
1750
  const room = await this.getStoryRoom(storyId);
1751
+ // Get all agents in the room
1266
1752
  agents = room.getAgents();
1267
1753
  if (agents.length === 0) {
1268
1754
  throw new Error('No agents in story room');
1269
1755
  }
1270
1756
  logger_1.logger.log(`Compacting ${agents.length} agents in parallel`);
1757
+ // Disable markup and balance checks during compaction
1271
1758
  const agentsToCompact = agents.filter(agent => agent !== room.getModeratorAgent());
1272
1759
  this.disableStoryAgentFlags(agentsToCompact, 'compaction');
1760
+ // Compact all agents in parallel
1273
1761
  const compactionPromises = agents.map(async (agent) => {
1274
1762
  if (agent === room.getModeratorAgent()) {
1275
1763
  agent.history = [];
@@ -1283,6 +1771,7 @@ let StoryService = class StoryService {
1283
1771
  logger_1.logger.error(`Error compacting ${agent.agentName}:`, error);
1284
1772
  }
1285
1773
  });
1774
+ // Execute all compactions in parallel
1286
1775
  await Promise.all(compactionPromises);
1287
1776
  logger_1.logger.log(`Finished compacting ${agents.length} agents in parallel`);
1288
1777
  return { success: true };
@@ -1292,41 +1781,65 @@ let StoryService = class StoryService {
1292
1781
  return { success: false, message: error.message };
1293
1782
  }
1294
1783
  finally {
1784
+ // Always re-enable flags after compaction
1295
1785
  if (agents.length > 0) {
1296
1786
  this.enableStoryAgentFlags(agents, 'compaction');
1297
1787
  }
1298
1788
  }
1299
1789
  }
1790
+ /**
1791
+ * Progresses a story to the next chapter by:
1792
+ * 1. Updating the Plot Plan artifact based on recent story events
1793
+ * 2. Updating all Character Profile artifacts based on character development
1794
+ * 3. Creating a new chapter folder with the next chapter index
1795
+ * 4. Backing up the current room messages to the new chapter folder
1796
+ * 5. Compacting the story conversation history in place
1797
+ * 6. Clearing all room messages to start fresh for the next chapter
1798
+ * @param storyId The story ID
1799
+ * @returns Result with success status, chapter index, and compaction details
1800
+ */
1300
1801
  async progressStoryToNextChapter(storyId) {
1802
+ // Validate story exists
1301
1803
  const story = await this.ensureStoryLoaded(storyId);
1302
1804
  if (!story) {
1303
1805
  throw new Error('Story not found');
1304
1806
  }
1807
+ // Reject concurrent progression. Two calls would double-backup the chapter,
1808
+ // emit duplicate progress events, and call updatePlotPlan twice.
1305
1809
  if (this.chaptersInProgress.has(storyId)) {
1306
1810
  throw new errors_1.OperationFailedError('Chapter progression is already in progress for this story');
1307
1811
  }
1308
1812
  this.chaptersInProgress.add(storyId);
1309
1813
  try {
1814
+ // Clear any pending progress-chapter suggestion now that the player is acting on it
1310
1815
  if (story.pendingSuggestion?.type === 'suggest-progress-chapter') {
1311
1816
  story.pendingSuggestion = undefined;
1312
1817
  this.storyStore.updateStoryMetadata(storyId, story);
1313
1818
  }
1819
+ // Check if already progressing
1314
1820
  const existingEmitter = this.progressService.getProgressEmitter(storyId);
1315
1821
  if (!existingEmitter) {
1316
1822
  this.progressService.createProgressEmitter(storyId);
1317
1823
  }
1318
1824
  const room = await this.getStoryRoom(storyId);
1319
1825
  room.setCurrentSpeaker('system');
1826
+ // Generate opening scene and get chapter title for PREVIOUS chapter
1320
1827
  this.progressService.emitProgress(storyId, 'opening-scene', 'Generating opening scene of chapter...');
1321
1828
  const agents = room.getAgents();
1322
1829
  const narrator = agents.find((agent) => agent.promptFolder === 'narrator');
1323
1830
  const { openingScene, chapterTitle, preamble } = await this.generateOpeningScene(room, narrator);
1831
+ // Now save the PREVIOUS chapter with its generated title
1324
1832
  this.progressService.emitProgress(storyId, 'chapter-backup', `Saving previous chapter: "${chapterTitle}"...`);
1325
1833
  const chapterIndex = this.storyStore.getNextChapterIndex(storyId);
1326
1834
  const backupSuccess = this.storyStore.createChapterBackup(storyId, chapterIndex, chapterTitle);
1327
1835
  if (!backupSuccess) {
1328
1836
  throw new Error('Failed to backup chapter');
1329
1837
  }
1838
+ // The room's situation is still the end of the chapter just backed up. Move
1839
+ // it to the new chapter's before anything reads it - the moderator treats it
1840
+ // as authoritative about who is present, and the first thing it does with it
1841
+ // is decide who hears the opening scene. After the backup, so the snapshot
1842
+ // stays a picture of the chapter that ended.
1330
1843
  const openingSituation = this.parseNarratorPreamble(preamble);
1331
1844
  if (openingSituation.situation) {
1332
1845
  room.setSituation(openingSituation.situation);
@@ -1338,8 +1851,10 @@ let StoryService = class StoryService {
1338
1851
  const audience = openingSituation.situation
1339
1852
  ? await this.moderateOpeningSceneAudience(room, openingScene)
1340
1853
  : null;
1854
+ // Clear room messages and populate with opening scene
1341
1855
  room.clearRoomMessages();
1342
1856
  this.populateStoryHistory(room, openingScene, audience ?? undefined);
1857
+ // Set human agent as the current speaker-chapter is ready for their response
1343
1858
  const humanAgent = room.getAgents().find((a) => a.isControlledByHuman);
1344
1859
  if (humanAgent) {
1345
1860
  room.setCurrentSpeaker(humanAgent.agentNickname);
@@ -1358,10 +1873,29 @@ let StoryService = class StoryService {
1358
1873
  return { chapterIndex };
1359
1874
  }
1360
1875
  catch (err) {
1876
+ // Sync phase threw - async worker never started, so clean up here.
1361
1877
  this.chaptersInProgress.delete(storyId);
1362
1878
  throw err;
1363
1879
  }
1364
1880
  }
1881
+ /**
1882
+ * Reverts the most recent chapter progression. Restores the previous
1883
+ * chapter's room messages, artifacts, and agent histories from the
1884
+ * `chapters/chapter_N/` backup, then deletes that backup so the story
1885
+ * is back to exactly the state it was in before the player clicked
1886
+ * Next Chapter.
1887
+ *
1888
+ * Only valid when the current chapter has not been played yet - i.e.
1889
+ * the only room message is the Opening Scene. The endpoint also requires
1890
+ * at least one chapter backup to exist.
1891
+ *
1892
+ * Token counts and cost totals are not rolled back (those tokens were
1893
+ * actually consumed), matching `resetStory` semantics.
1894
+ *
1895
+ * @throws {NotFoundError} If the story or its room does not exist
1896
+ * @throws {OperationFailedError} If no previous chapter exists, or the
1897
+ * chapter has already been played past the opening scene.
1898
+ */
1365
1899
  async revertStoryChapter(storyId) {
1366
1900
  const story = this.storyStore.getStory(storyId);
1367
1901
  if (!story || !story.roomId) {
@@ -1405,6 +1939,11 @@ let StoryService = class StoryService {
1405
1939
  }
1406
1940
  logger_1.logger.log(`Reverted story ${storyId} to chapter ${targetChapter} (${restoredMessages?.length ?? 0} messages, ${restoredArtifacts.length} artifacts)`);
1407
1941
  }
1942
+ /**
1943
+ * Performs the actual chapter progression work asynchronously
1944
+ * Phase 1: Quick opening scene generation (user-visible, 5-10s)
1945
+ * Phase 2: Background processing (plot, profiles, compaction, 20-50s)
1946
+ */
1408
1947
  async progressStoryToNextChapterAsync(storyId) {
1409
1948
  let room = null;
1410
1949
  let agents = [];
@@ -1415,6 +1954,7 @@ let StoryService = class StoryService {
1415
1954
  agents = room.getAgents();
1416
1955
  narrator = agents.find((agent) => agent.promptFolder === 'narrator');
1417
1956
  characterAgents = agents.filter((agent) => agent.promptFolder === 'character');
1957
+ // Enable chapter progression flags for narrator and characters
1418
1958
  if (narrator) {
1419
1959
  narrator.disableMarkup = true;
1420
1960
  narrator.disableBalanceCheck = true;
@@ -1426,16 +1966,20 @@ let StoryService = class StoryService {
1426
1966
  agent.disableBalanceCheck = true;
1427
1967
  agent.save();
1428
1968
  }
1969
+ // Update plot plan first, then character profiles (characters need the new plot plan)
1429
1970
  this.progressService.emitProgress(storyId, 'profiles', 'Updating plot plan and character profiles...');
1430
1971
  const skipDetailedPlot = this.storyStore.getStory(storyId)?.skipDetailedPlot ?? false;
1431
1972
  const updatedPlotPlan = await this.updatePlotPlan(room, narrator, skipDetailedPlot);
1432
1973
  await this.updateCharacterProfiles(room, characterAgents, updatedPlotPlan);
1974
+ // Update story cost
1433
1975
  await this.updateStoryCost(storyId);
1976
+ // Signal opening scene is ready
1977
+ // Final completion event
1434
1978
  this.progressService.emitProgress(storyId, 'complete', 'Chapter progression complete!');
1435
1979
  }
1436
1980
  catch (error) {
1437
1981
  logger_1.logger.error('Error in async chapter progression:', error);
1438
- throw error;
1982
+ throw error; // Caught by outer handler
1439
1983
  }
1440
1984
  finally {
1441
1985
  if (room) {
@@ -1444,22 +1988,33 @@ let StoryService = class StoryService {
1444
1988
  }
1445
1989
  }
1446
1990
  }
1991
+ /**
1992
+ * Generates the opening scene for a new chapter and a title for the previous chapter
1993
+ * Uses create_chapter prompt which returns the title on the first line (with a #
1994
+ * prefix), then the same `<time>`/`<situation>` preamble a narration carries, then
1995
+ * the opening scene.
1996
+ */
1447
1997
  async generateOpeningScene(room, narrator) {
1448
1998
  const artifacts = room.getArtifacts();
1449
1999
  const plotPlanArtifact = artifacts.find((a) => a.name === 'Plot Plan');
1450
2000
  const currentPlotPlan = plotPlanArtifact?.body || 'No plot plan found.';
1451
2001
  const formattedHistory = narrator.getRawMessages();
2002
+ // Call AI with create_chapter prompt
1452
2003
  const aiResponse = await narrator.preparedPrompt('create_chapter', {
1453
2004
  currentPlotPlan: currentPlotPlan,
1454
2005
  formattedHistory: formattedHistory || 'No recent events...',
1455
2006
  }, false);
2007
+ // Parse the response - first line should have chapter title with # prefix
1456
2008
  const lines = aiResponse.split('\n');
1457
- let chapterTitle = 'Untitled Chapter';
2009
+ let chapterTitle = 'Untitled Chapter'; // Default if not found
1458
2010
  let openingScene = aiResponse;
2011
+ // Check if first line starts with #
1459
2012
  if (lines.length > 0 && lines[0].trim().startsWith('#')) {
1460
- chapterTitle = lines[0].trim().substring(1).trim();
1461
- openingScene = lines.slice(1).join('\n').trim();
2013
+ chapterTitle = lines[0].trim().substring(1).trim(); // Remove # and whitespace
2014
+ openingScene = lines.slice(1).join('\n').trim(); // Rest is the opening scene
1462
2015
  }
2016
+ // The tags sit below the title, so the title has to come off before the same
2017
+ // peeling a narration gets can find them.
1463
2018
  const parsed = room_1.Room.extractPreamble(openingScene);
1464
2019
  return {
1465
2020
  openingScene: parsed ? parsed.content : openingScene,
@@ -1467,6 +2022,22 @@ let StoryService = class StoryService {
1467
2022
  preamble: parsed ? parsed.preamble : '',
1468
2023
  };
1469
2024
  }
2025
+ /**
2026
+ * Asks the moderator which characters are present for the opening scene of a
2027
+ * new chapter.
2028
+ *
2029
+ * A chapter opening does not go through the room's message loop - it is written
2030
+ * before the chapter exists and seeded straight into history - so nothing has
2031
+ * decided its audience. Without this every character hears it, including the ones
2032
+ * the narrator left several days' travel away.
2033
+ *
2034
+ * Requires the room's situation to already be the new chapter's, since that is
2035
+ * what the moderator treats as authoritative about who is present.
2036
+ *
2037
+ * @returns The nicknames who may hear the opening scene, or null if the moderator
2038
+ * could not be reached or named nobody - in which case the caller should seed
2039
+ * every agent rather than silently narrate to an empty room.
2040
+ */
1470
2041
  async moderateOpeningSceneAudience(room, openingScene) {
1471
2042
  const moderator = room.getModeratorAgent();
1472
2043
  const narrator = room.getAgents().find((a) => a.promptFolder === 'narrator');
@@ -1485,6 +2056,12 @@ let StoryService = class StoryService {
1485
2056
  return null;
1486
2057
  }
1487
2058
  }
2059
+ /**
2060
+ * Compacts every agent whose history has outgrown the threshold, in parallel.
2061
+ * The threshold and the exemption for windowed agents live on `Agent`, so a
2062
+ * story and a room agree on when a history has grown too long.
2063
+ * @param agents The agents to consider
2064
+ */
1488
2065
  async compactAgentHistories(agents) {
1489
2066
  await Promise.all(agents.map(async (agent) => {
1490
2067
  if (!agent.needsCompaction())
@@ -1499,6 +2076,7 @@ let StoryService = class StoryService {
1499
2076
  }));
1500
2077
  }
1501
2078
  extractMarkdownContent(response) {
2079
+ // Strip any preamble text and pull content from inside a ```markdown ... ``` fence if present
1502
2080
  const fenceMatch = response.match(/```(?:markdown)?\s*\n([\s\S]*?)```/);
1503
2081
  if (fenceMatch) {
1504
2082
  return fenceMatch[1].trim();
@@ -1506,15 +2084,23 @@ let StoryService = class StoryService {
1506
2084
  return response.trim();
1507
2085
  }
1508
2086
  async updatePlotPlan(room, narrator, skipDetailedPlot = false) {
2087
+ // Get the current Plot Plan artifact
1509
2088
  const artifacts = room.getArtifacts();
1510
2089
  const plotPlanArtifact = artifacts.find((a) => a.name === 'Plot Plan');
1511
2090
  const currentPlotPlan = plotPlanArtifact ? plotPlanArtifact.body : 'No plot plan found.';
2091
+ // Re-enable web search just for the plot-plan call. It's globally
2092
+ // disabled at the start of progressStoryToNextChapterAsync because the
2093
+ // main story model is too slow with search; the smaller model used by
2094
+ // withSmallModel makes search affordable here.
1512
2095
  const previousAllowSearch = narrator.allowSearch;
1513
2096
  narrator.allowSearch = true;
1514
2097
  try {
2098
+ // Call the AI to update the plot plan. The narrator's conversation
2099
+ // history is already sent natively, so we don't pass formattedHistory.
1515
2100
  const progressPlotResponse = await narrator.withSmallModel(() => narrator.preparedPrompt(skipDetailedPlot ? 'progress_simple_plot' : 'progress_plot', {
1516
2101
  currentPlotPlan: currentPlotPlan,
1517
2102
  }, false));
2103
+ // Publish the updated Plot Plan as an artifact (visible only to narrator)
1518
2104
  if (progressPlotResponse) {
1519
2105
  const cleanedPlotPlan = this.extractMarkdownContent(progressPlotResponse);
1520
2106
  room.publishArtifact('Plot Plan', narrator.agentNickname, cleanedPlotPlan, [
@@ -1526,12 +2112,24 @@ let StoryService = class StoryService {
1526
2112
  }
1527
2113
  catch (error) {
1528
2114
  logger_1.logger.error(`Error updating plot plan:`, error);
2115
+ // Don't throw - allow other background operations to continue
1529
2116
  }
1530
2117
  finally {
1531
2118
  narrator.allowSearch = previousAllowSearch;
1532
2119
  }
1533
2120
  return '';
1534
2121
  }
2122
+ /**
2123
+ * Stores a character's inventory in the owning agent's private context. The
2124
+ * inventory is therefore visible only to that character (injected into its own
2125
+ * transient prompt) and, in aggregate, to the Moderator — never to other
2126
+ * characters. Storing it on the agent rather than in a room artifact keeps the
2127
+ * frequently-changing inventory out of the cached system instructions.
2128
+ *
2129
+ * @param room The story room
2130
+ * @param characterNickname The owning character's nickname
2131
+ * @param body Markdown body of the inventory (typically '## Items' and optional '## Conditions' sections)
2132
+ */
1535
2133
  storeCharacterInventory(room, characterNickname, body) {
1536
2134
  const agent = room
1537
2135
  .getAgents()
@@ -1544,6 +2142,13 @@ let StoryService = class StoryService {
1544
2142
  agent.save();
1545
2143
  logger_1.logger.log(`Stored inventory for ${characterNickname}`);
1546
2144
  }
2145
+ /**
2146
+ * Reads changes.update_inventory off a moderator response and rewrites each
2147
+ * named character's stored inventory. Silently no-ops if no updates.
2148
+ *
2149
+ * @param room The story room
2150
+ * @param moderatorMessage The moderator's RoomMessage (with .changes populated)
2151
+ */
1547
2152
  applyInventoryUpdates(room, moderatorMessage) {
1548
2153
  const updates = moderatorMessage.changes?.update_inventory ?? [];
1549
2154
  if (!Array.isArray(updates) || updates.length === 0)
@@ -1558,36 +2163,74 @@ let StoryService = class StoryService {
1558
2163
  this.storeCharacterInventory(room, characterName, inventory);
1559
2164
  }
1560
2165
  }
2166
+ /**
2167
+ * Helper method to update all character profiles based on story progression
2168
+ * Processes all characters in parallel for better performance
2169
+ * @param room The story room
2170
+ * @param characterAgents Array of character agents (excluding narrator)
2171
+ * @returns Update result with details for each character
2172
+ */
1561
2173
  async updateCharacterProfiles(room, characterAgents, plotPlan = '', latestNarration) {
2174
+ // Get the room's artifacts once to avoid repeated access
1562
2175
  const artifacts = room.getArtifacts();
2176
+ // Roster of every story character with their visible (observable)
2177
+ // description. Passed to introduce_character so a newly-introduced
2178
+ // character can be told what the characters they're interacting with
2179
+ // look like, even when they don't yet know names or backstories.
1563
2180
  const characterRoster = room
1564
2181
  .getAgents()
1565
2182
  .filter((a) => a.promptFolder === 'character')
1566
2183
  .map((a) => ({ name: a.agentNickname, description: a.description || '' }));
2184
+ // Create promises for all character profile updates. Each resolves to
2185
+ // the agent if its profile actually changed (so we only regenerate
2186
+ // portraits for those), or null if it was left unchanged / errored.
1567
2187
  const updatePromises = characterAgents.map(async (character) => {
1568
2188
  try {
2189
+ // Get the current character profile artifact
1569
2190
  const profileArtifact = artifacts.find((a) => a.name === `Character Profile - ${character.agentNickname}`);
1570
2191
  const currentProfile = profileArtifact ? profileArtifact.body : null;
2192
+ // Bootstrap case: a brand-new character with no native history
2193
+ // (e.g., just introduced via room.arrive) needs the existing room
2194
+ // messages so its first profile is consistent with what the
2195
+ // narrator and other characters have already said. We do NOT
2196
+ // write those messages into the character's own history because
2197
+ // that would leak knowledge the character should not yet have.
2198
+ // In steady state the character's native conversation history
2199
+ // is sent natively by textPrompt, so formattedHistory stays empty.
1571
2200
  let formattedHistory = [];
1572
2201
  const hasNativeHistory = (character.history?.length ?? 0) > 0;
1573
2202
  if (!hasNativeHistory) {
1574
2203
  formattedHistory = room
1575
2204
  .getLatestRoomMessages(0, true)
1576
2205
  .map((m) => `${m.sender}: ${m.content}\n`);
2206
+ // The narration that introduced this character is processed
2207
+ // before it is logged to the room, so it won't appear in the
2208
+ // messages above. Append it explicitly so the new character's
2209
+ // first profile reflects the scene they were introduced into.
1577
2210
  if (latestNarration) {
1578
2211
  formattedHistory.push(`${room.getRoomLeader()}: ${latestNarration}\n`);
1579
2212
  }
1580
2213
  }
2214
+ // A character with no profile yet was introduced mid-story:
2215
+ // use the lightweight introduce_character prompt, which only
2216
+ // generates a brief role/knowledge/personality profile, instead
2217
+ // of the full progress_character treatment.
1581
2218
  const profilePromptName = currentProfile
1582
2219
  ? 'progress_character'
1583
2220
  : 'introduce_character';
2221
+ // Call the AI to update the character profile
1584
2222
  const progressCharacterResponse = await character.withSmallModel(() => character.preparedPrompt(profilePromptName, {
1585
2223
  agentName: character.agentNickname,
1586
2224
  currentProfile: currentProfile,
1587
2225
  formattedHistory: formattedHistory,
1588
2226
  plotPlan,
2227
+ // Every other story character and their visible
2228
+ // description (used by introduce_character).
1589
2229
  otherCharacters: characterRoster.filter((c) => c.name !== character.agentNickname),
1590
2230
  }, false));
2231
+ // progress_character returns no_changes when the character was
2232
+ // not significantly affected by recent events. Leave the
2233
+ // existing profile, inventory, and portrait untouched.
1591
2234
  if (progressCharacterResponse.no_changes ||
1592
2235
  !progressCharacterResponse.character_profile) {
1593
2236
  logger_1.logger.log(`No profile changes needed for ${character.agentNickname}; leaving profile unchanged`);
@@ -1608,8 +2251,11 @@ let StoryService = class StoryService {
1608
2251
  return null;
1609
2252
  }
1610
2253
  });
2254
+ // Execute all profile updates in parallel; keep only the characters
2255
+ // whose profiles actually changed so we don't regenerate every portrait.
1611
2256
  const changedAgents = (await Promise.all(updatePromises)).filter((agent) => agent !== null);
1612
2257
  logger_1.logger.log(`Updated ${changedAgents.length} of ${characterAgents.length} character profiles in parallel`);
2258
+ // Update portraits for all characters using the edit artist
1613
2259
  const pathParts = room.getStorageDir().split(path.sep);
1614
2260
  const storiesIndex = pathParts.findIndex((p) => p === 'stories');
1615
2261
  const storyId = storiesIndex >= 0 ? pathParts[storiesIndex + 1] : null;
@@ -1617,6 +2263,7 @@ let StoryService = class StoryService {
1617
2263
  logger_1.logger.error('Could not extract story ID from room path; skipping portrait updates');
1618
2264
  }
1619
2265
  else {
2266
+ // Only regenerate portraits for characters whose profiles changed.
1620
2267
  const portraitPromises = changedAgents.map(async (characterAgent) => {
1621
2268
  try {
1622
2269
  const artifactId = await this.updateCharacterPortrait(room, characterAgent, storyId);
@@ -1635,123 +2282,20 @@ let StoryService = class StoryService {
1635
2282
  logger_1.logger.log(`Updated portraits for ${changedAgents.length} characters`);
1636
2283
  }
1637
2284
  }
1638
- getImageModelConfig(modelName, variant = 'generation') {
1639
- try {
1640
- if (!modelName) {
1641
- return null;
1642
- }
1643
- const imageModelsPath = path.join(this.userPaths.getCommonConfigDir(), 'image_models.json');
1644
- const imageModels = JSON.parse(fs.readFileSync(imageModelsPath, 'utf8'));
1645
- const entry = imageModels.find((m) => m.name === modelName);
1646
- if (!entry) {
1647
- logger_1.logger.warn(`Image model not found: ${modelName}`);
1648
- return null;
1649
- }
1650
- const variantConfig = entry[variant];
1651
- if (!variantConfig || !variantConfig.service || !variantConfig.model) {
1652
- logger_1.logger.log(`No ${variant} model for "${modelName}" (images disabled)`);
1653
- return null;
1654
- }
1655
- return {
1656
- service: variantConfig.service,
1657
- model: variantConfig.model,
1658
- };
1659
- }
1660
- catch (error) {
1661
- logger_1.logger.error('Error loading image model config:', error);
1662
- return null;
1663
- }
1664
- }
1665
- getImagePropertiesForAgent(agent) {
1666
- try {
1667
- const imageModelsPath = path.join(this.userPaths.getCommonConfigDir(), 'image_models.json');
1668
- const imageModels = JSON.parse(fs.readFileSync(imageModelsPath, 'utf8'));
1669
- const isEditAgent = (agent.agentNickname ?? '').toLowerCase().includes('edit');
1670
- const preferred = isEditAgent ? 'editing' : 'generation';
1671
- const fallback = isEditAgent ? 'generation' : 'editing';
1672
- const findVariant = (variant) => {
1673
- const entry = imageModels.find((m) => m[variant]?.model === agent.modelName);
1674
- return entry ? entry[variant] : null;
1675
- };
1676
- const variantConfig = findVariant(preferred) ?? findVariant(fallback);
1677
- if (!variantConfig) {
1678
- logger_1.logger.warn(`No image_models.json entry for "${agent.modelName}"; image generation may fail`);
1679
- return {};
1680
- }
1681
- return {
1682
- ...(variantConfig.imageProperties ?? {}),
1683
- ...(variantConfig.centsPerImage != null
1684
- ? { centsPerImage: variantConfig.centsPerImage }
1685
- : {}),
1686
- };
1687
- }
1688
- catch (error) {
1689
- logger_1.logger.error('Error loading image properties for agent:', error);
1690
- return {};
1691
- }
1692
- }
1693
- createArtistAgent(storyId, storyAgentsDir, storyArtifactService, imageModelName, nickname = 'Artist', variant = 'generation') {
1694
- const storyInfo = this.storyStore.getStory(storyId);
1695
- const imageConfig = this.getImageModelConfig(imageModelName, variant);
1696
- if (!imageConfig) {
1697
- logger_1.logger.log(`Artist agent creation skipped (${nickname}): images disabled`);
1698
- return null;
1699
- }
1700
- const artistAgent = this.agentFactory.createAgent(imageConfig.service, `${storyInfo.name} - ${nickname}`, nickname, 'AI artist for generating character portraits and scene illustrations', 'default', imageConfig.model, storyAgentsDir, storyArtifactService);
1701
- artistAgent.maxHistoryMessages = 10;
1702
- artistAgent.promptCacheTTL = 0;
1703
- artistAgent.save();
1704
- logger_1.logger.log(`Created artist agent: ${artistAgent.agentName} (${imageConfig.service}/${imageConfig.model})`);
1705
- return artistAgent;
1706
- }
2285
+ /**
2286
+ * Generates portrait image for a character
2287
+ * @param room The story room
2288
+ * @param characterAgent The character agent
2289
+ * @param storyId The story ID
2290
+ * @returns Promise resolving to the artifact ID of the generated image, or null on failure
2291
+ */
1707
2292
  async generateCharacterPortrait(room, characterAgent, storyId) {
1708
2293
  const artifacts = room.getArtifacts();
1709
2294
  const profileArtifact = artifacts.find((a) => a.name === `Character Profile - ${characterAgent.agentNickname}`);
1710
2295
  const storyInfo = this.storyStore.getStory(storyId);
1711
2296
  const character = storyInfo.characters.find((c) => c.name === characterAgent.agentNickname);
1712
2297
  const characterProfile = profileArtifact?.body || character?.description || '';
1713
- return this.generatePortraitForName(storyId, characterAgent.agentNickname, characterProfile, characterAgent);
1714
- }
1715
- async generatePortraitForName(storyId, characterName, characterProfile, promptAgent) {
1716
- try {
1717
- if (!characterProfile) {
1718
- logger_1.logger.warn(`No profile for ${characterName}, skipping portrait`);
1719
- return null;
1720
- }
1721
- const storyInfo = this.storyStore.getStory(storyId);
1722
- const scenario = storyInfo?.scenario || '';
1723
- const storyArtifactService = this.getStoryArtifactService(storyId);
1724
- const artistAgent = await this.agentStore.getAgent(storyInfo.artistAgentId);
1725
- if (!artistAgent) {
1726
- logger_1.logger.warn(`Artist agent not found: ${storyInfo.artistAgentId}`);
1727
- return null;
1728
- }
1729
- artistAgent.artifactService = storyArtifactService;
1730
- const describeAgent = promptAgent || artistAgent;
1731
- const visualDescription = await describeAgent.preparedPrompt('describe_character', {
1732
- characterName,
1733
- characterProfile,
1734
- scenario,
1735
- }, false);
1736
- if (!visualDescription || typeof visualDescription !== 'string') {
1737
- logger_1.logger.warn(`Failed to generate visual description for ${characterName}`);
1738
- return null;
1739
- }
1740
- const imageResult = await artistAgent.generateImage(visualDescription, this.getImagePropertiesForAgent(artistAgent));
1741
- if (imageResult.error) {
1742
- return null;
1743
- }
1744
- artistAgent.save();
1745
- const artifactId = imageResult.artifactId;
1746
- storyArtifactService.renameArtifact(artifactId, `Portrait - ${characterName}`);
1747
- storyArtifactService.updateArtifactDescription(artifactId, visualDescription);
1748
- logger_1.logger.log(`Generated portrait for ${characterName}: ${artifactId}`);
1749
- return artifactId;
1750
- }
1751
- catch (error) {
1752
- logger_1.logger.error(`Error generating portrait for ${characterName}:`, error);
1753
- return null;
1754
- }
2298
+ return this.illustration.portrait(this.illustrationTarget(storyId), characterAgent.agentNickname, characterProfile, room, characterAgent);
1755
2299
  }
1756
2300
  async updateCharacterPortrait(room, characterAgent, storyId, updateDescription = false) {
1757
2301
  try {
@@ -1765,43 +2309,50 @@ let StoryService = class StoryService {
1765
2309
  logger_1.logger.warn(`No profile for ${characterAgent.agentNickname}, skipping appearance update`);
1766
2310
  return null;
1767
2311
  }
1768
- const storyArtifactService = this.getStoryArtifactService(storyId);
1769
- const artistEditAgent = storyInfo.artistEditAgentId
1770
- ? await this.agentStore.getAgent(storyInfo.artistEditAgentId)
1771
- : null;
1772
- const hasArtist = !!artistEditAgent;
1773
- if (artistEditAgent) {
1774
- artistEditAgent.artifactService = storyArtifactService;
1775
- }
2312
+ const target = this.illustrationTarget(storyId);
2313
+ // The edit artist may be absent when images are disabled for this story.
2314
+ const hasArtist = !!storyInfo.artistEditAgentId;
2315
+ // When we don't need to refresh the description and there's no
2316
+ // artist, there is nothing to do — bail before spending any tokens.
1776
2317
  if (!updateDescription && !hasArtist) {
1777
2318
  logger_1.logger.warn(`No edit artist configured for story ${storyId}, skipping portrait update`);
1778
2319
  return null;
1779
2320
  }
1780
- const portraitName = `Portrait - ${characterAgent.agentNickname}`;
1781
- const existingPortrait = hasArtist
1782
- ? storyArtifactService.listArtifacts().find((a) => a.name === portraitName)
1783
- : undefined;
2321
+ const existingPortrait = hasArtist && this.illustration.hasPortrait(target, characterAgent.agentNickname);
2322
+ // Fast path: image-only update (e.g. chapter progression) where the
2323
+ // character has no portrait yet — generate one from scratch without
2324
+ // running the update_portrait prompt.
1784
2325
  if (!updateDescription && hasArtist && !existingPortrait) {
1785
2326
  logger_1.logger.warn(`No existing portrait for ${characterAgent.agentNickname}, generating from scratch`);
1786
2327
  return this.generateCharacterPortrait(room, characterAgent, storyId);
1787
2328
  }
2329
+ // Ask the character to describe how they look now. This yields both
2330
+ // the image-editing prompt and a short observable description.
1788
2331
  const portraitResponse = await characterAgent.preparedPrompt('update_portrait', {
1789
2332
  characterName: characterAgent.agentNickname,
1790
2333
  characterProfile: characterDescription,
1791
2334
  currentDescription: characterAgent.description || '',
1792
2335
  scenario: scenario,
1793
2336
  }, false);
2337
+ // Refresh the agent's short observable description so it stays in
2338
+ // sync with the changed appearance. Other prompts (the identity
2339
+ // block, the introduce_character roster, moderator routing) read
2340
+ // this. Done regardless of whether images are generated.
1794
2341
  if (updateDescription &&
1795
2342
  portraitResponse?.description &&
1796
2343
  typeof portraitResponse.description === 'string') {
1797
2344
  characterAgent.description = portraitResponse.description;
1798
2345
  characterAgent.save();
2346
+ // Keep the story metadata copy in sync (used by markdown export
2347
+ // and as the portrait-generation fallback when no profile
2348
+ // artifact exists).
1799
2349
  if (character) {
1800
2350
  character.description = portraitResponse.description;
1801
2351
  this.storyStore.updateStoryMetadata(storyId, storyInfo);
1802
2352
  }
1803
2353
  logger_1.logger.log(`Updated appearance description for ${characterAgent.agentNickname}`);
1804
2354
  }
2355
+ // No artist → description-only update is complete.
1805
2356
  if (!hasArtist) {
1806
2357
  return null;
1807
2358
  }
@@ -1810,229 +2361,24 @@ let StoryService = class StoryService {
1810
2361
  logger_1.logger.warn(`Failed to generate update description for ${characterAgent.agentNickname}`);
1811
2362
  return null;
1812
2363
  }
2364
+ // Artist exists but no portrait yet (only reachable when also
2365
+ // updating the description) — generate from scratch.
1813
2366
  if (!existingPortrait) {
1814
2367
  logger_1.logger.warn(`No existing portrait for ${characterAgent.agentNickname}, generating from scratch`);
1815
2368
  return this.generateCharacterPortrait(room, characterAgent, storyId);
1816
2369
  }
1817
- const imageResult = await artistEditAgent.editImage(visualDescription, this.getImagePropertiesForAgent(artistEditAgent), [existingPortrait.artifactId]);
1818
- if (imageResult.error) {
1819
- return null;
1820
- }
1821
- storyArtifactService.deleteArtifact(existingPortrait.artifactId);
1822
- artistEditAgent.save();
1823
- const artifactId = imageResult.artifactId;
1824
- storyArtifactService.renameArtifact(artifactId, portraitName);
1825
- storyArtifactService.updateArtifactDescription(artifactId, visualDescription);
1826
- logger_1.logger.log(`Updated portrait for ${characterAgent.agentNickname}: ${artifactId}`);
1827
- return artifactId;
2370
+ return this.illustration.updatePortrait(target, characterAgent.agentNickname, visualDescription, room);
1828
2371
  }
1829
2372
  catch (error) {
1830
2373
  logger_1.logger.error(`Error updating portrait for ${characterAgent.agentNickname}:`, error);
1831
2374
  return null;
1832
2375
  }
1833
2376
  }
1834
- async generateSceneIllustration(storyId, situation, allowReference = true, latestNarration) {
1835
- try {
1836
- const story = this.storyStore.getStory(storyId);
1837
- if (!story?.illustratorAgentId) {
1838
- logger_1.logger.log('No illustrator configured');
1839
- return;
1840
- }
1841
- const illustrator = await this.agentStore.getAgent(story.illustratorAgentId);
1842
- const room = await this.roomStore.getRoom(story.roomId);
1843
- if (!illustrator || !room)
1844
- return;
1845
- let narrationText = latestNarration;
1846
- if (!narrationText) {
1847
- const allMessages = room.getLatestRoomMessages(0, true);
1848
- const latestMessage = allMessages[allMessages.length - 1];
1849
- if (!latestMessage) {
1850
- logger_1.logger.warn('No messages in room');
1851
- return;
1852
- }
1853
- narrationText = latestMessage.content;
1854
- }
1855
- illustrator.addToConversationHistory(narrationText, false);
1856
- const storyArtifactService = this.getStoryArtifactService(storyId);
1857
- const allArtifacts = storyArtifactService.listArtifacts();
1858
- const existingScenes = allArtifacts
1859
- .filter((a) => a.name.startsWith('Scene - '))
1860
- .map((a) => ({
1861
- name: a.name.replace('Scene - ', ''),
1862
- description: a.description || '',
1863
- }));
1864
- const portraitCharacters = allArtifacts
1865
- .filter((a) => a.name.startsWith('Portrait - '))
1866
- .map((a) => ({
1867
- name: a.name.replace('Portrait - ', ''),
1868
- description: a.description || '',
1869
- }));
1870
- let existingScenesString = existingScenes
1871
- .map((s) => `- ${s.name}: ${s.description}`)
1872
- .join('\n');
1873
- if (!existingScenesString)
1874
- existingScenesString =
1875
- 'No scene reference images have been created yet. (set isReference: true)';
1876
- const situationForScene = `${story.situationTime ? `${story.situationTime} - ` : ''}${story.situation}`;
1877
- let prompt = `**Current Situation**:\n ${situationForScene}\n\n**Existing Scenes**:\n ${existingScenesString}`;
1878
- const sceneAnalysis = await illustrator.instructedPrompt(prompt, 'describe_scene', {
1879
- characters: portraitCharacters,
1880
- }, true, true);
1881
- illustrator.save();
1882
- if (!sceneAnalysis || !sceneAnalysis.createImage) {
1883
- logger_1.logger.log('Illustrator decided not to create an image for this situation');
1884
- return;
1885
- }
1886
- if (sceneAnalysis.isReference) {
1887
- if (!allowReference) {
1888
- logger_1.logger.warn(`Illustrator requested another reference (${sceneAnalysis.sceneName}) after one was just created; skipping to avoid loop`);
1889
- return;
1890
- }
1891
- const referenceCreated = await this.generateSceneReference(storyId, sceneAnalysis.sceneName, sceneAnalysis.sceneDescription);
1892
- if (referenceCreated) {
1893
- await this.generateSceneIllustration(storyId, situation, false, latestNarration);
1894
- }
1895
- }
1896
- else {
1897
- await this.ensureMinorCharacterPortraits(storyId, sceneAnalysis.characterNames || [], sceneAnalysis.newCharacters || [], portraitCharacters.map((c) => c.name), illustrator);
1898
- await this.generateStoryImage(storyId, story.turnNumber, sceneAnalysis.imageCaption, sceneAnalysis.sceneName, sceneAnalysis.sceneDescription, sceneAnalysis.characterNames);
1899
- }
1900
- }
1901
- catch (error) {
1902
- logger_1.logger.error('Scene illustration error:', error);
1903
- }
1904
- }
1905
- async ensureMinorCharacterPortraits(storyId, characterNames, newCharacters, existingPortraitNames, promptAgent) {
1906
- const existing = new Set(existingPortraitNames);
1907
- const descriptionsByName = new Map(newCharacters.map((c) => [c.name, c.briefDescription]));
1908
- for (const name of characterNames) {
1909
- if (existing.has(name))
1910
- continue;
1911
- const briefDescription = descriptionsByName.get(name);
1912
- if (!briefDescription) {
1913
- logger_1.logger.warn(`Illustrator named "${name}" but provided no newCharacters entry; portrait will be skipped`);
1914
- continue;
1915
- }
1916
- await this.generatePortraitForName(storyId, name, briefDescription, promptAgent);
1917
- }
1918
- }
1919
- async generateSceneReference(storyId, sceneName, sceneDescription) {
1920
- try {
1921
- logger_1.logger.log(`Generating scene reference: ${sceneName}`);
1922
- const storyInfo = this.storyStore.getStory(storyId);
1923
- if (!storyInfo || !storyInfo.artistAgentId) {
1924
- logger_1.logger.error(`Cannot generate scene reference: story ${storyId} has no artist agent`);
1925
- return false;
1926
- }
1927
- const artistAgent = await this.agentStore.getAgent(storyInfo.artistAgentId);
1928
- if (!artistAgent) {
1929
- logger_1.logger.error(`Artist agent not found: ${storyInfo.artistAgentId}`);
1930
- return false;
1931
- }
1932
- const storyArtifactService = this.getStoryArtifactService(storyId);
1933
- if (!storyArtifactService) {
1934
- logger_1.logger.error(`Story artifact service not found: ${storyId}`);
1935
- return false;
1936
- }
1937
- artistAgent.artifactService = storyArtifactService;
1938
- const imageResult = await artistAgent.generateImage(sceneDescription, this.getImagePropertiesForAgent(artistAgent));
1939
- if (imageResult.error) {
1940
- logger_1.logger.error(`Scene reference image generation failed for "${sceneName}":`, imageResult.error);
1941
- return false;
1942
- }
1943
- artistAgent.save();
1944
- const artifactId = imageResult.artifactId;
1945
- storyArtifactService.renameArtifact(artifactId, `Scene - ${sceneName}`);
1946
- storyArtifactService.updateArtifactDescription(artifactId, sceneDescription);
1947
- logger_1.logger.log(`Generated scene reference: ${sceneName} (${artifactId})`);
1948
- return true;
1949
- }
1950
- catch (error) {
1951
- logger_1.logger.error('Scene reference generation error:', error);
1952
- return false;
1953
- }
1954
- }
1955
- async generateStoryImage(storyId, turnNumber, imageCaption, sceneName, sceneDescription, characterNames) {
1956
- try {
1957
- logger_1.logger.log(`Generating story image for turn ${turnNumber}`);
1958
- const storyArtifactService = this.getStoryArtifactService(storyId);
1959
- const allArtifacts = storyArtifactService.listArtifacts();
1960
- const sceneArtifact = allArtifacts.find((a) => a.name === `Scene - ${sceneName}`);
1961
- if (!sceneArtifact) {
1962
- logger_1.logger.warn(`Scene not found: ${sceneName}`);
1963
- return;
1964
- }
1965
- const storyInfo = this.storyStore.getStory(storyId);
1966
- if (!storyInfo || !storyInfo.artistAgentId) {
1967
- logger_1.logger.error(`Cannot generate story image: story ${storyId} has no artist agent`);
1968
- return;
1969
- }
1970
- const artistAgent = await this.agentStore.getAgent(storyInfo.artistAgentId);
1971
- if (!artistAgent) {
1972
- logger_1.logger.error(`Artist agent not found: ${storyInfo.artistAgentId}`);
1973
- return;
1974
- }
1975
- artistAgent.artifactService = storyArtifactService;
1976
- const room = await this.getStoryRoom(storyId);
1977
- const characterPortraitIds = [];
1978
- for (const charName of characterNames) {
1979
- const currentArtifacts = storyArtifactService.listArtifacts();
1980
- const portrait = currentArtifacts.find((a) => a.name === `Portrait - ${charName}`);
1981
- if (portrait) {
1982
- characterPortraitIds.push(portrait.artifactId);
1983
- }
1984
- else {
1985
- logger_1.logger.warn(`Portrait not found for ${charName}, generating now`);
1986
- const characterAgent = room
1987
- .getAgents()
1988
- .find((a) => a.agentNickname === charName);
1989
- if (characterAgent) {
1990
- const newPortraitId = await this.generateCharacterPortrait(room, characterAgent, storyId);
1991
- if (newPortraitId) {
1992
- characterPortraitIds.push(newPortraitId);
1993
- }
1994
- else {
1995
- logger_1.logger.warn(`Could not generate portrait for ${charName}, skipping`);
1996
- }
1997
- }
1998
- else {
1999
- logger_1.logger.warn(`No agent found for character ${charName}, skipping portrait`);
2000
- }
2001
- }
2002
- }
2003
- const referenceImageIds = [sceneArtifact.artifactId, ...characterPortraitIds];
2004
- const editAgent = storyInfo.artistEditAgentId
2005
- ? await this.agentStore.getAgent(storyInfo.artistEditAgentId)
2006
- : null;
2007
- if (editAgent) {
2008
- editAgent.artifactService = storyArtifactService;
2009
- }
2010
- const imageResult = referenceImageIds?.length && editAgent
2011
- ? await editAgent.editImage(sceneDescription, this.getImagePropertiesForAgent(editAgent), referenceImageIds)
2012
- : await artistAgent.generateImage(sceneDescription, this.getImagePropertiesForAgent(artistAgent));
2013
- if (imageResult.error) {
2014
- return;
2015
- }
2016
- artistAgent.save();
2017
- const artifactId = imageResult.artifactId;
2018
- storyArtifactService.renameArtifact(artifactId, `Story image - ${turnNumber}`);
2019
- storyArtifactService.updateArtifactDescription(artifactId, imageCaption);
2020
- logger_1.logger.log(`Generated story image: ${imageCaption} (${artifactId})`);
2021
- try {
2022
- const imgUrl = `/api/stories/${storyId}/artifacts/${artifactId}`;
2023
- const imageMarkdown = `![${imageCaption}](${imgUrl})`;
2024
- const imageMessage = new message_1.RoomMessage(imageCaption, app_types_1.MessageAction.SYSTEM, imageMarkdown);
2025
- room.addRoomMessage(imageMessage);
2026
- logger_1.logger.log(`Added story image message to room`);
2027
- }
2028
- catch (error) {
2029
- logger_1.logger.error('Error adding image message to room:', error);
2030
- }
2031
- }
2032
- catch (error) {
2033
- logger_1.logger.error('Story image generation error:', error);
2034
- }
2035
- }
2377
+ /**
2378
+ * Parses the narrator's preamble into structured fields. Extracts each
2379
+ * tag's inner text (first occurrence, case-insensitive); missing tags
2380
+ * are simply omitted from the result.
2381
+ */
2036
2382
  parseNarratorPreamble(preamble) {
2037
2383
  const result = {};
2038
2384
  if (!preamble)
@@ -2051,6 +2397,8 @@ let StoryService = class StoryService {
2051
2397
  if (situation)
2052
2398
  result.situation = situation;
2053
2399
  if (introduceRaw) {
2400
+ // Value format: "none (reasoning)" or "CharacterName (reasoning)".
2401
+ // Treat the first token as the name; "none" means no introduce.
2054
2402
  const firstToken = introduceRaw.split(/[\s(:,]/)[0];
2055
2403
  if (firstToken && firstToken.toLowerCase() !== 'none') {
2056
2404
  result.introduceCharacter = firstToken;
@@ -2061,18 +2409,35 @@ let StoryService = class StoryService {
2061
2409
  }
2062
2410
  return result;
2063
2411
  }
2412
+ /**
2413
+ * Updates the story's situation in metadata. Invoked from the Room's
2414
+ * situation-update callback with the raw preamble text emitted by the
2415
+ * narrator. The Room itself stays story-agnostic and does not interpret
2416
+ * the preamble contents - all parsing happens here.
2417
+ *
2418
+ * @param storyId The story ID
2419
+ * @param preamble The raw preamble text captured by the Room
2420
+ */
2064
2421
  async updateStorySituation(storyId, preamble, latestNarration) {
2065
2422
  const story = this.storyStore.getStory(storyId);
2066
2423
  if (!story)
2067
2424
  return;
2068
2425
  const room = await this.getStoryRoom(storyId);
2069
2426
  const parsed = this.parseNarratorPreamble(preamble);
2427
+ // The narrator emits the time as a separate <time> member of its preamble; keep
2428
+ // it separate end-to-end (rather than merging it into the situation text) so
2429
+ // every agent prompt can render it on its own labeled line.
2070
2430
  const situationText = parsed.situation ?? preamble;
2071
2431
  const situationTime = parsed.time ?? '';
2432
+ // Always overwrite the room's currentSituation with the readable form. The Room
2433
+ // defaulted it to the raw preamble (which may be XML); other agents' prompts
2434
+ // read getSituation() and shouldn't see tags.
2072
2435
  room.setSituation(situationText);
2073
2436
  room.setSituationTime(situationTime);
2074
2437
  if (parsed.progressChapter) {
2438
+ // Clear declined characters on chapter progression
2075
2439
  story.declinedCharacters = [];
2440
+ // Send suggestion instead of auto-executing
2076
2441
  story.pendingSuggestion = {
2077
2442
  type: 'suggest-progress-chapter',
2078
2443
  timestamp: Date.now(),
@@ -2084,16 +2449,25 @@ let StoryService = class StoryService {
2084
2449
  await this.compactAgentHistories(room.getAgents());
2085
2450
  if (parsed.introduceCharacter) {
2086
2451
  const newCharacterName = parsed.introduceCharacter;
2452
+ // Skip if the named character already exists in the room
2087
2453
  const existingAgent = room.getAgents().find((a) => room.checkAgentNicknameMatch(a.agentNickname, newCharacterName));
2088
2454
  if (existingAgent) {
2089
2455
  logger_1.logger.log(`INTRODUCE: ${newCharacterName} ignored - character already in story`);
2090
2456
  return;
2091
2457
  }
2458
+ // Check if character was already declined
2092
2459
  const declinedCharacters = story?.declinedCharacters || [];
2093
2460
  if (declinedCharacters.includes(newCharacterName)) {
2094
2461
  logger_1.logger.log(`Character ${newCharacterName} was declined, skipping prompt`);
2095
2462
  return;
2096
2463
  }
2464
+ // Auto-create the character agent now, and await it, so the agent
2465
+ // exists in the room before the narrator's message is routed by the
2466
+ // moderator. Otherwise the moderator picks the new character as the
2467
+ // next speaker, no matching agent is found, and the message bounces
2468
+ // back to the room leader (the Narrator) in a loop.
2469
+ // fromNarratorSuggestion=true because the narrator already wove the
2470
+ // character into the scene, so no INTRODUCE message is sent back.
2097
2471
  logger_1.logger.log(`Auto-creating narrator-introduced character ${newCharacterName}`);
2098
2472
  try {
2099
2473
  await this.introduceCharacter(storyId, newCharacterName, '', undefined, true, latestNarration);
@@ -2107,15 +2481,43 @@ let StoryService = class StoryService {
2107
2481
  story.situationTime = situationTime;
2108
2482
  this.storyStore.updateStoryMetadata(storyId, story);
2109
2483
  logger_1.logger.log(`Updated story ${storyId} situation: ${situationTime ? `${situationTime} - ` : ''}${situationText}`);
2110
- this.generateSceneIllustration(storyId, situationText, true, latestNarration).catch((error) => {
2484
+ // Generate scene illustration (fire and forget). Pass the narration that
2485
+ // triggered this update — it isn't in the room transcript yet (the
2486
+ // situation is processed before the moderator relays the message).
2487
+ this.illustrateStorySituation(storyId, room, situationText, latestNarration).catch((error) => {
2111
2488
  logger_1.logger.error('Illustration generation error:', error);
2489
+ // Silently continue
2112
2490
  });
2113
2491
  }
2492
+ /**
2493
+ * Asks the shared illustration pipeline for a picture of the story's current
2494
+ * scene. The situation is passed in rather than read off the room: the room's
2495
+ * copy holds the narrator's raw four-tag preamble, while the story's is the
2496
+ * parsed inner text, and the illustrator wants the latter.
2497
+ */
2498
+ async illustrateStorySituation(storyId, room, situation, narration) {
2499
+ const story = this.storyStore.getStory(storyId);
2500
+ await this.illustration.illustrate(room, this.illustrationTarget(storyId), {
2501
+ situation,
2502
+ situationTime: story?.situationTime,
2503
+ narration,
2504
+ sequence: story?.turnNumber ?? 0,
2505
+ allowReference: true,
2506
+ });
2507
+ }
2508
+ /**
2509
+ * Generates a complete markdown document of the story
2510
+ * Includes metadata, all completed chapters, and current chapter in progress
2511
+ * @param storyId The story ID
2512
+ * @returns The complete story as markdown text
2513
+ */
2114
2514
  async generateStoryMarkdown(storyId) {
2515
+ // 1. Load story metadata
2115
2516
  const story = this.storyStore.getStory(storyId);
2116
2517
  if (!story) {
2117
2518
  throw new Error('Story not found');
2118
2519
  }
2520
+ // 2. Build markdown header with metadata
2119
2521
  let markdown = `# ${story.name}\n\n`;
2120
2522
  markdown += `**Scenario**: ${story.scenario}\n\n`;
2121
2523
  markdown += `**Characters**:\n`;
@@ -2124,71 +2526,114 @@ let StoryService = class StoryService {
2124
2526
  markdown += `- ${char.name} (${type}): ${char.description}\n`;
2125
2527
  }
2126
2528
  markdown += `\n---\n\n`;
2529
+ // 3. Get all chapters
2127
2530
  const chapters = this.storyStore.listChapters(storyId);
2531
+ // 4. Process each completed chapter
2128
2532
  for (const chapter of chapters) {
2129
2533
  markdown += `## Chapter ${chapter.chapterNum}: ${chapter.chapterTitle}\n\n`;
2130
2534
  const messages = await this.storyStore.getChapterContent(storyId, chapter.chapterNum);
2131
2535
  markdown += this.formatMessagesToMarkdown(messages);
2132
2536
  markdown += `\n---\n\n`;
2133
2537
  }
2538
+ // 5. Add current chapter in progress
2134
2539
  const room = await this.getStoryRoom(storyId);
2135
2540
  if (room) {
2136
2541
  markdown += `## Current Chapter\n\n`;
2137
2542
  markdown += this.formatMessagesToMarkdown(room.getLatestRoomMessages(0, true));
2138
2543
  }
2544
+ // 6. Process images to add sizing for better display
2139
2545
  markdown = this.processImageMarkdown(markdown, 600);
2140
2546
  return markdown;
2141
2547
  }
2548
+ /**
2549
+ * Creates a zip archive of the entire story folder
2550
+ * @param storyId The story ID
2551
+ * @returns Promise resolving to a readable stream of the zip file
2552
+ */
2142
2553
  async exportStoryData(storyId) {
2554
+ // 1. Get story metadata for filename
2143
2555
  const story = this.storyStore.getStory(storyId);
2144
2556
  if (!story) {
2145
2557
  throw new Error('Story not found');
2146
2558
  }
2559
+ // 2. Get story folder path
2147
2560
  const userStoriesDir = path.join(this.userPaths.getUserDataDir(), 'stories');
2148
2561
  const storyFolderPath = path.join(userStoriesDir, storyId);
2562
+ // 3. Verify story folder exists
2149
2563
  if (!fs.existsSync(storyFolderPath)) {
2150
2564
  throw new Error('Story folder not found on disk');
2151
2565
  }
2566
+ // 4. Create zip archive
2152
2567
  const archive = (0, archiver_1.default)('zip', {
2153
- zlib: { level: 9 },
2568
+ zlib: { level: 9 }, // Maximum compression
2154
2569
  });
2570
+ // 5. Add entire story folder to archive
2571
+ // The directory() method adds all files and subdirectories recursively
2155
2572
  archive.directory(storyFolderPath, false);
2573
+ // 6. Finalize the archive (important!)
2156
2574
  archive.finalize();
2575
+ // 7. Generate safe filename
2157
2576
  const sanitizedName = story.name.replace(/[^a-z0-9]/gi, '_');
2158
2577
  const filename = `${sanitizedName}.zip`;
2578
+ // 8. Return stream and filename
2159
2579
  return {
2160
2580
  stream: archive,
2161
2581
  filename: filename,
2162
2582
  };
2163
2583
  }
2584
+ /**
2585
+ * Formats room messages as markdown text
2586
+ *
2587
+ * A message's situation is not printed. It restates where the scene stands,
2588
+ * which is useful live and merely repetitive on the page — the narrator sets one
2589
+ * often enough that the document filled up with headings.
2590
+ *
2591
+ * @param messages Array of room messages
2592
+ * @returns Formatted markdown string
2593
+ */
2164
2594
  formatMessagesToMarkdown(messages) {
2165
2595
  let text = '';
2166
2596
  for (const msg of messages) {
2167
- if (msg.situation) {
2168
- text += `### ${msg.situation}\n\n`;
2169
- }
2597
+ // For stories, actions are only 'system' or 'moderate'
2598
+ // In both cases, output sender and content
2170
2599
  text += `**${msg.sender}**: ${msg.content}\n\n`;
2171
2600
  }
2172
2601
  return text;
2173
2602
  }
2603
+ /**
2604
+ * Process markdown to add sizing to images for better display
2605
+ * Converts ![alt](url) to <img> tags with width constraints
2606
+ * @param markdown The markdown string to process
2607
+ * @param maxWidth Maximum width for images (default: 600px)
2608
+ * @returns Processed markdown with HTML img tags
2609
+ */
2174
2610
  processImageMarkdown(markdown, maxWidth = 600) {
2611
+ // Replace markdown image syntax with HTML img tags with sizing
2612
+ // Pattern: ![alt text](url)
2175
2613
  markdown = markdown.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (match, alt, url) => {
2176
2614
  return `<img src="${url}" alt="${alt}" style="max-width: ${maxWidth}px; width: 100%; height: auto; display: block; margin: 1rem auto;" />`;
2177
2615
  });
2178
2616
  return markdown;
2179
2617
  }
2618
+ /**
2619
+ * Updates the story's total cost by aggregating costs from all agents in the story's room
2620
+ * @param storyId The story ID
2621
+ */
2180
2622
  async updateStoryCost(storyId) {
2181
2623
  try {
2624
+ // Get story metadata
2182
2625
  const storyInfo = this.storyStore.getStory(storyId);
2183
2626
  if (!storyInfo || !storyInfo.roomId) {
2184
2627
  logger_1.logger.warn(`Cannot update story cost: story ${storyId} not found or has no room`);
2185
2628
  return;
2186
2629
  }
2630
+ // Get the room to access all agents
2187
2631
  const room = await this.roomStore.getRoom(storyInfo.roomId);
2188
2632
  if (!room) {
2189
2633
  logger_1.logger.warn(`Cannot update story cost: room ${storyInfo.roomId} not found`);
2190
2634
  return;
2191
2635
  }
2636
+ // Aggregate costs from all agents in the room
2192
2637
  let totalCost = 0;
2193
2638
  let totalInputTokens = 0;
2194
2639
  let totalOutputTokens = 0;
@@ -2198,6 +2643,7 @@ let StoryService = class StoryService {
2198
2643
  totalInputTokens += agent.totalInputTokens || 0;
2199
2644
  totalOutputTokens += agent.totalOutputTokens || 0;
2200
2645
  }
2646
+ // Add illustrator agent costs
2201
2647
  if (storyInfo.illustratorAgentId) {
2202
2648
  const illustratorAgent = await this.agentStore.getAgent(storyInfo.illustratorAgentId);
2203
2649
  if (illustratorAgent) {
@@ -2209,6 +2655,7 @@ let StoryService = class StoryService {
2209
2655
  logger_1.logger.warn(`Illustrator agent not found: ${storyInfo.illustratorAgentId}`);
2210
2656
  }
2211
2657
  }
2658
+ // Add artist agent costs
2212
2659
  if (storyInfo.artistAgentId) {
2213
2660
  const artistAgent = await this.agentStore.getAgent(storyInfo.artistAgentId);
2214
2661
  if (artistAgent) {
@@ -2220,6 +2667,7 @@ let StoryService = class StoryService {
2220
2667
  logger_1.logger.warn(`Artist agent not found: ${storyInfo.artistAgentId}`);
2221
2668
  }
2222
2669
  }
2670
+ // Add artist edit agent costs (scene illustrations go through editImage)
2223
2671
  if (storyInfo.artistEditAgentId) {
2224
2672
  const artistEditAgent = await this.agentStore.getAgent(storyInfo.artistEditAgentId);
2225
2673
  if (artistEditAgent) {
@@ -2231,9 +2679,11 @@ let StoryService = class StoryService {
2231
2679
  logger_1.logger.warn(`Artist edit agent not found: ${storyInfo.artistEditAgentId}`);
2232
2680
  }
2233
2681
  }
2682
+ // Update story metadata
2234
2683
  storyInfo.totalCost = totalCost;
2235
2684
  storyInfo.totalInputTokens = totalInputTokens;
2236
2685
  storyInfo.totalOutputTokens = totalOutputTokens;
2686
+ // Persist to disk
2237
2687
  this.storyStore.updateStoryMetadata(storyId, storyInfo);
2238
2688
  }
2239
2689
  catch (error) {
@@ -2251,5 +2701,6 @@ exports.StoryService = StoryService = __decorate([
2251
2701
  story_message_service_1.StoryMessageService,
2252
2702
  user_paths_service_1.UserPathsService,
2253
2703
  agent_factory_1.AgentFactory,
2254
- room_factory_1.RoomFactory])
2704
+ room_factory_1.RoomFactory,
2705
+ illustration_service_1.IllustrationService])
2255
2706
  ], StoryService);