briyah 1.2.4 → 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.
- package/README.md +89 -6
- package/data/common/config/image_models.json +160 -97
- package/data/common/config/markup +1 -1
- package/data/common/config/story_models.json +15 -3
- package/data/common/config/story_models_full.json +2 -2
- package/data/common/prompts/character/create_user_character.prompt +3 -12
- package/data/common/prompts/character/introduce_character.json +18 -0
- package/data/common/prompts/character/introduce_character.mock +4 -0
- package/data/common/prompts/character/introduce_character.prompt +58 -0
- package/data/common/prompts/character/perceive.prompt +3 -0
- package/data/common/prompts/character/progress_character.json +8 -4
- package/data/common/prompts/character/progress_character.mock +1 -0
- package/data/common/prompts/character/progress_character.prompt +20 -2
- package/data/common/prompts/character/update_portrait.json +18 -0
- package/data/common/prompts/character/update_portrait.mock +4 -0
- package/data/common/prompts/character/update_portrait.prompt +17 -1
- package/data/common/prompts/narrator/create_simple_plot.json +0 -0
- package/data/common/prompts/narrator/create_simple_plot.mock +13 -0
- package/data/common/prompts/narrator/create_simple_plot.prompt +35 -0
- package/data/common/prompts/narrator/perceive.prompt +12 -9
- package/data/common/prompts/narrator/progress_simple_plot.json +0 -0
- package/data/common/prompts/narrator/progress_simple_plot.mock +13 -0
- package/data/common/prompts/narrator/progress_simple_plot.prompt +40 -0
- package/data/common/prompts/perceive.json +1 -1
- package/data/common/prompts/perceive.prompt +82 -20
- package/data/common/prompts/story_moderator/moderate.json +1 -1
- package/data/common/prompts/story_moderator/moderate.prompt +26 -6
- package/dist-sdk/server/src/ai/LLM/anthropic.service.js +1 -2
- package/dist-sdk/server/src/ai/LLM/base-ai.service.d.ts +1 -1
- package/dist-sdk/server/src/ai/LLM/base-ai.service.js +13 -42
- package/dist-sdk/server/src/ai/LLM/deepseek.service.js +9 -0
- package/dist-sdk/server/src/ai/LLM/fal.service.js +1 -2
- package/dist-sdk/server/src/ai/LLM/googleai.service.js +1 -2
- package/dist-sdk/server/src/ai/LLM/grok.service.js +1 -2
- package/dist-sdk/server/src/ai/LLM/openai.service.js +1 -2
- package/dist-sdk/server/src/ai/LLM/together.service.js +1 -2
- package/dist-sdk/server/src/ai/agent-config.d.ts +2 -0
- package/dist-sdk/server/src/ai/agent-store.service.js +8 -0
- package/dist-sdk/server/src/ai/agent.d.ts +2 -0
- package/dist-sdk/server/src/ai/agent.js +2 -0
- package/dist-sdk/server/src/ai/model_prices.js +2 -1
- package/dist-sdk/server/src/app/user-service-factory.d.ts +3 -1
- package/dist-sdk/server/src/app/user-service-factory.js +14 -5
- package/dist-sdk/server/src/app.controller.d.ts +15 -4
- package/dist-sdk/server/src/app.controller.js +184 -5
- package/dist-sdk/server/src/app.service.d.ts +23 -6
- package/dist-sdk/server/src/app.service.js +72 -6
- package/dist-sdk/server/src/room/message.js +5 -1
- package/dist-sdk/server/src/room/room-factory.d.ts +5 -1
- package/dist-sdk/server/src/room/room-factory.js +6 -1
- package/dist-sdk/server/src/room/room-store.service.d.ts +5 -1
- package/dist-sdk/server/src/room/room-store.service.js +13 -2
- package/dist-sdk/server/src/room/room.d.ts +27 -5
- package/dist-sdk/server/src/room/room.js +397 -96
- 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 +19 -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/story/story.service.d.ts +5 -4
- package/dist-sdk/server/src/story/story.service.js +207 -120
- 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 +23 -0
- package/dist-sdk/server/src/tools/tool-execution.service.js +125 -0
- package/dist-sdk/server/src/tools/tool-store.service.d.ts +17 -0
- package/dist-sdk/server/src/tools/tool-store.service.js +143 -0
- package/dist-sdk/shared/types/app.types.d.ts +51 -5
- package/dist-sdk/shared/types/app.types.js +3 -0
- package/docs/assets/hierarchy.js +1 -1
- package/docs/assets/highlight.css +0 -7
- package/docs/assets/navigation.js +1 -1
- package/docs/assets/search.js +1 -1
- package/docs/classes/Agent.html +22 -14
- package/docs/classes/Briyah.html +35 -10
- package/docs/classes/BriyahConfigService.html +5 -5
- package/docs/classes/Room.html +32 -26
- package/docs/classes/RoomMessage.html +10 -10
- package/docs/enums/MessageAction.html +6 -3
- package/docs/hierarchy.html +1 -1
- package/docs/index.html +23 -6
- package/docs/interfaces/AgentInfo.html +3 -2
- package/docs/interfaces/AgentMessagesResponse.html +2 -2
- package/docs/interfaces/AppService.html +194 -150
- 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 -3
- 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/RoomMessagesResponse.html +2 -2
- package/docs/interfaces/StoryErrorEvent.html +3 -3
- package/docs/interfaces/StoryIdea.html +2 -2
- package/docs/interfaces/StoryInfo.html +5 -4
- 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 +6 -0
- package/docs/interfaces/ToolHelpers.html +7 -0
- package/docs/interfaces/ToolParameter.html +5 -0
- package/docs/interfaces/ToolSummary.html +4 -0
- package/docs/interfaces/ToolsResponse.html +4 -0
- 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 -0
- package/package.json +2 -1
|
@@ -5,9 +5,9 @@ const app_types_1 = require("../../../shared/types/app.types");
|
|
|
5
5
|
const message_1 = require("./message");
|
|
6
6
|
const crypto_1 = require("crypto");
|
|
7
7
|
const errors_1 = require("../common/errors");
|
|
8
|
-
const child_process_1 = require("child_process");
|
|
9
8
|
const logger_1 = require("../common/logger");
|
|
10
9
|
class Room {
|
|
10
|
+
static MAX_TOOL_ITERATIONS = 5;
|
|
11
11
|
id;
|
|
12
12
|
name;
|
|
13
13
|
goal;
|
|
@@ -28,11 +28,15 @@ class Room {
|
|
|
28
28
|
onStateChangeCallbacks = new Map();
|
|
29
29
|
onError;
|
|
30
30
|
currentSituation = '';
|
|
31
|
+
currentSituationTime = '';
|
|
31
32
|
onSituationUpdate;
|
|
32
33
|
onModeratorResponseCallback;
|
|
33
34
|
templateRoomId;
|
|
34
35
|
storageDir;
|
|
35
36
|
roomStoreService;
|
|
37
|
+
toolStoreService;
|
|
38
|
+
toolExecutionService;
|
|
39
|
+
currentToolContext = undefined;
|
|
36
40
|
constructor(id, name, goal, baseRoomDir = '', storageDir = '', roomStoreService = null) {
|
|
37
41
|
this.name = name;
|
|
38
42
|
this.goal = goal;
|
|
@@ -147,7 +151,7 @@ class Room {
|
|
|
147
151
|
getLatestRoomMessages(fromIndex = 0, includeThoughts = false) {
|
|
148
152
|
const messages = this.roomMessages.filter((msg) => msg.index >= fromIndex);
|
|
149
153
|
if (!includeThoughts) {
|
|
150
|
-
return messages.filter((msg) => msg.action !== app_types_1.MessageAction.THINK);
|
|
154
|
+
return messages.filter((msg) => msg.action !== app_types_1.MessageAction.THINK && msg.action !== app_types_1.MessageAction.TOOL);
|
|
151
155
|
}
|
|
152
156
|
return messages;
|
|
153
157
|
}
|
|
@@ -158,12 +162,12 @@ class Room {
|
|
|
158
162
|
});
|
|
159
163
|
this.nextMessageIndex = this.roomMessages.length;
|
|
160
164
|
}
|
|
161
|
-
addRoomMessage(message) {
|
|
165
|
+
addRoomMessage(message, options) {
|
|
162
166
|
message.index = this.nextMessageIndex++;
|
|
163
167
|
this.roomMessages.push(message);
|
|
164
168
|
this.saveMessages([message]);
|
|
165
|
-
if (message.situation) {
|
|
166
|
-
this.handleSituationUpdate(message.situation);
|
|
169
|
+
if (message.situation && !options?.suppressSituationUpdate) {
|
|
170
|
+
void this.handleSituationUpdate(message.situation);
|
|
167
171
|
}
|
|
168
172
|
this.notifyStateChange();
|
|
169
173
|
}
|
|
@@ -233,6 +237,12 @@ class Room {
|
|
|
233
237
|
}
|
|
234
238
|
}
|
|
235
239
|
}
|
|
240
|
+
if (normalizedAction === app_types_1.MessageAction.EXECUTE && (!response.name || !response.name.trim())) {
|
|
241
|
+
needsModeration = true;
|
|
242
|
+
}
|
|
243
|
+
if (normalizedAction === app_types_1.MessageAction.COMMISSION && targets.length === 0) {
|
|
244
|
+
needsModeration = true;
|
|
245
|
+
}
|
|
236
246
|
}
|
|
237
247
|
if (needsModeration) {
|
|
238
248
|
return new message_1.RoomMessage(agent.agentNickname, app_types_1.MessageAction.MODERATE, content, [], null, situation);
|
|
@@ -284,45 +294,175 @@ class Room {
|
|
|
284
294
|
const values = Object.values(app_types_1.MessageAction);
|
|
285
295
|
return values.includes(lowered) ? lowered : undefined;
|
|
286
296
|
}
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
if (
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
297
|
+
getPresentCharacters(perceivingAgent, message) {
|
|
298
|
+
const audienceNames = message.getTargets();
|
|
299
|
+
const senderName = message.getSender();
|
|
300
|
+
return this.agents.filter((a) => {
|
|
301
|
+
if (a.promptFolder !== 'character')
|
|
302
|
+
return false;
|
|
303
|
+
if (a.agentNickname === perceivingAgent.agentNickname)
|
|
304
|
+
return false;
|
|
305
|
+
if (this.checkAgentNicknameMatch(a.agentNickname, senderName))
|
|
306
|
+
return true;
|
|
307
|
+
if (audienceNames.some((name) => this.checkAgentNicknameMatch(a.agentNickname, name)))
|
|
308
|
+
return true;
|
|
309
|
+
if (audienceNames.length === 0 && message.canHear(a.agentNickname))
|
|
310
|
+
return true;
|
|
311
|
+
return false;
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
buildCharacterPrivateContextDigest() {
|
|
315
|
+
return this.agents
|
|
316
|
+
.filter((a) => a.promptFolder === 'character' && a.privateContext && a.privateContext.trim())
|
|
317
|
+
.map((a) => `### ${a.agentNickname}\n${a.privateContext}`)
|
|
318
|
+
.join('\n\n');
|
|
319
|
+
}
|
|
320
|
+
async buildAvailableTools(agent) {
|
|
321
|
+
if (!agent.toolNames || agent.toolNames.length === 0) {
|
|
322
|
+
return [];
|
|
323
|
+
}
|
|
324
|
+
const nativeByName = new Map((this.toolExecutionService?.listNativeTools() || []).map((t) => [t.name, t]));
|
|
325
|
+
const tools = [];
|
|
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
|
+
}
|
|
339
|
+
const tool = await this.toolStoreService.getTool(name);
|
|
340
|
+
if (tool) {
|
|
341
|
+
tools.push({
|
|
342
|
+
name: tool.name,
|
|
343
|
+
description: tool.description,
|
|
344
|
+
parameters: tool.parameters || [],
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
return tools;
|
|
349
|
+
}
|
|
350
|
+
async buildPerceiveVariables(agent) {
|
|
351
|
+
const visibleArtifacts = this.getVisibleArtifacts(agent.agentNickname)
|
|
352
|
+
.map((a) => `${a.name} (by ${a.creator}): ${a.body}`)
|
|
353
|
+
.join('\n\n');
|
|
354
|
+
const allArtifacts = this.getArtifacts();
|
|
355
|
+
const invisibleArtifactNames = allArtifacts
|
|
356
|
+
.filter((a) => !this.getVisibleArtifacts(agent.agentNickname).includes(a))
|
|
357
|
+
.map((a) => a.name)
|
|
358
|
+
.join(', ');
|
|
359
|
+
const humanAgent = this.getAgents().find((a) => a.isControlledByHuman);
|
|
360
|
+
const humanCharacterName = humanAgent ? humanAgent.agentNickname : 'Player';
|
|
361
|
+
const maxOutputChars = 4096;
|
|
362
|
+
return {
|
|
363
|
+
agentName: agent.agentName,
|
|
364
|
+
agentNickname: agent.agentNickname,
|
|
365
|
+
agentDescription: agent.description,
|
|
366
|
+
otherAgents: this.agents.filter((a) => a.agentNickname !== agent.agentNickname),
|
|
367
|
+
roomLeader: this.getRoomLeader(),
|
|
368
|
+
roomGoal: this.getGoal(),
|
|
369
|
+
scenario: this.getGoal(),
|
|
370
|
+
situation: this.getSituation() || 'Story beginning',
|
|
371
|
+
visibleArtifacts: visibleArtifacts,
|
|
372
|
+
invisibleArtifactNames: invisibleArtifactNames,
|
|
373
|
+
humanCharacterName: humanCharacterName,
|
|
374
|
+
humanAgentName: humanCharacterName,
|
|
375
|
+
maxOutputChars: maxOutputChars,
|
|
376
|
+
availableTools: await this.buildAvailableTools(agent),
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
buildTransientPrompt(agent, message) {
|
|
380
|
+
let prompt = this.buildSituationHeader() || null;
|
|
381
|
+
if (message) {
|
|
382
|
+
const presentCharacters = this.getPresentCharacters(agent, message);
|
|
383
|
+
if (presentCharacters.length > 0) {
|
|
384
|
+
const descriptions = presentCharacters
|
|
385
|
+
.map((c) => `- ${c.agentNickname}: ${c.description}`)
|
|
386
|
+
.join('\n');
|
|
387
|
+
const charactersPresent = `Characters present (how they currently appear to you):\n${descriptions}`;
|
|
388
|
+
prompt = prompt ? `${prompt}\n\n${charactersPresent}` : charactersPresent;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
if (agent.privateContext && agent.privateContext.trim()) {
|
|
392
|
+
const privateBlock = `Your private context (known only to you):\n${agent.privateContext}`;
|
|
393
|
+
prompt = prompt ? `${prompt}\n\n${privateBlock}` : privateBlock;
|
|
394
|
+
}
|
|
395
|
+
if (agent.agentNickname === this.getRoomLeader()) {
|
|
396
|
+
const digest = this.buildCharacterPrivateContextDigest();
|
|
397
|
+
if (digest) {
|
|
398
|
+
const digestBlock = `Character Inventories and Conditions:\n${digest}`;
|
|
399
|
+
prompt = prompt ? `${prompt}\n\n${digestBlock}` : digestBlock;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
return prompt;
|
|
403
|
+
}
|
|
404
|
+
async promptAgentOnce(agent, transientPrompt, variables) {
|
|
405
|
+
const response = await agent.instructedPrompt(transientPrompt, 'perceive', variables, false, true, variables.maxOutputChars);
|
|
406
|
+
const answer = this.parseAgentResponse(agent, response);
|
|
407
|
+
agent.addToConversationHistory(response, true);
|
|
408
|
+
agent.save();
|
|
409
|
+
return answer;
|
|
410
|
+
}
|
|
411
|
+
async runAgentTurn(agent, heardMessage, opts = {}) {
|
|
412
|
+
const variables = await this.buildPerceiveVariables(agent);
|
|
413
|
+
let response = await this.promptAgentOnce(agent, this.buildTransientPrompt(agent, heardMessage), variables);
|
|
414
|
+
for (let i = 0; i < Room.MAX_TOOL_ITERATIONS; i++) {
|
|
415
|
+
if (this.isPaused || this.isAdjourned)
|
|
416
|
+
return null;
|
|
417
|
+
let feedback;
|
|
418
|
+
if (response.action === app_types_1.MessageAction.PUBLISH && response.name) {
|
|
419
|
+
this.publishArtifact(response.name, agent.agentNickname, response.content, response.targets);
|
|
420
|
+
const wasDeleted = !response.content || !response.content.trim();
|
|
421
|
+
feedback = `From system: Artifact "${response.name}" was ${wasDeleted ? 'deleted' : 'published'}.`;
|
|
422
|
+
}
|
|
423
|
+
else if (response.action === app_types_1.MessageAction.EXECUTE) {
|
|
424
|
+
feedback = await this.executeToolForAgent(agent, response);
|
|
425
|
+
}
|
|
426
|
+
else if (opts.inCommission && response.action === app_types_1.MessageAction.COMMISSION) {
|
|
427
|
+
feedback = `From system: Nested commissions are not permitted. Complete your own task and respond with action "deliver".`;
|
|
428
|
+
}
|
|
429
|
+
else {
|
|
430
|
+
if (!opts.inCommission && response.action === app_types_1.MessageAction.DELIVER) {
|
|
431
|
+
response.action = app_types_1.MessageAction.SPEAK;
|
|
432
|
+
}
|
|
433
|
+
return response;
|
|
434
|
+
}
|
|
435
|
+
agent.addToConversationHistory(feedback, false);
|
|
323
436
|
agent.save();
|
|
437
|
+
response = await this.promptAgentOnce(agent, this.buildTransientPrompt(agent, null), variables);
|
|
324
438
|
}
|
|
325
|
-
|
|
439
|
+
if (this.isPaused || this.isAdjourned)
|
|
440
|
+
return null;
|
|
441
|
+
agent.addToConversationHistory(`From system: You have reached the tool-call limit for this turn. Respond now with an audible action (speak, whisper, think, ...).`, false);
|
|
442
|
+
agent.save();
|
|
443
|
+
response = await this.promptAgentOnce(agent, this.buildTransientPrompt(agent, null), variables);
|
|
444
|
+
if (response.action === app_types_1.MessageAction.EXECUTE ||
|
|
445
|
+
response.action === app_types_1.MessageAction.PUBLISH) {
|
|
446
|
+
response = new message_1.RoomMessage(agent.agentNickname, app_types_1.MessageAction.THINK, response.content, []);
|
|
447
|
+
}
|
|
448
|
+
return response;
|
|
449
|
+
}
|
|
450
|
+
async executeToolForAgent(agent, message) {
|
|
451
|
+
const toolName = message.name;
|
|
452
|
+
const result = this.toolExecutionService
|
|
453
|
+
? await this.toolExecutionService.runForAgent(toolName, message.content, agent.toolNames || [], this.currentToolContext)
|
|
454
|
+
: { ok: false, error: 'Tool execution is not available in this room' };
|
|
455
|
+
const argsPreview = message.content && message.content.length > 200
|
|
456
|
+
? `${message.content.slice(0, 200)}...`
|
|
457
|
+
: message.content || '';
|
|
458
|
+
const statusText = 'error' in result ? `error: ${result.error}` : 'ok';
|
|
459
|
+
this.addRoomMessage(new message_1.RoomMessage(agent.agentNickname, app_types_1.MessageAction.TOOL, `${toolName}(${argsPreview}) → ${statusText}`));
|
|
460
|
+
return `From system: Result of tool "${toolName}":\n${JSON.stringify(result)}`;
|
|
461
|
+
}
|
|
462
|
+
getAgentAiResponse(agent, message, onResponse) {
|
|
463
|
+
this.runAgentTurn(agent, message)
|
|
464
|
+
.then((answer) => onResponse(answer))
|
|
465
|
+
.catch((e) => {
|
|
326
466
|
if (e instanceof errors_1.InsufficientBalanceError) {
|
|
327
467
|
this.handleInsufficientBalance(e);
|
|
328
468
|
}
|
|
@@ -330,8 +470,8 @@ class Room {
|
|
|
330
470
|
let internalizedError = `${agent.agentNickname} thinks: No one heard me because ${e.message}`;
|
|
331
471
|
agent.addToConversationHistory(internalizedError, true);
|
|
332
472
|
}
|
|
333
|
-
|
|
334
|
-
|
|
473
|
+
onResponse(null);
|
|
474
|
+
});
|
|
335
475
|
}
|
|
336
476
|
perceive(agent, message, onResponse) {
|
|
337
477
|
if (!message.canHear(agent.agentNickname)) {
|
|
@@ -347,7 +487,7 @@ class Room {
|
|
|
347
487
|
if (agent.isControlledByHuman) {
|
|
348
488
|
return;
|
|
349
489
|
}
|
|
350
|
-
this.getAgentAiResponse(agent, onResponse);
|
|
490
|
+
this.getAgentAiResponse(agent, message, onResponse);
|
|
351
491
|
}
|
|
352
492
|
async moderate(moderatorAgent, message, onResponse) {
|
|
353
493
|
const humanAgent = this.getAgents().find((agent) => agent.isControlledByHuman);
|
|
@@ -374,10 +514,14 @@ class Room {
|
|
|
374
514
|
invisibleArtifactNames: invisibleArtifactNames,
|
|
375
515
|
};
|
|
376
516
|
let prompt = `
|
|
377
|
-
|
|
517
|
+
${this.buildSituationHeader()}
|
|
378
518
|
Sender: ${message.getSender()}
|
|
379
519
|
Recent Message: ${message.getContent()}
|
|
380
520
|
`;
|
|
521
|
+
const characterContexts = this.buildCharacterPrivateContextDigest();
|
|
522
|
+
if (characterContexts) {
|
|
523
|
+
prompt += `\nCharacter Inventories and Conditions:\n${characterContexts}\n`;
|
|
524
|
+
}
|
|
381
525
|
try {
|
|
382
526
|
let response = await moderatorAgent.instructedPrompt(prompt, 'moderate', variables, false, true);
|
|
383
527
|
let answer = this.parseAgentResponse(moderatorAgent, response);
|
|
@@ -471,6 +615,10 @@ Recent Message: ${message.getContent()}
|
|
|
471
615
|
setRoomStoreService(service) {
|
|
472
616
|
this.roomStoreService = service;
|
|
473
617
|
}
|
|
618
|
+
setToolServices(toolStore, toolExecution) {
|
|
619
|
+
this.toolStoreService = toolStore;
|
|
620
|
+
this.toolExecutionService = toolExecution;
|
|
621
|
+
}
|
|
474
622
|
saveMessages(messages) {
|
|
475
623
|
if (!this.roomStoreService || !this.storageDir || !this.id) {
|
|
476
624
|
return;
|
|
@@ -520,6 +668,22 @@ Recent Message: ${message.getContent()}
|
|
|
520
668
|
getSituation() {
|
|
521
669
|
return this.currentSituation;
|
|
522
670
|
}
|
|
671
|
+
getSituationTime() {
|
|
672
|
+
return this.currentSituationTime;
|
|
673
|
+
}
|
|
674
|
+
setSituationTime(time) {
|
|
675
|
+
this.currentSituationTime = time || '';
|
|
676
|
+
}
|
|
677
|
+
buildSituationHeader() {
|
|
678
|
+
const lines = [];
|
|
679
|
+
if (this.currentSituationTime) {
|
|
680
|
+
lines.push(`Current time: ${this.currentSituationTime} (24-hour clock)`);
|
|
681
|
+
}
|
|
682
|
+
if (this.currentSituation) {
|
|
683
|
+
lines.push(`Current Situation: ${this.currentSituation}`);
|
|
684
|
+
}
|
|
685
|
+
return lines.join('\n');
|
|
686
|
+
}
|
|
523
687
|
setSituation(situation) {
|
|
524
688
|
this.currentSituation = situation;
|
|
525
689
|
}
|
|
@@ -529,11 +693,11 @@ Recent Message: ${message.getContent()}
|
|
|
529
693
|
setOnModeratorResponse(callback) {
|
|
530
694
|
this.onModeratorResponseCallback = callback;
|
|
531
695
|
}
|
|
532
|
-
handleSituationUpdate(situation) {
|
|
696
|
+
async handleSituationUpdate(situation, messageBody) {
|
|
533
697
|
logger_1.logger.log(`Situation updated: ${situation}`);
|
|
534
698
|
this.currentSituation = situation;
|
|
535
699
|
if (this.onSituationUpdate) {
|
|
536
|
-
this.onSituationUpdate(situation);
|
|
700
|
+
await this.onSituationUpdate(situation, messageBody);
|
|
537
701
|
}
|
|
538
702
|
}
|
|
539
703
|
handlePublishMessages(messages) {
|
|
@@ -547,37 +711,6 @@ Recent Message: ${message.getContent()}
|
|
|
547
711
|
}
|
|
548
712
|
}
|
|
549
713
|
}
|
|
550
|
-
handleExecuteMessages(messages) {
|
|
551
|
-
for (const message of messages) {
|
|
552
|
-
if (message.content && message.content.trim()) {
|
|
553
|
-
const command = message.content.trim();
|
|
554
|
-
const creator = message.sender;
|
|
555
|
-
const description = message.name || 'Command execution';
|
|
556
|
-
const resultViewers = message.targets;
|
|
557
|
-
this.executeCommand(command, creator, description, resultViewers);
|
|
558
|
-
}
|
|
559
|
-
}
|
|
560
|
-
}
|
|
561
|
-
executeCommand(command, creator, description, resultViewers = []) {
|
|
562
|
-
const workingDir = this.baseRoomDir || process.cwd();
|
|
563
|
-
logger_1.logger.log(`FEATURE DISABLED -- Executing command: ${command} in directory: ${workingDir} by agent: ${creator}`);
|
|
564
|
-
return;
|
|
565
|
-
(0, child_process_1.exec)(command, { cwd: workingDir }, (error, stdout, stderr) => {
|
|
566
|
-
let result = '';
|
|
567
|
-
if (error) {
|
|
568
|
-
result = `Error: ${error.message}\n${stderr}`;
|
|
569
|
-
logger_1.logger.error(`Command execution error: ${error.message}`);
|
|
570
|
-
}
|
|
571
|
-
else if (stderr) {
|
|
572
|
-
result = `${stdout}\n\nStderr: ${stderr}`;
|
|
573
|
-
}
|
|
574
|
-
else {
|
|
575
|
-
result = stdout;
|
|
576
|
-
}
|
|
577
|
-
const artifactBody = `Command: ${command}\nWorking Directory: ${workingDir}\n\n${result}`;
|
|
578
|
-
this.publishArtifact(description, creator, artifactBody, resultViewers);
|
|
579
|
-
});
|
|
580
|
-
}
|
|
581
714
|
handleAdjournMessages(messages) {
|
|
582
715
|
if (messages.length === 0) {
|
|
583
716
|
return;
|
|
@@ -601,7 +734,10 @@ Recent Message: ${message.getContent()}
|
|
|
601
734
|
this.addRoomMessage(messages[0]);
|
|
602
735
|
}
|
|
603
736
|
}
|
|
604
|
-
addPendingMessage(message, clearQueue = false) {
|
|
737
|
+
addPendingMessage(message, clearQueue = false, context) {
|
|
738
|
+
if (context !== undefined) {
|
|
739
|
+
this.currentToolContext = context;
|
|
740
|
+
}
|
|
605
741
|
if (!this.pendingMessages) {
|
|
606
742
|
this.pendingMessages = [];
|
|
607
743
|
}
|
|
@@ -693,7 +829,7 @@ Recent Message: ${message.getContent()}
|
|
|
693
829
|
}
|
|
694
830
|
logger_1.logger.log(`Moderator routing: sender=${originalMessage.sender} action=${moderatorMessage.action}, name=${responderNickname}, targets=${targets.join(', ')}`);
|
|
695
831
|
if (moderatorMessage.action === app_types_1.MessageAction.RELAY) {
|
|
696
|
-
this.addRoomMessage(new message_1.RoomMessage(originalMessage.sender, originalMessage.action, content, originalMessage.targets, originalMessage.name, originalMessage.situation));
|
|
832
|
+
this.addRoomMessage(new message_1.RoomMessage(originalMessage.sender, originalMessage.action, content, originalMessage.targets, originalMessage.name, originalMessage.situation), { suppressSituationUpdate: true });
|
|
697
833
|
}
|
|
698
834
|
for (const recipientName of targets) {
|
|
699
835
|
if (recipientName === responderNickname)
|
|
@@ -724,6 +860,7 @@ Recent Message: ${message.getContent()}
|
|
|
724
860
|
return;
|
|
725
861
|
}
|
|
726
862
|
this.setCurrentSpeaker(responderNickname);
|
|
863
|
+
originalMessage.targets = targets;
|
|
727
864
|
this.perceive(responderAgent, originalMessage, (response) => {
|
|
728
865
|
if (this.isPaused) {
|
|
729
866
|
this.processingInProgress = false;
|
|
@@ -751,6 +888,149 @@ Recent Message: ${message.getContent()}
|
|
|
751
888
|
}
|
|
752
889
|
}
|
|
753
890
|
}
|
|
891
|
+
async runDeliverTurn(agent, commission) {
|
|
892
|
+
try {
|
|
893
|
+
let response = await this.runAgentTurn(agent, commission, { inCommission: true });
|
|
894
|
+
if (response === null)
|
|
895
|
+
return null;
|
|
896
|
+
if (response.action !== app_types_1.MessageAction.DELIVER) {
|
|
897
|
+
agent.addToConversationHistory(`From system: You were commissioned by ${commission.sender}. Respond now with action "deliver" targeting ${commission.sender}, containing your complete result.`, false);
|
|
898
|
+
agent.save();
|
|
899
|
+
const variables = await this.buildPerceiveVariables(agent);
|
|
900
|
+
response = await this.promptAgentOnce(agent, this.buildTransientPrompt(agent, null), variables);
|
|
901
|
+
}
|
|
902
|
+
if (response.action !== app_types_1.MessageAction.DELIVER) {
|
|
903
|
+
return new message_1.RoomMessage(agent.agentNickname, app_types_1.MessageAction.DELIVER, response.content, [commission.sender]);
|
|
904
|
+
}
|
|
905
|
+
response.sender = agent.agentNickname;
|
|
906
|
+
response.targets = [commission.sender];
|
|
907
|
+
return response;
|
|
908
|
+
}
|
|
909
|
+
catch (e) {
|
|
910
|
+
if (e instanceof errors_1.InsufficientBalanceError) {
|
|
911
|
+
this.handleInsufficientBalance(e);
|
|
912
|
+
return null;
|
|
913
|
+
}
|
|
914
|
+
logger_1.logger.error(`Commissioned agent ${agent.agentNickname} failed:`, e);
|
|
915
|
+
return new message_1.RoomMessage(agent.agentNickname, app_types_1.MessageAction.DELIVER, `(No deliverable: ${agent.agentNickname} encountered an error: ${e.message})`, [commission.sender]);
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
async handleCommissionMessage(msg) {
|
|
919
|
+
try {
|
|
920
|
+
const aiTargets = [];
|
|
921
|
+
const humanTargetNames = [];
|
|
922
|
+
const unknownNames = [];
|
|
923
|
+
for (const name of [...new Set(msg.getTargets())]) {
|
|
924
|
+
const agent = this.agents.find((a) => this.checkAgentNicknameMatch(a.agentNickname, name));
|
|
925
|
+
if (!agent) {
|
|
926
|
+
unknownNames.push(name);
|
|
927
|
+
}
|
|
928
|
+
else if (agent.agentNickname === msg.sender) {
|
|
929
|
+
}
|
|
930
|
+
else if (agent.isControlledByHuman) {
|
|
931
|
+
humanTargetNames.push(agent.agentNickname);
|
|
932
|
+
}
|
|
933
|
+
else if (!aiTargets.includes(agent)) {
|
|
934
|
+
aiTargets.push(agent);
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
for (const agent of this.agents) {
|
|
938
|
+
if (agent.agentNickname === msg.sender)
|
|
939
|
+
continue;
|
|
940
|
+
agent.addToConversationHistory(msg, false);
|
|
941
|
+
agent.save();
|
|
942
|
+
}
|
|
943
|
+
const commissioner = this.agents.find((a) => this.checkAgentNicknameMatch(a.agentNickname, msg.sender));
|
|
944
|
+
if (aiTargets.length === 0) {
|
|
945
|
+
const reasons = [];
|
|
946
|
+
if (unknownNames.length > 0)
|
|
947
|
+
reasons.push(`unknown agents: ${unknownNames.join(', ')}`);
|
|
948
|
+
if (humanTargetNames.length > 0)
|
|
949
|
+
reasons.push(`human-controlled agents cannot be commissioned: ${humanTargetNames.join(', ')}`);
|
|
950
|
+
const note = `From system: Your commission could not be delivered (${reasons.join('; ') || 'no valid targets'}).`;
|
|
951
|
+
await this.respondToCommissioner(commissioner, note);
|
|
952
|
+
return;
|
|
953
|
+
}
|
|
954
|
+
const settled = await Promise.allSettled(aiTargets.map((t) => this.runDeliverTurn(t, msg)));
|
|
955
|
+
if (this.isPaused || this.isAdjourned || !this.processingInProgress) {
|
|
956
|
+
if (this.processingInProgress) {
|
|
957
|
+
this.processingInProgress = false;
|
|
958
|
+
this.notifyStateChange();
|
|
959
|
+
}
|
|
960
|
+
return;
|
|
961
|
+
}
|
|
962
|
+
const delivers = settled.map((result, i) => {
|
|
963
|
+
if (result.status === 'fulfilled' && result.value)
|
|
964
|
+
return result.value;
|
|
965
|
+
return new message_1.RoomMessage(aiTargets[i].agentNickname, app_types_1.MessageAction.DELIVER, `(No deliverable: ${aiTargets[i].agentNickname} did not complete the commission)`, [msg.sender]);
|
|
966
|
+
});
|
|
967
|
+
for (const deliver of delivers) {
|
|
968
|
+
this.addRoomMessage(deliver);
|
|
969
|
+
for (const agent of this.agents) {
|
|
970
|
+
if (agent.agentNickname === deliver.sender)
|
|
971
|
+
continue;
|
|
972
|
+
if (this.checkAgentNicknameMatch(agent.agentNickname, msg.sender))
|
|
973
|
+
continue;
|
|
974
|
+
agent.addToConversationHistory(deliver, false);
|
|
975
|
+
agent.save();
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
const sections = delivers.map((d) => `## From ${d.sender}\n${d.content}`);
|
|
979
|
+
if (humanTargetNames.length > 0) {
|
|
980
|
+
sections.push(`(Skipped: ${humanTargetNames.join(', ')} — human-controlled agents cannot be commissioned)`);
|
|
981
|
+
}
|
|
982
|
+
if (unknownNames.length > 0) {
|
|
983
|
+
sections.push(`(Unknown agents: ${unknownNames.join(', ')})`);
|
|
984
|
+
}
|
|
985
|
+
const aggregate = `From system: Deliverables for your commission:\n\n${sections.join('\n\n')}`;
|
|
986
|
+
await this.respondToCommissioner(commissioner, aggregate);
|
|
987
|
+
}
|
|
988
|
+
catch (error) {
|
|
989
|
+
logger_1.logger.error('Error handling commission message:', error);
|
|
990
|
+
this.processingInProgress = false;
|
|
991
|
+
this.notifyStateChange();
|
|
992
|
+
if (this.pendingMessages && this.pendingMessages.length > 0) {
|
|
993
|
+
this.processPendingMessages();
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
async respondToCommissioner(commissioner, note) {
|
|
998
|
+
if (!commissioner) {
|
|
999
|
+
logger_1.logger.warn('Commissioner not found in room; dropping commission results');
|
|
1000
|
+
}
|
|
1001
|
+
else {
|
|
1002
|
+
commissioner.addToConversationHistory(note, false);
|
|
1003
|
+
commissioner.save();
|
|
1004
|
+
if (commissioner.isControlledByHuman) {
|
|
1005
|
+
this.addRoomMessage(new message_1.RoomMessage('system', app_types_1.MessageAction.SYSTEM, note, [
|
|
1006
|
+
commissioner.agentNickname,
|
|
1007
|
+
]));
|
|
1008
|
+
this.processingInProgress = false;
|
|
1009
|
+
this.notifyStateChange();
|
|
1010
|
+
this.setCurrentSpeaker(commissioner.agentNickname);
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
let reply = null;
|
|
1014
|
+
try {
|
|
1015
|
+
reply = await this.runAgentTurn(commissioner, null);
|
|
1016
|
+
}
|
|
1017
|
+
catch (e) {
|
|
1018
|
+
if (e instanceof errors_1.InsufficientBalanceError) {
|
|
1019
|
+
this.handleInsufficientBalance(e);
|
|
1020
|
+
return;
|
|
1021
|
+
}
|
|
1022
|
+
throw e;
|
|
1023
|
+
}
|
|
1024
|
+
if (reply !== null && !this.isPaused && !this.isAdjourned) {
|
|
1025
|
+
this.pendingMessages = [...(this.pendingMessages || []), reply];
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
this.processingInProgress = false;
|
|
1029
|
+
this.notifyStateChange();
|
|
1030
|
+
if (this.pendingMessages && this.pendingMessages.length > 0) {
|
|
1031
|
+
this.processPendingMessages();
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
754
1034
|
processPendingMessages() {
|
|
755
1035
|
if (this.isPaused ||
|
|
756
1036
|
this.processingInProgress ||
|
|
@@ -763,7 +1043,10 @@ Recent Message: ${message.getContent()}
|
|
|
763
1043
|
const messages = [...this.pendingMessages];
|
|
764
1044
|
this.pendingMessages = [];
|
|
765
1045
|
this.handlePublishMessages(messages.filter((m) => m.getAction() === app_types_1.MessageAction.PUBLISH));
|
|
766
|
-
|
|
1046
|
+
const strayExecuteMessages = messages.filter((m) => m.getAction() === app_types_1.MessageAction.EXECUTE);
|
|
1047
|
+
if (strayExecuteMessages.length > 0) {
|
|
1048
|
+
logger_1.logger.warn(`Dropping ${strayExecuteMessages.length} queued EXECUTE message(s); tool calls are handled within the sender's turn`);
|
|
1049
|
+
}
|
|
767
1050
|
this.handleAdjournMessages(messages.filter((m) => m.getAction() === app_types_1.MessageAction.ADJOURN));
|
|
768
1051
|
if (this.isAdjourned) {
|
|
769
1052
|
logger_1.logger.log(`Room ${this.name} has been adjourned. Message processing stopped.`);
|
|
@@ -789,21 +1072,34 @@ Recent Message: ${message.getContent()}
|
|
|
789
1072
|
if (moderateMessages.length > 1) {
|
|
790
1073
|
this.pendingMessages = [...moderateMessages.slice(1), ...this.pendingMessages];
|
|
791
1074
|
}
|
|
792
|
-
|
|
793
|
-
if (
|
|
794
|
-
this.
|
|
795
|
-
this.notifyStateChange();
|
|
796
|
-
return;
|
|
1075
|
+
const dispatchToModerator = async () => {
|
|
1076
|
+
if (originalMessage.situation) {
|
|
1077
|
+
await this.handleSituationUpdate(originalMessage.situation, originalMessage.getContent());
|
|
797
1078
|
}
|
|
798
|
-
|
|
799
|
-
this.
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
if (
|
|
805
|
-
this.
|
|
1079
|
+
await this.moderate(moderator, originalMessage, (response) => {
|
|
1080
|
+
if (this.isPaused) {
|
|
1081
|
+
this.processingInProgress = false;
|
|
1082
|
+
this.notifyStateChange();
|
|
1083
|
+
return;
|
|
1084
|
+
}
|
|
1085
|
+
if (response !== null) {
|
|
1086
|
+
this.handleModeratorResponse(response, originalMessage);
|
|
806
1087
|
}
|
|
1088
|
+
else {
|
|
1089
|
+
this.processingInProgress = false;
|
|
1090
|
+
this.notifyStateChange();
|
|
1091
|
+
if (this.pendingMessages && this.pendingMessages.length > 0) {
|
|
1092
|
+
this.processPendingMessages();
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
});
|
|
1096
|
+
};
|
|
1097
|
+
dispatchToModerator().catch((error) => {
|
|
1098
|
+
logger_1.logger.error('Error dispatching message to moderator:', error);
|
|
1099
|
+
this.processingInProgress = false;
|
|
1100
|
+
this.notifyStateChange();
|
|
1101
|
+
if (this.pendingMessages && this.pendingMessages.length > 0) {
|
|
1102
|
+
this.processPendingMessages();
|
|
807
1103
|
}
|
|
808
1104
|
});
|
|
809
1105
|
return;
|
|
@@ -825,6 +1121,10 @@ Recent Message: ${message.getContent()}
|
|
|
825
1121
|
nextMessage = filteredMessage;
|
|
826
1122
|
}
|
|
827
1123
|
this.addRoomMessage(nextMessage);
|
|
1124
|
+
if (nextMessage.getAction() === app_types_1.MessageAction.COMMISSION) {
|
|
1125
|
+
void this.handleCommissionMessage(nextMessage);
|
|
1126
|
+
return;
|
|
1127
|
+
}
|
|
828
1128
|
this.setCurrentSpeaker(nextMessage.targets[0]);
|
|
829
1129
|
let agentsInProgress = this.agents.length;
|
|
830
1130
|
if (agentsInProgress === 0) {
|
|
@@ -872,7 +1172,8 @@ Recent Message: ${message.getContent()}
|
|
|
872
1172
|
filtered = shoutMessages;
|
|
873
1173
|
}
|
|
874
1174
|
if (filtered.length > 1) {
|
|
875
|
-
const speakMessages = filtered.filter((m) => m.getAction() === app_types_1.MessageAction.SPEAK
|
|
1175
|
+
const speakMessages = filtered.filter((m) => m.getAction() === app_types_1.MessageAction.SPEAK ||
|
|
1176
|
+
m.getAction() === app_types_1.MessageAction.COMMISSION);
|
|
876
1177
|
const whisperMessages = filtered.filter((m) => m.getAction() === app_types_1.MessageAction.WHISPER);
|
|
877
1178
|
if (speakMessages.length > 0) {
|
|
878
1179
|
filtered = speakMessages;
|
|
@@ -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;
|