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
@@ -13,6 +13,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
13
13
  exports.DeepSeekAiService = void 0;
14
14
  const common_1 = require("@nestjs/common");
15
15
  const deepseek_1 = require("@ai-sdk/deepseek");
16
+ // Aliased: `textPrompt`'s own parameter is called `jsonSchema` and would shadow it.
16
17
  const ai_1 = require("ai");
17
18
  const jsonrepair_1 = require("jsonrepair");
18
19
  const base_ai_service_1 = require("./base-ai.service");
@@ -76,6 +77,12 @@ let DeepSeekAiService = DeepSeekAiService_1 = class DeepSeekAiService extends ba
76
77
  throw error;
77
78
  }
78
79
  }
80
+ /**
81
+ * Adds a message to the agent history in the DeepSeek format
82
+ * @param agent The agent to add the message to
83
+ * @param message The formatted message to add
84
+ * @param fromSelf Whether the message was generated by this agent (true) or received from outside (false)
85
+ */
79
86
  addToConversationHistory(agent, message, fromSelf = false) {
80
87
  if (!agent.history) {
81
88
  agent.history = [];
@@ -88,9 +95,34 @@ let DeepSeekAiService = DeepSeekAiService_1 = class DeepSeekAiService extends ba
88
95
  });
89
96
  agent.trimHistoryIfNeeded();
90
97
  }
