briyah 2.0.3 → 2.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (391) hide show
  1. package/README.md +55 -8
  2. package/data/common/config/LICENSE-model-prices.md +65 -0
  3. package/data/common/config/markup +1 -1
  4. package/data/common/config/model_prices.json +47443 -46295
  5. package/data/common/config/story_models.json +3 -3
  6. package/data/common/prompts/illustrator/describe_scene.prompt +4 -4
  7. package/data/common/prompts/narrator/create_story.prompt +2 -0
  8. package/data/common/prompts/perceive.prompt +1 -1
  9. package/data/packs/dnd5e/prompts/battle_master/perceive.prompt +1 -1
  10. package/data/packs/dnd5e/prompts/campaign_designer/perceive.prompt +1 -1
  11. package/data/packs/dnd5e/prompts/character_creator/perceive.prompt +795 -787
  12. package/data/packs/dnd5e/prompts/dungeon_master/defaults_config.json +2 -1
  13. package/data/packs/dnd5e/prompts/dungeon_master/perceive.prompt +1 -1
  14. package/data/packs/dnd5e/rooms/campaign.json +18 -15
  15. package/data/packs/dnd5e/rooms/table.json +17 -16
  16. package/dist-sdk/server/src/ai/LLM/anthropic.service.d.ts +103 -0
  17. package/dist-sdk/server/src/ai/LLM/anthropic.service.js +174 -3
  18. package/dist-sdk/server/src/ai/LLM/base-ai.service.d.ts +194 -3
  19. package/dist-sdk/server/src/ai/LLM/base-ai.service.js +299 -19
  20. package/dist-sdk/server/src/ai/LLM/blank-image.d.ts +36 -0
  21. package/dist-sdk/server/src/ai/LLM/blank-image.js +80 -0
  22. package/dist-sdk/server/src/ai/LLM/comfyui-client.d.ts +26 -0
  23. package/dist-sdk/server/src/ai/LLM/comfyui-client.js +25 -0
  24. package/dist-sdk/server/src/ai/LLM/comfyui-workflow.d.ts +54 -0
  25. package/dist-sdk/server/src/ai/LLM/comfyui-workflow.js +59 -1
  26. package/dist-sdk/server/src/ai/LLM/comfyui.service.d.ts +21 -1
  27. package/dist-sdk/server/src/ai/LLM/comfyui.service.js +25 -1
  28. package/dist-sdk/server/src/ai/LLM/deepseek.service.d.ts +52 -0
  29. package/dist-sdk/server/src/ai/LLM/deepseek.service.js +103 -4
  30. package/dist-sdk/server/src/ai/LLM/fal.service.d.ts +25 -0
  31. package/dist-sdk/server/src/ai/LLM/fal.service.js +56 -2
  32. package/dist-sdk/server/src/ai/LLM/googleai.service.d.ts +19 -0
  33. package/dist-sdk/server/src/ai/LLM/googleai.service.js +43 -2
  34. package/dist-sdk/server/src/ai/LLM/grok.service.d.ts +22 -0
  35. package/dist-sdk/server/src/ai/LLM/grok.service.js +55 -3
  36. package/dist-sdk/server/src/ai/LLM/mock.service.js +31 -4
  37. package/dist-sdk/server/src/ai/LLM/openai.service.d.ts +30 -0
  38. package/dist-sdk/server/src/ai/LLM/openai.service.js +81 -3
  39. package/dist-sdk/server/src/ai/LLM/self-hosted.service.d.ts +21 -0
  40. package/dist-sdk/server/src/ai/LLM/self-hosted.service.js +45 -3
  41. package/dist-sdk/server/src/ai/LLM/together.service.d.ts +30 -0
  42. package/dist-sdk/server/src/ai/LLM/together.service.js +61 -3
  43. package/dist-sdk/server/src/ai/agent-config.d.ts +15 -1
  44. package/dist-sdk/server/src/ai/agent-factory.d.ts +16 -0
  45. package/dist-sdk/server/src/ai/agent-factory.js +20 -0
  46. package/dist-sdk/server/src/ai/agent-message.service.d.ts +30 -0
  47. package/dist-sdk/server/src/ai/agent-message.service.js +30 -0
  48. package/dist-sdk/server/src/ai/agent-store.service.d.ts +80 -0
  49. package/dist-sdk/server/src/ai/agent-store.service.js +166 -7
  50. package/dist-sdk/server/src/ai/agent.d.ts +197 -2
  51. package/dist-sdk/server/src/ai/agent.js +225 -14
  52. package/dist-sdk/server/src/ai/ai-debug-logger.d.ts +18 -0
  53. package/dist-sdk/server/src/ai/ai-debug-logger.js +19 -0
  54. package/dist-sdk/server/src/ai/ai-factory.service.d.ts +9 -0
  55. package/dist-sdk/server/src/ai/ai-factory.service.js +9 -0
  56. package/dist-sdk/server/src/ai/artifact.service.d.ts +131 -0
  57. package/dist-sdk/server/src/ai/artifact.service.js +148 -3
  58. package/dist-sdk/server/src/ai/attached-file.service.d.ts +87 -0
  59. package/dist-sdk/server/src/ai/attached-file.service.js +105 -0
  60. package/dist-sdk/server/src/ai/model_prices.d.ts +30 -0
  61. package/dist-sdk/server/src/ai/model_prices.js +91 -5
  62. package/dist-sdk/server/src/ai/pack-artifacts.d.ts +84 -0
  63. package/dist-sdk/server/src/ai/pack-artifacts.js +168 -0
  64. package/dist-sdk/server/src/ai/published-agents.service.d.ts +25 -0
  65. package/dist-sdk/server/src/ai/published-agents.service.js +30 -3
  66. package/dist-sdk/server/src/app/balance-message.service.d.ts +24 -0
  67. package/dist-sdk/server/src/app/balance-message.service.js +24 -0
  68. package/dist-sdk/server/src/app/balance.module.d.ts +4 -0
  69. package/dist-sdk/server/src/app/balance.module.js +4 -0
  70. package/dist-sdk/server/src/app/balance.service.d.ts +37 -0
  71. package/dist-sdk/server/src/app/balance.service.js +54 -0
  72. package/dist-sdk/server/src/app/stripe.controller.d.ts +21 -0
  73. package/dist-sdk/server/src/app/stripe.controller.js +35 -0
  74. package/dist-sdk/server/src/app/stripe.service.d.ts +43 -0
  75. package/dist-sdk/server/src/app/stripe.service.js +62 -0
  76. package/dist-sdk/server/src/app/transaction.service.d.ts +27 -0
  77. package/dist-sdk/server/src/app/transaction.service.js +36 -0
  78. package/dist-sdk/server/src/app/user-service-factory.d.ts +8 -0
  79. package/dist-sdk/server/src/app/user-service-factory.js +46 -3
  80. package/dist-sdk/server/src/app/user-service-manager.d.ts +27 -0
  81. package/dist-sdk/server/src/app/user-service-manager.js +43 -0
  82. package/dist-sdk/server/src/app.controller.d.ts +120 -0
  83. package/dist-sdk/server/src/app.controller.js +365 -14
  84. package/dist-sdk/server/src/app.module.js +28 -6
  85. package/dist-sdk/server/src/app.service.d.ts +1710 -4
  86. package/dist-sdk/server/src/app.service.js +1938 -20
  87. package/dist-sdk/server/src/auth/agent-access.decorator.d.ts +17 -0
  88. package/dist-sdk/server/src/auth/agent-access.decorator.js +17 -0
  89. package/dist-sdk/server/src/auth/auth.controller.js +46 -0
  90. package/dist-sdk/server/src/auth/auth.module.js +3 -2
  91. package/dist-sdk/server/src/auth/auth.service.d.ts +33 -0
  92. package/dist-sdk/server/src/auth/auth.service.js +39 -3
  93. package/dist-sdk/server/src/auth/jwt-auth.guard.js +44 -0
  94. package/dist-sdk/server/src/auth/jwt.strategy.js +2 -2
  95. package/dist-sdk/server/src/auth/owner-only.decorator.d.ts +9 -0
  96. package/dist-sdk/server/src/auth/owner-only.decorator.js +9 -0
  97. package/dist-sdk/server/src/auth/phone-validation.service.d.ts +25 -0
  98. package/dist-sdk/server/src/auth/phone-validation.service.js +30 -0
  99. package/dist-sdk/server/src/auth/rate-limit.service.d.ts +19 -0
  100. package/dist-sdk/server/src/auth/rate-limit.service.js +24 -0
  101. package/dist-sdk/server/src/auth/room-access.decorator.d.ts +8 -0
  102. package/dist-sdk/server/src/auth/room-access.decorator.js +8 -0
  103. package/dist-sdk/server/src/auth/scopes.decorator.d.ts +7 -0
  104. package/dist-sdk/server/src/auth/scopes.decorator.js +7 -0
  105. package/dist-sdk/server/src/auth/scopes.guard.d.ts +16 -0
  106. package/dist-sdk/server/src/auth/scopes.guard.js +30 -0
  107. package/dist-sdk/server/src/auth/session.guard.d.ts +4 -0
  108. package/dist-sdk/server/src/auth/session.guard.js +8 -0
  109. package/dist-sdk/server/src/auth/twilio.service.d.ts +27 -0
  110. package/dist-sdk/server/src/auth/twilio.service.js +30 -4
  111. package/dist-sdk/server/src/auth/users.service.d.ts +30 -0
  112. package/dist-sdk/server/src/auth/users.service.js +42 -0
  113. package/dist-sdk/server/src/common/errors.d.ts +20 -0
  114. package/dist-sdk/server/src/common/errors.js +21 -0
  115. package/dist-sdk/server/src/config/env-config.d.ts +7 -0
  116. package/dist-sdk/server/src/config/prompt-resolver.d.ts +180 -0
  117. package/dist-sdk/server/src/config/prompt-resolver.js +182 -0
  118. package/dist-sdk/server/src/config/user-config.service.d.ts +59 -0
  119. package/dist-sdk/server/src/config/user-config.service.js +57 -0
  120. package/dist-sdk/server/src/config/user-paths.service.d.ts +61 -0
  121. package/dist-sdk/server/src/config/user-paths.service.js +67 -0
  122. package/dist-sdk/server/src/documents/pdf-conversion.d.ts +121 -1
  123. package/dist-sdk/server/src/documents/pdf-conversion.js +94 -0
  124. package/dist-sdk/server/src/packs/pack-instantiation.service.d.ts +98 -0
  125. package/dist-sdk/server/src/packs/pack-instantiation.service.js +104 -0
  126. package/dist-sdk/server/src/packs/pack-manifest.d.ts +114 -0
  127. package/dist-sdk/server/src/packs/pack-manifest.js +69 -0
  128. package/dist-sdk/server/src/packs/pack.service.d.ts +99 -1
  129. package/dist-sdk/server/src/packs/pack.service.js +98 -1
  130. package/dist-sdk/server/src/room/artifact-store.service.d.ts +27 -0
  131. package/dist-sdk/server/src/room/artifact-store.service.js +49 -3
  132. package/dist-sdk/server/src/room/artifact.d.ts +18 -0
  133. package/dist-sdk/server/src/room/illustration/illustration.service.d.ts +211 -0
  134. package/dist-sdk/server/src/room/illustration/illustration.service.js +771 -0
  135. package/dist-sdk/server/src/room/illustration/illustration.types.d.ts +101 -0
  136. package/dist-sdk/server/src/room/illustration/illustration.types.js +2 -0
  137. package/dist-sdk/server/src/room/message.d.ts +64 -0
  138. package/dist-sdk/server/src/room/message.js +77 -2
  139. package/dist-sdk/server/src/room/nickname.d.ts +26 -0
  140. package/dist-sdk/server/src/room/nickname.js +26 -0
  141. package/dist-sdk/server/src/room/published-rooms.service.js +2 -0
  142. package/dist-sdk/server/src/room/room-config.d.ts +84 -1
  143. package/dist-sdk/server/src/room/room-config.js +19 -0
  144. package/dist-sdk/server/src/room/room-factory.d.ts +20 -0
  145. package/dist-sdk/server/src/room/room-factory.js +25 -0
  146. package/dist-sdk/server/src/room/room-message.service.d.ts +28 -0
  147. package/dist-sdk/server/src/room/room-message.service.js +28 -0
  148. package/dist-sdk/server/src/room/room-store.service.d.ts +184 -0
  149. package/dist-sdk/server/src/room/room-store.service.js +280 -6
  150. package/dist-sdk/server/src/room/room.d.ts +981 -1
  151. package/dist-sdk/server/src/room/room.js +1531 -27
  152. package/dist-sdk/server/src/rpg/rpg-models.d.ts +50 -0
  153. package/dist-sdk/server/src/rpg/rpg-models.js +53 -0
  154. package/dist-sdk/server/src/rpg/rpg-roster.d.ts +37 -0
  155. package/dist-sdk/server/src/rpg/rpg-roster.js +37 -0
  156. package/dist-sdk/server/src/rpg/rpg.service.d.ts +87 -0
  157. package/dist-sdk/server/src/rpg/rpg.service.js +108 -1
  158. package/dist-sdk/server/src/sdk/briyah-config.d.ts +57 -0
  159. package/dist-sdk/server/src/sdk/briyah-config.js +17 -0
  160. package/dist-sdk/server/src/sdk/briyah.d.ts +228 -0
  161. package/dist-sdk/server/src/sdk/briyah.js +285 -7
  162. package/dist-sdk/server/src/sdk/index.js +23 -0
  163. package/dist-sdk/server/src/shared/shared.module.d.ts +8 -0
  164. package/dist-sdk/server/src/shared/shared.module.js +13 -5
  165. package/dist-sdk/server/src/story/story-message.service.d.ts +43 -0
  166. package/dist-sdk/server/src/story/story-message.service.js +43 -0
  167. package/dist-sdk/server/src/story/story-progress.service.d.ts +23 -0
  168. package/dist-sdk/server/src/story/story-progress.service.js +23 -0
  169. package/dist-sdk/server/src/story/story-store.service.d.ts +92 -0
  170. package/dist-sdk/server/src/story/story-store.service.js +136 -1
  171. package/dist-sdk/server/src/story/story.service.d.ts +366 -9
  172. package/dist-sdk/server/src/story/story.service.js +825 -374
  173. package/dist-sdk/server/src/tools/core/illustrate.tool.d.ts +14 -0
  174. package/dist-sdk/server/src/tools/core/illustrate.tool.js +80 -0
  175. package/dist-sdk/server/src/tools/core/index.d.ts +22 -0
  176. package/dist-sdk/server/src/tools/core/index.js +24 -1
  177. package/dist-sdk/server/src/tools/core/rename.tool.d.ts +8 -0
  178. package/dist-sdk/server/src/tools/core/rename.tool.js +11 -0
  179. package/dist-sdk/server/src/tools/native-tool-registry.service.d.ts +22 -0
  180. package/dist-sdk/server/src/tools/native-tool-registry.service.js +22 -0
  181. package/dist-sdk/server/src/tools/native-tool.types.d.ts +266 -0
  182. package/dist-sdk/server/src/tools/packs/dnd5e/data/backgrounds.d.ts +29 -0
  183. package/dist-sdk/server/src/tools/packs/dnd5e/data/backgrounds.js +29 -0
  184. package/dist-sdk/server/src/tools/packs/dnd5e/data/cantrips.d.ts +46 -0
  185. package/dist-sdk/server/src/tools/packs/dnd5e/data/cantrips.js +40 -0
  186. package/dist-sdk/server/src/tools/packs/dnd5e/data/feats.d.ts +33 -0
  187. package/dist-sdk/server/src/tools/packs/dnd5e/data/feats.js +19 -0
  188. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.d.ts +37 -0
  189. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.generated.d.ts +17 -0
  190. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.generated.js +17 -0
  191. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.js +27 -0
  192. package/dist-sdk/server/src/tools/packs/dnd5e/data/kits.d.ts +36 -0
  193. package/dist-sdk/server/src/tools/packs/dnd5e/data/kits.js +32 -0
  194. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.d.ts +32 -0
  195. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.generated.d.ts +13 -0
  196. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.generated.js +13 -0
  197. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.js +18 -0
  198. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.d.ts +54 -0
  199. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.generated.d.ts +13 -0
  200. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.generated.js +13 -0
  201. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.js +20 -0
  202. package/dist-sdk/server/src/tools/packs/dnd5e/data/races.d.ts +36 -0
  203. package/dist-sdk/server/src/tools/packs/dnd5e/data/races.js +18 -0
  204. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.d.ts +29 -0
  205. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.generated.d.ts +13 -0
  206. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.generated.js +13 -0
  207. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.js +21 -0
  208. package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.d.ts +95 -0
  209. package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.js +66 -2
  210. package/dist-sdk/server/src/tools/packs/dnd5e/data/weapons.d.ts +50 -0
  211. package/dist-sdk/server/src/tools/packs/dnd5e/data/weapons.js +28 -0
  212. package/dist-sdk/server/src/tools/packs/dnd5e/engine/bestiary.d.ts +92 -0
  213. package/dist-sdk/server/src/tools/packs/dnd5e/engine/bestiary.js +152 -0
  214. package/dist-sdk/server/src/tools/packs/dnd5e/engine/campaign-items.d.ts +28 -0
  215. package/dist-sdk/server/src/tools/packs/dnd5e/engine/campaign-items.js +29 -0
  216. package/dist-sdk/server/src/tools/packs/dnd5e/engine/cantrips.d.ts +31 -0
  217. package/dist-sdk/server/src/tools/packs/dnd5e/engine/cantrips.js +36 -2
  218. package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.d.ts +261 -0
  219. package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.js +401 -0
  220. package/dist-sdk/server/src/tools/packs/dnd5e/engine/coerce.d.ts +11 -0
  221. package/dist-sdk/server/src/tools/packs/dnd5e/engine/coerce.js +11 -0
  222. package/dist-sdk/server/src/tools/packs/dnd5e/engine/dice.d.ts +65 -0
  223. package/dist-sdk/server/src/tools/packs/dnd5e/engine/dice.js +67 -0
  224. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encounter.d.ts +73 -0
  225. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encounter.js +63 -0
  226. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encumbrance.d.ts +66 -0
  227. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encumbrance.js +59 -0
  228. package/dist-sdk/server/src/tools/packs/dnd5e/engine/feats.d.ts +54 -0
  229. package/dist-sdk/server/src/tools/packs/dnd5e/engine/feats.js +49 -0
  230. package/dist-sdk/server/src/tools/packs/dnd5e/engine/foes.d.ts +42 -0
  231. package/dist-sdk/server/src/tools/packs/dnd5e/engine/foes.js +59 -0
  232. package/dist-sdk/server/src/tools/packs/dnd5e/engine/guides.d.ts +72 -0
  233. package/dist-sdk/server/src/tools/packs/dnd5e/engine/guides.js +63 -0
  234. package/dist-sdk/server/src/tools/packs/dnd5e/engine/items.d.ts +57 -0
  235. package/dist-sdk/server/src/tools/packs/dnd5e/engine/items.js +54 -0
  236. package/dist-sdk/server/src/tools/packs/dnd5e/engine/kits.d.ts +81 -0
  237. package/dist-sdk/server/src/tools/packs/dnd5e/engine/kits.js +85 -0
  238. package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.d.ts +60 -0
  239. package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.js +64 -0
  240. package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.d.ts +169 -0
  241. package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.js +203 -0
  242. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.d.ts +201 -0
  243. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.js +149 -0
  244. package/dist-sdk/server/src/tools/packs/dnd5e/engine/spells.d.ts +56 -0
  245. package/dist-sdk/server/src/tools/packs/dnd5e/engine/spells.js +54 -0
  246. package/dist-sdk/server/src/tools/packs/dnd5e/engine/weapons.d.ts +65 -0
  247. package/dist-sdk/server/src/tools/packs/dnd5e/engine/weapons.js +73 -0
  248. package/dist-sdk/server/src/tools/packs/dnd5e/index.d.ts +18 -0
  249. package/dist-sdk/server/src/tools/packs/dnd5e/index.js +18 -0
  250. package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.d.ts +4 -0
  251. package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.js +116 -1
  252. package/dist-sdk/server/src/tools/packs/dnd5e/tools/class.tool.d.ts +14 -0
  253. package/dist-sdk/server/src/tools/packs/dnd5e/tools/class.tool.js +17 -0
  254. package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.d.ts +1 -0
  255. package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.js +35 -1
  256. package/dist-sdk/server/src/tools/packs/dnd5e/tools/encounter.tool.d.ts +6 -0
  257. package/dist-sdk/server/src/tools/packs/dnd5e/tools/encounter.tool.js +25 -0
  258. package/dist-sdk/server/src/tools/packs/dnd5e/tools/item.tool.d.ts +7 -0
  259. package/dist-sdk/server/src/tools/packs/dnd5e/tools/item.tool.js +13 -0
  260. package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.d.ts +8 -0
  261. package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.js +55 -0
  262. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.d.ts +194 -0
  263. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.js +263 -1
  264. package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.d.ts +1 -0
  265. package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.js +127 -2
  266. package/dist-sdk/server/src/tools/packs/dnd5e/tools/spell.tool.d.ts +13 -0
  267. package/dist-sdk/server/src/tools/packs/dnd5e/tools/spell.tool.js +18 -0
  268. package/dist-sdk/server/src/tools/packs/dnd5e/tools/state.tools.d.ts +1 -0
  269. package/dist-sdk/server/src/tools/packs/dnd5e/tools/state.tools.js +23 -0
  270. package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.d.ts +1 -0
  271. package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.js +35 -0
  272. package/dist-sdk/server/src/tools/packs/index.d.ts +49 -0
  273. package/dist-sdk/server/src/tools/packs/index.js +66 -0
  274. package/dist-sdk/server/src/tools/shared/coerce.d.ts +95 -0
  275. package/dist-sdk/server/src/tools/shared/coerce.js +98 -0
  276. package/dist-sdk/server/src/tools/tool-execution.service.d.ts +107 -3
  277. package/dist-sdk/server/src/tools/tool-execution.service.js +163 -19
  278. package/dist-sdk/server/src/tools/tool-store.service.d.ts +11 -0
  279. package/dist-sdk/server/src/tools/tool-store.service.js +13 -1
  280. package/dist-sdk/shared/types/app.types.d.ts +328 -13
  281. package/dist-sdk/shared/types/app.types.js +18 -1
  282. package/package.json +167 -168
  283. package/data/common/config/random_words.txt +0 -2241
  284. package/data/common/story_ideas/biblical.json +0 -122
  285. package/data/common/story_ideas/fantasy.json +0 -82
  286. package/data/common/story_ideas/historical_fiction.json +0 -82
  287. package/data/common/story_ideas/science_fiction.json +0 -82
  288. package/docs/.nojekyll +0 -1
  289. package/docs/assets/hierarchy.js +0 -1
  290. package/docs/assets/highlight.css +0 -113
  291. package/docs/assets/icons.js +0 -18
  292. package/docs/assets/icons.svg +0 -1
  293. package/docs/assets/main.js +0 -60
  294. package/docs/assets/navigation.js +0 -1
  295. package/docs/assets/search.js +0 -1
  296. package/docs/assets/style.css +0 -1648
  297. package/docs/classes/Agent.html +0 -801
  298. package/docs/classes/Briyah.html +0 -296
  299. package/docs/classes/BriyahConfigService.html +0 -119
  300. package/docs/classes/NativeToolRegistry.html +0 -166
  301. package/docs/classes/PackInstantiationService.html +0 -157
  302. package/docs/classes/PackService.html +0 -247
  303. package/docs/classes/Room.html +0 -1434
  304. package/docs/classes/RoomMessage.html +0 -290
  305. package/docs/enums/MessageAction.html +0 -136
  306. package/docs/functions/availableToolPacks.html +0 -41
  307. package/docs/functions/buildMarkdown.html +0 -54
  308. package/docs/functions/dnd5eTools.html +0 -44
  309. package/docs/functions/installToolPacks.html +0 -51
  310. package/docs/functions/pageMarker.html +0 -45
  311. package/docs/functions/registerToolPacks.html +0 -54
  312. package/docs/functions/splitMarkdownIntoPages.html +0 -51
  313. package/docs/functions/stripWrappingFence.html +0 -52
  314. package/docs/hierarchy.html +0 -46
  315. package/docs/index.html +0 -595
  316. package/docs/interfaces/AgentCreationOptions.html +0 -125
  317. package/docs/interfaces/AgentInfo.html +0 -218
  318. package/docs/interfaces/AgentMessagesResponse.html +0 -74
  319. package/docs/interfaces/AppService.html +0 -3340
  320. package/docs/interfaces/Artifact.html +0 -95
  321. package/docs/interfaces/ArtifactMetadata.html +0 -112
  322. package/docs/interfaces/ArtifactWriteOptions.html +0 -90
  323. package/docs/interfaces/AttachDocumentResponse.html +0 -62
  324. package/docs/interfaces/BriyahConfigOptions.html +0 -124
  325. package/docs/interfaces/ChapterInfo.html +0 -62
  326. package/docs/interfaces/Character.html +0 -86
  327. package/docs/interfaces/ConversionAgent.html +0 -78
  328. package/docs/interfaces/CreateAgentResponse.html +0 -56
  329. package/docs/interfaces/CreateRoomResponse.html +0 -62
  330. package/docs/interfaces/CreateStoryResponse.html +0 -56
  331. package/docs/interfaces/FileList.html +0 -56
  332. package/docs/interfaces/FileMetadata.html +0 -89
  333. package/docs/interfaces/IConfigService.html +0 -79
  334. package/docs/interfaces/InstantiateModels.html +0 -64
  335. package/docs/interfaces/InstantiateRoomResult.html +0 -70
  336. package/docs/interfaces/LoadedPack.html +0 -131
  337. package/docs/interfaces/LoggingOptions.html +0 -92
  338. package/docs/interfaces/Message.html +0 -84
  339. package/docs/interfaces/ModelChoice.html +0 -73
  340. package/docs/interfaces/ModelInfo.html +0 -74
  341. package/docs/interfaces/NativeToolDefinition.html +0 -107
  342. package/docs/interfaces/PackAgentTemplate.html +0 -101
  343. package/docs/interfaces/PackRoomTemplate.html +0 -108
  344. package/docs/interfaces/PackView.html +0 -172
  345. package/docs/interfaces/PdfConversionOptions.html +0 -102
  346. package/docs/interfaces/PdfConversionResult.html +0 -97
  347. package/docs/interfaces/PdfMarkdownOptions.html +0 -198
  348. package/docs/interfaces/PdfMarkdownResult.html +0 -106
  349. package/docs/interfaces/PdfPageMarkdown.html +0 -94
  350. package/docs/interfaces/PreparedPromptResponse.html +0 -62
  351. package/docs/interfaces/ProcessTextResponse.html +0 -86
  352. package/docs/interfaces/PromptFile.html +0 -70
  353. package/docs/interfaces/PromptFileContent.html +0 -76
  354. package/docs/interfaces/PromptFilesResponse.html +0 -56
  355. package/docs/interfaces/PromptFolder.html +0 -80
  356. package/docs/interfaces/PromptFolderDefaults.html +0 -155
  357. package/docs/interfaces/PromptFolderDefaultsResponse.html +0 -79
  358. package/docs/interfaces/PromptFoldersResponse.html +0 -56
  359. package/docs/interfaces/RoomDetails.html +0 -151
  360. package/docs/interfaces/RoomErrorUpdate.html +0 -82
  361. package/docs/interfaces/RoomInfo.html +0 -88
  362. package/docs/interfaces/RoomMessageUpdate.html +0 -113
  363. package/docs/interfaces/RoomMessagesResponse.html +0 -62
  364. package/docs/interfaces/SendMessageResult.html +0 -62
  365. package/docs/interfaces/StoryErrorEvent.html +0 -84
  366. package/docs/interfaces/StoryIdea.html +0 -74
  367. package/docs/interfaces/StoryInfo.html +0 -198
  368. package/docs/interfaces/StoryIntroduceCharacterEvent.html +0 -79
  369. package/docs/interfaces/StoryProgressChapterEvent.html +0 -72
  370. package/docs/interfaces/StoryState.html +0 -108
  371. package/docs/interfaces/StoryStateEvent.html +0 -76
  372. package/docs/interfaces/ToolArtifact.html +0 -85
  373. package/docs/interfaces/ToolCaller.html +0 -77
  374. package/docs/interfaces/ToolDefinition.html +0 -80
  375. package/docs/interfaces/ToolHelpers.html +0 -105
  376. package/docs/interfaces/ToolPackDocuments.html +0 -100
  377. package/docs/interfaces/ToolParameter.html +0 -74
  378. package/docs/interfaces/ToolRoomAccess.html +0 -260
  379. package/docs/interfaces/ToolSummary.html +0 -74
  380. package/docs/interfaces/ToolsResponse.html +0 -68
  381. package/docs/interfaces/Transaction.html +0 -104
  382. package/docs/interfaces/TransactionHistoryResponse.html +0 -62
  383. package/docs/modules.html +0 -53
  384. package/docs/types/PackOrigin.html +0 -34
  385. package/docs/types/PromptScope.html +0 -34
  386. package/docs/types/RoomTurnMode.html +0 -42
  387. package/docs/types/RoomUpdate.html +0 -36
  388. package/docs/types/RosterOverrides.html +0 -42
  389. package/docs/types/ToolContext.html +0 -40
  390. package/docs/types/ToolRunResult.html +0 -34
  391. package/src/tools/packs/dnd5e/README.md +0 -867
