briyah 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/README.md +309 -4
  2. package/data/common/prompts/character_creator/defaults_config.json +1 -1
  3. package/dist-sdk/server/src/app.service.d.ts +8 -1
  4. package/dist-sdk/server/src/app.service.js +26 -0
  5. package/dist-sdk/server/src/room/room.d.ts +3 -2
  6. package/dist-sdk/server/src/room/room.js +8 -5
  7. package/dist-sdk/server/src/sdk/index.d.ts +2 -2
  8. package/dist-sdk/server/src/story/story.service.js +2 -2
  9. package/docs/assets/hierarchy.js +1 -1
  10. package/docs/assets/navigation.js +1 -1
  11. package/docs/assets/search.js +1 -1
  12. package/docs/classes/Agent.html +20 -20
  13. package/docs/classes/Briyah.html +14 -14
  14. package/docs/classes/BriyahConfigService.html +5 -5
  15. package/docs/classes/NativeToolRegistry.html +6 -6
  16. package/docs/classes/Room.html +46 -37
  17. package/docs/classes/RoomMessage.html +11 -11
  18. package/docs/enums/MessageAction.html +3 -3
  19. package/docs/functions/availableToolPacks.html +2 -2
  20. package/docs/functions/dnd5eTools.html +2 -2
  21. package/docs/functions/enabledToolPacks.html +2 -2
  22. package/docs/functions/registerToolPacks.html +2 -2
  23. package/docs/hierarchy.html +1 -1
  24. package/docs/index.html +125 -4
  25. package/docs/interfaces/AgentCreationOptions.html +26 -0
  26. package/docs/interfaces/AgentInfo.html +3 -3
  27. package/docs/interfaces/AgentMessagesResponse.html +2 -2
  28. package/docs/interfaces/AppService.html +210 -178
  29. package/docs/interfaces/Artifact.html +4 -4
  30. package/docs/interfaces/ArtifactMetadata.html +3 -3
  31. package/docs/interfaces/ArtifactWriteOptions.html +5 -5
  32. package/docs/interfaces/AttachDocumentResponse.html +2 -2
  33. package/docs/interfaces/BriyahConfigOptions.html +9 -9
  34. package/docs/interfaces/ChapterInfo.html +2 -2
  35. package/docs/interfaces/Character.html +2 -2
  36. package/docs/interfaces/CreateAgentResponse.html +2 -2
  37. package/docs/interfaces/CreateRoomResponse.html +2 -2
  38. package/docs/interfaces/CreateStoryResponse.html +2 -2
  39. package/docs/interfaces/FileList.html +2 -2
  40. package/docs/interfaces/FileMetadata.html +3 -3
  41. package/docs/interfaces/IConfigService.html +3 -3
  42. package/docs/interfaces/LoggingOptions.html +6 -6
  43. package/docs/interfaces/Message.html +2 -2
  44. package/docs/interfaces/ModelInfo.html +2 -2
  45. package/docs/interfaces/NativeToolDefinition.html +8 -8
  46. package/docs/interfaces/PreparedPromptResponse.html +2 -2
  47. package/docs/interfaces/ProcessTextResponse.html +2 -2
  48. package/docs/interfaces/PromptFile.html +2 -2
  49. package/docs/interfaces/PromptFileContent.html +2 -2
  50. package/docs/interfaces/PromptFilesResponse.html +2 -2
  51. package/docs/interfaces/PromptFolder.html +2 -2
  52. package/docs/interfaces/PromptFolderDefaults.html +24 -0
  53. package/docs/interfaces/PromptFolderDefaultsResponse.html +5 -0
  54. package/docs/interfaces/PromptFoldersResponse.html +2 -2
  55. package/docs/interfaces/RoomDetails.html +4 -4
  56. package/docs/interfaces/RoomInfo.html +2 -2
  57. package/docs/interfaces/RoomMessageUpdate.html +2 -2
  58. package/docs/interfaces/RoomMessagesResponse.html +2 -2
  59. package/docs/interfaces/SendMessageResult.html +2 -2
  60. package/docs/interfaces/StoryErrorEvent.html +3 -3
  61. package/docs/interfaces/StoryIdea.html +2 -2
  62. package/docs/interfaces/StoryInfo.html +3 -3
  63. package/docs/interfaces/StoryIntroduceCharacterEvent.html +3 -3
  64. package/docs/interfaces/StoryProgressChapterEvent.html +3 -3
  65. package/docs/interfaces/StoryState.html +5 -5
  66. package/docs/interfaces/StoryStateEvent.html +3 -3
  67. package/docs/interfaces/ToolArtifact.html +4 -4
  68. package/docs/interfaces/ToolCaller.html +5 -5
  69. package/docs/interfaces/ToolDefinition.html +2 -2
  70. package/docs/interfaces/ToolHelpers.html +4 -4
  71. package/docs/interfaces/ToolParameter.html +2 -2
  72. package/docs/interfaces/ToolRoomAccess.html +9 -9
  73. package/docs/interfaces/ToolSummary.html +2 -2
  74. package/docs/interfaces/ToolsResponse.html +2 -2
  75. package/docs/interfaces/Transaction.html +2 -2
  76. package/docs/interfaces/TransactionHistoryResponse.html +2 -2
  77. package/docs/modules.html +1 -1
  78. package/docs/types/PromptScope.html +1 -1
  79. package/docs/types/RoomTurnMode.html +8 -0
  80. package/docs/types/ToolContext.html +2 -2
  81. package/docs/types/ToolRunResult.html +1 -1
  82. package/package.json +3 -2
  83. package/src/tools/packs/dnd5e/README.md +627 -0
