briyah 1.0.6 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +32 -22
  2. package/dist/server/src/ai/LLM/anthropic.service.js +19 -15
  3. package/dist/server/src/ai/LLM/base-ai.service.js +5 -4
  4. package/dist/server/src/ai/LLM/deepseek.service.js +11 -13
  5. package/dist/server/src/ai/LLM/fal.service.js +20 -24
  6. package/dist/server/src/ai/LLM/googleai.service.js +13 -15
  7. package/dist/server/src/ai/LLM/grok.service.js +12 -14
  8. package/dist/server/src/ai/LLM/mock.service.js +9 -11
  9. package/dist/server/src/ai/LLM/openai.service.js +18 -20
  10. package/dist/server/src/ai/LLM/together.service.js +14 -13
  11. package/dist/server/src/ai/LLM/vertexai.service.js +12 -14
  12. package/dist/server/src/ai/agent-store.service.js +12 -11
  13. package/dist/server/src/ai/artifact.service.js +7 -6
  14. package/dist/server/src/ai/attached-file.service.js +8 -7
  15. package/dist/server/src/ai/model_prices.d.ts +1 -2
  16. package/dist/server/src/ai/model_prices.js +15 -14
  17. package/dist/server/src/ai/published-agents.service.js +6 -5
  18. package/dist/server/src/app/balance.service.js +7 -6
  19. package/dist/server/src/app/stripe.controller.js +12 -11
  20. package/dist/server/src/app/stripe.service.js +20 -19
  21. package/dist/server/src/app/transaction.service.js +6 -5
  22. package/dist/server/src/app/user-service-manager.js +6 -5
  23. package/dist/server/src/app.controller.js +95 -94
  24. package/dist/server/src/app.service.js +31 -30
  25. package/dist/server/src/auth/auth.controller.js +21 -20
  26. package/dist/server/src/auth/jwt-auth.guard.js +4 -3
  27. package/dist/server/src/auth/rate-limit.service.d.ts +0 -1
  28. package/dist/server/src/auth/rate-limit.service.js +6 -7
  29. package/dist/server/src/auth/twilio.service.js +4 -3
  30. package/dist/server/src/auth/users.service.js +6 -5
  31. package/dist/server/src/common/logger.d.ts +21 -0
  32. package/dist/server/src/common/logger.js +83 -0
  33. package/dist/server/src/config/configuration.service.js +1 -1
  34. package/dist/server/src/room/artifact-store.service.d.ts +0 -1
  35. package/dist/server/src/room/artifact-store.service.js +16 -17
  36. package/dist/server/src/room/published-rooms.service.js +5 -3
  37. package/dist/server/src/room/room-store.service.js +17 -16
  38. package/dist/server/src/room/room.js +14 -13
  39. package/dist/server/src/sdk/briyah-config.d.ts +7 -0
  40. package/dist/server/src/sdk/briyah-config.js +2 -0
  41. package/dist/server/src/sdk/briyah.js +14 -5
  42. package/dist/server/src/sdk/index.d.ts +2 -1
  43. package/dist/server/src/story/story-progress.service.js +2 -1
  44. package/dist/server/src/story/story-store.service.js +28 -27
  45. package/dist/server/src/story/story.service.js +113 -112
  46. package/docs/.nojekyll +1 -0
  47. package/docs/assets/hierarchy.js +1 -0
  48. package/docs/assets/highlight.css +106 -0
  49. package/docs/assets/icons.js +18 -0
  50. package/docs/assets/icons.svg +1 -0
  51. package/docs/assets/main.js +60 -0
  52. package/docs/assets/navigation.js +1 -0
  53. package/docs/assets/search.js +1 -0
  54. package/docs/assets/style.css +1633 -0
  55. package/docs/classes/Agent.html +87 -0
  56. package/docs/classes/Briyah.html +64 -0
  57. package/docs/classes/BriyahConfigService.html +12 -0
  58. package/docs/classes/Room.html +119 -0
  59. package/docs/enums/MessageAction.html +13 -0
  60. package/docs/hierarchy.html +1 -0
  61. package/docs/index.html +136 -0
  62. package/docs/interfaces/AgentInfo.html +17 -0
  63. package/docs/interfaces/AgentMessagesResponse.html +5 -0
  64. package/docs/interfaces/AppService.html +680 -0
  65. package/docs/interfaces/ArtifactMetadata.html +8 -0
  66. package/docs/interfaces/AttachDocumentResponse.html +3 -0
  67. package/docs/interfaces/BriyahConfigOptions.html +16 -0
  68. package/docs/interfaces/ChapterInfo.html +3 -0
  69. package/docs/interfaces/Character.html +7 -0
  70. package/docs/interfaces/CreateAgentResponse.html +2 -0
  71. package/docs/interfaces/CreateRoomResponse.html +3 -0
  72. package/docs/interfaces/CreateStoryResponse.html +2 -0
  73. package/docs/interfaces/FileList.html +2 -0
  74. package/docs/interfaces/LoggingOptions.html +9 -0
  75. package/docs/interfaces/Message.html +6 -0
  76. package/docs/interfaces/ModelInfo.html +5 -0
  77. package/docs/interfaces/PreparedPromptResponse.html +3 -0
  78. package/docs/interfaces/ProcessTextResponse.html +7 -0
  79. package/docs/interfaces/PromptFile.html +3 -0
  80. package/docs/interfaces/PromptFileContent.html +3 -0
  81. package/docs/interfaces/PromptFilesResponse.html +2 -0
  82. package/docs/interfaces/PromptFolder.html +3 -0
  83. package/docs/interfaces/PromptFoldersResponse.html +2 -0
  84. package/docs/interfaces/RoomDetails.html +9 -0
  85. package/docs/interfaces/RoomInfo.html +5 -0
  86. package/docs/interfaces/RoomMessagesResponse.html +3 -0
  87. package/docs/interfaces/StoryIdea.html +5 -0
  88. package/docs/interfaces/StoryInfo.html +21 -0
  89. package/docs/interfaces/StoryState.html +9 -0
  90. package/docs/modules.html +1 -0
  91. package/docs/types/PromptScope.html +1 -0
  92. package/package.json +6 -3
  93. package/data/common/config/story_ideas.txt +0 -6
