briyah 2.0.3 → 2.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (371) hide show
  1. package/README.md +43 -7
  2. package/data/common/config/LICENSE-model-prices.md +65 -0
  3. package/data/common/config/model_prices.json +47443 -46295
  4. package/data/common/prompts/narrator/create_story.prompt +2 -0
  5. package/dist-sdk/server/src/ai/LLM/anthropic.service.d.ts +103 -0
  6. package/dist-sdk/server/src/ai/LLM/anthropic.service.js +173 -2
  7. package/dist-sdk/server/src/ai/LLM/base-ai.service.d.ts +172 -3
  8. package/dist-sdk/server/src/ai/LLM/base-ai.service.js +241 -5
  9. package/dist-sdk/server/src/ai/LLM/comfyui-client.d.ts +26 -0
  10. package/dist-sdk/server/src/ai/LLM/comfyui-client.js +25 -0
  11. package/dist-sdk/server/src/ai/LLM/comfyui-workflow.d.ts +54 -0
  12. package/dist-sdk/server/src/ai/LLM/comfyui-workflow.js +59 -1
  13. package/dist-sdk/server/src/ai/LLM/comfyui.service.d.ts +21 -1
  14. package/dist-sdk/server/src/ai/LLM/comfyui.service.js +25 -1
  15. package/dist-sdk/server/src/ai/LLM/deepseek.service.d.ts +52 -0
  16. package/dist-sdk/server/src/ai/LLM/deepseek.service.js +102 -3
  17. package/dist-sdk/server/src/ai/LLM/fal.service.d.ts +25 -0
  18. package/dist-sdk/server/src/ai/LLM/fal.service.js +55 -1
  19. package/dist-sdk/server/src/ai/LLM/googleai.service.d.ts +19 -0
  20. package/dist-sdk/server/src/ai/LLM/googleai.service.js +42 -1
  21. package/dist-sdk/server/src/ai/LLM/grok.service.d.ts +22 -0
  22. package/dist-sdk/server/src/ai/LLM/grok.service.js +54 -2
  23. package/dist-sdk/server/src/ai/LLM/mock.service.js +31 -4
  24. package/dist-sdk/server/src/ai/LLM/openai.service.d.ts +30 -0
  25. package/dist-sdk/server/src/ai/LLM/openai.service.js +80 -2
  26. package/dist-sdk/server/src/ai/LLM/self-hosted.service.d.ts +21 -0
  27. package/dist-sdk/server/src/ai/LLM/self-hosted.service.js +44 -2
  28. package/dist-sdk/server/src/ai/LLM/together.service.d.ts +30 -0
  29. package/dist-sdk/server/src/ai/LLM/together.service.js +60 -2
  30. package/dist-sdk/server/src/ai/agent-config.d.ts +15 -0
  31. package/dist-sdk/server/src/ai/agent-factory.d.ts +16 -0
  32. package/dist-sdk/server/src/ai/agent-factory.js +20 -0
  33. package/dist-sdk/server/src/ai/agent-message.service.d.ts +30 -0
  34. package/dist-sdk/server/src/ai/agent-message.service.js +30 -0
  35. package/dist-sdk/server/src/ai/agent-store.service.d.ts +80 -0
  36. package/dist-sdk/server/src/ai/agent-store.service.js +166 -5
  37. package/dist-sdk/server/src/ai/agent.d.ts +196 -0
  38. package/dist-sdk/server/src/ai/agent.js +224 -11
  39. package/dist-sdk/server/src/ai/ai-debug-logger.d.ts +18 -0
  40. package/dist-sdk/server/src/ai/ai-debug-logger.js +19 -0
  41. package/dist-sdk/server/src/ai/ai-factory.service.d.ts +9 -0
  42. package/dist-sdk/server/src/ai/ai-factory.service.js +9 -0
  43. package/dist-sdk/server/src/ai/artifact.service.d.ts +131 -0
  44. package/dist-sdk/server/src/ai/artifact.service.js +148 -3
  45. package/dist-sdk/server/src/ai/attached-file.service.d.ts +87 -0
  46. package/dist-sdk/server/src/ai/attached-file.service.js +105 -0
  47. package/dist-sdk/server/src/ai/model_prices.d.ts +30 -0
  48. package/dist-sdk/server/src/ai/model_prices.js +91 -5
  49. package/dist-sdk/server/src/ai/pack-artifacts.d.ts +84 -0
  50. package/dist-sdk/server/src/ai/pack-artifacts.js +168 -0
  51. package/dist-sdk/server/src/ai/published-agents.service.d.ts +25 -0
  52. package/dist-sdk/server/src/ai/published-agents.service.js +30 -3
  53. package/dist-sdk/server/src/app/balance-message.service.d.ts +24 -0
  54. package/dist-sdk/server/src/app/balance-message.service.js +24 -0
  55. package/dist-sdk/server/src/app/balance.module.d.ts +4 -0
  56. package/dist-sdk/server/src/app/balance.module.js +4 -0
  57. package/dist-sdk/server/src/app/balance.service.d.ts +37 -0
  58. package/dist-sdk/server/src/app/balance.service.js +54 -0
  59. package/dist-sdk/server/src/app/stripe.controller.d.ts +21 -0
  60. package/dist-sdk/server/src/app/stripe.controller.js +35 -0
  61. package/dist-sdk/server/src/app/stripe.service.d.ts +43 -0
  62. package/dist-sdk/server/src/app/stripe.service.js +62 -0
  63. package/dist-sdk/server/src/app/transaction.service.d.ts +27 -0
  64. package/dist-sdk/server/src/app/transaction.service.js +36 -0
  65. package/dist-sdk/server/src/app/user-service-factory.d.ts +8 -0
  66. package/dist-sdk/server/src/app/user-service-factory.js +38 -1
  67. package/dist-sdk/server/src/app/user-service-manager.d.ts +27 -0
  68. package/dist-sdk/server/src/app/user-service-manager.js +43 -0
  69. package/dist-sdk/server/src/app.controller.d.ts +87 -0
  70. package/dist-sdk/server/src/app.controller.js +272 -12
  71. package/dist-sdk/server/src/app.module.js +28 -6
  72. package/dist-sdk/server/src/app.service.d.ts +1661 -0
  73. package/dist-sdk/server/src/app.service.js +1837 -4
  74. package/dist-sdk/server/src/auth/agent-access.decorator.d.ts +17 -0
  75. package/dist-sdk/server/src/auth/agent-access.decorator.js +17 -0
  76. package/dist-sdk/server/src/auth/auth.controller.js +46 -0
  77. package/dist-sdk/server/src/auth/auth.module.js +3 -2
  78. package/dist-sdk/server/src/auth/auth.service.d.ts +33 -0
  79. package/dist-sdk/server/src/auth/auth.service.js +39 -3
  80. package/dist-sdk/server/src/auth/jwt-auth.guard.js +18 -0
  81. package/dist-sdk/server/src/auth/jwt.strategy.js +2 -2
  82. package/dist-sdk/server/src/auth/owner-only.decorator.d.ts +9 -0
  83. package/dist-sdk/server/src/auth/owner-only.decorator.js +9 -0
  84. package/dist-sdk/server/src/auth/phone-validation.service.d.ts +25 -0
  85. package/dist-sdk/server/src/auth/phone-validation.service.js +30 -0
  86. package/dist-sdk/server/src/auth/rate-limit.service.d.ts +19 -0
  87. package/dist-sdk/server/src/auth/rate-limit.service.js +24 -0
  88. package/dist-sdk/server/src/auth/room-access.decorator.d.ts +8 -0
  89. package/dist-sdk/server/src/auth/room-access.decorator.js +8 -0
  90. package/dist-sdk/server/src/auth/scopes.decorator.d.ts +7 -0
  91. package/dist-sdk/server/src/auth/scopes.decorator.js +7 -0
  92. package/dist-sdk/server/src/auth/scopes.guard.d.ts +16 -0
  93. package/dist-sdk/server/src/auth/scopes.guard.js +30 -0
  94. package/dist-sdk/server/src/auth/session.guard.d.ts +4 -0
  95. package/dist-sdk/server/src/auth/session.guard.js +8 -0
  96. package/dist-sdk/server/src/auth/twilio.service.d.ts +27 -0
  97. package/dist-sdk/server/src/auth/twilio.service.js +30 -4
  98. package/dist-sdk/server/src/auth/users.service.d.ts +30 -0
  99. package/dist-sdk/server/src/auth/users.service.js +42 -0
  100. package/dist-sdk/server/src/common/errors.d.ts +20 -0
  101. package/dist-sdk/server/src/common/errors.js +21 -0
  102. package/dist-sdk/server/src/config/env-config.d.ts +7 -0
  103. package/dist-sdk/server/src/config/prompt-resolver.d.ts +180 -0
  104. package/dist-sdk/server/src/config/prompt-resolver.js +182 -0
  105. package/dist-sdk/server/src/config/user-config.service.d.ts +59 -0
  106. package/dist-sdk/server/src/config/user-config.service.js +57 -0
  107. package/dist-sdk/server/src/config/user-paths.service.d.ts +61 -0
  108. package/dist-sdk/server/src/config/user-paths.service.js +67 -0
  109. package/dist-sdk/server/src/documents/pdf-conversion.d.ts +121 -1
  110. package/dist-sdk/server/src/documents/pdf-conversion.js +94 -0
  111. package/dist-sdk/server/src/packs/pack-instantiation.service.d.ts +98 -0
  112. package/dist-sdk/server/src/packs/pack-instantiation.service.js +99 -0
  113. package/dist-sdk/server/src/packs/pack-manifest.d.ts +100 -0
  114. package/dist-sdk/server/src/packs/pack-manifest.js +58 -0
  115. package/dist-sdk/server/src/packs/pack.service.d.ts +99 -1
  116. package/dist-sdk/server/src/packs/pack.service.js +98 -1
  117. package/dist-sdk/server/src/room/artifact-store.service.d.ts +27 -0
  118. package/dist-sdk/server/src/room/artifact-store.service.js +49 -3
  119. package/dist-sdk/server/src/room/artifact.d.ts +18 -0
  120. package/dist-sdk/server/src/room/message.d.ts +64 -0
  121. package/dist-sdk/server/src/room/message.js +77 -2
  122. package/dist-sdk/server/src/room/nickname.d.ts +26 -0
  123. package/dist-sdk/server/src/room/nickname.js +26 -0
  124. package/dist-sdk/server/src/room/published-rooms.service.js +2 -0
  125. package/dist-sdk/server/src/room/room-config.d.ts +26 -0
  126. package/dist-sdk/server/src/room/room-factory.d.ts +12 -0
  127. package/dist-sdk/server/src/room/room-factory.js +14 -0
  128. package/dist-sdk/server/src/room/room-message.service.d.ts +28 -0
  129. package/dist-sdk/server/src/room/room-message.service.js +28 -0
  130. package/dist-sdk/server/src/room/room-store.service.d.ts +176 -0
  131. package/dist-sdk/server/src/room/room-store.service.js +238 -5
  132. package/dist-sdk/server/src/room/room.d.ts +878 -0
  133. package/dist-sdk/server/src/room/room.js +1291 -23
  134. package/dist-sdk/server/src/rpg/rpg-models.d.ts +50 -0
  135. package/dist-sdk/server/src/rpg/rpg-models.js +53 -0
  136. package/dist-sdk/server/src/rpg/rpg-roster.d.ts +37 -0
  137. package/dist-sdk/server/src/rpg/rpg-roster.js +37 -0
  138. package/dist-sdk/server/src/rpg/rpg.service.d.ts +87 -0
  139. package/dist-sdk/server/src/rpg/rpg.service.js +103 -0
  140. package/dist-sdk/server/src/sdk/briyah-config.d.ts +57 -0
  141. package/dist-sdk/server/src/sdk/briyah-config.js +17 -0
  142. package/dist-sdk/server/src/sdk/briyah.d.ts +228 -0
  143. package/dist-sdk/server/src/sdk/briyah.js +285 -7
  144. package/dist-sdk/server/src/sdk/index.js +23 -0
  145. package/dist-sdk/server/src/shared/shared.module.d.ts +8 -0
  146. package/dist-sdk/server/src/shared/shared.module.js +13 -5
  147. package/dist-sdk/server/src/story/story-message.service.d.ts +43 -0
  148. package/dist-sdk/server/src/story/story-message.service.js +43 -0
  149. package/dist-sdk/server/src/story/story-progress.service.d.ts +23 -0
  150. package/dist-sdk/server/src/story/story-progress.service.js +23 -0
  151. package/dist-sdk/server/src/story/story-store.service.d.ts +92 -0
  152. package/dist-sdk/server/src/story/story-store.service.js +136 -1
  153. package/dist-sdk/server/src/story/story.service.d.ts +398 -0
  154. package/dist-sdk/server/src/story/story.service.js +829 -25
  155. package/dist-sdk/server/src/tools/core/index.d.ts +22 -0
  156. package/dist-sdk/server/src/tools/core/index.js +22 -0
  157. package/dist-sdk/server/src/tools/core/rename.tool.d.ts +8 -0
  158. package/dist-sdk/server/src/tools/core/rename.tool.js +11 -0
  159. package/dist-sdk/server/src/tools/native-tool-registry.service.d.ts +22 -0
  160. package/dist-sdk/server/src/tools/native-tool-registry.service.js +22 -0
  161. package/dist-sdk/server/src/tools/native-tool.types.d.ts +176 -0
  162. package/dist-sdk/server/src/tools/packs/dnd5e/data/backgrounds.d.ts +29 -0
  163. package/dist-sdk/server/src/tools/packs/dnd5e/data/backgrounds.js +29 -0
  164. package/dist-sdk/server/src/tools/packs/dnd5e/data/cantrips.d.ts +46 -0
  165. package/dist-sdk/server/src/tools/packs/dnd5e/data/cantrips.js +40 -0
  166. package/dist-sdk/server/src/tools/packs/dnd5e/data/feats.d.ts +33 -0
  167. package/dist-sdk/server/src/tools/packs/dnd5e/data/feats.js +19 -0
  168. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.d.ts +37 -0
  169. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.generated.d.ts +17 -0
  170. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.generated.js +17 -0
  171. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.js +27 -0
  172. package/dist-sdk/server/src/tools/packs/dnd5e/data/kits.d.ts +36 -0
  173. package/dist-sdk/server/src/tools/packs/dnd5e/data/kits.js +32 -0
  174. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.d.ts +32 -0
  175. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.generated.d.ts +13 -0
  176. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.generated.js +13 -0
  177. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.js +18 -0
  178. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.d.ts +54 -0
  179. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.generated.d.ts +13 -0
  180. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.generated.js +13 -0
  181. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.js +20 -0
  182. package/dist-sdk/server/src/tools/packs/dnd5e/data/races.d.ts +36 -0
  183. package/dist-sdk/server/src/tools/packs/dnd5e/data/races.js +18 -0
  184. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.d.ts +29 -0
  185. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.generated.d.ts +13 -0
  186. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.generated.js +13 -0
  187. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.js +21 -0
  188. package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.d.ts +95 -0
  189. package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.js +66 -2
  190. package/dist-sdk/server/src/tools/packs/dnd5e/data/weapons.d.ts +50 -0
  191. package/dist-sdk/server/src/tools/packs/dnd5e/data/weapons.js +28 -0
  192. package/dist-sdk/server/src/tools/packs/dnd5e/engine/bestiary.d.ts +92 -0
  193. package/dist-sdk/server/src/tools/packs/dnd5e/engine/bestiary.js +152 -0
  194. package/dist-sdk/server/src/tools/packs/dnd5e/engine/campaign-items.d.ts +28 -0
  195. package/dist-sdk/server/src/tools/packs/dnd5e/engine/campaign-items.js +29 -0
  196. package/dist-sdk/server/src/tools/packs/dnd5e/engine/cantrips.d.ts +31 -0
  197. package/dist-sdk/server/src/tools/packs/dnd5e/engine/cantrips.js +36 -2
  198. package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.d.ts +261 -0
  199. package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.js +401 -0
  200. package/dist-sdk/server/src/tools/packs/dnd5e/engine/coerce.d.ts +11 -0
  201. package/dist-sdk/server/src/tools/packs/dnd5e/engine/coerce.js +11 -0
  202. package/dist-sdk/server/src/tools/packs/dnd5e/engine/dice.d.ts +65 -0
  203. package/dist-sdk/server/src/tools/packs/dnd5e/engine/dice.js +67 -0
  204. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encounter.d.ts +73 -0
  205. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encounter.js +63 -0
  206. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encumbrance.d.ts +66 -0
  207. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encumbrance.js +59 -0
  208. package/dist-sdk/server/src/tools/packs/dnd5e/engine/feats.d.ts +54 -0
  209. package/dist-sdk/server/src/tools/packs/dnd5e/engine/feats.js +49 -0
  210. package/dist-sdk/server/src/tools/packs/dnd5e/engine/foes.d.ts +42 -0
  211. package/dist-sdk/server/src/tools/packs/dnd5e/engine/foes.js +59 -0
  212. package/dist-sdk/server/src/tools/packs/dnd5e/engine/guides.d.ts +72 -0
  213. package/dist-sdk/server/src/tools/packs/dnd5e/engine/guides.js +63 -0
  214. package/dist-sdk/server/src/tools/packs/dnd5e/engine/items.d.ts +57 -0
  215. package/dist-sdk/server/src/tools/packs/dnd5e/engine/items.js +54 -0
  216. package/dist-sdk/server/src/tools/packs/dnd5e/engine/kits.d.ts +81 -0
  217. package/dist-sdk/server/src/tools/packs/dnd5e/engine/kits.js +85 -0
  218. package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.d.ts +60 -0
  219. package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.js +64 -0
  220. package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.d.ts +169 -0
  221. package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.js +203 -0
  222. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.d.ts +192 -0
  223. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.js +144 -0
  224. package/dist-sdk/server/src/tools/packs/dnd5e/engine/spells.d.ts +56 -0
  225. package/dist-sdk/server/src/tools/packs/dnd5e/engine/spells.js +54 -0
  226. package/dist-sdk/server/src/tools/packs/dnd5e/engine/weapons.d.ts +65 -0
  227. package/dist-sdk/server/src/tools/packs/dnd5e/engine/weapons.js +73 -0
  228. package/dist-sdk/server/src/tools/packs/dnd5e/index.d.ts +18 -0
  229. package/dist-sdk/server/src/tools/packs/dnd5e/index.js +18 -0
  230. package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.d.ts +4 -0
  231. package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.js +116 -1
  232. package/dist-sdk/server/src/tools/packs/dnd5e/tools/class.tool.d.ts +14 -0
  233. package/dist-sdk/server/src/tools/packs/dnd5e/tools/class.tool.js +17 -0
  234. package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.d.ts +1 -0
  235. package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.js +35 -1
  236. package/dist-sdk/server/src/tools/packs/dnd5e/tools/encounter.tool.d.ts +6 -0
  237. package/dist-sdk/server/src/tools/packs/dnd5e/tools/encounter.tool.js +25 -0
  238. package/dist-sdk/server/src/tools/packs/dnd5e/tools/item.tool.d.ts +7 -0
  239. package/dist-sdk/server/src/tools/packs/dnd5e/tools/item.tool.js +13 -0
  240. package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.d.ts +8 -0
  241. package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.js +55 -0
  242. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.d.ts +164 -0
  243. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.js +188 -1
  244. package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.d.ts +1 -0
  245. package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.js +116 -0
  246. package/dist-sdk/server/src/tools/packs/dnd5e/tools/spell.tool.d.ts +13 -0
  247. package/dist-sdk/server/src/tools/packs/dnd5e/tools/spell.tool.js +18 -0
  248. package/dist-sdk/server/src/tools/packs/dnd5e/tools/state.tools.d.ts +1 -0
  249. package/dist-sdk/server/src/tools/packs/dnd5e/tools/state.tools.js +23 -0
  250. package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.d.ts +1 -0
  251. package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.js +35 -0
  252. package/dist-sdk/server/src/tools/packs/index.d.ts +49 -0
  253. package/dist-sdk/server/src/tools/packs/index.js +66 -0
  254. package/dist-sdk/server/src/tools/shared/coerce.d.ts +95 -0
  255. package/dist-sdk/server/src/tools/shared/coerce.js +98 -0
  256. package/dist-sdk/server/src/tools/tool-execution.service.d.ts +73 -0
  257. package/dist-sdk/server/src/tools/tool-execution.service.js +74 -0
  258. package/dist-sdk/server/src/tools/tool-store.service.d.ts +11 -0
  259. package/dist-sdk/server/src/tools/tool-store.service.js +13 -1
  260. package/dist-sdk/shared/types/app.types.d.ts +285 -13
  261. package/dist-sdk/shared/types/app.types.js +3 -0
  262. package/package.json +167 -168
  263. package/data/common/config/random_words.txt +0 -2241
  264. package/data/common/story_ideas/biblical.json +0 -122
  265. package/data/common/story_ideas/fantasy.json +0 -82
  266. package/data/common/story_ideas/historical_fiction.json +0 -82
  267. package/data/common/story_ideas/science_fiction.json +0 -82
  268. package/docs/.nojekyll +0 -1
  269. package/docs/assets/hierarchy.js +0 -1
  270. package/docs/assets/highlight.css +0 -113
  271. package/docs/assets/icons.js +0 -18
  272. package/docs/assets/icons.svg +0 -1
  273. package/docs/assets/main.js +0 -60
  274. package/docs/assets/navigation.js +0 -1
  275. package/docs/assets/search.js +0 -1
  276. package/docs/assets/style.css +0 -1648
  277. package/docs/classes/Agent.html +0 -801
  278. package/docs/classes/Briyah.html +0 -296
  279. package/docs/classes/BriyahConfigService.html +0 -119
  280. package/docs/classes/NativeToolRegistry.html +0 -166
  281. package/docs/classes/PackInstantiationService.html +0 -157
  282. package/docs/classes/PackService.html +0 -247
  283. package/docs/classes/Room.html +0 -1434
  284. package/docs/classes/RoomMessage.html +0 -290
  285. package/docs/enums/MessageAction.html +0 -136
  286. package/docs/functions/availableToolPacks.html +0 -41
  287. package/docs/functions/buildMarkdown.html +0 -54
  288. package/docs/functions/dnd5eTools.html +0 -44
  289. package/docs/functions/installToolPacks.html +0 -51
  290. package/docs/functions/pageMarker.html +0 -45
  291. package/docs/functions/registerToolPacks.html +0 -54
  292. package/docs/functions/splitMarkdownIntoPages.html +0 -51
  293. package/docs/functions/stripWrappingFence.html +0 -52
  294. package/docs/hierarchy.html +0 -46
  295. package/docs/index.html +0 -595
  296. package/docs/interfaces/AgentCreationOptions.html +0 -125
  297. package/docs/interfaces/AgentInfo.html +0 -218
  298. package/docs/interfaces/AgentMessagesResponse.html +0 -74
  299. package/docs/interfaces/AppService.html +0 -3340
  300. package/docs/interfaces/Artifact.html +0 -95
  301. package/docs/interfaces/ArtifactMetadata.html +0 -112
  302. package/docs/interfaces/ArtifactWriteOptions.html +0 -90
  303. package/docs/interfaces/AttachDocumentResponse.html +0 -62
  304. package/docs/interfaces/BriyahConfigOptions.html +0 -124
  305. package/docs/interfaces/ChapterInfo.html +0 -62
  306. package/docs/interfaces/Character.html +0 -86
  307. package/docs/interfaces/ConversionAgent.html +0 -78
  308. package/docs/interfaces/CreateAgentResponse.html +0 -56
  309. package/docs/interfaces/CreateRoomResponse.html +0 -62
  310. package/docs/interfaces/CreateStoryResponse.html +0 -56
  311. package/docs/interfaces/FileList.html +0 -56
  312. package/docs/interfaces/FileMetadata.html +0 -89
  313. package/docs/interfaces/IConfigService.html +0 -79
  314. package/docs/interfaces/InstantiateModels.html +0 -64
  315. package/docs/interfaces/InstantiateRoomResult.html +0 -70
  316. package/docs/interfaces/LoadedPack.html +0 -131
  317. package/docs/interfaces/LoggingOptions.html +0 -92
  318. package/docs/interfaces/Message.html +0 -84
  319. package/docs/interfaces/ModelChoice.html +0 -73
  320. package/docs/interfaces/ModelInfo.html +0 -74
  321. package/docs/interfaces/NativeToolDefinition.html +0 -107
  322. package/docs/interfaces/PackAgentTemplate.html +0 -101
  323. package/docs/interfaces/PackRoomTemplate.html +0 -108
  324. package/docs/interfaces/PackView.html +0 -172
  325. package/docs/interfaces/PdfConversionOptions.html +0 -102
  326. package/docs/interfaces/PdfConversionResult.html +0 -97
  327. package/docs/interfaces/PdfMarkdownOptions.html +0 -198
  328. package/docs/interfaces/PdfMarkdownResult.html +0 -106
  329. package/docs/interfaces/PdfPageMarkdown.html +0 -94
  330. package/docs/interfaces/PreparedPromptResponse.html +0 -62
  331. package/docs/interfaces/ProcessTextResponse.html +0 -86
  332. package/docs/interfaces/PromptFile.html +0 -70
  333. package/docs/interfaces/PromptFileContent.html +0 -76
  334. package/docs/interfaces/PromptFilesResponse.html +0 -56
  335. package/docs/interfaces/PromptFolder.html +0 -80
  336. package/docs/interfaces/PromptFolderDefaults.html +0 -155
  337. package/docs/interfaces/PromptFolderDefaultsResponse.html +0 -79
  338. package/docs/interfaces/PromptFoldersResponse.html +0 -56
  339. package/docs/interfaces/RoomDetails.html +0 -151
  340. package/docs/interfaces/RoomErrorUpdate.html +0 -82
  341. package/docs/interfaces/RoomInfo.html +0 -88
  342. package/docs/interfaces/RoomMessageUpdate.html +0 -113
  343. package/docs/interfaces/RoomMessagesResponse.html +0 -62
  344. package/docs/interfaces/SendMessageResult.html +0 -62
  345. package/docs/interfaces/StoryErrorEvent.html +0 -84
  346. package/docs/interfaces/StoryIdea.html +0 -74
  347. package/docs/interfaces/StoryInfo.html +0 -198
  348. package/docs/interfaces/StoryIntroduceCharacterEvent.html +0 -79
  349. package/docs/interfaces/StoryProgressChapterEvent.html +0 -72
  350. package/docs/interfaces/StoryState.html +0 -108
  351. package/docs/interfaces/StoryStateEvent.html +0 -76
  352. package/docs/interfaces/ToolArtifact.html +0 -85
  353. package/docs/interfaces/ToolCaller.html +0 -77
  354. package/docs/interfaces/ToolDefinition.html +0 -80
  355. package/docs/interfaces/ToolHelpers.html +0 -105
  356. package/docs/interfaces/ToolPackDocuments.html +0 -100
  357. package/docs/interfaces/ToolParameter.html +0 -74
  358. package/docs/interfaces/ToolRoomAccess.html +0 -260
  359. package/docs/interfaces/ToolSummary.html +0 -74
  360. package/docs/interfaces/ToolsResponse.html +0 -68
  361. package/docs/interfaces/Transaction.html +0 -104
  362. package/docs/interfaces/TransactionHistoryResponse.html +0 -62
  363. package/docs/modules.html +0 -53
  364. package/docs/types/PackOrigin.html +0 -34
  365. package/docs/types/PromptScope.html +0 -34
  366. package/docs/types/RoomTurnMode.html +0 -42
  367. package/docs/types/RoomUpdate.html +0 -36
  368. package/docs/types/RosterOverrides.html +0 -42
  369. package/docs/types/ToolContext.html +0 -40
  370. package/docs/types/ToolRunResult.html +0 -34
  371. package/src/tools/packs/dnd5e/README.md +0 -867