@@ -55,34 +55,71 @@ const logger_1 = require("../../common/logger");
55
55
  const jsonrepair_1 = require("jsonrepair");
56
56
  const model_prices_1 = require("../model_prices");
57
57
  const ai_debug_logger_1 = require("../ai-debug-logger");
58
+ const blank_image_1 = require("./blank-image");
58
59
  let BaseAiService = class BaseAiService {
60
+ // Cache for models to avoid repeated API calls
59
61
  modelsCache = null;
62
+ // Indicates whether this service is properly initialized and available for use
60
63
  _isAvailable = true;
61
64
  constructor() { }
65
+ /**
66
+ * Returns whether this service is available for use
67
+ * This is typically false if the service failed to initialize (e.g., missing API key)
68
+ */
62
69
  get isAvailable() {
63
70
  return this._isAvailable;
64
71
  }
72
+ /**
73
+ * Gets the name of this service type
74
+ * @returns The service type name
75
+ */
65
76
  getServiceName() {
66
77
  return '';
67
78
  }
79
+ /**
80
+ * Provider prefix used when looking up model pricing in model_prices.json.
81
+ * Override in services that use prefixed keys (e.g. `deepseek/`, `xai/`,
82
+ * `together_ai/`, `fal_ai/`). Default is no prefix — the raw model name is
83
+ * expected to match a key directly.
84
+ */
68
85
  getModelPricePrefix() {
69
86
  return null;
70
87
  }
71
88
  supportsImageGeneration() {
72
89
  return false;
73
90
  }
91
+ /**
92
+ * Whether createAgent() must find the model in model_prices.json /
93
+ * image_models.json before an agent can be created. Services whose model
94
+ * names are deployment-specific and have no marginal cost (Mock,
95
+ * self-hosted providers) override this to return false.
96
+ */
74
97
  requiresKnownModel() {
75
98
  return true;
76
99
  }
77
100
  supportsPromptCaching() {
78
101
  return false;
79
102
  }
103
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
80
104
  getCacheConfig(_agent, _cacheMessage) {
81
105
  return null;
82
106
  }
83
107
  stripQuotes(quotedText) {
84
108
  return quotedText.replace(/^['"]+|['"]+$/g, '');
85
109
  }
110
+ /**
111
+ * Finds a prompt file using the shared lookup order.
112
+ *
113
+ * For a bare folder that is the historical four levels — user/folder,
114
+ * user/root, common/folder, common/root — plus the folders of any pack the
115
+ * agent's owner has enabled. For a pack-qualified folder (`dnd5e:battle_master`)
116
+ * it is the pack's own tiers, then the shared roots. See `prompt-resolver.ts`.
117
+ *
118
+ * @param agent The agent context
119
+ * @param fileName The prompt file name without extension
120
+ * @param extension The file extension (e.g., '.prompt' or '.json')
121
+ * @returns The full path to the file, or null if not found
122
+ */
86
123
  findPromptFile(agent, fileName, extension) {
87
124
  const userPaths = agent.userPaths;
88
125
  if (!userPaths) {
@@ -92,27 +129,79 @@ let BaseAiService = class BaseAiService {
92
129
  enabledPacks: agent.enabledPacks,
93
130
  })?.absolutePath ?? null);
94
131
  }
132
+ /**
133
+ * Whether a prompt file resolves for this agent, without reading or compiling it.
134
+ *
135
+ * Lets a caller find out that {@link getPreparedPrompt} would throw before
136
+ * committing to a call — used to tell an agent that can run a given kind of turn
137
+ * from one whose prompt folder simply does not have that prompt.
138
+ *
139
+ * @param agent The agent whose prompt folder is searched
140
+ * @param fileName The prompt file name without extension
141
+ * @param extension The file extension, defaulting to `.prompt`
142
+ */
95
143
  hasPromptFile(agent, fileName, extension = '.prompt') {
96
144
  return this.findPromptFile(agent, fileName, extension) !== null;
97
145
  }
98
146
  getPreparedPrompt(agent, promptFileName, variables) {
147
+ // Use 4-level fallback to find the prompt file
99
148
  const preparedFile = this.findPromptFile(agent, promptFileName, '.prompt');
100
149
  if (!preparedFile) {
101
150
  throw new errors_1.NotFoundError(`Prompt file '${promptFileName}.prompt' not found for agent '${agent.agentName}' (folder: ${agent.promptFolder})`);
102
151
  }
152
+ // Read and compile the prompt template.
153
+ //
154
+ // noEscape because a prompt is not HTML. Handlebars escapes `{{var}}` by
155
+ // default, which turned every apostrophe in a description into `'`
156
+ // and every fenced code block inside an artifact into `````
157
+ // — so a character sheet arrived at the model as entity soup, and the
158
+ // JSON inside it doubly so. There is no injection risk to trade against:
159
+ // nothing downstream renders this as markup.
103
160
  const preparedPrompt = fs.readFileSync(preparedFile).toString('utf8');
104
161
  const template = (0, handlebars_1.compile)(preparedPrompt, { noEscape: true });
105
162
  return template(variables);
106
163
  }
164
+ /**
165
+ * The agent's system instruction, resolved from its prompt folder per call.
166
+ *
167
+ * Read on every call for the same reason {@link getPreparedPrompt} re-reads its
168
+ * template: the folder's files are the source, so an edit reaches the next turn.
169
+ * A copy taken at creation could not — nothing in the API sets this field, so a
170
+ * stale copy stayed stale for the life of the agent.
171
+ *
172
+ * Reached only when the caller passes no instructions of its own. A room turn
173
+ * renders `perceive.prompt` and passes that, which *replaces* this rather than
174
+ * adding to it, so the read never happens on the hot path.
175
+ *
176
+ * @param agent The agent whose prompt folder is searched
177
+ * @returns The file's contents, or '' when the folder has no such file
178
+ */
179
+ getSystemInstruction(agent) {
180
+ const systemInstructionFile = this.findPromptFile(agent, 'system_instruction', '.prompt');
181
+ if (!systemInstructionFile) {
182
+ return '';
183
+ }
184
+ try {
185
+ return (0, fs_1.readFileSync)(systemInstructionFile).toString('utf8');
186
+ }
187
+ catch (error) {
188
+ logger_1.logger.error(`Error reading system instruction from ${systemInstructionFile}:`, error);
189
+ return '';
190
+ }
191
+ }
107
192
  getPreparedSchema(agent, promptFileName) {
193
+ // Use 4-level fallback to find the schema file
108
194
  const jsonSchemaFile = this.findPromptFile(agent, promptFileName, '.json');
195
+ // Schemas are optional, return null if not found
109
196
  if (!jsonSchemaFile) {
110
197
  return null;
111
198
  }
199
+ // Allows creating an empty .json file to return a plain text response
112
200
  let jsonSchemaString = (0, fs_1.readFileSync)(jsonSchemaFile).toString('utf8');
113
201
  if (!jsonSchemaString) {
114
202
  return null;
115
203
  }
204
+ // Try to parse the JSON schema if found
116
205
  try {
117
206
  return JSON.parse(jsonSchemaString);
118
207
  }
@@ -121,15 +210,24 @@ let BaseAiService = class BaseAiService {
121
210
  return null;
122
211
  }
123
212
  }
213
+ /**
214
+ * Lists available models from the AI service
215
+ * Uses cached results if available, otherwise queries the API
216
+ * @returns Promise with model information
217
+ */
124
218
  async listModels() {
219
+ // Check if service is available
125
220
  if (!this.isAvailable) {
126
221
  return Promise.reject(new Error(`${this.getServiceName()} service is not available. Check API key configuration.`));
127
222
  }
223
+ // Return cached models if available
128
224
  if (this.modelsCache) {
129
225
  return this.modelsCache;
130
226
  }
227
+ // If no cache, call the actual implementation
131
228
  try {
132
229
  const models = await this.fetchModelsFromApi();
230
+ // Cache the result for future calls
133
231
  this.modelsCache = models;
134
232
  return models;
135
233
  }
@@ -138,10 +236,30 @@ let BaseAiService = class BaseAiService {
138
236
  throw error;
139
237
  }
140
238
  }
239
+ /**
240
+ * Actual implementation to fetch models from the API
241
+ * This should be overridden by subclasses
242
+ * @returns Promise with model information
243
+ */
141
244
  async fetchModelsFromApi() {
142
245
  throw new Error('fetchModelsFromApi method not implemented in base class');
143
246
  }
247
+ /**
248
+ * Creates an agent with the AI service
249
+ * @param userPaths User paths service for prompt and data directories
250
+ * @param configService Environment-variable configuration service
251
+ * @param agentStoreService
252
+ * @param balanceService
253
+ * @param artifactService
254
+ * @param agentName Name of the agent
255
+ * @param description
256
+ * @param promptFolder Directory name containing prompts
257
+ * @param modelName Name of the model to use
258
+ * @param storageDir
259
+ * @returns A new Agent instance
260
+ */
144
261
  createAgent(userPaths, configService, agentStoreService, balanceService, artifactService, agentName, agentNickname, description, promptFolder, modelName, storageDir = '') {
262
+ // Check if service is available
145
263
  if (!this.isAvailable) {
146
264
  throw new Error(`${this.getServiceName()} service is not available. Check API key configuration.`);
147
265
  }
@@ -151,49 +269,82 @@ let BaseAiService = class BaseAiService {
151
269
  if (!agentName) {
152
270
  throw new Error('Agent name is required');
153
271
  }
272
+ // Refuse to create an agent for a model that has no pricing entry —
273
+ // otherwise cost tracking silently falls back to zero and balance gating
274
+ // is bypassed. Services with requiresKnownModel() === false are exempt:
275
+ // their models have no real cost and are never listed in model_prices.json.
154
276
  if (this.requiresKnownModel() && !(0, model_prices_1.isKnownModel)(modelName, this.getModelPricePrefix())) {
155
277
  throw new Error(`Model '${modelName}' is not listed in model_prices.json for ${this.getServiceName()}. ` +
156
278
  `Add a pricing entry before using this model.`);
157
279
  }
158
- const tempAgent = { promptFolder, userPaths };
159
- const systemInstructionFile = this.findPromptFile(tempAgent, 'system_instruction', '.prompt');
160
- let systemInstructionPrompt = null;
161
- if (systemInstructionFile) {
162
- try {
163
- systemInstructionPrompt = (0, fs_1.readFileSync)(systemInstructionFile).toString('utf8');
164
- }
165
- catch (error) {
166
- logger_1.logger.error(`Error reading system instruction from ${systemInstructionFile}:`, error);
167
- systemInstructionPrompt = null;
168
- }
169
- }
170
- const agent = new agent_1.Agent(null, userPaths, configService, agentStoreService, balanceService, artifactService, agentName, agentNickname, description, promptFolder, systemInstructionPrompt, [], modelName, this.getServiceName(), this, null, false, 0, '', storageDir);
280
+ const agent = new agent_1.Agent(null, userPaths, configService, agentStoreService, balanceService, artifactService, agentName, agentNickname, description, promptFolder, [], modelName, this.getServiceName(), this, // Pass the service instance itself
281
+ null, // no reasoning
282
+ false, // do not allow search
283
+ 0, // Default to maximum output tokens
284
+ '', // begin instruction
285
+ storageDir);
171
286
  return agent;
172
287
  }
173
- async textPrompt(agent, prompt, _jsonSchema = null, _saveResponse = true, _promptInstructions = null, _cacheConfig = null, _maxOutputChars = 0) {
288
+ /**
289
+ * Sends a text prompt to the AI service
290
+ * @param agent The agent context
291
+ * @param prompt The text prompt
292
+ * @param _jsonSchema
293
+ * @param _saveResponse
294
+ * @param _promptInstructions
295
+ * @param _cacheConfig
296
+ * @param _maxOutputChars
297
+ * @returns The AI response
298
+ */
299
+ async textPrompt(agent, prompt, _jsonSchema = null, // eslint-disable-line @typescript-eslint/no-unused-vars
300
+ _saveResponse = true, // eslint-disable-line @typescript-eslint/no-unused-vars
301
+ _promptInstructions = null, // eslint-disable-line @typescript-eslint/no-unused-vars
302
+ _cacheConfig = null, // eslint-disable-line @typescript-eslint/no-unused-vars
303
+ _maxOutputChars = 0) {
304
+ // Check if service is available
174
305
  if (!this.isAvailable) {
175
306
  return Promise.reject(new Error(`${this.getServiceName()} service is not available. Check API key configuration.`));
176
307
  }
177
308
  throw new Error('Method not implemented in base class');
178
309
  }
179
- async generateImage(_agent, _prompt, _imageProperties) {
310
+ /**
311
+ * Generates an image from a text prompt with optional reference images
312
+ * @param agent The agent making the request
313
+ * @param prompt Text description of the image to generate
314
+ * @param width
315
+ * @param height
316
+ * @param quality
317
+ * @param referenceImageArtifactIds Optional array of artifact IDs containing reference images
318
+ * @param options Optional generation parameters (size, quality, format)
319
+ * @returns Promise resolving to JSON string with { url, artifactId }
320
+ */
321
+ async generateImage(_agent, // eslint-disable-line @typescript-eslint/no-unused-vars
322
+ _prompt, // eslint-disable-line @typescript-eslint/no-unused-vars
323
+ _imageProperties) {
180
324
  if (!this.isAvailable) {
181
325
  return Promise.reject(new Error(`${this.getServiceName()} service is not available. Check API key configuration.`));
182
326
  }
183
327
  throw new Error(`generateImage method not implemented for ${this.getServiceName()}`);
184
328
  }
185
- async editImage(_agent, _prompt, _imageProperties, _referenceImageArtifactIds) {
329
+ async editImage(_agent, // eslint-disable-line @typescript-eslint/no-unused-vars
330
+ _prompt, // eslint-disable-line @typescript-eslint/no-unused-vars
331
+ _imageProperties, // eslint-disable-line @typescript-eslint/no-unused-vars
332
+ _referenceImageArtifactIds) {
186
333
  if (!this.isAvailable) {
187
334
  return Promise.reject(new Error(`${this.getServiceName()} service is not available. Check API key configuration.`));
188
335
  }
189
336
  throw new Error(`editImage method not implemented for ${this.getServiceName()}`);
190
337
  }
338
+ /**
339
+ * Helper: Load reference images from artifacts
340
+ */
191
341
  async loadReferenceImages(agent, artifactIds) {
192
342
  const images = [];
193
343
  for (const artifactId of artifactIds) {
194
344
  const imageData = agent.artifactService.getArtifact(artifactId);
195
345
  const metadata = agent.artifactService.getArtifactMetadata(artifactId);
196
346
  if (imageData && Buffer.isBuffer(imageData) && metadata) {
347
+ // Convert Buffer to File for OpenAI API
197
348
  const uint8Array = new Uint8Array(imageData);
198
349
  const blob = new Blob([uint8Array], {
199
350
  type: metadata.mimeType || 'image/png',
@@ -206,13 +357,39 @@ let BaseAiService = class BaseAiService {
206
357
  }
207
358
  return images;
208
359
  }
360
+ /**
361
+ * Helper: Save image from base64 data as artifact
362
+ *
363
+ * The one place every image from every provider passes through, which is why the
364
+ * blank-frame check lives here. A refusal comes back as a successful response
365
+ * holding no picture; throwing rather than storing it turns into `{ error }` in
366
+ * each provider's catch, and every caller already bails on that before it deletes
367
+ * the portrait the new image was meant to replace.
368
+ */
209
369
  async saveImageAsArtifact(agent, base64Data, prompt) {
370
+ // Decode base64 to buffer
210
371
  const buffer = Buffer.from(base64Data, 'base64');
372
+ if ((0, blank_image_1.isBlankImage)(buffer)) {
373
+ throw new blank_image_1.BlankImageError(`${this.getServiceName()} returned a blank ${buffer.length}-byte image`);
374
+ }
375
+ // Default to PNG for generated images
211
376
  const mimeType = 'image/png';
377
+ // Generate name from prompt (truncate if too long)
212
378
  const name = prompt.substring(0, 50).trim() + ' (generated)';
379
+ // Save as artifact
213
380
  return agent.artifactService.storeImageArtifact(name, buffer, mimeType);
214
381
  }
382
+ /**
383
+ * Processes a prepared prompt with the AI service
384
+ * @param agent The agent context
385
+ * @param promptFileName Name of the prompt file
386
+ * @param variables Variables to use in the prompt template
387
+ * @param saveResponse Whether to save the response in the agent history
388
+ * @param cacheConfig
389
+ * @returns The AI response as a parsed JSON object
390
+ */
215
391
  async preparedPrompt(agent, promptFileName, variables, saveResponse = true, cacheConfig = false, maxOutputChars = 0) {
392
+ // Check if service is available
216
393
  if (!this.isAvailable) {
217
394
  return Promise.reject(new Error(`${this.getServiceName()} service is not available. Check API key configuration.`));
218
395
  }
@@ -221,14 +398,42 @@ let BaseAiService = class BaseAiService {
221
398
  return this.textPrompt(agent, preparedPrompt, jsonSchema, saveResponse, null, cacheConfig, maxOutputChars);
222
399
  }
223
400
  async instructedPrompt(agent, prompt, instructionFileName, variables, saveResponse = true, cacheConfig = null, maxOutputChars = 0) {
401
+ // Check if service is available
224
402
  if (!this.isAvailable) {
225
403
  return Promise.reject(new Error(`${this.getServiceName()} service is not available. Check API key configuration.`));
226
404
  }
227
- let promptInstructions = this.getPreparedPrompt(agent, instructionFileName, variables);
228
- let jsonSchema = this.getPreparedSchema(agent, instructionFileName);
405
+ // The folder's standing instruction prefixes the rendered one, so a folder
406
+ // works the same whether its agent is talked to alone or is in a room.
407
+ //
408
+ // Without this a folder had to pick: `system_instruction.prompt` carries the
409
+ // role for a one-to-one chat on the Agents page (where nothing renders an
410
+ // instruction file, so the provider falls back to it), and a room renders
411
+ // `perceive.prompt` and passes it here — which *replaces* the fallback rather
412
+ // than adding to it. A folder written for one context lost its role in the
413
+ // other.
414
+ //
415
+ // The standing instruction goes first for two reasons: a role reads before
416
+ // the protocol that carries it out, and the system block is the cached
417
+ // prefix — a file changes far less often than a rendered `perceive.prompt`,
418
+ // which carries the artifact roster and every other agent's description, so
419
+ // the stable half belongs in front.
420
+ const renderedInstructions = this.getPreparedPrompt(agent, instructionFileName, variables);
421
+ const standingInstruction = this.getSystemInstruction(agent).trim();
422
+ const promptInstructions = standingInstruction
423
+ ? `${standingInstruction}\n\n${renderedInstructions}`
424
+ : renderedInstructions;
425
+ const jsonSchema = this.getPreparedSchema(agent, instructionFileName);
229
426
  return this.textPrompt(agent, prompt, jsonSchema, saveResponse, promptInstructions, cacheConfig, maxOutputChars);
230
427
  }
428
+ /**
429
+ * Attaches a document to the agent or as a shared document
430
+ * @param agent The agent context (null for shared documents)
431
+ * @param fileName The name of the file
432
+ * @param fileData The file data as a Uint8Array
433
+ * @returns Promise with a human-readable success message
434
+ */
231
435
  async attachDocument(agent, fileName, fileData) {
436
+ // Check if service is available
232
437
  if (!this.isAvailable) {
233
438
  return Promise.reject(new Error(`${this.getServiceName()} service is not available. Check API key configuration.`));
234
439
  }
@@ -238,6 +443,7 @@ let BaseAiService = class BaseAiService {
238
443
  try {
239
444
  let ext = fileName.split('.').pop();
240
445
  let mimeType = 'application/octet-stream';
446
+ // Determine MIME type based on extension
241
447
  if (ext.toLowerCase() === 'pdf') {
242
448
  mimeType = 'application/pdf';
243
449
  }
@@ -253,26 +459,34 @@ let BaseAiService = class BaseAiService {
253
459
  else if (['xls', 'xlsx'].includes(ext.toLowerCase())) {
254
460
  mimeType = 'application/vnd.ms-excel';
255
461
  }
462
+ // Create metadata for this file and store the file data with it
256
463
  const fileMetadata = {
257
464
  fileName,
465
+ // fileId should already be set by AttachedFileService before this method is called
258
466
  mimeType,
259
467
  size: fileData.length,
260
468
  uploadDate: new Date().toISOString(),
261
469
  serviceMetadata: {
262
470
  serviceName: this.getServiceName(),
263
- fileData: Array.from(fileData),
471
+ // Store the actual file data temporarily in metadata for immediate use
472
+ fileData: Array.from(fileData), // Convert Uint8Array to regular array for JSON serialization
264
473
  },
265
474
  };
475
+ // Check if file already exists in agent's attachedFiles
266
476
  const existingFileIndex = agent.attachedFiles.findIndex((f) => f.fileName === fileName);
267
477
  if (existingFileIndex >= 0) {
478
+ // Update existing metadata (preserve existing fileId)
268
479
  agent.attachedFiles[existingFileIndex] = {
269
480
  ...agent.attachedFiles[existingFileIndex],
270
481
  ...fileMetadata,
271
482
  };
272
483
  }
273
484
  else {
485
+ // Add new file metadata to agent
486
+ // Cast to FileMetadata since fileId should already be set by AttachedFileService
274
487
  agent.attachedFiles.push(fileMetadata);
275
488
  }
489
+ // Note: File is stored in attachedFiles and will be prepended to each request by textPrompt
276
490
  return `Document attached: ${fileName}`;
277
491
  }
278
492
  catch (error) {
@@ -280,12 +494,28 @@ let BaseAiService = class BaseAiService {
280
494
  throw new Error(`Error attaching document: ${error.message}`);
281
495
  }
282
496
  }
497
+ /**
498
+ * Finishes an agent and cleans up resources
499
+ * @param agent The agent to finish
500
+ */
501
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
283
502
  async finishAgent(_agent) {
503
+ // Check if service is available
284
504
  if (!this.isAvailable) {
285
505
  return Promise.reject(new Error(`${this.getServiceName()} service is not available. Check API key configuration.`));
286
506
  }
507
+ // Default implementation does nothing
287
508
  }
509
+ /**
510
+ * Adds a message to the agent history in the appropriate format for this service
511
+ * @param agent The agent to add the message to
512
+ * @param message The formatted message to add
513
+ * @param fromSelf Whether the message was generated by this agent (true) or received from outside (false)
514
+ * @param developer Whether the message is a system instruction from the developer
515
+ */
288
516
  addToConversationHistory(agent, message, fromSelf = false, developer = false) {
517
+ // Default implementation for most services
518
+ // Subclasses should override this if they have a different history format
289
519
  if (!agent.history) {
290
520
  agent.history = [];
291
521
  }
@@ -300,10 +530,21 @@ let BaseAiService = class BaseAiService {
300
530
  });
301
531
  agent.trimHistoryIfNeeded();
302
532
  }
533
+ /**
534
+ * Trims a string to extract JSON content
535
+ * @param str The string to trim
536
+ * @returns The trimmed string containing only JSON
537
+ */
538
+ /**
539
+ * Formats a message from the agent's history in a human-readable way
540
+ * @param message The message object from the agent's history
541
+ * @returns A formatted string representation of the message
542
+ */
303
543
  formatMessage(message) {
304
544
  if (!message) {
305
545
  return 'No message';
306
546
  }
547
+ // Default implementation for most services
307
548
  if (message.role && message.content) {
308
549
  let content = message.content;
309
550
  if (typeof content === 'object') {
@@ -311,17 +552,33 @@ let BaseAiService = class BaseAiService {
311
552
  }
312
553
  return `${message.role}: ${content}`;
313
554
  }
555
+ // Generic fallback
314
556
  return JSON.stringify(message);
315
557
  }
558
+ // -------------------------------------------------------------------------
559
+ // AI debug-logging helpers — call these in textPrompt() overrides
560
+ // -------------------------------------------------------------------------
316
561
  debugLogRequest(agentName, content) {
317
562
  ai_debug_logger_1.AiDebugLogger.writeRequest(agentName, content);
318
563
  }
564
+ /** Only writes a file when content is non-empty (no-op for non-reasoning models). */
319
565
  debugLogThinking(agentName, thinking) {
320
566
  ai_debug_logger_1.AiDebugLogger.writeThinking(agentName, thinking);
321
567
  }
322
568
  debugLogResponse(agentName, response) {
323
569
  ai_debug_logger_1.AiDebugLogger.writeResponse(agentName, response);
324
570
  }
571
+ /**
572
+ * The provider's own account of a refused call, as a single log line.
573
+ *
574
+ * `logger` renders its extra arguments with `JSON.stringify`, and an Error
575
+ * stringifies to `{}` — so passing a caught error as an argument logs nothing
576
+ * at all. The status code and response body that say *why* a call was refused
577
+ * live on the AI SDK's `APICallError`, so they have to be read off explicitly
578
+ * and interpolated into the message itself.
579
+ * @param error The error a generate call threw
580
+ * @returns A one-line description, with the response body truncated
581
+ */
325
582
  static describeProviderError(error) {
326
583
  if (!ai_1.APICallError.isInstance(error)) {
327
584
  return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
@@ -341,8 +598,11 @@ let BaseAiService = class BaseAiService {
341
598
  if (!str) {
342
599
  return str;
343
600
  }
601
+ // Remove <think>...</think> tags and their content
602
+ // Use a regex that matches the opening tag, any content (including newlines), and the closing tag
344
603
  str = str.replace(/<think>[\s\S]*?<\/think>/gi, '').trim();
345
604
  if (str.startsWith('```')) {
605
+ // Strip first line and return the rest
346
606
  const lines = str.split('\n');
347
607
  if (lines.length > 1) {
348
608
  str = lines.slice(1).join('\n');
@@ -352,6 +612,7 @@ let BaseAiService = class BaseAiService {
352
612
  }
353
613
  }
354
614
  if (str.endsWith('```')) {
615
+ // Strip last line
355
616
  const lines = str.split('\n');
356
617
  if (lines.length > 1) {
357
618
  str = lines.slice(0, -1).join('\n');
@@ -363,10 +624,12 @@ let BaseAiService = class BaseAiService {
363
624
  return str;
364
625
  }
365
626
  trimToJson(str) {
627
+ // Look for either object or array start
366
628
  let objectStart = str.indexOf('{');
367
629
  let arrayStart = str.indexOf('[');
368
630
  let startIndex = -1;
369
631
  let endChar = '';
632
+ // Determine which comes first (or if only one exists)
370
633
  if (objectStart !== -1 && arrayStart !== -1) {
371
634
  if (objectStart < arrayStart) {
372
635
  startIndex = objectStart;
@@ -394,6 +657,21 @@ let BaseAiService = class BaseAiService {
394
657
  }
395
658
  return str;
396
659
  }
660
+ /**
661
+ * Parses a model's JSON response into an object, tolerating the encoding
662
+ * mistakes models routinely make. Tries a strict JSON.parse first; on
663
+ * failure it runs the text through jsonrepair, which fixes unescaped quotes
664
+ * (e.g. an inch mark like 5'6" inside a string), literal control
665
+ * characters, trailing commas, and similar issues — then parses again.
666
+ *
667
+ * This is the single place every provider should turn raw model text into
668
+ * a structured object, so a single stray character never discards an
669
+ * otherwise-valid response.
670
+ *
671
+ * @param text Raw (already trimmed-to-JSON) model output.
672
+ * @returns The parsed object.
673
+ * @throws The original parse error if the text cannot be recovered.
674
+ */
397
675
  parseStructuredResponse(text) {
398
676
  try {
399
677
  return JSON.parse(text);
@@ -405,6 +683,8 @@ let BaseAiService = class BaseAiService {
405
683
  return JSON.parse(repaired);
406
684
  }
407
685
  catch {
686
+ // Surface the original error — it points at the real problem
687
+ // better than the post-repair failure.
408
688
  logger_1.logger.error('Failed to parse structured response even after repair');
409
689
  throw firstError;
410
690
  }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Recognizing the frame an image model returns when it has refused.
3
+ *
4
+ * A refusal usually arrives as a perfectly successful response carrying a uniformly
5
+ * black picture rather than as an error, so nothing upstream of the pixels can tell
6
+ * it apart from a drawing. Stored, it replaces the likeness it was meant to redraw —
7
+ * `IllustrationService.updatePortrait` deletes the old portrait once the new one is
8
+ * in hand — and the original is gone for good.
9
+ *
10
+ * The test is the compressed size rather than the pixels, because both PNG's deflate
11
+ * and JPEG's DCT crush a flat frame to almost nothing. Measured at 1024x1024, in
12
+ * bytes per pixel:
13
+ *
14
+ * solid colour 0.003
15
+ * smooth gradient 0.11 the flattest thing a model actually draws
16
+ * photographic detail 1.0 - 3.0
17
+ *
18
+ * So the two cases are more than an order of magnitude apart on either side of the
19
+ * threshold below, and deciding between them needs no decoder and no dependency.
20
+ *
21
+ * The limits are worth knowing. A refusal that is not flat — a placeholder graphic,
22
+ * a frame of noise — reads as a picture; those are not what the models in use here
23
+ * return, and guessing at them would cost real drawings. In the other direction a
24
+ * genuinely flat synthetic image, two blocks of colour or a shape on a plain ground,
25
+ * reads as blank, which is why this is applied to generated illustration output and
26
+ * not to anything a person uploads.
27
+ */
28
+ /** Thrown instead of storing a frame that carries no picture. */
29
+ export declare class BlankImageError extends Error {
30
+ constructor(message: string);
31
+ }
32
+ /**
33
+ * Whether these bytes are a blank frame rather than a picture.
34
+ * @param image The decoded image bytes
35
+ */
36
+ export declare function isBlankImage(image: Buffer): boolean;