package/README.md CHANGED
@@ -34,10 +34,10 @@ const appService = briyah.getAppService('user-123');
34
34
  // Call agent.save() when you want to persist it to disk.
35
35
  const agent = appService.createAgent(
36
36
  'Anthropic',
37
- 'Assistant',
38
- 'Assistant',
37
+ 'AI Assistant',
38
+ 'James',
39
39
  'A helpful AI assistant',
40
- 'claude-3-5-sonnet-20241022'
40
+ 'claude-haiku-4-5'
41
41
  );
42
42
 
43
43
  if (!agent.id) throw new Error('Agent creation failed');
@@ -58,7 +58,7 @@ await briyah.shutdown();
58
58
  interface BriyahConfigOptions {
59
59
  /**
60
60
  * Base directory for Briyah data storage
61
- * Default: './data' relative to process.cwd()
61
+ * Default: './briyah-data' relative to process.cwd()
62
62
  */
63
63
  dataPath?: string;
64
64
 
@@ -84,11 +84,6 @@ interface BriyahConfigOptions {
84
84
 
85
85
  ### Environment Variables
86
86
 
87
- Briyah requires certain environment variables to be set:
88
-
89
- **Required:**
90
- - `STARTING_BALANCE` - Starting balance for new users (e.g., "10.00")
91
-
92
87
  **LLM Provider API Keys** (at least one required):
93
88
  - `ANTHROPIC_API_KEY` - For Claude models
94
89
  - `OPENAI_API_KEY` - For GPT models
@@ -98,9 +93,32 @@ Briyah requires certain environment variables to be set:
98
93
  - `TOGETHER_API_KEY` - For Together AI models
99
94
 
100
95
  **Optional:**
96
+ - `STARTING_BALANCE` - Starting balance for new users (e.g., "10.00")
101
97
  - `SERVER_DATA_PATH` - Global default data path (overridden by constructor `dataPath`)
102
98
  - `USER_SERVICE_CACHE_TIMEOUT_MINUTES` - Cache timeout (overridden by constructor option)
103
99
 
100
+ ### Logging
101
+
102
+ Briyah writes logs to `{dataPath}/logs/briyah.log` by default. Configure or disable via the `logging` option:
103
+
104
+ ```typescript
105
+ const briyah = new Briyah({
106
+ dataPath: './my-data',
107
+ logging: {
108
+ enabled: true, // default
109
+ logFile: './my-data/logs/app.log', // default: {dataPath}/logs/briyah.log
110
+ console: false, // set true to also log to stdout/stderr
111
+ level: 'warn', // 'debug' | 'log' | 'warn' | 'error' — default: 'log'
112
+ }
113
+ });
114
+
115
+ // Log to console only (no file):
116
+ const briyah = new Briyah({ logging: { console: true, logFile: null } });
117
+
118
+ // Disable logging entirely:
119
+ const briyah = new Briyah({ logging: { enabled: false } });
120
+ ```
121
+
104
122
  ## API Reference
105
123
 
106
124
  ### Briyah Class
@@ -282,10 +300,10 @@ const appService = briyah.getAppService('user-123');
282
300
  // Create an agent
283
301
  const agent = appService.createAgent(
284
302
  'Anthropic', // provider
285
- 'Assistant', // name
286
- 'Assistant', // nickname
287
- 'Helpful AI', // description
288
- 'claude-3-5-sonnet-20241022' // model
303
+ 'AI Assistant', // name
304
+ 'James', // nickname
305
+ 'A helpful AI assistant', // description
306
+ 'claude-haiku-4-5' // model
289
307
  );
290
308
 
291
309
  if (!agent.id) throw new Error('Agent creation failed');
@@ -309,7 +327,7 @@ const appService = briyah.getAppService('user-123');
309
327
 
310
328
  // Create agents
311
329
  const analyst = appService.createAgent('OpenAI', 'Analyst', 'Analyst', 'Data analyst', 'gpt-4');
312
- const writer = appService.createAgent('Anthropic', 'Writer', 'Writer', 'Content writer', 'claude-3-5-sonnet-20241022');
330
+ const writer = appService.createAgent('Anthropic', 'Writer', 'Writer', 'Content writer', 'claude-haiku-4-5');
313
331
 
314
332
  if (!analyst.id || !writer.id) throw new Error('Agent creation failed');
315
333
 
@@ -375,10 +393,6 @@ const user2Service = briyah2.getAppService('user-123');
375
393
 
376
394
  **Note:** Singleton services (LLM providers, message emitters) are shared across all Briyah instances within the same process. This is safe because they are stateless or keyed by ID.
377
395
 
378
- ## Backward Compatibility
379
-
380
- The Briyah SDK is fully backward compatible with the existing NestJS application. The NestJS app continues to work without any changes, while new applications can use the SDK for simplified integration.
381
-
382
396
  ## Troubleshooting
383
397
 
384
398
  ### "Must call init() before getAppService()"
@@ -396,7 +410,3 @@ Set the `STARTING_BALANCE` environment variable or pass `startingBalance` in the
396
410
  ### Cache not working as expected
397
411
 
398
412
  Check the cache statistics with `getCacheStats()` and adjust `userServiceCacheTimeoutMinutes` in the constructor options.
399
-
400
- ## Support
401
-
402
- For issues or questions, please refer to the main Briyah documentation or create an issue in the repository.
@@ -8,16 +8,14 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
8
8
  var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
10
  };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
11
  Object.defineProperty(exports, "__esModule", { value: true });
15
12
  exports.AnthropicAiService = void 0;
16
13
  const common_1 = require("@nestjs/common");
17
14
  const sdk_1 = require("@anthropic-ai/sdk");
18
15
  const base_ai_service_1 = require("./base-ai.service");
19
- const model_prices_1 = __importDefault(require("../model_prices"));
16
+ const model_prices_1 = require("../model_prices");
20
17
  const errors_1 = require("../../common/errors");
18
+ const logger_1 = require("../../common/logger");
21
19
  let AnthropicAiService = class AnthropicAiService extends base_ai_service_1.BaseAiService {
22
20
  anthropic;
23
21
  constructor() {
@@ -25,7 +23,6 @@ let AnthropicAiService = class AnthropicAiService extends base_ai_service_1.Base
25
23
  try {
26
24
  const apiKey = process.env['ANTHROPIC_API_KEY'];
27
25
  if (!apiKey) {
28
- console.warn('ANTHROPIC_API_KEY environment variable not set. Anthropic service will not be available.');
29
26
  this._isAvailable = false;
30
27
  return;
31
28
  }
@@ -34,9 +31,10 @@ let AnthropicAiService = class AnthropicAiService extends base_ai_service_1.Base
34
31
  timeout: 1200000,
35
32
  maxRetries: 3,
36
33
  });
34
+ logger_1.logger.debug('Anthropic service initialized successfully');
37
35
  }
38
36
  catch (error) {
39
- console.error('Error initializing Anthropic service:', error);
37
+ logger_1.logger.error('Error initializing Anthropic service:', error);
40
38
  this._isAvailable = false;
41
39
  }
42
40
  }
