briyah 1.2.5 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +63 -29
- package/dist-sdk/server/src/app/user-service-factory.d.ts +3 -1
- package/dist-sdk/server/src/app/user-service-factory.js +8 -3
- package/dist-sdk/server/src/app.controller.js +18 -5
- package/dist-sdk/server/src/app.service.d.ts +6 -2
- package/dist-sdk/server/src/app.service.js +31 -2
- package/dist-sdk/server/src/room/room.d.ts +4 -1
- package/dist-sdk/server/src/room/room.js +38 -5
- package/dist-sdk/server/src/sdk/briyah-config.d.ts +3 -0
- package/dist-sdk/server/src/sdk/briyah-config.js +4 -0
- package/dist-sdk/server/src/sdk/briyah.d.ts +6 -0
- package/dist-sdk/server/src/sdk/briyah.js +21 -1
- package/dist-sdk/server/src/sdk/index.d.ts +2 -1
- package/dist-sdk/server/src/shared/shared.module.js +3 -0
- package/dist-sdk/server/src/tools/native-tool-registry.service.d.ts +10 -0
- package/dist-sdk/server/src/tools/native-tool-registry.service.js +46 -0
- package/dist-sdk/server/src/tools/native-tool.types.d.ts +12 -0
- package/dist-sdk/server/src/tools/native-tool.types.js +2 -0
- package/dist-sdk/server/src/tools/tool-execution.service.d.ts +12 -8
- package/dist-sdk/server/src/tools/tool-execution.service.js +43 -18
- package/dist-sdk/shared/types/app.types.d.ts +12 -0
- package/docs/assets/hierarchy.js +1 -1
- package/docs/assets/navigation.js +1 -1
- package/docs/assets/search.js +1 -1
- package/docs/classes/Agent.html +15 -15
- package/docs/classes/Briyah.html +35 -10
- package/docs/classes/BriyahConfigService.html +5 -5
- package/docs/classes/Room.html +33 -26
- package/docs/classes/RoomMessage.html +10 -10
- package/docs/enums/MessageAction.html +3 -3
- package/docs/hierarchy.html +1 -1
- package/docs/index.html +19 -9
- package/docs/interfaces/AgentInfo.html +2 -2
- package/docs/interfaces/AgentMessagesResponse.html +2 -2
- package/docs/interfaces/AppService.html +166 -148
- package/docs/interfaces/Artifact.html +3 -3
- package/docs/interfaces/ArtifactMetadata.html +2 -2
- package/docs/interfaces/AttachDocumentResponse.html +2 -2
- package/docs/interfaces/BriyahConfigOptions.html +16 -8
- package/docs/interfaces/ChapterInfo.html +2 -2
- package/docs/interfaces/Character.html +2 -2
- package/docs/interfaces/CreateAgentResponse.html +2 -2
- package/docs/interfaces/CreateRoomResponse.html +2 -2
- package/docs/interfaces/CreateStoryResponse.html +2 -2
- package/docs/interfaces/FileList.html +2 -2
- package/docs/interfaces/FileMetadata.html +3 -3
- package/docs/interfaces/IConfigService.html +3 -3
- package/docs/interfaces/LoggingOptions.html +6 -6
- package/docs/interfaces/Message.html +2 -2
- package/docs/interfaces/ModelInfo.html +2 -2
- package/docs/interfaces/NativeToolDefinition.html +16 -0
- package/docs/interfaces/PreparedPromptResponse.html +2 -2
- package/docs/interfaces/ProcessTextResponse.html +2 -2
- package/docs/interfaces/PromptFile.html +2 -2
- package/docs/interfaces/PromptFileContent.html +2 -2
- package/docs/interfaces/PromptFilesResponse.html +2 -2
- package/docs/interfaces/PromptFolder.html +2 -2
- package/docs/interfaces/PromptFoldersResponse.html +2 -2
- package/docs/interfaces/RoomDetails.html +2 -2
- package/docs/interfaces/RoomInfo.html +2 -2
- package/docs/interfaces/RoomMessageUpdate.html +9 -0
- package/docs/interfaces/RoomMessagesResponse.html +2 -2
- package/docs/interfaces/SendMessageResult.html +3 -0
- package/docs/interfaces/StoryErrorEvent.html +3 -3
- package/docs/interfaces/StoryIdea.html +2 -2
- package/docs/interfaces/StoryInfo.html +3 -3
- package/docs/interfaces/StoryIntroduceCharacterEvent.html +3 -3
- package/docs/interfaces/StoryProgressChapterEvent.html +3 -3
- package/docs/interfaces/StoryState.html +5 -5
- package/docs/interfaces/StoryStateEvent.html +3 -3
- package/docs/interfaces/ToolDefinition.html +2 -2
- package/docs/interfaces/ToolHelpers.html +7 -0
- package/docs/interfaces/ToolParameter.html +2 -2
- package/docs/interfaces/ToolSummary.html +4 -0
- package/docs/interfaces/ToolsResponse.html +4 -2
- package/docs/interfaces/Transaction.html +2 -2
- package/docs/interfaces/TransactionHistoryResponse.html +2 -2
- package/docs/modules.html +1 -1
- package/docs/types/PromptScope.html +1 -1
- package/docs/types/ToolContext.html +6 -0
- package/docs/types/ToolRunResult.html +1 -1
- 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.**
|
|
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
|
-
//
|
|
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:
|
|
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
|
-
|
|
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
|
-
|
|
515
|
+
import { Briyah } from 'briyah';
|
|
516
|
+
|
|
517
|
+
const briyah = new Briyah({ dataPath: './data/briyah', startingBalance: 10.00 });
|
|
518
|
+
await briyah.init();
|
|
494
519
|
|
|
495
|
-
//
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
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: '
|
|
525
|
+
{ name: 'text', type: 'string', description: 'The note text', required: true }
|
|
502
526
|
],
|
|
503
|
-
|
|
504
|
-
const
|
|
505
|
-
|
|
506
|
-
return {
|
|
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
|
-
//
|
|
512
|
-
const
|
|
513
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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 {
|
|
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, 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';
|
|
@@ -70,10 +70,11 @@ export declare class AppService {
|
|
|
70
70
|
listRooms(): Promise<RoomInfo[]>;
|
|
71
71
|
getRoomDetails(roomId: string): Promise<RoomDetails | null>;
|
|
72
72
|
getRoomById(roomId: string): Promise<Room | null>;
|
|
73
|
+
setRoomLeader(roomId: string, agentNickname: string): Promise<void>;
|
|
73
74
|
getRoomMessages(roomId: string, fromIndex?: number, includeThoughts?: boolean): Promise<RoomMessagesResponse>;
|
|
74
75
|
getAgentMessages(agentId: string, fromIndex?: number): Promise<AgentMessagesResponse>;
|
|
75
76
|
getStoryMessages(storyId: string, fromIndex: number): Promise<RoomMessagesResponse>;
|
|
76
|
-
sendRoomMessage(roomId: string, content: string, sender: string, action?: string, targets?: string[], clearQueue?: boolean): Promise<
|
|
77
|
+
sendRoomMessage(roomId: string, content: string, sender: string, action?: string, targets?: string[], clearQueue?: boolean, context?: unknown): Promise<SendMessageResult>;
|
|
77
78
|
pauseRoom(roomId: string): Promise<void>;
|
|
78
79
|
resumeRoom(roomId: string): Promise<void>;
|
|
79
80
|
deleteAgent(agentId: string): Promise<void>;
|
|
@@ -113,10 +114,13 @@ export declare class AppService {
|
|
|
113
114
|
beginInstruction?: string;
|
|
114
115
|
toolNames?: string[];
|
|
115
116
|
}): Promise<void>;
|
|
117
|
+
get userAuthoredToolsEnabled(): boolean;
|
|
116
118
|
listTools(): Promise<ToolDefinition[]>;
|
|
119
|
+
listNativeToolSummaries(): ToolSummary[];
|
|
117
120
|
createTool(tool: ToolDefinition): Promise<ToolDefinition>;
|
|
118
121
|
updateTool(name: string, tool: ToolDefinition): Promise<ToolDefinition>;
|
|
119
122
|
deleteTool(name: string): Promise<void>;
|
|
123
|
+
private assertUserAuthoringAllowed;
|
|
120
124
|
testTool(name: string, args: Record<string, any>): Promise<ToolRunResult>;
|
|
121
125
|
listAttachedFiles(agentId: string): Promise<FileList>;
|
|
122
126
|
deleteAttachedFile(agentId: string, fileName: string): Promise<void>;
|
|
@@ -413,6 +413,14 @@ class AppService {
|
|
|
413
413
|
async getRoomById(roomId) {
|
|
414
414
|
return await this.roomStore.getRoom(roomId);
|
|
415
415
|
}
|
|
416
|
+
async setRoomLeader(roomId, agentNickname) {
|
|
417
|
+
const room = await this.roomStore.getRoom(roomId);
|
|
418
|
+
if (!room) {
|
|
419
|
+
throw new errors_1.NotFoundError('Room not found');
|
|
420
|
+
}
|
|
421
|
+
room.setRoomLeader(agentNickname);
|
|
422
|
+
room.saveMetadata();
|
|
423
|
+
}
|
|
416
424
|
async getRoomMessages(roomId, fromIndex = 0, includeThoughts = false) {
|
|
417
425
|
const room = await this.roomStore.getRoom(roomId);
|
|
418
426
|
if (!room) {
|
|
@@ -463,7 +471,7 @@ class AppService {
|
|
|
463
471
|
const totalCost = story.totalCost || 0;
|
|
464
472
|
return { messages, totalCost };
|
|
465
473
|
}
|
|
466
|
-
async sendRoomMessage(roomId, content, sender, action = 'moderate', targets = [], clearQueue = false) {
|
|
474
|
+
async sendRoomMessage(roomId, content, sender, action = 'moderate', targets = [], clearQueue = false, context) {
|
|
467
475
|
const room = await this.roomStore.getRoom(roomId);
|
|
468
476
|
if (!room) {
|
|
469
477
|
throw new errors_1.NotFoundError('Room not found');
|
|
@@ -486,7 +494,7 @@ class AppService {
|
|
|
486
494
|
messageAction = app_types_1.MessageAction.SPEAK;
|
|
487
495
|
}
|
|
488
496
|
room.ready();
|
|
489
|
-
room.addPendingMessage(new message_1.RoomMessage(sender, messageAction, content, targets), clearQueue);
|
|
497
|
+
return room.addPendingMessage(new message_1.RoomMessage(sender, messageAction, content, targets), clearQueue, context);
|
|
490
498
|
}
|
|
491
499
|
async pauseRoom(roomId) {
|
|
492
500
|
const room = await this.roomStore.getRoom(roomId);
|
|
@@ -838,10 +846,23 @@ class AppService {
|
|
|
838
846
|
agent.toolNames = updates.toolNames;
|
|
839
847
|
agent.save();
|
|
840
848
|
}
|
|
849
|
+
get userAuthoredToolsEnabled() {
|
|
850
|
+
return this.toolExecution.userAuthoredToolsEnabled;
|
|
851
|
+
}
|
|
841
852
|
async listTools() {
|
|
853
|
+
if (!this.userAuthoredToolsEnabled)
|
|
854
|
+
return [];
|
|
842
855
|
return this.toolStore.listTools();
|
|
843
856
|
}
|
|
857
|
+
listNativeToolSummaries() {
|
|
858
|
+
return this.toolExecution.listNativeTools().map((t) => ({
|
|
859
|
+
name: t.name,
|
|
860
|
+
description: t.description,
|
|
861
|
+
parameters: t.parameters || [],
|
|
862
|
+
}));
|
|
863
|
+
}
|
|
844
864
|
async createTool(tool) {
|
|
865
|
+
this.assertUserAuthoringAllowed();
|
|
845
866
|
const existing = await this.toolStore.getTool(tool.name);
|
|
846
867
|
if (existing) {
|
|
847
868
|
throw new errors_1.OperationFailedError(`Tool "${tool.name}" already exists`);
|
|
@@ -849,6 +870,7 @@ class AppService {
|
|
|
849
870
|
return this.toolStore.saveTool(tool);
|
|
850
871
|
}
|
|
851
872
|
async updateTool(name, tool) {
|
|
873
|
+
this.assertUserAuthoringAllowed();
|
|
852
874
|
const existing = await this.toolStore.getTool(name);
|
|
853
875
|
if (!existing) {
|
|
854
876
|
throw new errors_1.NotFoundError(`Tool "${name}" not found`);
|
|
@@ -856,11 +878,17 @@ class AppService {
|
|
|
856
878
|
return this.toolStore.saveTool({ ...tool, name });
|
|
857
879
|
}
|
|
858
880
|
async deleteTool(name) {
|
|
881
|
+
this.assertUserAuthoringAllowed();
|
|
859
882
|
const deleted = await this.toolStore.deleteTool(name);
|
|
860
883
|
if (!deleted) {
|
|
861
884
|
throw new errors_1.NotFoundError(`Tool "${name}" not found`);
|
|
862
885
|
}
|
|
863
886
|
}
|
|
887
|
+
assertUserAuthoringAllowed() {
|
|
888
|
+
if (!this.userAuthoredToolsEnabled) {
|
|
889
|
+
throw new errors_1.OperationFailedError('User-authored tools are disabled on this deployment');
|
|
890
|
+
}
|
|
891
|
+
}
|
|
864
892
|
async testTool(name, args) {
|
|
865
893
|
return this.toolExecution.test(name, args);
|
|
866
894
|
}
|
|
@@ -1093,6 +1121,7 @@ class AppService {
|
|
|
1093
1121
|
isPaused: room.getPaused(),
|
|
1094
1122
|
currentSpeaker: room.getCurrentSpeaker(),
|
|
1095
1123
|
processingInProgress: room.isProcessingInProgress(),
|
|
1124
|
+
waitingForHuman: room.isWaitingForHuman(),
|
|
1096
1125
|
};
|
|
1097
1126
|
this.roomMessageService.emitUpdate(roomId, roomState);
|
|
1098
1127
|
});
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Agent } from '../ai/agent';
|
|
2
|
+
import { SendMessageResult } from '../../../shared/types/app.types';
|
|
2
3
|
import { RoomMessage } from './message';
|
|
3
4
|
import { Artifact } from './artifact';
|
|
4
5
|
import { ToolStoreService } from '../tools/tool-store.service';
|
|
@@ -33,6 +34,7 @@ export declare class Room {
|
|
|
33
34
|
private roomStoreService;
|
|
34
35
|
private toolStoreService?;
|
|
35
36
|
private toolExecutionService?;
|
|
37
|
+
private currentToolContext;
|
|
36
38
|
constructor(id: string | null, name: string, goal: string, baseRoomDir?: string, storageDir?: string, roomStoreService?: any);
|
|
37
39
|
deleteRoom(): void;
|
|
38
40
|
setLoading(isLoading: boolean): void;
|
|
@@ -119,8 +121,9 @@ export declare class Room {
|
|
|
119
121
|
private handleSituationUpdate;
|
|
120
122
|
handlePublishMessages(messages: RoomMessage[]): void;
|
|
121
123
|
handleAdjournMessages(messages: RoomMessage[]): void;
|
|
122
|
-
addPendingMessage(message: RoomMessage, clearQueue?: boolean):
|
|
124
|
+
addPendingMessage(message: RoomMessage, clearQueue?: boolean, context?: unknown): SendMessageResult;
|
|
123
125
|
isProcessingInProgress(): boolean;
|
|
126
|
+
isWaitingForHuman(): boolean;
|
|
124
127
|
pause(): void;
|
|
125
128
|
resume(): void;
|
|
126
129
|
interrupt(): 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 (!
|
|
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
|
}
|
|
@@ -740,12 +757,15 @@ Recent Message: ${message.getContent()}
|
|
|
740
757
|
humanAgent.save();
|
|
741
758
|
this.pendingMessages.push(message);
|
|
742
759
|
this.resume();
|
|
743
|
-
return;
|
|
760
|
+
return { accepted: true };
|
|
744
761
|
}
|
|
745
762
|
if (isHumanMessage) {
|
|
746
763
|
if (this.currentSpeaker !== null && this.currentSpeaker !== humanAgent.agentNickname) {
|
|
747
764
|
logger_1.logger.warn(`Human agent ${humanAgent.agentNickname} tried to speak out of turn. Current speaker: ${this.currentSpeaker}`);
|
|
748
|
-
return
|
|
765
|
+
return {
|
|
766
|
+
accepted: false,
|
|
767
|
+
reason: `It is ${this.currentSpeaker}'s turn to speak`,
|
|
768
|
+
};
|
|
749
769
|
}
|
|
750
770
|
humanAgent.addToConversationHistory(message, true);
|
|
751
771
|
humanAgent.save();
|
|
@@ -755,10 +775,23 @@ Recent Message: ${message.getContent()}
|
|
|
755
775
|
if (!this.processingInProgress) {
|
|
756
776
|
this.processPendingMessages();
|
|
757
777
|
}
|
|
778
|
+
return { accepted: true };
|
|
758
779
|
}
|
|
759
780
|
isProcessingInProgress() {
|
|
760
781
|
return this.processingInProgress;
|
|
761
782
|
}
|
|
783
|
+
isWaitingForHuman() {
|
|
784
|
+
const humanAgent = this.agents.find((a) => a.isControlledByHuman);
|
|
785
|
+
if (!humanAgent) {
|
|
786
|
+
return false;
|
|
787
|
+
}
|
|
788
|
+
if (this.currentSpeaker === humanAgent.agentNickname) {
|
|
789
|
+
return true;
|
|
790
|
+
}
|
|
791
|
+
return (this.currentSpeaker === null &&
|
|
792
|
+
!this.processingInProgress &&
|
|
793
|
+
(!this.pendingMessages || this.pendingMessages.length === 0));
|
|
794
|
+
}
|
|
762
795
|
pause() {
|
|
763
796
|
this.isPaused = true;
|
|
764
797
|
const humanAgent = this.agents.find(a => a.isControlledByHuman);
|
|
@@ -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.
|
|
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() {
|
|
@@ -130,6 +136,8 @@ class Briyah {
|
|
|
130
136
|
}
|
|
131
137
|
static ALWAYS_REFRESH_FILES = [
|
|
132
138
|
'config/model_prices.json',
|
|
139
|
+
'prompts/perceive.prompt',
|
|
140
|
+
'prompts/perceive.json',
|
|
133
141
|
];
|
|
134
142
|
seedCommonData() {
|
|
135
143
|
const dataPath = this.configService.get('BRIYAH_DATA_PATH') || path.resolve(process.cwd(), 'briyah-data');
|
|
@@ -179,6 +187,18 @@ class Briyah {
|
|
|
179
187
|
isInitialized() {
|
|
180
188
|
return this.initialized;
|
|
181
189
|
}
|
|
190
|
+
registerTool(def) {
|
|
191
|
+
this.nativeToolRegistry.registerTool(def);
|
|
192
|
+
}
|
|
193
|
+
registerTools(defs) {
|
|
194
|
+
this.nativeToolRegistry.registerTools(defs);
|
|
195
|
+
}
|
|
196
|
+
unregisterTool(name) {
|
|
197
|
+
return this.nativeToolRegistry.unregisterTool(name);
|
|
198
|
+
}
|
|
199
|
+
listNativeTools() {
|
|
200
|
+
return this.nativeToolRegistry.listTools();
|
|
201
|
+
}
|
|
182
202
|
getConfigService() {
|
|
183
203
|
return this.configService;
|
|
184
204
|
}
|
|
@@ -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, 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';
|
|
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';
|