briyah 2.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/README.md +245 -65
  2. package/dist-sdk/server/src/app.controller.js +1 -1
  3. package/dist-sdk/server/src/app.service.d.ts +2 -0
  4. package/dist-sdk/server/src/app.service.js +25 -4
  5. package/dist-sdk/server/src/config/prompt-resolver.d.ts +2 -0
  6. package/dist-sdk/server/src/config/prompt-resolver.js +14 -7
  7. package/dist-sdk/server/src/packs/pack-instantiation.service.d.ts +2 -1
  8. package/dist-sdk/server/src/packs/pack-instantiation.service.js +16 -5
  9. package/dist-sdk/server/src/room/room-message.service.d.ts +2 -1
  10. package/dist-sdk/server/src/room/room-message.service.js +3 -2
  11. package/dist-sdk/server/src/room/room.js +4 -2
  12. package/dist-sdk/server/src/sdk/index.d.ts +2 -2
  13. package/dist-sdk/shared/types/app.types.d.ts +9 -0
  14. package/docs/assets/hierarchy.js +1 -1
  15. package/docs/assets/highlight.css +7 -0
  16. package/docs/assets/navigation.js +1 -1
  17. package/docs/assets/search.js +1 -1
  18. package/docs/classes/Agent.html +73 -73
  19. package/docs/classes/Briyah.html +16 -16
  20. package/docs/classes/BriyahConfigService.html +7 -7
  21. package/docs/classes/NativeToolRegistry.html +10 -10
  22. package/docs/classes/PackInstantiationService.html +20 -9
  23. package/docs/classes/PackService.html +13 -13
  24. package/docs/classes/Room.html +90 -90
  25. package/docs/classes/RoomMessage.html +22 -22
  26. package/docs/enums/MessageAction.html +18 -18
  27. package/docs/functions/availableToolPacks.html +4 -4
  28. package/docs/functions/dnd5eTools.html +4 -4
  29. package/docs/functions/installToolPacks.html +4 -4
  30. package/docs/functions/registerToolPacks.html +4 -4
  31. package/docs/hierarchy.html +9 -9
  32. package/docs/index.html +155 -41
  33. package/docs/interfaces/AgentCreationOptions.html +12 -12
  34. package/docs/interfaces/AgentInfo.html +30 -30
  35. package/docs/interfaces/AgentMessagesResponse.html +8 -8
  36. package/docs/interfaces/AppService.html +216 -185
  37. package/docs/interfaces/Artifact.html +9 -9
  38. package/docs/interfaces/ArtifactMetadata.html +13 -13
  39. package/docs/interfaces/ArtifactWriteOptions.html +7 -7
  40. package/docs/interfaces/AttachDocumentResponse.html +6 -6
  41. package/docs/interfaces/BriyahConfigOptions.html +12 -12
  42. package/docs/interfaces/ChapterInfo.html +6 -6
  43. package/docs/interfaces/Character.html +10 -10
  44. package/docs/interfaces/CreateAgentResponse.html +5 -5
  45. package/docs/interfaces/CreateRoomResponse.html +6 -6
  46. package/docs/interfaces/CreateStoryResponse.html +5 -5
  47. package/docs/interfaces/FileList.html +5 -5
  48. package/docs/interfaces/FileMetadata.html +10 -10
  49. package/docs/interfaces/IConfigService.html +5 -5
  50. package/docs/interfaces/InstantiateModels.html +6 -6
  51. package/docs/interfaces/InstantiateRoomResult.html +7 -7
  52. package/docs/interfaces/LoadedPack.html +16 -16
  53. package/docs/interfaces/LoggingOptions.html +9 -9
  54. package/docs/interfaces/Message.html +9 -9
  55. package/docs/interfaces/ModelChoice.html +7 -7
  56. package/docs/interfaces/ModelInfo.html +8 -8
  57. package/docs/interfaces/NativeToolDefinition.html +10 -10
  58. package/docs/interfaces/PackAgentTemplate.html +9 -9
  59. package/docs/interfaces/PackRoomTemplate.html +11 -11
  60. package/docs/interfaces/PackView.html +20 -20
  61. package/docs/interfaces/PreparedPromptResponse.html +6 -6
  62. package/docs/interfaces/ProcessTextResponse.html +10 -10
  63. package/docs/interfaces/PromptFile.html +7 -7
  64. package/docs/interfaces/PromptFileContent.html +8 -8
  65. package/docs/interfaces/PromptFilesResponse.html +5 -5
  66. package/docs/interfaces/PromptFolder.html +8 -8
  67. package/docs/interfaces/PromptFolderDefaults.html +19 -19
  68. package/docs/interfaces/PromptFolderDefaultsResponse.html +21 -8
  69. package/docs/interfaces/PromptFoldersResponse.html +5 -5
  70. package/docs/interfaces/RoomDetails.html +19 -19
  71. package/docs/interfaces/RoomErrorUpdate.html +82 -0
  72. package/docs/interfaces/RoomInfo.html +10 -10
  73. package/docs/interfaces/RoomMessageUpdate.html +30 -15
  74. package/docs/interfaces/RoomMessagesResponse.html +6 -6
  75. package/docs/interfaces/SendMessageResult.html +6 -6
  76. package/docs/interfaces/StoryErrorEvent.html +8 -8
  77. package/docs/interfaces/StoryIdea.html +8 -8
  78. package/docs/interfaces/StoryInfo.html +28 -28
  79. package/docs/interfaces/StoryIntroduceCharacterEvent.html +7 -7
  80. package/docs/interfaces/StoryProgressChapterEvent.html +6 -6
  81. package/docs/interfaces/StoryState.html +12 -12
  82. package/docs/interfaces/StoryStateEvent.html +7 -7
  83. package/docs/interfaces/ToolArtifact.html +9 -9
  84. package/docs/interfaces/ToolCaller.html +7 -7
  85. package/docs/interfaces/ToolDefinition.html +9 -9
  86. package/docs/interfaces/ToolHelpers.html +6 -6
  87. package/docs/interfaces/ToolParameter.html +8 -8
  88. package/docs/interfaces/ToolRoomAccess.html +14 -14
  89. package/docs/interfaces/ToolSummary.html +8 -8
  90. package/docs/interfaces/ToolsResponse.html +7 -7
  91. package/docs/interfaces/Transaction.html +13 -13
  92. package/docs/interfaces/TransactionHistoryResponse.html +6 -6
  93. package/docs/modules.html +8 -8
  94. package/docs/types/PackOrigin.html +4 -4
  95. package/docs/types/PromptScope.html +4 -4
  96. package/docs/types/RoomTurnMode.html +4 -4
  97. package/docs/types/RoomUpdate.html +36 -0
  98. package/docs/types/RosterOverrides.html +42 -0
  99. package/docs/types/ToolContext.html +4 -4
  100. package/docs/types/ToolRunResult.html +4 -4
  101. package/package.json +1 -1
  102. package/src/tools/packs/dnd5e/README.md +39 -3