@@ -74,7 +72,7 @@ let AnthropicAiService = class AnthropicAiService extends base_ai_service_1.Base
74
72
  }));
75
73
  }
76
74
  catch (error) {
77
- console.error('Error fetching Anthropic models:', error);
75
+ logger_1.logger.error('Error fetching Anthropic models:', error);
78
76
  }
79
77
  }
80
78
  addToConversationHistory(agent, message, fromSelf = false) {
@@ -193,7 +191,7 @@ let AnthropicAiService = class AnthropicAiService extends base_ai_service_1.Base
193
191
  thinkingTokens = 2048;
194
192
  else if (agent.reasoningEffort === 'high')
195
193
  thinkingTokens = 4096;
196
- const modelInfo = model_prices_1.default[agent.modelName];
194
+ const modelInfo = (0, model_prices_1.getModelPrices)()[agent.modelName];
197
195
  if (modelInfo && !modelInfo.supports_reasoning)
198
196
  thinkingTokens = 0;
199
197
  let maxOutputTokens;
@@ -245,8 +243,8 @@ let AnthropicAiService = class AnthropicAiService extends base_ai_service_1.Base
245
243
  }
246
244
  catch (parseError) {
247
245
  lastError = parseError;
248
- console.warn(`JSON parse attempt ${attempt}/${maxRetries} failed:`, parseError);
249
- console.warn('Raw response:', responseText);
246
+ logger_1.logger.warn(`JSON parse attempt ${attempt}/${maxRetries} failed:`, parseError);
247
+ logger_1.logger.warn('Raw response:', responseText);
250
248
  if (attempt < maxRetries) {
251
249
  const retryMessage = `Your previous response was not valid JSON. Please respond with ONLY valid JSON that can be parsed. No explanatory text, no markdown, no formatting - just pure JSON that conforms to the schema. Here was the parsing error: ${parseError.message}`;
252
250
  messages.push({
@@ -283,7 +281,13 @@ let AnthropicAiService = class AnthropicAiService extends base_ai_service_1.Base
283
281
  }
284
282
  catch (apiError) {
285
283
  lastError = apiError;
286
- console.error(`API call attempt ${attempt}/${maxRetries} failed:`, apiError);
284
+ if (apiError.status === 404) {
285
+ const innerError = apiError.error?.error;
286
+ const errorType = innerError?.type ?? 'not_found_error';
287
+ const errorMessage = innerError?.message ?? apiError.message;
288
+ throw new Error(`${errorType}: ${errorMessage}`);
289
+ }
290
+ logger_1.logger.error(`API call attempt ${attempt}/${maxRetries} failed:`, apiError);
287
291
  if (attempt < maxRetries) {
288
292
  await new Promise((resolve) => setTimeout(resolve, 1000 * attempt));
289
293
  }
@@ -292,9 +296,9 @@ let AnthropicAiService = class AnthropicAiService extends base_ai_service_1.Base
292
296
  throw new Error(`Failed to get valid response after ${maxRetries} attempts. Last error: ${lastError?.message || 'Unknown error'}`);
293
297
  }
294
298
  computeMessageCost(agent, usage) {
295
- const modelInfo = model_prices_1.default[agent.modelName];
299
+ const modelInfo = (0, model_prices_1.getModelPrices)()[agent.modelName];
296
300
  if (!modelInfo) {
297
- console.error(`No price info found for model ${agent.modelName}`);
301
+ logger_1.logger.error(`No price info found for model ${agent.modelName}`);
298
302
  return 0;
299
303
  }
300
304
  const cacheCreationTokens = usage.cache_creation_input_tokens || 0;
@@ -313,12 +317,12 @@ let AnthropicAiService = class AnthropicAiService extends base_ai_service_1.Base
313
317
  agent.totalOutputTokens += outputTokens;
314
318
  agent.totalCost += cost;
315
319
  agent.totalMarkup += markup;
316
- console.log(`Cost for ${agent.agentName} message: ${cost.toFixed(4)}, markup: ${markup.toFixed(4)}`);
320
+ logger_1.logger.log(`Cost for ${agent.agentName} message: ${cost.toFixed(4)}, markup: ${markup.toFixed(4)}`);
317
321
  if (agent.balanceService && cost > 0) {
318
322
  agent.balanceService.decrementBalance(cost, markup);
319
323
  }
320
324
  if (cacheCreationTokens > 0 || cacheReadTokens > 0) {
321
- console.log(`Cache metrics for ${agent.agentName}: creation=${cacheCreationTokens}, read=${cacheReadTokens}, standard=${standardInputTokens}`);
325
+ logger_1.logger.log(`Cache metrics for ${agent.agentName}: creation=${cacheCreationTokens}, read=${cacheReadTokens}, standard=${standardInputTokens}`);
322
326
  }
323
327
  }
324
328
  };
@@ -50,6 +50,7 @@ const fs_1 = require("fs");
50
50
  const fs = __importStar(require("fs"));
51
51
  const handlebars_1 = require("handlebars");
52
52
  const errors_1 = require("../../common/errors");
53
+ const logger_1 = require("../../common/logger");
53
54
  let BaseAiService = class BaseAiService {
54
55
  modelsCache = null;
55
56
  _isAvailable = true;
@@ -112,7 +113,7 @@ let BaseAiService = class BaseAiService {
112
113
  return JSON.parse(jsonSchemaString);
113
114
  }
114
115
  catch (error) {
115
- console.error(`Error parsing JSON schema from ${jsonSchemaFile}:`, error);
116
+ logger_1.logger.error(`Error parsing JSON schema from ${jsonSchemaFile}:`, error);
116
117
  return null;
117
118
  }
118
119
  }
@@ -129,7 +130,7 @@ let BaseAiService = class BaseAiService {
129
130
  return models;
130
131
  }
131
132
  catch (error) {
132
- console.error(`Error fetching models for ${this.getServiceName()}:`, error);
133
+ logger_1.logger.error(`Error fetching models for ${this.getServiceName()}:`, error);
133
134
  throw error;
134
135
  }
135
136
  }
@@ -154,7 +155,7 @@ let BaseAiService = class BaseAiService {
154
155
  systemInstructionPrompt = (0, fs_1.readFileSync)(systemInstructionFile).toString('utf8');
155
156
  }
156
157
  catch (error) {
157
- console.error(`Error reading system instruction from ${systemInstructionFile}:`, error);
158
+ logger_1.logger.error(`Error reading system instruction from ${systemInstructionFile}:`, error);
158
159
  systemInstructionPrompt = null;
159
160
  }
160
161
  }
