briyah 1.5.0 → 2.0.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 (231) hide show
  1. package/README.md +1272 -994
  2. package/data/common/config/markup +1 -1
  3. package/data/common/prompts/character/progress_character.json +5 -5
  4. package/data/common/prompts/illustrator/describe_scene.json +11 -3
  5. package/data/common/prompts/perceive.json +2 -2
  6. package/data/common/prompts/room_moderator/moderate.json +34 -34
  7. package/data/common/prompts/story_moderator/moderate.json +62 -62
  8. package/data/packs/dnd5e/agents/battle-master.json +6 -0
  9. package/data/packs/dnd5e/agents/campaign-designer.json +6 -0
  10. package/data/packs/dnd5e/agents/character-creator.json +6 -0
  11. package/data/packs/dnd5e/agents/dungeon-master.json +6 -0
  12. package/data/packs/dnd5e/agents/player.json +13 -0
  13. package/data/packs/dnd5e/agents/table-moderator.json +6 -0
  14. package/data/{common/artifacts/dnd5e/dungeon_master-procedure.md → packs/dnd5e/artifacts/battle_master-combat.md} +31 -131
  15. package/data/packs/dnd5e/artifacts/dungeon_master-procedure.md +192 -0
  16. package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/manifest.json +8 -2
  17. package/data/packs/dnd5e/pack.json +6 -0
  18. package/data/packs/dnd5e/prompts/battle_master/defaults_config.json +23 -0
  19. package/data/packs/dnd5e/prompts/battle_master/perceive.json +33 -0
  20. package/data/packs/dnd5e/prompts/battle_master/perceive.prompt +378 -0
  21. package/data/{common → packs/dnd5e}/prompts/character_creator/defaults_config.json +1 -1
  22. package/data/{common → packs/dnd5e}/prompts/character_creator/perceive.prompt +29 -0
  23. package/data/{common → packs/dnd5e}/prompts/dnd_player/perceive.prompt +40 -22
  24. package/data/{common → packs/dnd5e}/prompts/dnd_room_moderator/moderate.json +34 -34
  25. package/data/{common → packs/dnd5e}/prompts/dnd_room_moderator/moderate.prompt +14 -3
  26. package/data/{common → packs/dnd5e}/prompts/dungeon_master/defaults_config.json +1 -0
  27. package/data/{common → packs/dnd5e}/prompts/dungeon_master/perceive.prompt +122 -115
  28. package/data/packs/dnd5e/prompts/dungeon_master/system_instruction.prompt +0 -0
  29. package/data/packs/dnd5e/rooms/table.json +16 -0
  30. package/dist-sdk/server/src/ai/LLM/base-ai.service.js +4 -13
  31. package/dist-sdk/server/src/ai/LLM/deepseek.service.d.ts +2 -1
  32. package/dist-sdk/server/src/ai/LLM/deepseek.service.js +65 -77
  33. package/dist-sdk/server/src/ai/agent-config.d.ts +2 -0
  34. package/dist-sdk/server/src/ai/agent-store.service.js +8 -0
  35. package/dist-sdk/server/src/ai/agent.d.ts +6 -0
  36. package/dist-sdk/server/src/ai/agent.js +25 -2
  37. package/dist-sdk/server/src/ai/artifact.service.d.ts +3 -1
  38. package/dist-sdk/server/src/ai/artifact.service.js +12 -5
  39. package/dist-sdk/server/src/ai/pack-artifacts.d.ts +3 -3
  40. package/dist-sdk/server/src/ai/pack-artifacts.js +21 -15
  41. package/dist-sdk/server/src/app/user-service-factory.js +9 -1
  42. package/dist-sdk/server/src/app.controller.d.ts +11 -11
  43. package/dist-sdk/server/src/app.controller.js +179 -89
  44. package/dist-sdk/server/src/app.service.d.ts +30 -7
  45. package/dist-sdk/server/src/app.service.js +146 -95
  46. package/dist-sdk/server/src/common/errors.d.ts +0 -3
  47. package/dist-sdk/server/src/common/errors.js +1 -11
  48. package/dist-sdk/server/src/config/prompt-resolver.d.ts +41 -0
  49. package/dist-sdk/server/src/config/prompt-resolver.js +196 -0
  50. package/dist-sdk/server/src/config/user-config.service.d.ts +17 -0
  51. package/dist-sdk/server/src/config/user-config.service.js +103 -0
  52. package/dist-sdk/server/src/config/user-paths.service.d.ts +4 -4
  53. package/dist-sdk/server/src/config/user-paths.service.js +12 -16
  54. package/dist-sdk/server/src/packs/pack-instantiation.service.d.ts +36 -0
  55. package/dist-sdk/server/src/packs/pack-instantiation.service.js +165 -0
  56. package/dist-sdk/server/src/packs/pack-manifest.d.ts +52 -0
  57. package/dist-sdk/server/src/packs/pack-manifest.js +256 -0
  58. package/dist-sdk/server/src/packs/pack.service.d.ts +24 -0
  59. package/dist-sdk/server/src/packs/pack.service.js +151 -0
  60. package/dist-sdk/server/src/room/room-config.d.ts +5 -0
  61. package/dist-sdk/server/src/room/room-message.service.d.ts +2 -1
  62. package/dist-sdk/server/src/room/room-message.service.js +3 -2
  63. package/dist-sdk/server/src/room/room-store.service.d.ts +3 -0
  64. package/dist-sdk/server/src/room/room-store.service.js +41 -5
  65. package/dist-sdk/server/src/room/room.d.ts +7 -0
  66. package/dist-sdk/server/src/room/room.js +33 -3
  67. package/dist-sdk/server/src/sdk/briyah.d.ts +2 -0
  68. package/dist-sdk/server/src/sdk/briyah.js +45 -8
  69. package/dist-sdk/server/src/sdk/index.d.ts +7 -2
  70. package/dist-sdk/server/src/sdk/index.js +6 -2
  71. package/dist-sdk/server/src/shared/shared.module.js +0 -3
  72. package/dist-sdk/server/src/story/story.service.d.ts +2 -2
  73. package/dist-sdk/server/src/tools/packs/dnd5e/data/kits.d.ts +17 -0
  74. package/dist-sdk/server/src/tools/packs/dnd5e/data/kits.js +54 -0
  75. package/dist-sdk/server/src/tools/packs/dnd5e/data/races.d.ts +3 -0
  76. package/dist-sdk/server/src/tools/packs/dnd5e/data/races.js +6 -0
  77. package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.d.ts +2 -0
  78. package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.js +4 -0
  79. package/dist-sdk/server/src/tools/packs/dnd5e/engine/backgrounds.d.ts +1 -1
  80. package/dist-sdk/server/src/tools/packs/dnd5e/engine/backgrounds.js +6 -3
  81. package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.d.ts +3 -0
  82. package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.js +45 -5
  83. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encounter.d.ts +27 -0
  84. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encounter.js +103 -0
  85. package/dist-sdk/server/src/tools/packs/dnd5e/engine/foes.d.ts +7 -0
  86. package/dist-sdk/server/src/tools/packs/dnd5e/engine/foes.js +83 -0
  87. package/dist-sdk/server/src/tools/packs/dnd5e/engine/kits.d.ts +19 -0
  88. package/dist-sdk/server/src/tools/packs/dnd5e/engine/kits.js +130 -0
  89. package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.d.ts +2 -1
  90. package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.js +13 -2
  91. package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.d.ts +6 -0
  92. package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.js +16 -0
  93. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.d.ts +10 -0
  94. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.js +82 -1
  95. package/dist-sdk/server/src/tools/packs/dnd5e/index.js +2 -0
  96. package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.js +51 -6
  97. package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.js +19 -9
  98. package/dist-sdk/server/src/tools/packs/dnd5e/tools/encounter.tool.d.ts +2 -0
  99. package/dist-sdk/server/src/tools/packs/dnd5e/tools/encounter.tool.js +134 -0
  100. package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.js +31 -13
  101. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.d.ts +2 -0
  102. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.js +25 -8
  103. package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.js +70 -4
  104. package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.js +27 -0
  105. package/dist-sdk/server/src/tools/packs/index.d.ts +1 -2
  106. package/dist-sdk/server/src/tools/packs/index.js +5 -11
  107. package/dist-sdk/shared/types/app.types.d.ts +81 -13
  108. package/docs/assets/hierarchy.js +1 -1
  109. package/docs/assets/highlight.css +15 -1
  110. package/docs/assets/icons.js +1 -1
  111. package/docs/assets/icons.svg +1 -1
  112. package/docs/assets/main.js +4 -4
  113. package/docs/assets/navigation.js +1 -1
  114. package/docs/assets/search.js +1 -1
  115. package/docs/assets/style.css +18 -3
  116. package/docs/classes/Agent.html +702 -37
  117. package/docs/classes/Briyah.html +250 -33
  118. package/docs/classes/BriyahConfigService.html +117 -10
  119. package/docs/classes/NativeToolRegistry.html +156 -11
  120. package/docs/classes/PackInstantiationService.html +157 -0
  121. package/docs/classes/PackService.html +247 -0
  122. package/docs/classes/Room.html +1190 -77
  123. package/docs/classes/RoomMessage.html +260 -29
  124. package/docs/enums/MessageAction.html +123 -3
  125. package/docs/functions/availableToolPacks.html +41 -2
  126. package/docs/functions/dnd5eTools.html +42 -3
  127. package/docs/functions/installToolPacks.html +48 -0
  128. package/docs/functions/registerToolPacks.html +54 -6
  129. package/docs/hierarchy.html +42 -1
  130. package/docs/index.html +301 -54
  131. package/docs/interfaces/AgentCreationOptions.html +110 -11
  132. package/docs/interfaces/AgentInfo.html +188 -3
  133. package/docs/interfaces/AgentMessagesResponse.html +71 -2
  134. package/docs/interfaces/AppService.html +2806 -474
  135. package/docs/interfaces/Artifact.html +81 -4
  136. package/docs/interfaces/ArtifactMetadata.html +104 -3
  137. package/docs/interfaces/ArtifactWriteOptions.html +75 -6
  138. package/docs/interfaces/AttachDocumentResponse.html +61 -2
  139. package/docs/interfaces/BriyahConfigOptions.html +107 -10
  140. package/docs/interfaces/ChapterInfo.html +61 -2
  141. package/docs/interfaces/Character.html +81 -2
  142. package/docs/interfaces/CreateAgentResponse.html +56 -2
  143. package/docs/interfaces/CreateRoomResponse.html +61 -2
  144. package/docs/interfaces/CreateStoryResponse.html +56 -2
  145. package/docs/interfaces/FileList.html +56 -2
  146. package/docs/interfaces/FileMetadata.html +84 -3
  147. package/docs/interfaces/IConfigService.html +76 -3
  148. package/docs/interfaces/InstantiateModels.html +64 -0
  149. package/docs/interfaces/InstantiateRoomResult.html +70 -0
  150. package/docs/interfaces/LoadedPack.html +131 -0
  151. package/docs/interfaces/LoggingOptions.html +86 -7
  152. package/docs/interfaces/Message.html +80 -2
  153. package/docs/interfaces/ModelChoice.html +73 -0
  154. package/docs/interfaces/ModelInfo.html +71 -2
  155. package/docs/interfaces/NativeToolDefinition.html +96 -9
  156. package/docs/interfaces/PackAgentTemplate.html +101 -0
  157. package/docs/interfaces/PackRoomTemplate.html +108 -0
  158. package/docs/interfaces/PackView.html +172 -0
  159. package/docs/interfaces/PreparedPromptResponse.html +61 -2
  160. package/docs/interfaces/ProcessTextResponse.html +81 -2
  161. package/docs/interfaces/PromptFile.html +69 -2
  162. package/docs/interfaces/PromptFileContent.html +75 -2
  163. package/docs/interfaces/PromptFilesResponse.html +56 -2
  164. package/docs/interfaces/PromptFolder.html +79 -2
  165. package/docs/interfaces/PromptFolderDefaults.html +136 -5
  166. package/docs/interfaces/PromptFolderDefaultsResponse.html +78 -4
  167. package/docs/interfaces/PromptFoldersResponse.html +56 -2
  168. package/docs/interfaces/RoomDetails.html +133 -4
  169. package/docs/interfaces/RoomErrorUpdate.html +82 -0
  170. package/docs/interfaces/RoomInfo.html +84 -2
  171. package/docs/interfaces/RoomMessageUpdate.html +106 -2
  172. package/docs/interfaces/RoomMessagesResponse.html +61 -2
  173. package/docs/interfaces/SendMessageResult.html +61 -2
  174. package/docs/interfaces/StoryErrorEvent.html +76 -4
  175. package/docs/interfaces/StoryIdea.html +71 -2
  176. package/docs/interfaces/StoryInfo.html +173 -3
  177. package/docs/interfaces/StoryIntroduceCharacterEvent.html +71 -4
  178. package/docs/interfaces/StoryProgressChapterEvent.html +64 -3
  179. package/docs/interfaces/StoryState.html +99 -6
  180. package/docs/interfaces/StoryStateEvent.html +69 -3
  181. package/docs/interfaces/ToolArtifact.html +81 -4
  182. package/docs/interfaces/ToolCaller.html +75 -6
  183. package/docs/interfaces/ToolDefinition.html +76 -2
  184. package/docs/interfaces/ToolHelpers.html +91 -6
  185. package/docs/interfaces/ToolParameter.html +71 -2
  186. package/docs/interfaces/ToolRoomAccess.html +200 -24
  187. package/docs/interfaces/ToolSummary.html +71 -2
  188. package/docs/interfaces/ToolsResponse.html +66 -2
  189. package/docs/interfaces/Transaction.html +96 -2
  190. package/docs/interfaces/TransactionHistoryResponse.html +61 -2
  191. package/docs/modules.html +53 -1
  192. package/docs/types/PackOrigin.html +34 -0
  193. package/docs/types/PromptScope.html +34 -1
  194. package/docs/types/RoomTurnMode.html +36 -2
  195. package/docs/types/RoomUpdate.html +36 -0
  196. package/docs/types/RosterOverrides.html +42 -0
  197. package/docs/types/ToolContext.html +36 -2
  198. package/docs/types/ToolRunResult.html +34 -1
  199. package/package.json +139 -139
  200. package/src/tools/packs/dnd5e/README.md +186 -27
  201. package/dist-sdk/server/src/library/library.service.d.ts +0 -14
  202. package/dist-sdk/server/src/library/library.service.js +0 -165
  203. package/docs/functions/enabledToolPacks.html +0 -2
  204. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/campaign_designer-setting.md +0 -0
  205. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/character_creator-basics.md +0 -0
  206. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-barbarian.md +0 -0
  207. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-bard.md +0 -0
  208. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-cleric.md +0 -0
  209. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-druid.md +0 -0
  210. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-fighter.md +0 -0
  211. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-monk.md +0 -0
  212. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-paladin.md +0 -0
  213. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-ranger.md +0 -0
  214. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-rogue.md +0 -0
  215. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-sorcerer.md +0 -0
  216. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-warlock.md +0 -0
  217. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-wizard.md +0 -0
  218. /package/data/{common/prompts/campaign_designer → packs/dnd5e/prompts/battle_master}/system_instruction.prompt +0 -0
  219. /package/data/{common → packs/dnd5e}/prompts/campaign_designer/defaults_config.json +0 -0
  220. /package/data/{common → packs/dnd5e}/prompts/campaign_designer/perceive.json +0 -0
  221. /package/data/{common → packs/dnd5e}/prompts/campaign_designer/perceive.prompt +0 -0
  222. /package/data/{common/prompts/character_creator → packs/dnd5e/prompts/campaign_designer}/system_instruction.prompt +0 -0
  223. /package/data/{common → packs/dnd5e}/prompts/character_creator/perceive.json +0 -0
  224. /package/data/{common/prompts/dnd_player → packs/dnd5e/prompts/character_creator}/system_instruction.prompt +0 -0
  225. /package/data/{common → packs/dnd5e}/prompts/dnd_player/defaults_config.json +0 -0
  226. /package/data/{common → packs/dnd5e}/prompts/dnd_player/perceive.json +0 -0
  227. /package/data/{common/prompts/dnd_room_moderator → packs/dnd5e/prompts/dnd_player}/system_instruction.prompt +0 -0
  228. /package/data/{common → packs/dnd5e}/prompts/dnd_room_moderator/defaults_config.json +0 -0
  229. /package/data/{common/prompts/dungeon_master → packs/dnd5e/prompts/dnd_room_moderator}/system_instruction.prompt +0 -0
  230. /package/data/{common → packs/dnd5e}/prompts/dungeon_master/compact_agent.prompt +0 -0
  231. /package/data/{common → packs/dnd5e}/prompts/dungeon_master/perceive.json +0 -0
