briyah 1.3.4 → 1.4.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 +689 -619
- package/data/common/artifacts/dnd5e/campaign_designer-setting.md +112 -0
- package/data/common/artifacts/dnd5e/character_creator-basics.md +40 -0
- package/data/common/artifacts/dnd5e/class-barbarian.md +64 -0
- package/data/common/artifacts/dnd5e/class-bard.md +63 -0
- package/data/common/artifacts/dnd5e/class-cleric.md +60 -0
- package/data/common/artifacts/dnd5e/class-druid.md +56 -0
- package/data/common/artifacts/dnd5e/class-fighter.md +53 -0
- package/data/common/artifacts/dnd5e/class-monk.md +77 -0
- package/data/common/artifacts/dnd5e/class-paladin.md +66 -0
- package/data/common/artifacts/dnd5e/class-ranger.md +73 -0
- package/data/common/artifacts/dnd5e/class-rogue.md +62 -0
- package/data/common/artifacts/dnd5e/class-sorcerer.md +67 -0
- package/data/common/artifacts/dnd5e/class-warlock.md +83 -0
- package/data/common/artifacts/dnd5e/class-wizard.md +51 -0
- package/data/common/artifacts/dnd5e/dungeon_master-procedure.md +348 -0
- package/data/common/artifacts/dnd5e/manifest.json +95 -0
- package/data/common/config/comfyui-workflows/flux-kontext.edit.json +98 -0
- package/data/common/config/comfyui-workflows/flux-kontext.t2i.json +80 -0
- package/data/common/config/comfyui-workflows/flux2-dev.edit.json +125 -0
- package/data/common/config/comfyui-workflows/flux2-dev.t2i.json +96 -0
- package/data/common/config/image_models_full.json +186 -99
- package/data/common/config/markup +1 -1
- package/data/common/config/model_prices.json +1250 -237
- package/data/common/prompts/campaign_designer/defaults_config.json +16 -0
- package/data/common/prompts/campaign_designer/perceive.json +29 -0
- package/data/common/prompts/campaign_designer/perceive.prompt +345 -0
- package/data/common/prompts/campaign_designer/system_instruction.prompt +0 -0
- package/data/common/prompts/character_creator/defaults_config.json +31 -0
- package/data/common/prompts/character_creator/perceive.json +29 -0
- package/data/common/prompts/character_creator/perceive.prompt +621 -0
- package/data/common/prompts/character_creator/system_instruction.prompt +0 -0
- package/data/common/prompts/dnd_player/defaults_config.json +5 -0
- package/data/common/prompts/dnd_player/perceive.json +29 -0
- package/data/common/prompts/dnd_player/perceive.prompt +312 -0
- package/data/common/prompts/dnd_player/system_instruction.prompt +0 -0
- package/data/common/prompts/dnd_room_moderator/defaults_config.json +9 -0
- package/data/common/prompts/dnd_room_moderator/moderate.json +34 -0
- package/data/common/prompts/dnd_room_moderator/moderate.prompt +291 -0
- package/data/common/prompts/dnd_room_moderator/system_instruction.prompt +0 -0
- package/data/common/prompts/dungeon_master/compact_agent.prompt +24 -0
- package/data/common/prompts/dungeon_master/defaults_config.json +29 -0
- package/data/common/prompts/dungeon_master/perceive.json +33 -0
- package/data/common/prompts/dungeon_master/perceive.prompt +757 -0
- package/data/common/prompts/dungeon_master/system_instruction.prompt +0 -0
- package/data/common/prompts/room_moderator/moderate.json +34 -29
- package/data/common/prompts/room_moderator/moderate.prompt +230 -210
- package/data/common/prompts/story_moderator/moderate.prompt +5 -2
- package/data/common/prompts/story_moderator/moderate_to_alice.mock +6 -6
- package/data/common/prompts/story_moderator/moderate_to_bob.mock +6 -6
- package/dist-sdk/server/src/ai/LLM/anthropic.service.d.ts +2 -0
- package/dist-sdk/server/src/ai/LLM/anthropic.service.js +34 -22
- package/dist-sdk/server/src/ai/LLM/base-ai.service.d.ts +2 -0
- package/dist-sdk/server/src/ai/LLM/base-ai.service.js +8 -3
- package/dist-sdk/server/src/ai/LLM/comfyui-client.d.ts +29 -0
- package/dist-sdk/server/src/ai/LLM/comfyui-client.js +142 -0
- package/dist-sdk/server/src/ai/LLM/comfyui-workflow.d.ts +19 -0
- package/dist-sdk/server/src/ai/LLM/comfyui-workflow.js +217 -0
- package/dist-sdk/server/src/ai/LLM/comfyui.module.d.ts +2 -0
- package/dist-sdk/server/src/ai/LLM/comfyui.module.js +21 -0
- package/dist-sdk/server/src/ai/LLM/comfyui.service.d.ts +26 -0
- package/dist-sdk/server/src/ai/LLM/comfyui.service.js +191 -0
- package/dist-sdk/server/src/ai/LLM/mock.service.d.ts +1 -0
- package/dist-sdk/server/src/ai/LLM/mock.service.js +3 -0
- package/dist-sdk/server/src/ai/LLM/self-hosted.module.d.ts +2 -0
- package/dist-sdk/server/src/ai/LLM/self-hosted.module.js +21 -0
- package/dist-sdk/server/src/ai/LLM/self-hosted.service.d.ts +13 -0
- package/dist-sdk/server/src/ai/LLM/self-hosted.service.js +205 -0
- package/dist-sdk/server/src/ai/agent-config.d.ts +1 -0
- package/dist-sdk/server/src/ai/agent-store.service.js +6 -4
- package/dist-sdk/server/src/ai/agent.d.ts +7 -0
- package/dist-sdk/server/src/ai/agent.js +33 -2
- package/dist-sdk/server/src/ai/ai-factory.module.js +4 -0
- package/dist-sdk/server/src/ai/ai-factory.service.d.ts +5 -1
- package/dist-sdk/server/src/ai/ai-factory.service.js +16 -2
- package/dist-sdk/server/src/ai/artifact.service.d.ts +2 -0
- package/dist-sdk/server/src/ai/artifact.service.js +29 -1
- package/dist-sdk/server/src/ai/pack-artifacts.d.ts +7 -0
- package/dist-sdk/server/src/ai/pack-artifacts.js +155 -0
- package/dist-sdk/server/src/app/stripe.controller.js +5 -0
- package/dist-sdk/server/src/app.controller.d.ts +18 -18
- package/dist-sdk/server/src/app.controller.js +249 -25
- package/dist-sdk/server/src/app.service.d.ts +30 -17
- package/dist-sdk/server/src/app.service.js +304 -36
- package/dist-sdk/server/src/auth/auth.controller.js +3 -2
- package/dist-sdk/server/src/auth/owner-only.decorator.d.ts +1 -0
- package/dist-sdk/server/src/auth/owner-only.decorator.js +8 -0
- package/dist-sdk/server/src/auth/twilio.service.d.ts +5 -1
- package/dist-sdk/server/src/auth/twilio.service.js +5 -3
- package/dist-sdk/server/src/config/user-paths.service.d.ts +2 -0
- package/dist-sdk/server/src/config/user-paths.service.js +8 -0
- package/dist-sdk/server/src/room/artifact-store.service.js +10 -2
- package/dist-sdk/server/src/room/artifact.d.ts +1 -0
- package/dist-sdk/server/src/room/message.d.ts +2 -1
- package/dist-sdk/server/src/room/message.js +5 -4
- package/dist-sdk/server/src/room/room-config.d.ts +3 -0
- package/dist-sdk/server/src/room/room-store.service.d.ts +4 -2
- package/dist-sdk/server/src/room/room-store.service.js +46 -12
- package/dist-sdk/server/src/room/room.d.ts +29 -3
- package/dist-sdk/server/src/room/room.js +390 -122
- package/dist-sdk/server/src/sdk/briyah.js +21 -3
- package/dist-sdk/server/src/sdk/index.d.ts +4 -1
- package/dist-sdk/server/src/sdk/index.js +9 -1
- package/dist-sdk/server/src/story/story.service.js +21 -12
- package/dist-sdk/server/src/tools/native-tool.types.d.ts +31 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/backgrounds.d.ts +22 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/backgrounds.js +59 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/feats.d.ts +24 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/feats.js +11 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.d.ts +5 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.generated.d.ts +1 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.generated.js +154 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.js +9 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.d.ts +20 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.generated.d.ts +2 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.generated.js +1824 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.js +6 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.d.ts +44 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.generated.d.ts +2 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.generated.js +17293 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.js +5 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/races.d.ts +41 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/races.js +250 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.d.ts +16 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.generated.d.ts +2 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.generated.js +3760 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.js +12 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.d.ts +63 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.js +449 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/weapons.d.ts +23 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/weapons.js +88 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/backgrounds.d.ts +20 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/backgrounds.js +109 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/bestiary.d.ts +30 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/bestiary.js +329 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/campaign-items.d.ts +9 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/campaign-items.js +100 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.d.ts +117 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.js +1057 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/coerce.d.ts +13 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/coerce.js +147 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/dice.d.ts +27 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/dice.js +263 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/encumbrance.d.ts +26 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/encumbrance.js +129 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/feats.d.ts +22 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/feats.js +127 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/items.d.ts +33 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/items.js +137 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.d.ts +26 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.js +182 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.d.ts +48 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.js +344 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.d.ts +98 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.js +456 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/spells.d.ts +27 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/spells.js +123 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/weapons.d.ts +23 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/weapons.js +201 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/index.d.ts +3 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/index.js +35 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.d.ts +2 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.js +323 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.d.ts +3 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.js +117 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/item.tool.d.ts +2 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/item.tool.js +122 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.d.ts +2 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.js +157 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.d.ts +32 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.js +203 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.d.ts +4 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.js +465 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/spell.tool.d.ts +2 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/spell.tool.js +116 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/state.tools.d.ts +4 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/state.tools.js +234 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.d.ts +6 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.js +616 -0
- package/dist-sdk/server/src/tools/packs/index.d.ts +7 -0
- package/dist-sdk/server/src/tools/packs/index.js +45 -0
- package/dist-sdk/server/src/tools/tool-execution.service.d.ts +2 -2
- package/dist-sdk/server/src/tools/tool-execution.service.js +7 -6
- package/dist-sdk/shared/types/app.types.d.ts +63 -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 +51 -15
- package/docs/classes/Briyah.html +14 -14
- package/docs/classes/BriyahConfigService.html +5 -5
- package/docs/classes/NativeToolRegistry.html +21 -0
- package/docs/classes/Room.html +79 -29
- package/docs/classes/RoomMessage.html +32 -15
- package/docs/enums/MessageAction.html +3 -3
- package/docs/functions/availableToolPacks.html +2 -0
- package/docs/functions/dnd5eTools.html +5 -0
- package/docs/functions/enabledToolPacks.html +2 -0
- package/docs/functions/registerToolPacks.html +6 -0
- package/docs/hierarchy.html +1 -1
- package/docs/index.html +47 -3
- package/docs/interfaces/AgentInfo.html +17 -2
- package/docs/interfaces/AgentMessagesResponse.html +2 -2
- package/docs/interfaces/AppService.html +230 -181
- package/docs/interfaces/Artifact.html +15 -3
- package/docs/interfaces/ArtifactMetadata.html +5 -2
- package/docs/interfaces/ArtifactWriteOptions.html +21 -0
- package/docs/interfaces/AttachDocumentResponse.html +2 -2
- package/docs/interfaces/BriyahConfigOptions.html +9 -9
- 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 +11 -7
- 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 +15 -2
- package/docs/interfaces/RoomInfo.html +3 -2
- package/docs/interfaces/RoomMessageUpdate.html +2 -2
- package/docs/interfaces/RoomMessagesResponse.html +2 -2
- package/docs/interfaces/SendMessageResult.html +2 -2
- 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/ToolArtifact.html +8 -0
- package/docs/interfaces/ToolCaller.html +8 -0
- package/docs/interfaces/ToolDefinition.html +2 -2
- package/docs/interfaces/ToolHelpers.html +7 -3
- package/docs/interfaces/ToolParameter.html +2 -2
- package/docs/interfaces/ToolRoomAccess.html +51 -0
- package/docs/interfaces/ToolSummary.html +3 -2
- package/docs/interfaces/ToolsResponse.html +2 -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 +2 -2
- package/docs/types/ToolRunResult.html +1 -1
- package/package.json +7 -4
|
@@ -0,0 +1,191 @@
|
|
|
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
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.ComfyUiAiService = void 0;
|
|
13
|
+
const common_1 = require("@nestjs/common");
|
|
14
|
+
const crypto_1 = require("crypto");
|
|
15
|
+
const base_ai_service_1 = require("./base-ai.service");
|
|
16
|
+
const comfyui_client_1 = require("./comfyui-client");
|
|
17
|
+
const comfyui_workflow_1 = require("./comfyui-workflow");
|
|
18
|
+
const errors_1 = require("../../common/errors");
|
|
19
|
+
const logger_1 = require("../../common/logger");
|
|
20
|
+
let ComfyUiAiService = class ComfyUiAiService extends base_ai_service_1.BaseAiService {
|
|
21
|
+
client;
|
|
22
|
+
constructor() {
|
|
23
|
+
super();
|
|
24
|
+
try {
|
|
25
|
+
const baseUrl = process.env['COMFYUI_BASE_URL'];
|
|
26
|
+
if (!baseUrl) {
|
|
27
|
+
this._isAvailable = false;
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
let extraHeaders;
|
|
31
|
+
const rawHeaders = process.env['COMFYUI_EXTRA_HEADERS'];
|
|
32
|
+
if (rawHeaders) {
|
|
33
|
+
try {
|
|
34
|
+
extraHeaders = JSON.parse(rawHeaders);
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
logger_1.logger.error('COMFYUI_EXTRA_HEADERS is not valid JSON, ignoring:', error.message);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
this.client = new comfyui_client_1.ComfyUiClient({
|
|
41
|
+
baseUrl,
|
|
42
|
+
extraHeaders,
|
|
43
|
+
timeoutMs: parseInt(process.env['COMFYUI_TIMEOUT_MS'], 10) || undefined,
|
|
44
|
+
pollIntervalMs: parseInt(process.env['COMFYUI_POLL_INTERVAL_MS'], 10) || undefined,
|
|
45
|
+
});
|
|
46
|
+
logger_1.logger.debug('ComfyUI service initialized successfully');
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
logger_1.logger.error('Error initializing ComfyUI service:', error);
|
|
50
|
+
this._isAvailable = false;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
getServiceName() {
|
|
54
|
+
return 'ComfyUI';
|
|
55
|
+
}
|
|
56
|
+
supportsImageGeneration() {
|
|
57
|
+
return true;
|
|
58
|
+
}
|
|
59
|
+
requiresKnownModel() {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
async fetchModelsFromApi() {
|
|
63
|
+
return (0, comfyui_workflow_1.listWorkflowPairs)().map((pair) => ({
|
|
64
|
+
name: pair.name,
|
|
65
|
+
description: `ComfyUI workflow (${pair.variants.join(', ')})`,
|
|
66
|
+
model: pair.name,
|
|
67
|
+
service: 'ComfyUI',
|
|
68
|
+
}));
|
|
69
|
+
}
|
|
70
|
+
async textPrompt(_agent, _prompt, _jsonSchema = null, _saveResponse = true, _promptInstructions = null, _cacheConfig = null, _maxOutputChars = 0) {
|
|
71
|
+
throw new Error('ComfyUI agents are image-generation only. Use generateImage/editImage, ' +
|
|
72
|
+
'or choose a text provider for chat agents.');
|
|
73
|
+
}
|
|
74
|
+
async generateImage(agent, prompt, imageProperties) {
|
|
75
|
+
try {
|
|
76
|
+
const { centsPerImage, width = 1024, height = 1024, seed } = imageProperties ?? {};
|
|
77
|
+
const balanceError = this.checkBalance(agent, centsPerImage);
|
|
78
|
+
if (balanceError)
|
|
79
|
+
throw balanceError;
|
|
80
|
+
const workflow = this.prepareWorkflow(agent, 't2i', {
|
|
81
|
+
prompt,
|
|
82
|
+
seed: seed ?? (0, crypto_1.randomInt)(0, 2 ** 31 - 1),
|
|
83
|
+
width,
|
|
84
|
+
height,
|
|
85
|
+
});
|
|
86
|
+
const artifactId = await this.runWorkflow(agent, workflow, prompt, centsPerImage);
|
|
87
|
+
return { artifactId };
|
|
88
|
+
}
|
|
89
|
+
catch (error) {
|
|
90
|
+
if (error instanceof errors_1.InsufficientBalanceError)
|
|
91
|
+
throw error;
|
|
92
|
+
logger_1.logger.error('ComfyUI generateImage failed:', error.message || error);
|
|
93
|
+
return { error };
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
async editImage(agent, prompt, imageProperties, referenceImageArtifactIds) {
|
|
97
|
+
try {
|
|
98
|
+
const { centsPerImage, width = 1024, height = 1024, seed } = imageProperties ?? {};
|
|
99
|
+
if (!referenceImageArtifactIds || referenceImageArtifactIds.length === 0) {
|
|
100
|
+
return this.generateImage(agent, prompt, imageProperties);
|
|
101
|
+
}
|
|
102
|
+
const balanceError = this.checkBalance(agent, centsPerImage);
|
|
103
|
+
if (balanceError)
|
|
104
|
+
throw balanceError;
|
|
105
|
+
const references = this.loadReferenceBuffers(agent, referenceImageArtifactIds);
|
|
106
|
+
const refImages = [];
|
|
107
|
+
for (const reference of references) {
|
|
108
|
+
const uploaded = await this.client.uploadImage(reference.buffer, `briyah-ref-${(0, crypto_1.randomUUID)()}.png`);
|
|
109
|
+
refImages.push(uploaded.subfolder ? `${uploaded.subfolder}/${uploaded.name}` : uploaded.name);
|
|
110
|
+
}
|
|
111
|
+
const effectivePrompt = references.length > 1
|
|
112
|
+
? this.buildMultiRefPreamble(references.length) + prompt
|
|
113
|
+
: prompt;
|
|
114
|
+
let workflow = this.prepareWorkflow(agent, 'edit', {
|
|
115
|
+
prompt: effectivePrompt,
|
|
116
|
+
seed: seed ?? (0, crypto_1.randomInt)(0, 2 ** 31 - 1),
|
|
117
|
+
width,
|
|
118
|
+
height,
|
|
119
|
+
refImage: refImages[0],
|
|
120
|
+
});
|
|
121
|
+
workflow = (0, comfyui_workflow_1.chainReferenceImages)(workflow, refImages.slice(1));
|
|
122
|
+
const artifactId = await this.runWorkflow(agent, workflow, prompt, centsPerImage);
|
|
123
|
+
return { artifactId };
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
if (error instanceof errors_1.InsufficientBalanceError)
|
|
127
|
+
throw error;
|
|
128
|
+
logger_1.logger.error('ComfyUI editImage failed:', error.message || error);
|
|
129
|
+
return { error };
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
checkBalance(agent, centsPerImage) {
|
|
133
|
+
if (!centsPerImage || centsPerImage <= 0)
|
|
134
|
+
return null;
|
|
135
|
+
if (agent.balanceService && !agent.disableBalanceCheck) {
|
|
136
|
+
if (!agent.balanceService.hasSufficientBalance()) {
|
|
137
|
+
return new errors_1.InsufficientBalanceError('Insufficient balance for image generation. Please add funds to continue.');
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
prepareWorkflow(agent, variant, values) {
|
|
143
|
+
const templateFile = (0, comfyui_workflow_1.resolveWorkflowFile)(agent.modelName, variant, agent.userPaths);
|
|
144
|
+
if (!templateFile) {
|
|
145
|
+
throw new Error(`No ComfyUI ${variant} workflow "${agent.modelName}.${variant}.json" found in the ` +
|
|
146
|
+
'user or common comfyui-workflows directory.');
|
|
147
|
+
}
|
|
148
|
+
const template = (0, comfyui_workflow_1.loadWorkflowTemplate)(templateFile);
|
|
149
|
+
return (0, comfyui_workflow_1.patchWorkflow)(template, values);
|
|
150
|
+
}
|
|
151
|
+
async runWorkflow(agent, workflow, prompt, centsPerImage) {
|
|
152
|
+
this.debugLogRequest(agent.agentName, workflow);
|
|
153
|
+
const promptId = await this.client.queuePrompt(workflow);
|
|
154
|
+
const imageRef = await this.client.waitForCompletion(promptId);
|
|
155
|
+
const imageBuffer = await this.client.fetchOutput(imageRef);
|
|
156
|
+
this.computeImageCost(agent, centsPerImage);
|
|
157
|
+
return this.saveImageAsArtifact(agent, imageBuffer.toString('base64'), prompt);
|
|
158
|
+
}
|
|
159
|
+
computeImageCost(agent, centsPerImage) {
|
|
160
|
+
if (!centsPerImage || centsPerImage <= 0)
|
|
161
|
+
return;
|
|
162
|
+
const cost = centsPerImage / 100;
|
|
163
|
+
agent.totalCost += cost;
|
|
164
|
+
logger_1.logger.log(`Image cost for ${agent.agentName}: $${cost.toFixed(4)}`);
|
|
165
|
+
if (agent.balanceService) {
|
|
166
|
+
agent.balanceService.decrementBalance(cost, 0);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
loadReferenceBuffers(agent, artifactIds) {
|
|
170
|
+
const references = [];
|
|
171
|
+
for (const artifactId of artifactIds) {
|
|
172
|
+
const imageData = agent.artifactService.getArtifact(artifactId);
|
|
173
|
+
if (!imageData || !Buffer.isBuffer(imageData)) {
|
|
174
|
+
throw new Error(`Reference image artifact '${artifactId}' is missing or not an image; ` +
|
|
175
|
+
'refusing to generate with an incomplete reference set.');
|
|
176
|
+
}
|
|
177
|
+
references.push({ buffer: imageData, artifactId });
|
|
178
|
+
}
|
|
179
|
+
return references;
|
|
180
|
+
}
|
|
181
|
+
buildMultiRefPreamble(referenceCount) {
|
|
182
|
+
return (`${referenceCount} reference images are provided in order. ` +
|
|
183
|
+
'Reference Image 1 is the scene/setting; each subsequent reference image is a character portrait. ' +
|
|
184
|
+
"Any mention of 'Image k' below refers to the k-th reference image. ONLY produce one output image depicting a single scene.\n\n");
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
exports.ComfyUiAiService = ComfyUiAiService;
|
|
188
|
+
exports.ComfyUiAiService = ComfyUiAiService = __decorate([
|
|
189
|
+
(0, common_1.Injectable)(),
|
|
190
|
+
__metadata("design:paramtypes", [])
|
|
191
|
+
], ComfyUiAiService);
|
|
@@ -4,6 +4,7 @@ import { ModelInfo } from '../../../../shared/types/app.types';
|
|
|
4
4
|
export declare class MockAiService extends BaseAiService {
|
|
5
5
|
constructor();
|
|
6
6
|
getServiceName(): string;
|
|
7
|
+
requiresKnownModel(): boolean;
|
|
7
8
|
protected fetchModelsFromApi(): Promise<ModelInfo[]>;
|
|
8
9
|
preparedPrompt(agent: Agent, promptFileName: string, variables: any, saveResponse?: boolean, _cacheConfig?: any): Promise<any>;
|
|
9
10
|
getMockFile(promptFileName: string, prompt: string, variables: any): string;
|
|
@@ -0,0 +1,21 @@
|
|
|
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.SelfHostedModule = void 0;
|
|
10
|
+
const common_1 = require("@nestjs/common");
|
|
11
|
+
const self_hosted_service_1 = require("./self-hosted.service");
|
|
12
|
+
let SelfHostedModule = class SelfHostedModule {
|
|
13
|
+
};
|
|
14
|
+
exports.SelfHostedModule = SelfHostedModule;
|
|
15
|
+
exports.SelfHostedModule = SelfHostedModule = __decorate([
|
|
16
|
+
(0, common_1.Module)({
|
|
17
|
+
imports: [],
|
|
18
|
+
providers: [self_hosted_service_1.SelfHostedAiService],
|
|
19
|
+
exports: [self_hosted_service_1.SelfHostedAiService],
|
|
20
|
+
})
|
|
21
|
+
], SelfHostedModule);
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { BaseAiService } from './base-ai.service';
|
|
2
|
+
import { Agent } from '../agent';
|
|
3
|
+
import { ModelInfo } from '../../../../shared/types/app.types';
|
|
4
|
+
export declare class SelfHostedAiService extends BaseAiService {
|
|
5
|
+
private openai;
|
|
6
|
+
constructor();
|
|
7
|
+
getServiceName(): string;
|
|
8
|
+
requiresKnownModel(): boolean;
|
|
9
|
+
fetchModelsFromApi(): Promise<ModelInfo[]>;
|
|
10
|
+
textPrompt(agent: Agent, prompt: string, jsonSchema?: any, saveResponse?: boolean, promptInstructions?: string, _cacheConfig?: any, _maxOutputChars?: number): Promise<any>;
|
|
11
|
+
addToConversationHistory(agent: Agent, message: string, fromSelf?: boolean, developer?: boolean): void;
|
|
12
|
+
private computeMessageCost;
|
|
13
|
+
}
|
|
@@ -0,0 +1,205 @@
|
|
|
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
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.SelfHostedAiService = void 0;
|
|
13
|
+
const common_1 = require("@nestjs/common");
|
|
14
|
+
const openai_1 = require("openai");
|
|
15
|
+
const base_ai_service_1 = require("./base-ai.service");
|
|
16
|
+
const model_prices_1 = require("../model_prices");
|
|
17
|
+
const errors_1 = require("../../common/errors");
|
|
18
|
+
const logger_1 = require("../../common/logger");
|
|
19
|
+
let SelfHostedAiService = class SelfHostedAiService extends base_ai_service_1.BaseAiService {
|
|
20
|
+
openai;
|
|
21
|
+
constructor() {
|
|
22
|
+
super();
|
|
23
|
+
try {
|
|
24
|
+
const baseURL = process.env['SELF_HOSTED_BASE_URL'];
|
|
25
|
+
if (!baseURL) {
|
|
26
|
+
this._isAvailable = false;
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
this.openai = new openai_1.OpenAI({
|
|
30
|
+
apiKey: process.env['SELF_HOSTED_API_KEY'] || 'sk-no-key-required',
|
|
31
|
+
baseURL,
|
|
32
|
+
timeout: 600000,
|
|
33
|
+
maxRetries: 3,
|
|
34
|
+
});
|
|
35
|
+
logger_1.logger.debug('SelfHosted service initialized successfully');
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
logger_1.logger.error('Error initializing SelfHosted service:', error);
|
|
39
|
+
this._isAvailable = false;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
getServiceName() {
|
|
43
|
+
return 'SelfHosted';
|
|
44
|
+
}
|
|
45
|
+
requiresKnownModel() {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
async fetchModelsFromApi() {
|
|
49
|
+
const models = await this.openai.models.list();
|
|
50
|
+
return models.data
|
|
51
|
+
.filter((model) => model && model.id)
|
|
52
|
+
.map((model) => ({
|
|
53
|
+
name: model.id,
|
|
54
|
+
description: model.id,
|
|
55
|
+
model: model.id,
|
|
56
|
+
service: 'SelfHosted',
|
|
57
|
+
}));
|
|
58
|
+
}
|
|
59
|
+
async textPrompt(agent, prompt, jsonSchema = null, saveResponse = true, promptInstructions = null, _cacheConfig = null, _maxOutputChars = 0) {
|
|
60
|
+
const modelInfo = (0, model_prices_1.resolveModelInfo)(agent.modelName, this.getModelPricePrefix());
|
|
61
|
+
if (modelInfo && agent.balanceService && !agent.disableBalanceCheck) {
|
|
62
|
+
const hasSufficientBalance = agent.balanceService.hasSufficientBalance();
|
|
63
|
+
if (!hasSufficientBalance) {
|
|
64
|
+
throw new errors_1.InsufficientBalanceError('Insufficient balance. Please add funds to continue using AI services.');
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const identity = `Your agent identity is ${agent.agentName}: ${agent.description}`;
|
|
68
|
+
const instructions = promptInstructions || agent.systemInstruction;
|
|
69
|
+
const messages = [];
|
|
70
|
+
if (instructions)
|
|
71
|
+
messages.push({
|
|
72
|
+
role: 'system',
|
|
73
|
+
content: [{ type: 'text', text: instructions }],
|
|
74
|
+
});
|
|
75
|
+
messages.push({
|
|
76
|
+
role: 'system',
|
|
77
|
+
content: [{ type: 'text', text: identity }],
|
|
78
|
+
});
|
|
79
|
+
if (agent.attachedFiles && agent.attachedFiles.length > 0) {
|
|
80
|
+
for (const file of agent.attachedFiles) {
|
|
81
|
+
if (!file.serviceMetadata?.fileData)
|
|
82
|
+
continue;
|
|
83
|
+
const fileData = new Uint8Array(file.serviceMetadata.fileData);
|
|
84
|
+
const textContent = Buffer.from(fileData).toString('utf-8');
|
|
85
|
+
messages.push({
|
|
86
|
+
role: 'user',
|
|
87
|
+
content: [
|
|
88
|
+
{
|
|
89
|
+
type: 'text',
|
|
90
|
+
text: `Attached file "${file.fileName}":\n\n${textContent}`,
|
|
91
|
+
},
|
|
92
|
+
],
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (agent.attachedArtifacts && agent.attachedArtifacts.length > 0) {
|
|
97
|
+
for (const artifactId of agent.attachedArtifacts) {
|
|
98
|
+
const content = agent.artifactService.getArtifact(artifactId);
|
|
99
|
+
if (content && typeof content === 'string') {
|
|
100
|
+
const metadata = agent.artifactService.getArtifactMetadata(artifactId);
|
|
101
|
+
const fileName = metadata ? `${metadata.name}.md` : 'artifact.md';
|
|
102
|
+
messages.push({
|
|
103
|
+
role: 'user',
|
|
104
|
+
content: [
|
|
105
|
+
{
|
|
106
|
+
type: 'text',
|
|
107
|
+
text: `Attached document: ${fileName}\n\n${content}`,
|
|
108
|
+
},
|
|
109
|
+
],
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
if (jsonSchema) {
|
|
115
|
+
messages.push({
|
|
116
|
+
role: 'system',
|
|
117
|
+
content: [
|
|
118
|
+
{
|
|
119
|
+
type: 'text',
|
|
120
|
+
text: `You must respond with valid JSON matching this schema: ${JSON.stringify(jsonSchema)}`,
|
|
121
|
+
},
|
|
122
|
+
],
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
messages.push(...agent.history);
|
|
126
|
+
if (prompt) {
|
|
127
|
+
messages.push({
|
|
128
|
+
role: 'user',
|
|
129
|
+
content: [{ type: 'text', text: prompt }],
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
const requestParams = {
|
|
133
|
+
model: agent.modelName,
|
|
134
|
+
messages: messages,
|
|
135
|
+
};
|
|
136
|
+
this.debugLogRequest(agent.agentName, requestParams);
|
|
137
|
+
let responseText;
|
|
138
|
+
try {
|
|
139
|
+
const response = await this.openai.chat.completions.create(requestParams);
|
|
140
|
+
for (const choice of response.choices) {
|
|
141
|
+
if (choice.message.content)
|
|
142
|
+
responseText = choice.message.content;
|
|
143
|
+
}
|
|
144
|
+
responseText = this.trimResponseText(responseText);
|
|
145
|
+
if (jsonSchema) {
|
|
146
|
+
responseText = this.trimToJson(responseText);
|
|
147
|
+
}
|
|
148
|
+
this.debugLogResponse(agent.agentName, responseText);
|
|
149
|
+
if (response.usage) {
|
|
150
|
+
this.computeMessageCost(agent, response.usage, modelInfo);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
logger_1.logger.error(error);
|
|
155
|
+
throw error;
|
|
156
|
+
}
|
|
157
|
+
if (saveResponse) {
|
|
158
|
+
this.addToConversationHistory(agent, prompt, false);
|
|
159
|
+
this.addToConversationHistory(agent, responseText, true);
|
|
160
|
+
}
|
|
161
|
+
if (jsonSchema)
|
|
162
|
+
return this.parseStructuredResponse(responseText);
|
|
163
|
+
return responseText;
|
|
164
|
+
}
|
|
165
|
+
addToConversationHistory(agent, message, fromSelf = false, developer = false) {
|
|
166
|
+
if (!agent.history) {
|
|
167
|
+
agent.history = [];
|
|
168
|
+
}
|
|
169
|
+
if (!message)
|
|
170
|
+
return;
|
|
171
|
+
let role = fromSelf ? 'assistant' : 'user';
|
|
172
|
+
if (developer)
|
|
173
|
+
role = 'system';
|
|
174
|
+
agent.history.push({
|
|
175
|
+
role: role,
|
|
176
|
+
content: message,
|
|
177
|
+
});
|
|
178
|
+
agent.trimHistoryIfNeeded();
|
|
179
|
+
}
|
|
180
|
+
computeMessageCost(agent, usage, modelInfo) {
|
|
181
|
+
const promptTokens = usage.prompt_tokens || 0;
|
|
182
|
+
const completionTokens = usage.completion_tokens || 0;
|
|
183
|
+
agent.totalInputTokens += promptTokens;
|
|
184
|
+
agent.totalOutputTokens += completionTokens;
|
|
185
|
+
if (!modelInfo) {
|
|
186
|
+
logger_1.logger.debug(`No price info for self-hosted model ${agent.modelName}; tokens tracked, no cost charged.`);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
const inputCost = promptTokens * (modelInfo.input_cost_per_token || 0);
|
|
190
|
+
const outputCost = completionTokens * (modelInfo.output_cost_per_token || 0);
|
|
191
|
+
const markup = agent.disableMarkup ? 0 : outputCost * agent.markupRate;
|
|
192
|
+
const cost = inputCost + outputCost + markup;
|
|
193
|
+
agent.totalCost += cost;
|
|
194
|
+
agent.totalMarkup += markup;
|
|
195
|
+
logger_1.logger.log(`Cost for ${agent.agentName} message: ${cost} (markup: ${markup.toFixed(4)})`);
|
|
196
|
+
if (agent.balanceService && cost > 0) {
|
|
197
|
+
agent.balanceService.decrementBalance(cost, markup);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
exports.SelfHostedAiService = SelfHostedAiService;
|
|
202
|
+
exports.SelfHostedAiService = SelfHostedAiService = __decorate([
|
|
203
|
+
(0, common_1.Injectable)(),
|
|
204
|
+
__metadata("design:paramtypes", [])
|
|
205
|
+
], SelfHostedAiService);
|
|
@@ -148,6 +148,8 @@ let AgentStoreService = class AgentStoreService {
|
|
|
148
148
|
instance.markupRate = template.markupRate;
|
|
149
149
|
instance.smallModelName = template.smallModelName;
|
|
150
150
|
instance.toolNames = [...template.toolNames];
|
|
151
|
+
instance.useModerator = template.useModerator;
|
|
152
|
+
instance.isControlledByHuman = template.isControlledByHuman;
|
|
151
153
|
this.storeAgent(instance);
|
|
152
154
|
return instanceId;
|
|
153
155
|
}
|
|
@@ -192,11 +194,9 @@ let AgentStoreService = class AgentStoreService {
|
|
|
192
194
|
instance.promptCacheTTL = template.promptCacheTTL;
|
|
193
195
|
instance.markupRate = template.markupRate;
|
|
194
196
|
instance.toolNames = [...template.toolNames];
|
|
197
|
+
instance.useModerator = template.useModerator;
|
|
198
|
+
instance.isControlledByHuman = template.isControlledByHuman;
|
|
195
199
|
instance.history = [];
|
|
196
|
-
instance.totalInputTokens = 0;
|
|
197
|
-
instance.totalOutputTokens = 0;
|
|
198
|
-
instance.totalCost = 0;
|
|
199
|
-
instance.totalMarkup = 0;
|
|
200
200
|
instance.aiService = this.aiFactoryService.createAiService(instance.serviceName);
|
|
201
201
|
this.storeAgent(instance);
|
|
202
202
|
}
|
|
@@ -261,6 +261,7 @@ let AgentStoreService = class AgentStoreService {
|
|
|
261
261
|
agent.maxHistoryMessages = config.maxHistoryMessages || undefined;
|
|
262
262
|
agent.promptCacheTTL = Number(config.promptCacheTTL) ?? 0;
|
|
263
263
|
agent.toolNames = config.toolNames || [];
|
|
264
|
+
agent.useModerator = config.useModerator || false;
|
|
264
265
|
agent.id = config.id;
|
|
265
266
|
this.agents.set(config.id, agent);
|
|
266
267
|
if (config.attachedFiles && config.attachedFiles.length > 0) {
|
|
@@ -339,6 +340,7 @@ let AgentStoreService = class AgentStoreService {
|
|
|
339
340
|
promptCacheTTL: agent.promptCacheTTL,
|
|
340
341
|
ownerRoomId: agent.ownerRoomId,
|
|
341
342
|
toolNames: agent.toolNames,
|
|
343
|
+
useModerator: agent.useModerator,
|
|
342
344
|
};
|
|
343
345
|
const filePath = path.join(storageDir, `${agent.id}.json`);
|
|
344
346
|
fs.writeFileSync(filePath, JSON.stringify(config, null, 2), 'utf-8');
|
|
@@ -51,6 +51,7 @@ export declare class Agent {
|
|
|
51
51
|
isControlledByHuman: boolean;
|
|
52
52
|
beginInstruction: string;
|
|
53
53
|
toolNames: string[];
|
|
54
|
+
useModerator: boolean;
|
|
54
55
|
promptCacheTTL: number;
|
|
55
56
|
private onStateChange;
|
|
56
57
|
storageDir: string;
|
|
@@ -68,11 +69,17 @@ export declare class Agent {
|
|
|
68
69
|
canRespond(message: Message): boolean;
|
|
69
70
|
getFormattedMessages(fromIndex?: number): string[];
|
|
70
71
|
getRawMessages(): string[];
|
|
72
|
+
private static readonly HISTORY_OMITTED_FIELDS;
|
|
73
|
+
private static formatMessageForHistory;
|
|
71
74
|
addToConversationHistory(message: any, fromSelf?: boolean): void;
|
|
72
75
|
trimHistoryIfNeeded(threshold?: number): void;
|
|
76
|
+
hasPrompt(name: string): boolean;
|
|
73
77
|
instructedPrompt(prompt: string, instructionFileName: string, variables: any, saveResponse?: boolean, cacheMessage?: boolean, maxOutputChars?: number): Promise<any>;
|
|
74
78
|
preparedPrompt(promptFileName: string, variables: any, saveResponse?: boolean, cacheMessage?: boolean): Promise<any>;
|
|
75
79
|
withSmallModel<T>(fn: () => Promise<T>): Promise<T>;
|
|
80
|
+
static compactionThresholdChars(): number;
|
|
81
|
+
historyChars(): number;
|
|
82
|
+
needsCompaction(): boolean;
|
|
76
83
|
compact(): Promise<{
|
|
77
84
|
success: boolean;
|
|
78
85
|
originalLength: number;
|
|
@@ -49,6 +49,7 @@ class Agent {
|
|
|
49
49
|
isControlledByHuman = false;
|
|
50
50
|
beginInstruction = '';
|
|
51
51
|
toolNames = [];
|
|
52
|
+
useModerator = false;
|
|
52
53
|
promptCacheTTL = 0;
|
|
53
54
|
onStateChange = null;
|
|
54
55
|
storageDir;
|
|
@@ -138,6 +139,20 @@ class Agent {
|
|
|
138
139
|
}
|
|
139
140
|
return this.history.map((message) => message.content);
|
|
140
141
|
}
|
|
142
|
+
static HISTORY_OMITTED_FIELDS = ['timestamp', 'index', 'situation'];
|
|
143
|
+
static formatMessageForHistory(message) {
|
|
144
|
+
const compact = {};
|
|
145
|
+
for (const [field, value] of Object.entries(message)) {
|
|
146
|
+
if (Agent.HISTORY_OMITTED_FIELDS.includes(field))
|
|
147
|
+
continue;
|
|
148
|
+
if (value === undefined || value === null || value === '')
|
|
149
|
+
continue;
|
|
150
|
+
if (Array.isArray(value) && value.length === 0)
|
|
151
|
+
continue;
|
|
152
|
+
compact[field] = value;
|
|
153
|
+
}
|
|
154
|
+
return JSON.stringify(compact);
|
|
155
|
+
}
|
|
141
156
|
addToConversationHistory(message, fromSelf = false) {
|
|
142
157
|
let formattedMessage = message;
|
|
143
158
|
if (typeof message === 'object') {
|
|
@@ -145,7 +160,7 @@ class Agent {
|
|
|
145
160
|
formattedMessage = `From: ${message.sender}\n${message.content}`;
|
|
146
161
|
}
|
|
147
162
|
else {
|
|
148
|
-
formattedMessage =
|
|
163
|
+
formattedMessage = Agent.formatMessageForHistory(message);
|
|
149
164
|
}
|
|
150
165
|
}
|
|
151
166
|
this.aiService.addToConversationHistory(this, formattedMessage, fromSelf);
|
|
@@ -171,6 +186,11 @@ class Agent {
|
|
|
171
186
|
this.history = [...this.history.slice(0, systemMessageCount), ...keepMessages];
|
|
172
187
|
}
|
|
173
188
|
}
|
|
189
|
+
hasPrompt(name) {
|
|
190
|
+
if (!this.aiService || !this.userPaths)
|
|
191
|
+
return false;
|
|
192
|
+
return this.aiService.hasPromptFile(this, name);
|
|
193
|
+
}
|
|
174
194
|
async instructedPrompt(prompt, instructionFileName, variables, saveResponse = true, cacheMessage = false, maxOutputChars = 0) {
|
|
175
195
|
return await this.aiService.instructedPrompt(this, prompt, instructionFileName, variables, saveResponse, this.aiService.getCacheConfig(this, cacheMessage), maxOutputChars);
|
|
176
196
|
}
|
|
@@ -190,10 +210,21 @@ class Agent {
|
|
|
190
210
|
this.modelName = original;
|
|
191
211
|
}
|
|
192
212
|
}
|
|
213
|
+
static compactionThresholdChars() {
|
|
214
|
+
return Number(process.env.AGENT_COMPACTION_THRESHOLD) || 100000;
|
|
215
|
+
}
|
|
216
|
+
historyChars() {
|
|
217
|
+
return (this.history ?? []).reduce((sum, m) => sum + (m?.content?.length || 0), 0);
|
|
218
|
+
}
|
|
219
|
+
needsCompaction() {
|
|
220
|
+
if (this.maxHistoryMessages)
|
|
221
|
+
return false;
|
|
222
|
+
return this.historyChars() > Agent.compactionThresholdChars();
|
|
223
|
+
}
|
|
193
224
|
async compact() {
|
|
194
225
|
const originalHistory = [...(this.history || [])];
|
|
195
226
|
const originalLength = originalHistory.length;
|
|
196
|
-
const originalChars =
|
|
227
|
+
const originalChars = this.historyChars();
|
|
197
228
|
if (originalLength === 0) {
|
|
198
229
|
return {
|
|
199
230
|
success: true,
|
|
@@ -17,6 +17,8 @@ const together_module_1 = require("./LLM/together.module");
|
|
|
17
17
|
const mock_module_1 = require("./LLM/mock.module");
|
|
18
18
|
const googleai_module_1 = require("./LLM/googleai.module");
|
|
19
19
|
const fal_module_1 = require("./LLM/fal.module");
|
|
20
|
+
const comfyui_module_1 = require("./LLM/comfyui.module");
|
|
21
|
+
const self_hosted_module_1 = require("./LLM/self-hosted.module");
|
|
20
22
|
let AiFactoryModule = class AiFactoryModule {
|
|
21
23
|
};
|
|
22
24
|
exports.AiFactoryModule = AiFactoryModule;
|
|
@@ -31,6 +33,8 @@ exports.AiFactoryModule = AiFactoryModule = __decorate([
|
|
|
31
33
|
mock_module_1.MockAiModule,
|
|
32
34
|
googleai_module_1.GoogleAiModule,
|
|
33
35
|
fal_module_1.FalAiModule,
|
|
36
|
+
comfyui_module_1.ComfyUiModule,
|
|
37
|
+
self_hosted_module_1.SelfHostedModule,
|
|
34
38
|
],
|
|
35
39
|
providers: [ai_factory_service_1.AiFactoryService],
|
|
36
40
|
exports: [ai_factory_service_1.AiFactoryService],
|
|
@@ -7,6 +7,8 @@ import { TogetherAiService } from './LLM/together.service';
|
|
|
7
7
|
import { MockAiService } from './LLM/mock.service';
|
|
8
8
|
import { GoogleAiService } from './LLM/googleai.service';
|
|
9
9
|
import { FalAiService } from './LLM/fal.service';
|
|
10
|
+
import { ComfyUiAiService } from './LLM/comfyui.service';
|
|
11
|
+
import { SelfHostedAiService } from './LLM/self-hosted.service';
|
|
10
12
|
export declare class AiFactoryService {
|
|
11
13
|
private readonly openAiService;
|
|
12
14
|
private readonly grokAiService;
|
|
@@ -16,7 +18,9 @@ export declare class AiFactoryService {
|
|
|
16
18
|
private readonly mockAiService;
|
|
17
19
|
private readonly googleAiService;
|
|
18
20
|
private readonly falAiService;
|
|
19
|
-
|
|
21
|
+
private readonly comfyUiAiService;
|
|
22
|
+
private readonly selfHostedAiService;
|
|
23
|
+
constructor(openAiService: OpenAiService, grokAiService: GrokAiService, anthropicAiService: AnthropicAiService, deepSeekAiService: DeepSeekAiService, togetherAiService: TogetherAiService, mockAiService: MockAiService, googleAiService: GoogleAiService, falAiService: FalAiService, comfyUiAiService: ComfyUiAiService, selfHostedAiService: SelfHostedAiService);
|
|
20
24
|
createAiService(serviceName: string): BaseAiService;
|
|
21
25
|
getAllAiServices(): BaseAiService[];
|
|
22
26
|
}
|