@@ -261,7 +262,7 @@ let BaseAiService = class BaseAiService {
261
262
  return `Document attached: ${fileName}`;
262
263
  }
263
264
  catch (error) {
264
- console.error(`Error attaching document in ${this.getServiceName()} service:`, error);
265
+ logger_1.logger.error(`Error attaching document in ${this.getServiceName()} service:`, error);
265
266
  throw new Error(`Error attaching document: ${error.message}`);
266
267
  }
267
268
  }
@@ -8,9 +8,6 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
8
8
  var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
10
  };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
11
  Object.defineProperty(exports, "__esModule", { value: true });
15
12
  exports.DeepSeekAiService = void 0;
16
13
  const common_1 = require("@nestjs/common");
@@ -18,8 +15,9 @@ const deepseek_1 = require("@ai-sdk/deepseek");
18
15
  const ai_1 = require("ai");
19
16
  const base_ai_service_1 = require("./base-ai.service");
20
17
  const zod_1 = require("zod");
21
- const model_prices_1 = __importDefault(require("../model_prices"));
18
+ const model_prices_1 = require("../model_prices");
22
19
  const errors_1 = require("../../common/errors");
20
+ const logger_1 = require("../../common/logger");
23
21
  let DeepSeekAiService = class DeepSeekAiService extends base_ai_service_1.BaseAiService {
24
22
  deepseekClient;
25
23
  constructor() {
@@ -27,16 +25,16 @@ let DeepSeekAiService = class DeepSeekAiService extends base_ai_service_1.BaseAi
27
25
  try {
28
26
  const apiKey = process.env['DEEPSEEK_API_KEY'];
29
27
  if (!apiKey) {
30
- console.warn('DEEPSEEK_API_KEY environment variable not set. DeepSeek service will not be available.');
31
28
  this._isAvailable = false;
32
29
  return;
33
30
  }
34
31
  this.deepseekClient = (0, deepseek_1.createDeepSeek)({
35
32
  apiKey: apiKey,
36
33
  });
34
+ logger_1.logger.debug('DeepSeek service initialized successfully');
37
35
  }
38
36
  catch (error) {
39
- console.error('Error initializing DeepSeek service:', error);
37
+ logger_1.logger.error('Error initializing DeepSeek service:', error);
40
38
  this._isAvailable = false;
41
39
  }
42
40
  }
@@ -70,7 +68,7 @@ let DeepSeekAiService = class DeepSeekAiService extends base_ai_service_1.BaseAi
70
68
  });
