briyah 1.2.5 → 1.2.6

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 (80) hide show
  1. package/README.md +63 -29
  2. package/dist-sdk/server/src/app/user-service-factory.d.ts +3 -1
  3. package/dist-sdk/server/src/app/user-service-factory.js +8 -3
  4. package/dist-sdk/server/src/app.controller.js +18 -5
  5. package/dist-sdk/server/src/app.service.d.ts +5 -2
  6. package/dist-sdk/server/src/app.service.js +22 -2
  7. package/dist-sdk/server/src/room/room.d.ts +2 -1
  8. package/dist-sdk/server/src/room/room.js +20 -3
  9. package/dist-sdk/server/src/sdk/briyah-config.d.ts +3 -0
  10. package/dist-sdk/server/src/sdk/briyah-config.js +4 -0
  11. package/dist-sdk/server/src/sdk/briyah.d.ts +6 -0
  12. package/dist-sdk/server/src/sdk/briyah.js +19 -1
  13. package/dist-sdk/server/src/sdk/index.d.ts +2 -1
  14. package/dist-sdk/server/src/shared/shared.module.js +3 -0
  15. package/dist-sdk/server/src/tools/native-tool-registry.service.d.ts +10 -0
  16. package/dist-sdk/server/src/tools/native-tool-registry.service.js +46 -0
  17. package/dist-sdk/server/src/tools/native-tool.types.d.ts +12 -0
  18. package/dist-sdk/server/src/tools/native-tool.types.js +2 -0
  19. package/dist-sdk/server/src/tools/tool-execution.service.d.ts +12 -8
  20. package/dist-sdk/server/src/tools/tool-execution.service.js +43 -18
  21. package/dist-sdk/shared/types/app.types.d.ts +7 -0
  22. package/docs/assets/hierarchy.js +1 -1
  23. package/docs/assets/navigation.js +1 -1
  24. package/docs/assets/search.js +1 -1
  25. package/docs/classes/Agent.html +15 -15
  26. package/docs/classes/Briyah.html +35 -10
  27. package/docs/classes/BriyahConfigService.html +5 -5
  28. package/docs/classes/Room.html +26 -26
  29. package/docs/classes/RoomMessage.html +10 -10
  30. package/docs/enums/MessageAction.html +3 -3
  31. package/docs/hierarchy.html +1 -1
  32. package/docs/index.html +19 -9
  33. package/docs/interfaces/AgentInfo.html +2 -2
  34. package/docs/interfaces/AgentMessagesResponse.html +2 -2
  35. package/docs/interfaces/AppService.html +156 -147
  36. package/docs/interfaces/Artifact.html +3 -3
  37. package/docs/interfaces/ArtifactMetadata.html +2 -2
  38. package/docs/interfaces/AttachDocumentResponse.html +2 -2
  39. package/docs/interfaces/BriyahConfigOptions.html +16 -8
  40. package/docs/interfaces/ChapterInfo.html +2 -2
  41. package/docs/interfaces/Character.html +2 -2
  42. package/docs/interfaces/CreateAgentResponse.html +2 -2
  43. package/docs/interfaces/CreateRoomResponse.html +2 -2
  44. package/docs/interfaces/CreateStoryResponse.html +2 -2
  45. package/docs/interfaces/FileList.html +2 -2
  46. package/docs/interfaces/FileMetadata.html +3 -3
  47. package/docs/interfaces/IConfigService.html +3 -3
  48. package/docs/interfaces/LoggingOptions.html +6 -6
  49. package/docs/interfaces/Message.html +2 -2
  50. package/docs/interfaces/ModelInfo.html +2 -2
  51. package/docs/interfaces/NativeToolDefinition.html +16 -0
  52. package/docs/interfaces/PreparedPromptResponse.html +2 -2
  53. package/docs/interfaces/ProcessTextResponse.html +2 -2
  54. package/docs/interfaces/PromptFile.html +2 -2
  55. package/docs/interfaces/PromptFileContent.html +2 -2
  56. package/docs/interfaces/PromptFilesResponse.html +2 -2
  57. package/docs/interfaces/PromptFolder.html +2 -2
  58. package/docs/interfaces/PromptFoldersResponse.html +2 -2
  59. package/docs/interfaces/RoomDetails.html +2 -2
  60. package/docs/interfaces/RoomInfo.html +2 -2
  61. package/docs/interfaces/RoomMessagesResponse.html +2 -2
  62. package/docs/interfaces/StoryErrorEvent.html +3 -3
  63. package/docs/interfaces/StoryIdea.html +2 -2
  64. package/docs/interfaces/StoryInfo.html +3 -3
  65. package/docs/interfaces/StoryIntroduceCharacterEvent.html +3 -3
  66. package/docs/interfaces/StoryProgressChapterEvent.html +3 -3
  67. package/docs/interfaces/StoryState.html +5 -5
  68. package/docs/interfaces/StoryStateEvent.html +3 -3
  69. package/docs/interfaces/ToolDefinition.html +2 -2
  70. package/docs/interfaces/ToolHelpers.html +7 -0
  71. package/docs/interfaces/ToolParameter.html +2 -2
  72. package/docs/interfaces/ToolSummary.html +4 -0
  73. package/docs/interfaces/ToolsResponse.html +4 -2
  74. package/docs/interfaces/Transaction.html +2 -2
  75. package/docs/interfaces/TransactionHistoryResponse.html +2 -2
  76. package/docs/modules.html +1 -1
  77. package/docs/types/PromptScope.html +1 -1
  78. package/docs/types/ToolContext.html +6 -0
  79. package/docs/types/ToolRunResult.html +1 -1
  80. package/package.json +1 -1
