briyah 1.3.5 → 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 (238) hide show
  1. package/README.md +689 -684
  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/markup +1 -1
  19. package/data/common/config/model_prices.json +1250 -237
  20. package/data/common/prompts/campaign_designer/defaults_config.json +16 -0
  21. package/data/common/prompts/campaign_designer/perceive.json +29 -0
  22. package/data/common/prompts/campaign_designer/perceive.prompt +345 -0
  23. package/data/common/prompts/campaign_designer/system_instruction.prompt +0 -0
  24. package/data/common/prompts/character_creator/defaults_config.json +31 -0
  25. package/data/common/prompts/character_creator/perceive.json +29 -0
  26. package/data/common/prompts/character_creator/perceive.prompt +621 -0
  27. package/data/common/prompts/character_creator/system_instruction.prompt +0 -0
  28. package/data/common/prompts/dnd_player/defaults_config.json +5 -0
  29. package/data/common/prompts/dnd_player/perceive.json +29 -0
  30. package/data/common/prompts/dnd_player/perceive.prompt +312 -0
  31. package/data/common/prompts/dnd_player/system_instruction.prompt +0 -0
  32. package/data/common/prompts/dnd_room_moderator/defaults_config.json +9 -0
  33. package/data/common/prompts/dnd_room_moderator/moderate.json +34 -0
  34. package/data/common/prompts/dnd_room_moderator/moderate.prompt +291 -0
  35. package/data/common/prompts/dnd_room_moderator/system_instruction.prompt +0 -0
  36. package/data/common/prompts/dungeon_master/compact_agent.prompt +24 -0
  37. package/data/common/prompts/dungeon_master/defaults_config.json +29 -0
  38. package/data/common/prompts/dungeon_master/perceive.json +33 -0
  39. package/data/common/prompts/dungeon_master/perceive.prompt +757 -0
  40. package/data/common/prompts/dungeon_master/system_instruction.prompt +0 -0
  41. package/data/common/prompts/room_moderator/moderate.json +34 -29
  42. package/data/common/prompts/room_moderator/moderate.prompt +230 -210
  43. package/data/common/prompts/story_moderator/moderate.prompt +5 -2
  44. package/data/common/prompts/story_moderator/moderate_to_alice.mock +6 -6
  45. package/data/common/prompts/story_moderator/moderate_to_bob.mock +6 -6
  46. package/dist-sdk/server/src/ai/LLM/anthropic.service.d.ts +2 -0
  47. package/dist-sdk/server/src/ai/LLM/anthropic.service.js +34 -22
  48. package/dist-sdk/server/src/ai/LLM/base-ai.service.d.ts +1 -0
  49. package/dist-sdk/server/src/ai/LLM/base-ai.service.js +4 -1
  50. package/dist-sdk/server/src/ai/agent-config.d.ts +1 -0
  51. package/dist-sdk/server/src/ai/agent-store.service.js +6 -4
  52. package/dist-sdk/server/src/ai/agent.d.ts +7 -0
  53. package/dist-sdk/server/src/ai/agent.js +33 -2
  54. package/dist-sdk/server/src/ai/artifact.service.d.ts +2 -0
  55. package/dist-sdk/server/src/ai/artifact.service.js +29 -1
  56. package/dist-sdk/server/src/ai/pack-artifacts.d.ts +7 -0
  57. package/dist-sdk/server/src/ai/pack-artifacts.js +155 -0
  58. package/dist-sdk/server/src/app/stripe.controller.js +5 -0
  59. package/dist-sdk/server/src/app.controller.d.ts +18 -18
  60. package/dist-sdk/server/src/app.controller.js +249 -25
  61. package/dist-sdk/server/src/app.service.d.ts +30 -17
  62. package/dist-sdk/server/src/app.service.js +303 -35
  63. package/dist-sdk/server/src/auth/auth.controller.js +3 -2
  64. package/dist-sdk/server/src/auth/owner-only.decorator.d.ts +1 -0
  65. package/dist-sdk/server/src/auth/owner-only.decorator.js +8 -0
  66. package/dist-sdk/server/src/auth/twilio.service.d.ts +5 -1
  67. package/dist-sdk/server/src/auth/twilio.service.js +5 -3
  68. package/dist-sdk/server/src/config/user-paths.service.d.ts +2 -0
  69. package/dist-sdk/server/src/config/user-paths.service.js +8 -0
  70. package/dist-sdk/server/src/room/artifact-store.service.js +10 -2
  71. package/dist-sdk/server/src/room/artifact.d.ts +1 -0
  72. package/dist-sdk/server/src/room/message.d.ts +2 -1
  73. package/dist-sdk/server/src/room/message.js +5 -4
  74. package/dist-sdk/server/src/room/room-config.d.ts +3 -0
  75. package/dist-sdk/server/src/room/room-store.service.d.ts +4 -2
  76. package/dist-sdk/server/src/room/room-store.service.js +46 -12
  77. package/dist-sdk/server/src/room/room.d.ts +29 -3
  78. package/dist-sdk/server/src/room/room.js +390 -122
  79. package/dist-sdk/server/src/sdk/briyah.js +12 -0
  80. package/dist-sdk/server/src/sdk/index.d.ts +4 -1
  81. package/dist-sdk/server/src/sdk/index.js +9 -1
  82. package/dist-sdk/server/src/story/story.service.js +10 -12
  83. package/dist-sdk/server/src/tools/native-tool.types.d.ts +31 -0
  84. package/dist-sdk/server/src/tools/packs/dnd5e/data/backgrounds.d.ts +22 -0
  85. package/dist-sdk/server/src/tools/packs/dnd5e/data/backgrounds.js +59 -0
  86. package/dist-sdk/server/src/tools/packs/dnd5e/data/feats.d.ts +24 -0
  87. package/dist-sdk/server/src/tools/packs/dnd5e/data/feats.js +11 -0
  88. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.d.ts +5 -0
  89. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.generated.d.ts +1 -0
  90. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.generated.js +154 -0
  91. package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.js +9 -0
  92. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.d.ts +20 -0
  93. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.generated.d.ts +2 -0
  94. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.generated.js +1824 -0
  95. package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.js +6 -0
  96. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.d.ts +44 -0
  97. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.generated.d.ts +2 -0
  98. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.generated.js +17293 -0
  99. package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.js +5 -0
  100. package/dist-sdk/server/src/tools/packs/dnd5e/data/races.d.ts +41 -0
  101. package/dist-sdk/server/src/tools/packs/dnd5e/data/races.js +250 -0
  102. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.d.ts +16 -0
  103. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.generated.d.ts +2 -0
  104. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.generated.js +3760 -0
  105. package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.js +12 -0
  106. package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.d.ts +63 -0
  107. package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.js +449 -0
  108. package/dist-sdk/server/src/tools/packs/dnd5e/data/weapons.d.ts +23 -0
  109. package/dist-sdk/server/src/tools/packs/dnd5e/data/weapons.js +88 -0
  110. package/dist-sdk/server/src/tools/packs/dnd5e/engine/backgrounds.d.ts +20 -0
  111. package/dist-sdk/server/src/tools/packs/dnd5e/engine/backgrounds.js +109 -0
  112. package/dist-sdk/server/src/tools/packs/dnd5e/engine/bestiary.d.ts +30 -0
  113. package/dist-sdk/server/src/tools/packs/dnd5e/engine/bestiary.js +329 -0
  114. package/dist-sdk/server/src/tools/packs/dnd5e/engine/campaign-items.d.ts +9 -0
  115. package/dist-sdk/server/src/tools/packs/dnd5e/engine/campaign-items.js +100 -0
  116. package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.d.ts +117 -0
  117. package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.js +1057 -0
  118. package/dist-sdk/server/src/tools/packs/dnd5e/engine/coerce.d.ts +13 -0
  119. package/dist-sdk/server/src/tools/packs/dnd5e/engine/coerce.js +147 -0
  120. package/dist-sdk/server/src/tools/packs/dnd5e/engine/dice.d.ts +27 -0
  121. package/dist-sdk/server/src/tools/packs/dnd5e/engine/dice.js +263 -0
  122. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encumbrance.d.ts +26 -0
  123. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encumbrance.js +129 -0
  124. package/dist-sdk/server/src/tools/packs/dnd5e/engine/feats.d.ts +22 -0
  125. package/dist-sdk/server/src/tools/packs/dnd5e/engine/feats.js +127 -0
  126. package/dist-sdk/server/src/tools/packs/dnd5e/engine/items.d.ts +33 -0
  127. package/dist-sdk/server/src/tools/packs/dnd5e/engine/items.js +137 -0
  128. package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.d.ts +26 -0
  129. package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.js +182 -0
  130. package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.d.ts +48 -0
  131. package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.js +344 -0
  132. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.d.ts +98 -0
  133. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.js +456 -0
  134. package/dist-sdk/server/src/tools/packs/dnd5e/engine/spells.d.ts +27 -0
  135. package/dist-sdk/server/src/tools/packs/dnd5e/engine/spells.js +123 -0
  136. package/dist-sdk/server/src/tools/packs/dnd5e/engine/weapons.d.ts +23 -0
  137. package/dist-sdk/server/src/tools/packs/dnd5e/engine/weapons.js +201 -0
  138. package/dist-sdk/server/src/tools/packs/dnd5e/index.d.ts +3 -0
  139. package/dist-sdk/server/src/tools/packs/dnd5e/index.js +35 -0
  140. package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.d.ts +2 -0
  141. package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.js +323 -0
  142. package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.d.ts +3 -0
  143. package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.js +117 -0
  144. package/dist-sdk/server/src/tools/packs/dnd5e/tools/item.tool.d.ts +2 -0
  145. package/dist-sdk/server/src/tools/packs/dnd5e/tools/item.tool.js +122 -0
  146. package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.d.ts +2 -0
  147. package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.js +157 -0
  148. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.d.ts +32 -0
  149. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.js +203 -0
  150. package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.d.ts +4 -0
  151. package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.js +465 -0
  152. package/dist-sdk/server/src/tools/packs/dnd5e/tools/spell.tool.d.ts +2 -0
  153. package/dist-sdk/server/src/tools/packs/dnd5e/tools/spell.tool.js +116 -0
  154. package/dist-sdk/server/src/tools/packs/dnd5e/tools/state.tools.d.ts +4 -0
  155. package/dist-sdk/server/src/tools/packs/dnd5e/tools/state.tools.js +234 -0
  156. package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.d.ts +6 -0
  157. package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.js +616 -0
  158. package/dist-sdk/server/src/tools/packs/index.d.ts +7 -0
  159. package/dist-sdk/server/src/tools/packs/index.js +45 -0
  160. package/dist-sdk/server/src/tools/tool-execution.service.d.ts +2 -2
  161. package/dist-sdk/server/src/tools/tool-execution.service.js +7 -6
  162. package/dist-sdk/shared/types/app.types.d.ts +63 -0
  163. package/docs/assets/hierarchy.js +1 -1
  164. package/docs/assets/navigation.js +1 -1
  165. package/docs/assets/search.js +1 -1
  166. package/docs/classes/Agent.html +51 -15
  167. package/docs/classes/Briyah.html +14 -14
  168. package/docs/classes/BriyahConfigService.html +5 -5
  169. package/docs/classes/NativeToolRegistry.html +21 -0
  170. package/docs/classes/Room.html +79 -29
  171. package/docs/classes/RoomMessage.html +32 -15
  172. package/docs/enums/MessageAction.html +3 -3
  173. package/docs/functions/availableToolPacks.html +2 -0
  174. package/docs/functions/dnd5eTools.html +5 -0
  175. package/docs/functions/enabledToolPacks.html +2 -0
  176. package/docs/functions/registerToolPacks.html +6 -0
  177. package/docs/hierarchy.html +1 -1
  178. package/docs/index.html +3 -3
  179. package/docs/interfaces/AgentInfo.html +17 -2
  180. package/docs/interfaces/AgentMessagesResponse.html +2 -2
  181. package/docs/interfaces/AppService.html +230 -181
  182. package/docs/interfaces/Artifact.html +15 -3
  183. package/docs/interfaces/ArtifactMetadata.html +5 -2
  184. package/docs/interfaces/ArtifactWriteOptions.html +21 -0
  185. package/docs/interfaces/AttachDocumentResponse.html +2 -2
  186. package/docs/interfaces/BriyahConfigOptions.html +9 -9
  187. package/docs/interfaces/ChapterInfo.html +2 -2
  188. package/docs/interfaces/Character.html +2 -2
  189. package/docs/interfaces/CreateAgentResponse.html +2 -2
  190. package/docs/interfaces/CreateRoomResponse.html +2 -2
  191. package/docs/interfaces/CreateStoryResponse.html +2 -2
  192. package/docs/interfaces/FileList.html +2 -2
  193. package/docs/interfaces/FileMetadata.html +3 -3
  194. package/docs/interfaces/IConfigService.html +3 -3
  195. package/docs/interfaces/LoggingOptions.html +6 -6
  196. package/docs/interfaces/Message.html +2 -2
  197. package/docs/interfaces/ModelInfo.html +2 -2
  198. package/docs/interfaces/NativeToolDefinition.html +11 -7
  199. package/docs/interfaces/PreparedPromptResponse.html +2 -2
  200. package/docs/interfaces/ProcessTextResponse.html +2 -2
  201. package/docs/interfaces/PromptFile.html +2 -2
  202. package/docs/interfaces/PromptFileContent.html +2 -2
  203. package/docs/interfaces/PromptFilesResponse.html +2 -2
  204. package/docs/interfaces/PromptFolder.html +2 -2
  205. package/docs/interfaces/PromptFoldersResponse.html +2 -2
  206. package/docs/interfaces/RoomDetails.html +15 -2
  207. package/docs/interfaces/RoomInfo.html +3 -2
  208. package/docs/interfaces/RoomMessageUpdate.html +2 -2
  209. package/docs/interfaces/RoomMessagesResponse.html +2 -2
  210. package/docs/interfaces/SendMessageResult.html +2 -2
  211. package/docs/interfaces/StoryErrorEvent.html +3 -3
  212. package/docs/interfaces/StoryIdea.html +2 -2
  213. package/docs/interfaces/StoryInfo.html +3 -3
  214. package/docs/interfaces/StoryIntroduceCharacterEvent.html +3 -3
  215. package/docs/interfaces/StoryProgressChapterEvent.html +3 -3
  216. package/docs/interfaces/StoryState.html +5 -5
  217. package/docs/interfaces/StoryStateEvent.html +3 -3
  218. package/docs/interfaces/ToolArtifact.html +8 -0
  219. package/docs/interfaces/ToolCaller.html +8 -0
  220. package/docs/interfaces/ToolDefinition.html +2 -2
  221. package/docs/interfaces/ToolHelpers.html +7 -3
  222. package/docs/interfaces/ToolParameter.html +2 -2
  223. package/docs/interfaces/ToolRoomAccess.html +51 -0
  224. package/docs/interfaces/ToolSummary.html +3 -2
  225. package/docs/interfaces/ToolsResponse.html +2 -2
  226. package/docs/interfaces/Transaction.html +2 -2
  227. package/docs/interfaces/TransactionHistoryResponse.html +2 -2
  228. package/docs/modules.html +1 -1
  229. package/docs/types/PromptScope.html +1 -1
  230. package/docs/types/ToolContext.html +2 -2
  231. package/docs/types/ToolRunResult.html +1 -1
  232. package/package.json +6 -4
  233. package/dist-sdk/server/src/ai/LLM/base-ai.service.spec.d.ts +0 -1
  234. package/dist-sdk/server/src/ai/LLM/base-ai.service.spec.js +0 -89
  235. package/dist-sdk/server/src/ai/LLM/comfyui-client.spec.d.ts +0 -1
  236. package/dist-sdk/server/src/ai/LLM/comfyui-client.spec.js +0 -143
  237. package/dist-sdk/server/src/ai/LLM/comfyui-workflow.spec.d.ts +0 -1
  238. package/dist-sdk/server/src/ai/LLM/comfyui-workflow.spec.js +0 -207