71
69
  }
72
70
  catch (error) {
73
- console.error('Error fetching DeepSeek models from API:', error);
71
+ logger_1.logger.error('Error fetching DeepSeek models from API:', error);
74
72
  throw error;
75
73
  }
76
74
  }
@@ -230,7 +228,7 @@ let DeepSeekAiService = class DeepSeekAiService extends base_ai_service_1.BaseAi
230
228
  }
231
229
  }
232
230
  catch (error) {
233
- console.error('Error generating response from DeepSeek:', error);
231
+ logger_1.logger.error('Error generating response from DeepSeek:', error);
234
232
  throw error;
235
233
  }
236
234
  }
@@ -245,12 +243,12 @@ let DeepSeekAiService = class DeepSeekAiService extends base_ai_service_1.BaseAi
245
243
  const cachedTokens = usage.cachedInputTokens || 0;
246
244
  const uncachedInputTokens = totalInputTokens - cachedTokens;
247
245
  const outputTokens = usage.outputTokens || 0;
248
- let modelInfo = model_prices_1.default[agent.modelName];
246
+ let modelInfo = (0, model_prices_1.getModelPrices)()[agent.modelName];
249
247
  if (!modelInfo && !agent.modelName.startsWith('deepseek/')) {
250
- modelInfo = model_prices_1.default[`deepseek/${agent.modelName}`];
248
+ modelInfo = (0, model_prices_1.getModelPrices)()[`deepseek/${agent.modelName}`];
251
249
  }
