briyah 1.5.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1092 -994
- package/data/common/config/markup +1 -1
- package/data/common/prompts/character/progress_character.json +5 -5
- package/data/common/prompts/illustrator/describe_scene.json +11 -3
- package/data/common/prompts/perceive.json +2 -2
- package/data/common/prompts/room_moderator/moderate.json +34 -34
- package/data/common/prompts/story_moderator/moderate.json +62 -62
- package/data/packs/dnd5e/agents/battle-master.json +6 -0
- package/data/packs/dnd5e/agents/campaign-designer.json +6 -0
- package/data/packs/dnd5e/agents/character-creator.json +6 -0
- package/data/packs/dnd5e/agents/dungeon-master.json +6 -0
- package/data/packs/dnd5e/agents/player.json +13 -0
- package/data/packs/dnd5e/agents/table-moderator.json +6 -0
- package/data/{common/artifacts/dnd5e/dungeon_master-procedure.md → packs/dnd5e/artifacts/battle_master-combat.md} +31 -131
- package/data/packs/dnd5e/artifacts/dungeon_master-procedure.md +192 -0
- package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/manifest.json +8 -2
- package/data/packs/dnd5e/pack.json +6 -0
- package/data/packs/dnd5e/prompts/battle_master/defaults_config.json +23 -0
- package/data/packs/dnd5e/prompts/battle_master/perceive.json +33 -0
- package/data/packs/dnd5e/prompts/battle_master/perceive.prompt +378 -0
- package/data/{common → packs/dnd5e}/prompts/character_creator/defaults_config.json +1 -1
- package/data/{common → packs/dnd5e}/prompts/character_creator/perceive.prompt +29 -0
- package/data/{common → packs/dnd5e}/prompts/dnd_player/perceive.prompt +40 -22
- package/data/{common → packs/dnd5e}/prompts/dnd_room_moderator/moderate.json +34 -34
- package/data/{common → packs/dnd5e}/prompts/dnd_room_moderator/moderate.prompt +14 -3
- package/data/{common → packs/dnd5e}/prompts/dungeon_master/defaults_config.json +1 -0
- package/data/{common → packs/dnd5e}/prompts/dungeon_master/perceive.prompt +122 -115
- package/data/packs/dnd5e/prompts/dungeon_master/system_instruction.prompt +0 -0
- package/data/packs/dnd5e/rooms/table.json +16 -0
- package/dist-sdk/server/src/ai/LLM/base-ai.service.js +4 -13
- package/dist-sdk/server/src/ai/LLM/deepseek.service.d.ts +2 -1
- package/dist-sdk/server/src/ai/LLM/deepseek.service.js +65 -77
- package/dist-sdk/server/src/ai/agent-config.d.ts +2 -0
- package/dist-sdk/server/src/ai/agent-store.service.js +8 -0
- package/dist-sdk/server/src/ai/agent.d.ts +6 -0
- package/dist-sdk/server/src/ai/agent.js +25 -2
- package/dist-sdk/server/src/ai/artifact.service.d.ts +3 -1
- package/dist-sdk/server/src/ai/artifact.service.js +12 -5
- package/dist-sdk/server/src/ai/pack-artifacts.d.ts +3 -3
- package/dist-sdk/server/src/ai/pack-artifacts.js +21 -15
- package/dist-sdk/server/src/app/user-service-factory.js +9 -1
- package/dist-sdk/server/src/app.controller.d.ts +11 -11
- package/dist-sdk/server/src/app.controller.js +178 -88
- package/dist-sdk/server/src/app.service.d.ts +28 -7
- package/dist-sdk/server/src/app.service.js +121 -91
- package/dist-sdk/server/src/common/errors.d.ts +0 -3
- package/dist-sdk/server/src/common/errors.js +1 -11
- package/dist-sdk/server/src/config/prompt-resolver.d.ts +39 -0
- package/dist-sdk/server/src/config/prompt-resolver.js +189 -0
- package/dist-sdk/server/src/config/user-config.service.d.ts +17 -0
- package/dist-sdk/server/src/config/user-config.service.js +103 -0
- package/dist-sdk/server/src/config/user-paths.service.d.ts +4 -4
- package/dist-sdk/server/src/config/user-paths.service.js +12 -16
- package/dist-sdk/server/src/packs/pack-instantiation.service.d.ts +35 -0
- package/dist-sdk/server/src/packs/pack-instantiation.service.js +154 -0
- package/dist-sdk/server/src/packs/pack-manifest.d.ts +52 -0
- package/dist-sdk/server/src/packs/pack-manifest.js +256 -0
- package/dist-sdk/server/src/packs/pack.service.d.ts +24 -0
- package/dist-sdk/server/src/packs/pack.service.js +151 -0
- package/dist-sdk/server/src/room/room-config.d.ts +5 -0
- package/dist-sdk/server/src/room/room-store.service.d.ts +3 -0
- package/dist-sdk/server/src/room/room-store.service.js +41 -5
- package/dist-sdk/server/src/room/room.d.ts +7 -0
- package/dist-sdk/server/src/room/room.js +29 -1
- package/dist-sdk/server/src/sdk/briyah.d.ts +2 -0
- package/dist-sdk/server/src/sdk/briyah.js +45 -8
- package/dist-sdk/server/src/sdk/index.d.ts +6 -1
- package/dist-sdk/server/src/sdk/index.js +6 -2
- package/dist-sdk/server/src/shared/shared.module.js +0 -3
- package/dist-sdk/server/src/story/story.service.d.ts +2 -2
- package/dist-sdk/server/src/tools/packs/dnd5e/data/kits.d.ts +17 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/kits.js +54 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/races.d.ts +3 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/races.js +6 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.d.ts +2 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.js +4 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/backgrounds.d.ts +1 -1
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/backgrounds.js +6 -3
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.d.ts +3 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.js +45 -5
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/encounter.d.ts +27 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/encounter.js +103 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/foes.d.ts +7 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/foes.js +83 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/kits.d.ts +19 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/kits.js +130 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.d.ts +2 -1
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.js +13 -2
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.d.ts +6 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.js +16 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.d.ts +10 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.js +82 -1
- package/dist-sdk/server/src/tools/packs/dnd5e/index.js +2 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.js +51 -6
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.js +19 -9
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/encounter.tool.d.ts +2 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/encounter.tool.js +134 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.js +31 -13
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.d.ts +2 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.js +25 -8
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.js +70 -4
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.js +27 -0
- package/dist-sdk/server/src/tools/packs/index.d.ts +1 -2
- package/dist-sdk/server/src/tools/packs/index.js +5 -11
- package/dist-sdk/shared/types/app.types.d.ts +72 -13
- package/docs/assets/hierarchy.js +1 -1
- package/docs/assets/highlight.css +8 -1
- package/docs/assets/icons.js +1 -1
- package/docs/assets/icons.svg +1 -1
- package/docs/assets/main.js +4 -4
- package/docs/assets/navigation.js +1 -1
- package/docs/assets/search.js +1 -1
- package/docs/assets/style.css +18 -3
- package/docs/classes/Agent.html +702 -37
- package/docs/classes/Briyah.html +250 -33
- package/docs/classes/BriyahConfigService.html +117 -10
- package/docs/classes/NativeToolRegistry.html +156 -11
- package/docs/classes/PackInstantiationService.html +146 -0
- package/docs/classes/PackService.html +247 -0
- package/docs/classes/Room.html +1190 -77
- package/docs/classes/RoomMessage.html +260 -29
- package/docs/enums/MessageAction.html +123 -3
- package/docs/functions/availableToolPacks.html +41 -2
- package/docs/functions/dnd5eTools.html +42 -3
- package/docs/functions/installToolPacks.html +48 -0
- package/docs/functions/registerToolPacks.html +54 -6
- package/docs/hierarchy.html +42 -1
- package/docs/index.html +158 -25
- package/docs/interfaces/AgentCreationOptions.html +110 -11
- package/docs/interfaces/AgentInfo.html +188 -3
- package/docs/interfaces/AgentMessagesResponse.html +71 -2
- package/docs/interfaces/AppService.html +2775 -474
- package/docs/interfaces/Artifact.html +81 -4
- package/docs/interfaces/ArtifactMetadata.html +104 -3
- package/docs/interfaces/ArtifactWriteOptions.html +75 -6
- package/docs/interfaces/AttachDocumentResponse.html +61 -2
- package/docs/interfaces/BriyahConfigOptions.html +107 -10
- package/docs/interfaces/ChapterInfo.html +61 -2
- package/docs/interfaces/Character.html +81 -2
- package/docs/interfaces/CreateAgentResponse.html +56 -2
- package/docs/interfaces/CreateRoomResponse.html +61 -2
- package/docs/interfaces/CreateStoryResponse.html +56 -2
- package/docs/interfaces/FileList.html +56 -2
- package/docs/interfaces/FileMetadata.html +84 -3
- package/docs/interfaces/IConfigService.html +76 -3
- package/docs/interfaces/InstantiateModels.html +64 -0
- package/docs/interfaces/InstantiateRoomResult.html +70 -0
- package/docs/interfaces/LoadedPack.html +131 -0
- package/docs/interfaces/LoggingOptions.html +86 -7
- package/docs/interfaces/Message.html +80 -2
- package/docs/interfaces/ModelChoice.html +73 -0
- package/docs/interfaces/ModelInfo.html +71 -2
- package/docs/interfaces/NativeToolDefinition.html +96 -9
- package/docs/interfaces/PackAgentTemplate.html +101 -0
- package/docs/interfaces/PackRoomTemplate.html +108 -0
- package/docs/interfaces/PackView.html +172 -0
- package/docs/interfaces/PreparedPromptResponse.html +61 -2
- package/docs/interfaces/ProcessTextResponse.html +81 -2
- package/docs/interfaces/PromptFile.html +69 -2
- package/docs/interfaces/PromptFileContent.html +75 -2
- package/docs/interfaces/PromptFilesResponse.html +56 -2
- package/docs/interfaces/PromptFolder.html +79 -2
- package/docs/interfaces/PromptFolderDefaults.html +136 -5
- package/docs/interfaces/PromptFolderDefaultsResponse.html +65 -4
- package/docs/interfaces/PromptFoldersResponse.html +56 -2
- package/docs/interfaces/RoomDetails.html +133 -4
- package/docs/interfaces/RoomInfo.html +84 -2
- package/docs/interfaces/RoomMessageUpdate.html +91 -2
- package/docs/interfaces/RoomMessagesResponse.html +61 -2
- package/docs/interfaces/SendMessageResult.html +61 -2
- package/docs/interfaces/StoryErrorEvent.html +76 -4
- package/docs/interfaces/StoryIdea.html +71 -2
- package/docs/interfaces/StoryInfo.html +173 -3
- package/docs/interfaces/StoryIntroduceCharacterEvent.html +71 -4
- package/docs/interfaces/StoryProgressChapterEvent.html +64 -3
- package/docs/interfaces/StoryState.html +99 -6
- package/docs/interfaces/StoryStateEvent.html +69 -3
- package/docs/interfaces/ToolArtifact.html +81 -4
- package/docs/interfaces/ToolCaller.html +75 -6
- package/docs/interfaces/ToolDefinition.html +76 -2
- package/docs/interfaces/ToolHelpers.html +91 -6
- package/docs/interfaces/ToolParameter.html +71 -2
- package/docs/interfaces/ToolRoomAccess.html +200 -24
- package/docs/interfaces/ToolSummary.html +71 -2
- package/docs/interfaces/ToolsResponse.html +66 -2
- package/docs/interfaces/Transaction.html +96 -2
- package/docs/interfaces/TransactionHistoryResponse.html +61 -2
- package/docs/modules.html +53 -1
- package/docs/types/PackOrigin.html +34 -0
- package/docs/types/PromptScope.html +34 -1
- package/docs/types/RoomTurnMode.html +36 -2
- package/docs/types/ToolContext.html +36 -2
- package/docs/types/ToolRunResult.html +34 -1
- package/package.json +139 -139
- package/src/tools/packs/dnd5e/README.md +149 -26
- package/dist-sdk/server/src/library/library.service.d.ts +0 -14
- package/dist-sdk/server/src/library/library.service.js +0 -165
- package/docs/functions/enabledToolPacks.html +0 -2
- /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/campaign_designer-setting.md +0 -0
- /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/character_creator-basics.md +0 -0
- /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-barbarian.md +0 -0
- /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-bard.md +0 -0
- /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-cleric.md +0 -0
- /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-druid.md +0 -0
- /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-fighter.md +0 -0
- /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-monk.md +0 -0
- /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-paladin.md +0 -0
- /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-ranger.md +0 -0
- /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-rogue.md +0 -0
- /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-sorcerer.md +0 -0
- /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-warlock.md +0 -0
- /package/data/{common/artifacts/dnd5e → packs/dnd5e/artifacts}/class-wizard.md +0 -0
- /package/data/{common/prompts/campaign_designer → packs/dnd5e/prompts/battle_master}/system_instruction.prompt +0 -0
- /package/data/{common → packs/dnd5e}/prompts/campaign_designer/defaults_config.json +0 -0
- /package/data/{common → packs/dnd5e}/prompts/campaign_designer/perceive.json +0 -0
- /package/data/{common → packs/dnd5e}/prompts/campaign_designer/perceive.prompt +0 -0
- /package/data/{common/prompts/character_creator → packs/dnd5e/prompts/campaign_designer}/system_instruction.prompt +0 -0
- /package/data/{common → packs/dnd5e}/prompts/character_creator/perceive.json +0 -0
- /package/data/{common/prompts/dnd_player → packs/dnd5e/prompts/character_creator}/system_instruction.prompt +0 -0
- /package/data/{common → packs/dnd5e}/prompts/dnd_player/defaults_config.json +0 -0
- /package/data/{common → packs/dnd5e}/prompts/dnd_player/perceive.json +0 -0
- /package/data/{common/prompts/dnd_room_moderator → packs/dnd5e/prompts/dnd_player}/system_instruction.prompt +0 -0
- /package/data/{common → packs/dnd5e}/prompts/dnd_room_moderator/defaults_config.json +0 -0
- /package/data/{common/prompts/dungeon_master → packs/dnd5e/prompts/dnd_room_moderator}/system_instruction.prompt +0 -0
- /package/data/{common → packs/dnd5e}/prompts/dungeon_master/compact_agent.prompt +0 -0
- /package/data/{common → packs/dnd5e}/prompts/dungeon_master/perceive.json +0 -0
package/README.md
CHANGED
|
@@ -1,994 +1,1092 @@
|
|
|
1
|
-
# Briyah SDK
|
|
2
|
-
|
|
3
|
-
Briyah is an SDK for AI agents, multi-agent rooms, and interactive stories. It wraps the Briyah runtime as a single class with per-user data isolation and balance tracking, and supports Anthropic, OpenAI, Google, Grok, DeepSeek, Together, and Fal as LLM providers.
|
|
4
|
-
|
|
5
|
-
What's in the package:
|
|
6
|
-
|
|
7
|
-
- **Agents.** AI agents with a system prompt, persistent conversation history, attached documents, and per-call cost and token tracking. Histories can be summarized/compacted or cleared.
|
|
8
|
-
- **Rooms.** Multi-agent conversations with a shared goal. Agents exchange messages at different visibility levels (speak, whisper, think, shout), publish shared artifacts, run tools, commission each other for parallel research, and a moderator can route turns.
|
|
9
|
-
- **Tools.** Functions agents can call from a room, granted per agent. Two kinds:
|
|
10
|
-
- **Native tools** — real functions you register in your host code with `briyah.registerTool` (see [Example 8](#example-8-registering-native-tools-with-opaque-context)). They have full access to your imports, database, and filesystem, and receive an **opaque per-invocation context** you supply — use it to scope a call to trusted data the model cannot set. This is the recommended way for SDK integrations.
|
|
11
|
-
- **User-authored tools** — named JS-string bodies stored per user and run in-process with a timeout (`helpers.fetch` available). Off by default; enable with `allowUserAuthoredTools` only when you trust the authors. On multi-user hosts, leave off and expose native tools instead.
|
|
12
|
-
An agent may chain several tool calls privately before responding.
|
|
13
|
-
- **Stories.** Text-based interactive fiction with a narrator, AI-played characters, and a human player. Stories progress through chapters and can introduce new characters mid-game. Story events (state updates, character suggestions, chapter transitions, errors) are delivered through an emitter the host app subscribes to.
|
|
14
|
-
- **Text processing.** One-shot `processText` for non-conversational use, with cost and token counts on the result.
|
|
15
|
-
- **File attachments.** Attach documents to agents as context. Supported file types vary by LLM provider.
|
|
16
|
-
- **Per-user data.** Agents, rooms, stories, attached files, balances, and transactions are scoped to a userId the host controls. Per-user directories keep state isolated.
|
|
17
|
-
- **Balances and transactions.** Track per-user balances against usage cost. Record pending, succeeded, failed, or cancelled transactions when integrating with a payment provider, credit balances on webhook confirmation, and resume stories that paused on insufficient funds. Briyah does not process payments itself.
|
|
18
|
-
- **Real-time event emitters.** Story-state and balance updates can be forwarded to SSE or websockets.
|
|
19
|
-
|
|
20
|
-
State is persisted as JSON files under a configurable data path; no external database is required.
|
|
21
|
-
|
|
22
|
-
## Installation
|
|
23
|
-
|
|
24
|
-
```bash
|
|
25
|
-
npm install briyah
|
|
26
|
-
```
|
|
27
|
-
|
|
28
|
-
```typescript
|
|
29
|
-
import { Briyah } from 'briyah';
|
|
30
|
-
```
|
|
31
|
-
|
|
32
|
-
## Quick Start
|
|
33
|
-
|
|
34
|
-
```typescript
|
|
35
|
-
import { Briyah } from 'briyah';
|
|
36
|
-
|
|
37
|
-
// 1. Create and initialize Briyah instance
|
|
38
|
-
const briyah = new Briyah({
|
|
39
|
-
dataPath: './my-briyah-data',
|
|
40
|
-
userServiceCacheTimeoutMinutes: 30,
|
|
41
|
-
startingBalance: 10.00
|
|
42
|
-
});
|
|
43
|
-
|
|
44
|
-
await briyah.init();
|
|
45
|
-
|
|
46
|
-
// 2. Get user-specific service (userId managed by your app)
|
|
47
|
-
const appService = briyah.getAppService('user-123');
|
|
48
|
-
|
|
49
|
-
// 3. Use full Briyah functionality
|
|
50
|
-
// createAgent() registers the agent in memory immediately — agent.id is usable right away.
|
|
51
|
-
// Call agent.save() when you want to persist it to disk.
|
|
52
|
-
const agent = appService.createAgent(
|
|
53
|
-
'Anthropic',
|
|
54
|
-
'AI Assistant',
|
|
55
|
-
'James',
|
|
56
|
-
'A helpful AI assistant',
|
|
57
|
-
'claude-haiku-4-5'
|
|
58
|
-
);
|
|
59
|
-
|
|
60
|
-
if (!agent.id) throw new Error('Agent creation failed');
|
|
61
|
-
const result = await appService.processText(agent.id, 'Hello! How are you?');
|
|
62
|
-
console.log(result.result);
|
|
63
|
-
|
|
64
|
-
agent.save(); // persist to disk
|
|
65
|
-
|
|
66
|
-
// 4. Cleanup when done
|
|
67
|
-
await briyah.shutdown();
|
|
68
|
-
```
|
|
69
|
-
|
|
70
|
-
## Configuration
|
|
71
|
-
|
|
72
|
-
### BriyahConfigOptions
|
|
73
|
-
|
|
74
|
-
```typescript
|
|
75
|
-
interface BriyahConfigOptions {
|
|
76
|
-
/**
|
|
77
|
-
* Base directory for Briyah data storage
|
|
78
|
-
* Default: './briyah-data' relative to process.cwd()
|
|
79
|
-
*/
|
|
80
|
-
dataPath?: string;
|
|
81
|
-
|
|
82
|
-
/**
|
|
83
|
-
* Timeout in minutes for cached user services
|
|
84
|
-
* Default: 30 minutes
|
|
85
|
-
*/
|
|
86
|
-
userServiceCacheTimeoutMinutes?: number;
|
|
87
|
-
|
|
88
|
-
/**
|
|
89
|
-
* Starting balance for new users (in dollars)
|
|
90
|
-
* Default: value from process.env.STARTING_BALANCE
|
|
91
|
-
*/
|
|
92
|
-
startingBalance?: number;
|
|
93
|
-
|
|
94
|
-
/**
|
|
95
|
-
* Native tools to register up front (equivalent to calling registerTool
|
|
96
|
-
* for each). See Example 8.
|
|
97
|
-
*/
|
|
98
|
-
tools?: NativeToolDefinition[];
|
|
99
|
-
|
|
100
|
-
/**
|
|
101
|
-
* Allow end users to author and run their own JS-string tools. Native tools
|
|
102
|
-
* are unaffected. Leave off for untrusted multi-user hosts. Default: false.
|
|
103
|
-
*/
|
|
104
|
-
allowUserAuthoredTools?: boolean;
|
|
105
|
-
|
|
106
|
-
/**
|
|
107
|
-
* Override environment variables
|
|
108
|
-
* Useful for testing or multi-instance configurations
|
|
109
|
-
*/
|
|
110
|
-
envOverrides?: Record<string, string>;
|
|
111
|
-
}
|
|
112
|
-
```
|
|
113
|
-
|
|
114
|
-
### Environment Variables
|
|
115
|
-
|
|
116
|
-
**LLM Provider API Keys** (at least one required):
|
|
117
|
-
- `ANTHROPIC_API_KEY` - For Claude models
|
|
118
|
-
- `OPENAI_API_KEY` - For GPT models
|
|
119
|
-
- `GOOGLE_GENAI_API_KEY` - For Google AI (Gemini) models
|
|
120
|
-
- `XAI_API_KEY` - For Grok models
|
|
121
|
-
- `DEEPSEEK_API_KEY` - For DeepSeek models
|
|
122
|
-
- `TOGETHER_API_KEY` - For Together AI models
|
|
123
|
-
- `FAL_API_KEY` - For Fal image-generation models
|
|
124
|
-
|
|
125
|
-
**Self-hosted providers** (optional, count toward the "at least one" requirement):
|
|
126
|
-
- `SELF_HOSTED_BASE_URL` - OpenAI-compatible inference server for the `SelfHosted` text provider (vLLM, Ollama, llama.cpp, LM Studio). Must include the `/v1` path, e.g. `http://gpu-box:8000/v1`
|
|
127
|
-
- `SELF_HOSTED_API_KEY` - Optional bearer token for the above
|
|
128
|
-
- `COMFYUI_BASE_URL` - ComfyUI server for the `ComfyUI` image provider, no trailing slash, e.g. `http://gpu-box:8188` (see Example 9)
|
|
129
|
-
- `COMFYUI_EXTRA_HEADERS` - Optional JSON object of headers sent on every ComfyUI request, e.g. `{"Authorization":"Basic ..."}` for a reverse proxy
|
|
130
|
-
- `COMFYUI_TIMEOUT_MS` - Total wait for a queued generation, default `600000` (covers queue wait and model cold start)
|
|
131
|
-
- `COMFYUI_POLL_INTERVAL_MS` - Poll interval while waiting, default `2000`
|
|
132
|
-
|
|
133
|
-
**Optional:**
|
|
134
|
-
- `STARTING_BALANCE` - Starting balance for new users (e.g., "10.00")
|
|
135
|
-
- `BRIYAH_DATA_PATH` - Global default data path (overridden by constructor `dataPath`)
|
|
136
|
-
- `USER_SERVICE_CACHE_TIMEOUT_MINUTES` - Cache timeout (overridden by constructor option)
|
|
137
|
-
- `ALLOW_USER_AUTHORED_TOOLS` - `"true"` to let users author/run their own tools (overridden by the `allowUserAuthoredTools` option). Default off.
|
|
138
|
-
|
|
139
|
-
### Logging
|
|
140
|
-
|
|
141
|
-
Briyah writes logs to `{dataPath}/logs/briyah.log` by default. Configure or disable via the `logging` option:
|
|
142
|
-
|
|
143
|
-
```typescript
|
|
144
|
-
const briyah = new Briyah({
|
|
145
|
-
dataPath: './my-data',
|
|
146
|
-
logging: {
|
|
147
|
-
enabled: true, // default
|
|
148
|
-
logFile: './my-data/logs/app.log', // default: {dataPath}/logs/briyah.log
|
|
149
|
-
console: false, // set true to also log to stdout/stderr
|
|
150
|
-
level: 'warn', // 'debug' | 'log' | 'warn' | 'error' — default: 'log'
|
|
151
|
-
}
|
|
152
|
-
});
|
|
153
|
-
|
|
154
|
-
// Log to console only (no file):
|
|
155
|
-
const briyah = new Briyah({ logging: { console: true, logFile: null } });
|
|
156
|
-
|
|
157
|
-
// Disable logging entirely:
|
|
158
|
-
const briyah = new Briyah({ logging: { enabled: false } });
|
|
159
|
-
```
|
|
160
|
-
|
|
161
|
-
## API Reference
|
|
162
|
-
|
|
163
|
-
### Briyah Class
|
|
164
|
-
|
|
165
|
-
#### constructor(options?: BriyahConfigOptions)
|
|
166
|
-
|
|
167
|
-
Creates a new Briyah SDK instance.
|
|
168
|
-
|
|
169
|
-
```typescript
|
|
170
|
-
const briyah = new Briyah({
|
|
171
|
-
dataPath: './briyah-data',
|
|
172
|
-
startingBalance: 10.00
|
|
173
|
-
});
|
|
174
|
-
```
|
|
175
|
-
|
|
176
|
-
#### async init(): Promise\<void\>
|
|
177
|
-
|
|
178
|
-
Initializes the Briyah system. Must be called before using `getAppService()`.
|
|
179
|
-
|
|
180
|
-
```typescript
|
|
181
|
-
await briyah.init();
|
|
182
|
-
```
|
|
183
|
-
|
|
184
|
-
#### getAppService(userId: string): AppService
|
|
185
|
-
|
|
186
|
-
Gets the AppService instance for a specific user. The AppService provides full access to:
|
|
187
|
-
- Agent management
|
|
188
|
-
- Room conversations
|
|
189
|
-
- Story generation
|
|
190
|
-
- Text processing
|
|
191
|
-
- File attachments
|
|
192
|
-
|
|
193
|
-
```typescript
|
|
194
|
-
const appService = briyah.getAppService('user-123');
|
|
195
|
-
```
|
|
196
|
-
|
|
197
|
-
**Throws:** Error if `init()` has not been called.
|
|
198
|
-
|
|
199
|
-
#### removeUserService(userId: string): void
|
|
200
|
-
|
|
201
|
-
Manually removes a user's service from the cache. Useful for:
|
|
202
|
-
- Forcing a fresh AppService instance
|
|
203
|
-
- Cleaning up when a user logs out
|
|
204
|
-
|
|
205
|
-
```typescript
|
|
206
|
-
briyah.removeUserService('user-123');
|
|
207
|
-
```
|
|
208
|
-
|
|
209
|
-
#### getCacheStats()
|
|
210
|
-
|
|
211
|
-
Returns statistics about cached user services.
|
|
212
|
-
|
|
213
|
-
```typescript
|
|
214
|
-
const stats = briyah.getCacheStats();
|
|
215
|
-
console.log(`Cached users: ${stats.cachedUsers}`);
|
|
216
|
-
```
|
|
217
|
-
|
|
218
|
-
#### async shutdown(): Promise\<void\>
|
|
219
|
-
|
|
220
|
-
Shuts down the Briyah system and cleans up resources.
|
|
221
|
-
|
|
222
|
-
```typescript
|
|
223
|
-
await briyah.shutdown();
|
|
224
|
-
```
|
|
225
|
-
|
|
226
|
-
#### isInitialized(): boolean
|
|
227
|
-
|
|
228
|
-
Checks if Briyah has been initialized.
|
|
229
|
-
|
|
230
|
-
```typescript
|
|
231
|
-
if (briyah.isInitialized()) {
|
|
232
|
-
const appService = briyah.getAppService('user-123');
|
|
233
|
-
}
|
|
234
|
-
```
|
|
235
|
-
|
|
236
|
-
### AppService
|
|
237
|
-
|
|
238
|
-
The AppService provides full access to Briyah functionality.
|
|
239
|
-
|
|
240
|
-
**Common operations:**
|
|
241
|
-
|
|
242
|
-
```typescript
|
|
243
|
-
// Agent Management
|
|
244
|
-
const agent = appService.createAgent(provider, name, nickname, description, model);
|
|
245
|
-
const agents = await appService.listAgents();
|
|
246
|
-
await appService.deleteAgent(agentId);
|
|
247
|
-
await appService.reloadAgent(agentId); // Clear conversation history (keeps any prior summary)
|
|
248
|
-
await appService.compactAgentConversation(agentId); // Summarize history into a single message
|
|
249
|
-
|
|
250
|
-
// Room Management
|
|
251
|
-
// roomLeader answers anything the room cannot place; turnMode 'directed' asks only the
|
|
252
|
-
// agent a message names ('broadcast', the default, asks every agent every time);
|
|
253
|
-
// moderator is only needed when no agent leads the turn order.
|
|
254
|
-
const room = await appService.createRoom(
|
|
255
|
-
name, goal, agentIds, roomLeader?, turnMode?, moderator?,
|
|
256
|
-
);
|
|
257
|
-
const rooms = await appService.listRooms();
|
|
258
|
-
const details = await appService.getRoomDetails(roomId);
|
|
259
|
-
// action defaults to 'moderate'. Returns {accepted, reason} — a message sent out of
|
|
260
|
-
// turn is refused, not thrown. `sender` must be an agentNickname.
|
|
261
|
-
await appService.sendRoomMessage(roomId, content, sender, action?, targets?);
|
|
262
|
-
// Required before subscribing to a room this process did not create.
|
|
263
|
-
await appService.ensureRoomStateCallback(roomId);
|
|
264
|
-
const emitter = appService.getRoomMessageEmitter(roomId); // 'update' events
|
|
265
|
-
|
|
266
|
-
// Prompt folder defaults — the role's name, tools and documents, as the create-agent
|
|
267
|
-
// dialog would fill them in. Read these rather than hard-coding a pack's tool names.
|
|
268
|
-
const { defaults } = appService.getPromptFolderDefaults('dungeon_master');
|
|
269
|
-
|
|
270
|
-
// Or let the folder build the agent: applies those defaults, saves, and attaches the
|
|
271
|
-
// folder's documents. Async (attaching is), unlike createAgent. `overrides` takes the
|
|
272
|
-
// same shape as the defaults; pass `attachDocuments: false` to decline the documents.
|
|
273
|
-
const agent = await appService.createAgentFromFolder({
|
|
274
|
-
folder: 'dungeon_master', aiServiceName: 'Anthropic', aiModel: 'claude-sonnet-5',
|
|
275
|
-
});
|
|
276
|
-
|
|
277
|
-
// Agents that belong to a room: created inside it, named after it, deleted with it,
|
|
278
|
-
// and left out of listAgents(). agentName is the bare name; the room's is prefixed on.
|
|
279
|
-
await appService.createRoomAgent(roomId, { aiServiceName, agentName, description, aiModel, promptName });
|
|
280
|
-
await appService.removeRoomAgent(roomId, agentId);
|
|
281
|
-
|
|
282
|
-
// Native tools (recommended for SDK integrations — see Example 8)
|
|
283
|
-
briyah.registerTool({ name, description, parameters, handler }); // process-level
|
|
284
|
-
briyah.listNativeTools();
|
|
285
|
-
|
|
286
|
-
// User-authored (string-code) tools — only when allowUserAuthoredTools is enabled
|
|
287
|
-
const tools = await appService.listTools();
|
|
288
|
-
const tool = await appService.createTool({ name, description, parameters, code, timeoutMs? });
|
|
289
|
-
await appService.updateTool(name, tool);
|
|
290
|
-
await appService.deleteTool(name);
|
|
291
|
-
const result = await appService.testTool(name, args); // { ok: true, result } | { ok: false, error }
|
|
292
|
-
|
|
293
|
-
// Story Management
|
|
294
|
-
// illustrateStory is required and positional — it is the fifth argument, not an option.
|
|
295
|
-
const story = await appService.createStory(
|
|
296
|
-
name, idea, userCharacterDesc, otherCharactersDesc, illustrateStory,
|
|
297
|
-
storyModel?, isImport?, imageModelName?, skipDetailedPlot?,
|
|
298
|
-
);
|
|
299
|
-
await appService.progressStory(storyId);
|
|
300
|
-
|
|
301
|
-
// Text Processing
|
|
302
|
-
const result = await appService.processText(agentId, text);
|
|
303
|
-
|
|
304
|
-
// Image Generation (image-capable providers; called on the Agent object — see Example 9)
|
|
305
|
-
const { artifactId } = await agent.generateImage(prompt, imageProperties);
|
|
306
|
-
const edited = await agent.editImage(prompt, imageProperties, referenceArtifactIds);
|
|
307
|
-
|
|
308
|
-
// File Attachments
|
|
309
|
-
const attachment = await appService.attachDocument(agentId, fileName, fileData);
|
|
310
|
-
await appService.deleteAttachedFile(agentId, fileName); // by filename
|
|
311
|
-
await appService.deleteAttachedFileById(documentId); // by document ID
|
|
312
|
-
```
|
|
313
|
-
|
|
314
|
-
## Prompt Folders
|
|
315
|
-
|
|
316
|
-
An agent's behaviour comes from a **prompt folder**, not from its description. The folder
|
|
317
|
-
holds the templates the room renders on every turn — most importantly `perceive.prompt`, which
|
|
318
|
-
tells the agent what it is and what it may do, and `perceive.json`, the JSON schema its replies
|
|
319
|
-
must satisfy. Two agents on the same model with the same description behave completely
|
|
320
|
-
differently if they were built from different folders.
|
|
321
|
-
|
|
322
|
-
`init()` seeds the
|
|
323
|
-
your first `createAgent` call. Existing files are preserved on upgrade, so anything you edit
|
|
324
|
-
survives.
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
`
|
|
359
|
-
a
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
```
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
const
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
const
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
);
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
const
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
//
|
|
562
|
-
//
|
|
563
|
-
//
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
const
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
}
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
);
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
await
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
const
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
```
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
{
|
|
770
|
-
);
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
);
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
await
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
const
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
const
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
'
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
);
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
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.
|