briyah 1.5.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/README.md +1092 -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 +178 -88
  44. package/dist-sdk/server/src/app.service.d.ts +28 -7
  45. package/dist-sdk/server/src/app.service.js +121 -91
  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 +39 -0
  49. package/dist-sdk/server/src/config/prompt-resolver.js +189 -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 +35 -0
  55. package/dist-sdk/server/src/packs/pack-instantiation.service.js +154 -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-store.service.d.ts +3 -0
  62. package/dist-sdk/server/src/room/room-store.service.js +41 -5
  63. package/dist-sdk/server/src/room/room.d.ts +7 -0
  64. package/dist-sdk/server/src/room/room.js +29 -1
  65. package/dist-sdk/server/src/sdk/briyah.d.ts +2 -0
  66. package/dist-sdk/server/src/sdk/briyah.js +45 -8
  67. package/dist-sdk/server/src/sdk/index.d.ts +6 -1
  68. package/dist-sdk/server/src/sdk/index.js +6 -2
  69. package/dist-sdk/server/src/shared/shared.module.js +0 -3
  70. package/dist-sdk/server/src/story/story.service.d.ts +2 -2
  71. package/dist-sdk/server/src/tools/packs/dnd5e/data/kits.d.ts +17 -0
  72. package/dist-sdk/server/src/tools/packs/dnd5e/data/kits.js +54 -0
  73. package/dist-sdk/server/src/tools/packs/dnd5e/data/races.d.ts +3 -0
  74. package/dist-sdk/server/src/tools/packs/dnd5e/data/races.js +6 -0
  75. package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.d.ts +2 -0
  76. package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.js +4 -0
  77. package/dist-sdk/server/src/tools/packs/dnd5e/engine/backgrounds.d.ts +1 -1
  78. package/dist-sdk/server/src/tools/packs/dnd5e/engine/backgrounds.js +6 -3
  79. package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.d.ts +3 -0
  80. package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.js +45 -5
  81. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encounter.d.ts +27 -0
  82. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encounter.js +103 -0
  83. package/dist-sdk/server/src/tools/packs/dnd5e/engine/foes.d.ts +7 -0
  84. package/dist-sdk/server/src/tools/packs/dnd5e/engine/foes.js +83 -0
  85. package/dist-sdk/server/src/tools/packs/dnd5e/engine/kits.d.ts +19 -0
  86. package/dist-sdk/server/src/tools/packs/dnd5e/engine/kits.js +130 -0
  87. package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.d.ts +2 -1
  88. package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.js +13 -2
  89. package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.d.ts +6 -0
  90. package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.js +16 -0
  91. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.d.ts +10 -0
  92. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.js +82 -1
  93. package/dist-sdk/server/src/tools/packs/dnd5e/index.js +2 -0
  94. package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.js +51 -6
  95. package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.js +19 -9
  96. package/dist-sdk/server/src/tools/packs/dnd5e/tools/encounter.tool.d.ts +2 -0
  97. package/dist-sdk/server/src/tools/packs/dnd5e/tools/encounter.tool.js +134 -0
  98. package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.js +31 -13
  99. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.d.ts +2 -0
  100. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.js +25 -8
  101. package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.js +70 -4
  102. package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.js +27 -0
  103. package/dist-sdk/server/src/tools/packs/index.d.ts +1 -2
  104. package/dist-sdk/server/src/tools/packs/index.js +5 -11
  105. package/dist-sdk/shared/types/app.types.d.ts +72 -13
  106. package/docs/assets/hierarchy.js +1 -1
  107. package/docs/assets/highlight.css +8 -1
  108. package/docs/assets/icons.js +1 -1
  109. package/docs/assets/icons.svg +1 -1
  110. package/docs/assets/main.js +4 -4
  111. package/docs/assets/navigation.js +1 -1
  112. package/docs/assets/search.js +1 -1
  113. package/docs/assets/style.css +18 -3
  114. package/docs/classes/Agent.html +702 -37
  115. package/docs/classes/Briyah.html +250 -33
  116. package/docs/classes/BriyahConfigService.html +117 -10
  117. package/docs/classes/NativeToolRegistry.html +156 -11
  118. package/docs/classes/PackInstantiationService.html +146 -0
  119. package/docs/classes/PackService.html +247 -0
  120. package/docs/classes/Room.html +1190 -77
  121. package/docs/classes/RoomMessage.html +260 -29
  122. package/docs/enums/MessageAction.html +123 -3
  123. package/docs/functions/availableToolPacks.html +41 -2
  124. package/docs/functions/dnd5eTools.html +42 -3
  125. package/docs/functions/installToolPacks.html +48 -0
  126. package/docs/functions/registerToolPacks.html +54 -6
  127. package/docs/hierarchy.html +42 -1
  128. package/docs/index.html +158 -25
  129. package/docs/interfaces/AgentCreationOptions.html +110 -11
  130. package/docs/interfaces/AgentInfo.html +188 -3
  131. package/docs/interfaces/AgentMessagesResponse.html +71 -2
  132. package/docs/interfaces/AppService.html +2775 -474
  133. package/docs/interfaces/Artifact.html +81 -4
  134. package/docs/interfaces/ArtifactMetadata.html +104 -3
  135. package/docs/interfaces/ArtifactWriteOptions.html +75 -6
  136. package/docs/interfaces/AttachDocumentResponse.html +61 -2
  137. package/docs/interfaces/BriyahConfigOptions.html +107 -10
  138. package/docs/interfaces/ChapterInfo.html +61 -2
  139. package/docs/interfaces/Character.html +81 -2
  140. package/docs/interfaces/CreateAgentResponse.html +56 -2
  141. package/docs/interfaces/CreateRoomResponse.html +61 -2
  142. package/docs/interfaces/CreateStoryResponse.html +56 -2
  143. package/docs/interfaces/FileList.html +56 -2
  144. package/docs/interfaces/FileMetadata.html +84 -3
  145. package/docs/interfaces/IConfigService.html +76 -3
  146. package/docs/interfaces/InstantiateModels.html +64 -0
  147. package/docs/interfaces/InstantiateRoomResult.html +70 -0
  148. package/docs/interfaces/LoadedPack.html +131 -0
  149. package/docs/interfaces/LoggingOptions.html +86 -7
  150. package/docs/interfaces/Message.html +80 -2
  151. package/docs/interfaces/ModelChoice.html +73 -0
  152. package/docs/interfaces/ModelInfo.html +71 -2
  153. package/docs/interfaces/NativeToolDefinition.html +96 -9
  154. package/docs/interfaces/PackAgentTemplate.html +101 -0
  155. package/docs/interfaces/PackRoomTemplate.html +108 -0
  156. package/docs/interfaces/PackView.html +172 -0
  157. package/docs/interfaces/PreparedPromptResponse.html +61 -2
  158. package/docs/interfaces/ProcessTextResponse.html +81 -2
  159. package/docs/interfaces/PromptFile.html +69 -2
  160. package/docs/interfaces/PromptFileContent.html +75 -2
  161. package/docs/interfaces/PromptFilesResponse.html +56 -2
  162. package/docs/interfaces/PromptFolder.html +79 -2
  163. package/docs/interfaces/PromptFolderDefaults.html +136 -5
  164. package/docs/interfaces/PromptFolderDefaultsResponse.html +65 -4
  165. package/docs/interfaces/PromptFoldersResponse.html +56 -2
  166. package/docs/interfaces/RoomDetails.html +133 -4
  167. package/docs/interfaces/RoomInfo.html +84 -2
  168. package/docs/interfaces/RoomMessageUpdate.html +91 -2
  169. package/docs/interfaces/RoomMessagesResponse.html +61 -2
  170. package/docs/interfaces/SendMessageResult.html +61 -2
  171. package/docs/interfaces/StoryErrorEvent.html +76 -4
  172. package/docs/interfaces/StoryIdea.html +71 -2
  173. package/docs/interfaces/StoryInfo.html +173 -3
  174. package/docs/interfaces/StoryIntroduceCharacterEvent.html +71 -4
  175. package/docs/interfaces/StoryProgressChapterEvent.html +64 -3
  176. package/docs/interfaces/StoryState.html +99 -6
  177. package/docs/interfaces/StoryStateEvent.html +69 -3
  178. package/docs/interfaces/ToolArtifact.html +81 -4
  179. package/docs/interfaces/ToolCaller.html +75 -6
  180. package/docs/interfaces/ToolDefinition.html +76 -2
  181. package/docs/interfaces/ToolHelpers.html +91 -6
  182. package/docs/interfaces/ToolParameter.html +71 -2
  183. package/docs/interfaces/ToolRoomAccess.html +200 -24
  184. package/docs/interfaces/ToolSummary.html +71 -2
  185. package/docs/interfaces/ToolsResponse.html +66 -2
  186. package/docs/interfaces/Transaction.html +96 -2
  187. package/docs/interfaces/TransactionHistoryResponse.html +61 -2
  188. package/docs/modules.html +53 -1
  189. package/docs/types/PackOrigin.html +34 -0
  190. package/docs/types/PromptScope.html +34 -1
  191. package/docs/types/RoomTurnMode.html +36 -2
  192. package/docs/types/ToolContext.html +36 -2
  193. package/docs/types/ToolRunResult.html +34 -1
  194. package/package.json +139 -139
  195. package/src/tools/packs/dnd5e/README.md +149 -26
  196. package/dist-sdk/server/src/library/library.service.d.ts +0 -14
  197. package/dist-sdk/server/src/library/library.service.js +0 -165
  198. package/docs/functions/enabledToolPacks.html +0 -2
  199. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/campaign_designer-setting.md +0 -0
  200. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/character_creator-basics.md +0 -0
  201. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-barbarian.md +0 -0
  202. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-bard.md +0 -0
  203. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-cleric.md +0 -0
  204. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-druid.md +0 -0
  205. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-fighter.md +0 -0
  206. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-monk.md +0 -0
  207. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-paladin.md +0 -0
  208. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-ranger.md +0 -0
  209. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-rogue.md +0 -0
  210. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-sorcerer.md +0 -0
  211. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-warlock.md +0 -0
  212. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-wizard.md +0 -0
  213. /package/data/{common/prompts/campaign_designer → packs/dnd5e/prompts/battle_master}/system_instruction.prompt +0 -0
  214. /package/data/{common → packs/dnd5e}/prompts/campaign_designer/defaults_config.json +0 -0
  215. /package/data/{common → packs/dnd5e}/prompts/campaign_designer/perceive.json +0 -0
  216. /package/data/{common → packs/dnd5e}/prompts/campaign_designer/perceive.prompt +0 -0
  217. /package/data/{common/prompts/character_creator → packs/dnd5e/prompts/campaign_designer}/system_instruction.prompt +0 -0
  218. /package/data/{common → packs/dnd5e}/prompts/character_creator/perceive.json +0 -0
  219. /package/data/{common/prompts/dnd_player → packs/dnd5e/prompts/character_creator}/system_instruction.prompt +0 -0
  220. /package/data/{common → packs/dnd5e}/prompts/dnd_player/defaults_config.json +0 -0
  221. /package/data/{common → packs/dnd5e}/prompts/dnd_player/perceive.json +0 -0
  222. /package/data/{common/prompts/dnd_room_moderator → packs/dnd5e/prompts/dnd_player}/system_instruction.prompt +0 -0
  223. /package/data/{common → packs/dnd5e}/prompts/dnd_room_moderator/defaults_config.json +0 -0
  224. /package/data/{common/prompts/dungeon_master → packs/dnd5e/prompts/dnd_room_moderator}/system_instruction.prompt +0 -0
  225. /package/data/{common → packs/dnd5e}/prompts/dungeon_master/compact_agent.prompt +0 -0
  226. /package/data/{common → packs/dnd5e}/prompts/dungeon_master/perceive.json +0 -0