package/README.md CHANGED
@@ -1,684 +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
- **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
- // Native tools (recommended for SDK integrations — see Example 8)
256
- briyah.registerTool({ name, description, parameters, handler }); // process-level
257
- briyah.listNativeTools();
258
-
259
- // User-authored (string-code) tools — only when allowUserAuthoredTools is enabled
260
- const tools = await appService.listTools();
261
- const tool = await appService.createTool({ name, description, parameters, code, timeoutMs? });
262
- await appService.updateTool(name, tool);
263
- await appService.deleteTool(name);
264
- const result = await appService.testTool(name, args); // { ok: true, result } | { ok: false, error }
265
-
266
- // Story Management
267
- const story = await appService.createStory(name, idea, userCharacterDesc, otherCharactersDesc, storyModel?);
268
- await appService.progressStory(storyId);
269
-
270
- // Text Processing
271
- const result = await appService.processText(agentId, text);
272
-
273
- // Image Generation (image-capable providers; called on the Agent object — see Example 9)
274
- const { artifactId } = await agent.generateImage(prompt, imageProperties);
275
- const edited = await agent.editImage(prompt, imageProperties, referenceArtifactIds);
276
-
277
- // File Attachments
278
- const attachment = await appService.attachDocument(agentId, fileName, fileData);
279
- await appService.deleteAttachedFile(agentId, fileName); // by filename
280
- await appService.deleteAttachedFileById(documentId); // by document ID
281
- ```
282
-
283
- ## Usage Examples
284
-
285
- ### Example 1: Multi-User Setup
286
-
287
- ```typescript
288
- import { Briyah } from 'briyah';
289
-
290
- // Initialize once at application startup
291
- const briyah = new Briyah({
292
- dataPath: './data/briyah',
293
- startingBalance: 10.00
294
- });
295
-
296
- await briyah.init();
297
-
298
- // In your route handler or service
299
- async function handleUserRequest(userId: string, message: string) {
300
- const appService = briyah.getAppService(userId);
301
-
302
- // Each user gets their own isolated AppService
303
- const agents = await appService.listAgents();
304
-
305
- // ... process user request
306
- }
307
-
308
- // Cleanup at application shutdown
309
- process.on('SIGINT', async () => {
310
- await briyah.shutdown();
311
- process.exit(0);
312
- });
313
- ```
314
-
315
- ### Example 2: Custom Data Path
316
-
317
- ```typescript
318
- import { Briyah } from 'briyah';
319
- import path from 'path';
320
-
321
- const briyah = new Briyah({
322
- dataPath: path.join(__dirname, '..', 'user-data', 'briyah'),
323
- userServiceCacheTimeoutMinutes: 60 // 1 hour cache
324
- });
325
-
326
- await briyah.init();
327
- ```
328
-
329
- ### Example 3: Testing Configuration
330
-
331
- ```typescript
332
- import { Briyah } from 'briyah';
333
-
334
- const testBriyah = new Briyah({
335
- dataPath: './test-data',
336
- startingBalance: 100.00,
337
- userServiceCacheTimeoutMinutes: 5,
338
- envOverrides: {
339
- ANTHROPIC_API_KEY: process.env.TEST_ANTHROPIC_KEY,
340
- OPENAI_API_KEY: process.env.TEST_OPENAI_KEY
341
- }
342
- });
343
-
344
- await testBriyah.init();
345
-
346
- // Run tests...
347
-
348
- await testBriyah.shutdown();
349
- ```
350
-
351
- ### Example 4: Agent Creation and Text Processing
352
-
353
- ```typescript
354
- const appService = briyah.getAppService('user-123');
355
-
356
- // Create an agent
357
- const agent = appService.createAgent(
358
- 'Anthropic', // provider
359
- 'AI Assistant', // name
360
- 'James', // nickname
361
- 'A helpful AI assistant', // description
362
- 'claude-haiku-4-5' // model
363
- );
364
-
365
- if (!agent.id) throw new Error('Agent creation failed');
366
- console.log(`Created agent: ${agent.id}`);
367
-
368
- // Process text with the agent
369
- const result = await appService.processText(
370
- agent.id,
371
- 'What is the capital of France?'
372
- );
373
-
374
- console.log(`Response: ${result.result}`);
375
- console.log(`Cost: $${result.totalCost}`);
376
- console.log(`Tokens: ${(result.totalInputTokens ?? 0) + (result.totalOutputTokens ?? 0)}`);
377
- ```
378
-
379
- ### Example 5: Multi-Agent Room Conversation
380
-
381
- ```typescript
382
- const appService = briyah.getAppService('user-123');
383
-
384
- // Create agents
385
- const analyst = appService.createAgent('OpenAI', 'Analyst', 'Analyst', 'Data analyst', 'gpt-4');
386
- const writer = appService.createAgent('Anthropic', 'Writer', 'Writer', 'Content writer', 'claude-haiku-4-5');
387
-
388
- if (!analyst.id || !writer.id) throw new Error('Agent creation failed');
389
-
390
- // Create a room with both agents
391
- const room = await appService.createRoom(
392
- 'Analysis Session',
393
- 'Analyze sales data and produce a written summary',
394
- [analyst.id, writer.id]
395
- );
396
-
397
- // Send a message to start the conversation
398
- await appService.sendRoomMessage(
399
- room.roomId,
400
- 'Please analyze the sales data for Q4',
401
- 'Analyst',
402
- 'speak'
403
- );
404
-
405
- // The agents will automatically respond and interact
406
- // Check room messages to see the conversation
407
- const messages = await appService.getRoomMessages(room.roomId);
408
- console.log(`Messages: ${messages.messages.length}`);
409
- ```
410
-
411
- ### Example 6: Story Message Emitter
412
-
413
- 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.
414
-
415
- ```typescript
416
- import type {
417
- StoryStateEvent,
418
- StoryIntroduceCharacterEvent,
419
- StoryProgressChapterEvent,
420
- StoryErrorEvent,
421
- } from 'briyah';
422
-
423
- const app = briyah.getAppService('user-123');
424
-
425
- const story = await app.createStory(
426
- 'The Lost Kingdom',
427
- 'A medieval fantasy where ancient ruins hold a terrible secret',
428
- 'A disgraced knight seeking redemption'
429
- );
430
-
431
- const emitter = app.getStoryMessageEmitter(story.id);
432
-
433
- // Fires after every turn with the full updated game state.
434
- emitter.on('story-state', async (event: StoryStateEvent) => {
435
- const { state } = event;
436
- console.log('Latest message:', state.latestRoomMessage?.content);
437
-
438
- // Detect the player's turn by comparing speaker names.
439
- // Do NOT use state.humanPrompt for this — it is a UI display string,
440
- // not a reliable turn indicator.
441
- if (state.currentSpeaker === state.userAgentName) {
442
- const input = await promptPlayer(state.humanPrompt);
443
- await app.respondToStory(story.id, input);
444
- }
445
- });
446
-
447
- // Fires when the narrator wants to introduce a new character.
448
- // The host app should present this to the player before acting.
449
- // Accept by calling introduceCharacterToStory, or decline with declineCharacter.
450
- emitter.on('suggest-introduce-character', async (event: StoryIntroduceCharacterEvent) => {
451
- const accept = await askPlayer(`Add ${event.characterName} to the story?`);
452
- if (accept) {
453
- await app.introduceCharacterToStory(story.id, event.characterName!, '', undefined, true);
454
- } else {
455
- await app.declineCharacter(story.id, event.characterName!);
456
- }
457
- });
458
-
459
- // Fires when the narrator wants to advance to the next chapter.
460
- // Call progressStory to accept. Ignoring the event stays in the current chapter —
461
- // there is no explicit rejection call.
462
- emitter.on('suggest-progress-chapter', async (_event: StoryProgressChapterEvent) => {
463
- const accept = await askPlayer('The narrator suggests ending this chapter. Continue?');
464
- if (accept) {
465
- await app.progressStory(story.id);
466
- }
467
- });
468
-
469
- // Fires on fatal errors during room processing.
470
- // Named 'story-error' rather than 'error' to avoid Node.js throwing when no
471
- // listener is attached.
472
- emitter.on('story-error', (event: StoryErrorEvent) => {
473
- if (event.errorType === 'InsufficientBalanceError') {
474
- console.error('Out of credits:', event.message);
475
- } else {
476
- console.error(`Story error [${event.errorType}]:`, event.message);
477
- }
478
- });
479
- ```
480
-
481
- ### Example 7: Recording Payments and Managing Balance
482
-
483
- 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.
484
-
485
- ```typescript
486
- const app = briyah.getAppService(userId);
487
-
488
- // --- When your payment provider initiates a charge ---
489
- // Record it as pending so the transaction log stays consistent.
490
- await app.recordTransaction(amount, paymentIntentId, 'pending');
491
-
492
- // --- When your payment provider webhook confirms success ---
493
- await app.updateTransactionStatus(paymentIntentId, 'succeeded');
494
- await app.addBalance(amount);
495
-
496
- // Resume any stories that paused mid-turn due to InsufficientBalanceError.
497
- await app.resumePausedStories();
498
-
499
- // --- When a payment fails or is cancelled ---
500
- await app.updateTransactionStatus(paymentIntentId, 'failed');
501
-
502
- // --- Querying balance and history ---
503
- const balance = app.getBalance();
504
-
505
- const { transactions, total } = await app.getTransactions(50, 0);
506
-
507
- const tx = await app.getTransactionByPaymentId(paymentIntentId);
508
- console.log(tx?.status); // 'pending' | 'succeeded' | 'failed' | 'cancelled'
509
- ```
510
-
511
- To push real-time balance updates to a connected client (e.g. via SSE), subscribe to the balance emitter before crediting the user:
512
-
513
- ```typescript
514
- const emitter = app.getBalanceMessageEmitter(userId);
515
- emitter.on('update', (newBalance: number) => {
516
- // Push newBalance to the client
517
- });
518
- ```
519
-
520
- ### Example 8: Registering Native Tools with Opaque Context
521
-
522
- 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.
523
-
524
- 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.
525
-
526
- ```typescript
527
- import { Briyah } from 'briyah';
528
-
529
- const briyah = new Briyah({ dataPath: './data/briyah', startingBalance: 10.00 });
530
- await briyah.init();
531
-
532
- // Register a tool that reads its scope from context, not from the LLM's args.
533
- briyah.registerTool({
534
- name: 'add_note',
535
- description: "Add a note to the record the user currently has open",
536
- parameters: [
537
- { name: 'text', type: 'string', description: 'The note text', required: true }
538
- ],
539
- handler: async (args, helpers, context) => {
540
- const { db, recordId } = context as { db: MyDb; recordId: string };
541
- await db.addNote(recordId, args.text); // recordId comes from context — the LLM cannot set it
542
- return { added: true };
543
- },
544
- timeoutMs: 15000 // optional; default 30s, max 120s
545
- });
546
-
547
- // Grant it to an agent (grants are enforced server-side).
548
- const assistant = app.createAgent('Anthropic', 'Assistant', 'Assistant',
549
- 'A helpful assistant that manages the open record', 'claude-haiku-4-5');
550
- assistant.toolNames = ['add_note'];
551
- assistant.save();
552
-
553
- // When the user acts on record "rec_42", pass that scope as context. Any tool the
554
- // agent calls during the resulting turn receives it; other rooms/interactions are
555
- // unaffected. A log-only 'tool' message records each call (visible when fetching
556
- // messages with includeThoughts=true).
557
- await app.sendRoomMessage(
558
- roomId,
559
- 'Add a note that the client called about renewal.',
560
- 'User',
561
- 'speak',
562
- [],
563
- false,
564
- { db, recordId: 'rec_42' } // opaque context
565
- );
566
- ```
567
-
568
- 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.
569
-
570
- 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.
571
-
572
- User-authored (string-code) tools remain available via `createTool`/`updateTool`/`testTool` when `allowUserAuthoredTools` is enabled, for trusted single-user setups.
573
-
574
- ### Example 9: Self-Hosted Image Generation with ComfyUI
575
-
576
- 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`).
577
-
578
- For this provider the agent's *model name* selects a **workflow-template pair**, not a checkpoint. Two pairs ship by default:
579
-
580
- | Pair name | Model | Files required on the ComfyUI server |
581
- |---|---|---|
582
- | `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` |
583
- | `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` |
584
-
585
- `flux2-dev` has substantially better multi-reference character consistency and wants a 32 GB-class GPU; `flux-kontext` runs on 16 GB-class cards.
586
-
587
- ```typescript
588
- import { Briyah } from 'briyah';
589
-
590
- const briyah = new Briyah({ dataPath: './data/briyah', startingBalance: 10.00 });
591
- await briyah.init();
592
-
593
- const app = briyah.getAppService('user-123');
594
-
595
- // Model name = workflow pair name
596
- const artist = app.createAgent('ComfyUI', 'Artist', 'Artist',
597
- 'Image generation agent', 'flux2-dev');
598
-
599
- // Text-to-image. Resolves to { artifactId } on success or { error } on failure.
600
- const generated = await artist.generateImage(
601
- 'A lighthouse on a rocky coast at dusk',
602
- { width: 1024, height: 1024 } // optional; a fixed seed may also be passed
603
- );
604
- if (generated.error) throw new Error(String(generated.error));
605
-
606
- // Generated images are stored as artifacts (PNG)
607
- const png = artist.artifactService.getArtifact(generated.artifactId);
608
-
609
- // Image-to-image with reference images. Each referenced artifact is uploaded
610
- // and conditioned on separately (chained ReferenceLatent nodes). Order is
611
- // preserved, so the prompt can refer to "Image 1", "Image 2", ...
612
- const edited = await artist.editImage(
613
- 'The character from Image 2 stands in the setting from Image 1',
614
- { width: 1024, height: 1024 },
615
- [sceneArtifactId, portraitArtifactId]
616
- );
617
- ```
618
-
619
- Notes:
620
-
621
- - **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.
622
- - **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.
623
- - **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`.
624
-
625
- **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.
626
-
627
- ## Data Storage
628
-
629
- Briyah stores data in the following structure:
630
-
631
- ```
632
- {dataPath}/
633
- ├── common/ # Shared across all users
634
- │ ├── config/ # LLM pricing and image-model config
635
- │ ├── prompts/ # Global prompt templates
636
- │ └── published-agents.json # Published agent mappings
637
- └── user/
638
- └── {userId}/ # Per-user data
639
- ├── agents/ # Agent configs and histories (one JSON per agent)
640
- ├── rooms/ # Room metadata, message logs, artifacts (one folder per room)
641
- ├── stories/ # Story state
642
- ├── tools/ # User-defined tools (one JSON per tool)
643
- ├── prompts/ # User-specific prompts
644
- ├── upload/ # User file attachments
645
- ├── transactions/ # Transaction records
646
- └── userconfig/ # User preferences and balance
647
- ```
648
-
649
- ## Multi-Instance Support
650
-
651
- You can create multiple Briyah instances with different configurations:
652
-
653
- ```typescript
654
- const briyah1 = new Briyah({ dataPath: './data1' });
655
- const briyah2 = new Briyah({ dataPath: './data2' });
656
-
657
- await briyah1.init();
658
- await briyah2.init();
659
-
660
- // Each instance has isolated data
661
- const user1Service = briyah1.getAppService('user-123');
662
- const user2Service = briyah2.getAppService('user-123');
663
- // These are completely separate services with different data paths
664
- ```
665
-
666
- **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.
667
-
668
- ## Troubleshooting
669
-
670
- ### "Must call init() before getAppService()"
671
-
672
- Make sure to call `await briyah.init()` before calling `getAppService()`.
673
-
674
- ### "No LLM provider API keys configured"
675
-
676
- Set at least one of the required API key environment variables (ANTHROPIC_API_KEY, OPENAI_API_KEY, etc.).
677
-
678
- ### "STARTING_BALANCE environment variable is required"
679
-
680
- Set the `STARTING_BALANCE` environment variable or pass `startingBalance` in the constructor options.
681
-
682
- ### Cache not working as expected
683
-
684
- 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.