98
+ /**
99
+ * Salvages a response the schema rejected but Briyah can still use.
100
+ *
101
+ * This service is the only one that *validates* against the prompt's JSON
102
+ * schema: `generateObject` converts it to Zod and throws
103
+ * `AI_NoObjectGeneratedError` on any mismatch. Every other provider does a
104
+ * lenient `JSON.parse`, so a response that merely omits a field reaches
105
+ * `Room.parseAgentResponse` — which is itself defensive, requiring `name` only
106
+ * for an EXECUTE and moderating anything it cannot read.
107
+ *
108
+ * The schemas therefore claim fields are required that Briyah does not require —
109
+ * `name` has to stay in `required` because OpenAI rejects a schema whose
110
+ * `required` omits any property. A response that merely leaves one out is
111
+ * perfectly usable, and discarding it loses the agent's whole turn.
112
+ *
113
+ * So a validation failure is downgraded to a warning and the unvalidated object
114
+ * is used. A response that is not JSON at all still throws — `value` is absent
115
+ * and the text will not parse, which is a genuinely unusable answer rather than
116
+ * a strict-schema quibble.
117
+ * @param agent The agent whose turn this was, for the log line
118
+ * @param error The error `generateObject` threw
119
+ * @returns The salvaged object and the usage to bill, or null to rethrow
120
+ */
91
121
  recoverUnvalidatedObject(agent, error) {
92
122
  if (!ai_1.NoObjectGeneratedError.isInstance(error))
93
123
  return null;
124
+ // `value` — the object the SDK parsed before Zod refused it — is on the
125
+ // error at runtime but absent from its published type.
94
126
  let object = error.value;
95
127
  if (object === undefined && error.text) {
96
128
  try {
@@ -106,6 +138,15 @@ let DeepSeekAiService = DeepSeekAiService_1 = class DeepSeekAiService extends ba
106
138
  `Keys returned: ${Object.keys(object).join(', ')}. ${DeepSeekAiService_1.describeValidationFailure(error)}`);
107
139
  return { object, usage: error.usage };
108
140
  }
141
+ /**
142
+ * The most specific message inside a validation failure's cause chain.
143
+ *
144
+ * `AI_NoObjectGeneratedError` wraps `AI_TypeValidationError` wraps `ZodError`,
145
+ * and only the innermost one says which field was wrong — which is the whole
146
+ * value of the log line.
147
+ * @param error The thrown error
148
+ * @returns A one-line description, truncated
149
+ */
109
150
  static describeValidationFailure(error) {
110
151
  let current = error;
111
152
  let message = '';
@@ -117,17 +158,26 @@ let DeepSeekAiService = DeepSeekAiService_1 = class DeepSeekAiService extends ba
117
158
  const flattened = message.replace(/\s+/g, ' ').trim();
118
159
  return flattened.length > 300 ? `${flattened.slice(0, 300)}…` : flattened;
119
160
  }
120
- async textPrompt(agent, prompt, jsonSchema = null, saveResponse = true, promptInstructions = null, _cacheConfig = null, maxOutputChars = 0) {
161
+ async textPrompt(agent, prompt, jsonSchema = null, saveResponse = true, promptInstructions = null,
162
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
163
+ _cacheConfig = null, maxOutputChars = 0) {
164
+ // CHECK BALANCE BEFORE AI CALL (unless disabled)
121
165
  if (agent.balanceService && !agent.disableBalanceCheck) {
122
166
  const hasSufficientBalance = agent.balanceService.hasSufficientBalance();
123
167
  if (!hasSufficientBalance) {
124
168
  throw new errors_1.InsufficientBalanceError('Insufficient balance. Please add funds to continue using AI services.');
125
169
  }
126
170
  }
171
+ // Build messages array locally without modifying agent.history yet
127
172
  const identity = `Your agent identity is ${agent.agentName}: ${agent.description}`;
128
- const instructions = promptInstructions || agent.systemInstruction;
173
+ const instructions = promptInstructions || this.getSystemInstruction(agent);
174
+ // The instructions go in the `system` option rather than as a leading
175
+ // system message. The SDK warns about the latter because a system turn
176
+ // sitting in `messages` is indistinguishable from one a model was talked
177
+ // into emitting, and this agent's `messages` are largely player text.
129
178
  const messages = [];
130
179
  messages.push({ role: 'user', content: identity });
180
+ // Add attached files as text (DeepSeek doesn't support document types)
131
181
  if (agent.attachedFiles && agent.attachedFiles.length > 0) {
132
182
  for (const file of agent.attachedFiles) {
133
183
  if (file.serviceMetadata?.fileData) {
@@ -140,12 +190,15 @@ let DeepSeekAiService = DeepSeekAiService_1 = class DeepSeekAiService extends ba
140
190
  }
141
191
  }
142
192
  }
193
+ // Handle attached artifacts
143
194
  if (agent.attachedArtifacts && agent.attachedArtifacts.length > 0) {
144
195
  for (const artifactId of agent.attachedArtifacts) {
145
196
  const content = agent.artifactService.getArtifact(artifactId);
197
+ // Only include text artifacts (skip binary/image artifacts)
146
198
  if (content && typeof content === 'string') {
147
199
  const metadata = agent.artifactService.getArtifactMetadata(artifactId);
148
200
  const fileName = metadata ? `${metadata.name}.md` : 'artifact.md';
201
+ // Add as user message
149
202
  messages.push({
150
203
  role: 'user',
151
204
  content: `Attached document: ${fileName}\n\n${content}`,
@@ -153,7 +206,9 @@ let DeepSeekAiService = DeepSeekAiService_1 = class DeepSeekAiService extends ba
153
206
  }
154
207
  }
155
208
  }
209
+ // Add conversation history
156
210
  messages.push(...agent.history);
211
+ // Add the new text prompt as a simple text message
157
212
  if (prompt) {
158
213
  messages.push({
159
214
  role: 'user',
@@ -170,16 +225,30 @@ let DeepSeekAiService = DeepSeekAiService_1 = class DeepSeekAiService extends ba
170
225
  };
171
226
  this.debugLogRequest(agent.agentName, requestParams);
172
227
  try {
228
+ // Use AI SDK to generate response
173
229
  if (jsonSchema) {
174
230
  let object;
175
231
  let usage;
176
232
  try {
233
+ // Generate structured output with schema
177
234
  const result = await (0, ai_1.generateObject)({
178
235
  model: this.deepseekClient(agent.modelName),
179
236
  system: instructions || undefined,
180
- messages: messages,
237
+ messages: messages, // Use local messages array
181
238
  temperature: 0,
239
+ // The prompt's JSON Schema, passed through as-is rather than
240
+ // converted to Zod. DeepSeek has no server-side schema
241
+ // enforcement, so the SDK injects the schema into the system
242
+ // message — which makes the field `description`s the actual
243
+ // instruction the model reads, and a Zod conversion drops
244
+ // them along with `additionalProperties` and nested
245
+ // `required`.
182
246
  schema: (0, ai_1.jsonSchema)(jsonSchema),
247
+ // Repair malformed JSON before the SDK parses it. Models
248
+ // routinely emit unescaped quotes (e.g. an inch mark like
249
+ // 5'6") or stray control characters that break a strict
250
+ // parse; jsonrepair fixes these so a single bad character
251
+ // doesn't discard the whole response.
183
252
  experimental_repairText: async ({ text }) => {
184
253
  try {
185
254
  return (0, jsonrepair_1.jsonrepair)(text);
@@ -204,21 +273,27 @@ let DeepSeekAiService = DeepSeekAiService_1 = class DeepSeekAiService extends ba
204
273
  object = recovered.object;
205
274
  usage = recovered.usage;
206
275
  }
276
+ // Track token usage including cache-specific metrics. Also runs on
277
+ // the recovered path — the tokens were spent either way, and
278
+ // skipping it billed the caller nothing for a call they paid for.
207
279
  if (usage) {
208
280
  this.computeMessageCost(agent, usage);
209
281
  }
210
282
  this.debugLogResponse(agent.agentName, JSON.stringify(object, null, 2));
283
+ // Only modify agent.history if saveResponse=true
211
284
  if (saveResponse) {
212
285
  this.addToConversationHistory(agent, prompt, false);
213
286
  this.addToConversationHistory(agent, JSON.stringify(object), true);
214
287
  }
288
+ // If saveResponse=false, don't modify history at all
215
289
  return object;
216
290
  }
217
291
  else {
292
+ // Generate text response
218
293
  const result = await (0, ai_1.generateText)({
219
294
  model: this.deepseekClient(agent.modelName),
220
295
  system: instructions || undefined,
221
- messages: messages,
296
+ messages: messages, // Use local messages array
222
297
  temperature: 0,
223
298
  providerOptions: {
224
299
  deepseek: {
@@ -226,15 +301,19 @@ let DeepSeekAiService = DeepSeekAiService_1 = class DeepSeekAiService extends ba
226
301
  },
227
302
  },
228
303
  });
304
+ // Track token usage including cache-specific metrics
229
305
  if (result.usage) {
230
306
  this.computeMessageCost(agent, result.usage);
231
307
  }
308
+ // result.reasoning is populated for deepseek-reasoner models
232
309
  this.debugLogThinking(agent.agentName, result.reasoning ?? '');
233
310
  this.debugLogResponse(agent.agentName, result.text);
311
+ // Only modify agent.history if saveResponse=true
234
312
  if (saveResponse) {
235
313
  this.addToConversationHistory(agent, prompt, false);
236
314
  this.addToConversationHistory(agent, result.text, true);
237
315
  }
316
+ // If saveResponse=false, don't modify history at all
238
317
  return result.text;
239
318
  }
240
319
  }
@@ -244,17 +323,32 @@ let DeepSeekAiService = DeepSeekAiService_1 = class DeepSeekAiService extends ba
244
323
  throw error;
245
324
  }
246
325
  }
326
+ /**
327
+ * Attaches a document to the agent or as a shared document
328
+ * @param agent The agent context (null for shared documents)
329
+ * @param fileName The name of the file
330
+ * @param fileData The file data as a Uint8Array
331
+ * @returns Promise with the result
332
+ */
247
333
  async attachDocument(agent, fileName, fileData) {
248
334
  if (agent === null) {
249
335
  throw new Error('Shared document attachment not supported by the DeepSeek service');
250
336
  }
251
337
  return super.attachDocument(agent, fileName, fileData);
252
338
  }
339
+ /**
340
+ * Compute the cost of a message with markup and cache-aware pricing for DeepSeek
341
+ * DeepSeek provides a 74-75% discount on cached tokens (no cache creation charge)
342
+ * Handles model name lookup with deepseek/ prefix if needed
343
+ * @param agent The agent making the request
344
+ * @param usage Usage object from the API response
345
+ */
253
346
  computeMessageCost(agent, usage) {
254
347
  const totalInputTokens = usage.inputTokens || 0;
255
348
  const cachedTokens = usage.cachedInputTokens || 0;
256
349
  const uncachedInputTokens = totalInputTokens - cachedTokens;
257
350
  const outputTokens = usage.outputTokens || 0;
351
+ // Try to find model with current name, then try with deepseek/ prefix
258
352
  let modelInfo = (0, model_prices_1.getModelPrices)()[agent.modelName];
259
353
  if (!modelInfo && !agent.modelName.startsWith('deepseek/')) {
260
354
  modelInfo = (0, model_prices_1.getModelPrices)()[`deepseek/${agent.modelName}`];
@@ -263,20 +357,25 @@ let DeepSeekAiService = DeepSeekAiService_1 = class DeepSeekAiService extends ba
263
357
  logger_1.logger.error(`No price info found for model ${agent.modelName} or deepseek/${agent.modelName}`);
264
358
  return;
265
359
  }
360
+ // Calculate cache-aware costs (DeepSeek: 75% discount on cached)
266
361
  const uncachedCost = uncachedInputTokens * modelInfo.input_cost_per_token;
267
362
  const cachedCost = cachedTokens *
268
363
  (modelInfo.cache_read_input_token_cost || modelInfo.input_cost_per_token * 0.25);
269
364
  const outputCost = outputTokens * modelInfo.output_cost_per_token;
365
+ // Calculate markup: 2x output cost only (unless disabled)
270
366
  const markup = agent.disableMarkup ? 0 : outputCost * agent.markupRate;
271
367
  const cost = uncachedCost + cachedCost + outputCost + markup;
368
+ // Update agent totals
272
369
  agent.totalInputTokens += totalInputTokens;
273
370
  agent.totalOutputTokens += outputTokens;
274
371
  agent.totalCost += cost;
275
372
  agent.totalMarkup += markup;
276
373
  logger_1.logger.log(`Cost for ${agent.agentName} message: ${cost} (markup: ${markup.toFixed(4)})`);
374
+ // Log cache metrics for monitoring
277
375
  if (cachedTokens > 0) {
278
376
  logger_1.logger.log(`Cache metrics for ${agent.agentName}: cached=${cachedTokens}, uncached=${uncachedInputTokens}`);
279
377
  }
378
+ // Decrement balance with markup
280
379
  if (agent.balanceService && cost > 0) {
281
380
  agent.balanceService.decrementBalance(cost, markup);
282
381
  }
@@ -7,9 +7,34 @@ export declare class FalAiService extends BaseAiService {
7
7
  getModelPricePrefix(): string;
8
8
  supportsImageGeneration(): boolean;
9
9
  fetchModelsFromApi(): Promise<ModelInfo[]>;
10
+ /**
11
+ * Adds a message to the agent history in the appropriate format for this service
12
+ * @param agent The agent to add the message to
13
+ * @param message The formatted message to add
14
+ * @param fromSelf Whether the message was generated by this agent (true) or received from outside (false)
15
+ * @param developer Whether the message is a system instruction from the developer
16
+ */
10
17
  addToConversationHistory(agent: Agent, message: string, fromSelf?: boolean, developer?: boolean): void;
11
18
  textPrompt(agent: Agent, prompt: string, jsonSchema?: any, saveResponse?: boolean, promptInstructions?: string, _cacheConfig?: any, maxOutputChars?: number): Promise<any>;
19
+ /**
20
+ * Compute the cost of a text message with markup for Fal AI
21
+ * Handles model name lookup with fal_ai/ prefix if needed
22
+ * @param agent The agent making the request
23
+ * @param usage Usage object from the API response (or estimated)
24
+ * @param estimatedInputTokens Fallback estimate if usage not provided
25
+ * @param estimatedOutputTokens Fallback estimate if usage not provided
26
+ */
12
27
  private computeMessageCost;
28
+ /**
29
+ * Generates an image from a text prompt with optional reference images
30
+ * @param agent The agent making the request
31
+ * @param prompt Text description of the image to generate
32
+ * @param width
33
+ * @param height
34
+ * @param quality
35
+ * @param referenceImageArtifactIds Optional array of artifact IDs containing reference images
36
+ * @returns Promise resolving to JSON string with { artifactId }
37
+ */
13
38
  private computeImageCost;
14
39
  generateImage(agent: Agent, prompt: string, imageProperties?: Record<string, any>): Promise<{
15
40
  artifactId?: string;
@@ -25,6 +25,7 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
25
25
  this._isAvailable = false;
26
26
  return;
27
27
  }
28
+ // Configure fal client
28
29
  client_1.fal.config({ credentials: apiKey });
29
30
  logger_1.logger.debug('FalAI service initialized successfully');
30
31
  }
@@ -59,6 +60,7 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
59
60
  }
60
61
  const data = await response.json();
61
62
  const models = [];
63
+ // Transform API response to ModelInfo format
62
64
  if (data.models && Array.isArray(data.models)) {
63
65
  for (const model of data.models) {
64
66
  models.push({
@@ -77,6 +79,13 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
77
79
  return [];
78
80
  }
79
81
  }
82
+ /**
83
+ * Adds a message to the agent history in the appropriate format for this service
84
+ * @param agent The agent to add the message to
85
+ * @param message The formatted message to add
86
+ * @param fromSelf Whether the message was generated by this agent (true) or received from outside (false)
87
+ * @param developer Whether the message is a system instruction from the developer
88
+ */
80
89
  addToConversationHistory(agent, message, fromSelf = false, developer = false) {
81
90
  if (!agent.history) {
82
91
  agent.history = [];
@@ -92,20 +101,27 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
92
101
  });
93
102
  agent.trimHistoryIfNeeded();
94
103
  }
95
- async textPrompt(agent, prompt, jsonSchema = null, saveResponse = true, promptInstructions = null, _cacheConfig = null, maxOutputChars = 0) {
104
+ async textPrompt(agent, prompt, jsonSchema = null, saveResponse = true, promptInstructions = null,
105
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
106
+ _cacheConfig = null, maxOutputChars = 0) {
107
+ // CHECK BALANCE BEFORE AI CALL (unless disabled)
96
108
  if (agent.balanceService && !agent.disableBalanceCheck) {
97
109
  const hasSufficientBalance = agent.balanceService.hasSufficientBalance();
98
110
  if (!hasSufficientBalance) {
99
111
  throw new errors_1.InsufficientBalanceError('Insufficient balance. Please add funds to continue using AI services.');
100
112
  }
101
113
  }
114
+ // Build messages array locally without modifying agent.history yet
115
+ // Prepend identity and system instruction at the beginning
102
116
  const identity = `Your agent identity is ${agent.agentName}: ${agent.description}`;
103
- const instructions = promptInstructions || agent.systemInstruction;
117
+ const instructions = promptInstructions || this.getSystemInstruction(agent);
118
+ // Build full prompt for fal.ai any-llm
104
119
  let fullPrompt = '';
105
120
  if (instructions) {
106
121
  fullPrompt += instructions + '\n\n';
107
122
  }
108
123
  fullPrompt += identity + '\n\n';
124
+ // Add attached files as text (fal.ai doesn't support native file uploads)
109
125
  if (agent.attachedFiles && agent.attachedFiles.length > 0) {
110
126
  for (const file of agent.attachedFiles) {
111
127
  if (file.serviceMetadata?.fileData) {
@@ -115,12 +131,15 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
115
131
  }
116
132
  }
117
133
  }
134
+ // Add conversation history
118
135
  for (const msg of agent.history) {
119
136
  fullPrompt += `${msg.role}: ${msg.content}\n\n`;
120
137
  }
138
+ // Add JSON schema instruction if provided
121
139
  if (jsonSchema) {
122
140
  fullPrompt += `You must respond with valid JSON matching this schema: ${JSON.stringify(jsonSchema)}\n\n`;
123
141
  }
142
+ // Add user prompt
124
143
  if (prompt) {
125
144
  fullPrompt += `user: ${prompt}\n\n`;
126
145
  }
@@ -129,6 +148,7 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
129
148
  let estimatedInputTokens = 0;
130
149
  let estimatedOutputTokens = 0;
131
150
  try {
151
+ // Estimate input tokens (rough estimate: 4 characters per token)
132
152
  estimatedInputTokens = Math.ceil(fullPrompt.length / 4);
133
153
  const result = (await client_1.fal.subscribe('fal-ai/any-llm', {
134
154
  input: {
@@ -136,6 +156,7 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
136
156
  prompt: fullPrompt,
137
157
  },
138
158
  }));
159
+ // Extract response
139
160
  if (result.output) {
140
161
  responseText = result.output;
141
162
  }
@@ -148,6 +169,7 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
148
169
  else {
149
170
  responseText = '';
150
171
  }
172
+ // Estimate output tokens
151
173
  estimatedOutputTokens = Math.ceil(responseText.length / 4);
152
174
  if (jsonSchema) {
153
175
  responseText = this.trimToJson(responseText);
@@ -155,6 +177,7 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
155
177
  else {
156
178
  responseText = this.trimResponseText(responseText);
157
179
  }
180
+ // Track token usage (using estimates since fal.ai may not return usage)
158
181
  const usage = result.usage || {
159
182
  prompt_tokens: estimatedInputTokens,
160
183
  completion_tokens: estimatedOutputTokens,
@@ -172,6 +195,7 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
172
195
  }
173
196
  throw error;
174
197
  }
198
+ // Only modify agent.history if saveResponse=true
175
199
  if (saveResponse) {
176
200
  this.addToConversationHistory(agent, prompt, false);
177
201
  this.addToConversationHistory(agent, responseText, true);
@@ -188,9 +212,18 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
188
212
  }
189
213
  return responseText;
190
214
  }
215
+ /**
216
+ * Compute the cost of a text message with markup for Fal AI
217
+ * Handles model name lookup with fal_ai/ prefix if needed
218
+ * @param agent The agent making the request
219
+ * @param usage Usage object from the API response (or estimated)
220
+ * @param estimatedInputTokens Fallback estimate if usage not provided
221
+ * @param estimatedOutputTokens Fallback estimate if usage not provided
222
+ */
191
223
  computeMessageCost(agent, usage, estimatedInputTokens, estimatedOutputTokens) {
192
224
  const inputTokens = usage?.prompt_tokens || estimatedInputTokens || 0;
193
225
  const outputTokens = usage?.completion_tokens || estimatedOutputTokens || 0;
226
+ // Try to find model with current name, then try with fal_ai/ prefix
194
227
  let modelInfo = (0, model_prices_1.getModelPrices)()[agent.modelName];
195
228
  if (!modelInfo && !agent.modelName.startsWith('fal_ai/')) {
196
229
  modelInfo = (0, model_prices_1.getModelPrices)()[`fal_ai/${agent.modelName}`];
@@ -199,10 +232,13 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
199
232
  logger_1.logger.warn(`No price info found for model ${agent.modelName}. Skipping cost tracking.`);
200
233
  return;
201
234
  }
235
+ // Simple calculation
202
236
  const inputCost = inputTokens * (modelInfo.input_cost_per_token || 0);
203
237
  const outputCost = outputTokens * (modelInfo.output_cost_per_token || 0);
238
+ // Calculate markup: 2x output cost (unless disabled)
204
239
  const markup = agent.disableMarkup ? 0 : outputCost * agent.markupRate;
205
240
  const cost = inputCost + outputCost + markup;
241
+ // Update agent totals
206
242
  agent.totalInputTokens += inputTokens;
207
243
  agent.totalOutputTokens += outputTokens;
208
244
  agent.totalCost += cost;
@@ -213,10 +249,21 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
213
249
  else {
214
250
  logger_1.logger.log(`Cost for ${agent.agentName} message: ${cost.toFixed(4)} (markup: ${markup.toFixed(4)})`);
215
251
  }
252
+ // Decrement balance with markup
216
253
  if (agent.balanceService && cost > 0) {
217
254
  agent.balanceService.decrementBalance(cost, markup);
218
255
  }
219
256
  }
257
+ /**
258
+ * Generates an image from a text prompt with optional reference images
259
+ * @param agent The agent making the request
260
+ * @param prompt Text description of the image to generate
261
+ * @param width
262
+ * @param height
263
+ * @param quality
264
+ * @param referenceImageArtifactIds Optional array of artifact IDs containing reference images
265
+ * @returns Promise resolving to JSON string with { artifactId }
266
+ */
220
267
  computeImageCost(agent, centsPerImage) {
221
268
  let modelInfo = (0, model_prices_1.getModelPrices)()[agent.modelName];
222
269
  if (!modelInfo && !agent.modelName.startsWith('fal_ai/')) {
@@ -268,15 +315,19 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
268
315
  input: input,
269
316
  }));
270
317
  this.computeImageCost(agent, centsPerImage);
318
+ // 7. Extract image from result
271
319
  let base64Data;
272
320
  if (result.data.images && result.data.images[0]) {
273
321
  const image = result.data.images[0];
322
+ // Check if it's a URL or base64
274
323
  if (image.url) {
324
+ // Download image and convert to base64
275
325
  const imageResponse = await fetch(image.url);
276
326
  const imageBuffer = Buffer.from(await imageResponse.arrayBuffer());
277
327
  base64Data = imageBuffer.toString('base64');
278
328
  }
279
329
  else if (image.content) {
330
+ // Already base64
280
331
  base64Data = image.content;
281
332
  }
282
333
  else {
@@ -284,6 +335,7 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
284
335
  }
285
336
  }
286
337
  else if (result.data.image) {
338
+ // Some models return single image object
287
339
  if (result.data.image.url) {
288
340
  const imageResponse = await fetch(result.data.image.url);
289
341
  const imageBuffer = Buffer.from(await imageResponse.arrayBuffer());
@@ -299,7 +351,9 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
299
351
  else {
300
352
  throw new Error('Unexpected response format from Fal AI');
301
353
  }
354
+ // 8. Save generated image as artifact
302
355
  const artifactId = await this.saveImageAsArtifact(agent, base64Data, prompt);
356
+ // 9. Return artifact ID
303
357
  return { artifactId };
304
358
  }
305
359
  catch (error) {
@@ -8,13 +8,32 @@ export declare class GoogleAiService extends BaseAiService {
8
8
  supportsImageGeneration(): boolean;
9
9
  supportsPromptCaching(): boolean;
10
10
  fetchModelsFromApi(): Promise<ModelInfo[]>;
11
+ /**
12
+ * Adds a message to the agent history in Google AI format
13
+ * @param agent The agent to add the message to
14
+ * @param message The formatted message to add
15
+ * @param fromSelf Whether the message was generated by this agent (true) or received from outside (false)
16
+ */
11
17
  addToConversationHistory(agent: Agent, message: string, fromSelf?: boolean): void;
12
18
  textPrompt(agent: Agent, prompt: string, jsonSchema?: any, saveResponse?: boolean, promptInstructions?: string, _cacheConfig?: any, maxOutputChars?: number): Promise<any>;
13
19
  generateImage(agent: Agent, prompt: string, imageProperties?: Record<string, any>): Promise<{
14
20
  artifactId?: string;
15
21
  error?: any;
16
22
  }>;
23
+ /**
24
+ * Compute the cost of a message with markup
25
+ * @param agent The agent making the request
26
+ * @param usage Usage metadata object
27
+ */
17
28
  private computeMessageCost;
29
+ /**
30
+ * Compute the cost of image generation with markup (hardcoded to 0 for images)
31
+ * @param agent The agent making the request
32
+ * @param modelName The model name used for image generation
33
+ */
18
34
  private computeImageCost;
35
+ /**
36
+ * Override the formatMessage method to handle Google AI specific message format
37
+ */
19
38
  formatMessage(message: any): string;
20
39
  }