package/README.md CHANGED
@@ -1,994 +1,1092 @@
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
+ ## 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('dnd5e: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: 'dnd5e: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 shared 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
+ A folder can also come from a **pack** — a domain's prompts, documents, tools and templates in
327
+ one directory. A pack's folders are referenced **pack-qualified**, and they are only listed once
328
+ the user has that pack enabled:
329
+
330
+ ```typescript
331
+ const appService = briyah.getAppService('user-123');
332
+ console.log(appService.listPromptFolders());
333
+ // default, narrator, character, illustrator, pdf_converter, room_moderator, ...
334
+
335
+ appService.packs.setEnabled('dnd5e', true);
336
+ console.log(appService.listPromptFolders());
337
+ // ... plus dnd5e:dungeon_master, dnd5e:dnd_player, dnd5e:character_creator,
338
+ // dnd5e:campaign_designer, dnd5e:battle_master, dnd5e:dnd_room_moderator
339
+ ```
340
+
341
+ See [Packs](#packs) — **if you are building on `dnd5e` you have to enable it first**, or the
342
+ folder name will not resolve and you will get a generic agent.
343
+
344
+ **The folder is the sixth argument to `createAgent`, and it defaults to `'default'`** — a
345
+ generic conversational agent. Passing a role folder is what makes the agent that role:
346
+
347
+ ```typescript
348
+ const dm = appService.createAgent(
349
+ 'Anthropic',
350
+ 'Dungeon Master', // agentName — a label; used in logs and the UI
351
+ 'DM', // agentNickname — the name the room routes by
352
+ 'Runs the game.',
353
+ 'claude-sonnet-5',
354
+ 'dnd5e:dungeon_master', // <- the prompt folder
355
+ );
356
+ ```
357
+
358
+ `agentNickname` is the identity: messages are addressed to it, artifact viewers are lists of
359
+ it, and it is what an agent writes into `targets`. `agentName` is a label. Give a character the
360
+ nickname you want it called by.
361
+
362
+ To write your own folder, copy a bundled one out of `{dataPath}/common/prompts/` (or a pack's
363
+ `{dataPath}/packs/<pack>/prompts/`), rename the directory, and edit it — a folder in the user data
364
+ directory takes precedence over the common one of the same name. Editing a *pack's* file instead
365
+ writes a private copy under `{dataPath}/user/<userId>/packs/<pack>/`, so one user's change does
366
+ not reach the others.
367
+
368
+ ## Packs
369
+
370
+ A **pack** is one domain's prompt folders, documents, native tools, and agent and room templates
371
+ in a single directory. `dnd5e` is the one that ships: eighteen tools for dice, character sheets,
372
+ the rules engine and a bestiary, six prompt folders, sixteen rules documents, and a room template
373
+ that builds a whole table.
374
+
375
+ It exists so a domain arrives as a unit — and so **your** prompts live in your own directory
376
+ rather than beside Briyah's. Install one by copying a directory into `{dataPath}/packs/`; there is
377
+ no import mechanism and nothing to register.
378
+
379
+ ```
380
+ {dataPath}/packs/<name>/
381
+ ├── pack.json optional: title, description, version
382
+ ├── prompts/ folders, referenced as <name>:<folder>
383
+ ├── artifacts/ manifest.json + .md documents
384
+ ├── agents/ agent templates
385
+ └── rooms/ room templates
386
+ ```
387
+
388
+ ### Installed for everyone, enabled per user
389
+
390
+ Tools register process-wide when you construct `Briyah`. Enabling is **per user**, and it is what
391
+ makes a pack's prompt folders resolve by bare name, its documents appear in `listUserArtifacts()`,
392
+ and its tools grantable:
393
+
394
+ ```typescript
395
+ const appService = briyah.getAppService('user-123');
396
+
397
+ appService.packs.listPacks();
398
+ // [{ pack: 'dnd5e', title: 'D&D 5th Edition', origin: 'host', enabled: false,
399
+ // counts: { prompts: 6, documents: 16, agents: 6, rooms: 1 },
400
+ // missingTools: [], missingPacks: [] }]
401
+
402
+ appService.packs.setEnabled('dnd5e', true);
403
+ ```
404
+
405
+ **Do this before building anything on the pack.** A pack-qualified folder
406
+ (`dnd5e:dungeon_master`) always resolves, but a bare `dungeon_master` only reaches the pack when
407
+ it is enabled — otherwise it falls back to the shared root prompts and you get a generic
408
+ conversational agent with no error to tell you.
409
+
410
+ Disabling later **hides** rather than switches off: the pack leaves the listings, but a room that
411
+ already exists keeps working, an attached document still loads, and a granted tool still runs.
412
+
413
+ If you would rather filter or wrap the tool definitions than take them all:
414
+
415
+ ```typescript
416
+ import { dnd5eTools, availableToolPacks } from 'briyah';
417
+ const briyah = new Briyah({ tools: dnd5eTools() });
418
+ console.log(availableToolPacks()); // ['dnd5e']
419
+ ```
420
+
421
+ ### Building a room from a template
422
+
423
+ The fastest path to a working table, and the one that gets the details right — the moderator is
424
+ created before the agents that need one, the leader and moderator are resolved to the nicknames
425
+ the created agents actually ended up with, and a failure rolls the whole room back:
426
+
427
+ ```typescript
428
+ const { roomId, agentIds, warnings } = await appService.packInstantiation.instantiateRoom(
429
+ 'dnd5e',
430
+ 'table',
431
+ {
432
+ primary: { aiServiceName: 'Anthropic', aiModel: 'claude-sonnet-5' },
433
+ economy: { aiServiceName: 'Anthropic', aiModel: 'claude-haiku-4-5-20251001' },
434
+ },
435
+ 'Tuesday Night Game', // optional; auto-suffixed if the name is taken
436
+ );
437
+ ```
438
+
439
+ That is a six-agent room with `turnMode: 'directed'`, the Dungeon Master as leader, a table
440
+ moderator, and every agent already carrying its tool grants and rules documents.
441
+
442
+ A template names a **role** rather than a model — `primary` or `economy` — because a model id goes
443
+ stale and assumes your provider keys. The Dungeon Master takes the primary; the agents that do
444
+ bookkeeping rather than prose take the economy one. Omit `economy` and everything uses the
445
+ primary. `warnings` reports anything that did not go to plan without stopping the room, such as a
446
+ document that failed to attach; it is worth logging, because a missing document is a capability
447
+ the agent appears to have and does not.
448
+
449
+ For a single agent, with no room:
450
+
451
+ ```typescript
452
+ const { agentId } = await appService.packInstantiation.instantiateAgent(
453
+ 'dnd5e',
454
+ 'character_creator',
455
+ { primary: { aiServiceName: 'Anthropic', aiModel: 'claude-sonnet-5' } },
456
+ );
457
+ ```
458
+
459
+ ### Building the same room by hand
460
+
461
+ If you want the pieces rather than the template, registering a pack makes its tools *grantable*,
462
+ not granted. An agent may only run the ones named in its `toolNames`:
463
+
464
+ ```typescript
465
+ const dm = appService.createAgent(
466
+ 'Anthropic', 'Dungeon Master', 'DM', 'Runs the game.', 'claude-sonnet-5',
467
+ 'dnd5e:dungeon_master', // <- pack-qualified
468
+ undefined, null, 0, '',
469
+ { toolNames: ['roll_dice', 'check', 'apply_hp', 'stat_block', 'read_sheet'] },
470
+ );
471
+ ```
472
+
473
+ A pack's **documents** are read-only rules text an agent carries in every call. They live in
474
+ `{dataPath}/packs/<pack>/artifacts/`, appear in `listUserArtifacts()` once the pack is enabled,
475
+ and attach by an id that never changes:
476
+
477
+ ```typescript
478
+ await appService.attachArtifactToAgent(dm.id, 'pack:dnd5e.dungeon_master-procedure');
479
+ await appService.attachArtifactToAgent(player.id, 'pack:dnd5e.class-bard');
480
+ ```
481
+
482
+ A document sits in that agent's cached prompt prefix on every call, so attach what it needs and
483
+ nothing more. `src/tools/packs/dnd5e/README.md` in this package lists all eighteen tools and which
484
+ agent each document belongs to.
485
+
486
+ ## Usage Examples
487
+
488
+ ### Example 1: Multi-User Setup
489
+
490
+ ```typescript
491
+ import { Briyah } from 'briyah';
492
+
493
+ // Initialize once at application startup
494
+ const briyah = new Briyah({
495
+ dataPath: './data/briyah',
496
+ startingBalance: 10.00
497
+ });
498
+
499
+ await briyah.init();
500
+
501
+ // In your route handler or service
502
+ async function handleUserRequest(userId: string, message: string) {
503
+ const appService = briyah.getAppService(userId);
504
+
505
+ // Each user gets their own isolated AppService
506
+ const agents = await appService.listAgents();
507
+
508
+ // ... process user request
509
+ }
510
+
511
+ // Cleanup at application shutdown
512
+ process.on('SIGINT', async () => {
513
+ await briyah.shutdown();
514
+ process.exit(0);
515
+ });
516
+ ```
517
+
518
+ ### Example 2: Custom Data Path
519
+
520
+ ```typescript
521
+ import { Briyah } from 'briyah';
522
+ import path from 'path';
523
+
524
+ const briyah = new Briyah({
525
+ dataPath: path.join(__dirname, '..', 'user-data', 'briyah'),
526
+ userServiceCacheTimeoutMinutes: 60 // 1 hour cache
527
+ });
528
+
529
+ await briyah.init();
530
+ ```
531
+
532
+ ### Example 3: Testing Configuration
533
+
534
+ ```typescript
535
+ import { Briyah } from 'briyah';
536
+
537
+ const testBriyah = new Briyah({
538
+ dataPath: './test-data',
539
+ startingBalance: 100.00,
540
+ userServiceCacheTimeoutMinutes: 5,
541
+ envOverrides: {
542
+ ANTHROPIC_API_KEY: process.env.TEST_ANTHROPIC_KEY,
543
+ OPENAI_API_KEY: process.env.TEST_OPENAI_KEY
544
+ }
545
+ });
546
+
547
+ await testBriyah.init();
548
+
549
+ // Run tests...
550
+
551
+ await testBriyah.shutdown();
552
+ ```
553
+
554
+ ### Example 4: Agent Creation and Text Processing
555
+
556
+ ```typescript
557
+ const appService = briyah.getAppService('user-123');
558
+
559
+ // Create an agent
560
+ const agent = appService.createAgent(
561
+ 'Anthropic', // provider
562
+ 'AI Assistant', // name
563
+ 'James', // nickname
564
+ 'A helpful AI assistant', // description
565
+ 'claude-haiku-4-5' // model
566
+ );
567
+
568
+ if (!agent.id) throw new Error('Agent creation failed');
569
+ console.log(`Created agent: ${agent.id}`);
570
+
571
+ // Process text with the agent
572
+ const result = await appService.processText(
573
+ agent.id,
574
+ 'What is the capital of France?'
575
+ );
576
+
577
+ console.log(`Response: ${result.result}`);
578
+ console.log(`Cost: $${result.totalCost}`);
579
+ console.log(`Tokens: ${(result.totalInputTokens ?? 0) + (result.totalOutputTokens ?? 0)}`);
580
+ ```
581
+
582
+ ### Example 5: Multi-Agent Room Conversation
583
+
584
+ ```typescript
585
+ const appService = briyah.getAppService('user-123');
586
+
587
+ // Create agents
588
+ const analyst = appService.createAgent('OpenAI', 'Analyst', 'Analyst', 'Data analyst', 'gpt-4');
589
+ const writer = appService.createAgent('Anthropic', 'Writer', 'Writer', 'Content writer', 'claude-haiku-4-5');
590
+
591
+ if (!analyst.id || !writer.id) throw new Error('Agent creation failed');
592
+
593
+ // Create a room with both agents
594
+ const room = await appService.createRoom(
595
+ 'Analysis Session',
596
+ 'Analyze sales data and produce a written summary',
597
+ [analyst.id, writer.id]
598
+ );
599
+
600
+ // Send a message to start the conversation
601
+ await appService.sendRoomMessage(
602
+ room.roomId,
603
+ 'Please analyze the sales data for Q4',
604
+ 'Analyst',
605
+ 'speak'
606
+ );
607
+
608
+ // The agents will automatically respond and interact
609
+ // Check room messages to see the conversation
610
+ const messages = await appService.getRoomMessages(room.roomId);
611
+ console.log(`Messages: ${messages.messages.length}`);
612
+ ```
613
+
614
+ ### Example 6: Story Message Emitter
615
+
616
+ 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.
617
+
618
+ ```typescript
619
+ import type {
620
+ StoryStateEvent,
621
+ StoryIntroduceCharacterEvent,
622
+ StoryProgressChapterEvent,
623
+ StoryErrorEvent,
624
+ } from 'briyah';
625
+
626
+ const app = briyah.getAppService('user-123');
627
+
628
+ const story = await app.createStory(
629
+ 'The Lost Kingdom',
630
+ 'A medieval fantasy where ancient ruins hold a terrible secret',
631
+ 'A disgraced knight seeking redemption',
632
+ 'A scholar and a sellsword',
633
+ false, // illustrateStory — required, and positional
634
+ );
635
+
636
+ const emitter = app.getStoryMessageEmitter(story.id);
637
+
638
+ // Fires after every turn with the full updated game state.
639
+ emitter.on('story-state', async (event: StoryStateEvent) => {
640
+ const { state } = event;
641
+ console.log('Latest message:', state.latestRoomMessage?.content);
642
+
643
+ // Detect the player's turn by comparing speaker names.
644
+ // Do NOT use state.humanPrompt for this — it is a UI display string,
645
+ // not a reliable turn indicator.
646
+ if (state.currentSpeaker === state.userAgentName) {
647
+ const input = await promptPlayer(state.humanPrompt);
648
+ await app.respondToStory(story.id, input);
649
+ }
650
+ });
651
+
652
+ // Fires when the narrator wants to introduce a new character.
653
+ // The host app should present this to the player before acting.
654
+ // Accept by calling introduceCharacterToStory, or decline with declineCharacter.
655
+ emitter.on('suggest-introduce-character', async (event: StoryIntroduceCharacterEvent) => {
656
+ const accept = await askPlayer(`Add ${event.characterName} to the story?`);
657
+ if (accept) {
658
+ await app.introduceCharacterToStory(story.id, event.characterName!, '', undefined, true);
659
+ } else {
660
+ await app.declineCharacter(story.id, event.characterName!);
661
+ }
662
+ });
663
+
664
+ // Fires when the narrator wants to advance to the next chapter.
665
+ // Call progressStory to accept. Ignoring the event stays in the current chapter —
666
+ // there is no explicit rejection call.
667
+ emitter.on('suggest-progress-chapter', async (_event: StoryProgressChapterEvent) => {
668
+ const accept = await askPlayer('The narrator suggests ending this chapter. Continue?');
669
+ if (accept) {
670
+ await app.progressStory(story.id);
671
+ }
672
+ });
673
+
674
+ // Fires on fatal errors during room processing.
675
+ // Named 'story-error' rather than 'error' to avoid Node.js throwing when no
676
+ // listener is attached.
677
+ emitter.on('story-error', (event: StoryErrorEvent) => {
678
+ if (event.errorType === 'InsufficientBalanceError') {
679
+ console.error('Out of credits:', event.message);
680
+ } else {
681
+ console.error(`Story error [${event.errorType}]:`, event.message);
682
+ }
683
+ });
684
+ ```
685
+
686
+ ### Example 7: Recording Payments and Managing Balance
687
+
688
+ 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.
689
+
690
+ ```typescript
691
+ const app = briyah.getAppService(userId);
692
+
693
+ // --- When your payment provider initiates a charge ---
694
+ // Record it as pending so the transaction log stays consistent.
695
+ await app.recordTransaction(amount, paymentIntentId, 'pending');
696
+
697
+ // --- When your payment provider webhook confirms success ---
698
+ await app.updateTransactionStatus(paymentIntentId, 'succeeded');
699
+ await app.addBalance(amount);
700
+
701
+ // Resume any stories that paused mid-turn due to InsufficientBalanceError.
702
+ await app.resumePausedStories();
703
+
704
+ // --- When a payment fails or is cancelled ---
705
+ await app.updateTransactionStatus(paymentIntentId, 'failed');
706
+
707
+ // --- Querying balance and history ---
708
+ const balance = app.getBalance();
709
+
710
+ const { transactions, total } = await app.getTransactions(50, 0);
711
+
712
+ const tx = await app.getTransactionByPaymentId(paymentIntentId);
713
+ console.log(tx?.status); // 'pending' | 'succeeded' | 'failed' | 'cancelled'
714
+ ```
715
+
716
+ To push real-time balance updates to a connected client (e.g. via SSE), subscribe to the balance emitter before crediting the user:
717
+
718
+ ```typescript
719
+ const emitter = app.getBalanceMessageEmitter(userId);
720
+ emitter.on('update', (newBalance: number) => {
721
+ // Push newBalance to the client
722
+ });
723
+ ```
724
+
725
+ ### Example 8: Registering Native Tools with Opaque Context
726
+
727
+ 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.
728
+
729
+ 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.
730
+
731
+ ```typescript
732
+ import { Briyah } from 'briyah';
733
+
734
+ const briyah = new Briyah({ dataPath: './data/briyah', startingBalance: 10.00 });
735
+ await briyah.init();
736
+
737
+ // Register a tool that reads its scope from context, not from the LLM's args.
738
+ briyah.registerTool({
739
+ name: 'add_note',
740
+ description: "Add a note to the record the user currently has open",
741
+ parameters: [
742
+ { name: 'text', type: 'string', description: 'The note text', required: true }
743
+ ],
744
+ handler: async (args, helpers, context) => {
745
+ const { db, recordId } = context as { db: MyDb; recordId: string };
746
+ await db.addNote(recordId, args.text); // recordId comes from context — the LLM cannot set it
747
+ return { added: true };
748
+ },
749
+ timeoutMs: 15000 // optional; default 30s, max 120s
750
+ });
751
+
752
+ // Grant it to an agent (grants are enforced server-side).
753
+ const assistant = app.createAgent('Anthropic', 'Assistant', 'Assistant',
754
+ 'A helpful assistant that manages the open record', 'claude-haiku-4-5');
755
+ assistant.toolNames = ['add_note'];
756
+ assistant.save();
757
+
758
+ // When the user acts on record "rec_42", pass that scope as context. Any tool the
759
+ // agent calls during the resulting turn receives it; other rooms/interactions are
760
+ // unaffected. A log-only 'tool' message records each call (visible when fetching
761
+ // messages with includeThoughts=true).
762
+ await app.sendRoomMessage(
763
+ roomId,
764
+ 'Add a note that the client called about renewal.',
765
+ 'User',
766
+ 'speak',
767
+ [],
768
+ false,
769
+ { db, recordId: 'rec_42' } // opaque context
770
+ );
771
+ ```
772
+
773
+ 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.
774
+
775
+ 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.
776
+
777
+ User-authored (string-code) tools remain available via `createTool`/`updateTool`/`testTool` when `allowUserAuthoredTools` is enabled, for trusted single-user setups.
778
+
779
+ ### Example 9: Self-Hosted Image Generation with ComfyUI
780
+
781
+ 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`).
782
+
783
+ For this provider the agent's *model name* selects a **workflow-template pair**, not a checkpoint. Two pairs ship by default:
784
+
785
+ | Pair name | Model | Files required on the ComfyUI server |
786
+ |---|---|---|
787
+ | `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` |
788
+ | `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` |
789
+
790
+ `flux2-dev` has substantially better multi-reference character consistency and wants a 32 GB-class GPU; `flux-kontext` runs on 16 GB-class cards.
791
+
792
+ ```typescript
793
+ import { Briyah } from 'briyah';
794
+
795
+ const briyah = new Briyah({ dataPath: './data/briyah', startingBalance: 10.00 });
796
+ await briyah.init();
797
+
798
+ const app = briyah.getAppService('user-123');
799
+
800
+ // Model name = workflow pair name
801
+ const artist = app.createAgent('ComfyUI', 'Artist', 'Artist',
802
+ 'Image generation agent', 'flux2-dev');
803
+
804
+ // Text-to-image. Resolves to { artifactId } on success or { error } on failure.
805
+ const generated = await artist.generateImage(
806
+ 'A lighthouse on a rocky coast at dusk',
807
+ { width: 1024, height: 1024 } // optional; a fixed seed may also be passed
808
+ );
809
+ if (generated.error) throw new Error(String(generated.error));
810
+
811
+ // Generated images are stored as artifacts (PNG)
812
+ const png = artist.artifactService.getArtifact(generated.artifactId);
813
+
814
+ // Image-to-image with reference images. Each referenced artifact is uploaded
815
+ // and conditioned on separately (chained ReferenceLatent nodes). Order is
816
+ // preserved, so the prompt can refer to "Image 1", "Image 2", ...
817
+ const edited = await artist.editImage(
818
+ 'The character from Image 2 stands in the setting from Image 1',
819
+ { width: 1024, height: 1024 },
820
+ [sceneArtifactId, portraitArtifactId]
821
+ );
822
+ ```
823
+
824
+ Notes:
825
+
826
+ - **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.
827
+ - **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.
828
+ - **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`.
829
+
830
+ **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.
831
+
832
+ ### Example 10: A turn-based table with a human player
833
+
834
+ Example 5 sends one message and reads the transcript back, which suits a batch job. A game or
835
+ any human-in-the-loop app needs the other shape: the agents take several turns among themselves,
836
+ then stop and wait for the person. Three things make that work.
837
+
838
+ **`turnMode: 'directed'`** — only the agent a message names is asked to reply, and the room
839
+ leader answers anything it cannot place. The default, `'broadcast'`, prompts *every* agent for
840
+ *every* message and keeps one reply, which costs several times as much and is wrong for a table
841
+ where one person speaks at a time.
842
+
843
+ **A human-controlled agent** — `createAgent`'s seventh argument. The room delivers messages to
844
+ it and then stops rather than generating a reply, which is what yields the floor to your console.
845
+
846
+ **The room message emitter** — the only way to see the conversation as it happens. It fires on
847
+ every change with the newest message and the room's state.
848
+
849
+ ```typescript
850
+ import { Briyah, dnd5eTools } from 'briyah';
851
+ import * as readline from 'node:readline/promises';
852
+
853
+ const briyah = new Briyah({ dataPath: './briyah-data', tools: dnd5eTools() });
854
+ await briyah.init(); // seeds prompt folders and the packs
855
+ const app = briyah.getAppService('user-123');
856
+
857
+ // Enable the pack for this user, or a bare folder name will not reach it and every
858
+ // agent below would come out generic. Enabling is per user; registering is not.
859
+ app.packs.setEnabled('dnd5e', true);
860
+
861
+ const dm = app.createAgent(
862
+ 'Anthropic', 'Dungeon Master', 'DM', 'Runs the game.', 'claude-sonnet-5',
863
+ 'dnd5e:dungeon_master', undefined, null, 0, '',
864
+ { toolNames: ['roll_dice', 'check', 'apply_hp', 'stat_block', 'read_sheet'] },
865
+ );
866
+ const rogue = app.createAgent(
867
+ 'Anthropic', 'Vex', 'Vex', 'A wary scout.', 'claude-haiku-4-5', 'dnd5e:dnd_player',
868
+ );
869
+ // The seventh argument is what makes this one wait for a person.
870
+ const you = app.createAgent(
871
+ 'Anthropic', 'Homer', 'Homer', 'A hopeful bard.', 'claude-haiku-4-5', 'dnd5e:dnd_player',
872
+ true,
873
+ );
874
+
875
+ // createAgent builds the agent in memory; save() writes it to disk. Without this the
876
+ // table exists for this process only and is gone on restart.
877
+ [dm, rogue, you].forEach((agent) => agent.save());
878
+
879
+ await app.attachArtifactToAgent(dm.id!, 'pack:dnd5e.dungeon_master-procedure');
880
+ await app.attachArtifactToAgent(rogue.id!, 'pack:dnd5e.class-rogue');
881
+ await app.attachArtifactToAgent(you.id!, 'pack:dnd5e.class-bard');
882
+
883
+ const { roomId } = await app.createRoom(
884
+ 'The Sunken Barrow',
885
+ 'A three-room dungeon crawl.',
886
+ [dm.id!, rogue.id!, you.id!],
887
+ 'DM', // roomLeader — answers anything the room cannot place
888
+ 'directed', // turnMode
889
+ );
890
+
891
+ // A room loaded from disk has no state-change callback, so its emitter would never
892
+ // fire. Harmless on a room you just created; required for one you resumed.
893
+ await app.ensureRoomStateCallback(roomId);
894
+
895
+ const io = readline.createInterface({ input: process.stdin, output: process.stdout });
896
+ let lastIndex = -1;
897
+ let atKeyboard = false; // the handler is async; without this it re-enters
898
+ let replyTo = 'DM'; // who last spoke to the player
899
+ let replyAs: 'speak' | 'whisper' = 'speak';
900
+
901
+ app.getRoomMessageEmitter(roomId).on('update', async (state) => {
902
+ if (state.type === 'error') { // a turn failed — see "Errors" below
903
+ console.error(`[${state.errorType}] ${state.message}`);
904
+ return;
905
+ }
906
+
907
+ const message = state.latestMessage;
908
+ if (message && state.messageIndex !== undefined && state.messageIndex > lastIndex) {
909
+ lastIndex = state.messageIndex; // the emitter can repeat a state
910
+ if (message.sender !== 'Homer') console.log(`${message.sender}: ${message.content}`);
911
+ // Answer whoever addressed you, the way they addressed you. During session
912
+ // zero that is the designer or the creator, whispering — replying to the DM
913
+ // instead drops the interview.
914
+ if (message.targets?.includes('Homer') && message.sender !== 'Homer') {
915
+ replyTo = message.sender;
916
+ replyAs = message.action === 'whisper' ? 'whisper' : 'speak';
917
+ }
918
+ }
919
+
920
+ // The floor is the player's only when the room *names* them. `waitingForHuman`
921
+ // is also true for a moment after sendRoomMessage clears currentSpeaker and
922
+ // before processing starts, so gating on it alone opens a second prompt before
923
+ // the table has said a word.
924
+ if (!atKeyboard && state.currentSpeaker === 'Homer') {
925
+ atKeyboard = true;
926
+ try {
927
+ const line = await io.question('> ');
928
+ const result = await app.sendRoomMessage(roomId, line, 'Homer', replyAs, [replyTo]);
929
+ if (!result.accepted) console.log(`(not your turn — ${result.reason})`);
930
+ } finally {
931
+ atKeyboard = false;
932
+ }
933
+ }
934
+ });
935
+
936
+ // The emitter only fires on a *change*, so the opening line comes from here.
937
+ await app.sendRoomMessage(roomId, 'Begin the adventure.', 'Homer', 'speak', ['DM']);
938
+ ```
939
+
940
+ **The emitter payload** carries `latestMessage`, `messageIndex`, `totalCost`, `isPaused`,
941
+ `currentSpeaker`, `processingInProgress` and `waitingForHuman`. `messageIndex` counts messages
942
+ with thoughts and tool notices excluded, so compare it against a list fetched the same way —
943
+ `getRoomMessages(roomId)` — or refetch when they disagree.
944
+
945
+ **Errors** arrive on the same emitter as `{type: 'error', errorType, message}`. Check for it
946
+ first, as above: a turn that dies — most often on a spent balance — otherwise just goes quiet,
947
+ with no message and nothing to await.
948
+
949
+ **`sendRoomMessage`'s `action` defaults to `'moderate'`**, not `'speak'`. Pass the action you
950
+ mean. A message sent out of turn is refused rather than thrown: the result is
951
+ `{accepted: false, reason}`, which is what to show as "not your turn".
952
+
953
+ **The `sender` string must be an `agentNickname`** — that is the name the room routes by.
954
+
955
+ Two notes for a long-running process. Call `await briyah.shutdown()` before exiting or it will
956
+ hang on open handles. And a room with no human-controlled agent never stops on its own: the
957
+ agents talk until the leader adjourns.
958
+
959
+ ### Example 11: Seating a whole D&D table
960
+
961
+ Example 10 seats a Dungeon Master and players, which is enough to see the loop but not enough
962
+ to play. The `dungeon_master` prompt whispers a **campaign designer** to build the world and a
963
+ **character creator** to build sheets, so a table without those two has a leader whose own
964
+ instructions reference agents that are not there.
965
+
966
+ The other half is that each role needs its folder's tool grants and pack documents.
967
+ `createAgentFromFolder` reads the folder's `defaults_config.json` and applies all of it — the
968
+ same wiring the web client's create-agent dialog performs — so you never transcribe eighteen
969
+ tool names or thirteen document ids by hand, and nothing drifts when the pack changes.
970
+
971
+ ```typescript
972
+ import { Briyah, dnd5eTools } from 'briyah';
973
+
974
+ const briyah = new Briyah({ dataPath: './briyah-data', tools: dnd5eTools() });
975
+ await briyah.init();
976
+ const app = briyah.getAppService('cli-user');
977
+
978
+ // Per user, and required: a bare folder name only reaches the pack once it is enabled.
979
+ app.packs.setEnabled('dnd5e', true);
980
+
981
+ const from = (folder: string, aiModel: string, overrides = {}) =>
982
+ app.createAgentFromFolder({ folder, aiServiceName: 'Anthropic', aiModel, overrides });
983
+
984
+ const dm = await from('dnd5e:dungeon_master', 'claude-sonnet-5');
985
+ const designer = await from('dnd5e:campaign_designer', 'claude-sonnet-5');
986
+ const creator = await from('dnd5e:character_creator', 'claude-haiku-4-5');
987
+
988
+ const you = await from('dnd5e:dnd_player', 'claude-haiku-4-5', {
989
+ agentNickname: 'Homer',
990
+ description: 'A player character with no sheet yet, played by a person.',
991
+ controlledByHuman: true,
992
+ });
993
+ const vex = await from('dnd5e:dnd_player', 'claude-haiku-4-5', {
994
+ agentNickname: 'Vex', description: 'A wary scout.',
995
+ });
996
+
997
+ // The goal is read by every agent every turn. Say what has *not* happened yet, or the
998
+ // Dungeon Master opens a scene for characters who have no sheets.
999
+ const { roomId } = await app.createRoom(
1000
+ 'Campaign — Homer',
1001
+ 'A fifth-edition campaign for Homer and Vex. Nothing is prepared: no campaign has been ' +
1002
+ 'designed and no character has a sheet. Run session zero first — have the Campaign ' +
1003
+ 'Designer interview Homer and publish the Campaign document, then hand the Character ' +
1004
+ 'Creator one player at a time until both sheets exist — and only then open the first scene.',
1005
+ [dm.id!, designer.id!, creator.id!, you.id!, vex.id!],
1006
+ 'DM',
1007
+ 'directed',
1008
+ );
1009
+ ```
1010
+
1011
+ Then run the loop from Example 10. Session zero is whispered, which is why that loop mirrors
1012
+ the action it replies with.
1013
+
1014
+ **Models by role.** The Dungeon Master reasons and makes every tool call; the specialists run a
1015
+ few dozen times per campaign; the players are cheap.
1016
+
1017
+ | Role | Model |
1018
+ |---|---|
1019
+ | Dungeon Master, campaign designer | `claude-sonnet-5` |
1020
+ | Character creator | `claude-haiku-4-5` |
1021
+ | Players, human and AI | `claude-haiku-4-5` |
1022
+
1023
+ **Moderators.** `createRoom`'s sixth argument names one, and the `dnd_room_moderator` folder
1024
+ provides one. A 5e table does **not** need it: the Dungeon Master leads a `directed` room and
1025
+ names who acts next, which is the same job. A moderator earns its place when no agent is in
1026
+ charge of the turn order — several people talking at once, or a room whose members address each
1027
+ other freely. If you give an agent `useModerator: true`, the room must have one or `createRoom`
1028
+ raises a `ValidationError`.
1029
+
1030
+ **Resuming.** `listRooms()` gives saved campaigns; `getRoomDetails(roomId)` gives the roster,
1031
+ where `agents[].controlledByHuman` identifies the person's character. Then
1032
+ `ensureRoomStateCallback(roomId)` before subscribing — without it the emitter on a resumed room
1033
+ never fires.
1034
+
1035
+ ## Data Storage
1036
+
1037
+ Briyah stores data in the following structure:
1038
+
1039
+ ```
1040
+ {dataPath}/
1041
+ ├── common/ # Shared across all users
1042
+ │ ├── config/ # LLM pricing and image-model config
1043
+ │ ├── prompts/ # Global prompt templates
1044
+ │ └── published-agents.json # Published agent mappings
1045
+ └── user/
1046
+ └── {userId}/ # Per-user data
1047
+ ├── agents/ # Agent configs and histories (one JSON per agent)
1048
+ ├── rooms/ # Room metadata, message logs, artifacts (one folder per room)
1049
+ ├── stories/ # Story state
1050
+ ├── tools/ # User-defined tools (one JSON per tool)
1051
+ ├── prompts/ # User-specific prompts
1052
+ ├── upload/ # User file attachments
1053
+ ├── transactions/ # Transaction records
1054
+ └── userconfig/ # User preferences and balance
1055
+ ```
1056
+
1057
+ ## Multi-Instance Support
1058
+
1059
+ You can create multiple Briyah instances with different configurations:
1060
+
1061
+ ```typescript
1062
+ const briyah1 = new Briyah({ dataPath: './data1' });
1063
+ const briyah2 = new Briyah({ dataPath: './data2' });
1064
+
1065
+ await briyah1.init();
1066
+ await briyah2.init();
1067
+
1068
+ // Each instance has isolated data
1069
+ const user1Service = briyah1.getAppService('user-123');
1070
+ const user2Service = briyah2.getAppService('user-123');
1071
+ // These are completely separate services with different data paths
1072
+ ```
1073
+
1074
+ **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.
1075
+
1076
+ ## Troubleshooting
1077
+
1078
+ ### "Must call init() before getAppService()"
1079
+
1080
+ Make sure to call `await briyah.init()` before calling `getAppService()`.
1081
+
1082
+ ### "No LLM provider API keys configured"
1083
+
1084
+ Set at least one of the required API key environment variables (ANTHROPIC_API_KEY, OPENAI_API_KEY, etc.).
1085
+
1086
+ ### "STARTING_BALANCE environment variable is required"
1087
+
1088
+ Set the `STARTING_BALANCE` environment variable or pass `startingBalance` in the constructor options.
1089
+
1090
+ ### Cache not working as expected
1091
+
1092
+ Check the cache statistics with `getCacheStats()` and adjust `userServiceCacheTimeoutMinutes` in the constructor options.