@@ -1,4 +1,11 @@
1
1
  "use strict";
2
+ /**
3
+ * Character construction and the rules-aware mutations the tools expose:
4
+ * building a sheet from a specification, taking damage, healing, resting, and
5
+ * spending resources. Every function here is pure — it takes state and returns
6
+ * new state plus a description — so the tools stay thin and this is all testable
7
+ * without a room.
8
+ */
2
9
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
10
  if (k2 === undefined) k2 = k;
4
11
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -76,13 +83,37 @@ const kits_1 = require("./kits");
76
83
  const spells_1 = require("./spells");
77
84
  const feats_1 = require("./feats");
78
85
  const sheet_1 = require("./sheet");
86
+ /**
87
+ * Narrows a mutation result to its refusal.
88
+ *
89
+ * This project compiles with `strictNullChecks: false`, which disables narrowing
90
+ * on the `ok` discriminant, so callers need an explicit guard.
91
+ * @param result The mutation result
92
+ * @returns True when nothing was changed
93
+ */
79
94
  function isRefusal(result) {
80
95
  return result.ok === false;
81
96
  }
97
+ /**
98
+ * Narrows a mutation result to its success.
99
+ * @param result The mutation result
100
+ * @returns True when the mutation produced new state
101
+ */
82
102
  function isSuccess(result) {
83
103
  return result.ok === true;
84
104
  }