252
250
  if (!modelInfo) {
253
- console.error(`No price info found for model ${agent.modelName} or deepseek/${agent.modelName}`);
251
+ logger_1.logger.error(`No price info found for model ${agent.modelName} or deepseek/${agent.modelName}`);
254
252
  return;
255
253
  }
256
254
  const uncachedCost = uncachedInputTokens * modelInfo.input_cost_per_token;
@@ -263,9 +261,9 @@ let DeepSeekAiService = class DeepSeekAiService extends base_ai_service_1.BaseAi
263
261
  agent.totalOutputTokens += outputTokens;
264
262
  agent.totalCost += cost;
265
263
  agent.totalMarkup += markup;
266
- console.log(`Cost for ${agent.agentName} message: ${cost} (markup: ${markup.toFixed(4)})`);
264
+ logger_1.logger.log(`Cost for ${agent.agentName} message: ${cost} (markup: ${markup.toFixed(4)})`);
267
265
  if (cachedTokens > 0) {
268
- console.log(`Cache metrics for ${agent.agentName}: cached=${cachedTokens}, uncached=${uncachedInputTokens}`);
266
+ logger_1.logger.log(`Cache metrics for ${agent.agentName}: cached=${cachedTokens}, uncached=${uncachedInputTokens}`);
269
267
  }
270
268
  if (agent.balanceService && cost > 0) {
271
269
  agent.balanceService.decrementBalance(cost, markup);
@@ -8,31 +8,28 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
8
8
  var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
10
  };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
11
  Object.defineProperty(exports, "__esModule", { value: true });
15
12
  exports.FalAiService = void 0;
16
13
  const common_1 = require("@nestjs/common");
17
14
  const client_1 = require("@fal-ai/client");
18
15
  const base_ai_service_1 = require("./base-ai.service");
19
- const model_prices_1 = __importDefault(require("../model_prices"));
16
+ const model_prices_1 = require("../model_prices");
20
17
  const errors_1 = require("../../common/errors");
18
+ const logger_1 = require("../../common/logger");
21
19
  let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
22
20
  constructor() {
23
21
  super();
24
22
  try {
25
23
  const apiKey = process.env['FAL_API_KEY'];
26
24
  if (!apiKey) {
27
- console.warn('FAL_API_KEY environment variable not set. Fal AI service will not be available.');
28
25
  this._isAvailable = false;
29
26
  return;
30
27
  }
31
28
  client_1.fal.config({ credentials: apiKey });
32
- console.log('Fal AI service initialized successfully');
29
+ logger_1.logger.debug('FalAI service initialized successfully');
33
30
  }
34
31
  catch (error) {
35
- console.error('Error initializing Fal AI service:', error);
32
+ logger_1.logger.error('Error initializing Fal AI service:', error);
36
33
  this._isAvailable = false;
37
34
  }
38
35
  }
@@ -46,7 +43,6 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
46
43
  try {
47
44
  const apiKey = process.env['FAL_API_KEY'];
48
45
  if (!apiKey) {
49
- console.warn('FAL_API_KEY not set, cannot fetch models');
50
46
  return [];
51
47
  }
52
48
  const response = await fetch('https://api.fal.ai/v1/models', {
@@ -55,7 +51,7 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
55
51
  },
56
52
  });
57
53
  if (!response.ok) {
58
- console.error(`Fal API error: ${response.status} ${response.statusText}`);
54
+ logger_1.logger.error(`Fal API error: ${response.status} ${response.statusText}`);
59
55
  return [];
60
56
  }
61
57
  const data = await response.json();
@@ -70,11 +66,11 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
70
66
  });
71
67
  }
72
68
  }
73
- console.log(`Fetched ${models.length} active models from Fal AI`);
69
+ logger_1.logger.log(`Fetched ${models.length} active models from Fal AI`);
74
70
  return models;
75
71
  }
76
72
  catch (error) {
77
- console.error('Error fetching Fal AI models:', error);
73
+ logger_1.logger.error('Error fetching Fal AI models:', error);
78
74
  return [];
79
75
  }
80
76
  }
@@ -164,7 +160,7 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
164
160
  this.computeMessageCost(agent, usage, estimatedInputTokens, estimatedOutputTokens);
165
161
  }
166
162
  catch (error) {
167
- console.error('Error calling Fal AI:', error);
163
+ logger_1.logger.error('Error calling Fal AI:', error);
168
164
  if (error.message?.includes('authentication') ||
169
165
  error.message?.includes('unauthorized')) {
170
166
  throw new Error('Fal AI authentication failed. Check FAL_API_KEY.');
@@ -183,8 +179,8 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
183
179
  return JSON.parse(responseText);
184
180
  }
185
181
  catch (parseError) {
186
- console.error('Failed to parse JSON response:', parseError);
187
- console.error('Response text:', responseText);
182
+ logger_1.logger.error('Failed to parse JSON response:', parseError);
183
+ logger_1.logger.error('Response text:', responseText);
188
184
  throw new Error('Failed to parse JSON response from Fal AI');
189
185
  }
190
186
  }