package/README.md CHANGED
@@ -6,7 +6,10 @@ What's in the package:
6
6
 
7
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
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.** User-defined functions agents can call from a room. A tool is a named async JavaScript function body with declared parameters that returns a JSON value; `helpers.fetch` is available for HTTP requests. Tools are granted per agent, and an agent may chain several tool calls privately before responding. Tool code runs in-process on the server with a timeout — only define tools you trust.
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.
10
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.
11
14
  - **Text processing.** One-shot `processText` for non-conversational use, with cost and token counts on the result.
12
15
  - **File attachments.** Attach documents to agents as context. Supported file types vary by LLM provider.
@@ -88,6 +91,18 @@ interface BriyahConfigOptions {
88
91
  */
89
92
  startingBalance?: number;
90
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
+
91
106
  /**
92
107
  * Override environment variables
93
108
  * Useful for testing or multi-instance configurations
@@ -111,6 +126,7 @@ interface BriyahConfigOptions {
111
126
  - `STARTING_BALANCE` - Starting balance for new users (e.g., "10.00")
112
127
  - `BRIYAH_DATA_PATH` - Global default data path (overridden by constructor `dataPath`)
113
128
  - `USER_SERVICE_CACHE_TIMEOUT_MINUTES` - Cache timeout (overridden by constructor option)
129
+ - `ALLOW_USER_AUTHORED_TOOLS` - `"true"` to let users author/run their own tools (overridden by the `allowUserAuthoredTools` option). Default off.
114
130
 
115
131
  ### Logging
116
132
 
@@ -228,7 +244,11 @@ const room = await appService.createRoom(name, goal, agentIds);
228
244
  const rooms = await appService.listRooms();
229
245
  await appService.sendRoomMessage(roomId, content, sender, action?);
230
246
 
231
- // Tool Management
247
+ // Native tools (recommended for SDK integrations — see Example 8)
248
+ briyah.registerTool({ name, description, parameters, handler }); // process-level
249
+ briyah.listNativeTools();
250
+
251
+ // User-authored (string-code) tools — only when allowUserAuthoredTools is enabled
232
252
  const tools = await appService.listTools();
233
253
  const tool = await appService.createTool({ name, description, parameters, code, timeoutMs? });
234
254
  await appService.updateTool(name, tool);
@@ -485,45 +505,59 @@ emitter.on('update', (newBalance: number) => {
485
505
  });
486
506
  ```
487
507
 
488
- ### Example 8: Giving Agents Tools
508
+ ### Example 8: Registering Native Tools with Opaque Context
509
+
510
+ 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.
489
511
 
490
- Tools let a room agent fetch or compute data mid-conversation. Define the tool once, grant it to specific agents, and the agent invokes it on its own (via the EXECUTE room action) when a conversation calls for it. The result is returned privately to the calling agent, which may chain several calls before speaking.
512
+ 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.
491
513
 
492
514
  ```typescript
493
- const app = briyah.getAppService('user-123');
515
+ import { Briyah } from 'briyah';
516
+
517
+ const briyah = new Briyah({ dataPath: './data/briyah', startingBalance: 10.00 });
518
+ await briyah.init();
494
519
 
495
- // 1. Define a tool. `code` is the body of an async function receiving
496
- // (args, helpers) and returning a JSON-serializable value.
497
- await app.createTool({
498
- name: 'weather_lookup',
499
- description: 'Gets the current temperature for a city',
520
+ // Register a tool that reads its scope from context, not from the LLM's args.
521
+ briyah.registerTool({
522
+ name: 'add_note',
523
+ description: "Add a note to the record the user currently has open",
500
524
  parameters: [
501
- { name: 'city', type: 'string', description: 'City name', required: true }
525
+ { name: 'text', type: 'string', description: 'The note text', required: true }
502
526
  ],
503
- code: `
504
- const res = await helpers.fetch('https://wttr.in/' + encodeURIComponent(args.city) + '?format=j1');
505
- const data = await res.json();
506
- return { tempC: data.current_condition[0].temp_C };
507
- `,
527
+ handler: async (args, helpers, context) => {
528
+ const { db, recordId } = context as { db: MyDb; recordId: string };
529
+ await db.addNote(recordId, args.text); // recordId comes from context — the LLM cannot set it
530
+ return { added: true };
531
+ },
508
532
  timeoutMs: 15000 // optional; default 30s, max 120s
509
533
  });
510
534
 
511
- // 2. Test it before any agent uses it
512
- const test = await app.testTool('weather_lookup', { city: 'Paris' });
513
- if (!test.ok) throw new Error(test.error);
535
+ // Grant it to an agent (grants are enforced server-side).
536
+ const assistant = app.createAgent('Anthropic', 'Assistant', 'Assistant',
537
+ 'A helpful assistant that manages the open record', 'claude-haiku-4-5');
538
+ assistant.toolNames = ['add_note'];
539
+ assistant.save();
540
+
541
+ // When the user acts on record "rec_42", pass that scope as context. Any tool the
542
+ // agent calls during the resulting turn receives it; other rooms/interactions are
543
+ // unaffected. A log-only 'tool' message records each call (visible when fetching
544
+ // messages with includeThoughts=true).
545
+ await app.sendRoomMessage(
546
+ roomId,
547
+ 'Add a note that the client called about renewal.',
548
+ 'User',
549
+ 'speak',
550
+ [],
551
+ false,
552
+ { db, recordId: 'rec_42' } // opaque context
553
+ );
554
+ ```
514
555
 
515
- // 3. Grant it to an agent (grants are enforced server-side)
516
- const researcher = app.createAgent('Anthropic', 'Researcher', 'Researcher',
517
- 'A researcher who uses tools for exact answers', 'claude-haiku-4-5');
518
- researcher.toolNames = ['weather_lookup'];
519
- researcher.save();
556
+ 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.
520
557
 
521
- // 4. In a room, the agent calls the tool on its own when a question needs it.
522
- // Other agents wait while it researches; a log-only 'tool' message records
523
- // each call (visible when fetching messages with includeThoughts=true).
524
- ```
558
+ 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.
525
559
 
526
- Agents can also delegate: an agent may respond with a `commission` action naming other agents, each of which researches independently (using its own tools) 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.
560
+ User-authored (string-code) tools remain available via `createTool`/`updateTool`/`testTool` when `allowUserAuthoredTools` is enabled, for trusted single-user setups.
527
561
 
528
562
  ## Data Storage
529
563
 
@@ -8,6 +8,7 @@ import { StoryMessageService } from '../story/story-message.service';
8
8
  import { PublishedAgentsService } from '../ai/published-agents.service';
9
9
  import { PublishedRoomsService } from '../room/published-rooms.service';
10
10
  import { BalanceMessageService } from './balance-message.service';
11
+ import { NativeToolRegistry } from '../tools/native-tool-registry.service';
11
12
  export declare class UserServiceFactory {
12
13
  private readonly aiFactoryService;
13
14
  private readonly agentMessageService;
@@ -18,6 +19,7 @@ export declare class UserServiceFactory {
18
19
  private readonly publishedRoomsService;
19
20
  private readonly balanceMessageService;
20
21
  private readonly configService;
21
- constructor(aiFactoryService: AiFactoryService, agentMessageService: AgentMessageService, roomMessageService: RoomMessageService, storyProgressService: StoryProgressService, storyMessageService: StoryMessageService, publishedAgentsService: PublishedAgentsService, publishedRoomsService: PublishedRoomsService, balanceMessageService: BalanceMessageService, configService: ConfigService);
22
+ private readonly nativeToolRegistry;
23
+ constructor(aiFactoryService: AiFactoryService, agentMessageService: AgentMessageService, roomMessageService: RoomMessageService, storyProgressService: StoryProgressService, storyMessageService: StoryMessageService, publishedAgentsService: PublishedAgentsService, publishedRoomsService: PublishedRoomsService, balanceMessageService: BalanceMessageService, configService: ConfigService, nativeToolRegistry: NativeToolRegistry);
22
24
  createAppService(userId: string): AppService;
23
25
  }
@@ -35,6 +35,7 @@ const agent_factory_1 = require("../ai/agent-factory");
35
35
  const room_factory_1 = require("../room/room-factory");
36
36
  const tool_store_service_1 = require("../tools/tool-store.service");
37
37
  const tool_execution_service_1 = require("../tools/tool-execution.service");
38
+ const native_tool_registry_service_1 = require("../tools/native-tool-registry.service");
38
39
  let UserServiceFactory = class UserServiceFactory {
39
40
  aiFactoryService;
40
41
  agentMessageService;
@@ -45,7 +46,8 @@ let UserServiceFactory = class UserServiceFactory {
45
46
  publishedRoomsService;
46
47
  balanceMessageService;
47
48
  configService;
48
- constructor(aiFactoryService, agentMessageService, roomMessageService, storyProgressService, storyMessageService, publishedAgentsService, publishedRoomsService, balanceMessageService, configService) {
49
+ nativeToolRegistry;
50
+ constructor(aiFactoryService, agentMessageService, roomMessageService, storyProgressService, storyMessageService, publishedAgentsService, publishedRoomsService, balanceMessageService, configService, nativeToolRegistry) {
49
51
  this.aiFactoryService = aiFactoryService;
50
52
  this.agentMessageService = agentMessageService;
51
53
  this.roomMessageService = roomMessageService;
@@ -55,6 +57,7 @@ let UserServiceFactory = class UserServiceFactory {
55
57
  this.publishedRoomsService = publishedRoomsService;
56
58
  this.balanceMessageService = balanceMessageService;
57
59
  this.configService = configService;
60
+ this.nativeToolRegistry = nativeToolRegistry;
58
61
  }
59
62
  createAppService(userId) {
60
63
  const userPaths = new user_paths_service_1.UserPathsService(userId);
@@ -66,7 +69,8 @@ let UserServiceFactory = class UserServiceFactory {
66
69
  const agentFactory = new agent_factory_1.AgentFactory(this.aiFactoryService, agentStore, userPaths, balanceService, artifactService, this.configService);
67
70
  const artifactStore = new artifact_store_service_1.ArtifactStoreService();
68
71
  const toolStore = new tool_store_service_1.ToolStoreService(userPaths);
69
- const toolExecution = new tool_execution_service_1.ToolExecutionService(toolStore);
72
+ const allowUserAuthoredTools = String(this.configService.get('ALLOW_USER_AUTHORED_TOOLS')).toLowerCase() === 'true';
73
+ const toolExecution = new tool_execution_service_1.ToolExecutionService(toolStore, this.nativeToolRegistry, allowUserAuthoredTools);
70
74
  const roomStore = new room_store_service_1.RoomStoreService(userPaths, agentStore, attachedFileService, artifactStore, toolStore, toolExecution);
71
75
  const roomFactory = new room_factory_1.RoomFactory(roomStore, toolStore, toolExecution);
72
76
  const storyStore = new story_store_service_1.StoryStoreService(userPaths, roomStore);
@@ -85,5 +89,6 @@ exports.UserServiceFactory = UserServiceFactory = __decorate([
85
89
  published_agents_service_1.PublishedAgentsService,
86
90
  published_rooms_service_1.PublishedRoomsService,
87
91
  balance_message_service_1.BalanceMessageService,
88
- config_1.ConfigService])
92
+ config_1.ConfigService,
93
+ native_tool_registry_service_1.NativeToolRegistry])
89
94
  ], UserServiceFactory);
@@ -365,19 +365,26 @@ let AppController = class AppController {
365
365
  async getTools(req) {
366
366
  try {
367
367
  const appService = this.getAppService(req);
368
- return { tools: await appService.listTools() };
368
+ return {
369
+ tools: await appService.listTools(),
370
+ nativeTools: appService.listNativeToolSummaries(),
371
+ allowUserAuthored: appService.userAuthoredToolsEnabled,
372
+ };
369
373
  }
370
374
  catch (error) {
371
375
  logger_1.logger.error(`[${req.user?.sub}] Error listing tools:`, error);
372
- return { tools: [] };
376
+ return { tools: [], nativeTools: [], allowUserAuthored: false };
373
377
  }
374
378
  }
375
379
  async createTool(req, body) {
376
380
  if (!body.name) {
377
381
  throw new common_1.BadRequestException('Tool name is required');
378
382
  }
383
+ const appService = this.getAppService(req);
384
+ if (!appService.userAuthoredToolsEnabled) {
385
+ throw new common_1.ForbiddenException('User-authored tools are disabled on this deployment');
386
+ }
379
387
  try {
380
- const appService = this.getAppService(req);
381
388
  return await appService.createTool(body);
382
389
  }
383
390
  catch (error) {
@@ -389,8 +396,11 @@ let AppController = class AppController {
389
396
  }
390
397
  }
391
398
  async updateTool(req, name, body) {
399
+ const appService = this.getAppService(req);
400
+ if (!appService.userAuthoredToolsEnabled) {
401
+ throw new common_1.ForbiddenException('User-authored tools are disabled on this deployment');
402
+ }
392
403
  try {
393
- const appService = this.getAppService(req);
394
404
  return await appService.updateTool(name, body);
395
405
  }
396
406
  catch (error) {
@@ -402,8 +412,11 @@ let AppController = class AppController {
402
412
  }
403
413
  }
404
414
  async deleteTool(req, name) {
415
+ const appService = this.getAppService(req);
416
+ if (!appService.userAuthoredToolsEnabled) {
417
+ throw new common_1.ForbiddenException('User-authored tools are disabled on this deployment');
418
+ }
405
419
  try {
406
- const appService = this.getAppService(req);
407
420
  await appService.deleteTool(name);
408
421
  }
409
422
  catch (error) {
@@ -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, CreateRoomResponse, FileList, PromptFileContent, PromptFoldersResponse, PromptFilesResponse, PromptScope, ProcessTextResponse, PreparedPromptResponse, AttachDocumentResponse, AgentMessagesResponse, RoomMessagesResponse, StoryInfo, StoryState, Character, Transaction, TransactionHistoryResponse, ToolDefinition, ToolRunResult } from '../../shared/types/app.types';
24
+ import { AgentInfo, RoomInfo, RoomDetails, CreateRoomResponse, FileList, PromptFileContent, PromptFoldersResponse, PromptFilesResponse, PromptScope, ProcessTextResponse, PreparedPromptResponse, AttachDocumentResponse, AgentMessagesResponse, RoomMessagesResponse, 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';
@@ -73,7 +73,7 @@ export declare class AppService {
73
73
  getRoomMessages(roomId: string, fromIndex?: number, includeThoughts?: boolean): Promise<RoomMessagesResponse>;
74
74
  getAgentMessages(agentId: string, fromIndex?: number): Promise<AgentMessagesResponse>;
75
75
  getStoryMessages(storyId: string, fromIndex: number): Promise<RoomMessagesResponse>;
76
- sendRoomMessage(roomId: string, content: string, sender: string, action?: string, targets?: string[], clearQueue?: boolean): Promise<void>;
76
+ sendRoomMessage(roomId: string, content: string, sender: string, action?: string, targets?: string[], clearQueue?: boolean, context?: unknown): Promise<void>;
77
77
  pauseRoom(roomId: string): Promise<void>;
78
78
  resumeRoom(roomId: string): Promise<void>;
79
79
  deleteAgent(agentId: string): Promise<void>;
@@ -113,10 +113,13 @@ export declare class AppService {
113
113
  beginInstruction?: string;
114
114
  toolNames?: string[];
115
115
  }): Promise<void>;
116
+ get userAuthoredToolsEnabled(): boolean;
116
117
  listTools(): Promise<ToolDefinition[]>;
118
+ listNativeToolSummaries(): ToolSummary[];
117
119
  createTool(tool: ToolDefinition): Promise<ToolDefinition>;
118
120
  updateTool(name: string, tool: ToolDefinition): Promise<ToolDefinition>;
119
121
  deleteTool(name: string): Promise<void>;
122
+ private assertUserAuthoringAllowed;
120
123
  testTool(name: string, args: Record<string, any>): Promise<ToolRunResult>;
121
124
  listAttachedFiles(agentId: string): Promise<FileList>;
122
125
  deleteAttachedFile(agentId: string, fileName: string): Promise<void>;
@@ -463,7 +463,7 @@ class AppService {
463
463
  const totalCost = story.totalCost || 0;
464
464
  return { messages, totalCost };
465
465
  }
466
- async sendRoomMessage(roomId, content, sender, action = 'moderate', targets = [], clearQueue = false) {
466
+ async sendRoomMessage(roomId, content, sender, action = 'moderate', targets = [], clearQueue = false, context) {
467
467
  const room = await this.roomStore.getRoom(roomId);
468
468
  if (!room) {
469
469
  throw new errors_1.NotFoundError('Room not found');
@@ -486,7 +486,7 @@ class AppService {
486
486
  messageAction = app_types_1.MessageAction.SPEAK;
487
487
  }
488
488
  room.ready();
489
- room.addPendingMessage(new message_1.RoomMessage(sender, messageAction, content, targets), clearQueue);
489
+ room.addPendingMessage(new message_1.RoomMessage(sender, messageAction, content, targets), clearQueue, context);
490
490
  }
491
491
  async pauseRoom(roomId) {
492
492
  const room = await this.roomStore.getRoom(roomId);
@@ -838,10 +838,23 @@ class AppService {
838
838
  agent.toolNames = updates.toolNames;
839
839
  agent.save();
840
840
  }
841
+ get userAuthoredToolsEnabled() {
842
+ return this.toolExecution.userAuthoredToolsEnabled;
843
+ }
841
844
  async listTools() {
845
+ if (!this.userAuthoredToolsEnabled)
846
+ return [];
842
847
  return this.toolStore.listTools();
843
848
  }
849
+ listNativeToolSummaries() {
850
+ return this.toolExecution.listNativeTools().map((t) => ({
851
+ name: t.name,
852
+ description: t.description,
853
+ parameters: t.parameters || [],
854
+ }));
855
+ }
844
856
  async createTool(tool) {
857
+ this.assertUserAuthoringAllowed();
845
858
  const existing = await this.toolStore.getTool(tool.name);
846
859
  if (existing) {
847
860
  throw new errors_1.OperationFailedError(`Tool "${tool.name}" already exists`);
@@ -849,6 +862,7 @@ class AppService {
849
862
  return this.toolStore.saveTool(tool);
850
863
  }
851
864
  async updateTool(name, tool) {
865
+ this.assertUserAuthoringAllowed();
852
866
  const existing = await this.toolStore.getTool(name);
853
867
  if (!existing) {
854
868
  throw new errors_1.NotFoundError(`Tool "${name}" not found`);
@@ -856,11 +870,17 @@ class AppService {
856
870
  return this.toolStore.saveTool({ ...tool, name });
857
871
  }
858
872
  async deleteTool(name) {
873
+ this.assertUserAuthoringAllowed();
859
874
  const deleted = await this.toolStore.deleteTool(name);
860
875
  if (!deleted) {
861
876
  throw new errors_1.NotFoundError(`Tool "${name}" not found`);
862
877
  }
863
878
  }
879
+ assertUserAuthoringAllowed() {
880
+ if (!this.userAuthoredToolsEnabled) {
881
+ throw new errors_1.OperationFailedError('User-authored tools are disabled on this deployment');
882
+ }
883
+ }
864
884
  async testTool(name, args) {
865
885
  return this.toolExecution.test(name, args);
866
886
  }
@@ -33,6 +33,7 @@ export declare class Room {
33
33
  private roomStoreService;
34
34
  private toolStoreService?;
35
35
  private toolExecutionService?;
36
+ private currentToolContext;
36
37
  constructor(id: string | null, name: string, goal: string, baseRoomDir?: string, storageDir?: string, roomStoreService?: any);
37
38
  deleteRoom(): void;
38
39
  setLoading(isLoading: boolean): void;
@@ -119,7 +120,7 @@ export declare class Room {
119
120
  private handleSituationUpdate;
120
121
  handlePublishMessages(messages: RoomMessage[]): void;
121
122
  handleAdjournMessages(messages: RoomMessage[]): void;
122
- addPendingMessage(message: RoomMessage, clearQueue?: boolean): void;
123
+ addPendingMessage(message: RoomMessage, clearQueue?: boolean, context?: unknown): void;
123
124
  isProcessingInProgress(): boolean;
124
125
  pause(): void;
125
126
  resume(): void;
@@ -36,6 +36,7 @@ class Room {
36
36
  roomStoreService;
37
37
  toolStoreService;
38
38
  toolExecutionService;
39
+ currentToolContext = undefined;
39
40
  constructor(id, name, goal, baseRoomDir = '', storageDir = '', roomStoreService = null) {
40
41
  this.name = name;
41
42
  this.goal = goal;
@@ -317,11 +318,24 @@ class Room {
317
318
  .join('\n\n');
318
319
  }
319
320
  async buildAvailableTools(agent) {
320
- if (!this.toolStoreService || !agent.toolNames || agent.toolNames.length === 0) {
321
+ if (!agent.toolNames || agent.toolNames.length === 0) {
321
322
  return [];
322
323
  }
324
+ const nativeByName = new Map((this.toolExecutionService?.listNativeTools() || []).map((t) => [t.name, t]));
323
325
  const tools = [];
324
326
  for (const name of agent.toolNames) {
327
+ const native = nativeByName.get(name);
328
+ if (native) {
329
+ tools.push({
330
+ name: native.name,
331
+ description: native.description,
332
+ parameters: native.parameters || [],
333
+ });
334
+ continue;
335
+ }
336
+ if (!this.toolStoreService || !this.toolExecutionService?.userAuthoredToolsEnabled) {
337
+ continue;
338
+ }
325
339
  const tool = await this.toolStoreService.getTool(name);
326
340
  if (tool) {
327
341
  tools.push({
@@ -436,7 +450,7 @@ class Room {
436
450
  async executeToolForAgent(agent, message) {
437
451
  const toolName = message.name;
438
452
  const result = this.toolExecutionService
439
- ? await this.toolExecutionService.runForAgent(toolName, message.content, agent.toolNames || [])
453
+ ? await this.toolExecutionService.runForAgent(toolName, message.content, agent.toolNames || [], this.currentToolContext)
440
454
  : { ok: false, error: 'Tool execution is not available in this room' };
441
455
  const argsPreview = message.content && message.content.length > 200
442
456
  ? `${message.content.slice(0, 200)}...`
@@ -720,7 +734,10 @@ Recent Message: ${message.getContent()}
720
734
  this.addRoomMessage(messages[0]);
721
735
  }
722
736
  }
723
- addPendingMessage(message, clearQueue = false) {
737
+ addPendingMessage(message, clearQueue = false, context) {
738
+ if (context !== undefined) {
739
+ this.currentToolContext = context;
740
+ }
724
741
  if (!this.pendingMessages) {
725
742
  this.pendingMessages = [];
726
743
  }
@@ -1,4 +1,5 @@
1
1
  import { IConfigService } from '../config/env-config';
2
+ import { NativeToolDefinition } from '../tools/native-tool.types';
2
3
  export interface LoggingOptions {
3
4
  enabled?: boolean;
4
5
  logFile?: string;
@@ -13,6 +14,8 @@ export interface BriyahConfigOptions {
13
14
  markupRate?: number;
14
15
  envOverrides?: Record<string, string>;
15
16
  logging?: LoggingOptions;
17
+ tools?: NativeToolDefinition[];
18
+ allowUserAuthoredTools?: boolean;
16
19
  }
17
20
  export declare class BriyahConfigService implements IConfigService {
18
21
  private env;
@@ -27,6 +27,10 @@ class BriyahConfigService {
27
27
  this.env.AI_DEBUG = 'true';
28
28
  process.env.AI_DEBUG = 'true';
29
29
  }
30
+ if (options?.allowUserAuthoredTools !== undefined) {
31
+ this.env.ALLOW_USER_AUTHORED_TOOLS = String(options.allowUserAuthoredTools);
32
+ process.env.ALLOW_USER_AUTHORED_TOOLS = String(options.allowUserAuthoredTools);
33
+ }
30
34
  }
31
35
  get(key, defaultValue) {
32
36
  const value = this.env[key];
@@ -2,6 +2,7 @@ import { AiFactoryService } from '../ai/ai-factory.service';
2
2
  import { PublishedAgentsService } from '../ai/published-agents.service';
3
3
  import { BriyahConfigService, BriyahConfigOptions } from './briyah-config';
4
4
  import { AppService } from '../app.service';
5
+ import { NativeToolDefinition } from '../tools/native-tool.types';
5
6
  export declare class Briyah {
6
7
  private configService;
7
8
  private aiFactoryService;
@@ -14,6 +15,7 @@ export declare class Briyah {
14
15
  private balanceMessageService;
15
16
  private userServiceFactory;
16
17
  private userServiceManager;
18
+ private nativeToolRegistry;
17
19
  private initialized;
18
20
  constructor(options?: BriyahConfigOptions);
19
21
  private validateEnvironment;
@@ -32,6 +34,10 @@ export declare class Briyah {
32
34
  };
33
35
  shutdown(): Promise<void>;
34
36
  isInitialized(): boolean;
37
+ registerTool(def: NativeToolDefinition): void;
38
+ registerTools(defs: NativeToolDefinition[]): void;
39
+ unregisterTool(name: string): boolean;
40
+ listNativeTools(): NativeToolDefinition[];
35
41
  getConfigService(): BriyahConfigService;
36
42
  getAiFactoryService(): AiFactoryService;
37
43
  getPublishedAgentsService(): PublishedAgentsService;
@@ -56,6 +56,7 @@ const user_service_manager_1 = require("../app/user-service-manager");
56
56
  const user_service_factory_1 = require("../app/user-service-factory");
57
57
  const briyah_config_1 = require("./briyah-config");
58
58
  const fal_service_1 = require("../ai/LLM/fal.service");
59
+ const native_tool_registry_service_1 = require("../tools/native-tool-registry.service");
59
60
  class Briyah {
60
61
  configService;
61
62
  aiFactoryService;
@@ -68,6 +69,7 @@ class Briyah {
68
69
  balanceMessageService;
69
70
  userServiceFactory;
70
71
  userServiceManager;
72
+ nativeToolRegistry;
71
73
  initialized = false;
72
74
  constructor(options) {
73
75
  this.configService = new briyah_config_1.BriyahConfigService(options);
@@ -80,6 +82,9 @@ class Briyah {
80
82
  });
81
83
  this.validateEnvironment();
82
84
  this.initializeSingletons(options?.dataPath);
85
+ if (options?.tools && options.tools.length > 0) {
86
+ this.nativeToolRegistry.registerTools(options.tools);
87
+ }
83
88
  }
84
89
  validateEnvironment() {
85
90
  const hasAnyProvider = this.configService.get('ANTHROPIC_API_KEY') ||
@@ -115,7 +120,8 @@ class Briyah {
115
120
  this.balanceMessageService = new balance_message_service_1.BalanceMessageService();
116
121
  this.publishedAgentsService = new published_agents_service_1.PublishedAgentsService();
117
122
  this.publishedRoomsService = new published_rooms_service_1.PublishedRoomsService();
118
- this.userServiceFactory = new user_service_factory_1.UserServiceFactory(this.aiFactoryService, this.agentMessageService, this.roomMessageService, this.storyProgressService, this.storyMessageService, this.publishedAgentsService, this.publishedRoomsService, this.balanceMessageService, this.configService);
123
+ this.nativeToolRegistry = new native_tool_registry_service_1.NativeToolRegistry();
124
+ this.userServiceFactory = new user_service_factory_1.UserServiceFactory(this.aiFactoryService, this.agentMessageService, this.roomMessageService, this.storyProgressService, this.storyMessageService, this.publishedAgentsService, this.publishedRoomsService, this.balanceMessageService, this.configService, this.nativeToolRegistry);
119
125
  this.userServiceManager = new user_service_manager_1.UserServiceManager(this.userServiceFactory, this.configService);
120
126
  }
121
127
  async init() {
@@ -179,6 +185,18 @@ class Briyah {
179
185
  isInitialized() {
180
186
  return this.initialized;
181
187
  }
188
+ registerTool(def) {
189
+ this.nativeToolRegistry.registerTool(def);
190
+ }
191
+ registerTools(defs) {
192
+ this.nativeToolRegistry.registerTools(defs);
193
+ }
194
+ unregisterTool(name) {
195
+ return this.nativeToolRegistry.unregisterTool(name);
196
+ }
197
+ listNativeTools() {
198
+ return this.nativeToolRegistry.listTools();
199
+ }
182
200
  getConfigService() {
183
201
  return this.configService;
184
202
  }
@@ -1,8 +1,9 @@
1
1
  export { Briyah } from './briyah';
2
2
  export { BriyahConfigService, BriyahConfigOptions } from './briyah-config';
3
3
  export type { AppService } from '../app.service';
4
- export type { AgentInfo, CreateAgentResponse, RoomInfo, RoomDetails, CreateRoomResponse, StoryInfo, CreateStoryResponse, ProcessTextResponse, FileList, PromptFileContent, AttachDocumentResponse, AgentMessagesResponse, RoomMessagesResponse, StoryState, Message, MessageAction, ModelInfo, ArtifactMetadata, PreparedPromptResponse, PromptScope, PromptFolder, PromptFoldersResponse, PromptFile, PromptFilesResponse, StoryIdea, Transaction, TransactionHistoryResponse, ToolDefinition, ToolParameter, ToolsResponse, ToolRunResult, StoryStateEvent, StoryIntroduceCharacterEvent, StoryProgressChapterEvent, StoryErrorEvent, Character, ChapterInfo, } from '../../../shared/types/app.types';
4
+ export type { AgentInfo, CreateAgentResponse, RoomInfo, RoomDetails, CreateRoomResponse, StoryInfo, CreateStoryResponse, ProcessTextResponse, FileList, PromptFileContent, AttachDocumentResponse, AgentMessagesResponse, RoomMessagesResponse, 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';
5
5
  export type { LoggingOptions } from './briyah-config';
6
+ export type { NativeToolDefinition, ToolHelpers, ToolContext } from '../tools/native-tool.types';
6
7
  export { Agent } from '../ai/agent';
7
8
  export { Room } from '../room/room';
8
9
  export { RoomMessage } from '../room/message';
@@ -12,6 +12,7 @@ const published_agents_service_1 = require("../ai/published-agents.service");
12
12
  const published_rooms_service_1 = require("../room/published-rooms.service");
13
13
  const user_service_manager_1 = require("../app/user-service-manager");
14
14
  const user_service_factory_1 = require("../app/user-service-factory");
15
+ const native_tool_registry_service_1 = require("../tools/native-tool-registry.service");
15
16
  const ai_factory_module_1 = require("../ai/ai-factory.module");
16
17
  const agent_store_module_1 = require("../ai/agent-store.module");
17
18
  const room_message_module_1 = require("../room/room-message.module");
@@ -37,6 +38,7 @@ exports.SharedModule = SharedModule = __decorate([
37
38
  user_service_manager_1.UserServiceManager,
38
39
  user_service_factory_1.UserServiceFactory,
39
40
  library_service_1.LibraryService,
41
+ native_tool_registry_service_1.NativeToolRegistry,
40
42
  ],
41
43
  exports: [
42
44
  published_agents_service_1.PublishedAgentsService,
@@ -44,6 +46,7 @@ exports.SharedModule = SharedModule = __decorate([
44
46
  user_service_manager_1.UserServiceManager,
45
47
  user_service_factory_1.UserServiceFactory,
46
48
  library_service_1.LibraryService,
49
+ native_tool_registry_service_1.NativeToolRegistry,
47
50
  ],
48
51
  })
49
52
  ], SharedModule);
@@ -0,0 +1,10 @@
1
+ import { NativeToolDefinition } from './native-tool.types';
2
+ export declare class NativeToolRegistry {
3
+ private tools;
4
+ registerTool(def: NativeToolDefinition): void;
5
+ registerTools(defs: NativeToolDefinition[]): void;
6
+ unregisterTool(name: string): boolean;
7
+ getTool(name: string): NativeToolDefinition | undefined;
8
+ has(name: string): boolean;
9
+ listTools(): NativeToolDefinition[];
10
+ }
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.NativeToolRegistry = void 0;
10
+ const common_1 = require("@nestjs/common");
11
+ const logger_1 = require("../common/logger");
12
+ let NativeToolRegistry = class NativeToolRegistry {
13
+ tools = new Map();
14
+ registerTool(def) {
15
+ if (!def.name || !/^[a-zA-Z0-9_-]+$/.test(def.name)) {
16
+ throw new Error(`Invalid native tool name "${def.name}": use only letters, numbers, hyphens and underscores`);
17
+ }
18
+ if (typeof def.handler !== 'function') {
19
+ throw new Error(`Native tool "${def.name}" must have a handler function`);
20
+ }
21
+ if (this.tools.has(def.name)) {
22
+ logger_1.logger.warn(`Native tool "${def.name}" is already registered; overwriting`);
23
+ }
24
+ this.tools.set(def.name, def);
25
+ }
26
+ registerTools(defs) {
27
+ for (const def of defs)
28
+ this.registerTool(def);
29
+ }
30
+ unregisterTool(name) {
31
+ return this.tools.delete(name);
32
+ }
33
+ getTool(name) {
34
+ return this.tools.get(name);
35
+ }
36
+ has(name) {
37
+ return this.tools.has(name);
38
+ }
39
+ listTools() {
40
+ return [...this.tools.values()];
41
+ }
42
+ };
43
+ exports.NativeToolRegistry = NativeToolRegistry;
44
+ exports.NativeToolRegistry = NativeToolRegistry = __decorate([
45
+ (0, common_1.Injectable)()
46
+ ], NativeToolRegistry);