package/README.md CHANGED
@@ -67,6 +67,45 @@ agent.save(); // persist to disk
67
67
  await briyah.shutdown();
68
68
  ```
69
69
 
70
+ ## Upgrading to 2.0
71
+
72
+ 2.0 moves the D&D content into a **pack**. Three things change for a host coming from 1.5; the
73
+ first two are a line each, and the third is something to know about your data directory.
74
+
75
+ **The D&D prompt folders are now the pack's.** `dungeon_master`, `dnd_player`,
76
+ `character_creator`, `campaign_designer` and `dnd_room_moderator` belong to `dnd5e`. Enable the
77
+ pack for the user, and qualify the folder name:
78
+
79
+ ```typescript
80
+ app.packs.setEnabled('dnd5e', true); // per user, and required
81
+ await app.createAgentFromFolder({ folder: 'dnd5e:dungeon_master', /* ... */ });
82
+ ```
83
+
84
+ A bare `dungeon_master` also reaches the pack once it is enabled, so enabling alone is enough if
85
+ you would rather not touch the strings. Doing neither is what breaks: in 1.5 those folders sat in
86
+ `common/prompts` and the bare name resolved, and in 2.0 it falls through to the shared root
87
+ prompts instead. `createAgentFromFolder` now refuses that rather than building a generic agent
88
+ from it — see [Prompt Folders](#prompt-folders).
89
+
90
+ **`enabledToolPacks` is gone**, replaced by `installToolPacks`. Most hosts can delete the call
91
+ entirely: the `Briyah` constructor installs every bundled pack's tools already. `BRIYAH_TOOL_PACKS`
92
+ no longer does anything either, and is not read.
93
+
94
+ **`init()` rewrites two things under your data path.** Both are stated here because neither is
95
+ visible until it has happened:
96
+
97
+ - `{dataPath}/packs/<bundled pack>/` is **deleted and re-copied on every init**. A pack's
98
+ directory is package-canonical, so a host that hand-edits `packs/dnd5e/` loses those edits on
99
+ the next boot. Edit it as a user instead — the change lands in
100
+ `{dataPath}/user/<userId>/packs/dnd5e/`, an overlay that takes precedence — or install your own
101
+ pack under a name Briyah does not bundle, which is never touched.
102
+ - Any `common/prompts/<folder>` whose name a pack now owns is **moved** to
103
+ `{dataPath}/retired-prompts/<folder>`, and the move is logged as a warning. On a 1.5 data
104
+ directory that is the five D&D folders. Moved rather than deleted because a leftover copy
105
+ outranks the pack for a bare name and would silently shadow it. Nothing reads
106
+ `retired-prompts/`: keep it if you had local edits worth porting into an overlay, delete it
107
+ otherwise.
108
+
70
109
  ## Configuration
71
110
 
72
111
  ### BriyahConfigOptions
@@ -136,6 +175,11 @@ interface BriyahConfigOptions {
136
175
  - `USER_SERVICE_CACHE_TIMEOUT_MINUTES` - Cache timeout (overridden by constructor option)
137
176
  - `ALLOW_USER_AUTHORED_TOOLS` - `"true"` to let users author/run their own tools (overridden by the `allowUserAuthoredTools` option). Default off.
138
177
 
178
+ **Retired:**
179
+ - `BRIYAH_TOOL_PACKS` - Read in 1.5 to choose which tool packs to register. It is not read in
180
+ 2.0 and setting it does nothing. Every bundled pack's tools are registered at construction;
181
+ what a user can reach is decided by pack enablement and per-agent tool grants. See [Packs](#packs).
182
+
139
183
  ### Logging
140
184
 
141
185
  Briyah writes logs to `{dataPath}/logs/briyah.log` by default. Configure or disable via the `logging` option:
@@ -265,7 +309,10 @@ const emitter = appService.getRoomMessageEmitter(roomId); // 'update' events
265
309
 
266
310
  // Prompt folder defaults — the role's name, tools and documents, as the create-agent
267
311
  // dialog would fill them in. Read these rather than hard-coding a pack's tool names.
268
- const { defaults } = appService.getPromptFolderDefaults('dnd5e:dungeon_master');
312
+ // `exists` is false for a folder nothing ships, which otherwise looks identical to a
313
+ // folder that declares no defaults.
314
+ const { defaults, exists } = appService.getPromptFolderDefaults('dnd5e:dungeon_master');
315
+ appService.promptFolderExists('dnd5e:dungeon_master'); // the same question, alone
269
316
 
270
317
  // Or let the folder build the agent: applies those defaults, saves, and attaches the
271
318
  // folder's documents. Async (attaching is), unlike createAgent. `overrides` takes the
@@ -338,8 +385,26 @@ console.log(appService.listPromptFolders());
338
385
  // dnd5e:campaign_designer, dnd5e:battle_master, dnd5e:dnd_room_moderator
339
386
  ```