@@ -193,12 +189,12 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
193
189
  computeMessageCost(agent, usage, estimatedInputTokens, estimatedOutputTokens) {
194
190
  const inputTokens = usage?.prompt_tokens || estimatedInputTokens || 0;
195
191
  const outputTokens = usage?.completion_tokens || estimatedOutputTokens || 0;
196
- let modelInfo = model_prices_1.default[agent.modelName];
192
+ let modelInfo = (0, model_prices_1.getModelPrices)()[agent.modelName];
197
193
  if (!modelInfo && !agent.modelName.startsWith('fal_ai/')) {
198
- modelInfo = model_prices_1.default[`fal_ai/${agent.modelName}`];
194
+ modelInfo = (0, model_prices_1.getModelPrices)()[`fal_ai/${agent.modelName}`];
199
195
  }
200
196
  if (!modelInfo) {
201
- console.warn(`No price info found for model ${agent.modelName}. Skipping cost tracking.`);
197
+ logger_1.logger.warn(`No price info found for model ${agent.modelName}. Skipping cost tracking.`);
202
198
  return;
203
199
  }
204
200
  const inputCost = inputTokens * (modelInfo.input_cost_per_token || 0);
@@ -210,29 +206,29 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
210
206
  agent.totalCost += cost;
211
207
  agent.totalMarkup += markup;
212
208
  if (!usage?.prompt_tokens) {
213
- console.log(`Cost for ${agent.agentName} message (estimated): ${cost.toFixed(4)} (markup: ${markup.toFixed(4)})`);
209
+ logger_1.logger.log(`Cost for ${agent.agentName} message (estimated): ${cost.toFixed(4)} (markup: ${markup.toFixed(4)})`);
214
210
  }
215
211
  else {
216
- console.log(`Cost for ${agent.agentName} message: ${cost.toFixed(4)} (markup: ${markup.toFixed(4)})`);
212
+ logger_1.logger.log(`Cost for ${agent.agentName} message: ${cost.toFixed(4)} (markup: ${markup.toFixed(4)})`);
217
213
  }
218
214
  if (agent.balanceService && cost > 0) {
219
215
  agent.balanceService.decrementBalance(cost, markup);
220
216
  }
221
217
  }
222
218
  computeImageCost(agent) {
223
- let modelInfo = model_prices_1.default[agent.modelName];
219
+ let modelInfo = (0, model_prices_1.getModelPrices)()[agent.modelName];
224
220
  if (!modelInfo && !agent.modelName.startsWith('fal_ai/')) {
225
- modelInfo = model_prices_1.default[`fal_ai/${agent.modelName}`];
221
+ modelInfo = (0, model_prices_1.getModelPrices)()[`fal_ai/${agent.modelName}`];
226
222
  }
227
223
  if (!modelInfo || !modelInfo.output_cost_per_image) {
228
- console.warn(`No image price info found for ${agent.modelName}. Skipping cost tracking.`);
224
+ logger_1.logger.warn(`No image price info found for ${agent.modelName}. Skipping cost tracking.`);
229
225
  return;
230
226
  }
231
227
  const cost = modelInfo.output_cost_per_image;
232
228
  const markup = 0;
233
229
  agent.totalCost += cost;
234
230
  agent.totalMarkup += markup;
235
- console.log(`Cost for image generation: ${cost.toFixed(4)} (markup: ${markup.toFixed(4)})`);
231
+ logger_1.logger.log(`Cost for image generation: ${cost.toFixed(4)} (markup: ${markup.toFixed(4)})`);
236
232
  if (agent.balanceService && cost > 0) {
237
233
  agent.balanceService.decrementBalance(cost, markup);
238
234
  }
@@ -302,7 +298,7 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
302
298
  return { artifactId };
303
299
  }
304
300
  catch (error) {
305
- console.error('Error generating image with Fal AI:', error.message || error);
301
+ logger_1.logger.error('Error generating image with Fal AI:', error.message || error);
306
302
  return { error };
307
303
  }
308
304
  }
@@ -8,16 +8,14 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
8
8
  var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
10
  };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
11
  Object.defineProperty(exports, "__esModule", { value: true });
15
12
  exports.GoogleAiService = void 0;
16
13
  const common_1 = require("@nestjs/common");
17
14
  const genai_1 = require("@google/genai");
18
15
  const base_ai_service_1 = require("./base-ai.service");
19
- const model_prices_1 = __importDefault(require("../model_prices"));
16
+ const model_prices_1 = require("../model_prices");
20
17
  const errors_1 = require("../../common/errors");