package/README.md CHANGED
@@ -248,9 +248,31 @@ await appService.reloadAgent(agentId); // Clear conversation histor
248
248
  await appService.compactAgentConversation(agentId); // Summarize history into a single message
249
249
 
250
250
  // Room Management
251
- const room = await appService.createRoom(name, goal, agentIds);
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
+ );
252
257
  const rooms = await appService.listRooms();
253
- await appService.sendRoomMessage(roomId, content, sender, action?);
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
+ });
254
276
 
255
277
  // Agents that belong to a room: created inside it, named after it, deleted with it,
256
278
  // and left out of listAgents(). agentName is the bare name; the room's is prefixed on.
@@ -269,7 +291,11 @@ await appService.deleteTool(name);
269
291
  const result = await appService.testTool(name, args); // { ok: true, result } | { ok: false, error }
270
292
 
271
293
  // Story Management
272
- const story = await appService.createStory(name, idea, userCharacterDesc, otherCharactersDesc, storyModel?);
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
+ );
273
299
  await appService.progressStory(storyId);
274
300
 
275
301
  // Text Processing
@@ -285,6 +311,87 @@ await appService.deleteAttachedFile(agentId, fileName); // by filename
285
311
  await appService.deleteAttachedFileById(documentId); // by document ID
286
312
  ```
287
313
 
314
+ ## Prompt Folders
315
+
316
+ An agent's behaviour comes from a **prompt folder**, not from its description. The folder
317
+ holds the templates the room renders on every turn — most importantly `perceive.prompt`, which
318
+ tells the agent what it is and what it may do, and `perceive.json`, the JSON schema its replies
319
+ must satisfy. Two agents on the same model with the same description behave completely
320
+ differently if they were built from different folders.
321
+
322
+ `init()` seeds the bundled folders into `{dataPath}/common/prompts/`, so they are on disk before
323
+ your first `createAgent` call. Existing files are preserved on upgrade, so anything you edit
324
+ survives.
325
+
326
+ ```typescript
327
+ const appService = briyah.getAppService('user-123');
328
+ console.log(appService.listPromptFolders());
329
+ // default, dungeon_master, dnd_player, character_creator, campaign_designer,
330
+ // dnd_room_moderator, narrator, character, illustrator, ...
331
+ ```
332
+
333
+ **The folder is the sixth argument to `createAgent`, and it defaults to `'default'`** — a
334
+ generic conversational agent. Passing a role folder is what makes the agent that role:
335
+
336
+ ```typescript
337
+ const dm = appService.createAgent(
338
+ 'Anthropic',
339
+ 'Dungeon Master', // agentName — a label; used in logs and the UI
340
+ 'DM', // agentNickname — the name the room routes by
341
+ 'Runs the game.',
342
+ 'claude-sonnet-5',
343
+ 'dungeon_master', // <- the prompt folder
344
+ );
345
+ ```
346
+
347
+ `agentNickname` is the identity: messages are addressed to it, artifact viewers are lists of
348
+ it, and it is what an agent writes into `targets`. `agentName` is a label. Give a character the
349
+ nickname you want it called by.
350
+
351
+ To write your own folder, copy a bundled one out of `{dataPath}/common/prompts/`, rename the
352
+ directory, and edit it — a folder in the user data directory takes precedence over the common
353
+ one of the same name.
354
+
355
+ ## Tool Packs
356
+
357
+ A tool pack is a set of native tools that ships with Briyah and registers only when asked for.
358
+ `dnd5e` is the one that exists: seventeen tools for dice, character sheets, the rules engine and
359
+ a bestiary. Turn it on either way:
360
+
361
+ ```typescript
362
+ // By name — the SDK registers the pack during construction
363
+ const briyah = new Briyah({ envOverrides: { BRIYAH_TOOL_PACKS: 'dnd5e' } });
364
+
365
+ // Or pass the definitions yourself, which also lets you filter or wrap them
366
+ import { dnd5eTools, availableToolPacks } from 'briyah';
367
+ const briyah = new Briyah({ tools: dnd5eTools() });
368
+ console.log(availableToolPacks()); // ['dnd5e']
369
+ ```
370
+
371
+ Registering makes the tools *grantable*, not granted. An agent may only run the ones named in
372
+ its `toolNames`:
373
+
374
+ ```typescript
375
+ const dm = appService.createAgent(
376
+ 'Anthropic', 'Dungeon Master', 'DM', 'Runs the game.', 'claude-sonnet-5', 'dungeon_master',
377
+ undefined, null, 0, '',
378
+ { toolNames: ['roll_dice', 'check', 'apply_hp', 'stat_block', 'read_sheet'] },
379
+ );
380
+ ```
381
+
382
+ Packs also ship read-only **documents** — rules text an agent carries in every call. They seed
383
+ into `{dataPath}/common/artifacts/`, appear in `listUserArtifacts()` alongside your own, and
384
+ attach by id:
385
+
386
+ ```typescript
387
+ await appService.attachArtifactToAgent(dm.id, 'pack:dnd5e.dungeon_master-procedure');
388
+ await appService.attachArtifactToAgent(player.id, 'pack:dnd5e.class-bard');
389
+ ```
390
+
391
+ A document sits in that agent's cached prompt prefix on every call, so attach what it needs and
392
+ nothing more. `src/tools/packs/dnd5e/README.md` in this package lists all seventeen tools and
393
+ which agent each document belongs to.
394
+
288
395
  ## Usage Examples
289
396
 
290
397
  ### Example 1: Multi-User Setup
@@ -430,7 +537,9 @@ const app = briyah.getAppService('user-123');
430
537
  const story = await app.createStory(
431
538
  'The Lost Kingdom',
432
539
  'A medieval fantasy where ancient ruins hold a terrible secret',
433
- 'A disgraced knight seeking redemption'
540
+ 'A disgraced knight seeking redemption',
541
+ 'A scholar and a sellsword',
542
+ false, // illustrateStory — required, and positional
434
543
  );
435
544
 
436
545
  const emitter = app.getStoryMessageEmitter(story.id);
@@ -629,6 +738,202 @@ Notes:
629
738
 
630
739
  **Custom workflows.** Any ComfyUI workflow can be used: build it in the ComfyUI web UI, run it once, then use Export (API format) and replace the values you want parameterized with tokens — `{{prompt}}` (may be embedded in a longer string), `{{seed}}`, `{{width}}`, `{{height}}` (replaced as numbers), and `{{ref_image}}` (edit workflows, the `LoadImage` input). Save the files as `{name}.t2i.json` (used by `generateImage`) and `{name}.edit.json` (used by `editImage`) in `{dataPath}/common/config/comfyui-workflows/`, or in `{dataPath}/user/{userId}/comfyui-workflows/` for a per-user override (checked first). The pair name becomes the model name. For multi-reference support, an edit workflow must contain exactly one `ReferenceLatent` node fed by a `VAEEncode` fed by a `LoadImage`; extra references are added at request time by cloning that chain.
631
740
 
741
+ ### Example 10: A turn-based table with a human player
742
+
743
+ Example 5 sends one message and reads the transcript back, which suits a batch job. A game or
744
+ any human-in-the-loop app needs the other shape: the agents take several turns among themselves,
745
+ then stop and wait for the person. Three things make that work.
746
+
747
+ **`turnMode: 'directed'`** — only the agent a message names is asked to reply, and the room
748
+ leader answers anything it cannot place. The default, `'broadcast'`, prompts *every* agent for
749
+ *every* message and keeps one reply, which costs several times as much and is wrong for a table
750
+ where one person speaks at a time.
751
+
752
+ **A human-controlled agent** — `createAgent`'s seventh argument. The room delivers messages to
753
+ it and then stops rather than generating a reply, which is what yields the floor to your console.
754
+
755
+ **The room message emitter** — the only way to see the conversation as it happens. It fires on
756
+ every change with the newest message and the room's state.
757
+
758
+ ```typescript
759
+ import { Briyah, dnd5eTools } from 'briyah';
760
+ import * as readline from 'node:readline/promises';
761
+
762
+ const briyah = new Briyah({ dataPath: './briyah-data', tools: dnd5eTools() });
763
+ await briyah.init(); // seeds prompt folders and pack documents
764
+ const app = briyah.getAppService('user-123');
765
+
766
+ const dm = app.createAgent(
767
+ 'Anthropic', 'Dungeon Master', 'DM', 'Runs the game.', 'claude-sonnet-5',
768
+ 'dungeon_master', undefined, null, 0, '',
769
+ { toolNames: ['roll_dice', 'check', 'apply_hp', 'stat_block', 'read_sheet'] },
770
+ );
771
+ const rogue = app.createAgent(
772
+ 'Anthropic', 'Vex', 'Vex', 'A wary scout.', 'claude-haiku-4-5', 'dnd_player',
773
+ );
774
+ // The seventh argument is what makes this one wait for a person.
775
+ const you = app.createAgent(
776
+ 'Anthropic', 'Homer', 'Homer', 'A hopeful bard.', 'claude-haiku-4-5', 'dnd_player',
777
+ true,
778
+ );
779
+
780
+ // createAgent builds the agent in memory; save() writes it to disk. Without this the
781
+ // table exists for this process only and is gone on restart.
782
+ [dm, rogue, you].forEach((agent) => agent.save());
783
+
784
+ await app.attachArtifactToAgent(dm.id!, 'pack:dnd5e.dungeon_master-procedure');
785
+ await app.attachArtifactToAgent(rogue.id!, 'pack:dnd5e.class-rogue');
786
+ await app.attachArtifactToAgent(you.id!, 'pack:dnd5e.class-bard');
787
+
788
+ const { roomId } = await app.createRoom(
789
+ 'The Sunken Barrow',
790
+ 'A three-room dungeon crawl.',
791
+ [dm.id!, rogue.id!, you.id!],
792
+ 'DM', // roomLeader — answers anything the room cannot place
793
+ 'directed', // turnMode
794
+ );
795
+
796
+ // A room loaded from disk has no state-change callback, so its emitter would never
797
+ // fire. Harmless on a room you just created; required for one you resumed.
798
+ await app.ensureRoomStateCallback(roomId);
799
+
800
+ const io = readline.createInterface({ input: process.stdin, output: process.stdout });
801
+ let lastIndex = -1;
802
+ let atKeyboard = false; // the handler is async; without this it re-enters
803
+ let replyTo = 'DM'; // who last spoke to the player
804
+ let replyAs: 'speak' | 'whisper' = 'speak';
805
+
806
+ app.getRoomMessageEmitter(roomId).on('update', async (state) => {
807
+ if (state.type === 'error') { // a turn failed — see "Errors" below
808
+ console.error(`[${state.errorType}] ${state.message}`);
809
+ return;
810
+ }
811
+
812
+ const message = state.latestMessage;
813
+ if (message && state.messageIndex !== undefined && state.messageIndex > lastIndex) {
814
+ lastIndex = state.messageIndex; // the emitter can repeat a state
815
+ if (message.sender !== 'Homer') console.log(`${message.sender}: ${message.content}`);
816
+ // Answer whoever addressed you, the way they addressed you. During session
817
+ // zero that is the designer or the creator, whispering — replying to the DM
818
+ // instead drops the interview.
819
+ if (message.targets?.includes('Homer') && message.sender !== 'Homer') {
820
+ replyTo = message.sender;
821
+ replyAs = message.action === 'whisper' ? 'whisper' : 'speak';
822
+ }
823
+ }
824
+
825
+ // The floor is the player's only when the room *names* them. `waitingForHuman`
826
+ // is also true for a moment after sendRoomMessage clears currentSpeaker and
827
+ // before processing starts, so gating on it alone opens a second prompt before
828
+ // the table has said a word.
829
+ if (!atKeyboard && state.currentSpeaker === 'Homer') {
830
+ atKeyboard = true;
831
+ try {
832
+ const line = await io.question('> ');
833
+ const result = await app.sendRoomMessage(roomId, line, 'Homer', replyAs, [replyTo]);
834
+ if (!result.accepted) console.log(`(not your turn — ${result.reason})`);
835
+ } finally {
836
+ atKeyboard = false;
837
+ }
838
+ }
839
+ });
840
+
841
+ // The emitter only fires on a *change*, so the opening line comes from here.
842
+ await app.sendRoomMessage(roomId, 'Begin the adventure.', 'Homer', 'speak', ['DM']);
843
+ ```
844
+
845
+ **The emitter payload** carries `latestMessage`, `messageIndex`, `totalCost`, `isPaused`,
846
+ `currentSpeaker`, `processingInProgress` and `waitingForHuman`. `messageIndex` counts messages
847
+ with thoughts and tool notices excluded, so compare it against a list fetched the same way —
848
+ `getRoomMessages(roomId)` — or refetch when they disagree.
849
+
850
+ **Errors** arrive on the same emitter as `{type: 'error', errorType, message}`. Check for it
851
+ first, as above: a turn that dies — most often on a spent balance — otherwise just goes quiet,
852
+ with no message and nothing to await.
853
+
854
+ **`sendRoomMessage`'s `action` defaults to `'moderate'`**, not `'speak'`. Pass the action you
855
+ mean. A message sent out of turn is refused rather than thrown: the result is
856
+ `{accepted: false, reason}`, which is what to show as "not your turn".
857
+
858
+ **The `sender` string must be an `agentNickname`** — that is the name the room routes by.
859
+
860
+ Two notes for a long-running process. Call `await briyah.shutdown()` before exiting or it will
861
+ hang on open handles. And a room with no human-controlled agent never stops on its own: the
862
+ agents talk until the leader adjourns.
863
+
864
+ ### Example 11: Seating a whole D&D table
865
+
866
+ Example 10 seats a Dungeon Master and players, which is enough to see the loop but not enough
867
+ to play. The `dungeon_master` prompt whispers a **campaign designer** to build the world and a
868
+ **character creator** to build sheets, so a table without those two has a leader whose own
869
+ instructions reference agents that are not there.
870
+
871
+ The other half is that each role needs its folder's tool grants and pack documents.
872
+ `createAgentFromFolder` reads the folder's `defaults_config.json` and applies all of it — the
873
+ same wiring the web client's create-agent dialog performs — so you never transcribe seventeen
874
+ tool names or thirteen document ids by hand, and nothing drifts when the pack changes.
875
+
876
+ ```typescript
877
+ import { Briyah, dnd5eTools } from 'briyah';
878
+
879
+ const briyah = new Briyah({ dataPath: './briyah-data', tools: dnd5eTools() });
880
+ await briyah.init();
881
+ const app = briyah.getAppService('cli-user');
882
+
883
+ const from = (folder: string, aiModel: string, overrides = {}) =>
884
+ app.createAgentFromFolder({ folder, aiServiceName: 'Anthropic', aiModel, overrides });
885
+
886
+ const dm = await from('dungeon_master', 'claude-sonnet-5');
887
+ const designer = await from('campaign_designer', 'claude-sonnet-5');
888
+ const creator = await from('character_creator', 'claude-haiku-4-5');
889
+
890
+ const you = await from('dnd_player', 'claude-haiku-4-5', {
891
+ agentNickname: 'Homer',
892
+ description: 'A player character with no sheet yet, played by a person.',
893
+ controlledByHuman: true,
894
+ });
895
+ const vex = await from('dnd_player', 'claude-haiku-4-5', {
896
+ agentNickname: 'Vex', description: 'A wary scout.',
897
+ });
898
+
899
+ // The goal is read by every agent every turn. Say what has *not* happened yet, or the
900
+ // Dungeon Master opens a scene for characters who have no sheets.
901
+ const { roomId } = await app.createRoom(
902
+ 'Campaign — Homer',
903
+ 'A fifth-edition campaign for Homer and Vex. Nothing is prepared: no campaign has been ' +
904
+ 'designed and no character has a sheet. Run session zero first — have the Campaign ' +
905
+ 'Designer interview Homer and publish the Campaign document, then hand the Character ' +
906
+ 'Creator one player at a time until both sheets exist — and only then open the first scene.',
907
+ [dm.id!, designer.id!, creator.id!, you.id!, vex.id!],
908
+ 'DM',
909
+ 'directed',
910
+ );
911
+ ```
912
+
913
+ Then run the loop from Example 10. Session zero is whispered, which is why that loop mirrors
914
+ the action it replies with.
915
+
916
+ **Models by role.** The Dungeon Master reasons and makes every tool call; the specialists run a
917
+ few dozen times per campaign; the players are cheap.
918
+
919
+ | Role | Model |
920
+ |---|---|
921
+ | Dungeon Master, campaign designer | `claude-sonnet-5` |
922
+ | Character creator | `claude-haiku-4-5` |
923
+ | Players, human and AI | `claude-haiku-4-5` |
924
+
925
+ **Moderators.** `createRoom`'s sixth argument names one, and the `dnd_room_moderator` folder
926
+ provides one. A 5e table does **not** need it: the Dungeon Master leads a `directed` room and
927
+ names who acts next, which is the same job. A moderator earns its place when no agent is in
928
+ charge of the turn order — several people talking at once, or a room whose members address each
929
+ other freely. If you give an agent `useModerator: true`, the room must have one or `createRoom`
930
+ raises a `ValidationError`.
931
+
932
+ **Resuming.** `listRooms()` gives saved campaigns; `getRoomDetails(roomId)` gives the roster,
933
+ where `agents[].controlledByHuman` identifies the person's character. Then
934
+ `ensureRoomStateCallback(roomId)` before subscribing — without it the emitter on a resumed room
935
+ never fires.
936
+
632
937
  ## Data Storage
633
938
 
634
939
  Briyah stores data in the following structure:
@@ -27,5 +27,5 @@
27
27
  "pack:dnd5e.class-wizard"
28
28
  ],
29
29
  "promptCacheTTL": 60,
30
- "maxHistoryMessages": 0
30
+ "maxHistoryMessages": 20
31
31
  }
@@ -21,7 +21,7 @@ import { TransactionService } from './app/transaction.service';
21
21
  import { AgentFactory } from './ai/agent-factory';
22
22
  import { RoomFactory } from './room/room-factory';
23
23
  import { EventEmitter } from 'events';
24
- import { AgentInfo, RoomInfo, RoomDetails, RoomTurnMode, CreateRoomResponse, CreateAgentResponse, CreateRoomAgentRequest, FileList, PromptFileContent, PromptFoldersResponse, PromptFilesResponse, PromptScope, PromptFolderDefaultsResponse, ProcessTextResponse, PreparedPromptResponse, AttachDocumentResponse, AgentMessagesResponse, RoomMessagesResponse, SendMessageResult, StoryInfo, StoryState, Character, Transaction, TransactionHistoryResponse, ToolDefinition, ToolSummary, ToolRunResult } from '../../shared/types/app.types';
24
+ import { AgentInfo, RoomInfo, RoomDetails, RoomTurnMode, CreateRoomResponse, CreateAgentResponse, CreateRoomAgentRequest, FileList, PromptFileContent, PromptFoldersResponse, PromptFilesResponse, PromptScope, PromptFolderDefaults, PromptFolderDefaultsResponse, ProcessTextResponse, PreparedPromptResponse, AttachDocumentResponse, AgentMessagesResponse, RoomMessagesResponse, SendMessageResult, StoryInfo, StoryState, Character, Transaction, TransactionHistoryResponse, ToolDefinition, ToolSummary, ToolRunResult } from '../../shared/types/app.types';
25
25
  import { RoomMessage } from './room/message';
26
26
  import { ToolStoreService } from './tools/tool-store.service';
27
27
  import { ToolExecutionService } from './tools/tool-execution.service';
@@ -67,6 +67,13 @@ export declare class AppService {
67
67
  getRandomStoryIdeaByGenre(genreName: string): StoryIdea | null;
68
68
  getRandomStoryIdea(): StoryIdea | null;
69
69
  createAgent(aiServiceName: string, agentName: string, agentNickname: string, description: string, aiModel: string, promptName?: string, controlledByHuman?: boolean, reasoningEffort?: 'low' | 'medium' | 'high' | null, maxOutputTokens?: number, beginInstruction?: string, options?: AgentCreationOptions): Agent;
70
+ createAgentFromFolder(options: {
71
+ folder: string;
72
+ aiServiceName: string;
73
+ aiModel: string;
74
+ overrides?: Partial<PromptFolderDefaults>;
75
+ attachDocuments?: boolean;
76
+ }): Promise<Agent>;
70
77
  processText(agentId: string, text: string): Promise<ProcessTextResponse>;
71
78
  attachDocument(agentId: string, fileName: string, fileData: Buffer): Promise<AttachDocumentResponse>;
72
79
  listPromptFolders(): string[];
@@ -200,6 +200,29 @@ class AppService {
200
200
  this.agentStore.registerAgent(agent);
201
201
  return agent;
202
202
  }
203
+ async createAgentFromFolder(options) {
204
+ const { defaults } = this.getPromptFolderDefaults(options.folder);
205
+ const settings = { ...defaults, ...options.overrides };
206
+ 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, {
207
+ toolNames: settings.toolNames ?? [],
208
+ allowSearch: settings.allowSearch,
209
+ useModerator: settings.useModerator,
210
+ privateContext: settings.privateContext,
211
+ promptCacheTTL: settings.promptCacheTTL,
212
+ maxHistoryMessages: settings.maxHistoryMessages,
213
+ smallModelName: settings.smallModelName,
214
+ });
215
+ if (!agent.id) {
216
+ throw new Error(`Failed to create an agent from prompt folder "${options.folder}"`);
217
+ }
218
+ agent.save();
219
+ if (options.attachDocuments !== false) {
220
+ for (const artifactId of settings.documentIds ?? []) {
221
+ await this.attachArtifactToAgent(agent.id, artifactId);
222
+ }
223
+ }
224
+ return agent;
225
+ }
203
226
  async processText(agentId, text) {
204
227
  const agent = await this.agentStore.getAgent(agentId);
205
228
  if (!agent) {
@@ -1374,6 +1397,9 @@ class AppService {
1374
1397
  logger_1.logger.warn('Cannot set up SSE callback for room without ID');
1375
1398
  return;
1376
1399
  }
1400
+ room.setOnError('app-service', (error) => {
1401
+ this.roomMessageService.emitError(roomId, error);
1402
+ });
1377
1403
  room.setOnStateChange('app-service', () => {
1378
1404
  const messages = room.getLatestRoomMessages(0, false);
1379
1405
  const latestMessage = messages.length > 0 ? messages[messages.length - 1] : undefined;
@@ -27,7 +27,7 @@ export declare class Room {
27
27
  private isPublished;
28
28
  private isLoading;
29
29
  private onStateChangeCallbacks;
30
- private onError?;
30
+ private onErrorCallbacks;
31
31
  private currentSituation;
32
32
  private currentSituationTime;
33
33
  private onSituationUpdate?;
@@ -126,7 +126,8 @@ export declare class Room {
126
126
  setOnStateChange(key: string, callback: () => void): void;
127
127
  removeOnStateChange(key: string): void;
128
128
  notifyStateChange(): void;
129
- setOnError(callback: (error: Error) => void): void;
129
+ setOnError(key: string, callback: (error: Error) => void): void;
130
+ clearOnError(key: string): void;
130
131
  private notifyError;
131
132
  getHumanAgents(): Agent[];
132
133
  getDefaultHumanAgent(): Agent | undefined;
@@ -33,7 +33,7 @@ class Room {
33
33
  isPublished = false;
34
34
  isLoading = false;
35
35
  onStateChangeCallbacks = new Map();
36
- onError;
36
+ onErrorCallbacks = new Map();
37
37
  currentSituation = '';
38
38
  currentSituationTime = '';
39
39
  onSituationUpdate;
@@ -861,12 +861,15 @@ Recent Message: ${message.getContent()}
861
861
  callback();
862
862
  }
863
863
  }
864
- setOnError(callback) {
865
- this.onError = callback;
864
+ setOnError(key, callback) {
865
+ this.onErrorCallbacks.set(key, callback);
866
+ }
867
+ clearOnError(key) {
868
+ this.onErrorCallbacks.delete(key);
866
869
  }
867
870
  notifyError(error) {
868
- if (this.onError) {
869
- this.onError(error);
871
+ for (const callback of this.onErrorCallbacks.values()) {
872
+ callback(error);
870
873
  }
871
874
  }
872
875
  getHumanAgents() {
@@ -1,7 +1,7 @@
1
1
  export { Briyah } from './briyah';
2
2
  export { BriyahConfigService, BriyahConfigOptions } from './briyah-config';
3
- export type { AppService } from '../app.service';
4
- export type { AgentInfo, CreateAgentResponse, RoomInfo, RoomDetails, CreateRoomResponse, StoryInfo, CreateStoryResponse, ProcessTextResponse, FileList, PromptFileContent, AttachDocumentResponse, AgentMessagesResponse, RoomMessagesResponse, RoomMessageUpdate, SendMessageResult, StoryState, Message, MessageAction, ModelInfo, ArtifactMetadata, PreparedPromptResponse, PromptScope, PromptFolder, PromptFoldersResponse, PromptFile, PromptFilesResponse, StoryIdea, Transaction, TransactionHistoryResponse, ToolDefinition, ToolParameter, ToolSummary, ToolsResponse, ToolRunResult, StoryStateEvent, StoryIntroduceCharacterEvent, StoryProgressChapterEvent, StoryErrorEvent, Character, ChapterInfo, } from '../../../shared/types/app.types';
3
+ export type { AppService, AgentCreationOptions } from '../app.service';
4
+ export type { AgentInfo, CreateAgentResponse, RoomInfo, RoomDetails, CreateRoomResponse, StoryInfo, CreateStoryResponse, ProcessTextResponse, FileList, PromptFileContent, AttachDocumentResponse, AgentMessagesResponse, RoomMessagesResponse, RoomMessageUpdate, RoomTurnMode, SendMessageResult, StoryState, Message, MessageAction, ModelInfo, ArtifactMetadata, PreparedPromptResponse, PromptScope, PromptFolder, PromptFoldersResponse, PromptFolderDefaults, PromptFolderDefaultsResponse, PromptFile, PromptFilesResponse, StoryIdea, Transaction, TransactionHistoryResponse, ToolDefinition, ToolParameter, ToolSummary, ToolsResponse, ToolRunResult, StoryStateEvent, StoryIntroduceCharacterEvent, StoryProgressChapterEvent, StoryErrorEvent, Character, ChapterInfo, } from '../../../shared/types/app.types';
5
5
  export type { LoggingOptions } from './briyah-config';
6
6
  export type { NativeToolDefinition, ToolHelpers, ToolContext, ToolCaller, ToolArtifact, ToolRoomAccess, ArtifactWriteOptions, } from '../tools/native-tool.types';
7
7
  export { dnd5eTools } from '../tools/packs/dnd5e';
@@ -237,7 +237,7 @@ let StoryService = class StoryService {
237
237
  room.setOnStateChange('story', () => {
238
238
  this.emitStoryStateUpdate(storyId);
239
239
  });
240
- room.setOnError((error) => {
240
+ room.setOnError('story', (error) => {
241
241
  this.handleRoomError(storyId, error);
242
242
  });
243
243
  room.setOnSituationUpdate((situation, latestMessage) => this.updateStorySituation(storyId, situation, latestMessage));
@@ -437,7 +437,7 @@ let StoryService = class StoryService {
437
437
  room.setOnStateChange('story', () => {
438
438
  this.emitStoryStateUpdate(storyInfo.id);
439
439
  });
440
- room.setOnError((error) => {
440
+ room.setOnError('story', (error) => {
441
441
  this.handleRoomError(storyInfo.id, error);
442
442
  });
443
443
  room.setOnSituationUpdate((situation, latestMessage) => this.updateStorySituation(storyInfo.id, situation, latestMessage));
@@ -1 +1 @@
1
- window.hierarchyData = "eJyNkE2LwjAURf/LXUdF+6GT5bhy4UaX0kVoX22YNIG8KIjkv0tQZ4pUnE0CyX3vcO4V3rnAkId5mX2JZV5UAp5aQ3XQzjLkFWWWTqt6gsS31xfVrZ1t9XFP/qxrgsCPtg3kfLESOHkDidooZuLZSHzahd5A3COQCNxM0vzk/hAFlnkxIG6JWR3/KIuifFK0DeRbVRPPHqm3y3+j6bPTpvFkk3WxyqsokO4Bc+dc/8odsRvEPlulggeIzXiH43ab/zX4RrLMqhjjDQeVoZA="
1
+ window.hierarchyData = "eJyNkE2LwjAURf/LXcdxrBolS125mI0upYvQvtpgmkBeZkAk/13ix0wZKrpJILnvHc49I3gfGWo/kctPsZCzUiBQY6mKxjuGOkNO8+l0R1BYBXPS7dq7xhx2FH5MRRA4GldDTYqlwHewUKisZiYeD8Q/2thZiFsECpHrUZ4f3R6SwELOesQvYtaHP0oxlw+KcZFCoyvi8T31dPlvNH+2xtaB3NW6mJdJIN895tb77j93wK4Xe22VC+4hNsMdDttt3mvwiaSclimlC/ouoYI="
@@ -1 +1 @@
1
- window.navigationData = "eJyN2FFvmzAQB/DvwnO1rtXabX3rkk6N1G5R0mkP0x48uBCrYCP7iBpN++4ThIAB+86v3N8/KNhnp7/+JghvmNwlz2CtyOE+RalVcpFUAvfJXQKqLu3lqPhuj2WRXCSvUmXJ3ad/F71xn4PCYWxaCGvBXraXx6Ourt1xX4w8iv184Ok6P3Kh1U7mWzAHmUKIGYUo85tAeYAXrYsN5NKiOc7JeYYSN1qXc6O5yo3qXrx/cFekjPbVr9ROD4JUCGY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