briyah 1.3.4 → 1.4.0

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 (254) hide show
  1. package/README.md +689 -619
  2. package/data/common/artifacts/dnd5e/campaign_designer-setting.md +112 -0
  3. package/data/common/artifacts/dnd5e/character_creator-basics.md +40 -0
  4. package/data/common/artifacts/dnd5e/class-barbarian.md +64 -0
  5. package/data/common/artifacts/dnd5e/class-bard.md +63 -0
  6. package/data/common/artifacts/dnd5e/class-cleric.md +60 -0
  7. package/data/common/artifacts/dnd5e/class-druid.md +56 -0
  8. package/data/common/artifacts/dnd5e/class-fighter.md +53 -0
  9. package/data/common/artifacts/dnd5e/class-monk.md +77 -0
  10. package/data/common/artifacts/dnd5e/class-paladin.md +66 -0
  11. package/data/common/artifacts/dnd5e/class-ranger.md +73 -0
  12. package/data/common/artifacts/dnd5e/class-rogue.md +62 -0
  13. package/data/common/artifacts/dnd5e/class-sorcerer.md +67 -0
  14. package/data/common/artifacts/dnd5e/class-warlock.md +83 -0
  15. package/data/common/artifacts/dnd5e/class-wizard.md +51 -0
  16. package/data/common/artifacts/dnd5e/dungeon_master-procedure.md +348 -0
  17. package/data/common/artifacts/dnd5e/manifest.json +95 -0
  18. package/data/common/config/comfyui-workflows/flux-kontext.edit.json +98 -0
  19. package/data/common/config/comfyui-workflows/flux-kontext.t2i.json +80 -0
  20. package/data/common/config/comfyui-workflows/flux2-dev.edit.json +125 -0
  21. package/data/common/config/comfyui-workflows/flux2-dev.t2i.json +96 -0
  22. package/data/common/config/image_models_full.json +186 -99
  23. package/data/common/config/markup +1 -1
  24. package/data/common/config/model_prices.json +1250 -237
  25. package/data/common/prompts/campaign_designer/defaults_config.json +16 -0
  26. package/data/common/prompts/campaign_designer/perceive.json +29 -0
  27. package/data/common/prompts/campaign_designer/perceive.prompt +345 -0
  28. package/data/common/prompts/campaign_designer/system_instruction.prompt +0 -0
  29. package/data/common/prompts/character_creator/defaults_config.json +31 -0
  30. package/data/common/prompts/character_creator/perceive.json +29 -0
  31. package/data/common/prompts/character_creator/perceive.prompt +621 -0
  32. package/data/common/prompts/character_creator/system_instruction.prompt +0 -0
  33. package/data/common/prompts/dnd_player/defaults_config.json +5 -0
  34. package/data/common/prompts/dnd_player/perceive.json +29 -0
  35. package/data/common/prompts/dnd_player/perceive.prompt +312 -0
  36. package/data/common/prompts/dnd_player/system_instruction.prompt +0 -0
  37. package/data/common/prompts/dnd_room_moderator/defaults_config.json +9 -0
  38. package/data/common/prompts/dnd_room_moderator/moderate.json +34 -0
  39. package/data/common/prompts/dnd_room_moderator/moderate.prompt +291 -0
  40. package/data/common/prompts/dnd_room_moderator/system_instruction.prompt +0 -0
  41. package/data/common/prompts/dungeon_master/compact_agent.prompt +24 -0
  42. package/data/common/prompts/dungeon_master/defaults_config.json +29 -0
  43. package/data/common/prompts/dungeon_master/perceive.json +33 -0
  44. package/data/common/prompts/dungeon_master/perceive.prompt +757 -0
  45. package/data/common/prompts/dungeon_master/system_instruction.prompt +0 -0
  46. package/data/common/prompts/room_moderator/moderate.json +34 -29
  47. package/data/common/prompts/room_moderator/moderate.prompt +230 -210
  48. package/data/common/prompts/story_moderator/moderate.prompt +5 -2
  49. package/data/common/prompts/story_moderator/moderate_to_alice.mock +6 -6
  50. package/data/common/prompts/story_moderator/moderate_to_bob.mock +6 -6
  51. package/dist-sdk/server/src/ai/LLM/anthropic.service.d.ts +2 -0
  52. package/dist-sdk/server/src/ai/LLM/anthropic.service.js +34 -22
  53. package/dist-sdk/server/src/ai/LLM/base-ai.service.d.ts +2 -0
  54. package/dist-sdk/server/src/ai/LLM/base-ai.service.js +8 -3
  55. package/dist-sdk/server/src/ai/LLM/comfyui-client.d.ts +29 -0
  56. package/dist-sdk/server/src/ai/LLM/comfyui-client.js +142 -0
  57. package/dist-sdk/server/src/ai/LLM/comfyui-workflow.d.ts +19 -0
  58. package/dist-sdk/server/src/ai/LLM/comfyui-workflow.js +217 -0
  59. package/dist-sdk/server/src/ai/LLM/comfyui.module.d.ts +2 -0
  60. package/dist-sdk/server/src/ai/LLM/comfyui.module.js +21 -0
  61. package/dist-sdk/server/src/ai/LLM/comfyui.service.d.ts +26 -0
  62. package/dist-sdk/server/src/ai/LLM/comfyui.service.js +191 -0
  63. package/dist-sdk/server/src/ai/LLM/mock.service.d.ts +1 -0
  64. package/dist-sdk/server/src/ai/LLM/mock.service.js +3 -0
  65. package/dist-sdk/server/src/ai/LLM/self-hosted.module.d.ts +2 -0
  66. package/dist-sdk/server/src/ai/LLM/self-hosted.module.js +21 -0
  67. package/dist-sdk/server/src/ai/LLM/self-hosted.service.d.ts +13 -0
  68. package/dist-sdk/server/src/ai/LLM/self-hosted.service.js +205 -0
  69. package/dist-sdk/server/src/ai/agent-config.d.ts +1 -0
  70. package/dist-sdk/server/src/ai/agent-store.service.js +6 -4
  71. package/dist-sdk/server/src/ai/agent.d.ts +7 -0
  72. package/dist-sdk/server/src/ai/agent.js +33 -2
  73. package/dist-sdk/server/src/ai/ai-factory.module.js +4 -0
  74. package/dist-sdk/server/src/ai/ai-factory.service.d.ts +5 -1
  75. package/dist-sdk/server/src/ai/ai-factory.service.js +16 -2
  76. package/dist-sdk/server/src/ai/artifact.service.d.ts +2 -0
  77. package/dist-sdk/server/src/ai/artifact.service.js +29 -1
  78. package/dist-sdk/server/src/ai/pack-artifacts.d.ts +7 -0
  79. package/dist-sdk/server/src/ai/pack-artifacts.js +155 -0
  80. package/dist-sdk/server/src/app/stripe.controller.js +5 -0
  81. package/dist-sdk/server/src/app.controller.d.ts +18 -18
  82. package/dist-sdk/server/src/app.controller.js +249 -25
  83. package/dist-sdk/server/src/app.service.d.ts +30 -17
  84. package/dist-sdk/server/src/app.service.js +304 -36
  85. package/dist-sdk/server/src/auth/auth.controller.js +3 -2
  86. package/dist-sdk/server/src/auth/owner-only.decorator.d.ts +1 -0
  87. package/dist-sdk/server/src/auth/owner-only.decorator.js +8 -0
  88. package/dist-sdk/server/src/auth/twilio.service.d.ts +5 -1
  89. package/dist-sdk/server/src/auth/twilio.service.js +5 -3
  90. package/dist-sdk/server/src/config/user-paths.service.d.ts +2 -0
  91. package/dist-sdk/server/src/config/user-paths.service.js +8 -0
  92. package/dist-sdk/server/src/room/artifact-store.service.js +10 -2
  93. package/dist-sdk/server/src/room/artifact.d.ts +1 -0
  94. package/dist-sdk/server/src/room/message.d.ts +2 -1
  95. package/dist-sdk/server/src/room/message.js +5 -4
  96. package/dist-sdk/server/src/room/room-config.d.ts +3 -0
  97. package/dist-sdk/server/src/room/room-store.service.d.ts +4 -2
  98. package/dist-sdk/server/src/room/room-store.service.js +46 -12
  99. package/dist-sdk/server/src/room/room.d.ts +29 -3
  100. package/dist-sdk/server/src/room/room.js +390 -122
  101. package/dist-sdk/server/src/sdk/briyah.js +21 -3
  102. package/dist-sdk/server/src/sdk/index.d.ts +4 -1
  103. package/dist-sdk/server/src/sdk/index.js +9 -1
  104. package/dist-sdk/server/src/story/story.service.js +21 -12
  105. package/dist-sdk/server/src/tools/native-tool.types.d.ts +31 -0
  106. package/dist-sdk/server/src/tools/packs/dnd5e/data/backgrounds.d.ts +22 -0
  107. package/dist-sdk/server/src/tools/packs/dnd5e/data/backgrounds.js +59 -0
  108. package/dist-sdk/server/src/tools/packs/dnd5e/data/feats.d.ts +24 -0
  109. package/dist-sdk/server/src/tools/packs/dnd5e/data/feats.js +11 -0
  110. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.d.ts +5 -0
  111. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.generated.d.ts +1 -0
  112. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.generated.js +154 -0
  113. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.js +9 -0
  114. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.d.ts +20 -0
  115. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.generated.d.ts +2 -0
  116. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.generated.js +1824 -0
  117. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.js +6 -0
  118. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.d.ts +44 -0
  119. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.generated.d.ts +2 -0
  120. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.generated.js +17293 -0
  121. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.js +5 -0
  122. package/dist-sdk/server/src/tools/packs/dnd5e/data/races.d.ts +41 -0
  123. package/dist-sdk/server/src/tools/packs/dnd5e/data/races.js +250 -0
  124. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.d.ts +16 -0
  125. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.generated.d.ts +2 -0
  126. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.generated.js +3760 -0
  127. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.js +12 -0
  128. package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.d.ts +63 -0
  129. package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.js +449 -0
  130. package/dist-sdk/server/src/tools/packs/dnd5e/data/weapons.d.ts +23 -0
  131. package/dist-sdk/server/src/tools/packs/dnd5e/data/weapons.js +88 -0
  132. package/dist-sdk/server/src/tools/packs/dnd5e/engine/backgrounds.d.ts +20 -0
  133. package/dist-sdk/server/src/tools/packs/dnd5e/engine/backgrounds.js +109 -0
  134. package/dist-sdk/server/src/tools/packs/dnd5e/engine/bestiary.d.ts +30 -0
  135. package/dist-sdk/server/src/tools/packs/dnd5e/engine/bestiary.js +329 -0
  136. package/dist-sdk/server/src/tools/packs/dnd5e/engine/campaign-items.d.ts +9 -0
  137. package/dist-sdk/server/src/tools/packs/dnd5e/engine/campaign-items.js +100 -0
  138. package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.d.ts +117 -0
  139. package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.js +1057 -0
  140. package/dist-sdk/server/src/tools/packs/dnd5e/engine/coerce.d.ts +13 -0
  141. package/dist-sdk/server/src/tools/packs/dnd5e/engine/coerce.js +147 -0
  142. package/dist-sdk/server/src/tools/packs/dnd5e/engine/dice.d.ts +27 -0
  143. package/dist-sdk/server/src/tools/packs/dnd5e/engine/dice.js +263 -0
  144. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encumbrance.d.ts +26 -0
  145. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encumbrance.js +129 -0
  146. package/dist-sdk/server/src/tools/packs/dnd5e/engine/feats.d.ts +22 -0
  147. package/dist-sdk/server/src/tools/packs/dnd5e/engine/feats.js +127 -0
  148. package/dist-sdk/server/src/tools/packs/dnd5e/engine/items.d.ts +33 -0
  149. package/dist-sdk/server/src/tools/packs/dnd5e/engine/items.js +137 -0
  150. package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.d.ts +26 -0
  151. package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.js +182 -0
  152. package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.d.ts +48 -0
  153. package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.js +344 -0
  154. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.d.ts +98 -0
  155. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.js +456 -0
  156. package/dist-sdk/server/src/tools/packs/dnd5e/engine/spells.d.ts +27 -0
  157. package/dist-sdk/server/src/tools/packs/dnd5e/engine/spells.js +123 -0
  158. package/dist-sdk/server/src/tools/packs/dnd5e/engine/weapons.d.ts +23 -0
  159. package/dist-sdk/server/src/tools/packs/dnd5e/engine/weapons.js +201 -0
  160. package/dist-sdk/server/src/tools/packs/dnd5e/index.d.ts +3 -0
  161. package/dist-sdk/server/src/tools/packs/dnd5e/index.js +35 -0
  162. package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.d.ts +2 -0
  163. package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.js +323 -0
  164. package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.d.ts +3 -0
  165. package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.js +117 -0
  166. package/dist-sdk/server/src/tools/packs/dnd5e/tools/item.tool.d.ts +2 -0
  167. package/dist-sdk/server/src/tools/packs/dnd5e/tools/item.tool.js +122 -0
  168. package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.d.ts +2 -0
  169. package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.js +157 -0
  170. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.d.ts +32 -0
  171. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.js +203 -0
  172. package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.d.ts +4 -0
  173. package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.js +465 -0
  174. package/dist-sdk/server/src/tools/packs/dnd5e/tools/spell.tool.d.ts +2 -0
  175. package/dist-sdk/server/src/tools/packs/dnd5e/tools/spell.tool.js +116 -0
  176. package/dist-sdk/server/src/tools/packs/dnd5e/tools/state.tools.d.ts +4 -0
  177. package/dist-sdk/server/src/tools/packs/dnd5e/tools/state.tools.js +234 -0
  178. package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.d.ts +6 -0
  179. package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.js +616 -0
  180. package/dist-sdk/server/src/tools/packs/index.d.ts +7 -0
  181. package/dist-sdk/server/src/tools/packs/index.js +45 -0
  182. package/dist-sdk/server/src/tools/tool-execution.service.d.ts +2 -2
  183. package/dist-sdk/server/src/tools/tool-execution.service.js +7 -6
  184. package/dist-sdk/shared/types/app.types.d.ts +63 -0
  185. package/docs/assets/hierarchy.js +1 -1
  186. package/docs/assets/navigation.js +1 -1
  187. package/docs/assets/search.js +1 -1
  188. package/docs/classes/Agent.html +51 -15
  189. package/docs/classes/Briyah.html +14 -14
  190. package/docs/classes/BriyahConfigService.html +5 -5
  191. package/docs/classes/NativeToolRegistry.html +21 -0
  192. package/docs/classes/Room.html +79 -29
  193. package/docs/classes/RoomMessage.html +32 -15
  194. package/docs/enums/MessageAction.html +3 -3
  195. package/docs/functions/availableToolPacks.html +2 -0
  196. package/docs/functions/dnd5eTools.html +5 -0
  197. package/docs/functions/enabledToolPacks.html +2 -0
  198. package/docs/functions/registerToolPacks.html +6 -0
  199. package/docs/hierarchy.html +1 -1
  200. package/docs/index.html +47 -3
  201. package/docs/interfaces/AgentInfo.html +17 -2
  202. package/docs/interfaces/AgentMessagesResponse.html +2 -2
  203. package/docs/interfaces/AppService.html +230 -181
  204. package/docs/interfaces/Artifact.html +15 -3
  205. package/docs/interfaces/ArtifactMetadata.html +5 -2
  206. package/docs/interfaces/ArtifactWriteOptions.html +21 -0
  207. package/docs/interfaces/AttachDocumentResponse.html +2 -2
  208. package/docs/interfaces/BriyahConfigOptions.html +9 -9
  209. package/docs/interfaces/ChapterInfo.html +2 -2
  210. package/docs/interfaces/Character.html +2 -2
  211. package/docs/interfaces/CreateAgentResponse.html +2 -2
  212. package/docs/interfaces/CreateRoomResponse.html +2 -2
  213. package/docs/interfaces/CreateStoryResponse.html +2 -2
  214. package/docs/interfaces/FileList.html +2 -2
  215. package/docs/interfaces/FileMetadata.html +3 -3
  216. package/docs/interfaces/IConfigService.html +3 -3
  217. package/docs/interfaces/LoggingOptions.html +6 -6
  218. package/docs/interfaces/Message.html +2 -2
  219. package/docs/interfaces/ModelInfo.html +2 -2
  220. package/docs/interfaces/NativeToolDefinition.html +11 -7
  221. package/docs/interfaces/PreparedPromptResponse.html +2 -2
  222. package/docs/interfaces/ProcessTextResponse.html +2 -2
  223. package/docs/interfaces/PromptFile.html +2 -2
  224. package/docs/interfaces/PromptFileContent.html +2 -2
  225. package/docs/interfaces/PromptFilesResponse.html +2 -2
  226. package/docs/interfaces/PromptFolder.html +2 -2
  227. package/docs/interfaces/PromptFoldersResponse.html +2 -2
  228. package/docs/interfaces/RoomDetails.html +15 -2
  229. package/docs/interfaces/RoomInfo.html +3 -2
  230. package/docs/interfaces/RoomMessageUpdate.html +2 -2
  231. package/docs/interfaces/RoomMessagesResponse.html +2 -2
  232. package/docs/interfaces/SendMessageResult.html +2 -2
  233. package/docs/interfaces/StoryErrorEvent.html +3 -3
  234. package/docs/interfaces/StoryIdea.html +2 -2
  235. package/docs/interfaces/StoryInfo.html +3 -3
  236. package/docs/interfaces/StoryIntroduceCharacterEvent.html +3 -3
  237. package/docs/interfaces/StoryProgressChapterEvent.html +3 -3
  238. package/docs/interfaces/StoryState.html +5 -5
  239. package/docs/interfaces/StoryStateEvent.html +3 -3
  240. package/docs/interfaces/ToolArtifact.html +8 -0
  241. package/docs/interfaces/ToolCaller.html +8 -0
  242. package/docs/interfaces/ToolDefinition.html +2 -2
  243. package/docs/interfaces/ToolHelpers.html +7 -3
  244. package/docs/interfaces/ToolParameter.html +2 -2
  245. package/docs/interfaces/ToolRoomAccess.html +51 -0
  246. package/docs/interfaces/ToolSummary.html +3 -2
  247. package/docs/interfaces/ToolsResponse.html +2 -2
  248. package/docs/interfaces/Transaction.html +2 -2
  249. package/docs/interfaces/TransactionHistoryResponse.html +2 -2
  250. package/docs/modules.html +1 -1
  251. package/docs/types/PromptScope.html +1 -1
  252. package/docs/types/ToolContext.html +2 -2
  253. package/docs/types/ToolRunResult.html +1 -1
  254. package/package.json +7 -4