340
387
 
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.
388
+ See [Packs](#packs) — **if you are building on `dnd5e` you have to enable it first**, or a bare
389
+ folder name will not reach it.
390
+
391
+ ### When a folder name is wrong
392
+
393
+ A prompt lookup always ends at the shared root prompts, so a folder that does not exist does not
394
+ fail — it produces a working, generic agent. Three things now say so instead:
395
+
396
+ ```typescript
397
+ appService.promptFolderExists('dnd5e:dungeon_master'); // false if the pack is not installed
398
+ const { defaults, exists } = appService.getPromptFolderDefaults('dungeon_master');
399
+ // exists distinguishes "no such folder" from "a folder that declares no defaults":
400
+ // both give you `defaults: {}`. A bare pack folder reports false until the pack is enabled.
401
+ ```
402
+
403
+ - `createAgentFromFolder` and `createRoomAgentFromFolder` **throw** a `NotFoundError` naming the
404
+ folder. The whole point of those calls is the folder's recipe — its tools, its documents, its
405
+ nickname — and a folder that is not there has none.
406
+ - `createAgent` **warns** and carries on, since it takes all of that from its arguments and the
407
+ folder is only one of them. The warning is in `{dataPath}/logs/briyah.log`.
343
408
 
344
409
  **The folder is the sixth argument to `createAgent`, and it defaults to `'default'`** — a
345
410
  generic conversational agent. Passing a role folder is what makes the agent that role:
@@ -395,9 +460,29 @@ and its tools grantable:
395
460
  const appService = briyah.getAppService('user-123');
396
461
 
397
462
  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: [] }]
463
+ // [{
464
+ // name: 'dnd5e', // <- the id; `title` is for display
465
+ // title: 'D&D 5th Edition',
466
+ // description: 'Run a fifth-edition tabletop game in a room: ...',
467
+ // version: '1.0.0',
468
+ // dir: '/srv/app/briyah-data/packs/dnd5e',
469
+ // origin: 'host', // 'host' installed it, or 'user' created it
470
+ // enabled: false,
471
+ // promptFolders: ['battle_master', 'campaign_designer', 'character_creator',
472
+ // 'dnd_player', 'dnd_room_moderator', 'dungeon_master'],
473
+ // agents: [{ key: 'dungeon_master', promptFolder: 'dungeon_master',
474
+ // label: 'Dungeon Master', modelRole: 'primary' }, ...],
475
+ // rooms: [{ key: 'table', name: 'D&D Table', goal: '...', turnMode: 'directed',
476
+ // agents: [{ key: 'table_moderator' }, ...],
477
+ // roomLeader: 'dungeon_master', moderator: 'table_moderator' }],
478
+ // documentCount: 16,
479
+ // requiresTools: ['apply_hp', 'check', 'roll_dice', ...], // derived from its grants
480
+ // requiresPacks: [],
481
+ // missingTools: [], // requiresTools this process has not registered
482
+ // missingPacks: [], // requiresPacks this user has not enabled
483
+ // }]
484
+ // The REST API returns a trimmed version of this (`pack` instead of `name`, and a
485
+ // `counts` object) — `listPacks()` in-process returns the `PackView` above.
401
486
 
402
487
  appService.packs.setEnabled('dnd5e', true);
403
488
  ```
@@ -433,12 +518,39 @@ const { roomId, agentIds, warnings } = await appService.packInstantiation.instan
433
518
  economy: { aiServiceName: 'Anthropic', aiModel: 'claude-haiku-4-5-20251001' },
434
519
  },
435
520
  'Tuesday Night Game', // optional; auto-suffixed if the name is taken
521
+ // optional; per-agent overrides, keyed by the template's own key for the seat
522
+ { player: { agentName: 'Homer', agentNickname: 'Homer' } },
436
523
  );
437
524
  ```
438
525
 
439
526
  That is a six-agent room with `turnMode: 'directed'`, the Dungeon Master as leader, a table
440
527
  moderator, and every agent already carrying its tool grants and rules documents.
441
528
 
