briyah 1.3.4 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (254) hide show
  1. package/README.md +689 -619
  2. package/data/common/artifacts/dnd5e/campaign_designer-setting.md +112 -0
  3. package/data/common/artifacts/dnd5e/character_creator-basics.md +40 -0
  4. package/data/common/artifacts/dnd5e/class-barbarian.md +64 -0
  5. package/data/common/artifacts/dnd5e/class-bard.md +63 -0
  6. package/data/common/artifacts/dnd5e/class-cleric.md +60 -0
  7. package/data/common/artifacts/dnd5e/class-druid.md +56 -0
  8. package/data/common/artifacts/dnd5e/class-fighter.md +53 -0
  9. package/data/common/artifacts/dnd5e/class-monk.md +77 -0
  10. package/data/common/artifacts/dnd5e/class-paladin.md +66 -0
  11. package/data/common/artifacts/dnd5e/class-ranger.md +73 -0
  12. package/data/common/artifacts/dnd5e/class-rogue.md +62 -0
  13. package/data/common/artifacts/dnd5e/class-sorcerer.md +67 -0
  14. package/data/common/artifacts/dnd5e/class-warlock.md +83 -0
  15. package/data/common/artifacts/dnd5e/class-wizard.md +51 -0
  16. package/data/common/artifacts/dnd5e/dungeon_master-procedure.md +348 -0
  17. package/data/common/artifacts/dnd5e/manifest.json +95 -0
  18. package/data/common/config/comfyui-workflows/flux-kontext.edit.json +98 -0
  19. package/data/common/config/comfyui-workflows/flux-kontext.t2i.json +80 -0
  20. package/data/common/config/comfyui-workflows/flux2-dev.edit.json +125 -0
  21. package/data/common/config/comfyui-workflows/flux2-dev.t2i.json +96 -0
  22. package/data/common/config/image_models_full.json +186 -99
  23. package/data/common/config/markup +1 -1
  24. package/data/common/config/model_prices.json +1250 -237
  25. package/data/common/prompts/campaign_designer/defaults_config.json +16 -0
  26. package/data/common/prompts/campaign_designer/perceive.json +29 -0
  27. package/data/common/prompts/campaign_designer/perceive.prompt +345 -0
  28. package/data/common/prompts/campaign_designer/system_instruction.prompt +0 -0
  29. package/data/common/prompts/character_creator/defaults_config.json +31 -0
  30. package/data/common/prompts/character_creator/perceive.json +29 -0
  31. package/data/common/prompts/character_creator/perceive.prompt +621 -0
  32. package/data/common/prompts/character_creator/system_instruction.prompt +0 -0
  33. package/data/common/prompts/dnd_player/defaults_config.json +5 -0
  34. package/data/common/prompts/dnd_player/perceive.json +29 -0
  35. package/data/common/prompts/dnd_player/perceive.prompt +312 -0
  36. package/data/common/prompts/dnd_player/system_instruction.prompt +0 -0
  37. package/data/common/prompts/dnd_room_moderator/defaults_config.json +9 -0
  38. package/data/common/prompts/dnd_room_moderator/moderate.json +34 -0
  39. package/data/common/prompts/dnd_room_moderator/moderate.prompt +291 -0
  40. package/data/common/prompts/dnd_room_moderator/system_instruction.prompt +0 -0
  41. package/data/common/prompts/dungeon_master/compact_agent.prompt +24 -0
  42. package/data/common/prompts/dungeon_master/defaults_config.json +29 -0
  43. package/data/common/prompts/dungeon_master/perceive.json +33 -0
  44. package/data/common/prompts/dungeon_master/perceive.prompt +757 -0
  45. package/data/common/prompts/dungeon_master/system_instruction.prompt +0 -0
  46. package/data/common/prompts/room_moderator/moderate.json +34 -29
  47. package/data/common/prompts/room_moderator/moderate.prompt +230 -210
  48. package/data/common/prompts/story_moderator/moderate.prompt +5 -2
  49. package/data/common/prompts/story_moderator/moderate_to_alice.mock +6 -6
  50. package/data/common/prompts/story_moderator/moderate_to_bob.mock +6 -6
  51. package/dist-sdk/server/src/ai/LLM/anthropic.service.d.ts +2 -0
  52. package/dist-sdk/server/src/ai/LLM/anthropic.service.js +34 -22
  53. package/dist-sdk/server/src/ai/LLM/base-ai.service.d.ts +2 -0
  54. package/dist-sdk/server/src/ai/LLM/base-ai.service.js +8 -3
  55. package/dist-sdk/server/src/ai/LLM/comfyui-client.d.ts +29 -0
  56. package/dist-sdk/server/src/ai/LLM/comfyui-client.js +142 -0
  57. package/dist-sdk/server/src/ai/LLM/comfyui-workflow.d.ts +19 -0
  58. package/dist-sdk/server/src/ai/LLM/comfyui-workflow.js +217 -0
  59. package/dist-sdk/server/src/ai/LLM/comfyui.module.d.ts +2 -0
  60. package/dist-sdk/server/src/ai/LLM/comfyui.module.js +21 -0
  61. package/dist-sdk/server/src/ai/LLM/comfyui.service.d.ts +26 -0
  62. package/dist-sdk/server/src/ai/LLM/comfyui.service.js +191 -0
  63. package/dist-sdk/server/src/ai/LLM/mock.service.d.ts +1 -0
  64. package/dist-sdk/server/src/ai/LLM/mock.service.js +3 -0
  65. package/dist-sdk/server/src/ai/LLM/self-hosted.module.d.ts +2 -0
  66. package/dist-sdk/server/src/ai/LLM/self-hosted.module.js +21 -0
  67. package/dist-sdk/server/src/ai/LLM/self-hosted.service.d.ts +13 -0
  68. package/dist-sdk/server/src/ai/LLM/self-hosted.service.js +205 -0
  69. package/dist-sdk/server/src/ai/agent-config.d.ts +1 -0
  70. package/dist-sdk/server/src/ai/agent-store.service.js +6 -4
  71. package/dist-sdk/server/src/ai/agent.d.ts +7 -0
  72. package/dist-sdk/server/src/ai/agent.js +33 -2
  73. package/dist-sdk/server/src/ai/ai-factory.module.js +4 -0
  74. package/dist-sdk/server/src/ai/ai-factory.service.d.ts +5 -1
  75. package/dist-sdk/server/src/ai/ai-factory.service.js +16 -2
  76. package/dist-sdk/server/src/ai/artifact.service.d.ts +2 -0
  77. package/dist-sdk/server/src/ai/artifact.service.js +29 -1
  78. package/dist-sdk/server/src/ai/pack-artifacts.d.ts +7 -0
  79. package/dist-sdk/server/src/ai/pack-artifacts.js +155 -0
  80. package/dist-sdk/server/src/app/stripe.controller.js +5 -0
  81. package/dist-sdk/server/src/app.controller.d.ts +18 -18
  82. package/dist-sdk/server/src/app.controller.js +249 -25
  83. package/dist-sdk/server/src/app.service.d.ts +30 -17
  84. package/dist-sdk/server/src/app.service.js +304 -36
  85. package/dist-sdk/server/src/auth/auth.controller.js +3 -2
  86. package/dist-sdk/server/src/auth/owner-only.decorator.d.ts +1 -0
  87. package/dist-sdk/server/src/auth/owner-only.decorator.js +8 -0
  88. package/dist-sdk/server/src/auth/twilio.service.d.ts +5 -1
  89. package/dist-sdk/server/src/auth/twilio.service.js +5 -3
  90. package/dist-sdk/server/src/config/user-paths.service.d.ts +2 -0
  91. package/dist-sdk/server/src/config/user-paths.service.js +8 -0
  92. package/dist-sdk/server/src/room/artifact-store.service.js +10 -2
  93. package/dist-sdk/server/src/room/artifact.d.ts +1 -0
  94. package/dist-sdk/server/src/room/message.d.ts +2 -1
  95. package/dist-sdk/server/src/room/message.js +5 -4
  96. package/dist-sdk/server/src/room/room-config.d.ts +3 -0
  97. package/dist-sdk/server/src/room/room-store.service.d.ts +4 -2
  98. package/dist-sdk/server/src/room/room-store.service.js +46 -12
  99. package/dist-sdk/server/src/room/room.d.ts +29 -3
  100. package/dist-sdk/server/src/room/room.js +390 -122
  101. package/dist-sdk/server/src/sdk/briyah.js +21 -3
  102. package/dist-sdk/server/src/sdk/index.d.ts +4 -1
  103. package/dist-sdk/server/src/sdk/index.js +9 -1
  104. package/dist-sdk/server/src/story/story.service.js +21 -12
  105. package/dist-sdk/server/src/tools/native-tool.types.d.ts +31 -0
  106. package/dist-sdk/server/src/tools/packs/dnd5e/data/backgrounds.d.ts +22 -0
  107. package/dist-sdk/server/src/tools/packs/dnd5e/data/backgrounds.js +59 -0
  108. package/dist-sdk/server/src/tools/packs/dnd5e/data/feats.d.ts +24 -0
  109. package/dist-sdk/server/src/tools/packs/dnd5e/data/feats.js +11 -0
  110. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.d.ts +5 -0
  111. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.generated.d.ts +1 -0
  112. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.generated.js +154 -0
  113. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.js +9 -0
  114. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.d.ts +20 -0
  115. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.generated.d.ts +2 -0
  116. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.generated.js +1824 -0
  117. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.js +6 -0
  118. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.d.ts +44 -0
  119. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.generated.d.ts +2 -0
  120. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.generated.js +17293 -0
  121. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.js +5 -0
  122. package/dist-sdk/server/src/tools/packs/dnd5e/data/races.d.ts +41 -0
  123. package/dist-sdk/server/src/tools/packs/dnd5e/data/races.js +250 -0
  124. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.d.ts +16 -0
  125. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.generated.d.ts +2 -0
  126. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.generated.js +3760 -0
  127. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.js +12 -0
  128. package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.d.ts +63 -0
  129. package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.js +449 -0
  130. package/dist-sdk/server/src/tools/packs/dnd5e/data/weapons.d.ts +23 -0
  131. package/dist-sdk/server/src/tools/packs/dnd5e/data/weapons.js +88 -0
  132. package/dist-sdk/server/src/tools/packs/dnd5e/engine/backgrounds.d.ts +20 -0
  133. package/dist-sdk/server/src/tools/packs/dnd5e/engine/backgrounds.js +109 -0
  134. package/dist-sdk/server/src/tools/packs/dnd5e/engine/bestiary.d.ts +30 -0
  135. package/dist-sdk/server/src/tools/packs/dnd5e/engine/bestiary.js +329 -0
  136. package/dist-sdk/server/src/tools/packs/dnd5e/engine/campaign-items.d.ts +9 -0
  137. package/dist-sdk/server/src/tools/packs/dnd5e/engine/campaign-items.js +100 -0
  138. package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.d.ts +117 -0
  139. package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.js +1057 -0
  140. package/dist-sdk/server/src/tools/packs/dnd5e/engine/coerce.d.ts +13 -0
  141. package/dist-sdk/server/src/tools/packs/dnd5e/engine/coerce.js +147 -0
  142. package/dist-sdk/server/src/tools/packs/dnd5e/engine/dice.d.ts +27 -0
  143. package/dist-sdk/server/src/tools/packs/dnd5e/engine/dice.js +263 -0
  144. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encumbrance.d.ts +26 -0
  145. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encumbrance.js +129 -0
  146. package/dist-sdk/server/src/tools/packs/dnd5e/engine/feats.d.ts +22 -0
  147. package/dist-sdk/server/src/tools/packs/dnd5e/engine/feats.js +127 -0
  148. package/dist-sdk/server/src/tools/packs/dnd5e/engine/items.d.ts +33 -0
  149. package/dist-sdk/server/src/tools/packs/dnd5e/engine/items.js +137 -0
  150. package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.d.ts +26 -0
  151. package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.js +182 -0
  152. package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.d.ts +48 -0
  153. package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.js +344 -0
  154. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.d.ts +98 -0
  155. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.js +456 -0
  156. package/dist-sdk/server/src/tools/packs/dnd5e/engine/spells.d.ts +27 -0
  157. package/dist-sdk/server/src/tools/packs/dnd5e/engine/spells.js +123 -0
  158. package/dist-sdk/server/src/tools/packs/dnd5e/engine/weapons.d.ts +23 -0
  159. package/dist-sdk/server/src/tools/packs/dnd5e/engine/weapons.js +201 -0
  160. package/dist-sdk/server/src/tools/packs/dnd5e/index.d.ts +3 -0
  161. package/dist-sdk/server/src/tools/packs/dnd5e/index.js +35 -0
  162. package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.d.ts +2 -0
  163. package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.js +323 -0
  164. package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.d.ts +3 -0
  165. package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.js +117 -0
  166. package/dist-sdk/server/src/tools/packs/dnd5e/tools/item.tool.d.ts +2 -0
  167. package/dist-sdk/server/src/tools/packs/dnd5e/tools/item.tool.js +122 -0
  168. package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.d.ts +2 -0
  169. package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.js +157 -0
  170. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.d.ts +32 -0
  171. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.js +203 -0
  172. package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.d.ts +4 -0
  173. package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.js +465 -0
  174. package/dist-sdk/server/src/tools/packs/dnd5e/tools/spell.tool.d.ts +2 -0
  175. package/dist-sdk/server/src/tools/packs/dnd5e/tools/spell.tool.js +116 -0
  176. package/dist-sdk/server/src/tools/packs/dnd5e/tools/state.tools.d.ts +4 -0
  177. package/dist-sdk/server/src/tools/packs/dnd5e/tools/state.tools.js +234 -0
  178. package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.d.ts +6 -0
  179. package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.js +616 -0
  180. package/dist-sdk/server/src/tools/packs/index.d.ts +7 -0
  181. package/dist-sdk/server/src/tools/packs/index.js +45 -0
  182. package/dist-sdk/server/src/tools/tool-execution.service.d.ts +2 -2
  183. package/dist-sdk/server/src/tools/tool-execution.service.js +7 -6
  184. package/dist-sdk/shared/types/app.types.d.ts +63 -0
  185. package/docs/assets/hierarchy.js +1 -1
  186. package/docs/assets/navigation.js +1 -1
  187. package/docs/assets/search.js +1 -1
  188. package/docs/classes/Agent.html +51 -15
  189. package/docs/classes/Briyah.html +14 -14
  190. package/docs/classes/BriyahConfigService.html +5 -5
  191. package/docs/classes/NativeToolRegistry.html +21 -0
  192. package/docs/classes/Room.html +79 -29
  193. package/docs/classes/RoomMessage.html +32 -15
  194. package/docs/enums/MessageAction.html +3 -3
  195. package/docs/functions/availableToolPacks.html +2 -0
  196. package/docs/functions/dnd5eTools.html +5 -0
  197. package/docs/functions/enabledToolPacks.html +2 -0
  198. package/docs/functions/registerToolPacks.html +6 -0
  199. package/docs/hierarchy.html +1 -1
  200. package/docs/index.html +47 -3
  201. package/docs/interfaces/AgentInfo.html +17 -2
  202. package/docs/interfaces/AgentMessagesResponse.html +2 -2
  203. package/docs/interfaces/AppService.html +230 -181
  204. package/docs/interfaces/Artifact.html +15 -3
  205. package/docs/interfaces/ArtifactMetadata.html +5 -2
  206. package/docs/interfaces/ArtifactWriteOptions.html +21 -0
  207. package/docs/interfaces/AttachDocumentResponse.html +2 -2
  208. package/docs/interfaces/BriyahConfigOptions.html +9 -9
  209. package/docs/interfaces/ChapterInfo.html +2 -2
  210. package/docs/interfaces/Character.html +2 -2
  211. package/docs/interfaces/CreateAgentResponse.html +2 -2
  212. package/docs/interfaces/CreateRoomResponse.html +2 -2
  213. package/docs/interfaces/CreateStoryResponse.html +2 -2
  214. package/docs/interfaces/FileList.html +2 -2
  215. package/docs/interfaces/FileMetadata.html +3 -3
  216. package/docs/interfaces/IConfigService.html +3 -3
  217. package/docs/interfaces/LoggingOptions.html +6 -6
  218. package/docs/interfaces/Message.html +2 -2
  219. package/docs/interfaces/ModelInfo.html +2 -2
  220. package/docs/interfaces/NativeToolDefinition.html +11 -7
  221. package/docs/interfaces/PreparedPromptResponse.html +2 -2
  222. package/docs/interfaces/ProcessTextResponse.html +2 -2
  223. package/docs/interfaces/PromptFile.html +2 -2
  224. package/docs/interfaces/PromptFileContent.html +2 -2
  225. package/docs/interfaces/PromptFilesResponse.html +2 -2
  226. package/docs/interfaces/PromptFolder.html +2 -2
  227. package/docs/interfaces/PromptFoldersResponse.html +2 -2
  228. package/docs/interfaces/RoomDetails.html +15 -2
  229. package/docs/interfaces/RoomInfo.html +3 -2
  230. package/docs/interfaces/RoomMessageUpdate.html +2 -2
  231. package/docs/interfaces/RoomMessagesResponse.html +2 -2
  232. package/docs/interfaces/SendMessageResult.html +2 -2
  233. package/docs/interfaces/StoryErrorEvent.html +3 -3
  234. package/docs/interfaces/StoryIdea.html +2 -2
  235. package/docs/interfaces/StoryInfo.html +3 -3
  236. package/docs/interfaces/StoryIntroduceCharacterEvent.html +3 -3
  237. package/docs/interfaces/StoryProgressChapterEvent.html +3 -3
  238. package/docs/interfaces/StoryState.html +5 -5
  239. package/docs/interfaces/StoryStateEvent.html +3 -3
  240. package/docs/interfaces/ToolArtifact.html +8 -0
  241. package/docs/interfaces/ToolCaller.html +8 -0
  242. package/docs/interfaces/ToolDefinition.html +2 -2
  243. package/docs/interfaces/ToolHelpers.html +7 -3
  244. package/docs/interfaces/ToolParameter.html +2 -2
  245. package/docs/interfaces/ToolRoomAccess.html +51 -0
  246. package/docs/interfaces/ToolSummary.html +3 -2
  247. package/docs/interfaces/ToolsResponse.html +2 -2
  248. package/docs/interfaces/Transaction.html +2 -2
  249. package/docs/interfaces/TransactionHistoryResponse.html +2 -2
  250. package/docs/modules.html +1 -1
  251. package/docs/types/PromptScope.html +1 -1
  252. package/docs/types/ToolContext.html +2 -2
  253. package/docs/types/ToolRunResult.html +1 -1
  254. package/package.json +7 -4