105
+ /** The standard array the rules offer instead of rolling. */
85
106
  exports.STANDARD_ARRAY = [15, 14, 13, 12, 10, 8];
107
+ /**
108
+ * Builds a complete sheet state from a specification, computing everything the
109
+ * rules determine: hit points, armour class, proficiency, saves, hit dice and
110
+ * spell slots. Only the class is genuinely required.
111
+ * @param name The character's name
112
+ * @param spec What the player chose
113
+ * @param owner Nickname of the agent who plays this character
114
+ * @returns The new state
115
+ * @throws {SheetError} With violation 'unknown_class' when the class is not in the SRD
116
+ */
86
117
  function buildCharacter(name, spec, owner) {
87
118
  const primaryKey = rules.resolveClass(spec.class || '');
88
119
  if (!primaryKey) {
@@ -127,8 +158,14 @@ function buildCharacter(name, spec, owner) {
127
158
  saveProf: [...srd_1.CLASSES[primaryKey].saves],
128
159
  skillProf: normalizeSkillList(spec.skills),
129
160
  skillExp: expertise.skills,
161
+ // Expertise with a tool implies proficiency with it, so it lands in both —
162
+ // otherwise a rogue with expertise in thieves' tools would be shown as not
163
+ // proficient with them.
130
164
  toolProf: (0, kits_1.canonicalToolNames)([...(spec.tools || []), ...expertise.tools]),
131
165
  toolExp: expertise.tools,
166
+ // On the sheet before the race is applied, for the same reason the player's
167
+ // tool picks are: it is what lets `applyRace` see a choice already covered
168
+ // and stop asking for it.
132
169
  languages: normalizeLanguages(spec.languages),
133
170
  hp: { max: 1, cur: 1, temp: 0 },
134
171
  hd: {},
@@ -150,22 +187,53 @@ function buildCharacter(name, spec, owner) {
150
187
  coin: spec.coin || { gp: 10 },
151
188
  xp: Math.max(Number(spec.xp) || 0, 0),
152
189
  };
190
+ // One set across both sources, so a single artisan's tool cannot settle both the
191
+ // dwarf's choice and the monk's. The player's own picks are already on the sheet
192
+ // and unspent, which is what lets a choice they covered go unmentioned — and a
193
+ // background's tools arrive that way too, in `spec.tools`, since a background is a
194
+ // document rather than a table.
153
195
  const consumedTools = new Set();
196
+ // The race goes on before anything is derived, because it changes ability
197
+ // scores and every derived number reads them. Applied exactly once, here: the
198
+ // increases land in `abil`, which then holds the character's real scores, so
199
+ // a second application would raise them again.
154
200
  const race = spec.applyRacialBonuses === false
155
201
  ? { increases: {}, tools: [], outstanding: [], problems: [] }
156
202
  : (0, races_1.applyRace)(state, spec.raceAbilityChoices, consumedTools);
203
+ // Class tools after the race, because a race offers a *shortlist* — the dwarf's
204
+ // three artisan's tools — where a class offers a whole category. Settling the
205
+ // narrow choice first leaves the player the wider one to spend, so a dwarf monk
206
+ // who named one tool is asked for any artisan's tool or instrument rather than
207
+ // for one of three. Only the primary class grants them, matching how `saveProf`
208
+ // above takes only the primary class's saves: multiclassing grants a documented
209
+ // *subset* of a class's proficiencies, which is a table this pack does not carry.
157
210
  const classTools = (0, kits_1.grantTools)(state, srd_1.CLASSES[primaryKey].tools, srd_1.CLASSES[primaryKey].name, consumedTools);
158
211
  recomputeDerived(state);
212
+ // Class feature pools after the race and after the first derive, because a pool
213
+ // sized off an ability modifier — a bard's inspiration, a paladin's Divine Sense —
214
+ // has to read the score the race has already raised.
159
215
  applyClassFeatureUses(state);
216
+ // Feats before the attacks are derived, since one could grant a weapon
217
+ // proficiency that changes an attack bonus.
160
218
  for (const feat of spec.feats || []) {
161
219
  if (!(0, feats_1.hasFeat)(state, feat))
162
220
  (0, feats_1.applyFeat)(state, feat);
163
221
  }
222
+ // Starting equipment is worn, not carried in a sack. Armour contributes
223
+ // nothing until it is flagged `eq`, so leaving this to the caller produced
224
+ // characters walking around in an unarmoured 10 + Dex while their sheet listed
225
+ // chain mail.
164
226
  equipStartingArmor(state);
165
227
  state.ac = rules.computeArmorClass(state).ac;
228
+ // Attack lines are computed from the weapons they are carrying unless the
229
+ // caller supplied their own. This is the whole reason the weapon table exists:
230
+ // the alternative is whoever builds the sheet working out a to-hit bonus in
231
+ // their head, which is the arithmetic this pack takes away.
166
232
  if (state.attacks.length === 0) {
167
233
  state.attacks = (0, weapons_1.deriveAttacks)(state);
168
234
  }
235
+ // An explicit hit point total or armour class overrides the computed one —
236
+ // the player may have rolled hit points or be wearing something not in the SRD.
169
237
  if (Number.isFinite(Number(spec.hp))) {
170
238
  state.hp.max = Math.max(Number(spec.hp), 1);
171
239
  }
@@ -173,6 +241,8 @@ function buildCharacter(name, spec, owner) {
173
241
  if (Number.isFinite(Number(spec.ac))) {
174
242
  state.ac = Number(spec.ac);
175
243
  }
244
+ // An explicit speed wins over the race's, for a character with a reason to
245
+ // differ. The race set it first so the common case needs nothing.
176
246
  if (Number.isFinite(Number(spec.speed))) {
177
247
  state.speed = Number(spec.speed);
178
248
  }
@@ -180,19 +250,45 @@ function buildCharacter(name, spec, owner) {
180
250
  lastClassToolApplication = classTools;
181
251
  return state;
182
252
  }
253
+ /**
254
+ * What the race contributed to the character built most recently.
255
+ *
256
+ * `buildCharacter` returns a `SheetState` and changing that signature would ripple
257
+ * through every caller, so the detail is parked here for `create_sheet` to report
258
+ * in the same turn. Read it immediately or not at all.
259
+ */
183
260
  let lastRaceApplication = {
184
261
  increases: {},
185
262
  tools: [],
186
263
  outstanding: [],
187
264
  problems: [],
188
265
  };
266
+ /** The race detail from the last `buildCharacter` call. */
189
267
  function lastRaceResult() {
190
268
  return lastRaceApplication;
191
269
  }
192
270
  let lastClassToolApplication = { added: [], outstanding: [] };
271
+ /**
272
+ * What the primary class contributed in tool proficiency, parked for the same reason.
273
+ *
274
+ * The race reports its own; this is the other source and the one most often owed
275
+ * rather than granted — a bard is three instruments short until asked.
276
+ */
193
277
  function lastClassToolResult() {
194
278
  return lastClassToolApplication;
195
279
  }
280
+ /**
281
+ * Marks the armour a newly built character is wearing.
282
+ *
283
+ * Picks the single body armour that gives the highest armour class, since
284
+ * {@link rules.computeArmorClass} stops at the first equipped suit and wearing two
285
+ * is not a thing. Any shield is worn as well, because a shield always helps.
286
+ *
287
+ * Armour is only worn when it actually beats going without, which keeps this
288
+ * honest for a character whose class defends them better unarmoured — a Dexterity
289
+ * 20 character handed ring mail is worse off in it, so they do not put it on.
290
+ * @param state The character, mutated in place
291
+ */
196
292
  function equipStartingArmor(state) {
197
293
  const dex = rules.abilityModifier(state, 'dex');
198
294
  let best;
@@ -206,10 +302,24 @@ function equipStartingArmor(state) {
206
302
  }
207
303
  if (best && best.ac >= 10 + dex)
208
304
  best.item.eq = true;
305
+ // Matched the same loose way computeArmorClass matches it, so "wooden shield"
306
+ // and a plain "Shield" both count.
209
307
  const shield = state.inv.find((item) => /\bshield\b/i.test(item.n));
210
308
  if (shield)
211
309
  shield.eq = true;
212
310
  }
311
+ /**
312
+ * How many uses an item holds when it is acquired, and what spending one does.
313
+ *
314
+ * Nothing used to answer this, which meant nothing ever set `chg` on an inventory
315
+ * item. `spend` has always had a path for a charged item — its own comment names the
316
+ * healer's kit — but the data it reads was never written, so buying a kit and then
317
+ * spending a use came back as *"Homer has no resource called 'healer's kit'"* while
318
+ * the tool's description advertised exactly that call.
319
+ * @param name The item, as it is written on the sheet
320
+ * @param campaign Items this campaign has defined, which override the book
321
+ * @returns Its uses when new, or undefined for something not spent a use at a time
322
+ */
213
323
  function itemUses(name, campaign = {}) {
214
324
  const gear = gear_1.GEAR_USES[name.trim().toLowerCase()];
215
325
  if (gear)
@@ -222,12 +332,22 @@ function itemUses(name, campaign = {}) {
222
332
  note: item.charges.recharge ? `Regains ${item.charges.recharge}.` : undefined,
223
333
  };
224
334
  }
335
+ /**
336
+ * Stocks a newly acquired item with its uses.
337
+ *
338
+ * Quantity multiplies them: two healer's kits are twenty uses, which is the number
339
+ * the table cares about, rather than two objects each tracked to ten.
340
+ * @param item The item, mutated in place
341
+ * @param campaign Items this campaign has defined
342
+ * @returns The same item, for chaining off a map
343
+ */
225
344
  function stockItem(item, campaign = {}) {
226
345
  const uses = itemUses(item.n, campaign);
227
346
  if (uses)
228
347
  item.chg = uses.uses * Math.max(item.q, 1);
229
348
  return item;
230
349
  }
350
+ /** Parses an equipment entry like `arrows x40` or `studded leather`. */
231
351
  function parseItemEntry(entry) {
232
352
  const text = String(entry).trim();
233
353
  const quantified = /^(.*?)\s*[x×]\s*(\d+)$/i.exec(text);
@@ -247,6 +367,17 @@ function normalizeSkillList(skills) {
247
367
  .map((s) => String(s).trim().toLowerCase())
248
368
  .filter((s) => srd_1.SKILL_ABILITY[s] !== undefined);
249
369
  }
370
+ /**
371
+ * Tidies a list of languages into the spelling the race table uses.
372
+ *
373
+ * Title-cased and deduplicated case-insensitively, so a creator passing "elvish"
374
+ * for a half-elf does not leave the sheet listing both that and the race's own
375
+ * "Elvish". Deliberately not checked against a list: the SRD names a handful of
376
+ * languages but a table is free to invent one, and refusing "Emberwood Cant"
377
+ * would be wrong more often than right.
378
+ * @param languages What the caller listed
379
+ * @returns The languages, tidied, in the order given
380
+ */
250
381
  function normalizeLanguages(languages) {
251
382
  if (!Array.isArray(languages))
252
383
  return [];
@@ -261,6 +392,19 @@ function normalizeLanguages(languages) {
261
392
  }
262
393
  return result;
263
394
  }
395
+ /**
396
+ * Splits an expertise list into the skills and the tools.
397
+ *
398
+ * A rogue's Expertise may be spent on thieves' tools instead of a second skill, and
399
+ * `expertise` is the field a creator naturally puts it in. `normalizeSkillList` used
400
+ * to drop anything that was not a skill, so the tool vanished without a word.
401
+ *
402
+ * An entry is only treated as a tool when it **resolves in the SRD table**. Anything
403
+ * else is still dropped rather than assumed: routing every unrecognised entry to the
404
+ * tools would turn a misspelt skill into a tool proficiency nobody asked for.
405
+ * @param entries What the caller listed as expertise
406
+ * @returns The skills and the tools, separated
407
+ */
264
408
  function splitExpertise(entries) {
265
409
  if (!Array.isArray(entries))
266
410
  return { skills: [], tools: [] };
@@ -277,6 +421,13 @@ function splitExpertise(entries) {
277
421
  }
278
422
  return { skills, tools };
279
423
  }
424
+ /**
425
+ * Works out how many uses a class feature pool holds for this character.
426
+ * @param state The character, for its ability scores
427
+ * @param max The rule for the maximum
428
+ * @param classLevel The level in the class granting the feature
429
+ * @returns The pool's maximum, never below 1
430
+ */
280
431
  function featureUseMaximum(state, max, classLevel) {
281
432
  if ('fixed' in max)
282
433
  return max.fixed;
@@ -286,6 +437,7 @@ function featureUseMaximum(state, max, classLevel) {
286
437
  const value = rules.abilityModifier(state, max.ability) + (max.plus ?? 0);
287
438
  return Math.max(value, max.min ?? 1);
288
439
  }
440
+ // byLevel: the highest step the character has reached.
289
441
  let result = 0;
290
442
  for (const [from, uses] of max.byLevel) {
291
443
  if (classLevel >= from)
@@ -293,6 +445,20 @@ function featureUseMaximum(state, max, classLevel) {
293
445
  }
294
446
  return result;
295
447
  }
448
+ /**
449
+ * Gives the character the limited-use pools its classes grant at their levels.
450
+ *
451
+ * Computed rather than patched in afterwards. Every campaign before this one built
452
+ * sheets that tracked no features at all, so the first `spend` of a Second Wind or a
453
+ * Bardic Inspiration failed with "this character tracks no limited-use features" and
454
+ * the table stopped to repair the sheet mid-scene.
455
+ *
456
+ * A pool that already exists keeps its current value: this runs on a rebuild and on
457
+ * a level-up, and a character halfway through its rages should not be quietly
458
+ * refilled by growing a level. Only the maximum moves.
459
+ *
460
+ * @param state The state to update in place
461
+ */
296
462
  function applyClassFeatureUses(state) {
297
463
  for (const entry of state.class) {
298
464
  const features = srd_1.CLASS_FEATURE_USES[entry.c] || [];
@@ -305,16 +471,29 @@ function applyClassFeatureUses(state) {
305
471
  const existing = state.uses[feature.key];
306
472
  state.uses[feature.key] = {
307
473
  max,
474
+ // A new pool arrives full; an existing one keeps what is left of it,
475
+ // clamped in case the maximum shrank.
308
476
  cur: existing ? Math.min(existing.cur, max) : max,
309
477
  reset: feature.reset,
310
478
  };
311
479
  }
312
480
  }
313
481
  }
482
+ /**
483
+ * Recomputes everything the rules derive from the character's level, abilities
484
+ * and equipment: hit points, hit dice, armour class, initiative and spell slots.
485
+ * Current values are preserved where they still make sense.
486
+ * @param state The state to update in place
487
+ */
314
488
  function recomputeDerived(state) {
489
+ // A monster has no class, so there is nothing to rebuild its hit points, hit
490
+ // dice or spell slots from — this would replace the stat block's totals with a
491
+ // level-1 character's. `patch_sheet` exposes `recompute` to the model, so the
492
+ // refusal belongs here rather than in the caller.
315
493
  if (state.foe)
316
494
  return;
317
495
  const con = rules.abilityModifier(state, 'con');
496
+ // Hit points and hit dice, summed across classes.
318
497
  let maxHp = 0;
319
498
  let totalLevels = 0;
320
499
  const hitDice = {};
@@ -332,18 +511,25 @@ function recomputeDerived(state) {
332
511
  maxHp += levels * rules.averageHitPointsPerLevel(entry.c, con);
333
512
  }
334
513
  });
514
+ // Keep spent hit dice spent, but never above the new maximum.
335
515
  for (const [die, pool] of Object.entries(hitDice)) {
336
516
  const previous = state.hd[die];
337
517
  pool.cur = previous ? Math.min(previous.cur, pool.max) : pool.max;
338
518
  }
519
+ // A racial bonus per level — the hill dwarf's Dwarven Toughness — is derived
520
+ // from the race rather than stored, so it stays right as the character levels.
339
521
  maxHp += (0, races_1.racialHpPerLevel)(state) * totalLevels;
340
522
  state.hd = hitDice;
341
523
  state.hp.max = Math.max(maxHp, 1);
342
524
  state.hp.cur = (0, sheet_1.clamp)(state.hp.cur, 0, state.hp.max);
343
525
  state.initBonus = rules.abilityModifier(state, 'dex');
344
526
  state.ac = rules.computeArmorClass(state).ac;
527
+ // Spell slots: the maximum comes from the tables, the remaining count is
528
+ // preserved so recomputing does not silently refill a caster.
345
529
  const expected = rules.expectedSpellSlots(state);
346
530
  const pact = rules.pactMagicSlots(state);
531
+ // Pact Magic occupies `slots` only when the warlock casts nothing else, since
532
+ // then there is nothing for it to be confused with.
347
533
  const pactOnly = pact !== undefined &&
348
534
  !state.class.some((entry) => {
349
535
  const caster = srd_1.CLASSES[entry.c]?.caster;
@@ -356,10 +542,14 @@ function recomputeDerived(state) {
356
542
  slots[level] = {
357
543
  max,
358
544
  cur: Math.max(max - spent, 0),
545
+ // Warlock pact slots come back on a short rest; everyone else's on a long one.
359
546
  reset: pactOnly ? 'short' : 'long',
360
547
  };
361
548
  }
362
549
  state.slots = slots;
550
+ // A warlock who also casts from the shared table keeps Pact Magic as a named
551
+ // resource: the slots recharge on a short rest and cannot be pooled with the
552
+ // others, and `slots` has one entry per spell level with nowhere to say so.
363
553
  for (const key of Object.keys(state.uses)) {
364
554
  if (key.startsWith(PACT_MAGIC_PREFIX))
365
555
  delete state.uses[key];
@@ -374,9 +564,20 @@ function recomputeDerived(state) {
374
564
  reset: 'short',
375
565
  };
376
566
  }
567
+ // An attack cantrip is mechanically a weapon and belongs on the attacks list,
568
+ // where `check` looks. Rebuilt here rather than stored, because its bonus follows
569
+ // the spellcasting ability and its dice step up at 5th, 11th and 17th level.
377
570
  (0, cantrips_1.syncCantripAttacks)(state);
378
571
  }
572
+ /** Key prefix for Pact Magic slots held as a named resource, with their level. */
379
573
  const PACT_MAGIC_PREFIX = 'pact_magic_level_';
574
+ /**
575
+ * Applies damage, healing or temporary hit points, including the whole
576
+ * dying/death-save sequence.
577
+ * @param input The character's current state (not mutated)
578
+ * @param options What to apply
579
+ * @returns The new state and a summary, or a refusal
580
+ */
380
581
  function applyHitPoints(input, options) {
381
582
  const state = cloneState(input);
382
583
  const details = [];
@@ -399,6 +600,7 @@ function applyHitPoints(input, options) {
399
600
  }
400
601
  if (options.temp !== undefined) {
401
602
  const incoming = Math.max(Number(options.temp) || 0, 0);
603
+ // Temporary hit points never stack; the higher total wins.
402
604
  if (incoming > state.hp.temp) {
403
605
  details.push(`Temporary hit points set to ${incoming} (was ${state.hp.temp}).`);
404
606
  state.hp.temp = incoming;
@@ -423,8 +625,10 @@ function applyHealing(state, amount, details) {
423
625
  return refuse('dead', `${state.name} is dead and cannot be healed by hit points alone.`, 'A creature that has failed three death saving throws dies; only magic such as revivify can return it.', ['Use a spell that restores life', 'Continue without this character']);
424
626
  }
425
627
  const before = state.hp.cur;
628
+ // Exhaustion 4 halves the maximum, and healing cannot pass the halved figure.
426
629
  const max = rules.effectiveMaxHp(state);
427
630
  state.hp.cur = Math.min(state.hp.cur + amount, max);
631
+ // Healing from 0 ends the dying state.
428
632
  if (before === 0 && state.hp.cur > 0) {
429
633
  state.deathSaves = { s: 0, f: 0 };
430
634
  state.stable = false;
@@ -444,6 +648,7 @@ function applyDamage(state, raw, options, details) {
444
648
  if (remaining === 0) {
445
649
  return done(state, `${state.name} takes no${typeNote} damage.`, details);
446
650
  }
651
+ // Temporary hit points absorb first.
447
652
  if (state.hp.temp > 0) {
448
653
  const absorbed = Math.min(state.hp.temp, remaining);
449
654
  state.hp.temp -= absorbed;
@@ -453,9 +658,12 @@ function applyDamage(state, raw, options, details) {
453
658
  const wasDying = state.hp.cur === 0;
454
659
  if (wasDying && remaining > 0) {
455
660
  state.stable = false;
661
+ // Instant death applies at 0 hit points too: any damage meeting the
662
+ // maximum kills outright, without a saving throw.
456
663
  if (remaining >= rules.effectiveMaxHp(state)) {
457
664
  return instantDeath(state, remaining, typeNote, details);
458
665
  }
666
+ // Otherwise damage while dying costs a death save, or two on a critical.
459
667
  const failures = options.critical ? 2 : 1;
460
668
  state.deathSaves.f = Math.min(state.deathSaves.f + failures, 3);
461
669
  details.push(options.critical
@@ -467,11 +675,14 @@ function applyDamage(state, raw, options, details) {
467
675
  state.hp.cur = Math.max(before - remaining, 0);
468
676
  const overflow = remaining - before;
469
677
  if (state.hp.cur === 0) {
678
+ // "Monsters die at 0 hit points." A foe never falls unconscious, never
679
+ // stabilizes and never rolls a death save.
470
680
  if (state.foe) {
471
681
  state.deathSaves = { s: 0, f: 3 };
472
682
  state.stable = false;
473
683
  return done(state, `${state.name} takes ${remaining}${typeNote} damage and dies.`, details);
474
684
  }
685
+ // Massive damage: overflow at or above the maximum is instant death.
475
686
  if (overflow >= rules.effectiveMaxHp(state)) {
476
687
  return instantDeath(state, remaining, typeNote, details, overflow);
477
688
  }
@@ -482,6 +693,15 @@ function applyDamage(state, raw, options, details) {
482
693
  }
483
694
  return finishDamage(state, remaining, typeNote, details);
484
695
  }
696
+ /**
697
+ * Kills a character outright from massive damage.
698
+ * @param state The character, mutated in place
699
+ * @param amount The damage dealt, for the summary
700
+ * @param typeNote The damage type, pre-formatted with a leading space
701
+ * @param details Lines to append the explanation to
702
+ * @param overflow Damage left after reaching 0, when the character was still up
703
+ * @returns The completed mutation
704
+ */
485
705
  function instantDeath(state, amount, typeNote, details, overflow) {
486
706
  state.hp.cur = 0;
487
707
  state.deathSaves = { s: 0, f: 3 };
@@ -499,6 +719,12 @@ function finishDamage(state, amount, typeNote, details) {
499
719
  }
500
720
  return done(state, `${state.name} takes ${amount}${typeNote} damage, now at ${state.hp.cur}/${state.hp.max} hit points.`, details);
501
721
  }
722
+ /**
723
+ * Records a death saving throw result.
724
+ * @param input The character's state
725
+ * @param roll The d20 face rolled
726
+ * @returns The new state and what it means
727
+ */
502
728
  function recordDeathSave(input, roll) {
503
729
  const state = cloneState(input);
504
730
  if (state.hp.cur > 0) {
@@ -535,6 +761,16 @@ function recordDeathSave(input, roll) {
535
761
  }
536
762
  return done(state, `${state.name} has ${state.deathSaves.s} success and ${state.deathSaves.f} failure death saves.`, details);
537
763
  }
764
+ // ---------------------------------------------------------------------------
765
+ // Rests
766
+ // ---------------------------------------------------------------------------
767
+ /**
768
+ * Takes a short rest, optionally spending hit dice.
769
+ * @param input The character's state
770
+ * @param hitDiceToSpend How many hit dice to roll
771
+ * @param rng The random source
772
+ * @returns The new state and what was restored
773
+ */
538
774
  function shortRest(input, hitDiceToSpend, rng = dice_1.defaultRng) {
539
775
  const state = cloneState(input);
540
776
  const details = [];
@@ -553,6 +789,7 @@ function shortRest(input, hitDiceToSpend, rng = dice_1.defaultRng) {
553
789
  for (const [die, pool] of available) {
554
790
  while (pool.cur > 0 && spent < hitDiceToSpend) {
555
791
  const roll = (0, dice_1.rollOne)(`1${die}`, rng);
792
+ // Each hit die adds the Constitution modifier, minimum 0 healing.
556
793
  const gain = Math.max(roll.total + con, 0);
557
794
  healed += gain;
558
795
  pool.cur -= 1;
@@ -574,12 +811,20 @@ function shortRest(input, hitDiceToSpend, rng = dice_1.defaultRng) {
574
811
  details.push(`Recharged: ${recharged.join(', ')}.`);
575
812
  return done(state, `${state.name} takes a short rest, now at ${state.hp.cur}/${state.hp.max} hit points.`, details);
576
813
  }
814
+ /**
815
+ * Takes a long rest: all hit points, half the total hit dice (minimum one), all
816
+ * spell slots, all long-rest features, and one level of exhaustion removed.
817
+ * @param input The character's state
818
+ * @returns The new state and what was restored
819
+ */
577
820
  function longRest(input) {
578
821
  const state = cloneState(input);
579
822
  const details = [];
580
823
  if (state.hp.cur === 0 && state.deathSaves.f >= 3) {
581
824
  return refuse('dead', `${state.name} is dead and cannot benefit from a rest.`);
582
825
  }
826
+ // Exhaustion drops first, so a character at level 4 is restored to the whole
827
+ // maximum the rest leaves them with rather than the halved one they arrived at.
583
828
  if (state.exh > 0) {
584
829
  state.exh -= 1;
585
830
  details.push(`Exhaustion reduced to ${state.exh}.`);
@@ -607,6 +852,7 @@ function longRest(input) {
607
852
  details.push(`Recharged: ${recharged.join(', ')}.`);
608
853
  return done(state, `${state.name} finishes a long rest at full hit points.`, details);
609
854
  }
855
+ /** Refills the pools that come back on the given rest, returning what changed. */
610
856
  function rechargeResources(state, kind) {
611
857
  const changed = [];
612
858
  for (const [level, pool] of Object.entries(state.slots)) {
@@ -625,6 +871,17 @@ function rechargeResources(state, kind) {
625
871
  }
626
872
  return changed;
627
873
  }
874
+ // ---------------------------------------------------------------------------
875
+ // Resources
876
+ // ---------------------------------------------------------------------------
877
+ /**
878
+ * Spends or restores a limited resource, refusing when there is none left.
879
+ * @param input The character's state
880
+ * @param resource 'slot', 'hit_die', or a feature/item key
881
+ * @param amount How many to spend; negative restores
882
+ * @param slotLevel Required when resource is 'slot'
883
+ * @returns The new state, or a refusal naming what is still available
884
+ */
628
885
  function spendResource(input, resource, amount, slotLevel) {
629
886
  const state = cloneState(input);
630
887
  const key = resource.trim().toLowerCase().replace(/\s+/g, '_');
@@ -636,11 +893,32 @@ function spendResource(input, resource, amount, slotLevel) {
636
893
  }
637
894
  return spendNamedResource(state, key, amount);
638
895
  }
896
+ /**
897
+ * Hands a die to another character to spend on a future roll.
898
+ *
899
+ * The giver's own resource is spent by the caller; this is the half that used not to
900
+ * exist. A character may hold several, and duplicates are kept rather than merged —
901
+ * two bards can each inspire the same fighter, and they are two dice.
902
+ * @param input The receiving character
903
+ * @param boon What is being handed over
904
+ * @returns The new state
905
+ */
639
906
  function grantBoon(input, boon) {
640
907
  const state = cloneState(input);
641
908
  state.boons = [...(state.boons || []), boon];
642
909
  return done(state, `${state.name} is holding ${boon.n} (${boon.die})${boon.from ? ` from ${boon.from}` : ''}.`, [`Add it to a d20 roll, or to damage if the boon says so, before the outcome is called.`]);
643
910
  }
911
+ /**
912
+ * Spends a held die and reports what it rolled.
913
+ *
914
+ * Rolled here rather than handed back as an expression, because the point of the
915
+ * whole feature is that using it takes one call at the moment it matters. A die that
916
+ * needs a second round trip is one that gets forgotten again.
917
+ * @param input The character holding it
918
+ * @param name Which boon, matched loosely
919
+ * @param rng The random source
920
+ * @returns The new state and the roll, or a refusal when nothing is held
921
+ */
644
922
  function spendBoon(input, name, rng = dice_1.defaultRng) {
645
923
  const state = cloneState(input);
646
924
  const held = state.boons || [];
@@ -651,6 +929,10 @@ function spendBoon(input, name, rng = dice_1.defaultRng) {
651
929
  ? held.map((boon) => `Holding: ${boon.n} (${boon.die})`)
652
930
  : ['Nothing has been handed to this character']);
653
931
  }
932
+ // The die is added to a roll that has already happened. Refusing when there is
933
+ // none is the whole guard: a ranger once declared she was spending hers, it was
934
+ // rolled *before* the attack, and the number was then added to nothing — 12
935
+ // against a DC of 13 reported as a miss when 12 + 1 would have hit.
654
936
  const pending = state.pendingRoll;
655
937
  if (!pending) {
656
938
  return refuse('no_roll', `${state.name} has not made a roll for ${held[index].n} to be added to.`, 'A die like this is added to a d20 after it is rolled, not before.', [
@@ -661,6 +943,7 @@ function spendBoon(input, name, rng = dice_1.defaultRng) {
661
943
  const boon = held[index];
662
944
  const roll = (0, dice_1.rollOne)(boon.die, rng);
663
945
  const total = pending.total + roll.total;
946
+ // A natural 1 fails whatever is added to it, so the die buys nothing.
664
947
  const passed = pending.dc === undefined ? undefined : !pending.natural1 && total >= pending.dc;
665
948
  const turned = passed === true && pending.dc !== undefined && pending.total < pending.dc;
666
949
  state.boons = held.filter((_, i) => i !== index);
@@ -684,6 +967,9 @@ function spendBoon(input, name, rng = dice_1.defaultRng) {
684
967
  passed,
685
968
  turned,
686
969
  };
970
+ // Damage belongs with the hit it came from. Rolled here rather than left to a
971
+ // separate call, because the separate call was `roll_dice`, which is refused for
972
+ // a combatant's own attack — so the one legitimate route was the blocked one.
687
973
  if (turned && pending.kind === 'attack') {
688
974
  const attack = state.attacks.find((entry) => entry.n.toLowerCase() === (pending.subject || '').toLowerCase());
689
975
  if (attack) {
@@ -748,7 +1034,11 @@ function spendHitDie(state, amount) {
748
1034
  return done(state, `${state.name} now has ${remaining} hit dice.`);
749
1035
  }
750
1036
  function spendNamedResource(state, key, amount) {
1037
+ // An inventory item with charges (a healer's kit) is spent the same way.
751
1038
  const item = state.inv.find((i) => i.n.toLowerCase().replace(/\s+/g, '_') === key);
1039
+ // A sheet written before gear carried its uses has no count on the item at all,
1040
+ // and a character holding one is not helped by being told they have no such
1041
+ // thing. An item nothing has ever been spent from is a full one, so stock it now.
752
1042
  if (item && item.chg === undefined) {
753
1043
  const stock = itemUses(item.n);
754
1044
  if (stock)
@@ -759,6 +1049,10 @@ function spendNamedResource(state, key, amount) {
759
1049
  return refuse('no_resource', `${state.name}'s ${item.n} has ${item.chg} use${item.chg === 1 ? '' : 's'} left, not ${amount}.`, undefined, ['Use a different item', 'Buy or find a replacement']);
760
1050
  }
761
1051
  item.chg = Math.max(item.chg - amount, 0);
1052
+ // What the use actually does, every time. A tool that goes quiet here is how
1053
+ // a healer's kit came to restore two hit points to a character who was
1054
+ // standing — it does nothing of the sort, and nothing at all for someone who
1055
+ // is conscious.
762
1056
  const note = itemUses(item.n)?.note;
763
1057
  const details = note ? [note] : undefined;
764
1058
  if (item.chg === 0) {
@@ -794,6 +1088,10 @@ function describeSlots(state) {
794
1088
  ? [`Slots still available — ${available.join('; ')}`]
795
1089
  : ['No spell slots of any level remain'];
796
1090
  }
1091
+ // ---------------------------------------------------------------------------
1092
+ // Conditions and exhaustion
1093
+ // ---------------------------------------------------------------------------
1094
+ /** Adds a condition if it is not already present. */
797
1095
  function addCondition(state, name, duration) {
798
1096
  const key = name.trim().toLowerCase();
799
1097
  const existing = state.cond.find((c) => c.n === key);
@@ -805,18 +1103,33 @@ function addCondition(state, name, duration) {
805
1103
  state.cond.push(duration ? { n: key, dur: duration } : { n: key });
806
1104
  return true;
807
1105
  }
1106
+ /** Removes a condition, returning whether it was present. */
808
1107
  function removeCondition(state, name) {
809
1108
  const key = name.trim().toLowerCase();
810
1109
  const before = state.cond.length;
811
1110
  state.cond = state.cond.filter((c) => c.n !== key);
812
1111
  return state.cond.length !== before;
813
1112
  }
1113
+ /**
1114
+ * Sets exhaustion, clamped to the legal range.
1115
+ *
1116
+ * Reaching level 4 halves the hit point maximum, so current hit points above the
1117
+ * halved figure come down with it. The stored maximum is left alone — exhaustion
1118
+ * is recoverable, and halving it in place would lose the real total.
1119
+ * @param state The character, mutated in place
1120
+ * @param level The new exhaustion level
1121
+ * @returns The level actually set
1122
+ */
814
1123
  function setExhaustion(state, level) {
815
1124
  state.exh = (0, sheet_1.clamp)(Math.trunc(level), 0, srd_1.MAX_EXHAUSTION);
816
1125
  state.hp.cur = Math.min(state.hp.cur, rules.effectiveMaxHp(state));
817
1126
  return state.exh;
818
1127
  }
1128
+ // ---------------------------------------------------------------------------
1129
+ // Inventory and currency
1130
+ // ---------------------------------------------------------------------------
819
1131
  const COIN_ORDER = ['pp', 'gp', 'ep', 'sp', 'cp'];
1132
+ /** Adds items to a character's inventory, merging with a matching entry. */
820
1133
  function addItems(state, entries) {
821
1134
  const added = [];
822
1135
  for (const entry of entries) {
@@ -824,6 +1137,7 @@ function addItems(state, entries) {
824
1137
  const existing = state.inv.find((i) => i.n.toLowerCase() === item.n.toLowerCase());
825
1138
  if (existing) {
826
1139
  existing.q += item.q;
1140
+ // A second kit adds its uses to the first rather than replacing them.
827
1141
  if (item.chg !== undefined)
828
1142
  existing.chg = (existing.chg || 0) + item.chg;
829
1143
  added.push(`${item.n} (now ${existing.q})`);
@@ -835,6 +1149,12 @@ function addItems(state, entries) {
835
1149
  }
836
1150
  return added;
837
1151
  }
1152
+ /**
1153
+ * Removes items from a character's inventory.
1154
+ * @param state The character
1155
+ * @param entries Item entries, optionally quantified
1156
+ * @returns What was removed, and what could not be
1157
+ */
838
1158
  function removeItems(state, entries) {
839
1159
  const removed = [];
840
1160
  const missing = [];
@@ -855,6 +1175,14 @@ function removeItems(state, entries) {
855
1175
  }
856
1176
  return { removed, missing };
857
1177
  }
1178
+ /**
1179
+ * Adjusts a character's money by signed amounts, e.g. `+150 gp; -3 sp`.
1180
+ * Refuses rather than going negative, since a debt is a story matter and not a
1181
+ * number the tool should invent.
1182
+ * @param state The character
1183
+ * @param entries Signed coin entries
1184
+ * @returns The changes applied, or a refusal
1185
+ */
858
1186
  function adjustCoin(state, entries) {
859
1187
  const deltas = {};
860
1188
  for (const entry of entries) {
@@ -900,6 +1228,19 @@ function adjustCoin(state, entries) {
900
1228
  }
901
1229
  return { ok: true, changes };
902
1230
  }
1231
+ /**
1232
+ * Divides a pile of money into equal shares, losing none of it.
1233
+ *
1234
+ * The remainder is the point. 150 gp between four is 37 each and 2 gp left over,
1235
+ * and dropping those two — which is what flooring the division does — quietly
1236
+ * destroys money the party earned. Instead the odd coins go one apiece to the first
1237
+ * shares, so four characters get 38, 38, 37, 37 and the pile is conserved exactly.
1238
+ *
1239
+ * Negative amounts divide the same way, so a party can split a bill.
1240
+ * @param entries Coin entries, signed or not, e.g. `['150 gp', '30 sp']`
1241
+ * @param shares How many ways to divide it
1242
+ * @returns One entry list per share, or a refusal when an amount cannot be read
1243
+ */
903
1244
  function divideCoin(entries, shares) {
904
1245
  if (shares < 1) {
905
1246
  return {
@@ -935,6 +1276,8 @@ function divideCoin(entries, shares) {
935
1276
  const total = totals[denomination];
936
1277
  if (!total)
937
1278
  continue;
1279
+ // Truncation toward zero, so the remainder carries the pile's own sign and a
1280
+ // split debt divides the same way a split reward does.
938
1281
  const base = Math.trunc(total / shares);
939
1282
  const remainder = total - base * shares;
940
1283
  const extra = Math.sign(remainder);
@@ -954,11 +1297,19 @@ function divideCoin(entries, shares) {
954
1297
  .join(', '),
955
1298
  };
956
1299
  }
1300
+ /** A readable description of what a character is carrying in coin. */
957
1301
  function describeCoin(state) {
958
1302
  return COIN_ORDER.filter((d) => state.coin[d])
959
1303
  .map((d) => `${state.coin[d]} ${d}`)
960
1304
  .join(', ');
961
1305
  }
1306
+ /**
1307
+ * Marks items worn or wielded, recalculating armour class.
1308
+ * @param state The character
1309
+ * @param names Item names to change
1310
+ * @param equipped True to equip, false to unequip
1311
+ * @returns The items changed, and names that matched nothing
1312
+ */
962
1313
  function setEquipped(state, names, equipped) {
963
1314
  const changed = [];
964
1315
  const missing = [];
@@ -979,6 +1330,19 @@ function setEquipped(state, names, equipped) {
979
1330
  }
980
1331
  return { changed, missing };
981
1332
  }
1333
+ /**
1334
+ * Attunes or unattunes items, enforcing the three-item limit.
1335
+ *
1336
+ * The limit is a rule, so exceeding it is a **refusal** rather than a thrown
1337
+ * error: the caller is told what is already attuned so a player can choose what to
1338
+ * give up. An item that needs no attunement is reported rather than silently
1339
+ * marked, since attuning to it means the caller misread the item.
1340
+ * @param state The character, mutated in place
1341
+ * @param names Item names to change
1342
+ * @param attune True to attune, false to release
1343
+ * @param needsAttunement Answers whether an item requires attunement at all
1344
+ * @returns What changed, what was not carried, and any refusal
1345
+ */
982
1346
  function setAttunement(state, names, attune, needsAttunement) {
983
1347
  const changed = [];
984
1348
  const missing = [];
@@ -1025,6 +1389,14 @@ function setAttunement(state, names, attune, needsAttunement) {
1025
1389
  state.ac = rules.computeArmorClass(state).ac;
1026
1390
  return { changed, missing, unnecessary };
1027
1391
  }
1392
+ /**
1393
+ * Awards experience and reports any level-up that becomes available. Deliberately
1394
+ * does not apply the level: the player chooses the hit points, spells and
1395
+ * ability increases, and inventing those for them is the tool overstepping.
1396
+ * @param input The character's state
1397
+ * @param amount Experience to add; may be negative
1398
+ * @returns The new state, plus what the character may now level into
1399
+ */
1028
1400
  function awardExperience(input, amount) {
1029
1401
  const state = cloneState(input);
1030
1402
  const beforeLevel = rules.totalLevel(state);
@@ -1055,12 +1427,16 @@ function awardExperience(input, amount) {
1055
1427
  need,
1056
1428
  };
1057
1429
  }
1430
+ /** What a player must decide to take a level in their class. */
1058
1431
  function levelUpChoices(state, toLevel) {
1059
1432
  const primary = state.class[0];
1060
1433
  const classRules = srd_1.CLASSES[primary?.c || ''];
1061
1434
  const choices = [
1062
1435
  `Hit point increase: roll the class hit die (${primary?.hd || 'd8'}) and add the Constitution modifier, or take the fixed average`,
1063
1436
  ];
1437
+ // Both of these are per-class, and both depend on the level in *that* class
1438
+ // rather than the character's total: a fighter gains extra improvements at 6
1439
+ // and 14, and a cleric picks a domain at 1 while a wizard waits until 2.
1064
1440
  const classLevel = (Number(primary?.lvl) || 1) + (toLevel - rules.totalLevel(state));
1065
1441
  if (classRules?.asiLevels.includes(classLevel)) {
1066
1442
  choices.push('Ability score improvement: +2 to one ability or +1 to two — OR a feat instead of it, never both');
@@ -1075,6 +1451,13 @@ function levelUpChoices(state, toLevel) {
1075
1451
  choices.push('Any new class feature gained at this level, added with patch_sheet if it has uses');
1076
1452
  return choices;
1077
1453
  }
1454
+ /**
1455
+ * Applies a level increase and recalculates everything downstream.
1456
+ * @param input The character's state
1457
+ * @param toLevel The total level to reach
1458
+ * @param choices What the player chose
1459
+ * @returns The new state, or a refusal
1460
+ */
1078
1461
  function applyLevelUp(input, toLevel, choices) {
1079
1462
  const state = cloneState(input);
1080
1463
  const current = rules.totalLevel(state);
@@ -1113,6 +1496,8 @@ function applyLevelUp(input, toLevel, choices) {
1113
1496
  }
1114
1497
  const details = [];
1115
1498
  const gained = toLevel - current;
1499
+ // A feat is taken *instead of* the ability score improvement, never alongside
1500
+ // it, so asking for both is a rules error rather than a generous reading.
1116
1501
  const asiPicked = choices.asi && Object.keys(choices.asi).length > 0;
1117
1502
  if (asiPicked && choices.feat) {
1118
1503
  return {
@@ -1128,6 +1513,8 @@ function applyLevelUp(input, toLevel, choices) {
1128
1513
  },
1129
1514
  };
1130
1515
  }
1516
+ // The feat is vetted before anything is written, so a refusal leaves the
1517
+ // character exactly as they were rather than half-levelled.
1131
1518
  if (choices.feat) {
1132
1519
  if ((0, feats_1.hasFeat)(state, choices.feat)) {
1133
1520
  return {
@@ -1187,6 +1574,8 @@ function applyLevelUp(input, toLevel, choices) {
1187
1574
  if (choices.spells && choices.spells.length > 0) {
1188
1575
  state.spells = [...(state.spells || []), ...choices.spells];
1189
1576
  details.push(`Learned ${choices.spells.join(', ')}.`);
1577
+ // Reported rather than refused: a subclass or a racial trait can grant a
1578
+ // spell off-list, so this is a thing worth noticing, not a thing to block.
1190
1579
  for (const off of (0, spells_1.offListSpells)(state, choices.spells)) {
1191
1580
  details.push(off.onLists
1192
1581
  ? `${off.spell} is on the ${off.onLists.join('/')} list rather than this character's — check a subclass or racial trait grants it.`
@@ -1203,14 +1592,20 @@ function applyLevelUp(input, toLevel, choices) {
1203
1592
  }
1204
1593
  }
1205
1594
  entry.lvl += gained;
1595
+ // Hit points: an explicit roll if given, otherwise the fixed average the
1596
+ // rules offer. recomputeDerived would use the average for every level, so the
1597
+ // maximum is set explicitly here to honour a roll.
1206
1598
  const con = rules.abilityModifier(state, 'con');
1207
1599
  const perLevel = choices.hp !== undefined && Number.isFinite(Number(choices.hp))
1208
1600
  ? Math.max(Number(choices.hp), 1)
1209
1601
  : rules.averageHitPointsPerLevel(entry.c, con);
1210
1602
  const hpBefore = state.hp.max;
1211
1603
  recomputeDerived(state);
1604
+ // A level can widen a pool (a barbarian's third rage at 3) or open a new one (a
1605
+ // fighter's Action Surge at 2). What is already spent stays spent.
1212
1606
  applyClassFeatureUses(state);
1213
1607
  if (choices.hp !== undefined) {
1608
+ // Replace the averaged gain for the new levels with what was rolled.
1214
1609
  const averaged = rules.averageHitPointsPerLevel(entry.c, con) * gained;
1215
1610
  state.hp.max = state.hp.max - averaged + perLevel * gained;
1216
1611
  }
@@ -1223,6 +1618,8 @@ function applyLevelUp(input, toLevel, choices) {
1223
1618
  .map(([level, pool]) => `L${level} x${pool.max}`);
1224
1619
  if (slots.length > 0)
1225
1620
  details.push(`Spell slots: ${slots.join(', ')}.`);
1621
+ // Experience is topped up to the threshold so a level granted by the DM
1622
+ // without awarding experience does not immediately look under-levelled.
1226
1623
  const threshold = srd_1.XP_THRESHOLDS[Math.min(toLevel, srd_1.XP_THRESHOLDS.length - 1)];
1227
1624
  if (state.xp < threshold) {
1228
1625
  state.xp = threshold;
@@ -1235,6 +1632,10 @@ function applyLevelUp(input, toLevel, choices) {
1235
1632
  details,
1236
1633
  };
1237
1634
  }
1635
+ // ---------------------------------------------------------------------------
1636
+ // Helpers
1637
+ // ---------------------------------------------------------------------------
1638
+ /** A structural copy, so a refused mutation cannot have altered the original. */
1238
1639
  function cloneState(state) {
1239
1640
  return JSON.parse(JSON.stringify(state));
1240
1641
  }