briyah 1.3.5 → 1.4.1

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 (239) hide show
  1. package/README.md +849 -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 +69 -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 +8 -5
  233. package/src/tools/packs/dnd5e/README.md +614 -0
  234. package/dist-sdk/server/src/ai/LLM/base-ai.service.spec.d.ts +0 -1
  235. package/dist-sdk/server/src/ai/LLM/base-ai.service.spec.js +0 -89
  236. package/dist-sdk/server/src/ai/LLM/comfyui-client.spec.d.ts +0 -1
  237. package/dist-sdk/server/src/ai/LLM/comfyui-client.spec.js +0 -143
  238. package/dist-sdk/server/src/ai/LLM/comfyui-workflow.spec.d.ts +0 -1
  239. package/dist-sdk/server/src/ai/LLM/comfyui-workflow.spec.js +0 -207
package/README.md CHANGED
@@ -1,684 +1,849 @@
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
+ ## Prompt Folders
289
+
290
+ An agent's behaviour comes from a **prompt folder**, not from its description. The folder
291
+ holds the templates the room renders on every turn — most importantly `perceive.prompt`, which
292
+ tells the agent what it is and what it may do, and `perceive.json`, the JSON schema its replies
293
+ must satisfy. Two agents on the same model with the same description behave completely
294
+ differently if they were built from different folders.
295
+
296
+ `init()` seeds the bundled folders into `{dataPath}/common/prompts/`, so they are on disk before
297
+ your first `createAgent` call. Existing files are preserved on upgrade, so anything you edit
298
+ survives.
299
+
300
+ ```typescript
301
+ const appService = briyah.getAppService('user-123');
302
+ console.log(appService.listPromptFolders());
303
+ // default, dungeon_master, dnd_player, character_creator, campaign_designer,
304
+ // dnd_room_moderator, narrator, character, illustrator, ...
305
+ ```
306
+
307
+ **The folder is the sixth argument to `createAgent`, and it defaults to `'default'`** — a
308
+ generic conversational agent. Passing a role folder is what makes the agent that role:
309
+
310
+ ```typescript
311
+ const dm = appService.createAgent(
312
+ 'Anthropic',
313
+ 'Dungeon Master', // agentName — a label; used in logs and the UI
314
+ 'DM', // agentNickname — the name the room routes by
315
+ 'Runs the game.',
316
+ 'claude-sonnet-5',
317
+ 'dungeon_master', // <- the prompt folder
318
+ );
319
+ ```
320
+
321
+ `agentNickname` is the identity: messages are addressed to it, artifact viewers are lists of
322
+ it, and it is what an agent writes into `targets`. `agentName` is a label. Give a character the
323
+ nickname you want it called by.
324
+
325
+ To write your own folder, copy a bundled one out of `{dataPath}/common/prompts/`, rename the
326
+ directory, and edit it — a folder in the user data directory takes precedence over the common
327
+ one of the same name.
328
+
329
+ ## Tool Packs
330
+
331
+ A tool pack is a set of native tools that ships with Briyah and registers only when asked for.
332
+ `dnd5e` is the one that exists: seventeen tools for dice, character sheets, the rules engine and
333
+ a bestiary. Turn it on either way:
334
+
335
+ ```typescript
336
+ // By name — the SDK registers the pack during construction
337
+ const briyah = new Briyah({ envOverrides: { BRIYAH_TOOL_PACKS: 'dnd5e' } });
338
+
339
+ // Or pass the definitions yourself, which also lets you filter or wrap them
340
+ import { dnd5eTools, availableToolPacks } from 'briyah';
341
+ const briyah = new Briyah({ tools: dnd5eTools() });
342
+ console.log(availableToolPacks()); // ['dnd5e']
343
+ ```
344
+
345
+ Registering makes the tools *grantable*, not granted. An agent may only run the ones named in
346
+ its `toolNames`:
347
+
348
+ ```typescript
349
+ const dm = appService.createAgent(
350
+ 'Anthropic', 'Dungeon Master', 'DM', 'Runs the game.', 'claude-sonnet-5', 'dungeon_master',
351
+ undefined, null, 0, '',
352
+ { toolNames: ['roll_dice', 'check', 'apply_hp', 'stat_block', 'read_sheet'] },
353
+ );
354
+ ```
355
+
356
+ Packs also ship read-only **documents** — rules text an agent carries in every call. They seed
357
+ into `{dataPath}/common/artifacts/`, appear in `listUserArtifacts()` alongside your own, and
358
+ attach by id:
359
+
360
+ ```typescript
361
+ await appService.attachArtifactToAgent(dm.id, 'pack:dnd5e.dungeon_master-procedure');
362
+ await appService.attachArtifactToAgent(player.id, 'pack:dnd5e.class-bard');
363
+ ```
364
+
365
+ A document sits in that agent's cached prompt prefix on every call, so attach what it needs and
366
+ nothing more. `src/tools/packs/dnd5e/README.md` in this package lists all seventeen tools and
367
+ which agent each document belongs to.
368
+
369
+ ## Usage Examples
370
+
371
+ ### Example 1: Multi-User Setup
372
+
373
+ ```typescript
374
+ import { Briyah } from 'briyah';
375
+
376
+ // Initialize once at application startup
377
+ const briyah = new Briyah({
378
+ dataPath: './data/briyah',
379
+ startingBalance: 10.00
380
+ });
381
+
382
+ await briyah.init();
383
+
384
+ // In your route handler or service
385
+ async function handleUserRequest(userId: string, message: string) {
386
+ const appService = briyah.getAppService(userId);
387
+
388
+ // Each user gets their own isolated AppService
389
+ const agents = await appService.listAgents();
390
+
391
+ // ... process user request
392
+ }
393
+
394
+ // Cleanup at application shutdown
395
+ process.on('SIGINT', async () => {
396
+ await briyah.shutdown();
397
+ process.exit(0);
398
+ });
399
+ ```
400
+
401
+ ### Example 2: Custom Data Path
402
+
403
+ ```typescript
404
+ import { Briyah } from 'briyah';
405
+ import path from 'path';
406
+
407
+ const briyah = new Briyah({
408
+ dataPath: path.join(__dirname, '..', 'user-data', 'briyah'),
409
+ userServiceCacheTimeoutMinutes: 60 // 1 hour cache
410
+ });
411
+
412
+ await briyah.init();
413
+ ```
414
+
415
+ ### Example 3: Testing Configuration
416
+
417
+ ```typescript
418
+ import { Briyah } from 'briyah';
419
+
420
+ const testBriyah = new Briyah({
421
+ dataPath: './test-data',
422
+ startingBalance: 100.00,
423
+ userServiceCacheTimeoutMinutes: 5,
424
+ envOverrides: {
425
+ ANTHROPIC_API_KEY: process.env.TEST_ANTHROPIC_KEY,
426
+ OPENAI_API_KEY: process.env.TEST_OPENAI_KEY
427
+ }
428
+ });
429
+
430
+ await testBriyah.init();
431
+
432
+ // Run tests...
433
+
434
+ await testBriyah.shutdown();
435
+ ```
436
+
437
+ ### Example 4: Agent Creation and Text Processing
438
+
439
+ ```typescript
440
+ const appService = briyah.getAppService('user-123');
441
+
442
+ // Create an agent
443
+ const agent = appService.createAgent(
444
+ 'Anthropic', // provider
445
+ 'AI Assistant', // name
446
+ 'James', // nickname
447
+ 'A helpful AI assistant', // description
448
+ 'claude-haiku-4-5' // model
449
+ );
450
+
451
+ if (!agent.id) throw new Error('Agent creation failed');
452
+ console.log(`Created agent: ${agent.id}`);
453
+
454
+ // Process text with the agent
455
+ const result = await appService.processText(
456
+ agent.id,
457
+ 'What is the capital of France?'
458
+ );
459
+
460
+ console.log(`Response: ${result.result}`);
461
+ console.log(`Cost: $${result.totalCost}`);
462
+ console.log(`Tokens: ${(result.totalInputTokens ?? 0) + (result.totalOutputTokens ?? 0)}`);
463
+ ```
464
+
465
+ ### Example 5: Multi-Agent Room Conversation
466
+
467
+ ```typescript
468
+ const appService = briyah.getAppService('user-123');
469
+
470
+ // Create agents
471
+ const analyst = appService.createAgent('OpenAI', 'Analyst', 'Analyst', 'Data analyst', 'gpt-4');
472
+ const writer = appService.createAgent('Anthropic', 'Writer', 'Writer', 'Content writer', 'claude-haiku-4-5');
473
+
474
+ if (!analyst.id || !writer.id) throw new Error('Agent creation failed');
475
+
476
+ // Create a room with both agents
477
+ const room = await appService.createRoom(
478
+ 'Analysis Session',
479
+ 'Analyze sales data and produce a written summary',
480
+ [analyst.id, writer.id]
481
+ );
482
+
483
+ // Send a message to start the conversation
484
+ await appService.sendRoomMessage(
485
+ room.roomId,
486
+ 'Please analyze the sales data for Q4',
487
+ 'Analyst',
488
+ 'speak'
489
+ );
490
+
491
+ // The agents will automatically respond and interact
492
+ // Check room messages to see the conversation
493
+ const messages = await appService.getRoomMessages(room.roomId);
494
+ console.log(`Messages: ${messages.messages.length}`);
495
+ ```
496
+
497
+ ### Example 6: Story Message Emitter
498
+
499
+ 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.
500
+
501
+ ```typescript
502
+ import type {
503
+ StoryStateEvent,
504
+ StoryIntroduceCharacterEvent,
505
+ StoryProgressChapterEvent,
506
+ StoryErrorEvent,
507
+ } from 'briyah';
508
+
509
+ const app = briyah.getAppService('user-123');
510
+
511
+ const story = await app.createStory(
512
+ 'The Lost Kingdom',
513
+ 'A medieval fantasy where ancient ruins hold a terrible secret',
514
+ 'A disgraced knight seeking redemption'
515
+ );
516
+
517
+ const emitter = app.getStoryMessageEmitter(story.id);
518
+
519
+ // Fires after every turn with the full updated game state.
520
+ emitter.on('story-state', async (event: StoryStateEvent) => {
521
+ const { state } = event;
522
+ console.log('Latest message:', state.latestRoomMessage?.content);
523
+
524
+ // Detect the player's turn by comparing speaker names.
525
+ // Do NOT use state.humanPrompt for this — it is a UI display string,
526
+ // not a reliable turn indicator.
527
+ if (state.currentSpeaker === state.userAgentName) {
528
+ const input = await promptPlayer(state.humanPrompt);
529
+ await app.respondToStory(story.id, input);
530
+ }
531
+ });
532
+
533
+ // Fires when the narrator wants to introduce a new character.
534
+ // The host app should present this to the player before acting.
535
+ // Accept by calling introduceCharacterToStory, or decline with declineCharacter.
536
+ emitter.on('suggest-introduce-character', async (event: StoryIntroduceCharacterEvent) => {
537
+ const accept = await askPlayer(`Add ${event.characterName} to the story?`);
538
+ if (accept) {
539
+ await app.introduceCharacterToStory(story.id, event.characterName!, '', undefined, true);
540
+ } else {
541
+ await app.declineCharacter(story.id, event.characterName!);
542
+ }
543
+ });
544
+
545
+ // Fires when the narrator wants to advance to the next chapter.
546
+ // Call progressStory to accept. Ignoring the event stays in the current chapter —
547
+ // there is no explicit rejection call.
548
+ emitter.on('suggest-progress-chapter', async (_event: StoryProgressChapterEvent) => {
549
+ const accept = await askPlayer('The narrator suggests ending this chapter. Continue?');
550
+ if (accept) {
551
+ await app.progressStory(story.id);
552
+ }
553
+ });
554
+
555
+ // Fires on fatal errors during room processing.
556
+ // Named 'story-error' rather than 'error' to avoid Node.js throwing when no
557
+ // listener is attached.
558
+ emitter.on('story-error', (event: StoryErrorEvent) => {
559
+ if (event.errorType === 'InsufficientBalanceError') {
560
+ console.error('Out of credits:', event.message);
561
+ } else {
562
+ console.error(`Story error [${event.errorType}]:`, event.message);
563
+ }
564
+ });
565
+ ```
566
+
567
+ ### Example 7: Recording Payments and Managing Balance
568
+
569
+ 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.
570
+
571
+ ```typescript
572
+ const app = briyah.getAppService(userId);
573
+
574
+ // --- When your payment provider initiates a charge ---
575
+ // Record it as pending so the transaction log stays consistent.
576
+ await app.recordTransaction(amount, paymentIntentId, 'pending');
577
+
578
+ // --- When your payment provider webhook confirms success ---
579
+ await app.updateTransactionStatus(paymentIntentId, 'succeeded');
580
+ await app.addBalance(amount);
581
+
582
+ // Resume any stories that paused mid-turn due to InsufficientBalanceError.
583
+ await app.resumePausedStories();
584
+
585
+ // --- When a payment fails or is cancelled ---
586
+ await app.updateTransactionStatus(paymentIntentId, 'failed');
587
+
588
+ // --- Querying balance and history ---
589
+ const balance = app.getBalance();
590
+
591
+ const { transactions, total } = await app.getTransactions(50, 0);
592
+
593
+ const tx = await app.getTransactionByPaymentId(paymentIntentId);
594
+ console.log(tx?.status); // 'pending' | 'succeeded' | 'failed' | 'cancelled'
595
+ ```
596
+
597
+ To push real-time balance updates to a connected client (e.g. via SSE), subscribe to the balance emitter before crediting the user:
598
+
599
+ ```typescript
600
+ const emitter = app.getBalanceMessageEmitter(userId);
601
+ emitter.on('update', (newBalance: number) => {
602
+ // Push newBalance to the client
603
+ });
604
+ ```
605
+
606
+ ### Example 8: Registering Native Tools with Opaque Context
607
+
608
+ 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.
609
+
610
+ 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.
611
+
612
+ ```typescript
613
+ import { Briyah } from 'briyah';
614
+
615
+ const briyah = new Briyah({ dataPath: './data/briyah', startingBalance: 10.00 });
616
+ await briyah.init();
617
+
618
+ // Register a tool that reads its scope from context, not from the LLM's args.
619
+ briyah.registerTool({
620
+ name: 'add_note',
621
+ description: "Add a note to the record the user currently has open",
622
+ parameters: [
623
+ { name: 'text', type: 'string', description: 'The note text', required: true }
624
+ ],
625
+ handler: async (args, helpers, context) => {
626
+ const { db, recordId } = context as { db: MyDb; recordId: string };
627
+ await db.addNote(recordId, args.text); // recordId comes from context — the LLM cannot set it
628
+ return { added: true };
629
+ },
630
+ timeoutMs: 15000 // optional; default 30s, max 120s
631
+ });
632
+
633
+ // Grant it to an agent (grants are enforced server-side).
634
+ const assistant = app.createAgent('Anthropic', 'Assistant', 'Assistant',
635
+ 'A helpful assistant that manages the open record', 'claude-haiku-4-5');
636
+ assistant.toolNames = ['add_note'];
637
+ assistant.save();
638
+
639
+ // When the user acts on record "rec_42", pass that scope as context. Any tool the
640
+ // agent calls during the resulting turn receives it; other rooms/interactions are
641
+ // unaffected. A log-only 'tool' message records each call (visible when fetching
642
+ // messages with includeThoughts=true).
643
+ await app.sendRoomMessage(
644
+ roomId,
645
+ 'Add a note that the client called about renewal.',
646
+ 'User',
647
+ 'speak',
648
+ [],
649
+ false,
650
+ { db, recordId: 'rec_42' } // opaque context
651
+ );
652
+ ```
653
+
654
+ 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.
655
+
656
+ 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.
657
+
658
+ User-authored (string-code) tools remain available via `createTool`/`updateTool`/`testTool` when `allowUserAuthoredTools` is enabled, for trusted single-user setups.
659
+
660
+ ### Example 9: Self-Hosted Image Generation with ComfyUI
661
+
662
+ 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`).
663
+
664
+ For this provider the agent's *model name* selects a **workflow-template pair**, not a checkpoint. Two pairs ship by default:
665
+
666
+ | Pair name | Model | Files required on the ComfyUI server |
667
+ |---|---|---|
668
+ | `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` |
669
+ | `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` |
670
+
671
+ `flux2-dev` has substantially better multi-reference character consistency and wants a 32 GB-class GPU; `flux-kontext` runs on 16 GB-class cards.
672
+
673
+ ```typescript
674
+ import { Briyah } from 'briyah';
675
+
676
+ const briyah = new Briyah({ dataPath: './data/briyah', startingBalance: 10.00 });
677
+ await briyah.init();
678
+
679
+ const app = briyah.getAppService('user-123');
680
+
681
+ // Model name = workflow pair name
682
+ const artist = app.createAgent('ComfyUI', 'Artist', 'Artist',
683
+ 'Image generation agent', 'flux2-dev');
684
+
685
+ // Text-to-image. Resolves to { artifactId } on success or { error } on failure.
686
+ const generated = await artist.generateImage(
687
+ 'A lighthouse on a rocky coast at dusk',
688
+ { width: 1024, height: 1024 } // optional; a fixed seed may also be passed
689
+ );
690
+ if (generated.error) throw new Error(String(generated.error));
691
+
692
+ // Generated images are stored as artifacts (PNG)
693
+ const png = artist.artifactService.getArtifact(generated.artifactId);
694
+
695
+ // Image-to-image with reference images. Each referenced artifact is uploaded
696
+ // and conditioned on separately (chained ReferenceLatent nodes). Order is
697
+ // preserved, so the prompt can refer to "Image 1", "Image 2", ...
698
+ const edited = await artist.editImage(
699
+ 'The character from Image 2 stands in the setting from Image 1',
700
+ { width: 1024, height: 1024 },
701
+ [sceneArtifactId, portraitArtifactId]
702
+ );
703
+ ```
704
+
705
+ Notes:
706
+
707
+ - **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.
708
+ - **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.
709
+ - **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`.
710
+
711
+ **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.
712
+
713
+ ### Example 10: A turn-based table with a human player
714
+
715
+ Example 5 sends one message and reads the transcript back, which suits a batch job. A game or
716
+ any human-in-the-loop app needs the other shape: the agents take several turns among themselves,
717
+ then stop and wait for the person. Three things make that work.
718
+
719
+ **`turnMode: 'directed'`** — only the agent a message names is asked to reply, and the room
720
+ leader answers anything it cannot place. The default, `'broadcast'`, prompts *every* agent for
721
+ *every* message and keeps one reply, which costs several times as much and is wrong for a table
722
+ where one person speaks at a time.
723
+
724
+ **A human-controlled agent** — `createAgent`'s seventh argument. The room delivers messages to
725
+ it and then stops rather than generating a reply, which is what yields the floor to your console.
726
+
727
+ **The room message emitter** — the only way to see the conversation as it happens. It fires on
728
+ every change with the newest message and the room's state.
729
+
730
+ ```typescript
731
+ import { Briyah, dnd5eTools } from 'briyah';
732
+ import * as readline from 'node:readline/promises';
733
+
734
+ const briyah = new Briyah({ dataPath: './briyah-data', tools: dnd5eTools() });
735
+ await briyah.init(); // seeds prompt folders and pack documents
736
+ const app = briyah.getAppService('user-123');
737
+
738
+ const dm = app.createAgent(
739
+ 'Anthropic', 'Dungeon Master', 'DM', 'Runs the game.', 'claude-sonnet-5',
740
+ 'dungeon_master', undefined, null, 0, '',
741
+ { toolNames: ['roll_dice', 'check', 'apply_hp', 'stat_block', 'read_sheet'] },
742
+ );
743
+ const rogue = app.createAgent(
744
+ 'Anthropic', 'Vex', 'Vex', 'A wary scout.', 'claude-haiku-4-5', 'dnd_player',
745
+ );
746
+ // The seventh argument is what makes this one wait for a person.
747
+ const you = app.createAgent(
748
+ 'Anthropic', 'Homer', 'Homer', 'A hopeful bard.', 'claude-haiku-4-5', 'dnd_player',
749
+ true,
750
+ );
751
+
752
+ // createAgent builds the agent in memory; save() writes it to disk. Without this the
753
+ // table exists for this process only and is gone on restart.
754
+ [dm, rogue, you].forEach((agent) => agent.save());
755
+
756
+ await app.attachArtifactToAgent(dm.id!, 'pack:dnd5e.dungeon_master-procedure');
757
+ await app.attachArtifactToAgent(rogue.id!, 'pack:dnd5e.class-rogue');
758
+ await app.attachArtifactToAgent(you.id!, 'pack:dnd5e.class-bard');
759
+
760
+ const { roomId } = await app.createRoom(
761
+ 'The Sunken Barrow',
762
+ 'A three-room dungeon crawl.',
763
+ [dm.id!, rogue.id!, you.id!],
764
+ 'DM', // roomLeader — answers anything the room cannot place
765
+ 'directed', // turnMode
766
+ );
767
+
768
+ // Watch the conversation. `waitingForHuman` is the cue to prompt your player.
769
+ const io = readline.createInterface({ input: process.stdin, output: process.stdout });
770
+ app.getRoomMessageEmitter(roomId).on('update', async (state) => {
771
+ if (state.latestMessage && state.latestMessage.sender !== 'Homer') {
772
+ console.log(`${state.latestMessage.sender}: ${state.latestMessage.content}`);
773
+ }
774
+ if (state.waitingForHuman && !state.processingInProgress) {
775
+ const line = await io.question('> ');
776
+ await app.sendRoomMessage(roomId, line, 'Homer', 'speak', ['DM']);
777
+ }
778
+ });
779
+
780
+ await app.sendRoomMessage(roomId, 'Begin the adventure.', 'Homer', 'speak', ['DM']);
781
+ ```
782
+
783
+ The emitter payload carries `latestMessage`, `messageIndex`, `totalCost`, `isPaused`,
784
+ `currentSpeaker`, `processingInProgress` and `waitingForHuman`. `messageIndex` counts messages
785
+ with thoughts and tool notices excluded, so compare it against a list you fetched the same way —
786
+ `getRoomMessages(roomId)` — or simply refetch when they disagree.
787
+
788
+ Two notes for a long-running process. Call `await briyah.shutdown()` before exiting or the
789
+ process will hang on open handles. And a room with no human-controlled agent never stops on its
790
+ own: the agents talk until the leader adjourns.
791
+
792
+ ## Data Storage
793
+
794
+ Briyah stores data in the following structure:
795
+
796
+ ```
797
+ {dataPath}/
798
+ ├── common/ # Shared across all users
799
+ │ ├── config/ # LLM pricing and image-model config
800
+ │ ├── prompts/ # Global prompt templates
801
+ │ └── published-agents.json # Published agent mappings
802
+ └── user/
803
+ └── {userId}/ # Per-user data
804
+ ├── agents/ # Agent configs and histories (one JSON per agent)
805
+ ├── rooms/ # Room metadata, message logs, artifacts (one folder per room)
806
+ ├── stories/ # Story state
807
+ ├── tools/ # User-defined tools (one JSON per tool)
808
+ ├── prompts/ # User-specific prompts
809
+ ├── upload/ # User file attachments
810
+ ├── transactions/ # Transaction records
811
+ └── userconfig/ # User preferences and balance
812
+ ```
813
+
814
+ ## Multi-Instance Support
815
+
816
+ You can create multiple Briyah instances with different configurations:
817
+
818
+ ```typescript
819
+ const briyah1 = new Briyah({ dataPath: './data1' });
820
+ const briyah2 = new Briyah({ dataPath: './data2' });
821
+
822
+ await briyah1.init();
823
+ await briyah2.init();
824
+
825
+ // Each instance has isolated data
826
+ const user1Service = briyah1.getAppService('user-123');
827
+ const user2Service = briyah2.getAppService('user-123');
828
+ // These are completely separate services with different data paths
829
+ ```
830
+
831
+ **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.
832
+
833
+ ## Troubleshooting
834
+
835
+ ### "Must call init() before getAppService()"
836
+
837
+ Make sure to call `await briyah.init()` before calling `getAppService()`.
838
+
839
+ ### "No LLM provider API keys configured"
840
+
841
+ Set at least one of the required API key environment variables (ANTHROPIC_API_KEY, OPENAI_API_KEY, etc.).
842
+
843
+ ### "STARTING_BALANCE environment variable is required"
844
+
845
+ Set the `STARTING_BALANCE` environment variable or pass `startingBalance` in the constructor options.
846
+
847
+ ### Cache not working as expected
848
+
849
+ Check the cache statistics with `getCacheStats()` and adjust `userServiceCacheTimeoutMinutes` in the constructor options.