@@ -0,0 +1,1057 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.STANDARD_ARRAY = void 0;
37
+ exports.isRefusal = isRefusal;
38
+ exports.isSuccess = isSuccess;
39
+ exports.buildCharacter = buildCharacter;
40
+ exports.lastRaceResult = lastRaceResult;
41
+ exports.lastBackgroundResult = lastBackgroundResult;
42
+ exports.parseItemEntry = parseItemEntry;
43
+ exports.applyClassFeatureUses = applyClassFeatureUses;
44
+ exports.recomputeDerived = recomputeDerived;
45
+ exports.applyHitPoints = applyHitPoints;
46
+ exports.recordDeathSave = recordDeathSave;
47
+ exports.shortRest = shortRest;
48
+ exports.longRest = longRest;
49
+ exports.spendResource = spendResource;
50
+ exports.addCondition = addCondition;
51
+ exports.removeCondition = removeCondition;
52
+ exports.setExhaustion = setExhaustion;
53
+ exports.addItems = addItems;
54
+ exports.removeItems = removeItems;
55
+ exports.adjustCoin = adjustCoin;
56
+ exports.describeCoin = describeCoin;
57
+ exports.setEquipped = setEquipped;
58
+ exports.setAttunement = setAttunement;
59
+ exports.awardExperience = awardExperience;
60
+ exports.applyLevelUp = applyLevelUp;
61
+ exports.cloneState = cloneState;
62
+ const srd_1 = require("../data/srd");
63
+ const magic_items_1 = require("../data/magic-items");
64
+ const dice_1 = require("./dice");
65
+ const rules = __importStar(require("./rules"));
66
+ const weapons_1 = require("./weapons");
67
+ const races_1 = require("./races");
68
+ const backgrounds_1 = require("./backgrounds");
69
+ const spells_1 = require("./spells");
70
+ const feats_1 = require("./feats");
71
+ const sheet_1 = require("./sheet");
72
+ function isRefusal(result) {
73
+ return result.ok === false;
74
+ }
75
+ function isSuccess(result) {
76
+ return result.ok === true;
77
+ }
78
+ exports.STANDARD_ARRAY = [15, 14, 13, 12, 10, 8];
79
+ function buildCharacter(name, spec, owner) {
80
+ const primaryKey = rules.resolveClass(spec.class || '');
81
+ if (!primaryKey) {
82
+ throw new sheet_1.SheetError('unknown_class', `"${spec.class || ''}" is not a class in the SRD. Choose one of: ${Object.keys(srd_1.CLASSES).join(', ')}.`);
83
+ }
84
+ const classes = [
85
+ {
86
+ c: primaryKey,
87
+ sub: spec.subclass || undefined,
88
+ lvl: Math.max(Number(spec.level) || 1, 1),
89
+ hd: srd_1.CLASSES[primaryKey].hitDie,
90
+ },
91
+ ];
92
+ for (const extra of spec.classes || []) {
93
+ const key = rules.resolveClass(extra.class || '');
94
+ if (!key || key === primaryKey)
95
+ continue;
96
+ classes.push({
97
+ c: key,
98
+ sub: extra.subclass || undefined,
99
+ lvl: Math.max(Number(extra.level) || 1, 1),
100
+ hd: srd_1.CLASSES[key].hitDie,
101
+ });
102
+ }
103
+ const abil = {};
104
+ srd_1.ABILITIES.forEach((ability, index) => {
105
+ const supplied = Number(spec.abilities?.[ability]);
106
+ abil[ability] = Number.isFinite(supplied) ? (0, sheet_1.clamp)(supplied, 1, 30) : exports.STANDARD_ARRAY[index];
107
+ });
108
+ const inv = (spec.equipment || []).map(parseItemEntry);
109
+ const state = {
110
+ v: sheet_1.SHEET_STATE_VERSION,
111
+ rev: 1,
112
+ name,
113
+ owner,
114
+ race: spec.race || undefined,
115
+ bg: spec.background || undefined,
116
+ align: spec.alignment || undefined,
117
+ class: classes,
118
+ abil,
119
+ saveProf: [...srd_1.CLASSES[primaryKey].saves],
120
+ skillProf: normalizeSkillList(spec.skills),
121
+ skillExp: normalizeSkillList(spec.expertise),
122
+ hp: { max: 1, cur: 1, temp: 0 },
123
+ hd: {},
124
+ ac: 10,
125
+ speed: Number(spec.speed) || 30,
126
+ initBonus: 0,
127
+ slots: {},
128
+ uses: {},
129
+ attacks: Array.isArray(spec.attacks) ? spec.attacks : [],
130
+ spells: Array.isArray(spec.spells) && spec.spells.length > 0 ? spec.spells : undefined,
131
+ cond: [],
132
+ exh: 0,
133
+ deathSaves: { s: 0, f: 0 },
134
+ stable: false,
135
+ resist: [],
136
+ immune: [],
137
+ vuln: [],
138
+ inv,
139
+ coin: spec.coin || { gp: 10 },
140
+ xp: Math.max(Number(spec.xp) || 0, 0),
141
+ };
142
+ const race = spec.applyRacialBonuses === false
143
+ ? { increases: {}, outstanding: [], problems: [] }
144
+ : (0, races_1.applyRace)(state, spec.raceAbilityChoices);
145
+ recomputeDerived(state);
146
+ applyClassFeatureUses(state);
147
+ const background = (0, backgrounds_1.applyBackground)(state, spec.backgroundEquipment !== false);
148
+ if (background.equipment.length > 0) {
149
+ const added = addItems(state, background.equipment);
150
+ if (added.length > 0)
151
+ background.changes.push(`gained ${added.join(', ')}`);
152
+ }
153
+ if (background.coin.length > 0) {
154
+ const coin = adjustCoin(state, background.coin);
155
+ if (coin.ok)
156
+ background.changes.push(`coin ${coin.changes.join(', ')}`);
157
+ }
158
+ for (const feat of spec.feats || []) {
159
+ if (!(0, feats_1.hasFeat)(state, feat))
160
+ (0, feats_1.applyFeat)(state, feat);
161
+ }
162
+ equipStartingArmor(state);
163
+ state.ac = rules.computeArmorClass(state).ac;
164
+ if (state.attacks.length === 0) {
165
+ state.attacks = (0, weapons_1.deriveAttacks)(state);
166
+ }
167
+ if (Number.isFinite(Number(spec.hp))) {
168
+ state.hp.max = Math.max(Number(spec.hp), 1);
169
+ }
170
+ state.hp.cur = state.hp.max;
171
+ if (Number.isFinite(Number(spec.ac))) {
172
+ state.ac = Number(spec.ac);
173
+ }
174
+ if (Number.isFinite(Number(spec.speed))) {
175
+ state.speed = Number(spec.speed);
176
+ }
177
+ lastRaceApplication = race;
178
+ lastBackgroundApplication = background;
179
+ return state;
180
+ }
181
+ let lastRaceApplication = { increases: {}, outstanding: [], problems: [] };
182
+ function lastRaceResult() {
183
+ return lastRaceApplication;
184
+ }
185
+ let lastBackgroundApplication = {
186
+ known: false,
187
+ changes: [],
188
+ outstanding: [],
189
+ equipment: [],
190
+ coin: [],
191
+ };
192
+ function lastBackgroundResult() {
193
+ return lastBackgroundApplication;
194
+ }
195
+ function equipStartingArmor(state) {
196
+ const dex = rules.abilityModifier(state, 'dex');
197
+ let best;
198
+ for (const item of state.inv) {
199
+ const armor = rules.resolveArmor(item.n);
200
+ if (!armor)
201
+ continue;
202
+ const ac = armor.baseAc + rules.armorDexBonus(armor, dex);
203
+ if (!best || ac > best.ac)
204
+ best = { item, ac };
205
+ }
206
+ if (best && best.ac >= 10 + dex)
207
+ best.item.eq = true;
208
+ const shield = state.inv.find((item) => /\bshield\b/i.test(item.n));
209
+ if (shield)
210
+ shield.eq = true;
211
+ }
212
+ function parseItemEntry(entry) {
213
+ const text = String(entry).trim();
214
+ const quantified = /^(.*?)\s*[x×]\s*(\d+)$/i.exec(text);
215
+ if (quantified) {
216
+ return { n: quantified[1].trim(), q: parseInt(quantified[2], 10) };
217
+ }
218
+ const leading = /^(\d+)\s+(.*)$/.exec(text);
219
+ if (leading && !/^\d+\s*(ft|feet|foot)\b/i.test(text)) {
220
+ return { n: leading[2].trim(), q: parseInt(leading[1], 10) };
221
+ }
222
+ return { n: text, q: 1 };
223
+ }
224
+ function normalizeSkillList(skills) {
225
+ if (!Array.isArray(skills))
226
+ return [];
227
+ return skills
228
+ .map((s) => String(s).trim().toLowerCase())
229
+ .filter((s) => srd_1.SKILL_ABILITY[s] !== undefined);
230
+ }
231
+ function featureUseMaximum(state, max, classLevel) {
232
+ if ('fixed' in max)
233
+ return max.fixed;
234
+ if ('perLevel' in max)
235
+ return max.perLevel * classLevel;
236
+ if ('ability' in max) {
237
+ const value = rules.abilityModifier(state, max.ability) + (max.plus ?? 0);
238
+ return Math.max(value, max.min ?? 1);
239
+ }
240
+ let result = 0;
241
+ for (const [from, uses] of max.byLevel) {
242
+ if (classLevel >= from)
243
+ result = uses;
244
+ }
245
+ return result;
246
+ }
247
+ function applyClassFeatureUses(state) {
248
+ for (const entry of state.class) {
249
+ const features = srd_1.CLASS_FEATURE_USES[entry.c] || [];
250
+ for (const feature of features) {
251
+ if (entry.lvl < feature.from)
252
+ continue;
253
+ const max = featureUseMaximum(state, feature.max, entry.lvl);
254
+ if (max <= 0)
255
+ continue;
256
+ const existing = state.uses[feature.key];
257
+ state.uses[feature.key] = {
258
+ max,
259
+ cur: existing ? Math.min(existing.cur, max) : max,
260
+ reset: feature.reset,
261
+ };
262
+ }
263
+ }
264
+ }
265
+ function recomputeDerived(state) {
266
+ const con = rules.abilityModifier(state, 'con');
267
+ let maxHp = 0;
268
+ let totalLevels = 0;
269
+ const hitDice = {};
270
+ state.class.forEach((entry, index) => {
271
+ const levels = Math.max(Number(entry.lvl) || 1, 1);
272
+ totalLevels += levels;
273
+ const die = entry.hd || srd_1.CLASSES[entry.c]?.hitDie || 'd8';
274
+ hitDice[die] = hitDice[die] || { max: 0, cur: 0 };
275
+ hitDice[die].max += levels;
276
+ if (index === 0) {
277
+ maxHp += rules.level1HitPoints(entry.c, con);
278
+ maxHp += (levels - 1) * rules.averageHitPointsPerLevel(entry.c, con);
279
+ }
280
+ else {
281
+ maxHp += levels * rules.averageHitPointsPerLevel(entry.c, con);
282
+ }
283
+ });
284
+ for (const [die, pool] of Object.entries(hitDice)) {
285
+ const previous = state.hd[die];
286
+ pool.cur = previous ? Math.min(previous.cur, pool.max) : pool.max;
287
+ }
288
+ maxHp += (0, races_1.racialHpPerLevel)(state) * totalLevels;
289
+ state.hd = hitDice;
290
+ state.hp.max = Math.max(maxHp, 1);
291
+ state.hp.cur = (0, sheet_1.clamp)(state.hp.cur, 0, state.hp.max);
292
+ state.initBonus = rules.abilityModifier(state, 'dex');
293
+ state.ac = rules.computeArmorClass(state).ac;
294
+ const expected = rules.expectedSpellSlots(state);
295
+ const pact = rules.pactMagicSlots(state);
296
+ const pactOnly = pact !== undefined &&
297
+ !state.class.some((entry) => {
298
+ const caster = srd_1.CLASSES[entry.c]?.caster;
299
+ return caster && caster !== 'none' && caster !== 'warlock';
300
+ });
301
+ const slots = {};
302
+ for (const [level, max] of Object.entries(expected)) {
303
+ const previous = state.slots[level];
304
+ const spent = previous ? Math.max(previous.max - previous.cur, 0) : 0;
305
+ slots[level] = {
306
+ max,
307
+ cur: Math.max(max - spent, 0),
308
+ reset: pactOnly ? 'short' : 'long',
309
+ };
310
+ }
311
+ state.slots = slots;
312
+ for (const key of Object.keys(state.uses)) {
313
+ if (key.startsWith(PACT_MAGIC_PREFIX))
314
+ delete state.uses[key];
315
+ }
316
+ if (pact && !pactOnly) {
317
+ const key = `${PACT_MAGIC_PREFIX}${pact.level}`;
318
+ const previous = state.uses[key];
319
+ const spent = previous ? Math.max(previous.max - previous.cur, 0) : 0;
320
+ state.uses[key] = {
321
+ max: pact.count,
322
+ cur: Math.max(pact.count - spent, 0),
323
+ reset: 'short',
324
+ };
325
+ }
326
+ }
327
+ const PACT_MAGIC_PREFIX = 'pact_magic_level_';
328
+ function applyHitPoints(input, options) {
329
+ const state = cloneState(input);
330
+ const details = [];
331
+ const amount = Number(options.amount) || 0;
332
+ if (options.action === 'stabilize') {
333
+ if (state.hp.cur > 0) {
334
+ return refuse('not_dying', `${state.name} is not dying — they have ${state.hp.cur} hit points.`);
335
+ }
336
+ state.stable = true;
337
+ state.deathSaves = { s: 0, f: 0 };
338
+ addCondition(state, 'unconscious');
339
+ return done(state, `${state.name} is stabilized at 0 hit points, still unconscious.`, details);
340
+ }
341
+ if (options.action === 'revive') {
342
+ state.hp.cur = Math.max(state.hp.cur, 1);
343
+ state.stable = false;
344
+ state.deathSaves = { s: 0, f: 0 };
345
+ removeCondition(state, 'unconscious');
346
+ return done(state, `${state.name} is revived at ${state.hp.cur} hit points.`, details);
347
+ }
348
+ if (options.temp !== undefined) {
349
+ const incoming = Math.max(Number(options.temp) || 0, 0);
350
+ if (incoming > state.hp.temp) {
351
+ details.push(`Temporary hit points set to ${incoming} (was ${state.hp.temp}).`);
352
+ state.hp.temp = incoming;
353
+ }
354
+ else {
355
+ details.push(`Kept the existing ${state.hp.temp} temporary hit points; ${incoming} would not have been an improvement.`);
356
+ }
357
+ if (amount === 0) {
358
+ return done(state, `${state.name} has ${state.hp.temp} temporary hit points.`, details);
359
+ }
360
+ }
361
+ if (amount > 0) {
362
+ return applyHealing(state, amount, details);
363
+ }
364
+ if (amount < 0) {
365
+ return applyDamage(state, -amount, options, details);
366
+ }
367
+ return done(state, `${state.name} is unchanged at ${state.hp.cur}/${state.hp.max} hit points.`, details);
368
+ }
369
+ function applyHealing(state, amount, details) {
370
+ if (state.hp.cur === 0 && state.deathSaves.f >= 3) {
371
+ 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']);
372
+ }
373
+ const before = state.hp.cur;
374
+ const max = rules.effectiveMaxHp(state);
375
+ state.hp.cur = Math.min(state.hp.cur + amount, max);
376
+ if (before === 0 && state.hp.cur > 0) {
377
+ state.deathSaves = { s: 0, f: 0 };
378
+ state.stable = false;
379
+ removeCondition(state, 'unconscious');
380
+ details.push('No longer dying or unconscious.');
381
+ }
382
+ if (state.hp.cur === max && before + amount > max) {
383
+ details.push(`${before + amount - max} healing was wasted at ${max === state.hp.max ? 'maximum hit points' : `the exhaustion-halved maximum of ${max}`}.`);
384
+ }
385
+ return done(state, `${state.name} heals ${state.hp.cur - before} to ${state.hp.cur}/${max} hit points.`, details);
386
+ }
387
+ function applyDamage(state, raw, options, details) {
388
+ const adjusted = rules.adjustDamage(state, raw, options.damageType, !!options.half);
389
+ details.push(...adjusted.notes);
390
+ let remaining = adjusted.amount;
391
+ const typeNote = options.damageType ? ` ${options.damageType}` : '';
392
+ if (remaining === 0) {
393
+ return done(state, `${state.name} takes no${typeNote} damage.`, details);
394
+ }
395
+ if (state.hp.temp > 0) {
396
+ const absorbed = Math.min(state.hp.temp, remaining);
397
+ state.hp.temp -= absorbed;
398
+ remaining -= absorbed;
399
+ details.push(`${absorbed} absorbed by temporary hit points (${state.hp.temp} left).`);
400
+ }
401
+ const wasDying = state.hp.cur === 0;
402
+ if (wasDying && remaining > 0) {
403
+ state.stable = false;
404
+ if (remaining >= rules.effectiveMaxHp(state)) {
405
+ return instantDeath(state, remaining, typeNote, details);
406
+ }
407
+ const failures = options.critical ? 2 : 1;
408
+ state.deathSaves.f = Math.min(state.deathSaves.f + failures, 3);
409
+ details.push(options.critical
410
+ ? 'A critical hit while dying counts as two failed death saving throws.'
411
+ : 'Damage while dying counts as a failed death saving throw.');
412
+ return finishDamage(state, remaining, typeNote, details);
413
+ }
414
+ const before = state.hp.cur;
415
+ state.hp.cur = Math.max(before - remaining, 0);
416
+ const overflow = remaining - before;
417
+ if (state.hp.cur === 0) {
418
+ if (overflow >= rules.effectiveMaxHp(state)) {
419
+ return instantDeath(state, remaining, typeNote, details, overflow);
420
+ }
421
+ state.deathSaves = { s: 0, f: 0 };
422
+ state.stable = false;
423
+ addCondition(state, 'unconscious');
424
+ details.push('Dropped to 0 hit points: unconscious and dying, making death saving throws.');
425
+ }
426
+ return finishDamage(state, remaining, typeNote, details);
427
+ }
428
+ function instantDeath(state, amount, typeNote, details, overflow) {
429
+ state.hp.cur = 0;
430
+ state.deathSaves = { s: 0, f: 3 };
431
+ state.stable = false;
432
+ addCondition(state, 'unconscious');
433
+ const max = rules.effectiveMaxHp(state);
434
+ details.push(overflow === undefined
435
+ ? `${amount} damage at 0 hit points meets the hit point maximum of ${max}, which is instant death.`
436
+ : `${overflow} damage remained after reaching 0, meeting the hit point maximum of ${max}, which is instant death.`);
437
+ return done(state, `${state.name} takes ${amount}${typeNote} damage and dies outright from massive damage.`, details);
438
+ }
439
+ function finishDamage(state, amount, typeNote, details) {
440
+ if (state.deathSaves.f >= 3) {
441
+ return done(state, `${state.name} takes ${amount}${typeNote} damage and dies — three failed death saving throws.`, details);
442
+ }
443
+ return done(state, `${state.name} takes ${amount}${typeNote} damage, now at ${state.hp.cur}/${state.hp.max} hit points.`, details);
444
+ }
445
+ function recordDeathSave(input, roll) {
446
+ const state = cloneState(input);
447
+ if (state.hp.cur > 0) {
448
+ return refuse('not_dying', `${state.name} is not dying and does not make death saving throws.`);
449
+ }
450
+ if (state.deathSaves.f >= 3) {
451
+ return refuse('dead', `${state.name} has already died.`);
452
+ }
453
+ const details = [];
454
+ if (roll === 20) {
455
+ state.hp.cur = 1;
456
+ state.deathSaves = { s: 0, f: 0 };
457
+ state.stable = false;
458
+ removeCondition(state, 'unconscious');
459
+ return done(state, `A natural 20: ${state.name} regains 1 hit point and is conscious.`, details);
460
+ }
461
+ if (roll === 1) {
462
+ state.deathSaves.f = Math.min(state.deathSaves.f + 2, 3);
463
+ details.push('A natural 1 counts as two failures.');
464
+ }
465
+ else if (roll >= 10) {
466
+ state.deathSaves.s = Math.min(state.deathSaves.s + 1, 3);
467
+ }
468
+ else {
469
+ state.deathSaves.f = Math.min(state.deathSaves.f + 1, 3);
470
+ }
471
+ if (state.deathSaves.f >= 3) {
472
+ return done(state, `${state.name} dies — three failed death saving throws.`, details);
473
+ }
474
+ if (state.deathSaves.s >= 3) {
475
+ state.stable = true;
476
+ state.deathSaves = { s: 0, f: 0 };
477
+ return done(state, `${state.name} is stable at 0 hit points after three successes.`, details);
478
+ }
479
+ return done(state, `${state.name} has ${state.deathSaves.s} success and ${state.deathSaves.f} failure death saves.`, details);
480
+ }
481
+ function shortRest(input, hitDiceToSpend, rng = dice_1.defaultRng) {
482
+ const state = cloneState(input);
483
+ const details = [];
484
+ if (hitDiceToSpend > 0) {
485
+ const available = Object.entries(state.hd).filter(([, pool]) => pool.cur > 0);
486
+ const total = available.reduce((sum, [, pool]) => sum + pool.cur, 0);
487
+ if (total === 0) {
488
+ return refuse('no_resource', `${state.name} has no hit dice left to spend.`, 'Hit dice are regained on a long rest, which restores half your total (minimum one).', ['Take a long rest to regain hit dice', 'Rest without spending hit dice']);
489
+ }
490
+ if (hitDiceToSpend > total) {
491
+ return refuse('no_resource', `${state.name} has only ${total} hit ${total === 1 ? 'die' : 'dice'} left, not ${hitDiceToSpend}.`, 'You may spend no more hit dice than you have remaining.', [`Spend ${total} instead`, 'Take a long rest to regain hit dice']);
492
+ }
493
+ const con = rules.abilityModifier(state, 'con');
494
+ let healed = 0;
495
+ let spent = 0;
496
+ for (const [die, pool] of available) {
497
+ while (pool.cur > 0 && spent < hitDiceToSpend) {
498
+ const roll = (0, dice_1.rollOne)(`1${die}`, rng);
499
+ const gain = Math.max(roll.total + con, 0);
500
+ healed += gain;
501
+ pool.cur -= 1;
502
+ spent += 1;
503
+ details.push(`${(0, dice_1.describeRoll)(roll)} ${con >= 0 ? '+' : ''}${con} Con = ${gain} healed`);
504
+ }
505
+ }
506
+ const before = state.hp.cur;
507
+ state.hp.cur = Math.min(state.hp.cur + healed, state.hp.max);
508
+ if (before === 0 && state.hp.cur > 0) {
509
+ state.deathSaves = { s: 0, f: 0 };
510
+ state.stable = false;
511
+ removeCondition(state, 'unconscious');
512
+ }
513
+ details.push(`Spent ${spent} hit ${spent === 1 ? 'die' : 'dice'} for ${state.hp.cur - before} hit points.`);
514
+ }
515
+ const recharged = rechargeResources(state, 'short');
516
+ if (recharged.length > 0)
517
+ details.push(`Recharged: ${recharged.join(', ')}.`);
518
+ return done(state, `${state.name} takes a short rest, now at ${state.hp.cur}/${state.hp.max} hit points.`, details);
519
+ }
520
+ function longRest(input) {
521
+ const state = cloneState(input);
522
+ const details = [];
523
+ if (state.hp.cur === 0 && state.deathSaves.f >= 3) {
524
+ return refuse('dead', `${state.name} is dead and cannot benefit from a rest.`);
525
+ }
526
+ if (state.exh > 0) {
527
+ state.exh -= 1;
528
+ details.push(`Exhaustion reduced to ${state.exh}.`);
529
+ }
530
+ state.hp.cur = rules.effectiveMaxHp(state);
531
+ state.hp.temp = 0;
532
+ state.deathSaves = { s: 0, f: 0 };
533
+ state.stable = false;
534
+ removeCondition(state, 'unconscious');
535
+ details.push(`Hit points restored to ${state.hp.cur}.`);
536
+ const totalDice = Object.values(state.hd).reduce((sum, pool) => sum + pool.max, 0);
537
+ let toRegain = Math.max(Math.floor(totalDice / 2), 1);
538
+ for (const [die, pool] of Object.entries(state.hd)) {
539
+ const missing = pool.max - pool.cur;
540
+ const regained = Math.min(missing, toRegain);
541
+ pool.cur += regained;
542
+ toRegain -= regained;
543
+ if (regained > 0)
544
+ details.push(`Regained ${regained} ${die} hit ${regained === 1 ? 'die' : 'dice'}.`);
545
+ if (toRegain <= 0)
546
+ break;
547
+ }
548
+ const recharged = rechargeResources(state, 'long');
549
+ if (recharged.length > 0)
550
+ details.push(`Recharged: ${recharged.join(', ')}.`);
551
+ return done(state, `${state.name} finishes a long rest at full hit points.`, details);
552
+ }
553
+ function rechargeResources(state, kind) {
554
+ const changed = [];
555
+ for (const [level, pool] of Object.entries(state.slots)) {
556
+ const refills = kind === 'long' || pool.reset === 'short';
557
+ if (refills && pool.cur < pool.max) {
558
+ pool.cur = pool.max;
559
+ changed.push(`level ${level} spell slots`);
560
+ }
561
+ }
562
+ for (const [key, pool] of Object.entries(state.uses)) {
563
+ const refills = pool.reset === 'short' ? true : kind === 'long' && pool.reset !== 'other';
564
+ if (refills && pool.cur < pool.max) {
565
+ pool.cur = pool.max;
566
+ changed.push(key.replace(/_/g, ' '));
567
+ }
568
+ }
569
+ return changed;
570
+ }
571
+ function spendResource(input, resource, amount, slotLevel) {
572
+ const state = cloneState(input);
573
+ const key = resource.trim().toLowerCase().replace(/\s+/g, '_');
574
+ if (key === 'slot' || key === 'spell_slot') {
575
+ return spendSpellSlot(state, amount, slotLevel);
576
+ }
577
+ if (key === 'hit_die' || key === 'hit_dice') {
578
+ return spendHitDie(state, amount);
579
+ }
580
+ return spendNamedResource(state, key, amount);
581
+ }
582
+ function spendSpellSlot(state, amount, slotLevel) {
583
+ if (!Number.isFinite(slotLevel) || slotLevel < 1 || slotLevel > 9) {
584
+ return refuse('bad_request', 'Spending a spell slot needs a level between 1 and 9.', undefined, ['Give the "level" parameter, e.g. level 2 for a second-level slot']);
585
+ }
586
+ const level = String(slotLevel);
587
+ const pool = state.slots[level];
588
+ if (!pool || pool.max === 0) {
589
+ return refuse('no_resource', `${state.name} has no level ${level} spell slots at all.`, 'A spellcaster must expend a spell slot of the spell’s level or higher.', describeSlots(state));
590
+ }
591
+ if (amount > 0 && pool.cur < amount) {
592
+ return refuse('no_resource', `${state.name} has ${pool.cur} of ${pool.max} level ${level} spell slots remaining, not ${amount}.`, 'A spellcaster must expend a spell slot of the spell’s level or higher.', [...describeSlots(state), 'Take a long rest to regain all spell slots']);
593
+ }
594
+ pool.cur = (0, sheet_1.clamp)(pool.cur - amount, 0, pool.max);
595
+ const verb = amount > 0 ? 'spends' : 'regains';
596
+ return done(state, `${state.name} ${verb} ${Math.abs(amount)} level ${level} spell slot${Math.abs(amount) === 1 ? '' : 's'}; ${pool.cur}/${pool.max} remaining.`);
597
+ }
598
+ function spendHitDie(state, amount) {
599
+ const entries = Object.entries(state.hd);
600
+ const total = entries.reduce((sum, [, pool]) => sum + pool.cur, 0);
601
+ if (amount > 0 && total < amount) {
602
+ return refuse('no_resource', `${state.name} has ${total} hit ${total === 1 ? 'die' : 'dice'} remaining, not ${amount}.`, 'A long rest restores half your total hit dice, minimum one.', ['Take a long rest to regain hit dice']);
603
+ }
604
+ let left = amount;
605
+ for (const [, pool] of entries) {
606
+ if (left === 0)
607
+ break;
608
+ if (left > 0) {
609
+ const taken = Math.min(pool.cur, left);
610
+ pool.cur -= taken;
611
+ left -= taken;
612
+ }
613
+ else {
614
+ const given = Math.min(pool.max - pool.cur, -left);
615
+ pool.cur += given;
616
+ left += given;
617
+ }
618
+ }
619
+ const remaining = Object.entries(state.hd)
620
+ .map(([die, pool]) => `${pool.cur}/${pool.max} ${die}`)
621
+ .join(', ');
622
+ return done(state, `${state.name} now has ${remaining} hit dice.`);
623
+ }
624
+ function spendNamedResource(state, key, amount) {
625
+ const item = state.inv.find((i) => i.n.toLowerCase().replace(/\s+/g, '_') === key);
626
+ if (item && item.chg !== undefined) {
627
+ if (amount > 0 && item.chg < amount) {
628
+ 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']);
629
+ }
630
+ item.chg = Math.max(item.chg - amount, 0);
631
+ if (item.chg === 0) {
632
+ return done(state, `${state.name}'s ${item.n} is used up.`);
633
+ }
634
+ return done(state, `${state.name}'s ${item.n} has ${item.chg} use${item.chg === 1 ? '' : 's'} left.`);
635
+ }
636
+ const pool = state.uses[key];
637
+ if (!pool) {
638
+ const known = [
639
+ ...Object.keys(state.uses).map((k) => k.replace(/_/g, ' ')),
640
+ ...state.inv.filter((i) => i.chg !== undefined).map((i) => i.n),
641
+ ];
642
+ return refuse('no_resource', `${state.name} has no resource called "${key.replace(/_/g, ' ')}".`, undefined, known.length > 0
643
+ ? [`Known resources: ${known.join(', ')}`]
644
+ : ['This character tracks no limited-use features']);
645
+ }
646
+ if (amount > 0 && pool.cur < amount) {
647
+ return refuse('no_resource', `${state.name} has ${pool.cur} of ${pool.max} ${key.replace(/_/g, ' ')} remaining, not ${amount}.`, undefined, [
648
+ pool.reset === 'short'
649
+ ? 'Take a short rest to recharge it'
650
+ : 'Take a long rest to recharge it',
651
+ ]);
652
+ }
653
+ pool.cur = (0, sheet_1.clamp)(pool.cur - amount, 0, pool.max);
654
+ return done(state, `${state.name} has ${pool.cur}/${pool.max} ${key.replace(/_/g, ' ')} remaining.`);
655
+ }
656
+ function describeSlots(state) {
657
+ const available = Object.entries(state.slots)
658
+ .filter(([, pool]) => pool.cur > 0)
659
+ .map(([level, pool]) => `level ${level}: ${pool.cur} of ${pool.max}`);
660
+ return available.length > 0
661
+ ? [`Slots still available — ${available.join('; ')}`]
662
+ : ['No spell slots of any level remain'];
663
+ }
664
+ function addCondition(state, name, duration) {
665
+ const key = name.trim().toLowerCase();
666
+ const existing = state.cond.find((c) => c.n === key);
667
+ if (existing) {
668
+ if (duration)
669
+ existing.dur = duration;
670
+ return false;
671
+ }
672
+ state.cond.push(duration ? { n: key, dur: duration } : { n: key });
673
+ return true;
674
+ }
675
+ function removeCondition(state, name) {
676
+ const key = name.trim().toLowerCase();
677
+ const before = state.cond.length;
678
+ state.cond = state.cond.filter((c) => c.n !== key);
679
+ return state.cond.length !== before;
680
+ }
681
+ function setExhaustion(state, level) {
682
+ state.exh = (0, sheet_1.clamp)(Math.trunc(level), 0, srd_1.MAX_EXHAUSTION);
683
+ state.hp.cur = Math.min(state.hp.cur, rules.effectiveMaxHp(state));
684
+ return state.exh;
685
+ }
686
+ const COIN_ORDER = ['pp', 'gp', 'ep', 'sp', 'cp'];
687
+ function addItems(state, entries) {
688
+ const added = [];
689
+ for (const entry of entries) {
690
+ const item = parseItemEntry(entry);
691
+ const existing = state.inv.find((i) => i.n.toLowerCase() === item.n.toLowerCase());
692
+ if (existing) {
693
+ existing.q += item.q;
694
+ added.push(`${item.n} (now ${existing.q})`);
695
+ }
696
+ else {
697
+ state.inv.push(item);
698
+ added.push(item.q > 1 ? `${item.n} x${item.q}` : item.n);
699
+ }
700
+ }
701
+ return added;
702
+ }
703
+ function removeItems(state, entries) {
704
+ const removed = [];
705
+ const missing = [];
706
+ for (const entry of entries) {
707
+ const wanted = parseItemEntry(entry);
708
+ const existing = state.inv.find((i) => i.n.toLowerCase() === wanted.n.toLowerCase());
709
+ if (!existing || existing.q < wanted.q) {
710
+ missing.push(existing
711
+ ? `${wanted.n} (has ${existing.q}, asked for ${wanted.q})`
712
+ : `${wanted.n} (none carried)`);
713
+ continue;
714
+ }
715
+ existing.q -= wanted.q;
716
+ removed.push({ n: existing.n, q: wanted.q, chg: existing.chg });
717
+ if (existing.q === 0) {
718
+ state.inv = state.inv.filter((i) => i !== existing);
719
+ }
720
+ }
721
+ return { removed, missing };
722
+ }
723
+ function adjustCoin(state, entries) {
724
+ const deltas = {};
725
+ for (const entry of entries) {
726
+ const match = /^([+-]?\s*\d+)\s*(pp|gp|ep|sp|cp)$/i.exec(entry.replace(/\s+/g, ' ').trim());
727
+ if (!match) {
728
+ return {
729
+ ok: false,
730
+ refusal: {
731
+ violation: 'bad_request',
732
+ message: `Could not read "${entry}" as an amount of money.`,
733
+ options: ['Use a signed amount and a denomination, e.g. "+150 gp; -3 sp"'],
734
+ },
735
+ };
736
+ }
737
+ const denomination = match[2].toLowerCase();
738
+ deltas[denomination] = (deltas[denomination] || 0) + parseInt(match[1].replace(/\s+/g, ''), 10);
739
+ }
740
+ for (const [denomination, delta] of Object.entries(deltas)) {
741
+ const balance = (state.coin[denomination] || 0) + delta;
742
+ if (balance < 0) {
743
+ return {
744
+ ok: false,
745
+ refusal: {
746
+ violation: 'insufficient_funds',
747
+ message: `${state.name} has ${state.coin[denomination] || 0} ${denomination} and cannot pay ${-delta}.`,
748
+ options: [
749
+ `Carried: ${describeCoin(state) || 'nothing'}`,
750
+ 'Offer a smaller amount, or something other than coin',
751
+ ],
752
+ },
753
+ };
754
+ }
755
+ }
756
+ const changes = [];
757
+ for (const denomination of COIN_ORDER) {
758
+ const delta = deltas[denomination];
759
+ if (!delta)
760
+ continue;
761
+ state.coin[denomination] = (state.coin[denomination] || 0) + delta;
762
+ if (state.coin[denomination] === 0)
763
+ delete state.coin[denomination];
764
+ changes.push(`${delta > 0 ? '+' : ''}${delta} ${denomination}`);
765
+ }
766
+ return { ok: true, changes };
767
+ }
768
+ function describeCoin(state) {
769
+ return COIN_ORDER.filter((d) => state.coin[d])
770
+ .map((d) => `${state.coin[d]} ${d}`)
771
+ .join(', ');
772
+ }
773
+ function setEquipped(state, names, equipped) {
774
+ const changed = [];
775
+ const missing = [];
776
+ for (const name of names) {
777
+ const item = state.inv.find((i) => i.n.toLowerCase() === name.trim().toLowerCase());
778
+ if (!item) {
779
+ missing.push(name);
780
+ continue;
781
+ }
782
+ if (equipped)
783
+ item.eq = true;
784
+ else
785
+ delete item.eq;
786
+ changed.push(item.n);
787
+ }
788
+ if (changed.length > 0) {
789
+ state.ac = rules.computeArmorClass(state).ac;
790
+ }
791
+ return { changed, missing };
792
+ }
793
+ function setAttunement(state, names, attune, needsAttunement) {
794
+ const changed = [];
795
+ const missing = [];
796
+ const unnecessary = [];
797
+ for (const name of names) {
798
+ const item = state.inv.find((i) => i.n.toLowerCase() === name.trim().toLowerCase());
799
+ if (!item) {
800
+ missing.push(name);
801
+ continue;
802
+ }
803
+ if (!attune) {
804
+ if (item.att)
805
+ changed.push(item.n);
806
+ delete item.att;
807
+ continue;
808
+ }
809
+ if (item.att)
810
+ continue;
811
+ if (!needsAttunement(item.n)) {
812
+ unnecessary.push(item.n);
813
+ continue;
814
+ }
815
+ const attuned = state.inv.filter((i) => i.att).length;
816
+ if (attuned >= magic_items_1.MAX_ATTUNED_ITEMS) {
817
+ return {
818
+ changed,
819
+ missing,
820
+ unnecessary,
821
+ refusal: {
822
+ violation: 'attunement_limit',
823
+ message: `${state.name} is already attuned to ${magic_items_1.MAX_ATTUNED_ITEMS} items and cannot attune to ${item.n}.`,
824
+ rule: `A creature can be attuned to no more than ${magic_items_1.MAX_ATTUNED_ITEMS} magic items at a time.`,
825
+ options: [
826
+ `Currently attuned: ${state.inv.filter((i) => i.att).map((i) => i.n).join(', ')}`,
827
+ 'Unattune one of those first, which takes a short rest',
828
+ ],
829
+ },
830
+ };
831
+ }
832
+ item.att = true;
833
+ changed.push(item.n);
834
+ }
835
+ if (changed.length > 0)
836
+ state.ac = rules.computeArmorClass(state).ac;
837
+ return { changed, missing, unnecessary };
838
+ }
839
+ function awardExperience(input, amount) {
840
+ const state = cloneState(input);
841
+ const beforeLevel = rules.totalLevel(state);
842
+ state.xp = Math.max(state.xp + amount, 0);
843
+ const entitled = rules.levelForXp(state.xp);
844
+ const details = [];
845
+ const next = rules.xpForNextLevel(state);
846
+ if (next !== null) {
847
+ details.push(`${next - state.xp} experience to level ${beforeLevel + 1}.`);
848
+ }
849
+ let need;
850
+ if (entitled > beforeLevel) {
851
+ need = {
852
+ character: state.name,
853
+ fromLevel: beforeLevel,
854
+ toLevel: entitled,
855
+ choices: levelUpChoices(state, entitled),
856
+ };
857
+ details.push(`${state.name} has earned level ${entitled}. Nothing has been applied — call level_up once they have chosen.`);
858
+ }
859
+ return {
860
+ result: {
861
+ ok: true,
862
+ state,
863
+ summary: `${state.name} ${amount >= 0 ? 'gains' : 'loses'} ${Math.abs(amount)} experience, now ${state.xp}.`,
864
+ details,
865
+ },
866
+ need,
867
+ };
868
+ }
869
+ function levelUpChoices(state, toLevel) {
870
+ const primary = state.class[0];
871
+ const classRules = srd_1.CLASSES[primary?.c || ''];
872
+ const choices = [
873
+ `Hit point increase: roll the class hit die (${primary?.hd || 'd8'}) and add the Constitution modifier, or take the fixed average`,
874
+ ];
875
+ const classLevel = (Number(primary?.lvl) || 1) + (toLevel - rules.totalLevel(state));
876
+ if (classRules?.asiLevels.includes(classLevel)) {
877
+ choices.push('Ability score improvement: +2 to one ability or +1 to two — OR a feat instead of it, never both');
878
+ }
879
+ if (classRules && !primary?.sub && classLevel >= classRules.subclassLevel) {
880
+ choices.push(`${classRules.subclassLabel}: choose the ${classRules.subclassLabel.toLowerCase()} this character follows`);
881
+ }
882
+ if (classRules && classRules.caster !== 'none') {
883
+ choices.push('New spells known or prepared, if the class gains any at this level');
884
+ choices.push('Spell slots are recalculated automatically');
885
+ }
886
+ choices.push('Any new class feature gained at this level, added with patch_sheet if it has uses');
887
+ return choices;
888
+ }
889
+ function applyLevelUp(input, toLevel, choices) {
890
+ const state = cloneState(input);
891
+ const current = rules.totalLevel(state);
892
+ if (toLevel <= current) {
893
+ return {
894
+ ok: false,
895
+ refusal: {
896
+ violation: 'bad_request',
897
+ message: `${state.name} is already level ${current}.`,
898
+ options: [`Pass to_level greater than ${current}`],
899
+ },
900
+ };
901
+ }
902
+ if (toLevel > 20) {
903
+ return {
904
+ ok: false,
905
+ refusal: {
906
+ violation: 'bad_request',
907
+ message: 'Level 20 is the maximum.',
908
+ options: ['Award experience without levelling'],
909
+ },
910
+ };
911
+ }
912
+ const entry = choices.class
913
+ ? state.class.find((c) => c.c === rules.resolveClass(choices.class))
914
+ : state.class[0];
915
+ if (!entry) {
916
+ return {
917
+ ok: false,
918
+ refusal: {
919
+ violation: 'bad_request',
920
+ message: `${state.name} has no levels in "${choices.class}".`,
921
+ options: [`Classes on this sheet: ${state.class.map((c) => c.c).join(', ')}`],
922
+ },
923
+ };
924
+ }
925
+ const details = [];
926
+ const gained = toLevel - current;
927
+ const asiPicked = choices.asi && Object.keys(choices.asi).length > 0;
928
+ if (asiPicked && choices.feat) {
929
+ return {
930
+ ok: false,
931
+ refusal: {
932
+ violation: 'asi_or_feat',
933
+ message: `${state.name} cannot take both an ability score improvement and the ${choices.feat} feat at this level.`,
934
+ rule: 'You may forgo the Ability Score Improvement to take a feat instead — one or the other.',
935
+ options: [
936
+ 'Take the ability score improvement and drop "feat"',
937
+ `Take ${choices.feat} and drop "asi"`,
938
+ ],
939
+ },
940
+ };
941
+ }
942
+ if (choices.feat) {
943
+ if ((0, feats_1.hasFeat)(state, choices.feat)) {
944
+ return {
945
+ ok: false,
946
+ refusal: {
947
+ violation: 'duplicate_feat',
948
+ message: `${state.name} already has ${choices.feat}.`,
949
+ rule: 'You can take each feat only once, unless the feat says otherwise.',
950
+ options: [
951
+ `Feats already taken: ${(state.feats || []).join(', ')}`,
952
+ 'Choose a different feat, or take the ability score improvement instead',
953
+ ],
954
+ },
955
+ };
956
+ }
957
+ const { feat, ambiguous } = (0, feats_1.resolveFeat)(choices.feat);
958
+ if (ambiguous) {
959
+ return {
960
+ ok: false,
961
+ refusal: {
962
+ violation: 'bad_request',
963
+ message: `"${choices.feat}" matches ${ambiguous.length} feats.`,
964
+ options: ambiguous,
965
+ },
966
+ };
967
+ }
968
+ const unmet = feat ? (0, feats_1.prerequisiteProblems)(state, feat) : [];
969
+ if (unmet.length > 0) {
970
+ return {
971
+ ok: false,
972
+ refusal: {
973
+ violation: 'prerequisite',
974
+ message: unmet.join(' '),
975
+ rule: "You must meet a feat's prerequisite to take it.",
976
+ options: [
977
+ 'Take the ability score improvement instead',
978
+ 'Choose a feat whose prerequisite this character meets',
979
+ ],
980
+ },
981
+ };
982
+ }
983
+ }
984
+ if (choices.asi) {
985
+ for (const [ability, increase] of Object.entries(choices.asi)) {
986
+ const key = ability;
987
+ if (!srd_1.ABILITIES.includes(key))
988
+ continue;
989
+ const before = state.abil[key];
990
+ state.abil[key] = (0, sheet_1.clamp)(before + Number(increase), 1, 20);
991
+ details.push(`${key.toUpperCase()} ${before} to ${state.abil[key]}.`);
992
+ }
993
+ }
994
+ if (choices.subclass) {
995
+ entry.sub = choices.subclass;
996
+ details.push(`Subclass: ${choices.subclass}.`);
997
+ }
998
+ if (choices.spells && choices.spells.length > 0) {
999
+ state.spells = [...(state.spells || []), ...choices.spells];
1000
+ details.push(`Learned ${choices.spells.join(', ')}.`);
1001
+ for (const off of (0, spells_1.offListSpells)(state, choices.spells)) {
1002
+ details.push(off.onLists
1003
+ ? `${off.spell} is on the ${off.onLists.join('/')} list rather than this character's — check a subclass or racial trait grants it.`
1004
+ : `${off.spell} is not an SRD spell, so nothing was verified about it.`);
1005
+ }
1006
+ }
1007
+ if (choices.feat) {
1008
+ const applied = (0, feats_1.applyFeat)(state, choices.feat);
1009
+ details.push(`Feat: ${applied.name}${applied.changes.length > 0 ? ` — ${applied.changes.join(', ')}` : ''}.`);
1010
+ details.push(...applied.notes);
1011
+ const note = (0, feats_1.resolveFeat)(applied.name).feat;
1012
+ if (note && (0, feats_1.prerequisiteNote)(note)) {
1013
+ details.push(`Prerequisite to keep in mind: ${(0, feats_1.prerequisiteNote)(note)}.`);
1014
+ }
1015
+ }
1016
+ entry.lvl += gained;
1017
+ const con = rules.abilityModifier(state, 'con');
1018
+ const perLevel = choices.hp !== undefined && Number.isFinite(Number(choices.hp))
1019
+ ? Math.max(Number(choices.hp), 1)
1020
+ : rules.averageHitPointsPerLevel(entry.c, con);
1021
+ const hpBefore = state.hp.max;
1022
+ recomputeDerived(state);
1023
+ applyClassFeatureUses(state);
1024
+ if (choices.hp !== undefined) {
1025
+ const averaged = rules.averageHitPointsPerLevel(entry.c, con) * gained;
1026
+ state.hp.max = state.hp.max - averaged + perLevel * gained;
1027
+ }
1028
+ state.hp.cur += state.hp.max - hpBefore;
1029
+ state.hp.cur = (0, sheet_1.clamp)(state.hp.cur, 0, state.hp.max);
1030
+ details.push(`Hit points ${hpBefore} to ${state.hp.max}.`);
1031
+ details.push(`Proficiency bonus is now +${rules.proficiencyBonus(state)}.`);
1032
+ const slots = Object.entries(state.slots)
1033
+ .filter(([, pool]) => pool.max > 0)
1034
+ .map(([level, pool]) => `L${level} x${pool.max}`);
1035
+ if (slots.length > 0)
1036
+ details.push(`Spell slots: ${slots.join(', ')}.`);
1037
+ const threshold = srd_1.XP_THRESHOLDS[Math.min(toLevel, srd_1.XP_THRESHOLDS.length - 1)];
1038
+ if (state.xp < threshold) {
1039
+ state.xp = threshold;
1040
+ details.push(`Experience set to ${threshold}, the threshold for level ${toLevel}.`);
1041
+ }
1042
+ return {
1043
+ ok: true,
1044
+ state,
1045
+ summary: `${state.name} reaches level ${toLevel} (${srd_1.CLASSES[entry.c]?.name || entry.c} ${entry.lvl}).`,
1046
+ details,
1047
+ };
1048
+ }
1049
+ function cloneState(state) {
1050
+ return JSON.parse(JSON.stringify(state));
1051
+ }
1052
+ function done(state, summary, details = []) {
1053
+ return { ok: true, state, summary, details: details.length > 0 ? details : undefined };
1054
+ }
1055
+ function refuse(violation, message, rule, options) {
1056
+ return { ok: false, refusal: { violation, message, rule, options } };
1057
+ }