package/README.md CHANGED
@@ -1,619 +1,689 @@
1
- # Briyah SDK
2
-
3
- Briyah is an SDK for AI agents, multi-agent rooms, and interactive stories. It wraps the Briyah runtime as a single class with per-user data isolation and balance tracking, and supports Anthropic, OpenAI, Google, Grok, DeepSeek, Together, and Fal as LLM providers.
4
-
5
- What's in the package:
6
-
7
- - **Agents.** AI agents with a system prompt, persistent conversation history, attached documents, and per-call cost and token tracking. Histories can be summarized/compacted or cleared.
8
- - **Rooms.** Multi-agent conversations with a shared goal. Agents exchange messages at different visibility levels (speak, whisper, think, shout), publish shared artifacts, run tools, commission each other for parallel research, and a moderator can route turns.
9
- - **Tools.** Functions agents can call from a room, granted per agent. Two kinds:
10
- - **Native tools** — real functions you register in your host code with `briyah.registerTool` (see [Example 8](#example-8-registering-native-tools-with-opaque-context)). They have full access to your imports, database, and filesystem, and receive an **opaque per-invocation context** you supply — use it to scope a call to trusted data the model cannot set. This is the recommended way for SDK integrations.
11
- - **User-authored tools** — named JS-string bodies stored per user and run in-process with a timeout (`helpers.fetch` available). Off by default; enable with `allowUserAuthoredTools` only when you trust the authors. On multi-user hosts, leave off and expose native tools instead.
12
- An agent may chain several tool calls privately before responding.
13
- - **Stories.** Text-based interactive fiction with a narrator, AI-played characters, and a human player. Stories progress through chapters and can introduce new characters mid-game. Story events (state updates, character suggestions, chapter transitions, errors) are delivered through an emitter the host app subscribes to.
14
- - **Text processing.** One-shot `processText` for non-conversational use, with cost and token counts on the result.
15
- - **File attachments.** Attach documents to agents as context. Supported file types vary by LLM provider.
16
- - **Per-user data.** Agents, rooms, stories, attached files, balances, and transactions are scoped to a userId the host controls. Per-user directories keep state isolated.
17
- - **Balances and transactions.** Track per-user balances against usage cost. Record pending, succeeded, failed, or cancelled transactions when integrating with a payment provider, credit balances on webhook confirmation, and resume stories that paused on insufficient funds. Briyah does not process payments itself.
18
- - **Real-time event emitters.** Story-state and balance updates can be forwarded to SSE or websockets.
19
-
20
- State is persisted as JSON files under a configurable data path; no external database is required.
21
-
22
- ## Installation
23
-
24
- ```bash
25
- npm install briyah
26
- ```
27
-
28
- ```typescript
29
- import { Briyah } from 'briyah';
30
- ```
31
-
32
- ## Quick Start
33
-
34
- ```typescript
35
- import { Briyah } from 'briyah';
36
-
37
- // 1. Create and initialize Briyah instance
38
- const briyah = new Briyah({
39
- dataPath: './my-briyah-data',
40
- userServiceCacheTimeoutMinutes: 30,
41
- startingBalance: 10.00
42
- });
43
-
44
- await briyah.init();
45
-
46
- // 2. Get user-specific service (userId managed by your app)
47
- const appService = briyah.getAppService('user-123');
48
-
49
- // 3. Use full Briyah functionality
50
- // createAgent() registers the agent in memory immediately — agent.id is usable right away.
51
- // Call agent.save() when you want to persist it to disk.
52
- const agent = appService.createAgent(
53
- 'Anthropic',
54
- 'AI Assistant',
55
- 'James',
56
- 'A helpful AI assistant',
57
- 'claude-haiku-4-5'
58
- );
59
-
60
- if (!agent.id) throw new Error('Agent creation failed');
61
- const result = await appService.processText(agent.id, 'Hello! How are you?');
62
- console.log(result.result);
63
-
64
- agent.save(); // persist to disk
65
-
66
- // 4. Cleanup when done
67
- await briyah.shutdown();
68
- ```
69
-
70
- ## Configuration
71
-
72
- ### BriyahConfigOptions
73
-
74
- ```typescript
75
- interface BriyahConfigOptions {
76
- /**
77
- * Base directory for Briyah data storage
78
- * Default: './briyah-data' relative to process.cwd()
79
- */
80
- dataPath?: string;
81
-
82
- /**
83
- * Timeout in minutes for cached user services
84
- * Default: 30 minutes
85
- */
86
- userServiceCacheTimeoutMinutes?: number;
87
-
88
- /**
89
- * Starting balance for new users (in dollars)
90
- * Default: value from process.env.STARTING_BALANCE
91
- */
92
- startingBalance?: number;
93
-
94
- /**
95
- * Native tools to register up front (equivalent to calling registerTool
96
- * for each). See Example 8.
97
- */
98
- tools?: NativeToolDefinition[];
99
-
100
- /**
101
- * Allow end users to author and run their own JS-string tools. Native tools
102
- * are unaffected. Leave off for untrusted multi-user hosts. Default: false.
103
- */
104
- allowUserAuthoredTools?: boolean;
105
-
106
- /**
107
- * Override environment variables
108
- * Useful for testing or multi-instance configurations
109
- */
110
- envOverrides?: Record<string, string>;
111
- }
112
- ```
113
-
114
- ### Environment Variables
115
-
116
- **LLM Provider API Keys** (at least one required):
117
- - `ANTHROPIC_API_KEY` - For Claude models
118
- - `OPENAI_API_KEY` - For GPT models
119
- - `GOOGLE_GENAI_API_KEY` - For Google AI (Gemini) models
120
- - `XAI_API_KEY` - For Grok models
121
- - `DEEPSEEK_API_KEY` - For DeepSeek models
122
- - `TOGETHER_API_KEY` - For Together AI models
123
- - `FAL_API_KEY` - For Fal image-generation models
124
-
125
- **Optional:**
126
- - `STARTING_BALANCE` - Starting balance for new users (e.g., "10.00")
127
- - `BRIYAH_DATA_PATH` - Global default data path (overridden by constructor `dataPath`)
128
- - `USER_SERVICE_CACHE_TIMEOUT_MINUTES` - Cache timeout (overridden by constructor option)
129
- - `ALLOW_USER_AUTHORED_TOOLS` - `"true"` to let users author/run their own tools (overridden by the `allowUserAuthoredTools` option). Default off.
130
-
131
- ### Logging
132
-
133
- Briyah writes logs to `{dataPath}/logs/briyah.log` by default. Configure or disable via the `logging` option:
134
-
135
- ```typescript
136
- const briyah = new Briyah({
137
- dataPath: './my-data',
138
- logging: {
139
- enabled: true, // default
140
- logFile: './my-data/logs/app.log', // default: {dataPath}/logs/briyah.log
141
- console: false, // set true to also log to stdout/stderr
142
- level: 'warn', // 'debug' | 'log' | 'warn' | 'error' — default: 'log'
143
- }
144
- });
145
-
146
- // Log to console only (no file):
147
- const briyah = new Briyah({ logging: { console: true, logFile: null } });
148
-
149
- // Disable logging entirely:
150
- const briyah = new Briyah({ logging: { enabled: false } });
151
- ```
152
-
153
- ## API Reference
154
-
155
- ### Briyah Class
156
-
157
- #### constructor(options?: BriyahConfigOptions)
158
-
159
- Creates a new Briyah SDK instance.
160
-
161
- ```typescript
162
- const briyah = new Briyah({
163
- dataPath: './briyah-data',
164
- startingBalance: 10.00
165
- });
166
- ```
167
-
168
- #### async init(): Promise\<void\>
169
-
170
- Initializes the Briyah system. Must be called before using `getAppService()`.
171
-
172
- ```typescript
173
- await briyah.init();
174
- ```
175
-
176
- #### getAppService(userId: string): AppService
177
-
178
- Gets the AppService instance for a specific user. The AppService provides full access to:
179
- - Agent management
180
- - Room conversations
181
- - Story generation
182
- - Text processing
183
- - File attachments
184
-
185
- ```typescript
186
- const appService = briyah.getAppService('user-123');
187
- ```
188
-
189
- **Throws:** Error if `init()` has not been called.
190
-
191
- #### removeUserService(userId: string): void
192
-
193
- Manually removes a user's service from the cache. Useful for:
194
- - Forcing a fresh AppService instance
195
- - Cleaning up when a user logs out
196
-
197
- ```typescript
198
- briyah.removeUserService('user-123');
199
- ```
200
-
201
- #### getCacheStats()
202
-
203
- Returns statistics about cached user services.
204
-
205
- ```typescript
206
- const stats = briyah.getCacheStats();
207
- console.log(`Cached users: ${stats.cachedUsers}`);
208
- ```
209
-
210
- #### async shutdown(): Promise\<void\>
211
-
212
- Shuts down the Briyah system and cleans up resources.
213
-
214
- ```typescript
215
- await briyah.shutdown();
216
- ```
217
-
218
- #### isInitialized(): boolean
219
-
220
- Checks if Briyah has been initialized.
221
-
222
- ```typescript
223
- if (briyah.isInitialized()) {
224
- const appService = briyah.getAppService('user-123');
225
- }
226
- ```
227
-
228
- ### AppService
229
-
230
- The AppService provides full access to Briyah functionality.
231
-
232
- **Common operations:**
233
-
234
- ```typescript
235
- // Agent Management
236
- const agent = appService.createAgent(provider, name, nickname, description, model);
237
- const agents = await appService.listAgents();
238
- await appService.deleteAgent(agentId);
239
- await appService.reloadAgent(agentId); // Clear conversation history (keeps any prior summary)
240
- await appService.compactAgentConversation(agentId); // Summarize history into a single message
241
-
242
- // Room Management
243
- const room = await appService.createRoom(name, goal, agentIds);
244
- const rooms = await appService.listRooms();
245
- await appService.sendRoomMessage(roomId, content, sender, action?);
246
-
247
- // Native tools (recommended for SDK integrations — see Example 8)
248
- briyah.registerTool({ name, description, parameters, handler }); // process-level
249
- briyah.listNativeTools();
250
-
251
- // User-authored (string-code) tools — only when allowUserAuthoredTools is enabled
252
- const tools = await appService.listTools();
253
- const tool = await appService.createTool({ name, description, parameters, code, timeoutMs? });
254
- await appService.updateTool(name, tool);
255
- await appService.deleteTool(name);
256
- const result = await appService.testTool(name, args); // { ok: true, result } | { ok: false, error }
257
-
258
- // Story Management
259
- const story = await appService.createStory(name, idea, userCharacterDesc, otherCharactersDesc, storyModel?);
260
- await appService.progressStory(storyId);
261
-
262
- // Text Processing
263
- const result = await appService.processText(agentId, text);
264
-
265
- // File Attachments
266
- const attachment = await appService.attachDocument(agentId, fileName, fileData);
267
- await appService.deleteAttachedFile(agentId, fileName); // by filename
268
- await appService.deleteAttachedFileById(documentId); // by document ID
269
- ```
270
-
271
- ## Usage Examples
272
-
273
- ### Example 1: Multi-User Setup
274
-
275
- ```typescript
276
- import { Briyah } from 'briyah';
277
-
278
- // Initialize once at application startup
279
- const briyah = new Briyah({
280
- dataPath: './data/briyah',
281
- startingBalance: 10.00
282
- });
283
-
284
- await briyah.init();
285
-
286
- // In your route handler or service
287
- async function handleUserRequest(userId: string, message: string) {
288
- const appService = briyah.getAppService(userId);
289
-
290
- // Each user gets their own isolated AppService
291
- const agents = await appService.listAgents();
292
-
293
- // ... process user request
294
- }
295
-
296
- // Cleanup at application shutdown
297
- process.on('SIGINT', async () => {
298
- await briyah.shutdown();
299
- process.exit(0);
300
- });
301
- ```
302
-
303
- ### Example 2: Custom Data Path
304
-
305
- ```typescript
306
- import { Briyah } from 'briyah';
307
- import path from 'path';
308
-
309
- const briyah = new Briyah({
310
- dataPath: path.join(__dirname, '..', 'user-data', 'briyah'),
311
- userServiceCacheTimeoutMinutes: 60 // 1 hour cache
312
- });
313
-
314
- await briyah.init();
315
- ```
316
-
317
- ### Example 3: Testing Configuration
318
-
319
- ```typescript
320
- import { Briyah } from 'briyah';
321
-
322
- const testBriyah = new Briyah({
323
- dataPath: './test-data',
324
- startingBalance: 100.00,
325
- userServiceCacheTimeoutMinutes: 5,
326
- envOverrides: {
327
- ANTHROPIC_API_KEY: process.env.TEST_ANTHROPIC_KEY,
328
- OPENAI_API_KEY: process.env.TEST_OPENAI_KEY
329
- }
330
- });
331
-
332
- await testBriyah.init();
333
-
334
- // Run tests...
335
-
336
- await testBriyah.shutdown();
337
- ```
338
-
339
- ### Example 4: Agent Creation and Text Processing
340
-
341
- ```typescript
342
- const appService = briyah.getAppService('user-123');
343
-
344
- // Create an agent
345
- const agent = appService.createAgent(
346
- 'Anthropic', // provider
347
- 'AI Assistant', // name
348
- 'James', // nickname
349
- 'A helpful AI assistant', // description
350
- 'claude-haiku-4-5' // model
351
- );
352
-
353
- if (!agent.id) throw new Error('Agent creation failed');
354
- console.log(`Created agent: ${agent.id}`);
355
-
356
- // Process text with the agent
357
- const result = await appService.processText(
358
- agent.id,
359
- 'What is the capital of France?'
360
- );
361
-
362
- console.log(`Response: ${result.result}`);
363
- console.log(`Cost: $${result.totalCost}`);
364
- console.log(`Tokens: ${(result.totalInputTokens ?? 0) + (result.totalOutputTokens ?? 0)}`);
365
- ```
366
-
367
- ### Example 5: Multi-Agent Room Conversation
368
-
369
- ```typescript
370
- const appService = briyah.getAppService('user-123');
371
-
372
- // Create agents
373
- const analyst = appService.createAgent('OpenAI', 'Analyst', 'Analyst', 'Data analyst', 'gpt-4');
374
- const writer = appService.createAgent('Anthropic', 'Writer', 'Writer', 'Content writer', 'claude-haiku-4-5');
375
-
376
- if (!analyst.id || !writer.id) throw new Error('Agent creation failed');
377
-
378
- // Create a room with both agents
379
- const room = await appService.createRoom(
380
- 'Analysis Session',
381
- 'Analyze sales data and produce a written summary',
382
- [analyst.id, writer.id]
383
- );
384
-
385
- // Send a message to start the conversation
386
- await appService.sendRoomMessage(
387
- room.roomId,
388
- 'Please analyze the sales data for Q4',
389
- 'Analyst',
390
- 'speak'
391
- );
392
-
393
- // The agents will automatically respond and interact
394
- // Check room messages to see the conversation
395
- const messages = await appService.getRoomMessages(room.roomId);
396
- console.log(`Messages: ${messages.messages.length}`);
397
- ```
398
-
399
- ### Example 6: Story Message Emitter
400
-
401
- The story message emitter delivers real-time events during gameplay. Subscribe to it after creating the story but before the first player turn, so no events are missed.
402
-
403
- ```typescript
404
- import type {
405
- StoryStateEvent,
406
- StoryIntroduceCharacterEvent,
407
- StoryProgressChapterEvent,
408
- StoryErrorEvent,
409
- } from 'briyah';
410
-
411
- const app = briyah.getAppService('user-123');
412
-
413
- const story = await app.createStory(
414
- 'The Lost Kingdom',
415
- 'A medieval fantasy where ancient ruins hold a terrible secret',
416
- 'A disgraced knight seeking redemption'
417
- );
418
-
419
- const emitter = app.getStoryMessageEmitter(story.id);
420
-
421
- // Fires after every turn with the full updated game state.
422
- emitter.on('story-state', async (event: StoryStateEvent) => {
423
- const { state } = event;
424
- console.log('Latest message:', state.latestRoomMessage?.content);
425
-
426
- // Detect the player's turn by comparing speaker names.
427
- // Do NOT use state.humanPrompt for this — it is a UI display string,
428
- // not a reliable turn indicator.
429
- if (state.currentSpeaker === state.userAgentName) {
430
- const input = await promptPlayer(state.humanPrompt);
431
- await app.respondToStory(story.id, input);
432
- }
433
- });
434
-
435
- // Fires when the narrator wants to introduce a new character.
436
- // The host app should present this to the player before acting.
437
- // Accept by calling introduceCharacterToStory, or decline with declineCharacter.
438
- emitter.on('suggest-introduce-character', async (event: StoryIntroduceCharacterEvent) => {
439
- const accept = await askPlayer(`Add ${event.characterName} to the story?`);
440
- if (accept) {
441
- await app.introduceCharacterToStory(story.id, event.characterName!, '', undefined, true);
442
- } else {
443
- await app.declineCharacter(story.id, event.characterName!);
444
- }
445
- });
446
-
447
- // Fires when the narrator wants to advance to the next chapter.
448
- // Call progressStory to accept. Ignoring the event stays in the current chapter —
449
- // there is no explicit rejection call.
450
- emitter.on('suggest-progress-chapter', async (_event: StoryProgressChapterEvent) => {
451
- const accept = await askPlayer('The narrator suggests ending this chapter. Continue?');
452
- if (accept) {
453
- await app.progressStory(story.id);
454
- }
455
- });
456
-
457
- // Fires on fatal errors during room processing.
458
- // Named 'story-error' rather than 'error' to avoid Node.js throwing when no
459
- // listener is attached.
460
- emitter.on('story-error', (event: StoryErrorEvent) => {
461
- if (event.errorType === 'InsufficientBalanceError') {
462
- console.error('Out of credits:', event.message);
463
- } else {
464
- console.error(`Story error [${event.errorType}]:`, event.message);
465
- }
466
- });
467
- ```
468
-
469
- ### Example 7: Recording Payments and Managing Balance
470
-
471
- Briyah does not process payments itself — your application handles the payment provider interaction. Once a payment is confirmed, use `AppService` to record the transaction, credit the user's balance, and restart any stories that stalled due to insufficient funds.
472
-
473
- ```typescript
474
- const app = briyah.getAppService(userId);
475
-
476
- // --- When your payment provider initiates a charge ---
477
- // Record it as pending so the transaction log stays consistent.
478
- await app.recordTransaction(amount, paymentIntentId, 'pending');
479
-
480
- // --- When your payment provider webhook confirms success ---
481
- await app.updateTransactionStatus(paymentIntentId, 'succeeded');
482
- await app.addBalance(amount);
483
-
484
- // Resume any stories that paused mid-turn due to InsufficientBalanceError.
485
- await app.resumePausedStories();
486
-
487
- // --- When a payment fails or is cancelled ---
488
- await app.updateTransactionStatus(paymentIntentId, 'failed');
489
-
490
- // --- Querying balance and history ---
491
- const balance = app.getBalance();
492
-
493
- const { transactions, total } = await app.getTransactions(50, 0);
494
-
495
- const tx = await app.getTransactionByPaymentId(paymentIntentId);
496
- console.log(tx?.status); // 'pending' | 'succeeded' | 'failed' | 'cancelled'
497
- ```
498
-
499
- To push real-time balance updates to a connected client (e.g. via SSE), subscribe to the balance emitter before crediting the user:
500
-
501
- ```typescript
502
- const emitter = app.getBalanceMessageEmitter(userId);
503
- emitter.on('update', (newBalance: number) => {
504
- // Push newBalance to the client
505
- });
506
- ```
507
-
508
- ### Example 8: Registering Native Tools with Opaque Context
509
-
510
- Native tools are functions you implement in your host code and register once with `briyah.registerTool`. Grant a tool to an agent by adding its name to `agent.toolNames`; the agent then calls it on its own (via the EXECUTE room action) when a conversation needs it, chaining several calls privately before it replies.
511
-
512
- Each call receives a third argument — an **opaque context** you pass to `sendRoomMessage`. Briyah never inspects it; it hands it straight to your handler. Use it for per-interaction data the model must not be able to choose. The declared `parameters` are what the LLM fills in; scoping data (which record, which tenant, a DB handle) belongs in context, so a confused or adversarial agent cannot target data outside the current interaction.
513
-
514
- ```typescript
515
- import { Briyah } from 'briyah';
516
-
517
- const briyah = new Briyah({ dataPath: './data/briyah', startingBalance: 10.00 });
518
- await briyah.init();
519
-
520
- // Register a tool that reads its scope from context, not from the LLM's args.
521
- briyah.registerTool({
522
- name: 'add_note',
523
- description: "Add a note to the record the user currently has open",
524
- parameters: [
525
- { name: 'text', type: 'string', description: 'The note text', required: true }
526
- ],
527
- handler: async (args, helpers, context) => {
528
- const { db, recordId } = context as { db: MyDb; recordId: string };
529
- await db.addNote(recordId, args.text); // recordId comes from context — the LLM cannot set it
530
- return { added: true };
531
- },
532
- timeoutMs: 15000 // optional; default 30s, max 120s
533
- });
534
-
535
- // Grant it to an agent (grants are enforced server-side).
536
- const assistant = app.createAgent('Anthropic', 'Assistant', 'Assistant',
537
- 'A helpful assistant that manages the open record', 'claude-haiku-4-5');
538
- assistant.toolNames = ['add_note'];
539
- assistant.save();
540
-
541
- // When the user acts on record "rec_42", pass that scope as context. Any tool the
542
- // agent calls during the resulting turn receives it; other rooms/interactions are
543
- // unaffected. A log-only 'tool' message records each call (visible when fetching
544
- // messages with includeThoughts=true).
545
- await app.sendRoomMessage(
546
- roomId,
547
- 'Add a note that the client called about renewal.',
548
- 'User',
549
- 'speak',
550
- [],
551
- false,
552
- { db, recordId: 'rec_42' } // opaque context
553
- );
554
- ```
555
-
556
- Because each Briyah `userId` gets its own isolated `AppService`, data directory, and balance, mapping one Briyah user per tenant (customer, workspace, org) gives you tenant isolation and per-tenant billing for free; the opaque context then scopes each call within that tenant.
557
-
558
- Agents can also delegate: an agent may respond with a `commission` action naming other agents, each of which researches independently (using its granted tools, with the same context) and replies with a `deliver`. The commissioner receives all deliverables at once and responds before the conversation continues. No SDK calls are needed for this — it is driven by the agents themselves.
559
-
560
- User-authored (string-code) tools remain available via `createTool`/`updateTool`/`testTool` when `allowUserAuthoredTools` is enabled, for trusted single-user setups.
561
-
562
- ## Data Storage
563
-
564
- Briyah stores data in the following structure:
565
-
566
- ```
567
- {dataPath}/
568
- ├── common/ # Shared across all users
569
- │ ├── config/ # LLM pricing and image-model config
570
- │ ├── prompts/ # Global prompt templates
571
- │ └── published-agents.json # Published agent mappings
572
- └── user/
573
- └── {userId}/ # Per-user data
574
- ├── agents/ # Agent configs and histories (one JSON per agent)
575
- ├── rooms/ # Room metadata, message logs, artifacts (one folder per room)
576
- ├── stories/ # Story state
577
- ├── tools/ # User-defined tools (one JSON per tool)
578
- ├── prompts/ # User-specific prompts
579
- ├── upload/ # User file attachments
580
- ├── transactions/ # Transaction records
581
- └── userconfig/ # User preferences and balance
582
- ```
583
-
584
- ## Multi-Instance Support
585
-
586
- You can create multiple Briyah instances with different configurations:
587
-
588
- ```typescript
589
- const briyah1 = new Briyah({ dataPath: './data1' });
590
- const briyah2 = new Briyah({ dataPath: './data2' });
591
-
592
- await briyah1.init();
593
- await briyah2.init();
594
-
595
- // Each instance has isolated data
596
- const user1Service = briyah1.getAppService('user-123');
597
- const user2Service = briyah2.getAppService('user-123');
598
- // These are completely separate services with different data paths
599
- ```
600
-
601
- **Note:** Singleton services (LLM providers, message emitters) are shared across all Briyah instances within the same process. This is safe because they are stateless or keyed by ID.
602
-
603
- ## Troubleshooting
604
-
605
- ### "Must call init() before getAppService()"
606
-
607
- Make sure to call `await briyah.init()` before calling `getAppService()`.
608
-
609
- ### "No LLM provider API keys configured"
610
-
611
- Set at least one of the required API key environment variables (ANTHROPIC_API_KEY, OPENAI_API_KEY, etc.).
612
-
613
- ### "STARTING_BALANCE environment variable is required"
614
-
615
- Set the `STARTING_BALANCE` environment variable or pass `startingBalance` in the constructor options.
616
-
617
- ### Cache not working as expected
618
-
619
- Check the cache statistics with `getCacheStats()` and adjust `userServiceCacheTimeoutMinutes` in the constructor options.
1
+ # Briyah SDK
2
+
3
+ Briyah is an SDK for AI agents, multi-agent rooms, and interactive stories. It wraps the Briyah runtime as a single class with per-user data isolation and balance tracking, and supports Anthropic, OpenAI, Google, Grok, DeepSeek, Together, and Fal as LLM providers.
4
+
5
+ What's in the package:
6
+
7
+ - **Agents.** AI agents with a system prompt, persistent conversation history, attached documents, and per-call cost and token tracking. Histories can be summarized/compacted or cleared.
8
+ - **Rooms.** Multi-agent conversations with a shared goal. Agents exchange messages at different visibility levels (speak, whisper, think, shout), publish shared artifacts, run tools, commission each other for parallel research, and a moderator can route turns.
9
+ - **Tools.** Functions agents can call from a room, granted per agent. Two kinds:
10
+ - **Native tools** — real functions you register in your host code with `briyah.registerTool` (see [Example 8](#example-8-registering-native-tools-with-opaque-context)). They have full access to your imports, database, and filesystem, and receive an **opaque per-invocation context** you supply — use it to scope a call to trusted data the model cannot set. This is the recommended way for SDK integrations.
11
+ - **User-authored tools** — named JS-string bodies stored per user and run in-process with a timeout (`helpers.fetch` available). Off by default; enable with `allowUserAuthoredTools` only when you trust the authors. On multi-user hosts, leave off and expose native tools instead.
12
+ An agent may chain several tool calls privately before responding.
13
+ - **Stories.** Text-based interactive fiction with a narrator, AI-played characters, and a human player. Stories progress through chapters and can introduce new characters mid-game. Story events (state updates, character suggestions, chapter transitions, errors) are delivered through an emitter the host app subscribes to.
14
+ - **Text processing.** One-shot `processText` for non-conversational use, with cost and token counts on the result.
15
+ - **File attachments.** Attach documents to agents as context. Supported file types vary by LLM provider.
16
+ - **Per-user data.** Agents, rooms, stories, attached files, balances, and transactions are scoped to a userId the host controls. Per-user directories keep state isolated.
17
+ - **Balances and transactions.** Track per-user balances against usage cost. Record pending, succeeded, failed, or cancelled transactions when integrating with a payment provider, credit balances on webhook confirmation, and resume stories that paused on insufficient funds. Briyah does not process payments itself.
18
+ - **Real-time event emitters.** Story-state and balance updates can be forwarded to SSE or websockets.
19
+
20
+ State is persisted as JSON files under a configurable data path; no external database is required.
21
+
22
+ ## Installation
23
+
24
+ ```bash
25
+ npm install briyah
26
+ ```
27
+
28
+ ```typescript
29
+ import { Briyah } from 'briyah';
30
+ ```
31
+
32
+ ## Quick Start
33
+
34
+ ```typescript
35
+ import { Briyah } from 'briyah';
36
+
37
+ // 1. Create and initialize Briyah instance
38
+ const briyah = new Briyah({
39
+ dataPath: './my-briyah-data',
40
+ userServiceCacheTimeoutMinutes: 30,
41
+ startingBalance: 10.00
42
+ });
43
+
44
+ await briyah.init();
45
+
46
+ // 2. Get user-specific service (userId managed by your app)
47
+ const appService = briyah.getAppService('user-123');
48
+
49
+ // 3. Use full Briyah functionality
50
+ // createAgent() registers the agent in memory immediately — agent.id is usable right away.
51
+ // Call agent.save() when you want to persist it to disk.
52
+ const agent = appService.createAgent(
53
+ 'Anthropic',
54
+ 'AI Assistant',
55
+ 'James',
56
+ 'A helpful AI assistant',
57
+ 'claude-haiku-4-5'
58
+ );
59
+
60
+ if (!agent.id) throw new Error('Agent creation failed');
61
+ const result = await appService.processText(agent.id, 'Hello! How are you?');
62
+ console.log(result.result);
63
+
64
+ agent.save(); // persist to disk
65
+
66
+ // 4. Cleanup when done
67
+ await briyah.shutdown();
68
+ ```
69
+
70
+ ## Configuration
71
+
72
+ ### BriyahConfigOptions
73
+
74
+ ```typescript
75
+ interface BriyahConfigOptions {
76
+ /**
77
+ * Base directory for Briyah data storage
78
+ * Default: './briyah-data' relative to process.cwd()
79
+ */
80
+ dataPath?: string;
81
+
82
+ /**
83
+ * Timeout in minutes for cached user services
84
+ * Default: 30 minutes
85
+ */
86
+ userServiceCacheTimeoutMinutes?: number;
87
+
88
+ /**
89
+ * Starting balance for new users (in dollars)
90
+ * Default: value from process.env.STARTING_BALANCE
91
+ */
92
+ startingBalance?: number;
93
+
94
+ /**
95
+ * Native tools to register up front (equivalent to calling registerTool
96
+ * for each). See Example 8.
97
+ */
98
+ tools?: NativeToolDefinition[];
99
+
100
+ /**
101
+ * Allow end users to author and run their own JS-string tools. Native tools
102
+ * are unaffected. Leave off for untrusted multi-user hosts. Default: false.
103
+ */
104
+ allowUserAuthoredTools?: boolean;
105
+
106
+ /**
107
+ * Override environment variables
108
+ * Useful for testing or multi-instance configurations
109
+ */
110
+ envOverrides?: Record<string, string>;
111
+ }
112
+ ```
113
+
114
+ ### Environment Variables
115
+
116
+ **LLM Provider API Keys** (at least one required):
117
+ - `ANTHROPIC_API_KEY` - For Claude models
118
+ - `OPENAI_API_KEY` - For GPT models
119
+ - `GOOGLE_GENAI_API_KEY` - For Google AI (Gemini) models
120
+ - `XAI_API_KEY` - For Grok models
121
+ - `DEEPSEEK_API_KEY` - For DeepSeek models
122
+ - `TOGETHER_API_KEY` - For Together AI models
123
+ - `FAL_API_KEY` - For Fal image-generation models
124
+
125
+ **Self-hosted providers** (optional, count toward the "at least one" requirement):
126
+ - `SELF_HOSTED_BASE_URL` - OpenAI-compatible inference server for the `SelfHosted` text provider (vLLM, Ollama, llama.cpp, LM Studio). Must include the `/v1` path, e.g. `http://gpu-box:8000/v1`
127
+ - `SELF_HOSTED_API_KEY` - Optional bearer token for the above
128
+ - `COMFYUI_BASE_URL` - ComfyUI server for the `ComfyUI` image provider, no trailing slash, e.g. `http://gpu-box:8188` (see Example 9)
129
+ - `COMFYUI_EXTRA_HEADERS` - Optional JSON object of headers sent on every ComfyUI request, e.g. `{"Authorization":"Basic ..."}` for a reverse proxy
130
+ - `COMFYUI_TIMEOUT_MS` - Total wait for a queued generation, default `600000` (covers queue wait and model cold start)
131
+ - `COMFYUI_POLL_INTERVAL_MS` - Poll interval while waiting, default `2000`
132
+
133
+ **Optional:**
134
+ - `STARTING_BALANCE` - Starting balance for new users (e.g., "10.00")
135
+ - `BRIYAH_DATA_PATH` - Global default data path (overridden by constructor `dataPath`)
136
+ - `USER_SERVICE_CACHE_TIMEOUT_MINUTES` - Cache timeout (overridden by constructor option)
137
+ - `ALLOW_USER_AUTHORED_TOOLS` - `"true"` to let users author/run their own tools (overridden by the `allowUserAuthoredTools` option). Default off.
138
+
139
+ ### Logging
140
+
141
+ Briyah writes logs to `{dataPath}/logs/briyah.log` by default. Configure or disable via the `logging` option:
142
+
143
+ ```typescript
144
+ const briyah = new Briyah({
145
+ dataPath: './my-data',
146
+ logging: {
147
+ enabled: true, // default
148
+ logFile: './my-data/logs/app.log', // default: {dataPath}/logs/briyah.log
149
+ console: false, // set true to also log to stdout/stderr
150
+ level: 'warn', // 'debug' | 'log' | 'warn' | 'error' — default: 'log'
151
+ }
152
+ });
153
+
154
+ // Log to console only (no file):
155
+ const briyah = new Briyah({ logging: { console: true, logFile: null } });
156
+
157
+ // Disable logging entirely:
158
+ const briyah = new Briyah({ logging: { enabled: false } });
159
+ ```
160
+
161
+ ## API Reference
162
+
163
+ ### Briyah Class
164
+
165
+ #### constructor(options?: BriyahConfigOptions)
166
+
167
+ Creates a new Briyah SDK instance.
168
+
169
+ ```typescript
170
+ const briyah = new Briyah({
171
+ dataPath: './briyah-data',
172
+ startingBalance: 10.00
173
+ });
174
+ ```
175
+
176
+ #### async init(): Promise\<void\>
177
+
178
+ Initializes the Briyah system. Must be called before using `getAppService()`.
179
+
180
+ ```typescript
181
+ await briyah.init();
182
+ ```
183
+
184
+ #### getAppService(userId: string): AppService
185
+
186
+ Gets the AppService instance for a specific user. The AppService provides full access to:
187
+ - Agent management
188
+ - Room conversations
189
+ - Story generation
190
+ - Text processing
191
+ - File attachments
192
+
193
+ ```typescript
194
+ const appService = briyah.getAppService('user-123');
195
+ ```
196
+
197
+ **Throws:** Error if `init()` has not been called.
198
+
199
+ #### removeUserService(userId: string): void
200
+
201
+ Manually removes a user's service from the cache. Useful for:
202
+ - Forcing a fresh AppService instance
203
+ - Cleaning up when a user logs out
204
+
205
+ ```typescript
206
+ briyah.removeUserService('user-123');
207
+ ```
208
+
209
+ #### getCacheStats()
210
+
211
+ Returns statistics about cached user services.
212
+
213
+ ```typescript
214
+ const stats = briyah.getCacheStats();
215
+ console.log(`Cached users: ${stats.cachedUsers}`);
216
+ ```
217
+
218
+ #### async shutdown(): Promise\<void\>
219
+
220
+ Shuts down the Briyah system and cleans up resources.
221
+
222
+ ```typescript
223
+ await briyah.shutdown();
224
+ ```
225
+
226
+ #### isInitialized(): boolean
227
+
228
+ Checks if Briyah has been initialized.
229
+
230
+ ```typescript
231
+ if (briyah.isInitialized()) {
232
+ const appService = briyah.getAppService('user-123');
233
+ }
234
+ ```
235
+
236
+ ### AppService
237
+
238
+ The AppService provides full access to Briyah functionality.
239
+
240
+ **Common operations:**
241
+
242
+ ```typescript
243
+ // Agent Management
244
+ const agent = appService.createAgent(provider, name, nickname, description, model);
245
+ const agents = await appService.listAgents();
246
+ await appService.deleteAgent(agentId);
247
+ await appService.reloadAgent(agentId); // Clear conversation history (keeps any prior summary)
248
+ await appService.compactAgentConversation(agentId); // Summarize history into a single message
249
+
250
+ // Room Management
251
+ const room = await appService.createRoom(name, goal, agentIds);
252
+ const rooms = await appService.listRooms();
253
+ await appService.sendRoomMessage(roomId, content, sender, action?);
254
+
255
+ // Agents that belong to a room: created inside it, named after it, deleted with it,
256
+ // and left out of listAgents(). agentName is the bare name; the room's is prefixed on.
257
+ await appService.createRoomAgent(roomId, { aiServiceName, agentName, description, aiModel, promptName });
258
+ await appService.removeRoomAgent(roomId, agentId);
259
+
260
+ // Native tools (recommended for SDK integrations — see Example 8)
261
+ briyah.registerTool({ name, description, parameters, handler }); // process-level
262
+ briyah.listNativeTools();
263
+
264
+ // User-authored (string-code) tools — only when allowUserAuthoredTools is enabled
265
+ const tools = await appService.listTools();
266
+ const tool = await appService.createTool({ name, description, parameters, code, timeoutMs? });
267
+ await appService.updateTool(name, tool);
268
+ await appService.deleteTool(name);
269
+ const result = await appService.testTool(name, args); // { ok: true, result } | { ok: false, error }
270
+
271
+ // Story Management
272
+ const story = await appService.createStory(name, idea, userCharacterDesc, otherCharactersDesc, storyModel?);
273
+ await appService.progressStory(storyId);
274
+
275
+ // Text Processing
276
+ const result = await appService.processText(agentId, text);
277
+
278
+ // Image Generation (image-capable providers; called on the Agent object — see Example 9)
279
+ const { artifactId } = await agent.generateImage(prompt, imageProperties);
280
+ const edited = await agent.editImage(prompt, imageProperties, referenceArtifactIds);
281
+
282
+ // File Attachments
283
+ const attachment = await appService.attachDocument(agentId, fileName, fileData);
284
+ await appService.deleteAttachedFile(agentId, fileName); // by filename
285
+ await appService.deleteAttachedFileById(documentId); // by document ID
286
+ ```
287
+
288
+ ## Usage Examples
289
+
290
+ ### Example 1: Multi-User Setup
291
+
292
+ ```typescript
293
+ import { Briyah } from 'briyah';
294
+
295
+ // Initialize once at application startup
296
+ const briyah = new Briyah({
297
+ dataPath: './data/briyah',
298
+ startingBalance: 10.00
299
+ });
300
+
301
+ await briyah.init();
302
+
303
+ // In your route handler or service
304
+ async function handleUserRequest(userId: string, message: string) {
305
+ const appService = briyah.getAppService(userId);
306
+
307
+ // Each user gets their own isolated AppService
308
+ const agents = await appService.listAgents();
309
+
310
+ // ... process user request
311
+ }
312
+
313
+ // Cleanup at application shutdown
314
+ process.on('SIGINT', async () => {
315
+ await briyah.shutdown();
316
+ process.exit(0);
317
+ });
318
+ ```
319
+
320
+ ### Example 2: Custom Data Path
321
+
322
+ ```typescript
323
+ import { Briyah } from 'briyah';
324
+ import path from 'path';
325
+
326
+ const briyah = new Briyah({
327
+ dataPath: path.join(__dirname, '..', 'user-data', 'briyah'),
328
+ userServiceCacheTimeoutMinutes: 60 // 1 hour cache
329
+ });
330
+
331
+ await briyah.init();
332
+ ```
333
+
334
+ ### Example 3: Testing Configuration
335
+
336
+ ```typescript
337
+ import { Briyah } from 'briyah';
338
+
339
+ const testBriyah = new Briyah({
340
+ dataPath: './test-data',
341
+ startingBalance: 100.00,
342
+ userServiceCacheTimeoutMinutes: 5,
343
+ envOverrides: {
344
+ ANTHROPIC_API_KEY: process.env.TEST_ANTHROPIC_KEY,
345
+ OPENAI_API_KEY: process.env.TEST_OPENAI_KEY
346
+ }
347
+ });
348
+
349
+ await testBriyah.init();
350
+
351
+ // Run tests...
352
+
353
+ await testBriyah.shutdown();
354
+ ```
355
+
356
+ ### Example 4: Agent Creation and Text Processing
357
+
358
+ ```typescript
359
+ const appService = briyah.getAppService('user-123');
360
+
361
+ // Create an agent
362
+ const agent = appService.createAgent(
363
+ 'Anthropic', // provider
364
+ 'AI Assistant', // name
365
+ 'James', // nickname
366
+ 'A helpful AI assistant', // description
367
+ 'claude-haiku-4-5' // model
368
+ );
369
+
370
+ if (!agent.id) throw new Error('Agent creation failed');
371
+ console.log(`Created agent: ${agent.id}`);
372
+
373
+ // Process text with the agent
374
+ const result = await appService.processText(
375
+ agent.id,
376
+ 'What is the capital of France?'
377
+ );
378
+
379
+ console.log(`Response: ${result.result}`);
380
+ console.log(`Cost: $${result.totalCost}`);
381
+ console.log(`Tokens: ${(result.totalInputTokens ?? 0) + (result.totalOutputTokens ?? 0)}`);
382
+ ```
383
+
384
+ ### Example 5: Multi-Agent Room Conversation
385
+
386
+ ```typescript
387
+ const appService = briyah.getAppService('user-123');
388
+
389
+ // Create agents
390
+ const analyst = appService.createAgent('OpenAI', 'Analyst', 'Analyst', 'Data analyst', 'gpt-4');
391
+ const writer = appService.createAgent('Anthropic', 'Writer', 'Writer', 'Content writer', 'claude-haiku-4-5');
392
+
393
+ if (!analyst.id || !writer.id) throw new Error('Agent creation failed');
394
+
395
+ // Create a room with both agents
396
+ const room = await appService.createRoom(
397
+ 'Analysis Session',
398
+ 'Analyze sales data and produce a written summary',
399
+ [analyst.id, writer.id]
400
+ );
401
+
402
+ // Send a message to start the conversation
403
+ await appService.sendRoomMessage(
404
+ room.roomId,
405
+ 'Please analyze the sales data for Q4',
406
+ 'Analyst',
407
+ 'speak'
408
+ );
409
+
410
+ // The agents will automatically respond and interact
411
+ // Check room messages to see the conversation
412
+ const messages = await appService.getRoomMessages(room.roomId);
413
+ console.log(`Messages: ${messages.messages.length}`);
414
+ ```
415
+
416
+ ### Example 6: Story Message Emitter
417
+
418
+ The story message emitter delivers real-time events during gameplay. Subscribe to it after creating the story but before the first player turn, so no events are missed.
419
+
420
+ ```typescript
421
+ import type {
422
+ StoryStateEvent,
423
+ StoryIntroduceCharacterEvent,
424
+ StoryProgressChapterEvent,
425
+ StoryErrorEvent,
426
+ } from 'briyah';
427
+
428
+ const app = briyah.getAppService('user-123');
429
+
430
+ const story = await app.createStory(
431
+ 'The Lost Kingdom',
432
+ 'A medieval fantasy where ancient ruins hold a terrible secret',
433
+ 'A disgraced knight seeking redemption'
434
+ );
435
+
436
+ const emitter = app.getStoryMessageEmitter(story.id);
437
+
438
+ // Fires after every turn with the full updated game state.
439
+ emitter.on('story-state', async (event: StoryStateEvent) => {
440
+ const { state } = event;
441
+ console.log('Latest message:', state.latestRoomMessage?.content);
442
+
443
+ // Detect the player's turn by comparing speaker names.
444
+ // Do NOT use state.humanPrompt for this — it is a UI display string,
445
+ // not a reliable turn indicator.
446
+ if (state.currentSpeaker === state.userAgentName) {
447
+ const input = await promptPlayer(state.humanPrompt);
448
+ await app.respondToStory(story.id, input);
449
+ }
450
+ });
451
+
452
+ // Fires when the narrator wants to introduce a new character.
453
+ // The host app should present this to the player before acting.
454
+ // Accept by calling introduceCharacterToStory, or decline with declineCharacter.
455
+ emitter.on('suggest-introduce-character', async (event: StoryIntroduceCharacterEvent) => {
456
+ const accept = await askPlayer(`Add ${event.characterName} to the story?`);
457
+ if (accept) {
458
+ await app.introduceCharacterToStory(story.id, event.characterName!, '', undefined, true);
459
+ } else {
460
+ await app.declineCharacter(story.id, event.characterName!);
461
+ }
462
+ });
463
+
464
+ // Fires when the narrator wants to advance to the next chapter.
465
+ // Call progressStory to accept. Ignoring the event stays in the current chapter —
466
+ // there is no explicit rejection call.
467
+ emitter.on('suggest-progress-chapter', async (_event: StoryProgressChapterEvent) => {
468
+ const accept = await askPlayer('The narrator suggests ending this chapter. Continue?');
469
+ if (accept) {
470
+ await app.progressStory(story.id);
471
+ }
472
+ });
473
+
474
+ // Fires on fatal errors during room processing.
475
+ // Named 'story-error' rather than 'error' to avoid Node.js throwing when no
476
+ // listener is attached.
477
+ emitter.on('story-error', (event: StoryErrorEvent) => {
478
+ if (event.errorType === 'InsufficientBalanceError') {
479
+ console.error('Out of credits:', event.message);
480
+ } else {
481
+ console.error(`Story error [${event.errorType}]:`, event.message);
482
+ }
483
+ });
484
+ ```
485
+
486
+ ### Example 7: Recording Payments and Managing Balance
487
+
488
+ Briyah does not process payments itself — your application handles the payment provider interaction. Once a payment is confirmed, use `AppService` to record the transaction, credit the user's balance, and restart any stories that stalled due to insufficient funds.
489
+
490
+ ```typescript
491
+ const app = briyah.getAppService(userId);
492
+
493
+ // --- When your payment provider initiates a charge ---
494
+ // Record it as pending so the transaction log stays consistent.
495
+ await app.recordTransaction(amount, paymentIntentId, 'pending');
496
+
497
+ // --- When your payment provider webhook confirms success ---
498
+ await app.updateTransactionStatus(paymentIntentId, 'succeeded');
499
+ await app.addBalance(amount);
500
+
501
+ // Resume any stories that paused mid-turn due to InsufficientBalanceError.
502
+ await app.resumePausedStories();
503
+
504
+ // --- When a payment fails or is cancelled ---
505
+ await app.updateTransactionStatus(paymentIntentId, 'failed');
506
+
507
+ // --- Querying balance and history ---
508
+ const balance = app.getBalance();
509
+
510
+ const { transactions, total } = await app.getTransactions(50, 0);
511
+
512
+ const tx = await app.getTransactionByPaymentId(paymentIntentId);
513
+ console.log(tx?.status); // 'pending' | 'succeeded' | 'failed' | 'cancelled'
514
+ ```
515
+
516
+ To push real-time balance updates to a connected client (e.g. via SSE), subscribe to the balance emitter before crediting the user:
517
+
518
+ ```typescript
519
+ const emitter = app.getBalanceMessageEmitter(userId);
520
+ emitter.on('update', (newBalance: number) => {
521
+ // Push newBalance to the client
522
+ });
523
+ ```
524
+
525
+ ### Example 8: Registering Native Tools with Opaque Context
526
+
527
+ Native tools are functions you implement in your host code and register once with `briyah.registerTool`. Grant a tool to an agent by adding its name to `agent.toolNames`; the agent then calls it on its own (via the EXECUTE room action) when a conversation needs it, chaining several calls privately before it replies.
528
+
529
+ Each call receives a third argument — an **opaque context** you pass to `sendRoomMessage`. Briyah never inspects it; it hands it straight to your handler. Use it for per-interaction data the model must not be able to choose. The declared `parameters` are what the LLM fills in; scoping data (which record, which tenant, a DB handle) belongs in context, so a confused or adversarial agent cannot target data outside the current interaction.
530
+
531
+ ```typescript
532
+ import { Briyah } from 'briyah';
533
+
534
+ const briyah = new Briyah({ dataPath: './data/briyah', startingBalance: 10.00 });
535
+ await briyah.init();
536
+
537
+ // Register a tool that reads its scope from context, not from the LLM's args.
538
+ briyah.registerTool({
539
+ name: 'add_note',
540
+ description: "Add a note to the record the user currently has open",
541
+ parameters: [
542
+ { name: 'text', type: 'string', description: 'The note text', required: true }
543
+ ],
544
+ handler: async (args, helpers, context) => {
545
+ const { db, recordId } = context as { db: MyDb; recordId: string };
546
+ await db.addNote(recordId, args.text); // recordId comes from context — the LLM cannot set it
547
+ return { added: true };
548
+ },
549
+ timeoutMs: 15000 // optional; default 30s, max 120s
550
+ });
551
+
552
+ // Grant it to an agent (grants are enforced server-side).
553
+ const assistant = app.createAgent('Anthropic', 'Assistant', 'Assistant',
554
+ 'A helpful assistant that manages the open record', 'claude-haiku-4-5');
555
+ assistant.toolNames = ['add_note'];
556
+ assistant.save();
557
+
558
+ // When the user acts on record "rec_42", pass that scope as context. Any tool the
559
+ // agent calls during the resulting turn receives it; other rooms/interactions are
560
+ // unaffected. A log-only 'tool' message records each call (visible when fetching
561
+ // messages with includeThoughts=true).
562
+ await app.sendRoomMessage(
563
+ roomId,
564
+ 'Add a note that the client called about renewal.',
565
+ 'User',
566
+ 'speak',
567
+ [],
568
+ false,
569
+ { db, recordId: 'rec_42' } // opaque context
570
+ );
571
+ ```
572
+
573
+ Because each Briyah `userId` gets its own isolated `AppService`, data directory, and balance, mapping one Briyah user per tenant (customer, workspace, org) gives you tenant isolation and per-tenant billing for free; the opaque context then scopes each call within that tenant.
574
+
575
+ Agents can also delegate: an agent may respond with a `commission` action naming other agents, each of which researches independently (using its granted tools, with the same context) and replies with a `deliver`. The commissioner receives all deliverables at once and responds before the conversation continues. No SDK calls are needed for this — it is driven by the agents themselves.
576
+
577
+ User-authored (string-code) tools remain available via `createTool`/`updateTool`/`testTool` when `allowUserAuthoredTools` is enabled, for trusted single-user setups.
578
+
579
+ ### Example 9: Self-Hosted Image Generation with ComfyUI
580
+
581
+ The `ComfyUI` provider generates images on a self-hosted [ComfyUI](https://github.com/comfyanonymous/ComfyUI) server. It is image-only: `generateImage`/`editImage` work, `textPrompt` throws. Set `COMFYUI_BASE_URL` to enable it. ComfyUI has no authentication of its own — keep it on a LAN/VPN or behind an authenticated reverse proxy (pass proxy credentials via `COMFYUI_EXTRA_HEADERS`).
582
+
583
+ For this provider the agent's *model name* selects a **workflow-template pair**, not a checkpoint. Two pairs ship by default:
584
+
585
+ | Pair name | Model | Files required on the ComfyUI server |
586
+ |---|---|---|
587
+ | `flux2-dev` | FLUX.2 dev (FP8 mixed) | `diffusion_models/flux2_dev_fp8mixed.safetensors`, `text_encoders/mistral_3_small_flux2_bf16.safetensors`, `vae/flux2-vae.safetensors` |
588
+ | `flux-kontext` | Flux.1 Kontext dev (FP8) | `diffusion_models/flux1-dev-kontext_fp8_scaled.safetensors`, `text_encoders/clip_l.safetensors` + `t5xxl_fp8_e4m3fn_scaled.safetensors`, `vae/ae.safetensors` |
589
+
590
+ `flux2-dev` has substantially better multi-reference character consistency and wants a 32 GB-class GPU; `flux-kontext` runs on 16 GB-class cards.
591
+
592
+ ```typescript
593
+ import { Briyah } from 'briyah';
594
+
595
+ const briyah = new Briyah({ dataPath: './data/briyah', startingBalance: 10.00 });
596
+ await briyah.init();
597
+
598
+ const app = briyah.getAppService('user-123');
599
+
600
+ // Model name = workflow pair name
601
+ const artist = app.createAgent('ComfyUI', 'Artist', 'Artist',
602
+ 'Image generation agent', 'flux2-dev');
603
+
604
+ // Text-to-image. Resolves to { artifactId } on success or { error } on failure.
605
+ const generated = await artist.generateImage(
606
+ 'A lighthouse on a rocky coast at dusk',
607
+ { width: 1024, height: 1024 } // optional; a fixed seed may also be passed
608
+ );
609
+ if (generated.error) throw new Error(String(generated.error));
610
+
611
+ // Generated images are stored as artifacts (PNG)
612
+ const png = artist.artifactService.getArtifact(generated.artifactId);
613
+
614
+ // Image-to-image with reference images. Each referenced artifact is uploaded
615
+ // and conditioned on separately (chained ReferenceLatent nodes). Order is
616
+ // preserved, so the prompt can refer to "Image 1", "Image 2", ...
617
+ const edited = await artist.editImage(
618
+ 'The character from Image 2 stands in the setting from Image 1',
619
+ { width: 1024, height: 1024 },
620
+ [sceneArtifactId, portraitArtifactId]
621
+ );
622
+ ```
623
+
624
+ Notes:
625
+
626
+ - **Cost**: generation is free by default — no balance is checked or decremented. To charge users, pass `centsPerImage` in the image properties; the balance gate then applies.
627
+ - **Latency**: the GPU processes one job at a time and the first generation after server start loads the model weights. `COMFYUI_TIMEOUT_MS` (default 10 minutes) covers queue wait plus cold start.
628
+ - **Stories**: to make a pair selectable in the story UI's image-model dropdown, add an entry to `{dataPath}/common/config/image_models.json` with `"service": "ComfyUI"` and the pair name as `"model"` in the `generation` and `editing` blocks, with `"centsPerImage": 0`.
629
+
630
+ **Custom workflows.** Any ComfyUI workflow can be used: build it in the ComfyUI web UI, run it once, then use Export (API format) and replace the values you want parameterized with tokens — `{{prompt}}` (may be embedded in a longer string), `{{seed}}`, `{{width}}`, `{{height}}` (replaced as numbers), and `{{ref_image}}` (edit workflows, the `LoadImage` input). Save the files as `{name}.t2i.json` (used by `generateImage`) and `{name}.edit.json` (used by `editImage`) in `{dataPath}/common/config/comfyui-workflows/`, or in `{dataPath}/user/{userId}/comfyui-workflows/` for a per-user override (checked first). The pair name becomes the model name. For multi-reference support, an edit workflow must contain exactly one `ReferenceLatent` node fed by a `VAEEncode` fed by a `LoadImage`; extra references are added at request time by cloning that chain.
631
+
632
+ ## Data Storage
633
+
634
+ Briyah stores data in the following structure:
635
+
636
+ ```
637
+ {dataPath}/
638
+ ├── common/ # Shared across all users
639
+ │ ├── config/ # LLM pricing and image-model config
640
+ │ ├── prompts/ # Global prompt templates
641
+ │ └── published-agents.json # Published agent mappings
642
+ └── user/
643
+ └── {userId}/ # Per-user data
644
+ ├── agents/ # Agent configs and histories (one JSON per agent)
645
+ ├── rooms/ # Room metadata, message logs, artifacts (one folder per room)
646
+ ├── stories/ # Story state
647
+ ├── tools/ # User-defined tools (one JSON per tool)
648
+ ├── prompts/ # User-specific prompts
649
+ ├── upload/ # User file attachments
650
+ ├── transactions/ # Transaction records
651
+ └── userconfig/ # User preferences and balance
652
+ ```
653
+
654
+ ## Multi-Instance Support
655
+
656
+ You can create multiple Briyah instances with different configurations:
657
+
658
+ ```typescript
659
+ const briyah1 = new Briyah({ dataPath: './data1' });
660
+ const briyah2 = new Briyah({ dataPath: './data2' });
661
+
662
+ await briyah1.init();
663
+ await briyah2.init();
664
+
665
+ // Each instance has isolated data
666
+ const user1Service = briyah1.getAppService('user-123');
667
+ const user2Service = briyah2.getAppService('user-123');
668
+ // These are completely separate services with different data paths
669
+ ```
670
+
671
+ **Note:** Singleton services (LLM providers, message emitters) are shared across all Briyah instances within the same process. This is safe because they are stateless or keyed by ID.
672
+
673
+ ## Troubleshooting
674
+
675
+ ### "Must call init() before getAppService()"
676
+
677
+ Make sure to call `await briyah.init()` before calling `getAppService()`.
678
+
679
+ ### "No LLM provider API keys configured"
680
+
681
+ Set at least one of the required API key environment variables (ANTHROPIC_API_KEY, OPENAI_API_KEY, etc.).
682
+
683
+ ### "STARTING_BALANCE environment variable is required"
684
+
685
+ Set the `STARTING_BALANCE` environment variable or pass `startingBalance` in the constructor options.
686
+
687
+ ### Cache not working as expected
688
+
689
+ Check the cache statistics with `getCacheStats()` and adjust `userServiceCacheTimeoutMinutes` in the constructor options.