18
+ const logger_1 = require("../../common/logger");
21
19
  let GoogleAiService = class GoogleAiService extends base_ai_service_1.BaseAiService {
22
20
  googleAI = null;
23
21
  constructor() {
@@ -25,14 +23,14 @@ let GoogleAiService = class GoogleAiService extends base_ai_service_1.BaseAiServ
25
23
  try {
26
24
  const apiKey = process.env['GOOGLE_GENAI_API_KEY'];
27
25
  if (!apiKey) {
28
- console.warn('GOOGLE_GENAI_API_KEY environment variable not set. Google AI service will not be available.');
29
26
  this._isAvailable = false;
30
27
  return;
31
28
  }
32
29
  this.googleAI = new genai_1.GoogleGenAI({ apiKey });
30
+ logger_1.logger.debug('Google AI service initialized successfully');
33
31
  }
34
32
  catch (error) {
35
- console.error('Error initializing Google AI service:', error);
33
+ logger_1.logger.error('Error initializing Google AI service:', error);
36
34
  this._isAvailable = false;
37
35
  }
38
36
  }
@@ -59,7 +57,7 @@ let GoogleAiService = class GoogleAiService extends base_ai_service_1.BaseAiServ
59
57
  });
60
58
  }
61
59
  catch (error) {
62
- console.warn('Could not fetch models from Google AI API, using fallback list:', error.message);
60
+ logger_1.logger.warn('Could not fetch models from Google AI API, using fallback list:', error.message);
63
61
  }
64
62
  }
65
63
  addToConversationHistory(agent, message, fromSelf = false) {
@@ -143,7 +141,7 @@ let GoogleAiService = class GoogleAiService extends base_ai_service_1.BaseAiServ
143
141
  }
144
142
  }
145
143
  catch (error) {
146
- console.error('Error calling Google AI:', error);
144
+ logger_1.logger.error('Error calling Google AI:', error);
147
145
  throw error;
148
146
  }
149
147
  if (saveResponse) {
@@ -205,16 +203,16 @@ let GoogleAiService = class GoogleAiService extends base_ai_service_1.BaseAiServ
205
203
  return { artifactId };
206
204
  }
207
205
  catch (error) {
208
- console.error('Error generating image with Google AI:', error);
206
+ logger_1.logger.error('Error generating image with Google AI:', error);
209
207
  return { error };
210
208
  }
211
209
  }
212
210
  computeMessageCost(agent, usage) {
213
211
  const inputTokens = usage.promptTokenCount || 0;
214
212
  const outputTokens = usage.candidatesTokenCount || 0;
215
- const modelInfo = model_prices_1.default[agent.modelName];
213
+ const modelInfo = (0, model_prices_1.getModelPrices)()[agent.modelName];
216
214
  if (!modelInfo) {
217
- console.error(`No price info found for model ${agent.modelName}`);
215
+ logger_1.logger.error(`No price info found for model ${agent.modelName}`);
218
216
  return;
219
217
  }
220
218
  const inputCost = inputTokens * modelInfo.input_cost_per_token;
@@ -225,15 +223,15 @@ let GoogleAiService = class GoogleAiService extends base_ai_service_1.BaseAiServ
225
223
  agent.totalOutputTokens += outputTokens;
226
224
  agent.totalCost += cost;
227
225
  agent.totalMarkup += markup;
228
- console.log(`Cost for ${agent.agentName} message: ${cost} (markup: ${markup.toFixed(4)})`);
226
+ logger_1.logger.log(`Cost for ${agent.agentName} message: ${cost} (markup: ${markup.toFixed(4)})`);
229
227
  if (agent.balanceService && cost > 0) {
230
228
  agent.balanceService.decrementBalance(cost, markup);
231
229
  }
232
230
  }
233
231
  computeImageCost(agent, modelName) {
234
- const modelInfo = model_prices_1.default[modelName];
232
+ const modelInfo = (0, model_prices_1.getModelPrices)()[modelName];
235
233
  if (!modelInfo || !modelInfo.output_cost_per_image) {
236
- console.error(`No image price info found for model ${modelName}`);
234
+ logger_1.logger.error(`No image price info found for model ${modelName}`);
237
235
  return;
238
236
  }
239
237
  const outputCost = modelInfo.output_cost_per_image;
@@ -241,7 +239,7 @@ let GoogleAiService = class GoogleAiService extends base_ai_service_1.BaseAiServ
241
239
  const cost = outputCost + markup;
242
240
  agent.totalCost += cost;
243
241
  agent.totalMarkup += markup;
244
- console.log(`Cost for image generation: ${cost} (markup: ${markup.toFixed(4)})`);
242
+ logger_1.logger.log(`Cost for image generation: ${cost} (markup: ${markup.toFixed(4)})`);
245
243
  if (agent.balanceService && cost > 0) {
246
244
  agent.balanceService.decrementBalance(cost, markup);
247
245
  }