package/README.md CHANGED
@@ -1,994 +1,1272 @@
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
- // roomLeader answers anything the room cannot place; turnMode 'directed' asks only the
252
- // agent a message names ('broadcast', the default, asks every agent every time);
253
- // moderator is only needed when no agent leads the turn order.
254
- const room = await appService.createRoom(
255
- name, goal, agentIds, roomLeader?, turnMode?, moderator?,
256
- );
257
- const rooms = await appService.listRooms();
258
- const details = await appService.getRoomDetails(roomId);
259
- // action defaults to 'moderate'. Returns {accepted, reason} — a message sent out of
260
- // turn is refused, not thrown. `sender` must be an agentNickname.
261
- await appService.sendRoomMessage(roomId, content, sender, action?, targets?);
262
- // Required before subscribing to a room this process did not create.
263
- await appService.ensureRoomStateCallback(roomId);
264
- const emitter = appService.getRoomMessageEmitter(roomId); // 'update' events
265
-
266
- // Prompt folder defaults — the role's name, tools and documents, as the create-agent
267
- // dialog would fill them in. Read these rather than hard-coding a pack's tool names.
268
- const { defaults } = appService.getPromptFolderDefaults('dungeon_master');
269
-
270
- // Or let the folder build the agent: applies those defaults, saves, and attaches the
271
- // folder's documents. Async (attaching is), unlike createAgent. `overrides` takes the
272
- // same shape as the defaults; pass `attachDocuments: false` to decline the documents.
273
- const agent = await appService.createAgentFromFolder({
274
- folder: 'dungeon_master', aiServiceName: 'Anthropic', aiModel: 'claude-sonnet-5',
275
- });
276
-
277
- // Agents that belong to a room: created inside it, named after it, deleted with it,
278
- // and left out of listAgents(). agentName is the bare name; the room's is prefixed on.
279
- await appService.createRoomAgent(roomId, { aiServiceName, agentName, description, aiModel, promptName });
280
- await appService.removeRoomAgent(roomId, agentId);
281
-
282
- // Native tools (recommended for SDK integrations — see Example 8)
283
- briyah.registerTool({ name, description, parameters, handler }); // process-level
284
- briyah.listNativeTools();
285
-
286
- // User-authored (string-code) tools — only when allowUserAuthoredTools is enabled
287
- const tools = await appService.listTools();
288
- const tool = await appService.createTool({ name, description, parameters, code, timeoutMs? });
289
- await appService.updateTool(name, tool);
290
- await appService.deleteTool(name);
291
- const result = await appService.testTool(name, args); // { ok: true, result } | { ok: false, error }
292
-
293
- // Story Management
294
- // illustrateStory is required and positional — it is the fifth argument, not an option.
295
- const story = await appService.createStory(
296
- name, idea, userCharacterDesc, otherCharactersDesc, illustrateStory,
297
- storyModel?, isImport?, imageModelName?, skipDetailedPlot?,
298
- );
299
- await appService.progressStory(storyId);
300
-
301
- // Text Processing
302
- const result = await appService.processText(agentId, text);
303
-
304
- // Image Generation (image-capable providers; called on the Agent object — see Example 9)
305
- const { artifactId } = await agent.generateImage(prompt, imageProperties);
306
- const edited = await agent.editImage(prompt, imageProperties, referenceArtifactIds);
307
-
308
- // File Attachments
309
- const attachment = await appService.attachDocument(agentId, fileName, fileData);
310
- await appService.deleteAttachedFile(agentId, fileName); // by filename
311
- await appService.deleteAttachedFileById(documentId); // by document ID
312
- ```
313
-
314
- ## Prompt Folders
315
-
316
- An agent's behaviour comes from a **prompt folder**, not from its description. The folder
317
- holds the templates the room renders on every turn — most importantly `perceive.prompt`, which
318
- tells the agent what it is and what it may do, and `perceive.json`, the JSON schema its replies
319
- must satisfy. Two agents on the same model with the same description behave completely
320
- differently if they were built from different folders.
321
-
322
- `init()` seeds the bundled folders into `{dataPath}/common/prompts/`, so they are on disk before
323
- your first `createAgent` call. Existing files are preserved on upgrade, so anything you edit
324
- survives.
325
-
326
- ```typescript
327
- const appService = briyah.getAppService('user-123');
328
- console.log(appService.listPromptFolders());
329
- // default, dungeon_master, dnd_player, character_creator, campaign_designer,
330
- // dnd_room_moderator, narrator, character, illustrator, ...
331
- ```
332
-
333
- **The folder is the sixth argument to `createAgent`, and it defaults to `'default'`** — a
334
- generic conversational agent. Passing a role folder is what makes the agent that role:
335
-
336
- ```typescript
337
- const dm = appService.createAgent(
338
- 'Anthropic',
339
- 'Dungeon Master', // agentName — a label; used in logs and the UI
340
- 'DM', // agentNickname — the name the room routes by
341
- 'Runs the game.',
342
- 'claude-sonnet-5',
343
- 'dungeon_master', // <- the prompt folder
344
- );
345
- ```
346
-
347
- `agentNickname` is the identity: messages are addressed to it, artifact viewers are lists of
348
- it, and it is what an agent writes into `targets`. `agentName` is a label. Give a character the
349
- nickname you want it called by.
350
-
351
- To write your own folder, copy a bundled one out of `{dataPath}/common/prompts/`, rename the
352
- directory, and edit it — a folder in the user data directory takes precedence over the common
353
- one of the same name.
354
-
355
- ## Tool Packs
356
-
357
- A tool pack is a set of native tools that ships with Briyah and registers only when asked for.
358
- `dnd5e` is the one that exists: seventeen tools for dice, character sheets, the rules engine and
359
- a bestiary. Turn it on either way:
360
-
361
- ```typescript
362
- // By name — the SDK registers the pack during construction
363
- const briyah = new Briyah({ envOverrides: { BRIYAH_TOOL_PACKS: 'dnd5e' } });
364
-
365
- // Or pass the definitions yourself, which also lets you filter or wrap them
366
- import { dnd5eTools, availableToolPacks } from 'briyah';
367
- const briyah = new Briyah({ tools: dnd5eTools() });
368
- console.log(availableToolPacks()); // ['dnd5e']
369
- ```
370
-
371
- Registering makes the tools *grantable*, not granted. An agent may only run the ones named in
372
- its `toolNames`:
373
-
374
- ```typescript
375
- const dm = appService.createAgent(
376
- 'Anthropic', 'Dungeon Master', 'DM', 'Runs the game.', 'claude-sonnet-5', 'dungeon_master',
377
- undefined, null, 0, '',
378
- { toolNames: ['roll_dice', 'check', 'apply_hp', 'stat_block', 'read_sheet'] },
379
- );
380
- ```
381
-
382
- Packs also ship read-only **documents** — rules text an agent carries in every call. They seed
383
- into `{dataPath}/common/artifacts/`, appear in `listUserArtifacts()` alongside your own, and
384
- attach by id:
385
-
386
- ```typescript
387
- await appService.attachArtifactToAgent(dm.id, 'pack:dnd5e.dungeon_master-procedure');
388
- await appService.attachArtifactToAgent(player.id, 'pack:dnd5e.class-bard');
389
- ```
390
-
391
- A document sits in that agent's cached prompt prefix on every call, so attach what it needs and
392
- nothing more. `src/tools/packs/dnd5e/README.md` in this package lists all seventeen tools and
393
- which agent each document belongs to.
394
-
395
- ## Usage Examples
396
-
397
- ### Example 1: Multi-User Setup
398
-
399
- ```typescript
400
- import { Briyah } from 'briyah';
401
-
402
- // Initialize once at application startup
403
- const briyah = new Briyah({
404
- dataPath: './data/briyah',
405
- startingBalance: 10.00
406
- });
407
-
408
- await briyah.init();
409
-
410
- // In your route handler or service
411
- async function handleUserRequest(userId: string, message: string) {
412
- const appService = briyah.getAppService(userId);
413
-
414
- // Each user gets their own isolated AppService
415
- const agents = await appService.listAgents();
416
-
417
- // ... process user request
418
- }
419
-
420
- // Cleanup at application shutdown
421
- process.on('SIGINT', async () => {
422
- await briyah.shutdown();
423
- process.exit(0);
424
- });
425
- ```
426
-
427
- ### Example 2: Custom Data Path
428
-
429
- ```typescript
430
- import { Briyah } from 'briyah';
431
- import path from 'path';
432
-
433
- const briyah = new Briyah({
434
- dataPath: path.join(__dirname, '..', 'user-data', 'briyah'),
435
- userServiceCacheTimeoutMinutes: 60 // 1 hour cache
436
- });
437
-
438
- await briyah.init();
439
- ```
440
-
441
- ### Example 3: Testing Configuration
442
-
443
- ```typescript
444
- import { Briyah } from 'briyah';
445
-
446
- const testBriyah = new Briyah({
447
- dataPath: './test-data',
448
- startingBalance: 100.00,
449
- userServiceCacheTimeoutMinutes: 5,
450
- envOverrides: {
451
- ANTHROPIC_API_KEY: process.env.TEST_ANTHROPIC_KEY,
452
- OPENAI_API_KEY: process.env.TEST_OPENAI_KEY
453
- }
454
- });
455
-
456
- await testBriyah.init();
457
-
458
- // Run tests...
459
-
460
- await testBriyah.shutdown();
461
- ```
462
-
463
- ### Example 4: Agent Creation and Text Processing
464
-
465
- ```typescript
466
- const appService = briyah.getAppService('user-123');
467
-
468
- // Create an agent
469
- const agent = appService.createAgent(
470
- 'Anthropic', // provider
471
- 'AI Assistant', // name
472
- 'James', // nickname
473
- 'A helpful AI assistant', // description
474
- 'claude-haiku-4-5' // model
475
- );
476
-
477
- if (!agent.id) throw new Error('Agent creation failed');
478
- console.log(`Created agent: ${agent.id}`);
479
-
480
- // Process text with the agent
481
- const result = await appService.processText(
482
- agent.id,
483
- 'What is the capital of France?'
484
- );
485
-
486
- console.log(`Response: ${result.result}`);
487
- console.log(`Cost: $${result.totalCost}`);
488
- console.log(`Tokens: ${(result.totalInputTokens ?? 0) + (result.totalOutputTokens ?? 0)}`);
489
- ```
490
-
491
- ### Example 5: Multi-Agent Room Conversation
492
-
493
- ```typescript
494
- const appService = briyah.getAppService('user-123');
495
-
496
- // Create agents
497
- const analyst = appService.createAgent('OpenAI', 'Analyst', 'Analyst', 'Data analyst', 'gpt-4');
498
- const writer = appService.createAgent('Anthropic', 'Writer', 'Writer', 'Content writer', 'claude-haiku-4-5');
499
-
500
- if (!analyst.id || !writer.id) throw new Error('Agent creation failed');
501
-
502
- // Create a room with both agents
503
- const room = await appService.createRoom(
504
- 'Analysis Session',
505
- 'Analyze sales data and produce a written summary',
506
- [analyst.id, writer.id]
507
- );
508
-
509
- // Send a message to start the conversation
510
- await appService.sendRoomMessage(
511
- room.roomId,
512
- 'Please analyze the sales data for Q4',
513
- 'Analyst',
514
- 'speak'
515
- );
516
-
517
- // The agents will automatically respond and interact
518
- // Check room messages to see the conversation
519
- const messages = await appService.getRoomMessages(room.roomId);
520
- console.log(`Messages: ${messages.messages.length}`);
521
- ```
522
-
523
- ### Example 6: Story Message Emitter
524
-
525
- 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.
526
-
527
- ```typescript
528
- import type {
529
- StoryStateEvent,
530
- StoryIntroduceCharacterEvent,
531
- StoryProgressChapterEvent,
532
- StoryErrorEvent,
533
- } from 'briyah';
534
-
535
- const app = briyah.getAppService('user-123');
536
-
537
- const story = await app.createStory(
538
- 'The Lost Kingdom',
539
- 'A medieval fantasy where ancient ruins hold a terrible secret',
540
- 'A disgraced knight seeking redemption',
541
- 'A scholar and a sellsword',
542
- false, // illustrateStory — required, and positional
543
- );
544
-
545
- const emitter = app.getStoryMessageEmitter(story.id);
546
-
547
- // Fires after every turn with the full updated game state.
548
- emitter.on('story-state', async (event: StoryStateEvent) => {
549
- const { state } = event;
550
- console.log('Latest message:', state.latestRoomMessage?.content);
551
-
552
- // Detect the player's turn by comparing speaker names.
553
- // Do NOT use state.humanPrompt for this — it is a UI display string,
554
- // not a reliable turn indicator.
555
- if (state.currentSpeaker === state.userAgentName) {
556
- const input = await promptPlayer(state.humanPrompt);
557
- await app.respondToStory(story.id, input);
558
- }
559
- });
560
-
561
- // Fires when the narrator wants to introduce a new character.
562
- // The host app should present this to the player before acting.
563
- // Accept by calling introduceCharacterToStory, or decline with declineCharacter.
564
- emitter.on('suggest-introduce-character', async (event: StoryIntroduceCharacterEvent) => {
565
- const accept = await askPlayer(`Add ${event.characterName} to the story?`);
566
- if (accept) {
567
- await app.introduceCharacterToStory(story.id, event.characterName!, '', undefined, true);
568
- } else {
569
- await app.declineCharacter(story.id, event.characterName!);
570
- }
571
- });
572
-
573
- // Fires when the narrator wants to advance to the next chapter.
574
- // Call progressStory to accept. Ignoring the event stays in the current chapter —
575
- // there is no explicit rejection call.
576
- emitter.on('suggest-progress-chapter', async (_event: StoryProgressChapterEvent) => {
577
- const accept = await askPlayer('The narrator suggests ending this chapter. Continue?');
578
- if (accept) {
579
- await app.progressStory(story.id);
580
- }
581
- });
582
-
583
- // Fires on fatal errors during room processing.
584
- // Named 'story-error' rather than 'error' to avoid Node.js throwing when no
585
- // listener is attached.
586
- emitter.on('story-error', (event: StoryErrorEvent) => {
587
- if (event.errorType === 'InsufficientBalanceError') {
588
- console.error('Out of credits:', event.message);
589
- } else {
590
- console.error(`Story error [${event.errorType}]:`, event.message);
591
- }
592
- });
593
- ```
594
-
595
- ### Example 7: Recording Payments and Managing Balance
596
-
597
- 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.
598
-
599
- ```typescript
600
- const app = briyah.getAppService(userId);
601
-
602
- // --- When your payment provider initiates a charge ---
603
- // Record it as pending so the transaction log stays consistent.
604
- await app.recordTransaction(amount, paymentIntentId, 'pending');
605
-
606
- // --- When your payment provider webhook confirms success ---
607
- await app.updateTransactionStatus(paymentIntentId, 'succeeded');
608
- await app.addBalance(amount);
609
-
610
- // Resume any stories that paused mid-turn due to InsufficientBalanceError.
611
- await app.resumePausedStories();
612
-
613
- // --- When a payment fails or is cancelled ---
614
- await app.updateTransactionStatus(paymentIntentId, 'failed');
615
-
616
- // --- Querying balance and history ---
617
- const balance = app.getBalance();
618
-
619
- const { transactions, total } = await app.getTransactions(50, 0);
620
-
621
- const tx = await app.getTransactionByPaymentId(paymentIntentId);
622
- console.log(tx?.status); // 'pending' | 'succeeded' | 'failed' | 'cancelled'
623
- ```
624
-
625
- To push real-time balance updates to a connected client (e.g. via SSE), subscribe to the balance emitter before crediting the user:
626
-
627
- ```typescript
628
- const emitter = app.getBalanceMessageEmitter(userId);
629
- emitter.on('update', (newBalance: number) => {
630
- // Push newBalance to the client
631
- });
632
- ```
633
-
634
- ### Example 8: Registering Native Tools with Opaque Context
635
-
636
- 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.
637
-
638
- 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.
639
-
640
- ```typescript
641
- import { Briyah } from 'briyah';
642
-
643
- const briyah = new Briyah({ dataPath: './data/briyah', startingBalance: 10.00 });
644
- await briyah.init();
645
-
646
- // Register a tool that reads its scope from context, not from the LLM's args.
647
- briyah.registerTool({
648
- name: 'add_note',
649
- description: "Add a note to the record the user currently has open",
650
- parameters: [
651
- { name: 'text', type: 'string', description: 'The note text', required: true }
652
- ],
653
- handler: async (args, helpers, context) => {
654
- const { db, recordId } = context as { db: MyDb; recordId: string };
655
- await db.addNote(recordId, args.text); // recordId comes from context — the LLM cannot set it
656
- return { added: true };
657
- },
658
- timeoutMs: 15000 // optional; default 30s, max 120s
659
- });
660
-
661
- // Grant it to an agent (grants are enforced server-side).
662
- const assistant = app.createAgent('Anthropic', 'Assistant', 'Assistant',
663
- 'A helpful assistant that manages the open record', 'claude-haiku-4-5');
664
- assistant.toolNames = ['add_note'];
665
- assistant.save();
666
-
667
- // When the user acts on record "rec_42", pass that scope as context. Any tool the
668
- // agent calls during the resulting turn receives it; other rooms/interactions are
669
- // unaffected. A log-only 'tool' message records each call (visible when fetching
670
- // messages with includeThoughts=true).
671
- await app.sendRoomMessage(
672
- roomId,
673
- 'Add a note that the client called about renewal.',
674
- 'User',
675
- 'speak',
676
- [],
677
- false,
678
- { db, recordId: 'rec_42' } // opaque context
679
- );
680
- ```
681
-
682
- 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.
683
-
684
- 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.
685
-
686
- User-authored (string-code) tools remain available via `createTool`/`updateTool`/`testTool` when `allowUserAuthoredTools` is enabled, for trusted single-user setups.
687
-
688
- ### Example 9: Self-Hosted Image Generation with ComfyUI
689
-
690
- 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`).
691
-
692
- For this provider the agent's *model name* selects a **workflow-template pair**, not a checkpoint. Two pairs ship by default:
693
-
694
- | Pair name | Model | Files required on the ComfyUI server |
695
- |---|---|---|
696
- | `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` |
697
- | `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` |
698
-
699
- `flux2-dev` has substantially better multi-reference character consistency and wants a 32 GB-class GPU; `flux-kontext` runs on 16 GB-class cards.
700
-
701
- ```typescript
702
- import { Briyah } from 'briyah';
703
-
704
- const briyah = new Briyah({ dataPath: './data/briyah', startingBalance: 10.00 });
705
- await briyah.init();
706
-
707
- const app = briyah.getAppService('user-123');
708
-
709
- // Model name = workflow pair name
710
- const artist = app.createAgent('ComfyUI', 'Artist', 'Artist',
711
- 'Image generation agent', 'flux2-dev');
712
-
713
- // Text-to-image. Resolves to { artifactId } on success or { error } on failure.
714
- const generated = await artist.generateImage(
715
- 'A lighthouse on a rocky coast at dusk',
716
- { width: 1024, height: 1024 } // optional; a fixed seed may also be passed
717
- );
718
- if (generated.error) throw new Error(String(generated.error));
719
-
720
- // Generated images are stored as artifacts (PNG)
721
- const png = artist.artifactService.getArtifact(generated.artifactId);
722
-
723
- // Image-to-image with reference images. Each referenced artifact is uploaded
724
- // and conditioned on separately (chained ReferenceLatent nodes). Order is
725
- // preserved, so the prompt can refer to "Image 1", "Image 2", ...
726
- const edited = await artist.editImage(
727
- 'The character from Image 2 stands in the setting from Image 1',
728
- { width: 1024, height: 1024 },
729
- [sceneArtifactId, portraitArtifactId]
730
- );
731
- ```
732
-
733
- Notes:
734
-
735
- - **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.
736
- - **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.
737
- - **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`.
738
-
739
- **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.
740
-
741
- ### Example 10: A turn-based table with a human player
742
-
743
- Example 5 sends one message and reads the transcript back, which suits a batch job. A game or
744
- any human-in-the-loop app needs the other shape: the agents take several turns among themselves,
745
- then stop and wait for the person. Three things make that work.
746
-
747
- **`turnMode: 'directed'`** — only the agent a message names is asked to reply, and the room
748
- leader answers anything it cannot place. The default, `'broadcast'`, prompts *every* agent for
749
- *every* message and keeps one reply, which costs several times as much and is wrong for a table
750
- where one person speaks at a time.
751
-
752
- **A human-controlled agent** — `createAgent`'s seventh argument. The room delivers messages to
753
- it and then stops rather than generating a reply, which is what yields the floor to your console.
754
-
755
- **The room message emitter** — the only way to see the conversation as it happens. It fires on
756
- every change with the newest message and the room's state.
757
-
758
- ```typescript
759
- import { Briyah, dnd5eTools } from 'briyah';
760
- import * as readline from 'node:readline/promises';
761
-
762
- const briyah = new Briyah({ dataPath: './briyah-data', tools: dnd5eTools() });
763
- await briyah.init(); // seeds prompt folders and pack documents
764
- const app = briyah.getAppService('user-123');
765
-
766
- const dm = app.createAgent(
767
- 'Anthropic', 'Dungeon Master', 'DM', 'Runs the game.', 'claude-sonnet-5',
768
- 'dungeon_master', undefined, null, 0, '',
769
- { toolNames: ['roll_dice', 'check', 'apply_hp', 'stat_block', 'read_sheet'] },
770
- );
771
- const rogue = app.createAgent(
772
- 'Anthropic', 'Vex', 'Vex', 'A wary scout.', 'claude-haiku-4-5', 'dnd_player',
773
- );
774
- // The seventh argument is what makes this one wait for a person.
775
- const you = app.createAgent(
776
- 'Anthropic', 'Homer', 'Homer', 'A hopeful bard.', 'claude-haiku-4-5', 'dnd_player',
777
- true,
778
- );
779
-
780
- // createAgent builds the agent in memory; save() writes it to disk. Without this the
781
- // table exists for this process only and is gone on restart.
782
- [dm, rogue, you].forEach((agent) => agent.save());
783
-
784
- await app.attachArtifactToAgent(dm.id!, 'pack:dnd5e.dungeon_master-procedure');
785
- await app.attachArtifactToAgent(rogue.id!, 'pack:dnd5e.class-rogue');
786
- await app.attachArtifactToAgent(you.id!, 'pack:dnd5e.class-bard');
787
-
788
- const { roomId } = await app.createRoom(
789
- 'The Sunken Barrow',
790
- 'A three-room dungeon crawl.',
791
- [dm.id!, rogue.id!, you.id!],
792
- 'DM', // roomLeader — answers anything the room cannot place
793
- 'directed', // turnMode
794
- );
795
-
796
- // A room loaded from disk has no state-change callback, so its emitter would never
797
- // fire. Harmless on a room you just created; required for one you resumed.
798
- await app.ensureRoomStateCallback(roomId);
799
-
800
- const io = readline.createInterface({ input: process.stdin, output: process.stdout });
801
- let lastIndex = -1;
802
- let atKeyboard = false; // the handler is async; without this it re-enters
803
- let replyTo = 'DM'; // who last spoke to the player
804
- let replyAs: 'speak' | 'whisper' = 'speak';
805
-
806
- app.getRoomMessageEmitter(roomId).on('update', async (state) => {
807
- if (state.type === 'error') { // a turn failed — see "Errors" below
808
- console.error(`[${state.errorType}] ${state.message}`);
809
- return;
810
- }
811
-
812
- const message = state.latestMessage;
813
- if (message && state.messageIndex !== undefined && state.messageIndex > lastIndex) {
814
- lastIndex = state.messageIndex; // the emitter can repeat a state
815
- if (message.sender !== 'Homer') console.log(`${message.sender}: ${message.content}`);
816
- // Answer whoever addressed you, the way they addressed you. During session
817
- // zero that is the designer or the creator, whispering — replying to the DM
818
- // instead drops the interview.
819
- if (message.targets?.includes('Homer') && message.sender !== 'Homer') {
820
- replyTo = message.sender;
821
- replyAs = message.action === 'whisper' ? 'whisper' : 'speak';
822
- }
823
- }
824
-
825
- // The floor is the player's only when the room *names* them. `waitingForHuman`
826
- // is also true for a moment after sendRoomMessage clears currentSpeaker and
827
- // before processing starts, so gating on it alone opens a second prompt before
828
- // the table has said a word.
829
- if (!atKeyboard && state.currentSpeaker === 'Homer') {
830
- atKeyboard = true;
831
- try {
832
- const line = await io.question('> ');
833
- const result = await app.sendRoomMessage(roomId, line, 'Homer', replyAs, [replyTo]);
834
- if (!result.accepted) console.log(`(not your turn — ${result.reason})`);
835
- } finally {
836
- atKeyboard = false;
837
- }
838
- }
839
- });
840
-
841
- // The emitter only fires on a *change*, so the opening line comes from here.
842
- await app.sendRoomMessage(roomId, 'Begin the adventure.', 'Homer', 'speak', ['DM']);
843
- ```
844
-
845
- **The emitter payload** carries `latestMessage`, `messageIndex`, `totalCost`, `isPaused`,
846
- `currentSpeaker`, `processingInProgress` and `waitingForHuman`. `messageIndex` counts messages
847
- with thoughts and tool notices excluded, so compare it against a list fetched the same way —
848
- `getRoomMessages(roomId)` — or refetch when they disagree.
849
-
850
- **Errors** arrive on the same emitter as `{type: 'error', errorType, message}`. Check for it
851
- first, as above: a turn that dies — most often on a spent balance — otherwise just goes quiet,
852
- with no message and nothing to await.
853
-
854
- **`sendRoomMessage`'s `action` defaults to `'moderate'`**, not `'speak'`. Pass the action you
855
- mean. A message sent out of turn is refused rather than thrown: the result is
856
- `{accepted: false, reason}`, which is what to show as "not your turn".
857
-
858
- **The `sender` string must be an `agentNickname`** — that is the name the room routes by.
859
-
860
- Two notes for a long-running process. Call `await briyah.shutdown()` before exiting or it will
861
- hang on open handles. And a room with no human-controlled agent never stops on its own: the
862
- agents talk until the leader adjourns.
863
-
864
- ### Example 11: Seating a whole D&D table
865
-
866
- Example 10 seats a Dungeon Master and players, which is enough to see the loop but not enough
867
- to play. The `dungeon_master` prompt whispers a **campaign designer** to build the world and a
868
- **character creator** to build sheets, so a table without those two has a leader whose own
869
- instructions reference agents that are not there.
870
-
871
- The other half is that each role needs its folder's tool grants and pack documents.
872
- `createAgentFromFolder` reads the folder's `defaults_config.json` and applies all of it — the
873
- same wiring the web client's create-agent dialog performs — so you never transcribe seventeen
874
- tool names or thirteen document ids by hand, and nothing drifts when the pack changes.
875
-
876
- ```typescript
877
- import { Briyah, dnd5eTools } from 'briyah';
878
-
879
- const briyah = new Briyah({ dataPath: './briyah-data', tools: dnd5eTools() });
880
- await briyah.init();
881
- const app = briyah.getAppService('cli-user');
882
-
883
- const from = (folder: string, aiModel: string, overrides = {}) =>
884
- app.createAgentFromFolder({ folder, aiServiceName: 'Anthropic', aiModel, overrides });
885
-
886
- const dm = await from('dungeon_master', 'claude-sonnet-5');
887
- const designer = await from('campaign_designer', 'claude-sonnet-5');
888
- const creator = await from('character_creator', 'claude-haiku-4-5');
889
-
890
- const you = await from('dnd_player', 'claude-haiku-4-5', {
891
- agentNickname: 'Homer',
892
- description: 'A player character with no sheet yet, played by a person.',
893
- controlledByHuman: true,
894
- });
895
- const vex = await from('dnd_player', 'claude-haiku-4-5', {
896
- agentNickname: 'Vex', description: 'A wary scout.',
897
- });
898
-
899
- // The goal is read by every agent every turn. Say what has *not* happened yet, or the
900
- // Dungeon Master opens a scene for characters who have no sheets.
901
- const { roomId } = await app.createRoom(
902
- 'Campaign — Homer',
903
- 'A fifth-edition campaign for Homer and Vex. Nothing is prepared: no campaign has been ' +
904
- 'designed and no character has a sheet. Run session zero first — have the Campaign ' +
905
- 'Designer interview Homer and publish the Campaign document, then hand the Character ' +
906
- 'Creator one player at a time until both sheets exist — and only then open the first scene.',
907
- [dm.id!, designer.id!, creator.id!, you.id!, vex.id!],
908
- 'DM',
909
- 'directed',
910
- );
911
- ```
912
-
913
- Then run the loop from Example 10. Session zero is whispered, which is why that loop mirrors
914
- the action it replies with.
915
-
916
- **Models by role.** The Dungeon Master reasons and makes every tool call; the specialists run a
917
- few dozen times per campaign; the players are cheap.
918
-
919
- | Role | Model |
920
- |---|---|
921
- | Dungeon Master, campaign designer | `claude-sonnet-5` |
922
- | Character creator | `claude-haiku-4-5` |
923
- | Players, human and AI | `claude-haiku-4-5` |
924
-
925
- **Moderators.** `createRoom`'s sixth argument names one, and the `dnd_room_moderator` folder
926
- provides one. A 5e table does **not** need it: the Dungeon Master leads a `directed` room and
927
- names who acts next, which is the same job. A moderator earns its place when no agent is in
928
- charge of the turn order — several people talking at once, or a room whose members address each
929
- other freely. If you give an agent `useModerator: true`, the room must have one or `createRoom`
930
- raises a `ValidationError`.
931
-
932
- **Resuming.** `listRooms()` gives saved campaigns; `getRoomDetails(roomId)` gives the roster,
933
- where `agents[].controlledByHuman` identifies the person's character. Then
934
- `ensureRoomStateCallback(roomId)` before subscribing — without it the emitter on a resumed room
935
- never fires.
936
-
937
- ## Data Storage
938
-
939
- Briyah stores data in the following structure:
940
-
941
- ```
942
- {dataPath}/
943
- ├── common/ # Shared across all users
944
- │ ├── config/ # LLM pricing and image-model config
945
- │ ├── prompts/ # Global prompt templates
946
- │ └── published-agents.json # Published agent mappings
947
- └── user/
948
- └── {userId}/ # Per-user data
949
- ├── agents/ # Agent configs and histories (one JSON per agent)
950
- ├── rooms/ # Room metadata, message logs, artifacts (one folder per room)
951
- ├── stories/ # Story state
952
- ├── tools/ # User-defined tools (one JSON per tool)
953
- ├── prompts/ # User-specific prompts
954
- ├── upload/ # User file attachments
955
- ├── transactions/ # Transaction records
956
- └── userconfig/ # User preferences and balance
957
- ```
958
-
959
- ## Multi-Instance Support
960
-
961
- You can create multiple Briyah instances with different configurations:
962
-
963
- ```typescript
964
- const briyah1 = new Briyah({ dataPath: './data1' });
965
- const briyah2 = new Briyah({ dataPath: './data2' });
966
-
967
- await briyah1.init();
968
- await briyah2.init();
969
-
970
- // Each instance has isolated data
971
- const user1Service = briyah1.getAppService('user-123');
972
- const user2Service = briyah2.getAppService('user-123');
973
- // These are completely separate services with different data paths
974
- ```
975
-
976
- **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.
977
-
978
- ## Troubleshooting
979
-
980
- ### "Must call init() before getAppService()"
981
-
982
- Make sure to call `await briyah.init()` before calling `getAppService()`.
983
-
984
- ### "No LLM provider API keys configured"
985
-
986
- Set at least one of the required API key environment variables (ANTHROPIC_API_KEY, OPENAI_API_KEY, etc.).
987
-
988
- ### "STARTING_BALANCE environment variable is required"
989
-
990
- Set the `STARTING_BALANCE` environment variable or pass `startingBalance` in the constructor options.
991
-
992
- ### Cache not working as expected
993
-
994
- 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
+ ## Upgrading to 2.0
71
+
72
+ 2.0 moves the D&D content into a **pack**. Three things change for a host coming from 1.5; the
73
+ first two are a line each, and the third is something to know about your data directory.
74
+
75
+ **The D&D prompt folders are now the pack's.** `dungeon_master`, `dnd_player`,
76
+ `character_creator`, `campaign_designer` and `dnd_room_moderator` belong to `dnd5e`. Enable the
77
+ pack for the user, and qualify the folder name:
78
+
79
+ ```typescript
80
+ app.packs.setEnabled('dnd5e', true); // per user, and required
81
+ await app.createAgentFromFolder({ folder: 'dnd5e:dungeon_master', /* ... */ });
82
+ ```
83
+
84
+ A bare `dungeon_master` also reaches the pack once it is enabled, so enabling alone is enough if
85
+ you would rather not touch the strings. Doing neither is what breaks: in 1.5 those folders sat in
86
+ `common/prompts` and the bare name resolved, and in 2.0 it falls through to the shared root
87
+ prompts instead. `createAgentFromFolder` now refuses that rather than building a generic agent
88
+ from it — see [Prompt Folders](#prompt-folders).
89
+
90
+ **`enabledToolPacks` is gone**, replaced by `installToolPacks`. Most hosts can delete the call
91
+ entirely: the `Briyah` constructor installs every bundled pack's tools already. `BRIYAH_TOOL_PACKS`
92
+ no longer does anything either, and is not read.
93
+
94
+ **`init()` rewrites two things under your data path.** Both are stated here because neither is
95
+ visible until it has happened:
96
+
97
+ - `{dataPath}/packs/<bundled pack>/` is **deleted and re-copied on every init**. A pack's
98
+ directory is package-canonical, so a host that hand-edits `packs/dnd5e/` loses those edits on
99
+ the next boot. Edit it as a user instead — the change lands in
100
+ `{dataPath}/user/<userId>/packs/dnd5e/`, an overlay that takes precedence — or install your own
101
+ pack under a name Briyah does not bundle, which is never touched.
102
+ - Any `common/prompts/<folder>` whose name a pack now owns is **moved** to
103
+ `{dataPath}/retired-prompts/<folder>`, and the move is logged as a warning. On a 1.5 data
104
+ directory that is the five D&D folders. Moved rather than deleted because a leftover copy
105
+ outranks the pack for a bare name and would silently shadow it. Nothing reads
106
+ `retired-prompts/`: keep it if you had local edits worth porting into an overlay, delete it
107
+ otherwise.
108
+
109
+ ## Configuration
110
+
111
+ ### BriyahConfigOptions
112
+
113
+ ```typescript
114
+ interface BriyahConfigOptions {
115
+ /**
116
+ * Base directory for Briyah data storage
117
+ * Default: './briyah-data' relative to process.cwd()
118
+ */
119
+ dataPath?: string;
120
+
121
+ /**
122
+ * Timeout in minutes for cached user services
123
+ * Default: 30 minutes
124
+ */
125
+ userServiceCacheTimeoutMinutes?: number;
126
+
127
+ /**
128
+ * Starting balance for new users (in dollars)
129
+ * Default: value from process.env.STARTING_BALANCE
130
+ */
131
+ startingBalance?: number;
132
+
133
+ /**
134
+ * Native tools to register up front (equivalent to calling registerTool
135
+ * for each). See Example 8.
136
+ */
137
+ tools?: NativeToolDefinition[];
138
+
139
+ /**
140
+ * Allow end users to author and run their own JS-string tools. Native tools
141
+ * are unaffected. Leave off for untrusted multi-user hosts. Default: false.
142
+ */
143
+ allowUserAuthoredTools?: boolean;
144
+
145
+ /**
146
+ * Override environment variables
147
+ * Useful for testing or multi-instance configurations
148
+ */
149
+ envOverrides?: Record<string, string>;
150
+ }
151
+ ```
152
+
153
+ ### Environment Variables
154
+
155
+ **LLM Provider API Keys** (at least one required):
156
+ - `ANTHROPIC_API_KEY` - For Claude models
157
+ - `OPENAI_API_KEY` - For GPT models
158
+ - `GOOGLE_GENAI_API_KEY` - For Google AI (Gemini) models
159
+ - `XAI_API_KEY` - For Grok models
160
+ - `DEEPSEEK_API_KEY` - For DeepSeek models
161
+ - `TOGETHER_API_KEY` - For Together AI models
162
+ - `FAL_API_KEY` - For Fal image-generation models
163
+
164
+ **Self-hosted providers** (optional, count toward the "at least one" requirement):
165
+ - `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`
166
+ - `SELF_HOSTED_API_KEY` - Optional bearer token for the above
167
+ - `COMFYUI_BASE_URL` - ComfyUI server for the `ComfyUI` image provider, no trailing slash, e.g. `http://gpu-box:8188` (see Example 9)
168
+ - `COMFYUI_EXTRA_HEADERS` - Optional JSON object of headers sent on every ComfyUI request, e.g. `{"Authorization":"Basic ..."}` for a reverse proxy
169
+ - `COMFYUI_TIMEOUT_MS` - Total wait for a queued generation, default `600000` (covers queue wait and model cold start)
170
+ - `COMFYUI_POLL_INTERVAL_MS` - Poll interval while waiting, default `2000`
171
+
172
+ **Optional:**
173
+ - `STARTING_BALANCE` - Starting balance for new users (e.g., "10.00")
174
+ - `BRIYAH_DATA_PATH` - Global default data path (overridden by constructor `dataPath`)
175
+ - `USER_SERVICE_CACHE_TIMEOUT_MINUTES` - Cache timeout (overridden by constructor option)
176
+ - `ALLOW_USER_AUTHORED_TOOLS` - `"true"` to let users author/run their own tools (overridden by the `allowUserAuthoredTools` option). Default off.
177
+
178
+ **Retired:**
179
+ - `BRIYAH_TOOL_PACKS` - Read in 1.5 to choose which tool packs to register. It is not read in
180
+ 2.0 and setting it does nothing. Every bundled pack's tools are registered at construction;
181
+ what a user can reach is decided by pack enablement and per-agent tool grants. See [Packs](#packs).
182
+
183
+ ### Logging
184
+
185
+ Briyah writes logs to `{dataPath}/logs/briyah.log` by default. Configure or disable via the `logging` option:
186
+
187
+ ```typescript
188
+ const briyah = new Briyah({
189
+ dataPath: './my-data',
190
+ logging: {
191
+ enabled: true, // default
192
+ logFile: './my-data/logs/app.log', // default: {dataPath}/logs/briyah.log
193
+ console: false, // set true to also log to stdout/stderr
194
+ level: 'warn', // 'debug' | 'log' | 'warn' | 'error' — default: 'log'
195
+ }
196
+ });
197
+
198
+ // Log to console only (no file):
199
+ const briyah = new Briyah({ logging: { console: true, logFile: null } });
200
+
201
+ // Disable logging entirely:
202
+ const briyah = new Briyah({ logging: { enabled: false } });
203
+ ```
204
+
205
+ ## API Reference
206
+
207
+ ### Briyah Class
208
+
209
+ #### constructor(options?: BriyahConfigOptions)
210
+
211
+ Creates a new Briyah SDK instance.
212
+
213
+ ```typescript
214
+ const briyah = new Briyah({
215
+ dataPath: './briyah-data',
216
+ startingBalance: 10.00
217
+ });
218
+ ```
219
+
220
+ #### async init(): Promise\<void\>
221
+
222
+ Initializes the Briyah system. Must be called before using `getAppService()`.
223
+
224
+ ```typescript
225
+ await briyah.init();
226
+ ```
227
+
228
+ #### getAppService(userId: string): AppService
229
+
230
+ Gets the AppService instance for a specific user. The AppService provides full access to:
231
+ - Agent management
232
+ - Room conversations
233
+ - Story generation
234
+ - Text processing
235
+ - File attachments
236
+
237
+ ```typescript
238
+ const appService = briyah.getAppService('user-123');
239
+ ```
240
+
241
+ **Throws:** Error if `init()` has not been called.
242
+
243
+ #### removeUserService(userId: string): void
244
+
245
+ Manually removes a user's service from the cache. Useful for:
246
+ - Forcing a fresh AppService instance
247
+ - Cleaning up when a user logs out
248
+
249
+ ```typescript
250
+ briyah.removeUserService('user-123');
251
+ ```
252
+
253
+ #### getCacheStats()
254
+
255
+ Returns statistics about cached user services.
256
+
257
+ ```typescript
258
+ const stats = briyah.getCacheStats();
259
+ console.log(`Cached users: ${stats.cachedUsers}`);
260
+ ```
261
+
262
+ #### async shutdown(): Promise\<void\>
263
+
264
+ Shuts down the Briyah system and cleans up resources.
265
+
266
+ ```typescript
267
+ await briyah.shutdown();
268
+ ```
269
+
270
+ #### isInitialized(): boolean
271
+
272
+ Checks if Briyah has been initialized.
273
+
274
+ ```typescript
275
+ if (briyah.isInitialized()) {
276
+ const appService = briyah.getAppService('user-123');
277
+ }
278
+ ```
279
+
280
+ ### AppService
281
+
282
+ The AppService provides full access to Briyah functionality.
283
+
284
+ **Common operations:**
285
+
286
+ ```typescript
287
+ // Agent Management
288
+ const agent = appService.createAgent(provider, name, nickname, description, model);
289
+ const agents = await appService.listAgents();
290
+ await appService.deleteAgent(agentId);
291
+ await appService.reloadAgent(agentId); // Clear conversation history (keeps any prior summary)
292
+ await appService.compactAgentConversation(agentId); // Summarize history into a single message
293
+
294
+ // Room Management
295
+ // roomLeader answers anything the room cannot place; turnMode 'directed' asks only the
296
+ // agent a message names ('broadcast', the default, asks every agent every time);
297
+ // moderator is only needed when no agent leads the turn order.
298
+ const room = await appService.createRoom(
299
+ name, goal, agentIds, roomLeader?, turnMode?, moderator?,
300
+ );
301
+ const rooms = await appService.listRooms();
302
+ const details = await appService.getRoomDetails(roomId);
303
+ // action defaults to 'moderate'. Returns {accepted, reason} — a message sent out of
304
+ // turn is refused, not thrown. `sender` must be an agentNickname.
305
+ await appService.sendRoomMessage(roomId, content, sender, action?, targets?);
306
+ // Required before subscribing to a room this process did not create.
307
+ await appService.ensureRoomStateCallback(roomId);
308
+ const emitter = appService.getRoomMessageEmitter(roomId); // 'update' events
309
+
310
+ // Prompt folder defaults — the role's name, tools and documents, as the create-agent
311
+ // dialog would fill them in. Read these rather than hard-coding a pack's tool names.
312
+ // `exists` is false for a folder nothing ships, which otherwise looks identical to a
313
+ // folder that declares no defaults.
314
+ const { defaults, exists } = appService.getPromptFolderDefaults('dnd5e:dungeon_master');
315
+ appService.promptFolderExists('dnd5e:dungeon_master'); // the same question, alone
316
+
317
+ // Or let the folder build the agent: applies those defaults, saves, and attaches the
318
+ // folder's documents. Async (attaching is), unlike createAgent. `overrides` takes the
319
+ // same shape as the defaults; pass `attachDocuments: false` to decline the documents.
320
+ const agent = await appService.createAgentFromFolder({
321
+ folder: 'dnd5e:dungeon_master', aiServiceName: 'Anthropic', aiModel: 'claude-sonnet-5',
322
+ });
323
+
324
+ // Agents that belong to a room: created inside it, named after it, deleted with it,
325
+ // and left out of listAgents(). agentName is the bare name; the room's is prefixed on.
326
+ await appService.createRoomAgent(roomId, { aiServiceName, agentName, description, aiModel, promptName });
327
+ await appService.removeRoomAgent(roomId, agentId);
328
+
329
+ // Native tools (recommended for SDK integrations — see Example 8)
330
+ briyah.registerTool({ name, description, parameters, handler }); // process-level
331
+ briyah.listNativeTools();
332
+
333
+ // User-authored (string-code) tools — only when allowUserAuthoredTools is enabled
334
+ const tools = await appService.listTools();
335
+ const tool = await appService.createTool({ name, description, parameters, code, timeoutMs? });
336
+ await appService.updateTool(name, tool);
337
+ await appService.deleteTool(name);
338
+ const result = await appService.testTool(name, args); // { ok: true, result } | { ok: false, error }
339
+
340
+ // Story Management
341
+ // illustrateStory is required and positional — it is the fifth argument, not an option.
342
+ const story = await appService.createStory(
343
+ name, idea, userCharacterDesc, otherCharactersDesc, illustrateStory,
344
+ storyModel?, isImport?, imageModelName?, skipDetailedPlot?,
345
+ );
346
+ await appService.progressStory(storyId);
347
+
348
+ // Text Processing
349
+ const result = await appService.processText(agentId, text);
350
+
351
+ // Image Generation (image-capable providers; called on the Agent object — see Example 9)
352
+ const { artifactId } = await agent.generateImage(prompt, imageProperties);
353
+ const edited = await agent.editImage(prompt, imageProperties, referenceArtifactIds);
354
+
355
+ // File Attachments
356
+ const attachment = await appService.attachDocument(agentId, fileName, fileData);
357
+ await appService.deleteAttachedFile(agentId, fileName); // by filename
358
+ await appService.deleteAttachedFileById(documentId); // by document ID
359
+ ```
360
+
361
+ ## Prompt Folders
362
+
363
+ An agent's behaviour comes from a **prompt folder**, not from its description. The folder
364
+ holds the templates the room renders on every turn — most importantly `perceive.prompt`, which
365
+ tells the agent what it is and what it may do, and `perceive.json`, the JSON schema its replies
366
+ must satisfy. Two agents on the same model with the same description behave completely
367
+ differently if they were built from different folders.
368
+
369
+ `init()` seeds the shared folders into `{dataPath}/common/prompts/`, so they are on disk before
370
+ your first `createAgent` call. Existing files are preserved on upgrade, so anything you edit
371
+ survives.
372
+
373
+ A folder can also come from a **pack** — a domain's prompts, documents, tools and templates in
374
+ one directory. A pack's folders are referenced **pack-qualified**, and they are only listed once
375
+ the user has that pack enabled:
376
+
377
+ ```typescript
378
+ const appService = briyah.getAppService('user-123');
379
+ console.log(appService.listPromptFolders());
380
+ // default, narrator, character, illustrator, pdf_converter, room_moderator, ...
381
+
382
+ appService.packs.setEnabled('dnd5e', true);
383
+ console.log(appService.listPromptFolders());
384
+ // ... plus dnd5e:dungeon_master, dnd5e:dnd_player, dnd5e:character_creator,
385
+ // dnd5e:campaign_designer, dnd5e:battle_master, dnd5e:dnd_room_moderator
386
+ ```
387
+
388
+ See [Packs](#packs) — **if you are building on `dnd5e` you have to enable it first**, or a bare
389
+ folder name will not reach it.
390
+
391
+ ### When a folder name is wrong
392
+
393
+ A prompt lookup always ends at the shared root prompts, so a folder that does not exist does not
394
+ fail — it produces a working, generic agent. Three things now say so instead:
395
+
396
+ ```typescript
397
+ appService.promptFolderExists('dnd5e:dungeon_master'); // false if the pack is not installed
398
+ const { defaults, exists } = appService.getPromptFolderDefaults('dungeon_master');
399
+ // exists distinguishes "no such folder" from "a folder that declares no defaults":
400
+ // both give you `defaults: {}`. A bare pack folder reports false until the pack is enabled.
401
+ ```
402
+
403
+ - `createAgentFromFolder` and `createRoomAgentFromFolder` **throw** a `NotFoundError` naming the
404
+ folder. The whole point of those calls is the folder's recipe — its tools, its documents, its
405
+ nickname — and a folder that is not there has none.
406
+ - `createAgent` **warns** and carries on, since it takes all of that from its arguments and the
407
+ folder is only one of them. The warning is in `{dataPath}/logs/briyah.log`.
408
+
409
+ **The folder is the sixth argument to `createAgent`, and it defaults to `'default'`** — a
410
+ generic conversational agent. Passing a role folder is what makes the agent that role:
411
+
412
+ ```typescript
413
+ const dm = appService.createAgent(
414
+ 'Anthropic',
415
+ 'Dungeon Master', // agentName — a label; used in logs and the UI
416
+ 'DM', // agentNickname — the name the room routes by
417
+ 'Runs the game.',
418
+ 'claude-sonnet-5',
419
+ 'dnd5e:dungeon_master', // <- the prompt folder
420
+ );
421
+ ```
422
+
423
+ `agentNickname` is the identity: messages are addressed to it, artifact viewers are lists of
424
+ it, and it is what an agent writes into `targets`. `agentName` is a label. Give a character the
425
+ nickname you want it called by.
426
+
427
+ To write your own folder, copy a bundled one out of `{dataPath}/common/prompts/` (or a pack's
428
+ `{dataPath}/packs/<pack>/prompts/`), rename the directory, and edit it — a folder in the user data
429
+ directory takes precedence over the common one of the same name. Editing a *pack's* file instead
430
+ writes a private copy under `{dataPath}/user/<userId>/packs/<pack>/`, so one user's change does
431
+ not reach the others.
432
+
433
+ ## Packs
434
+
435
+ A **pack** is one domain's prompt folders, documents, native tools, and agent and room templates
436
+ in a single directory. `dnd5e` is the one that ships: eighteen tools for dice, character sheets,
437
+ the rules engine and a bestiary, six prompt folders, sixteen rules documents, and a room template
438
+ that builds a whole table.
439
+
440
+ It exists so a domain arrives as a unit — and so **your** prompts live in your own directory
441
+ rather than beside Briyah's. Install one by copying a directory into `{dataPath}/packs/`; there is
442
+ no import mechanism and nothing to register.
443
+
444
+ ```
445
+ {dataPath}/packs/<name>/
446
+ ├── pack.json optional: title, description, version
447
+ ├── prompts/ folders, referenced as <name>:<folder>
448
+ ├── artifacts/ manifest.json + .md documents
449
+ ├── agents/ agent templates
450
+ └── rooms/ room templates
451
+ ```
452
+
453
+ ### Installed for everyone, enabled per user
454
+
455
+ Tools register process-wide when you construct `Briyah`. Enabling is **per user**, and it is what
456
+ makes a pack's prompt folders resolve by bare name, its documents appear in `listUserArtifacts()`,
457
+ and its tools grantable:
458
+
459
+ ```typescript
460
+ const appService = briyah.getAppService('user-123');
461
+
462
+ appService.packs.listPacks();
463
+ // [{
464
+ // name: 'dnd5e', // <- the id; `title` is for display
465
+ // title: 'D&D 5th Edition',
466
+ // description: 'Run a fifth-edition tabletop game in a room: ...',
467
+ // version: '1.0.0',
468
+ // dir: '/srv/app/briyah-data/packs/dnd5e',
469
+ // origin: 'host', // 'host' installed it, or 'user' created it
470
+ // enabled: false,
471
+ // promptFolders: ['battle_master', 'campaign_designer', 'character_creator',
472
+ // 'dnd_player', 'dnd_room_moderator', 'dungeon_master'],
473
+ // agents: [{ key: 'dungeon_master', promptFolder: 'dungeon_master',
474
+ // label: 'Dungeon Master', modelRole: 'primary' }, ...],
475
+ // rooms: [{ key: 'table', name: 'D&D Table', goal: '...', turnMode: 'directed',
476
+ // agents: [{ key: 'table_moderator' }, ...],
477
+ // roomLeader: 'dungeon_master', moderator: 'table_moderator' }],
478
+ // documentCount: 16,
479
+ // requiresTools: ['apply_hp', 'check', 'roll_dice', ...], // derived from its grants
480
+ // requiresPacks: [],
481
+ // missingTools: [], // requiresTools this process has not registered
482
+ // missingPacks: [], // requiresPacks this user has not enabled
483
+ // }]
484
+ // The REST API returns a trimmed version of this (`pack` instead of `name`, and a
485
+ // `counts` object) — `listPacks()` in-process returns the `PackView` above.
486
+
487
+ appService.packs.setEnabled('dnd5e', true);
488
+ ```
489
+
490
+ **Do this before building anything on the pack.** A pack-qualified folder
491
+ (`dnd5e:dungeon_master`) always resolves, but a bare `dungeon_master` only reaches the pack when
492
+ it is enabled — otherwise it falls back to the shared root prompts and you get a generic
493
+ conversational agent with no error to tell you.
494
+
495
+ Disabling later **hides** rather than switches off: the pack leaves the listings, but a room that
496
+ already exists keeps working, an attached document still loads, and a granted tool still runs.
497
+
498
+ If you would rather filter or wrap the tool definitions than take them all:
499
+
500
+ ```typescript
501
+ import { dnd5eTools, availableToolPacks } from 'briyah';
502
+ const briyah = new Briyah({ tools: dnd5eTools() });
503
+ console.log(availableToolPacks()); // ['dnd5e']
504
+ ```
505
+
506
+ ### Building a room from a template
507
+
508
+ The fastest path to a working table, and the one that gets the details right — the moderator is
509
+ created before the agents that need one, the leader and moderator are resolved to the nicknames
510
+ the created agents actually ended up with, and a failure rolls the whole room back:
511
+
512
+ ```typescript
513
+ const { roomId, agentIds, warnings } = await appService.packInstantiation.instantiateRoom(
514
+ 'dnd5e',
515
+ 'table',
516
+ {
517
+ primary: { aiServiceName: 'Anthropic', aiModel: 'claude-sonnet-5' },
518
+ economy: { aiServiceName: 'Anthropic', aiModel: 'claude-haiku-4-5-20251001' },
519
+ },
520
+ 'Tuesday Night Game', // optional; auto-suffixed if the name is taken
521
+ // optional; per-agent overrides, keyed by the template's own key for the seat
522
+ { player: { agentName: 'Homer', agentNickname: 'Homer' } },
523
+ );
524
+ ```
525
+
526
+ That is a six-agent room with `turnMode: 'directed'`, the Dungeon Master as leader, a table
527
+ moderator, and every agent already carrying its tool grants and rules documents.
528
+
529
+ **Naming the player.** The template's player seat ships as `PlayerOne`, which is not what the
530
+ person at the keyboard is called. The fifth argument changes any seat: the keys are the room
531
+ template's `agents[].key` (`table_moderator`, `dungeon_master`, `battle_master`,
532
+ `character_creator`, `campaign_designer`, `player` for `dnd5e:table`), and the value is the same
533
+ `PromptFolderDefaults` shape as a folder's own defaults, applied over them. A key no seat has is
534
+ refused before the room is created, rather than quietly doing nothing.
535
+
536
+ **More than one player.** The template seats one. Add the others afterwards with
537
+ `createRoomAgentFromFolder`, which is the same call instantiation makes per agent — a room-owned
538
+ agent, named after the room, deleted with it:
539
+
540
+ ```typescript
541
+ await appService.createRoomAgentFromFolder(roomId, {
542
+ folder: 'dnd5e:dnd_player',
543
+ aiServiceName: 'Anthropic',
544
+ aiModel: 'claude-haiku-4-5-20251001',
545
+ overrides: { agentName: 'Vex', agentNickname: 'Vex', description: 'A wary scout.' },
546
+ pack: 'dnd5e', // files it under the pack, so it hides and lists with one
547
+ packAgentKey: 'player', // records which template it came from
548
+ });
549
+ ```
550
+
551
+ Do it after `instantiateRoom` returns, not during: the room already has its moderator by then, so
552
+ a player carrying `useModerator: true` has one to route through.
553
+
554
+ A template names a **role** rather than a model — `primary` or `economy` — because a model id goes
555
+ stale and assumes your provider keys. The Dungeon Master takes the primary; the agents that do
556
+ bookkeeping rather than prose take the economy one. Omit `economy` and everything uses the
557
+ primary. `warnings` reports anything that did not go to plan without stopping the room, such as a
558
+ document that failed to attach; it is worth logging, because a missing document is a capability
559
+ the agent appears to have and does not.
560
+
561
+ For a single agent, with no room:
562
+
563
+ ```typescript
564
+ const { agentId } = await appService.packInstantiation.instantiateAgent(
565
+ 'dnd5e',
566
+ 'character_creator',
567
+ { primary: { aiServiceName: 'Anthropic', aiModel: 'claude-sonnet-5' } },
568
+ );
569
+ ```
570
+
571
+ ### Building the same room by hand
572
+
573
+ If you want the pieces rather than the template, registering a pack makes its tools *grantable*,
574
+ not granted. An agent may only run the ones named in its `toolNames`:
575
+
576
+ ```typescript
577
+ const dm = appService.createAgent(
578
+ 'Anthropic', 'Dungeon Master', 'DM', 'Runs the game.', 'claude-sonnet-5',
579
+ 'dnd5e:dungeon_master', // <- pack-qualified
580
+ undefined, null, 0, '',
581
+ { toolNames: ['roll_dice', 'check', 'apply_hp', 'stat_block', 'read_sheet'] },
582
+ );
583
+ ```
584
+
585
+ A pack's **documents** are read-only rules text an agent carries in every call. They live in
586
+ `{dataPath}/packs/<pack>/artifacts/`, appear in `listUserArtifacts()` once the pack is enabled,
587
+ and attach by an id that never changes:
588
+
589
+ ```typescript
590
+ await appService.attachArtifactToAgent(dm.id, 'pack:dnd5e.dungeon_master-procedure');
591
+ await appService.attachArtifactToAgent(player.id, 'pack:dnd5e.class-bard');
592
+ ```
593
+
594
+ A document sits in that agent's cached prompt prefix on every call, so attach what it needs and
595
+ nothing more. `src/tools/packs/dnd5e/README.md` in this package lists all eighteen tools and which
596
+ agent each document belongs to.
597
+
598
+ ## Usage Examples
599
+
600
+ ### Example 1: Multi-User Setup
601
+
602
+ ```typescript
603
+ import { Briyah } from 'briyah';
604
+
605
+ // Initialize once at application startup
606
+ const briyah = new Briyah({
607
+ dataPath: './data/briyah',
608
+ startingBalance: 10.00
609
+ });
610
+
611
+ await briyah.init();
612
+
613
+ // In your route handler or service
614
+ async function handleUserRequest(userId: string, message: string) {
615
+ const appService = briyah.getAppService(userId);
616
+
617
+ // Each user gets their own isolated AppService
618
+ const agents = await appService.listAgents();
619
+
620
+ // ... process user request
621
+ }
622
+
623
+ // Cleanup at application shutdown
624
+ process.on('SIGINT', async () => {
625
+ await briyah.shutdown();
626
+ process.exit(0);
627
+ });
628
+ ```
629
+
630
+ ### Example 2: Custom Data Path
631
+
632
+ ```typescript
633
+ import { Briyah } from 'briyah';
634
+ import path from 'path';
635
+
636
+ const briyah = new Briyah({
637
+ dataPath: path.join(__dirname, '..', 'user-data', 'briyah'),
638
+ userServiceCacheTimeoutMinutes: 60 // 1 hour cache
639
+ });
640
+
641
+ await briyah.init();
642
+ ```
643
+
644
+ ### Example 3: Testing Configuration
645
+
646
+ ```typescript
647
+ import { Briyah } from 'briyah';
648
+
649
+ const testBriyah = new Briyah({
650
+ dataPath: './test-data',
651
+ startingBalance: 100.00,
652
+ userServiceCacheTimeoutMinutes: 5,
653
+ envOverrides: {
654
+ ANTHROPIC_API_KEY: process.env.TEST_ANTHROPIC_KEY,
655
+ OPENAI_API_KEY: process.env.TEST_OPENAI_KEY
656
+ }
657
+ });
658
+
659
+ await testBriyah.init();
660
+
661
+ // Run tests...
662
+
663
+ await testBriyah.shutdown();
664
+ ```
665
+
666
+ ### Example 4: Agent Creation and Text Processing
667
+
668
+ ```typescript
669
+ const appService = briyah.getAppService('user-123');
670
+
671
+ // Create an agent
672
+ const agent = appService.createAgent(
673
+ 'Anthropic', // provider
674
+ 'AI Assistant', // name
675
+ 'James', // nickname
676
+ 'A helpful AI assistant', // description
677
+ 'claude-haiku-4-5' // model
678
+ );
679
+
680
+ if (!agent.id) throw new Error('Agent creation failed');
681
+ console.log(`Created agent: ${agent.id}`);
682
+
683
+ // Process text with the agent
684
+ const result = await appService.processText(
685
+ agent.id,
686
+ 'What is the capital of France?'
687
+ );
688
+
689
+ console.log(`Response: ${result.result}`);
690
+ console.log(`Cost: $${result.totalCost}`);
691
+ console.log(`Tokens: ${(result.totalInputTokens ?? 0) + (result.totalOutputTokens ?? 0)}`);
692
+ ```
693
+
694
+ ### Example 5: Multi-Agent Room Conversation
695
+
696
+ ```typescript
697
+ const appService = briyah.getAppService('user-123');
698
+
699
+ // Create agents
700
+ const analyst = appService.createAgent('OpenAI', 'Analyst', 'Analyst', 'Data analyst', 'gpt-4');
701
+ const writer = appService.createAgent('Anthropic', 'Writer', 'Writer', 'Content writer', 'claude-haiku-4-5');
702
+
703
+ if (!analyst.id || !writer.id) throw new Error('Agent creation failed');
704
+
705
+ // Create a room with both agents
706
+ const room = await appService.createRoom(
707
+ 'Analysis Session',
708
+ 'Analyze sales data and produce a written summary',
709
+ [analyst.id, writer.id]
710
+ );
711
+
712
+ // Send a message to start the conversation
713
+ await appService.sendRoomMessage(
714
+ room.roomId,
715
+ 'Please analyze the sales data for Q4',
716
+ 'Analyst',
717
+ 'speak'
718
+ );
719
+
720
+ // The agents will automatically respond and interact
721
+ // Check room messages to see the conversation
722
+ const messages = await appService.getRoomMessages(room.roomId);
723
+ console.log(`Messages: ${messages.messages.length}`);
724
+ ```
725
+
726
+ ### Example 6: Story Message Emitter
727
+
728
+ 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.
729
+
730
+ ```typescript
731
+ import type {
732
+ StoryStateEvent,
733
+ StoryIntroduceCharacterEvent,
734
+ StoryProgressChapterEvent,
735
+ StoryErrorEvent,
736
+ } from 'briyah';
737
+
738
+ const app = briyah.getAppService('user-123');
739
+
740
+ const story = await app.createStory(
741
+ 'The Lost Kingdom',
742
+ 'A medieval fantasy where ancient ruins hold a terrible secret',
743
+ 'A disgraced knight seeking redemption',
744
+ 'A scholar and a sellsword',
745
+ false, // illustrateStory — required, and positional
746
+ );
747
+
748
+ const emitter = app.getStoryMessageEmitter(story.id);
749
+
750
+ // Fires after every turn with the full updated game state.
751
+ emitter.on('story-state', async (event: StoryStateEvent) => {
752
+ const { state } = event;
753
+ console.log('Latest message:', state.latestRoomMessage?.content);
754
+
755
+ // Detect the player's turn by comparing speaker names.
756
+ // Do NOT use state.humanPrompt for this — it is a UI display string,
757
+ // not a reliable turn indicator.
758
+ if (state.currentSpeaker === state.userAgentName) {
759
+ const input = await promptPlayer(state.humanPrompt);
760
+ await app.respondToStory(story.id, input);
761
+ }
762
+ });
763
+
764
+ // Fires when the narrator wants to introduce a new character.
765
+ // The host app should present this to the player before acting.
766
+ // Accept by calling introduceCharacterToStory, or decline with declineCharacter.
767
+ emitter.on('suggest-introduce-character', async (event: StoryIntroduceCharacterEvent) => {
768
+ const accept = await askPlayer(`Add ${event.characterName} to the story?`);
769
+ if (accept) {
770
+ await app.introduceCharacterToStory(story.id, event.characterName!, '', undefined, true);
771
+ } else {
772
+ await app.declineCharacter(story.id, event.characterName!);
773
+ }
774
+ });
775
+
776
+ // Fires when the narrator wants to advance to the next chapter.
777
+ // Call progressStory to accept. Ignoring the event stays in the current chapter —
778
+ // there is no explicit rejection call.
779
+ emitter.on('suggest-progress-chapter', async (_event: StoryProgressChapterEvent) => {
780
+ const accept = await askPlayer('The narrator suggests ending this chapter. Continue?');
781
+ if (accept) {
782
+ await app.progressStory(story.id);
783
+ }
784
+ });
785
+
786
+ // Fires on fatal errors during room processing.
787
+ // Named 'story-error' rather than 'error' to avoid Node.js throwing when no
788
+ // listener is attached.
789
+ emitter.on('story-error', (event: StoryErrorEvent) => {
790
+ if (event.errorType === 'InsufficientBalanceError') {
791
+ console.error('Out of credits:', event.message);
792
+ } else {
793
+ console.error(`Story error [${event.errorType}]:`, event.message);
794
+ }
795
+ });
796
+ ```
797
+
798
+ ### Example 7: Recording Payments and Managing Balance
799
+
800
+ 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.
801
+
802
+ ```typescript
803
+ const app = briyah.getAppService(userId);
804
+
805
+ // --- When your payment provider initiates a charge ---
806
+ // Record it as pending so the transaction log stays consistent.
807
+ await app.recordTransaction(amount, paymentIntentId, 'pending');
808
+
809
+ // --- When your payment provider webhook confirms success ---
810
+ await app.updateTransactionStatus(paymentIntentId, 'succeeded');
811
+ await app.addBalance(amount);
812
+
813
+ // Resume any stories that paused mid-turn due to InsufficientBalanceError.
814
+ await app.resumePausedStories();
815
+
816
+ // --- When a payment fails or is cancelled ---
817
+ await app.updateTransactionStatus(paymentIntentId, 'failed');
818
+
819
+ // --- Querying balance and history ---
820
+ const balance = app.getBalance();
821
+
822
+ const { transactions, total } = await app.getTransactions(50, 0);
823
+
824
+ const tx = await app.getTransactionByPaymentId(paymentIntentId);
825
+ console.log(tx?.status); // 'pending' | 'succeeded' | 'failed' | 'cancelled'
826
+ ```
827
+
828
+ To push real-time balance updates to a connected client (e.g. via SSE), subscribe to the balance emitter before crediting the user:
829
+
830
+ ```typescript
831
+ const emitter = app.getBalanceMessageEmitter(userId);
832
+ emitter.on('update', (newBalance: number) => {
833
+ // Push newBalance to the client
834
+ });
835
+ ```
836
+
837
+ ### Example 8: Registering Native Tools with Opaque Context
838
+
839
+ 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.
840
+
841
+ 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.
842
+
843
+ ```typescript
844
+ import { Briyah } from 'briyah';
845
+
846
+ const briyah = new Briyah({ dataPath: './data/briyah', startingBalance: 10.00 });
847
+ await briyah.init();
848
+
849
+ // Register a tool that reads its scope from context, not from the LLM's args.
850
+ briyah.registerTool({
851
+ name: 'add_note',
852
+ description: "Add a note to the record the user currently has open",
853
+ parameters: [
854
+ { name: 'text', type: 'string', description: 'The note text', required: true }
855
+ ],
856
+ handler: async (args, helpers, context) => {
857
+ const { db, recordId } = context as { db: MyDb; recordId: string };
858
+ await db.addNote(recordId, args.text); // recordId comes from context — the LLM cannot set it
859
+ return { added: true };
860
+ },
861
+ timeoutMs: 15000 // optional; default 30s, max 120s
862
+ });
863
+
864
+ // Grant it to an agent (grants are enforced server-side).
865
+ const assistant = app.createAgent('Anthropic', 'Assistant', 'Assistant',
866
+ 'A helpful assistant that manages the open record', 'claude-haiku-4-5');
867
+ assistant.toolNames = ['add_note'];
868
+ assistant.save();
869
+
870
+ // When the user acts on record "rec_42", pass that scope as context. Any tool the
871
+ // agent calls during the resulting turn receives it; other rooms/interactions are
872
+ // unaffected. A log-only 'tool' message records each call (visible when fetching
873
+ // messages with includeThoughts=true).
874
+ await app.sendRoomMessage(
875
+ roomId,
876
+ 'Add a note that the client called about renewal.',
877
+ 'User',
878
+ 'speak',
879
+ [],
880
+ false,
881
+ { db, recordId: 'rec_42' } // opaque context
882
+ );
883
+ ```
884
+
885
+ 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.
886
+
887
+ 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.
888
+
889
+ User-authored (string-code) tools remain available via `createTool`/`updateTool`/`testTool` when `allowUserAuthoredTools` is enabled, for trusted single-user setups.
890
+
891
+ ### Example 9: Self-Hosted Image Generation with ComfyUI
892
+
893
+ 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`).
894
+
895
+ For this provider the agent's *model name* selects a **workflow-template pair**, not a checkpoint. Two pairs ship by default:
896
+
897
+ | Pair name | Model | Files required on the ComfyUI server |
898
+ |---|---|---|
899
+ | `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` |
900
+ | `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` |
901
+
902
+ `flux2-dev` has substantially better multi-reference character consistency and wants a 32 GB-class GPU; `flux-kontext` runs on 16 GB-class cards.
903
+
904
+ ```typescript
905
+ import { Briyah } from 'briyah';
906
+
907
+ const briyah = new Briyah({ dataPath: './data/briyah', startingBalance: 10.00 });
908
+ await briyah.init();
909
+
910
+ const app = briyah.getAppService('user-123');
911
+
912
+ // Model name = workflow pair name
913
+ const artist = app.createAgent('ComfyUI', 'Artist', 'Artist',
914
+ 'Image generation agent', 'flux2-dev');
915
+
916
+ // Text-to-image. Resolves to { artifactId } on success or { error } on failure.
917
+ const generated = await artist.generateImage(
918
+ 'A lighthouse on a rocky coast at dusk',
919
+ { width: 1024, height: 1024 } // optional; a fixed seed may also be passed
920
+ );
921
+ if (generated.error) throw new Error(String(generated.error));
922
+
923
+ // Generated images are stored as artifacts (PNG)
924
+ const png = artist.artifactService.getArtifact(generated.artifactId);
925
+
926
+ // Image-to-image with reference images. Each referenced artifact is uploaded
927
+ // and conditioned on separately (chained ReferenceLatent nodes). Order is
928
+ // preserved, so the prompt can refer to "Image 1", "Image 2", ...
929
+ const edited = await artist.editImage(
930
+ 'The character from Image 2 stands in the setting from Image 1',
931
+ { width: 1024, height: 1024 },
932
+ [sceneArtifactId, portraitArtifactId]
933
+ );
934
+ ```
935
+
936
+ Notes:
937
+
938
+ - **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.
939
+ - **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.
940
+ - **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`.
941
+
942
+ **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.
943
+
944
+ ### Example 10: A turn-based table with a human player
945
+
946
+ Example 5 sends one message and reads the transcript back, which suits a batch job. A game or
947
+ any human-in-the-loop app needs the other shape: the agents take several turns among themselves,
948
+ then stop and wait for the person. Three things make that work.
949
+
950
+ **`turnMode: 'directed'`** — only the agent a message names is asked to reply, and the room
951
+ leader answers anything it cannot place. The default, `'broadcast'`, prompts *every* agent for
952
+ *every* message and keeps one reply, which costs several times as much and is wrong for a table
953
+ where one person speaks at a time.
954
+
955
+ **A human-controlled agent** — `createAgent`'s seventh argument. The room delivers messages to
956
+ it and then stops rather than generating a reply, which is what yields the floor to your console.
957
+
958
+ **The room message emitter** — the only way to see the conversation as it happens. It fires on
959
+ every change with the newest message and the room's state.
960
+
961
+ ```typescript
962
+ import { Briyah } from 'briyah';
963
+ import type { RoomUpdate } from 'briyah';
964
+ import * as readline from 'node:readline/promises';
965
+
966
+ // The constructor installs every bundled pack's tools already; pass `tools` only to
967
+ // filter or wrap them, or to add your own.
968
+ const briyah = new Briyah({ dataPath: './briyah-data' });
969
+ await briyah.init(); // seeds prompt folders and the packs
970
+ const app = briyah.getAppService('user-123');
971
+
972
+ // Enable the pack for this user, or a bare folder name will not reach it. Enabling is
973
+ // per user; installing is not.
974
+ app.packs.setEnabled('dnd5e', true);
975
+
976
+ const dm = app.createAgent(
977
+ 'Anthropic', 'Dungeon Master', 'DM', 'Runs the game.', 'claude-sonnet-5',
978
+ 'dnd5e:dungeon_master', undefined, null, 0, '',
979
+ { toolNames: ['roll_dice', 'check', 'apply_hp', 'stat_block', 'read_sheet'] },
980
+ );
981
+ const rogue = app.createAgent(
982
+ 'Anthropic', 'Vex', 'Vex', 'A wary scout.', 'claude-haiku-4-5', 'dnd5e:dnd_player',
983
+ );
984
+ // The seventh argument is what makes this one wait for a person.
985
+ const you = app.createAgent(
986
+ 'Anthropic', 'Homer', 'Homer', 'A hopeful bard.', 'claude-haiku-4-5', 'dnd5e:dnd_player',
987
+ true,
988
+ );
989
+
990
+ // createAgent builds the agent in memory; save() writes it to disk. Without this the
991
+ // table exists for this process only and is gone on restart.
992
+ [dm, rogue, you].forEach((agent) => agent.save());
993
+
994
+ await app.attachArtifactToAgent(dm.id!, 'pack:dnd5e.dungeon_master-procedure');
995
+ await app.attachArtifactToAgent(rogue.id!, 'pack:dnd5e.class-rogue');
996
+ await app.attachArtifactToAgent(you.id!, 'pack:dnd5e.class-bard');
997
+
998
+ const { roomId } = await app.createRoom(
999
+ 'The Sunken Barrow',
1000
+ 'A three-room dungeon crawl.',
1001
+ [dm.id!, rogue.id!, you.id!],
1002
+ 'DM', // roomLeader — answers anything the room cannot place
1003
+ 'directed', // turnMode
1004
+ );
1005
+
1006
+ // A room loaded from disk has no state-change callback, so its emitter would never
1007
+ // fire. Harmless on a room you just created; required for one you resumed.
1008
+ await app.ensureRoomStateCallback(roomId);
1009
+
1010
+ const io = readline.createInterface({ input: process.stdin, output: process.stdout });
1011
+ let lastIndex = -1;
1012
+ let atKeyboard = false; // the handler is async; without this it re-enters
1013
+ let replyTo = 'DM'; // who last spoke to the player
1014
+ let replyAs: 'speak' | 'whisper' = 'speak';
1015
+
1016
+ app.getRoomMessageEmitter(roomId).on('update', async (state: RoomUpdate) => {
1017
+ if (state.type === 'error') { // a turn failed — see "Errors" below
1018
+ console.error(`[${state.errorType}] ${state.message}`);
1019
+ return;
1020
+ }
1021
+
1022
+ const message = state.latestMessage;
1023
+ if (message && state.messageIndex !== undefined && state.messageIndex > lastIndex) {
1024
+ lastIndex = state.messageIndex; // the emitter can repeat a state
1025
+ if (message.sender !== 'Homer') console.log(`${message.sender}: ${message.content}`);
1026
+ // Answer whoever addressed you, the way they addressed you. During session
1027
+ // zero that is the designer or the creator, whispering — replying to the DM
1028
+ // instead drops the interview.
1029
+ if (message.targets?.includes('Homer') && message.sender !== 'Homer') {
1030
+ replyTo = message.sender;
1031
+ replyAs = message.action === 'whisper' ? 'whisper' : 'speak';
1032
+ }
1033
+ }
1034
+
1035
+ // The floor is the player's only when the room *names* them. `waitingForHuman`
1036
+ // is also true for a moment after sendRoomMessage clears currentSpeaker and
1037
+ // before processing starts, so gating on it alone opens a second prompt before
1038
+ // the table has said a word.
1039
+ if (!atKeyboard && state.currentSpeaker === 'Homer') {
1040
+ atKeyboard = true;
1041
+ try {
1042
+ const line = await io.question('> ');
1043
+ const result = await app.sendRoomMessage(roomId, line, 'Homer', replyAs, [replyTo]);
1044
+ if (!result.accepted) console.log(`(not your turn — ${result.reason})`);
1045
+ } finally {
1046
+ atKeyboard = false;
1047
+ }
1048
+ }
1049
+ });
1050
+
1051
+ // The emitter only fires on a *change*, so the opening line comes from here.
1052
+ await app.sendRoomMessage(roomId, 'Begin the adventure.', 'Homer', 'speak', ['DM']);
1053
+ ```
1054
+
1055
+ **The emitter payload** is `RoomUpdate`, a two-member union discriminated by `type` —
1056
+ `RoomMessageUpdate` (`type: 'state'`) and `RoomErrorUpdate` (`type: 'error'`). Both are exported,
1057
+ so the narrowing above compiles under `strict` with nothing hand-written. A state update carries
1058
+ `latestMessage`, `messageIndex`, `totalCost`, `isPaused`, `currentSpeaker`,
1059
+ `processingInProgress` and `waitingForHuman`. `messageIndex` counts messages with thoughts and
1060
+ tool notices excluded, so compare it against a list fetched the same way —
1061
+ `getRoomMessages(roomId)` — or refetch when they disagree.
1062
+
1063
+ **Errors** arrive on the same emitter, as `{type: 'error', errorType, message, timestamp}`. Same
1064
+ event name rather than `'error'`, because an EventEmitter throws when an `'error'` event has no
1065
+ listener and that would take down a host that subscribed only to updates. Check for it first, as
1066
+ above: a turn that dies — most often on a spent balance — otherwise just goes quiet, with no
1067
+ message and nothing to await.
1068
+
1069
+ **`waitingForHuman` means "the human may send something", not "the human is being asked
1070
+ something".** It is true while a human holds the floor, and also true for an idle room — no
1071
+ speaker, nothing queued, nothing in flight — which includes the gap between `sendRoomMessage`
1072
+ accepting a line and processing starting. Gate a prompt on it alone and you open a second one
1073
+ before the table has said a word. `currentSpeaker === <the human's nickname>` is the test for
1074
+ "it is their turn", which is what the loop above uses; `waitingForHuman` is the right test for
1075
+ whether to enable a composer.
1076
+
1077
+ **`sendRoomMessage`'s `action` defaults to `'moderate'`**, not `'speak'`. Pass the action you
1078
+ mean. A message sent out of turn is refused rather than thrown: the result is
1079
+ `{accepted: false, reason}`, which is what to show as "not your turn".
1080
+
1081
+ **The `sender` string must be an `agentNickname`** — that is the name the room routes by.
1082
+
1083
+ **The `replyTo`/`replyAs` bookkeeping is only for a table with no moderator.** This room has
1084
+ none, so the player's line has to name its own recipient. Give the human agent
1085
+ `useModerator: true` in a room that has a moderator and all of it goes away — the room forces the
1086
+ message to `moderate`, clears the targets, and the moderator decides who answers. That is how the
1087
+ `dnd5e` room template ships; see [Example 11](#example-11-seating-a-whole-dd-table).
1088
+
1089
+ Two notes for a long-running process. Call `await briyah.shutdown()` before exiting or it will
1090
+ hang on open handles. And a room with no human-controlled agent never stops on its own: the
1091
+ agents talk until the leader adjourns.
1092
+
1093
+ ### Example 11: Seating a whole D&D table
1094
+
1095
+ Example 10 seats a Dungeon Master and players, which is enough to see the loop but not enough to
1096
+ play. The `dungeon_master` prompt whispers a **campaign designer** to build the world and a
1097
+ **character creator** to build sheets, and hands fights to a **battle master**, so a table
1098
+ without those three has a leader whose own instructions reference agents that are not there.
1099
+
1100
+ The pack ships that table as a room template, and instantiating it is the whole of the setup:
1101
+
1102
+ ```typescript
1103
+ import { Briyah } from 'briyah';
1104
+
1105
+ const briyah = new Briyah({ dataPath: './briyah-data' });
1106
+ await briyah.init();
1107
+ const app = briyah.getAppService('cli-user');
1108
+
1109
+ app.packs.setEnabled('dnd5e', true); // per user, and required
1110
+
1111
+ const { roomId, warnings } = await app.packInstantiation.instantiateRoom(
1112
+ 'dnd5e',
1113
+ 'table',
1114
+ {
1115
+ primary: { aiServiceName: 'Anthropic', aiModel: 'claude-sonnet-5' },
1116
+ economy: { aiServiceName: 'Anthropic', aiModel: 'claude-haiku-4-5' },
1117
+ },
1118
+ 'Campaign — Homer',
1119
+ { player: { agentName: 'Homer', agentNickname: 'Homer' } },
1120
+ );
1121
+ warnings.forEach((warning) => console.warn(warning));
1122
+ ```
1123
+
1124
+ That is six agents — moderator, Dungeon Master, battle master, character creator, campaign
1125
+ designer, and Homer at the keyboard — each with its folder's tool grants and rules documents,
1126
+ `turnMode: 'directed'`, the Dungeon Master leading, and the moderator created before the agents
1127
+ that route through it. Then run the loop from Example 10.
1128
+
1129
+ **The goal.** The template's goal describes the game in general. A first session usually wants
1130
+ one that says what has *not* happened yet, or the Dungeon Master opens a scene for characters
1131
+ who have no sheets:
1132
+
1133
+ ```typescript
1134
+ await app.editRoom(roomId, 'Campaign — Homer',
1135
+ 'A fifth-edition campaign for Homer. Nothing is prepared: no campaign has been designed ' +
1136
+ 'and no character has a sheet. Run session zero first — have the Campaign Designer ' +
1137
+ 'interview Homer and publish the Campaign document, then hand the Character Creator one ' +
1138
+ 'player at a time until every sheet exists — and only then open the first scene.');
1139
+ ```
1140
+
1141
+ **Models by role.** The Dungeon Master reasons and makes every tool call, and is the only agent
1142
+ the template puts on the primary model. Everyone else is `economy`, including the campaign
1143
+ designer, whose output is long but infrequent:
1144
+
1145
+ | Role | `modelRole` | Suggested |
1146
+ |---|---|---|
1147
+ | Dungeon Master | `primary` | `claude-sonnet-5` |
1148
+ | Battle master, character creator, campaign designer, moderator | `economy` | `claude-haiku-4-5` |
1149
+ | Players, human and AI | `economy` | `claude-haiku-4-5` |
1150
+
1151
+ Pass only `primary` and everything runs on it.
1152
+
1153
+ **The moderator, and what it saves your loop.** The shipped table seats one
1154
+ (`dnd5e:dnd_room_moderator`), and the player template sets `useModerator: true`. That pairing is
1155
+ not decoration: when a human agent has the flag, the room forces their message to `moderate` and
1156
+ clears its targets — server-side, whatever action you passed — and the moderator decides who
1157
+ hears it and who answers. A person typing a line does not know whether they are answering the
1158
+ designer's interview question or the DM's "what do you do", and with a moderator they do not have
1159
+ to: the `replyTo`/`replyAs` mirroring in Example 10 exists only because that table has none.
1160
+
1161
+ Skip the moderator when nothing addresses the player except the leader. Then the Dungeon Master
1162
+ names who acts next in a `directed` room, which is the same job for less money. If any agent has
1163
+ `useModerator: true`, the room must name a moderator or `createRoom` raises a `ValidationError`.
1164
+
1165
+ **Building it by hand.** If you want the pieces rather than the template, `createAgentFromFolder`
1166
+ reads a folder's `defaults_config.json` and applies all of it — the same wiring the web client's
1167
+ create-agent dialog performs — so you never transcribe eighteen tool names or thirteen document
1168
+ ids, and nothing drifts when the pack changes:
1169
+
1170
+ ```typescript
1171
+ const from = (folder: string, aiModel: string, overrides = {}) =>
1172
+ app.createAgentFromFolder({ folder, aiServiceName: 'Anthropic', aiModel, overrides });
1173
+
1174
+ const mod = await from('dnd5e:dnd_room_moderator', 'claude-haiku-4-5');
1175
+ const dm = await from('dnd5e:dungeon_master', 'claude-sonnet-5');
1176
+ const marshal = await from('dnd5e:battle_master', 'claude-haiku-4-5');
1177
+ const designer = await from('dnd5e:campaign_designer', 'claude-haiku-4-5');
1178
+ const creator = await from('dnd5e:character_creator', 'claude-haiku-4-5');
1179
+
1180
+ const you = await from('dnd5e:dnd_player', 'claude-haiku-4-5', {
1181
+ agentName: 'Homer', agentNickname: 'Homer',
1182
+ description: 'A player character with no sheet yet, played by a person.',
1183
+ controlledByHuman: true, useModerator: true,
1184
+ });
1185
+
1186
+ const { roomId } = await app.createRoom(
1187
+ 'Campaign — Homer',
1188
+ 'A fifth-edition campaign for Homer. ...',
1189
+ [mod.id!, dm.id!, marshal.id!, designer.id!, creator.id!, you.id!],
1190
+ 'DM', // roomLeader
1191
+ 'directed', // turnMode
1192
+ 'Moderator', // moderator — required, because Homer has useModerator
1193
+ );
1194
+ ```
1195
+
1196
+ The nicknames come from the folders: `Moderator`, `DM`, `Marshal`, `Designer`, `Creator`. These
1197
+ agents are free-standing rather than room-owned, so they appear in `listAgents()` and outlive the
1198
+ room; `createRoomAgentFromFolder` is the room-owned equivalent, and is what the template uses.
1199
+
1200
+ **Resuming.** `listRooms()` gives saved campaigns; `getRoomDetails(roomId)` gives the roster,
1201
+ where `agents[].controlledByHuman` identifies the person's character. Then
1202
+ `ensureRoomStateCallback(roomId)` before subscribing — without it the emitter on a resumed room
1203
+ never fires.
1204
+
1205
+ ## Data Storage
1206
+
1207
+ Briyah stores data in the following structure:
1208
+
1209
+ ```
1210
+ {dataPath}/
1211
+ ├── common/ # Shared across all users
1212
+ │ ├── config/ # LLM pricing and image-model config
1213
+ │ ├── prompts/ # Global prompt templates
1214
+ │ └── published-agents.json # Published agent mappings
1215
+ ├── packs/ # Installed packs, one directory each
1216
+ │ └── {pack}/ # pack.json, prompts/, artifacts/, agents/, rooms/
1217
+ ├── retired-prompts/ # Folders a pack took over; see "Upgrading to 2.0"
1218
+ ├── logs/ # briyah.log
1219
+ └── user/
1220
+ └── {userId}/ # Per-user data
1221
+ ├── agents/ # Agent configs and histories (one JSON per agent)
1222
+ ├── rooms/ # Room metadata, message logs, artifacts (one folder per room)
1223
+ ├── stories/ # Story state
1224
+ ├── tools/ # User-defined tools (one JSON per tool)
1225
+ ├── prompts/ # User-specific prompts
1226
+ ├── packs/{pack}/ # This user's edits to a pack, or a pack they created
1227
+ ├── artifacts/ # This user's own documents
1228
+ ├── upload/ # User file attachments
1229
+ ├── transactions/ # Transaction records
1230
+ └── userconfig/ # User preferences, balance, and enabled packs
1231
+ ```
1232
+
1233
+ `init()` seeds `common/` additively and **replaces** every bundled pack under `packs/` — see
1234
+ [Upgrading to 2.0](#upgrading-to-20) for exactly what is rewritten and where your own edits
1235
+ belong instead.
1236
+
1237
+ ## Multi-Instance Support
1238
+
1239
+ You can create multiple Briyah instances with different configurations:
1240
+
1241
+ ```typescript
1242
+ const briyah1 = new Briyah({ dataPath: './data1' });
1243
+ const briyah2 = new Briyah({ dataPath: './data2' });
1244
+
1245
+ await briyah1.init();
1246
+ await briyah2.init();
1247
+
1248
+ // Each instance has isolated data
1249
+ const user1Service = briyah1.getAppService('user-123');
1250
+ const user2Service = briyah2.getAppService('user-123');
1251
+ // These are completely separate services with different data paths
1252
+ ```
1253
+
1254
+ **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.
1255
+
1256
+ ## Troubleshooting
1257
+
1258
+ ### "Must call init() before getAppService()"
1259
+
1260
+ Make sure to call `await briyah.init()` before calling `getAppService()`.
1261
+
1262
+ ### "No LLM provider API keys configured"
1263
+
1264
+ Set at least one of the required API key environment variables (ANTHROPIC_API_KEY, OPENAI_API_KEY, etc.).
1265
+
1266
+ ### "STARTING_BALANCE environment variable is required"
1267
+
1268
+ Set the `STARTING_BALANCE` environment variable or pass `startingBalance` in the constructor options.
1269
+
1270
+ ### Cache not working as expected
1271
+
1272
+ Check the cache statistics with `getCacheStats()` and adjust `userServiceCacheTimeoutMinutes` in the constructor options.