briyah 1.4.1 → 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 (227) hide show
  1. package/README.md +1092 -849
  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 +36 -8
  45. package/dist-sdk/server/src/app.service.js +147 -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 +10 -2
  64. package/dist-sdk/server/src/room/room.js +37 -6
  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 +8 -3
  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/story/story.service.js +2 -2
  72. package/dist-sdk/server/src/tools/packs/dnd5e/data/kits.d.ts +17 -0
  73. package/dist-sdk/server/src/tools/packs/dnd5e/data/kits.js +54 -0
  74. package/dist-sdk/server/src/tools/packs/dnd5e/data/races.d.ts +3 -0
  75. package/dist-sdk/server/src/tools/packs/dnd5e/data/races.js +6 -0
  76. package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.d.ts +2 -0
  77. package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.js +4 -0
  78. package/dist-sdk/server/src/tools/packs/dnd5e/engine/backgrounds.d.ts +1 -1
  79. package/dist-sdk/server/src/tools/packs/dnd5e/engine/backgrounds.js +6 -3
  80. package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.d.ts +3 -0
  81. package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.js +45 -5
  82. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encounter.d.ts +27 -0
  83. package/dist-sdk/server/src/tools/packs/dnd5e/engine/encounter.js +103 -0
  84. package/dist-sdk/server/src/tools/packs/dnd5e/engine/foes.d.ts +7 -0
  85. package/dist-sdk/server/src/tools/packs/dnd5e/engine/foes.js +83 -0
  86. package/dist-sdk/server/src/tools/packs/dnd5e/engine/kits.d.ts +19 -0
  87. package/dist-sdk/server/src/tools/packs/dnd5e/engine/kits.js +130 -0
  88. package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.d.ts +2 -1
  89. package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.js +13 -2
  90. package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.d.ts +6 -0
  91. package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.js +16 -0
  92. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.d.ts +10 -0
  93. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.js +82 -1
  94. package/dist-sdk/server/src/tools/packs/dnd5e/index.js +2 -0
  95. package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.js +51 -6
  96. package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.js +19 -9
  97. package/dist-sdk/server/src/tools/packs/dnd5e/tools/encounter.tool.d.ts +2 -0
  98. package/dist-sdk/server/src/tools/packs/dnd5e/tools/encounter.tool.js +134 -0
  99. package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.js +31 -13
  100. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.d.ts +2 -0
  101. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.js +25 -8
  102. package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.js +70 -4
  103. package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.js +27 -0
  104. package/dist-sdk/server/src/tools/packs/index.d.ts +1 -2
  105. package/dist-sdk/server/src/tools/packs/index.js +5 -11
  106. package/dist-sdk/shared/types/app.types.d.ts +72 -13
  107. package/docs/assets/hierarchy.js +1 -1
  108. package/docs/assets/highlight.css +8 -1
  109. package/docs/assets/icons.js +1 -1
  110. package/docs/assets/icons.svg +1 -1
  111. package/docs/assets/main.js +4 -4
  112. package/docs/assets/navigation.js +1 -1
  113. package/docs/assets/search.js +1 -1
  114. package/docs/assets/style.css +18 -3
  115. package/docs/classes/Agent.html +702 -37
  116. package/docs/classes/Briyah.html +250 -33
  117. package/docs/classes/BriyahConfigService.html +117 -10
  118. package/docs/classes/NativeToolRegistry.html +156 -11
  119. package/docs/classes/PackInstantiationService.html +146 -0
  120. package/docs/classes/PackService.html +247 -0
  121. package/docs/classes/Room.html +1196 -74
  122. package/docs/classes/RoomMessage.html +260 -29
  123. package/docs/enums/MessageAction.html +123 -3
  124. package/docs/functions/availableToolPacks.html +41 -2
  125. package/docs/functions/dnd5eTools.html +42 -3
  126. package/docs/functions/installToolPacks.html +48 -0
  127. package/docs/functions/registerToolPacks.html +54 -6
  128. package/docs/hierarchy.html +42 -1
  129. package/docs/index.html +218 -30
  130. package/docs/interfaces/AgentCreationOptions.html +125 -0
  131. package/docs/interfaces/AgentInfo.html +188 -3
  132. package/docs/interfaces/AgentMessagesResponse.html +71 -2
  133. package/docs/interfaces/AppService.html +2799 -466
  134. package/docs/interfaces/Artifact.html +81 -4
  135. package/docs/interfaces/ArtifactMetadata.html +104 -3
  136. package/docs/interfaces/ArtifactWriteOptions.html +75 -6
  137. package/docs/interfaces/AttachDocumentResponse.html +61 -2
  138. package/docs/interfaces/BriyahConfigOptions.html +107 -10
  139. package/docs/interfaces/ChapterInfo.html +61 -2
  140. package/docs/interfaces/Character.html +81 -2
  141. package/docs/interfaces/CreateAgentResponse.html +56 -2
  142. package/docs/interfaces/CreateRoomResponse.html +61 -2
  143. package/docs/interfaces/CreateStoryResponse.html +56 -2
  144. package/docs/interfaces/FileList.html +56 -2
  145. package/docs/interfaces/FileMetadata.html +84 -3
  146. package/docs/interfaces/IConfigService.html +76 -3
  147. package/docs/interfaces/InstantiateModels.html +64 -0
  148. package/docs/interfaces/InstantiateRoomResult.html +70 -0
  149. package/docs/interfaces/LoadedPack.html +131 -0
  150. package/docs/interfaces/LoggingOptions.html +86 -7
  151. package/docs/interfaces/Message.html +80 -2
  152. package/docs/interfaces/ModelChoice.html +73 -0
  153. package/docs/interfaces/ModelInfo.html +71 -2
  154. package/docs/interfaces/NativeToolDefinition.html +96 -9
  155. package/docs/interfaces/PackAgentTemplate.html +101 -0
  156. package/docs/interfaces/PackRoomTemplate.html +108 -0
  157. package/docs/interfaces/PackView.html +172 -0
  158. package/docs/interfaces/PreparedPromptResponse.html +61 -2
  159. package/docs/interfaces/ProcessTextResponse.html +81 -2
  160. package/docs/interfaces/PromptFile.html +69 -2
  161. package/docs/interfaces/PromptFileContent.html +75 -2
  162. package/docs/interfaces/PromptFilesResponse.html +56 -2
  163. package/docs/interfaces/PromptFolder.html +79 -2
  164. package/docs/interfaces/PromptFolderDefaults.html +155 -0
  165. package/docs/interfaces/PromptFolderDefaultsResponse.html +66 -0
  166. package/docs/interfaces/PromptFoldersResponse.html +56 -2
  167. package/docs/interfaces/RoomDetails.html +133 -4
  168. package/docs/interfaces/RoomInfo.html +84 -2
  169. package/docs/interfaces/RoomMessageUpdate.html +91 -2
  170. package/docs/interfaces/RoomMessagesResponse.html +61 -2
  171. package/docs/interfaces/SendMessageResult.html +61 -2
  172. package/docs/interfaces/StoryErrorEvent.html +76 -4
  173. package/docs/interfaces/StoryIdea.html +71 -2
  174. package/docs/interfaces/StoryInfo.html +173 -3
  175. package/docs/interfaces/StoryIntroduceCharacterEvent.html +71 -4
  176. package/docs/interfaces/StoryProgressChapterEvent.html +64 -3
  177. package/docs/interfaces/StoryState.html +99 -6
  178. package/docs/interfaces/StoryStateEvent.html +69 -3
  179. package/docs/interfaces/ToolArtifact.html +81 -4
  180. package/docs/interfaces/ToolCaller.html +75 -6
  181. package/docs/interfaces/ToolDefinition.html +76 -2
  182. package/docs/interfaces/ToolHelpers.html +91 -6
  183. package/docs/interfaces/ToolParameter.html +71 -2
  184. package/docs/interfaces/ToolRoomAccess.html +200 -24
  185. package/docs/interfaces/ToolSummary.html +71 -2
  186. package/docs/interfaces/ToolsResponse.html +66 -2
  187. package/docs/interfaces/Transaction.html +96 -2
  188. package/docs/interfaces/TransactionHistoryResponse.html +61 -2
  189. package/docs/modules.html +53 -1
  190. package/docs/types/PackOrigin.html +34 -0
  191. package/docs/types/PromptScope.html +34 -1
  192. package/docs/types/RoomTurnMode.html +42 -0
  193. package/docs/types/ToolContext.html +36 -2
  194. package/docs/types/ToolRunResult.html +34 -1
  195. package/package.json +139 -139
  196. package/src/tools/packs/dnd5e/README.md +162 -26
  197. package/dist-sdk/server/src/library/library.service.d.ts +0 -14
  198. package/dist-sdk/server/src/library/library.service.js +0 -165
  199. package/docs/functions/enabledToolPacks.html +0 -2
  200. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/campaign_designer-setting.md +0 -0
  201. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/character_creator-basics.md +0 -0
  202. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-barbarian.md +0 -0
  203. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-bard.md +0 -0
  204. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-cleric.md +0 -0
  205. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-druid.md +0 -0
  206. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-fighter.md +0 -0
  207. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-monk.md +0 -0
  208. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-paladin.md +0 -0
  209. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-ranger.md +0 -0
  210. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-rogue.md +0 -0
  211. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-sorcerer.md +0 -0
  212. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-warlock.md +0 -0
  213. /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-wizard.md +0 -0
  214. /package/data/{common/prompts/campaign_designer → packs/dnd5e/prompts/battle_master}/system_instruction.prompt +0 -0
  215. /package/data/{common → packs/dnd5e}/prompts/campaign_designer/defaults_config.json +0 -0
  216. /package/data/{common → packs/dnd5e}/prompts/campaign_designer/perceive.json +0 -0
  217. /package/data/{common → packs/dnd5e}/prompts/campaign_designer/perceive.prompt +0 -0
  218. /package/data/{common/prompts/character_creator → packs/dnd5e/prompts/campaign_designer}/system_instruction.prompt +0 -0
  219. /package/data/{common → packs/dnd5e}/prompts/character_creator/perceive.json +0 -0
  220. /package/data/{common/prompts/dnd_player → packs/dnd5e/prompts/character_creator}/system_instruction.prompt +0 -0
  221. /package/data/{common → packs/dnd5e}/prompts/dnd_player/defaults_config.json +0 -0
  222. /package/data/{common → packs/dnd5e}/prompts/dnd_player/perceive.json +0 -0
  223. /package/data/{common/prompts/dnd_room_moderator → packs/dnd5e/prompts/dnd_player}/system_instruction.prompt +0 -0
  224. /package/data/{common → packs/dnd5e}/prompts/dnd_room_moderator/defaults_config.json +0 -0
  225. /package/data/{common/prompts/dungeon_master → packs/dnd5e/prompts/dnd_room_moderator}/system_instruction.prompt +0 -0
  226. /package/data/{common → packs/dnd5e}/prompts/dungeon_master/compact_agent.prompt +0 -0
  227. /package/data/{common → packs/dnd5e}/prompts/dungeon_master/perceive.json +0 -0