529
+ **Naming the player.** The template's player seat ships as `PlayerOne`, which is not what the
530
+ person at the keyboard is called. The fifth argument changes any seat: the keys are the room
531
+ template's `agents[].key` (`table_moderator`, `dungeon_master`, `battle_master`,
532
+ `character_creator`, `campaign_designer`, `player` for `dnd5e:table`), and the value is the same
533
+ `PromptFolderDefaults` shape as a folder's own defaults, applied over them. A key no seat has is
534
+ refused before the room is created, rather than quietly doing nothing.
535
+
536
+ **More than one player.** The template seats one. Add the others afterwards with
537
+ `createRoomAgentFromFolder`, which is the same call instantiation makes per agent — a room-owned
538
+ agent, named after the room, deleted with it:
539
+
540
+ ```typescript
541
+ await appService.createRoomAgentFromFolder(roomId, {
542
+ folder: 'dnd5e:dnd_player',
543
+ aiServiceName: 'Anthropic',
544
+ aiModel: 'claude-haiku-4-5-20251001',
545
+ overrides: { agentName: 'Vex', agentNickname: 'Vex', description: 'A wary scout.' },
546
+ pack: 'dnd5e', // files it under the pack, so it hides and lists with one
547
+ packAgentKey: 'player', // records which template it came from
548
+ });
549
+ ```
550
+
551
+ Do it after `instantiateRoom` returns, not during: the room already has its moderator by then, so
552
+ a player carrying `useModerator: true` has one to route through.
553
+
442
554
  A template names a **role** rather than a model — `primary` or `economy` — because a model id goes
443
555
  stale and assumes your provider keys. The Dungeon Master takes the primary; the agents that do
444
556
  bookkeeping rather than prose take the economy one. Omit `economy` and everything uses the
@@ -847,15 +959,18 @@ it and then stops rather than generating a reply, which is what yields the floor
847
959
  every change with the newest message and the room's state.
848
960
 
849
961
  ```typescript
850
- import { Briyah, dnd5eTools } from 'briyah';
962
+ import { Briyah } from 'briyah';
963
+ import type { RoomUpdate } from 'briyah';
851
964
  import * as readline from 'node:readline/promises';
852
965
 
853
- const briyah = new Briyah({ dataPath: './briyah-data', tools: dnd5eTools() });
966
+ // The constructor installs every bundled pack's tools already; pass `tools` only to
967
+ // filter or wrap them, or to add your own.
968
+ const briyah = new Briyah({ dataPath: './briyah-data' });
854
969
  await briyah.init(); // seeds prompt folders and the packs
855
970
  const app = briyah.getAppService('user-123');
856
971
 
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.
972
+ // Enable the pack for this user, or a bare folder name will not reach it. Enabling is
973
+ // per user; installing is not.
859
974
  app.packs.setEnabled('dnd5e', true);
860
975
 
861
976
  const dm = app.createAgent(
@@ -898,7 +1013,7 @@ let atKeyboard = false; // the handler is async; without this it re-ent
898
1013
  let replyTo = 'DM'; // who last spoke to the player
899
1014
  let replyAs: 'speak' | 'whisper' = 'speak';
900
1015
 
901
- app.getRoomMessageEmitter(roomId).on('update', async (state) => {
1016
+ app.getRoomMessageEmitter(roomId).on('update', async (state: RoomUpdate) => {
902
1017
  if (state.type === 'error') { // a turn failed — see "Errors" below
903
1018
  console.error(`[${state.errorType}] ${state.message}`);
904
1019
  return;
@@ -937,14 +1052,27 @@ app.getRoomMessageEmitter(roomId).on('update', async (state) => {
937
1052
  await app.sendRoomMessage(roomId, 'Begin the adventure.', 'Homer', 'speak', ['DM']);
938
1053
  ```
939
1054
 
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 —
1055
+ **The emitter payload** is `RoomUpdate`, a two-member union discriminated by `type` —
1056
+ `RoomMessageUpdate` (`type: 'state'`) and `RoomErrorUpdate` (`type: 'error'`). Both are exported,
1057
+ so the narrowing above compiles under `strict` with nothing hand-written. A state update carries
1058
+ `latestMessage`, `messageIndex`, `totalCost`, `isPaused`, `currentSpeaker`,
1059
+ `processingInProgress` and `waitingForHuman`. `messageIndex` counts messages with thoughts and
1060
+ tool notices excluded, so compare it against a list fetched the same way —
943
1061
  `getRoomMessages(roomId)` — or refetch when they disagree.
944
1062
 
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.
1063
+ **Errors** arrive on the same emitter, as `{type: 'error', errorType, message, timestamp}`. Same
1064
+ event name rather than `'error'`, because an EventEmitter throws when an `'error'` event has no
1065
+ listener and that would take down a host that subscribed only to updates. Check for it first, as
1066
+ above: a turn that dies — most often on a spent balance — otherwise just goes quiet, with no
1067
+ message and nothing to await.
1068
+
1069
+ **`waitingForHuman` means "the human may send something", not "the human is being asked
1070
+ something".** It is true while a human holds the floor, and also true for an idle room — no
1071
+ speaker, nothing queued, nothing in flight — which includes the gap between `sendRoomMessage`
1072
+ accepting a line and processing starting. Gate a prompt on it alone and you open a second one
1073
+ before the table has said a word. `currentSpeaker === <the human's nickname>` is the test for
1074
+ "it is their turn", which is what the loop above uses; `waitingForHuman` is the right test for
1075
+ whether to enable a composer.
948
1076
 
949
1077
  **`sendRoomMessage`'s `action` defaults to `'moderate'`**, not `'speak'`. Pass the action you
950
1078
  mean. A message sent out of turn is refused rather than thrown: the result is
@@ -952,80 +1080,122 @@ mean. A message sent out of turn is refused rather than thrown: the result is
952
1080
 
953
1081
  **The `sender` string must be an `agentNickname`** — that is the name the room routes by.
954
1082
 