package/README.md CHANGED
@@ -1,849 +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
- const room = await appService.createRoom(name, goal, agentIds);
252
- const rooms = await appService.listRooms();
253
- await appService.sendRoomMessage(roomId, content, sender, action?);
254
-
255
- // Agents that belong to a room: created inside it, named after it, deleted with it,
256
- // and left out of listAgents(). agentName is the bare name; the room's is prefixed on.
257
- await appService.createRoomAgent(roomId, { aiServiceName, agentName, description, aiModel, promptName });
258
- await appService.removeRoomAgent(roomId, agentId);
259
-
260
- // Native tools (recommended for SDK integrations — see Example 8)
261
- briyah.registerTool({ name, description, parameters, handler }); // process-level
262
- briyah.listNativeTools();
263
-
264
- // User-authored (string-code) tools — only when allowUserAuthoredTools is enabled
265
- const tools = await appService.listTools();
266
- const tool = await appService.createTool({ name, description, parameters, code, timeoutMs? });
267
- await appService.updateTool(name, tool);
268
- await appService.deleteTool(name);
269
- const result = await appService.testTool(name, args); // { ok: true, result } | { ok: false, error }
270
-
271
- // Story Management
272
- const story = await appService.createStory(name, idea, userCharacterDesc, otherCharactersDesc, storyModel?);
273
- await appService.progressStory(storyId);
274
-
275
- // Text Processing
276
- const result = await appService.processText(agentId, text);
277
-
278
- // Image Generation (image-capable providers; called on the Agent object — see Example 9)
279
- const { artifactId } = await agent.generateImage(prompt, imageProperties);
280
- const edited = await agent.editImage(prompt, imageProperties, referenceArtifactIds);
281
-
282
- // File Attachments
283
- const attachment = await appService.attachDocument(agentId, fileName, fileData);
284
- await appService.deleteAttachedFile(agentId, fileName); // by filename
285
- await appService.deleteAttachedFileById(documentId); // by document ID
286
- ```
287
-
288
- ## Prompt Folders
289
-
290
- An agent's behaviour comes from a **prompt folder**, not from its description. The folder
291
- holds the templates the room renders on every turn — most importantly `perceive.prompt`, which
292
- tells the agent what it is and what it may do, and `perceive.json`, the JSON schema its replies
293
- must satisfy. Two agents on the same model with the same description behave completely
294
- differently if they were built from different folders.
295
-
296
- `init()` seeds the bundled folders into `{dataPath}/common/prompts/`, so they are on disk before
297
- your first `createAgent` call. Existing files are preserved on upgrade, so anything you edit
298
- survives.
299
-
300
- ```typescript
301
- const appService = briyah.getAppService('user-123');
302
- console.log(appService.listPromptFolders());
303
- // default, dungeon_master, dnd_player, character_creator, campaign_designer,
304
- // dnd_room_moderator, narrator, character, illustrator, ...
305
- ```
306
-
307
- **The folder is the sixth argument to `createAgent`, and it defaults to `'default'`** — a
308
- generic conversational agent. Passing a role folder is what makes the agent that role:
309
-
310
- ```typescript
311
- const dm = appService.createAgent(
312
- 'Anthropic',
313
- 'Dungeon Master', // agentName — a label; used in logs and the UI
314
- 'DM', // agentNickname — the name the room routes by
315
- 'Runs the game.',
316
- 'claude-sonnet-5',
317
- 'dungeon_master', // <- the prompt folder
318
- );
319
- ```
320
-
321
- `agentNickname` is the identity: messages are addressed to it, artifact viewers are lists of
322
- it, and it is what an agent writes into `targets`. `agentName` is a label. Give a character the
323
- nickname you want it called by.
324
-
325
- To write your own folder, copy a bundled one out of `{dataPath}/common/prompts/`, rename the
326
- directory, and edit it — a folder in the user data directory takes precedence over the common
327
- one of the same name.
328
-
329
- ## Tool Packs
330
-
331
- A tool pack is a set of native tools that ships with Briyah and registers only when asked for.
332
- `dnd5e` is the one that exists: seventeen tools for dice, character sheets, the rules engine and
333
- a bestiary. Turn it on either way:
334
-
335
- ```typescript
336
- // By name — the SDK registers the pack during construction
337
- const briyah = new Briyah({ envOverrides: { BRIYAH_TOOL_PACKS: 'dnd5e' } });
338
-
339
- // Or pass the definitions yourself, which also lets you filter or wrap them
340
- import { dnd5eTools, availableToolPacks } from 'briyah';
341
- const briyah = new Briyah({ tools: dnd5eTools() });
342
- console.log(availableToolPacks()); // ['dnd5e']
343
- ```
344
-
345
- Registering makes the tools *grantable*, not granted. An agent may only run the ones named in
346
- its `toolNames`:
347
-
348
- ```typescript
349
- const dm = appService.createAgent(
350
- 'Anthropic', 'Dungeon Master', 'DM', 'Runs the game.', 'claude-sonnet-5', 'dungeon_master',
351
- undefined, null, 0, '',
352
- { toolNames: ['roll_dice', 'check', 'apply_hp', 'stat_block', 'read_sheet'] },
353
- );
354
- ```
355
-
356
- Packs also ship read-only **documents** — rules text an agent carries in every call. They seed
357
- into `{dataPath}/common/artifacts/`, appear in `listUserArtifacts()` alongside your own, and
358
- attach by id:
359
-
360
- ```typescript
361
- await appService.attachArtifactToAgent(dm.id, 'pack:dnd5e.dungeon_master-procedure');
362
- await appService.attachArtifactToAgent(player.id, 'pack:dnd5e.class-bard');
363
- ```
364
-
365
- A document sits in that agent's cached prompt prefix on every call, so attach what it needs and
366
- nothing more. `src/tools/packs/dnd5e/README.md` in this package lists all seventeen tools and
367
- which agent each document belongs to.
368
-
369
- ## Usage Examples
370
-
371
- ### Example 1: Multi-User Setup
372
-
373
- ```typescript
374
- import { Briyah } from 'briyah';
375
-
376
- // Initialize once at application startup
377
- const briyah = new Briyah({
378
- dataPath: './data/briyah',
379
- startingBalance: 10.00
380
- });
381
-
382
- await briyah.init();
383
-
384
- // In your route handler or service
385
- async function handleUserRequest(userId: string, message: string) {
386
- const appService = briyah.getAppService(userId);
387
-
388
- // Each user gets their own isolated AppService
389
- const agents = await appService.listAgents();
390
-
391
- // ... process user request
392
- }
393
-
394
- // Cleanup at application shutdown
395
- process.on('SIGINT', async () => {
396
- await briyah.shutdown();
397
- process.exit(0);
398
- });
399
- ```
400
-
401
- ### Example 2: Custom Data Path
402
-
403
- ```typescript
404
- import { Briyah } from 'briyah';
405
- import path from 'path';
406
-
407
- const briyah = new Briyah({
408
- dataPath: path.join(__dirname, '..', 'user-data', 'briyah'),
409
- userServiceCacheTimeoutMinutes: 60 // 1 hour cache
410
- });
411
-
412
- await briyah.init();
413
- ```
414
-
415
- ### Example 3: Testing Configuration
416
-
417
- ```typescript
418
- import { Briyah } from 'briyah';
419
-
420
- const testBriyah = new Briyah({
421
- dataPath: './test-data',
422
- startingBalance: 100.00,
423
- userServiceCacheTimeoutMinutes: 5,
424
- envOverrides: {
425
- ANTHROPIC_API_KEY: process.env.TEST_ANTHROPIC_KEY,
426
- OPENAI_API_KEY: process.env.TEST_OPENAI_KEY
427
- }
428
- });
429
-
430
- await testBriyah.init();
431
-
432
- // Run tests...
433
-
434
- await testBriyah.shutdown();
435
- ```
436
-
437
- ### Example 4: Agent Creation and Text Processing
438
-
439
- ```typescript
440
- const appService = briyah.getAppService('user-123');
441
-
442
- // Create an agent
443
- const agent = appService.createAgent(
444
- 'Anthropic', // provider
445
- 'AI Assistant', // name
446
- 'James', // nickname
447
- 'A helpful AI assistant', // description
448
- 'claude-haiku-4-5' // model
449
- );
450
-
451
- if (!agent.id) throw new Error('Agent creation failed');
452
- console.log(`Created agent: ${agent.id}`);
453
-
454
- // Process text with the agent
455
- const result = await appService.processText(
456
- agent.id,
457
- 'What is the capital of France?'
458
- );
459
-
460
- console.log(`Response: ${result.result}`);
461
- console.log(`Cost: $${result.totalCost}`);
462
- console.log(`Tokens: ${(result.totalInputTokens ?? 0) + (result.totalOutputTokens ?? 0)}`);
463
- ```
464
-
465
- ### Example 5: Multi-Agent Room Conversation
466
-
467
- ```typescript
468
- const appService = briyah.getAppService('user-123');
469
-
470
- // Create agents
471
- const analyst = appService.createAgent('OpenAI', 'Analyst', 'Analyst', 'Data analyst', 'gpt-4');
472
- const writer = appService.createAgent('Anthropic', 'Writer', 'Writer', 'Content writer', 'claude-haiku-4-5');
473
-
474
- if (!analyst.id || !writer.id) throw new Error('Agent creation failed');
475
-
476
- // Create a room with both agents
477
- const room = await appService.createRoom(
478
- 'Analysis Session',
479
- 'Analyze sales data and produce a written summary',
480
- [analyst.id, writer.id]
481
- );
482
-
483
- // Send a message to start the conversation
484
- await appService.sendRoomMessage(
485
- room.roomId,
486
- 'Please analyze the sales data for Q4',
487
- 'Analyst',
488
- 'speak'
489
- );
490
-
491
- // The agents will automatically respond and interact
492
- // Check room messages to see the conversation
493
- const messages = await appService.getRoomMessages(room.roomId);
494
- console.log(`Messages: ${messages.messages.length}`);
495
- ```
496
-
497
- ### Example 6: Story Message Emitter
498
-
499
- The story message emitter delivers real-time events during gameplay. Subscribe to it after creating the story but before the first player turn, so no events are missed.
500
-
501
- ```typescript
502
- import type {
503
- StoryStateEvent,
504
- StoryIntroduceCharacterEvent,
505
- StoryProgressChapterEvent,
506
- StoryErrorEvent,
507
- } from 'briyah';
508
-
509
- const app = briyah.getAppService('user-123');
510
-
511
- const story = await app.createStory(
512
- 'The Lost Kingdom',
513
- 'A medieval fantasy where ancient ruins hold a terrible secret',
514
- 'A disgraced knight seeking redemption'
515
- );
516
-
517
- const emitter = app.getStoryMessageEmitter(story.id);
518
-
519
- // Fires after every turn with the full updated game state.
520
- emitter.on('story-state', async (event: StoryStateEvent) => {
521
- const { state } = event;
522
- console.log('Latest message:', state.latestRoomMessage?.content);
523
-
524
- // Detect the player's turn by comparing speaker names.
525
- // Do NOT use state.humanPrompt for this — it is a UI display string,
526
- // not a reliable turn indicator.
527
- if (state.currentSpeaker === state.userAgentName) {
528
- const input = await promptPlayer(state.humanPrompt);
529
- await app.respondToStory(story.id, input);
530
- }
531
- });
532
-
533
- // Fires when the narrator wants to introduce a new character.
534
- // The host app should present this to the player before acting.
535
- // Accept by calling introduceCharacterToStory, or decline with declineCharacter.
536
- emitter.on('suggest-introduce-character', async (event: StoryIntroduceCharacterEvent) => {
537
- const accept = await askPlayer(`Add ${event.characterName} to the story?`);
538
- if (accept) {
539
- await app.introduceCharacterToStory(story.id, event.characterName!, '', undefined, true);
540
- } else {
541
- await app.declineCharacter(story.id, event.characterName!);
542
- }
543
- });
544
-
545
- // Fires when the narrator wants to advance to the next chapter.
546
- // Call progressStory to accept. Ignoring the event stays in the current chapter —
547
- // there is no explicit rejection call.
548
- emitter.on('suggest-progress-chapter', async (_event: StoryProgressChapterEvent) => {
549
- const accept = await askPlayer('The narrator suggests ending this chapter. Continue?');
550
- if (accept) {
551
- await app.progressStory(story.id);
552
- }
553
- });
554
-
555
- // Fires on fatal errors during room processing.
556
- // Named 'story-error' rather than 'error' to avoid Node.js throwing when no
557
- // listener is attached.
558
- emitter.on('story-error', (event: StoryErrorEvent) => {
559
- if (event.errorType === 'InsufficientBalanceError') {
560
- console.error('Out of credits:', event.message);
561
- } else {
562
- console.error(`Story error [${event.errorType}]:`, event.message);
563
- }
564
- });
565
- ```
566
-
567
- ### Example 7: Recording Payments and Managing Balance
568
-
569
- Briyah does not process payments itself — your application handles the payment provider interaction. Once a payment is confirmed, use `AppService` to record the transaction, credit the user's balance, and restart any stories that stalled due to insufficient funds.
570
-
571
- ```typescript
572
- const app = briyah.getAppService(userId);
573
-
574
- // --- When your payment provider initiates a charge ---
575
- // Record it as pending so the transaction log stays consistent.
576
- await app.recordTransaction(amount, paymentIntentId, 'pending');
577
-
578
- // --- When your payment provider webhook confirms success ---
579
- await app.updateTransactionStatus(paymentIntentId, 'succeeded');
580
- await app.addBalance(amount);
581
-
582
- // Resume any stories that paused mid-turn due to InsufficientBalanceError.
583
- await app.resumePausedStories();
584
-
585
- // --- When a payment fails or is cancelled ---
586
- await app.updateTransactionStatus(paymentIntentId, 'failed');
587
-
588
- // --- Querying balance and history ---
589
- const balance = app.getBalance();
590
-
591
- const { transactions, total } = await app.getTransactions(50, 0);
592
-
593
- const tx = await app.getTransactionByPaymentId(paymentIntentId);
594
- console.log(tx?.status); // 'pending' | 'succeeded' | 'failed' | 'cancelled'
595
- ```
596
-
597
- To push real-time balance updates to a connected client (e.g. via SSE), subscribe to the balance emitter before crediting the user:
598
-
599
- ```typescript
600
- const emitter = app.getBalanceMessageEmitter(userId);
601
- emitter.on('update', (newBalance: number) => {
602
- // Push newBalance to the client
603
- });
604
- ```
605
-
606
- ### Example 8: Registering Native Tools with Opaque Context
607
-
608
- Native tools are functions you implement in your host code and register once with `briyah.registerTool`. Grant a tool to an agent by adding its name to `agent.toolNames`; the agent then calls it on its own (via the EXECUTE room action) when a conversation needs it, chaining several calls privately before it replies.
609
-
610
- Each call receives a third argument — an **opaque context** you pass to `sendRoomMessage`. Briyah never inspects it; it hands it straight to your handler. Use it for per-interaction data the model must not be able to choose. The declared `parameters` are what the LLM fills in; scoping data (which record, which tenant, a DB handle) belongs in context, so a confused or adversarial agent cannot target data outside the current interaction.
611
-
612
- ```typescript
613
- import { Briyah } from 'briyah';
614
-
615
- const briyah = new Briyah({ dataPath: './data/briyah', startingBalance: 10.00 });
616
- await briyah.init();
617
-
618
- // Register a tool that reads its scope from context, not from the LLM's args.
619
- briyah.registerTool({
620
- name: 'add_note',
621
- description: "Add a note to the record the user currently has open",
622
- parameters: [
623
- { name: 'text', type: 'string', description: 'The note text', required: true }
624
- ],
625
- handler: async (args, helpers, context) => {
626
- const { db, recordId } = context as { db: MyDb; recordId: string };
627
- await db.addNote(recordId, args.text); // recordId comes from context — the LLM cannot set it
628
- return { added: true };
629
- },
630
- timeoutMs: 15000 // optional; default 30s, max 120s
631
- });
632
-
633
- // Grant it to an agent (grants are enforced server-side).
634
- const assistant = app.createAgent('Anthropic', 'Assistant', 'Assistant',
635
- 'A helpful assistant that manages the open record', 'claude-haiku-4-5');
636
- assistant.toolNames = ['add_note'];
637
- assistant.save();
638
-
639
- // When the user acts on record "rec_42", pass that scope as context. Any tool the
640
- // agent calls during the resulting turn receives it; other rooms/interactions are
641
- // unaffected. A log-only 'tool' message records each call (visible when fetching
642
- // messages with includeThoughts=true).
643
- await app.sendRoomMessage(
644
- roomId,
645
- 'Add a note that the client called about renewal.',
646
- 'User',
647
- 'speak',
648
- [],
649
- false,
650
- { db, recordId: 'rec_42' } // opaque context
651
- );
652
- ```
653
-
654
- Because each Briyah `userId` gets its own isolated `AppService`, data directory, and balance, mapping one Briyah user per tenant (customer, workspace, org) gives you tenant isolation and per-tenant billing for free; the opaque context then scopes each call within that tenant.
655
-
656
- Agents can also delegate: an agent may respond with a `commission` action naming other agents, each of which researches independently (using its granted tools, with the same context) and replies with a `deliver`. The commissioner receives all deliverables at once and responds before the conversation continues. No SDK calls are needed for this — it is driven by the agents themselves.
657
-
658
- User-authored (string-code) tools remain available via `createTool`/`updateTool`/`testTool` when `allowUserAuthoredTools` is enabled, for trusted single-user setups.
659
-
660
- ### Example 9: Self-Hosted Image Generation with ComfyUI
661
-
662
- The `ComfyUI` provider generates images on a self-hosted [ComfyUI](https://github.com/comfyanonymous/ComfyUI) server. It is image-only: `generateImage`/`editImage` work, `textPrompt` throws. Set `COMFYUI_BASE_URL` to enable it. ComfyUI has no authentication of its own — keep it on a LAN/VPN or behind an authenticated reverse proxy (pass proxy credentials via `COMFYUI_EXTRA_HEADERS`).
663
-
664
- For this provider the agent's *model name* selects a **workflow-template pair**, not a checkpoint. Two pairs ship by default:
665
-
666
- | Pair name | Model | Files required on the ComfyUI server |
667
- |---|---|---|
668
- | `flux2-dev` | FLUX.2 dev (FP8 mixed) | `diffusion_models/flux2_dev_fp8mixed.safetensors`, `text_encoders/mistral_3_small_flux2_bf16.safetensors`, `vae/flux2-vae.safetensors` |
669
- | `flux-kontext` | Flux.1 Kontext dev (FP8) | `diffusion_models/flux1-dev-kontext_fp8_scaled.safetensors`, `text_encoders/clip_l.safetensors` + `t5xxl_fp8_e4m3fn_scaled.safetensors`, `vae/ae.safetensors` |
670
-
671
- `flux2-dev` has substantially better multi-reference character consistency and wants a 32 GB-class GPU; `flux-kontext` runs on 16 GB-class cards.
672
-
673
- ```typescript
674
- import { Briyah } from 'briyah';
675
-
676
- const briyah = new Briyah({ dataPath: './data/briyah', startingBalance: 10.00 });
677
- await briyah.init();
678
-
679
- const app = briyah.getAppService('user-123');
680
-
681
- // Model name = workflow pair name
682
- const artist = app.createAgent('ComfyUI', 'Artist', 'Artist',
683
- 'Image generation agent', 'flux2-dev');
684
-
685
- // Text-to-image. Resolves to { artifactId } on success or { error } on failure.
686
- const generated = await artist.generateImage(
687
- 'A lighthouse on a rocky coast at dusk',
688
- { width: 1024, height: 1024 } // optional; a fixed seed may also be passed
689
- );
690
- if (generated.error) throw new Error(String(generated.error));
691
-
692
- // Generated images are stored as artifacts (PNG)
693
- const png = artist.artifactService.getArtifact(generated.artifactId);
694
-
695
- // Image-to-image with reference images. Each referenced artifact is uploaded
696
- // and conditioned on separately (chained ReferenceLatent nodes). Order is
697
- // preserved, so the prompt can refer to "Image 1", "Image 2", ...
698
- const edited = await artist.editImage(
699
- 'The character from Image 2 stands in the setting from Image 1',
700
- { width: 1024, height: 1024 },
701
- [sceneArtifactId, portraitArtifactId]
702
- );
703
- ```
704
-
705
- Notes:
706
-
707
- - **Cost**: generation is free by default — no balance is checked or decremented. To charge users, pass `centsPerImage` in the image properties; the balance gate then applies.
708
- - **Latency**: the GPU processes one job at a time and the first generation after server start loads the model weights. `COMFYUI_TIMEOUT_MS` (default 10 minutes) covers queue wait plus cold start.
709
- - **Stories**: to make a pair selectable in the story UI's image-model dropdown, add an entry to `{dataPath}/common/config/image_models.json` with `"service": "ComfyUI"` and the pair name as `"model"` in the `generation` and `editing` blocks, with `"centsPerImage": 0`.
710
-
711
- **Custom workflows.** Any ComfyUI workflow can be used: build it in the ComfyUI web UI, run it once, then use Export (API format) and replace the values you want parameterized with tokens — `{{prompt}}` (may be embedded in a longer string), `{{seed}}`, `{{width}}`, `{{height}}` (replaced as numbers), and `{{ref_image}}` (edit workflows, the `LoadImage` input). Save the files as `{name}.t2i.json` (used by `generateImage`) and `{name}.edit.json` (used by `editImage`) in `{dataPath}/common/config/comfyui-workflows/`, or in `{dataPath}/user/{userId}/comfyui-workflows/` for a per-user override (checked first). The pair name becomes the model name. For multi-reference support, an edit workflow must contain exactly one `ReferenceLatent` node fed by a `VAEEncode` fed by a `LoadImage`; extra references are added at request time by cloning that chain.
712
-
713
- ### Example 10: A turn-based table with a human player
714
-
715
- Example 5 sends one message and reads the transcript back, which suits a batch job. A game or
716
- any human-in-the-loop app needs the other shape: the agents take several turns among themselves,
717
- then stop and wait for the person. Three things make that work.
718
-
719
- **`turnMode: 'directed'`** — only the agent a message names is asked to reply, and the room
720
- leader answers anything it cannot place. The default, `'broadcast'`, prompts *every* agent for
721
- *every* message and keeps one reply, which costs several times as much and is wrong for a table
722
- where one person speaks at a time.
723
-
724
- **A human-controlled agent** — `createAgent`'s seventh argument. The room delivers messages to
725
- it and then stops rather than generating a reply, which is what yields the floor to your console.
726
-
727
- **The room message emitter** — the only way to see the conversation as it happens. It fires on
728
- every change with the newest message and the room's state.
729
-
730
- ```typescript
731
- import { Briyah, dnd5eTools } from 'briyah';
732
- import * as readline from 'node:readline/promises';
733
-
734
- const briyah = new Briyah({ dataPath: './briyah-data', tools: dnd5eTools() });
735
- await briyah.init(); // seeds prompt folders and pack documents
736
- const app = briyah.getAppService('user-123');
737
-
738
- const dm = app.createAgent(
739
- 'Anthropic', 'Dungeon Master', 'DM', 'Runs the game.', 'claude-sonnet-5',
740
- 'dungeon_master', undefined, null, 0, '',
741
- { toolNames: ['roll_dice', 'check', 'apply_hp', 'stat_block', 'read_sheet'] },
742
- );
743
- const rogue = app.createAgent(
744
- 'Anthropic', 'Vex', 'Vex', 'A wary scout.', 'claude-haiku-4-5', 'dnd_player',
745
- );
746
- // The seventh argument is what makes this one wait for a person.
747
- const you = app.createAgent(
748
- 'Anthropic', 'Homer', 'Homer', 'A hopeful bard.', 'claude-haiku-4-5', 'dnd_player',
749
- true,
750
- );
751
-
752
- // createAgent builds the agent in memory; save() writes it to disk. Without this the
753
- // table exists for this process only and is gone on restart.
754
- [dm, rogue, you].forEach((agent) => agent.save());
755
-
756
- await app.attachArtifactToAgent(dm.id!, 'pack:dnd5e.dungeon_master-procedure');
757
- await app.attachArtifactToAgent(rogue.id!, 'pack:dnd5e.class-rogue');
758
- await app.attachArtifactToAgent(you.id!, 'pack:dnd5e.class-bard');
759
-
760
- const { roomId } = await app.createRoom(
761
- 'The Sunken Barrow',
762
- 'A three-room dungeon crawl.',
763
- [dm.id!, rogue.id!, you.id!],
764
- 'DM', // roomLeader — answers anything the room cannot place
765
- 'directed', // turnMode
766
- );
767
-
768
- // Watch the conversation. `waitingForHuman` is the cue to prompt your player.
769
- const io = readline.createInterface({ input: process.stdin, output: process.stdout });
770
- app.getRoomMessageEmitter(roomId).on('update', async (state) => {
771
- if (state.latestMessage && state.latestMessage.sender !== 'Homer') {
772
- console.log(`${state.latestMessage.sender}: ${state.latestMessage.content}`);
773
- }
774
- if (state.waitingForHuman && !state.processingInProgress) {
775
- const line = await io.question('> ');
776
- await app.sendRoomMessage(roomId, line, 'Homer', 'speak', ['DM']);
777
- }
778
- });
779
-
780
- await app.sendRoomMessage(roomId, 'Begin the adventure.', 'Homer', 'speak', ['DM']);
781
- ```
782
-
783
- The emitter payload carries `latestMessage`, `messageIndex`, `totalCost`, `isPaused`,
784
- `currentSpeaker`, `processingInProgress` and `waitingForHuman`. `messageIndex` counts messages
785
- with thoughts and tool notices excluded, so compare it against a list you fetched the same way —
786
- `getRoomMessages(roomId)` — or simply refetch when they disagree.
787
-
788
- Two notes for a long-running process. Call `await briyah.shutdown()` before exiting or the
789
- process will hang on open handles. And a room with no human-controlled agent never stops on its
790
- own: the agents talk until the leader adjourns.
791
-
792
- ## Data Storage
793
-
794
- Briyah stores data in the following structure:
795
-
796
- ```
797
- {dataPath}/
798
- ├── common/ # Shared across all users
799
- │ ├── config/ # LLM pricing and image-model config
800
- │ ├── prompts/ # Global prompt templates
801
- │ └── published-agents.json # Published agent mappings
802
- └── user/
803
- └── {userId}/ # Per-user data
804
- ├── agents/ # Agent configs and histories (one JSON per agent)
805
- ├── rooms/ # Room metadata, message logs, artifacts (one folder per room)
806
- ├── stories/ # Story state
807
- ├── tools/ # User-defined tools (one JSON per tool)
808
- ├── prompts/ # User-specific prompts
809
- ├── upload/ # User file attachments
810
- ├── transactions/ # Transaction records
811
- └── userconfig/ # User preferences and balance
812
- ```
813
-
814
- ## Multi-Instance Support
815
-
816
- You can create multiple Briyah instances with different configurations:
817
-
818
- ```typescript
819
- const briyah1 = new Briyah({ dataPath: './data1' });
820
- const briyah2 = new Briyah({ dataPath: './data2' });
821
-
822
- await briyah1.init();
823
- await briyah2.init();
824
-
825
- // Each instance has isolated data
826
- const user1Service = briyah1.getAppService('user-123');
827
- const user2Service = briyah2.getAppService('user-123');
828
- // These are completely separate services with different data paths
829
- ```
830
-
831
- **Note:** Singleton services (LLM providers, message emitters) are shared across all Briyah instances within the same process. This is safe because they are stateless or keyed by ID.
832
-
833
- ## Troubleshooting
834
-
835
- ### "Must call init() before getAppService()"
836
-
837
- Make sure to call `await briyah.init()` before calling `getAppService()`.
838
-
839
- ### "No LLM provider API keys configured"
840
-
841
- Set at least one of the required API key environment variables (ANTHROPIC_API_KEY, OPENAI_API_KEY, etc.).
842
-
843
- ### "STARTING_BALANCE environment variable is required"
844
-
845
- Set the `STARTING_BALANCE` environment variable or pass `startingBalance` in the constructor options.
846
-
847
- ### Cache not working as expected
848
-
849
- Check the cache statistics with `getCacheStats()` and adjust `userServiceCacheTimeoutMinutes` in the constructor options.
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.