1083
+ **The `replyTo`/`replyAs` bookkeeping is only for a table with no moderator.** This room has
1084
+ none, so the player's line has to name its own recipient. Give the human agent
1085
+ `useModerator: true` in a room that has a moderator and all of it goes away — the room forces the
1086
+ message to `moderate`, clears the targets, and the moderator decides who answers. That is how the
1087
+ `dnd5e` room template ships; see [Example 11](#example-11-seating-a-whole-dd-table).
1088
+
955
1089
  Two notes for a long-running process. Call `await briyah.shutdown()` before exiting or it will
956
1090
  hang on open handles. And a room with no human-controlled agent never stops on its own: the
957
1091
  agents talk until the leader adjourns.
958
1092
 
959
1093
  ### Example 11: Seating a whole D&D table
960
1094
 
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.
1095
+ Example 10 seats a Dungeon Master and players, which is enough to see the loop but not enough to
1096
+ play. The `dungeon_master` prompt whispers a **campaign designer** to build the world and a
1097
+ **character creator** to build sheets, and hands fights to a **battle master**, so a table
1098
+ without those three has a leader whose own instructions reference agents that are not there.
965
1099
 
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.
1100
+ The pack ships that table as a room template, and instantiating it is the whole of the setup:
970
1101
 
971
1102
  ```typescript
972
- import { Briyah, dnd5eTools } from 'briyah';
1103
+ import { Briyah } from 'briyah';
973
1104
 
974
- const briyah = new Briyah({ dataPath: './briyah-data', tools: dnd5eTools() });
1105
+ const briyah = new Briyah({ dataPath: './briyah-data' });
975
1106
  await briyah.init();
976
1107
  const app = briyah.getAppService('cli-user');
977
1108
 
978
- // Per user, and required: a bare folder name only reaches the pack once it is enabled.
979
- app.packs.setEnabled('dnd5e', true);
1109
+ app.packs.setEnabled('dnd5e', true); // per user, and required
1110
+
1111
+ const { roomId, warnings } = await app.packInstantiation.instantiateRoom(
1112
+ 'dnd5e',
1113
+ 'table',
1114
+ {
1115
+ primary: { aiServiceName: 'Anthropic', aiModel: 'claude-sonnet-5' },
1116
+ economy: { aiServiceName: 'Anthropic', aiModel: 'claude-haiku-4-5' },
1117
+ },
1118
+ 'Campaign — Homer',
1119
+ { player: { agentName: 'Homer', agentNickname: 'Homer' } },
1120
+ );
1121
+ warnings.forEach((warning) => console.warn(warning));
1122
+ ```
1123
+
1124
+ That is six agents — moderator, Dungeon Master, battle master, character creator, campaign
1125
+ designer, and Homer at the keyboard — each with its folder's tool grants and rules documents,
1126
+ `turnMode: 'directed'`, the Dungeon Master leading, and the moderator created before the agents
1127
+ that route through it. Then run the loop from Example 10.
1128
+
1129
+ **The goal.** The template's goal describes the game in general. A first session usually wants
1130
+ one that says what has *not* happened yet, or the Dungeon Master opens a scene for characters
1131
+ who have no sheets:
1132
+
1133
+ ```typescript
1134
+ await app.editRoom(roomId, 'Campaign — Homer',
1135
+ 'A fifth-edition campaign for Homer. Nothing is prepared: no campaign has been designed ' +
1136
+ 'and no character has a sheet. Run session zero first — have the Campaign Designer ' +
1137
+ 'interview Homer and publish the Campaign document, then hand the Character Creator one ' +
1138
+ 'player at a time until every sheet exists — and only then open the first scene.');
1139
+ ```
1140
+
1141
+ **Models by role.** The Dungeon Master reasons and makes every tool call, and is the only agent
1142
+ the template puts on the primary model. Everyone else is `economy`, including the campaign
1143
+ designer, whose output is long but infrequent:
980
1144
 
1145
+ | Role | `modelRole` | Suggested |
1146
+ |---|---|---|
1147
+ | Dungeon Master | `primary` | `claude-sonnet-5` |
1148
+ | Battle master, character creator, campaign designer, moderator | `economy` | `claude-haiku-4-5` |
1149
+ | Players, human and AI | `economy` | `claude-haiku-4-5` |
1150
+
1151
+ Pass only `primary` and everything runs on it.
1152
+
1153
+ **The moderator, and what it saves your loop.** The shipped table seats one
1154
+ (`dnd5e:dnd_room_moderator`), and the player template sets `useModerator: true`. That pairing is
1155
+ not decoration: when a human agent has the flag, the room forces their message to `moderate` and
1156
+ clears its targets — server-side, whatever action you passed — and the moderator decides who
1157
+ hears it and who answers. A person typing a line does not know whether they are answering the
1158
+ designer's interview question or the DM's "what do you do", and with a moderator they do not have
1159
+ to: the `replyTo`/`replyAs` mirroring in Example 10 exists only because that table has none.
1160
+
1161
+ Skip the moderator when nothing addresses the player except the leader. Then the Dungeon Master
1162
+ names who acts next in a `directed` room, which is the same job for less money. If any agent has
1163
+ `useModerator: true`, the room must name a moderator or `createRoom` raises a `ValidationError`.
1164
+
1165
+ **Building it by hand.** If you want the pieces rather than the template, `createAgentFromFolder`
1166
+ reads a folder's `defaults_config.json` and applies all of it — the same wiring the web client's
1167
+ create-agent dialog performs — so you never transcribe eighteen tool names or thirteen document
1168
+ ids, and nothing drifts when the pack changes:
1169
+
1170
+ ```typescript
981
1171
  const from = (folder: string, aiModel: string, overrides = {}) =>
982
1172
  app.createAgentFromFolder({ folder, aiServiceName: 'Anthropic', aiModel, overrides });
983
1173
 
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');
1174
+ const mod = await from('dnd5e:dnd_room_moderator', 'claude-haiku-4-5');
1175
+ const dm = await from('dnd5e:dungeon_master', 'claude-sonnet-5');
1176
+ const marshal = await from('dnd5e:battle_master', 'claude-haiku-4-5');
1177
+ const designer = await from('dnd5e:campaign_designer', 'claude-haiku-4-5');
1178
+ const creator = await from('dnd5e:character_creator', 'claude-haiku-4-5');
987
1179
 
988
1180
  const you = await from('dnd5e:dnd_player', 'claude-haiku-4-5', {
989
- agentNickname: 'Homer',
1181
+ agentName: 'Homer', agentNickname: 'Homer',
990
1182
  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.',
1183
+ controlledByHuman: true, useModerator: true,
995
1184
  });
996
1185
 
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
1186
  const { roomId } = await app.createRoom(
1000
1187
  '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',
1188
+ 'A fifth-edition campaign for Homer. ...',
1189
+ [mod.id!, dm.id!, marshal.id!, designer.id!, creator.id!, you.id!],
1190
+ 'DM', // roomLeader
1191
+ 'directed', // turnMode
1192
+ 'Moderator', // moderator — required, because Homer has useModerator
1008
1193
  );
1009
1194
  ```
1010
1195
 
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`.
1196
+ The nicknames come from the folders: `Moderator`, `DM`, `Marshal`, `Designer`, `Creator`. These
1197
+ agents are free-standing rather than room-owned, so they appear in `listAgents()` and outlive the
1198
+ room; `createRoomAgentFromFolder` is the room-owned equivalent, and is what the template uses.
1029
1199
 
1030
1200
  **Resuming.** `listRooms()` gives saved campaigns; `getRoomDetails(roomId)` gives the roster,
1031
1201
  where `agents[].controlledByHuman` identifies the person's character. Then
@@ -1042,6 +1212,10 @@ Briyah stores data in the following structure:
1042
1212
  │ ├── config/ # LLM pricing and image-model config
1043
1213
  │ ├── prompts/ # Global prompt templates
1044
1214
  │ └── published-agents.json # Published agent mappings
1215
+ ├── packs/ # Installed packs, one directory each
1216
+ │ └── {pack}/ # pack.json, prompts/, artifacts/, agents/, rooms/
1217
+ ├── retired-prompts/ # Folders a pack took over; see "Upgrading to 2.0"
1218
+ ├── logs/ # briyah.log
1045
1219
  └── user/
1046
1220
  └── {userId}/ # Per-user data
1047
1221
  ├── agents/ # Agent configs and histories (one JSON per agent)
@@ -1049,11 +1223,17 @@ Briyah stores data in the following structure:
1049
1223
  ├── stories/ # Story state
1050
1224
  ├── tools/ # User-defined tools (one JSON per tool)
1051
1225
  ├── prompts/ # User-specific prompts
1226
+ ├── packs/{pack}/ # This user's edits to a pack, or a pack they created
1227
+ ├── artifacts/ # This user's own documents
1052
1228
  ├── upload/ # User file attachments
1053
1229
  ├── transactions/ # Transaction records
1054
- └── userconfig/ # User preferences and balance
1230
+ └── userconfig/ # User preferences, balance, and enabled packs
1055
1231
  ```
1056
1232
 
1233
+ `init()` seeds `common/` additively and **replaces** every bundled pack under `packs/` — see
1234
+ [Upgrading to 2.0](#upgrading-to-20) for exactly what is rewritten and where your own edits
1235
+ belong instead.
1236
+
1057
1237
  ## Multi-Instance Support
1058
1238
 
1059
1239
  You can create multiple Briyah instances with different configurations:
@@ -332,7 +332,7 @@ let AppController = AppController_1 = class AppController {
332
332
  }
333
333
  catch (error) {
334
334
  logger_1.logger.error(`[${req.user?.sub}] Error reading defaults for prompt folder ${folderName}:`, error);
335
- return { defaults: {} };
335
+ return { defaults: {}, exists: false };
336
336
  }
337
337
  }
338
338
  async getPromptFile(req, folderName, fileName) {
@@ -145,6 +145,8 @@ export declare class AppService {
145
145
  listPromptFilesWithScope(folderName: string): PromptFilesResponse;
146
146
  getPromptFile(folderName: string, fileName: string): PromptFileContent;
147
147
  getPromptFolderDefaults(folderName: string): PromptFolderDefaultsResponse;
148
+ promptFolderExists(folderName: string): boolean;
149
+ private requirePromptFolder;
148
150
  savePromptFile(folderName: string, fileName: string, content: string, fileType: string): void;
149
151
  deletePromptFile(folderName: string, fileName: string): void;
150
152
  getRoomArtifacts(roomId: string): Promise<{
@@ -182,6 +182,11 @@ class AppService {
182
182
  return this.getRandomStoryIdeaByGenre(randomGenre);
183
183
  }
184
184
  createAgent(aiServiceName, agentName, agentNickname, description, aiModel, promptName = 'default', controlledByHuman, reasoningEffort, maxOutputTokens, beginInstruction, options) {
185
+ if (!this.promptFolderExists(promptName)) {
186
+ logger_1.logger.warn(`Agent "${agentNickname}" names the prompt folder "${promptName}", which does not exist. ` +
187
+ `It will fall back to the shared root prompts and behave generically. ` +
188
+ `A pack's folder is named "<pack>:${promptName}" unless the pack is enabled for this user.`);
189
+ }
185
190
  const agent = this.agentFactory.createAgent(aiServiceName, agentName, agentNickname, description, promptName, aiModel);
186
191
  if (controlledByHuman !== undefined) {
187
192
  agent.isControlledByHuman = controlledByHuman;
@@ -218,6 +223,7 @@ class AppService {
218
223
  return agent;
219
224
  }
220
225
  async createAgentFromFolder(options) {
226
+ this.requirePromptFolder(options.folder);
221
227
  const { defaults } = this.getPromptFolderDefaults(options.folder);
222
228
  const settings = { ...defaults, ...options.overrides };
223
229
  const agent = this.createAgent(options.aiServiceName, settings.agentName ?? options.folder, settings.agentNickname ?? settings.agentName ?? options.folder, settings.description ?? '', options.aiModel, options.folder, settings.controlledByHuman, settings.reasoningEffort ?? null, undefined, settings.beginInstruction, {
@@ -545,6 +551,7 @@ class AppService {
545
551
  return { agentId: agent.id };
546
552
  }
547
553
  async createRoomAgentFromFolder(roomId, options) {
554
+ this.requirePromptFolder(options.folder);
548
555
  const { defaults } = this.getPromptFolderDefaults(options.folder);
549
556
  const settings = { ...defaults, ...options.overrides };
550
557
  const bareName = settings.agentName ?? options.folder;
@@ -980,9 +987,10 @@ class AppService {
980
987
  };
981
988
  }
982
989
  getPromptFolderDefaults(folderName) {
990
+ const exists = this.promptFolderExists(folderName);
983
991
  const file = this.getPromptFile(folderName, 'defaults_config.json');
984
992
  if (!file.content.trim()) {
985
- return { defaults: {} };
993
+ return { defaults: {}, exists };
986
994
  }
987
995
  let raw;
988
996
  try {
@@ -990,11 +998,11 @@ class AppService {
990
998
  }
991
999
  catch (error) {
992
1000
  logger_1.logger.warn(`Ignoring unparseable defaults_config.json in prompt folder "${folderName}": ${error.message}`);
993
- return { defaults: {} };
1001
+ return { defaults: {}, exists };
994
1002
  }
995
1003
  if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
996
1004
  logger_1.logger.warn(`Ignoring defaults_config.json in prompt folder "${folderName}": expected a JSON object`);
997
- return { defaults: {} };
1005
+ return { defaults: {}, exists };
998
1006
  }
999
1007
  const source = raw;
1000
1008
  const defaults = {};
@@ -1041,7 +1049,19 @@ class AppService {
1041
1049
  if (efforts.includes(effort)) {
1042
1050
  defaults.reasoningEffort = effort;
1043
1051
  }
1044
- return { defaults, scope: file.scope };
1052
+ return { defaults, scope: file.scope, exists };
1053
+ }
1054
+ promptFolderExists(folderName) {
1055
+ return (0, prompt_resolver_1.promptFolderExists)(this.userPaths, folderName, { enabledPacks: this.enabledPacks });
1056
+ }
1057
+ requirePromptFolder(folderName) {
1058
+ if (this.promptFolderExists(folderName))
1059
+ return;
1060
+ const enabled = this.enabledPacks();
1061
+ const hint = (0, prompt_resolver_1.isPackFolder)(folderName)
1062
+ ? `Check the pack is installed under the data directory and that the folder name is spelled as it is on disk.`
1063
+ : `A pack's folder must be named "<pack>:${folderName}", or the pack enabled for this user${enabled.length ? ` (enabled: ${enabled.join(', ')})` : ' (this user has none enabled)'}.`;
1064
+ throw new errors_1.NotFoundError(`No prompt folder "${folderName}". ${hint}`);
1045
1065
  }
1046
1066
  savePromptFile(folderName, fileName, content, fileType) {
1047
1067
  const targetDir = (0, prompt_resolver_1.promptWriteDir)(this.userPaths, folderName);
@@ -1438,6 +1458,7 @@ class AppService {
1438
1458
  .map((a) => a.totalCost)
1439
1459
  .reduce((acc, v) => acc + v, 0);
1440
1460
  const roomState = {
1461
+ type: 'state',
1441
1462
  roomId: roomId,
1442
1463
  latestMessage: latestMessage,
1443
1464
  messageIndex: messages.length > 0 ? messages.length - 1 : undefined,
@@ -12,6 +12,7 @@ export interface PromptDir {
12
12
  tier: PromptTier;
13
13
  pack: string | null;
14
14
  scope: PromptScope;
15
+ folderScoped: boolean;
15
16
  }
16
17
  export interface PromptCandidate extends PromptDir {
17
18
  absolutePath: string;
@@ -28,6 +29,7 @@ export declare function promptFolderDirs(userPaths: UserPathsService, folder: st
28
29
  export declare function promptFolderDirsLowestFirst(userPaths: UserPathsService, folder: string, options?: PromptResolveOptions): PromptDir[];
29
30
  export declare function promptSearchPaths(userPaths: UserPathsService, folder: string, fileName: string, extension: string, options?: PromptResolveOptions): PromptCandidate[];
30
31
  export declare function resolvePromptFile(userPaths: UserPathsService, folder: string, fileName: string, extension: string, options?: PromptResolveOptions): PromptCandidate | null;
32
+ export declare function promptFolderExists(userPaths: UserPathsService, folder: string, options?: PromptResolveOptions): boolean;
31
33
  export interface PromptFolderRef {
32
34
  value: string;
33
35
  folder: string;
@@ -43,6 +43,7 @@ exports.promptFolderDirs = promptFolderDirs;
43
43
  exports.promptFolderDirsLowestFirst = promptFolderDirsLowestFirst;
44
44
  exports.promptSearchPaths = promptSearchPaths;
45
45
  exports.resolvePromptFile = resolvePromptFile;
46
+ exports.promptFolderExists = promptFolderExists;
46
47
  exports.listPromptFolderRefs = listPromptFolderRefs;
47
48
  exports.promptWriteDir = promptWriteDir;
48
49
  const fs = __importStar(require("fs"));
@@ -101,13 +102,14 @@ function enabledPacksOf(options) {
101
102
  function promptFolderDirs(userPaths, folder, options) {
102
103
  const ref = parsePromptFolder(folder);
103
104
  const dirs = [];
104
- const push = (dir, tier, pack = null) => dirs.push({ dir, tier, pack, scope: scopeOf(tier) });
105
+ const push = (dir, tier, pack = null) => dirs.push({ dir, tier, pack, scope: scopeOf(tier), folderScoped: false });
106
+ const pushFolder = (dir, tier, pack = null) => dirs.push({ dir, tier, pack, scope: scopeOf(tier), folderScoped: true });
105
107
  if (ref.pack) {
106
108
  const overlay = path.join(userPaths.getUserPackDir(ref.pack), 'prompts');
107
109
  const installed = path.join(userPaths.getPackDir(ref.pack), 'prompts');
108
110
  if (ref.folder) {
109
- push(path.join(overlay, ref.folder), 'pack-overlay', ref.pack);
110
- push(path.join(installed, ref.folder), 'pack', ref.pack);
111
+ pushFolder(path.join(overlay, ref.folder), 'pack-overlay', ref.pack);
112
+ pushFolder(path.join(installed, ref.folder), 'pack', ref.pack);
111
113
  }
112
114
  push(overlay, 'pack-overlay', ref.pack);
113
115
  push(installed, 'pack', ref.pack);
@@ -116,14 +118,14 @@ function promptFolderDirs(userPaths, folder, options) {
116
118
  return dedupe(dirs);
117
119
  }
118
120
  if (ref.folder) {
119
- push(path.join(userPaths.getUserPromptsDir(), ref.folder), 'user');
121
+ pushFolder(path.join(userPaths.getUserPromptsDir(), ref.folder), 'user');
120
122
  }
121
123
  push(userPaths.getUserPromptsDir(), 'user');
122
124
  if (ref.folder) {
123
- push(path.join(userPaths.getCommonPromptsDir(), ref.folder), 'common');
125
+ pushFolder(path.join(userPaths.getCommonPromptsDir(), ref.folder), 'common');
124
126
  for (const pack of enabledPacksOf(options)) {
125
- push(path.join(userPaths.getUserPackDir(pack), 'prompts', ref.folder), 'pack-overlay', pack);
126
- push(path.join(userPaths.getPackDir(pack), 'prompts', ref.folder), 'pack', pack);
127
+ pushFolder(path.join(userPaths.getUserPackDir(pack), 'prompts', ref.folder), 'pack-overlay', pack);
128
+ pushFolder(path.join(userPaths.getPackDir(pack), 'prompts', ref.folder), 'pack', pack);
127
129
  }
128
130
  }
129
131
  push(userPaths.getCommonPromptsDir(), 'common');
@@ -147,6 +149,11 @@ function resolvePromptFile(userPaths, folder, fileName, extension, options) {
147
149
  }
148
150
  return null;
149
151
  }
152
+ function promptFolderExists(userPaths, folder, options) {
153
+ if (!parsePromptFolder(folder).folder)
154
+ return true;
155
+ return promptFolderDirs(userPaths, folder, options).some((entry) => entry.folderScoped && fs.existsSync(entry.dir));
156
+ }
150
157
  function listPromptFolderRefs(userPaths, options) {
151
158
  const byValue = new Map();
152
159
  const add = (dir, tier, pack) => {
@@ -11,6 +11,7 @@ export interface InstantiateModels {
11
11
  primary: ModelChoice;
12
12
  economy?: ModelChoice;
13
13
  }
14
+ export type RosterOverrides = Record<string, Partial<PromptFolderDefaults>>;
14
15
  export interface InstantiateRoomResult {
15
16
  roomId: string;
16
17
  agentIds: string[];
@@ -21,7 +22,7 @@ export declare class PackInstantiationService {
21
22
  private readonly packs;
22
23
  private readonly roomStore;
23
24
  constructor(app: AppService, packs: PackService, roomStore: RoomStoreService);
24
- instantiateRoom(packName: string, roomKey: string, models: InstantiateModels, name?: string): Promise<InstantiateRoomResult>;
25
+ instantiateRoom(packName: string, roomKey: string, models: InstantiateModels, name?: string, overrides?: RosterOverrides): Promise<InstantiateRoomResult>;
25
26
  instantiateAgent(packName: string, agentKey: string, models: InstantiateModels, overrides?: Partial<PromptFolderDefaults>): Promise<{
26
27
  agentId: string;
27
28
  warnings: string[];