briyah 2.0.10 → 2.0.11

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 (49) hide show
  1. package/data/common/config/image_models.json +85 -6
  2. package/data/common/config/model_prices.json +30170 -32794
  3. package/dist-sdk/server/src/ai/LLM/anthropic.service.js +1 -1
  4. package/dist-sdk/server/src/ai/LLM/comfyui.service.js +1 -1
  5. package/dist-sdk/server/src/ai/LLM/deepseek.service.d.ts +1 -1
  6. package/dist-sdk/server/src/ai/LLM/deepseek.service.js +3 -2
  7. package/dist-sdk/server/src/ai/LLM/fal.service.d.ts +1 -1
  8. package/dist-sdk/server/src/ai/LLM/fal.service.js +4 -3
  9. package/dist-sdk/server/src/ai/LLM/googleai.service.d.ts +1 -1
  10. package/dist-sdk/server/src/ai/LLM/googleai.service.js +5 -4
  11. package/dist-sdk/server/src/ai/LLM/grok.service.d.ts +1 -1
  12. package/dist-sdk/server/src/ai/LLM/grok.service.js +3 -2
  13. package/dist-sdk/server/src/ai/LLM/mock.service.d.ts +1 -1
  14. package/dist-sdk/server/src/ai/LLM/mock.service.js +3 -2
  15. package/dist-sdk/server/src/ai/LLM/openai.service.js +2 -2
  16. package/dist-sdk/server/src/ai/LLM/self-hosted.service.js +1 -1
  17. package/dist-sdk/server/src/ai/LLM/together.service.d.ts +1 -1
  18. package/dist-sdk/server/src/ai/LLM/together.service.js +5 -4
  19. package/dist-sdk/server/src/ai/agent-config.d.ts +4 -0
  20. package/dist-sdk/server/src/ai/agent-store.service.js +3 -0
  21. package/dist-sdk/server/src/ai/agent.d.ts +7 -0
  22. package/dist-sdk/server/src/ai/agent.js +6 -0
  23. package/dist-sdk/server/src/app/balance.service.d.ts +155 -27
  24. package/dist-sdk/server/src/app/balance.service.js +290 -97
  25. package/dist-sdk/server/src/app/usage-context.d.ts +24 -0
  26. package/dist-sdk/server/src/app/usage-context.js +35 -0
  27. package/dist-sdk/server/src/app.controller.d.ts +5 -0
  28. package/dist-sdk/server/src/app.controller.js +13 -2
  29. package/dist-sdk/server/src/app.service.d.ts +39 -4
  30. package/dist-sdk/server/src/app.service.js +40 -3
  31. package/dist-sdk/server/src/common/errors.d.ts +13 -1
  32. package/dist-sdk/server/src/common/errors.js +21 -1
  33. package/dist-sdk/server/src/packs/pack-instantiation.service.js +1 -0
  34. package/dist-sdk/server/src/packs/pack-manifest.d.ts +3 -1
  35. package/dist-sdk/server/src/packs/pack-manifest.js +2 -0
  36. package/dist-sdk/server/src/room/illustration/illustration.service.d.ts +17 -2
  37. package/dist-sdk/server/src/room/illustration/illustration.service.js +35 -9
  38. package/dist-sdk/server/src/room/illustration/illustration.types.d.ts +6 -0
  39. package/dist-sdk/server/src/room/room-config.d.ts +11 -1
  40. package/dist-sdk/server/src/room/room-store.service.js +4 -0
  41. package/dist-sdk/server/src/room/room.d.ts +9 -1
  42. package/dist-sdk/server/src/room/room.js +16 -1
  43. package/dist-sdk/server/src/sdk/index.d.ts +5 -1
  44. package/dist-sdk/server/src/sdk/index.js +12 -1
  45. package/dist-sdk/server/src/tools/core/illustrate.tool.js +10 -1
  46. package/dist-sdk/server/src/tools/native-tool.types.d.ts +3 -2
  47. package/dist-sdk/shared/types/app.types.d.ts +27 -0
  48. package/dist-sdk/shared/types/app.types.js +6 -1
  49. package/package.json +1 -1
@@ -559,7 +559,7 @@ let AnthropicAiService = class AnthropicAiService extends base_ai_service_1.Base
559
559
  logger_1.logger.log(`Cost for ${agent.agentName} message: ${cost.toFixed(4)}, markup: ${markup.toFixed(4)}`);
560
560
  // DECREMENT BALANCE AFTER CALL
561
561
  if (agent.balanceService && cost > 0) {
562
- agent.balanceService.decrementBalance(cost, markup);
562
+ agent.balanceService.decrementBalance(cost, markup, agent);
563
563
  }
564
564
  // Log cache metrics for monitoring
565
565
  if (cacheCreationTokens > 0 || cacheReadTokens > 0) {
@@ -181,7 +181,7 @@ let ComfyUiAiService = class ComfyUiAiService extends base_ai_service_1.BaseAiSe
181
181
  agent.totalCost += cost;
182
182
  logger_1.logger.log(`Image cost for ${agent.agentName}: $${cost.toFixed(4)}`);
183
183
  if (agent.balanceService) {
184
- agent.balanceService.decrementBalance(cost, 0);
184
+ agent.balanceService.decrementBalance(cost, 0, agent);
185
185
  }
186
186
  }
187
187
  /**
@@ -49,7 +49,7 @@ export declare class DeepSeekAiService extends BaseAiService {
49
49
  * @returns A one-line description, truncated
50
50
  */
51
51
  private static describeValidationFailure;
52
- textPrompt(agent: Agent, prompt: string, jsonSchema?: any, saveResponse?: boolean, promptInstructions?: string, _cacheConfig?: any, maxOutputChars?: number): Promise<any>;
52
+ textPrompt(agent: Agent, prompt: string, jsonSchema?: any, saveResponse?: boolean, promptInstructions?: string, _cacheConfig?: any, _maxOutputChars?: number): Promise<any>;
53
53
  /**
54
54
  * Attaches a document to the agent or as a shared document
55
55
  * @param agent The agent context (null for shared documents)
@@ -160,7 +160,8 @@ let DeepSeekAiService = DeepSeekAiService_1 = class DeepSeekAiService extends ba
160
160
  }
161
161
  async textPrompt(agent, prompt, jsonSchema = null, saveResponse = true, promptInstructions = null,
162
162
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
163
- _cacheConfig = null, maxOutputChars = 0) {
163
+ _cacheConfig = null, _maxOutputChars = 0 // eslint-disable-line @typescript-eslint/no-unused-vars
164
+ ) {
164
165
  // CHECK BALANCE BEFORE AI CALL (unless disabled)
165
166
  if (agent.balanceService && !agent.disableBalanceCheck) {
166
167
  const hasSufficientBalance = agent.balanceService.hasSufficientBalance();
@@ -377,7 +378,7 @@ let DeepSeekAiService = DeepSeekAiService_1 = class DeepSeekAiService extends ba
377
378
  }
378
379
  // Decrement balance with markup
379
380
  if (agent.balanceService && cost > 0) {
380
- agent.balanceService.decrementBalance(cost, markup);
381
+ agent.balanceService.decrementBalance(cost, markup, agent);
381
382
  }
382
383
  }
383
384
  };
@@ -15,7 +15,7 @@ export declare class FalAiService extends BaseAiService {
15
15
  * @param developer Whether the message is a system instruction from the developer
16
16
  */
17
17
  addToConversationHistory(agent: Agent, message: string, fromSelf?: boolean, developer?: boolean): void;
18
- textPrompt(agent: Agent, prompt: string, jsonSchema?: any, saveResponse?: boolean, promptInstructions?: string, _cacheConfig?: any, maxOutputChars?: number): Promise<any>;
18
+ textPrompt(agent: Agent, prompt: string, jsonSchema?: any, saveResponse?: boolean, promptInstructions?: string, _cacheConfig?: any, _maxOutputChars?: number): Promise<any>;
19
19
  /**
20
20
  * Compute the cost of a text message with markup for Fal AI
21
21
  * Handles model name lookup with fal_ai/ prefix if needed
@@ -103,7 +103,8 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
103
103
  }
104
104
  async textPrompt(agent, prompt, jsonSchema = null, saveResponse = true, promptInstructions = null,
105
105
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
106
- _cacheConfig = null, maxOutputChars = 0) {
106
+ _cacheConfig = null, _maxOutputChars = 0 // eslint-disable-line @typescript-eslint/no-unused-vars
107
+ ) {
107
108
  // CHECK BALANCE BEFORE AI CALL (unless disabled)
108
109
  if (agent.balanceService && !agent.disableBalanceCheck) {
109
110
  const hasSufficientBalance = agent.balanceService.hasSufficientBalance();
@@ -251,7 +252,7 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
251
252
  }
252
253
  // Decrement balance with markup
253
254
  if (agent.balanceService && cost > 0) {
254
- agent.balanceService.decrementBalance(cost, markup);
255
+ agent.balanceService.decrementBalance(cost, markup, agent);
255
256
  }
256
257
  }
257
258
  /**
@@ -283,7 +284,7 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
283
284
  agent.totalCost += cost;
284
285
  logger_1.logger.log(`Image cost for ${agent.agentName}: $${cost.toFixed(4)}`);
285
286
  if (agent.balanceService && cost > 0) {
286
- agent.balanceService.decrementBalance(cost, 0);
287
+ agent.balanceService.decrementBalance(cost, 0, agent);
287
288
  }
288
289
  }
289
290
  async generateImage(agent, prompt, imageProperties) {
@@ -15,7 +15,7 @@ export declare class GoogleAiService extends BaseAiService {
15
15
  * @param fromSelf Whether the message was generated by this agent (true) or received from outside (false)
16
16
  */
17
17
  addToConversationHistory(agent: Agent, message: string, fromSelf?: boolean): void;
18
- textPrompt(agent: Agent, prompt: string, jsonSchema?: any, saveResponse?: boolean, promptInstructions?: string, _cacheConfig?: any, maxOutputChars?: number): Promise<any>;
18
+ textPrompt(agent: Agent, prompt: string, jsonSchema?: any, saveResponse?: boolean, promptInstructions?: string, _cacheConfig?: any, _maxOutputChars?: number): Promise<any>;
19
19
  generateImage(agent: Agent, prompt: string, imageProperties?: Record<string, any>): Promise<{
20
20
  artifactId?: string;
21
21
  error?: any;
@@ -81,7 +81,8 @@ let GoogleAiService = class GoogleAiService extends base_ai_service_1.BaseAiServ
81
81
  }
82
82
  async textPrompt(agent, prompt, jsonSchema = null, saveResponse = true, promptInstructions = null,
83
83
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
84
- _cacheConfig = null, maxOutputChars = 0) {
84
+ _cacheConfig = null, _maxOutputChars = 0 // eslint-disable-line @typescript-eslint/no-unused-vars
85
+ ) {
85
86
  // CHECK BALANCE BEFORE AI CALL (unless disabled)
86
87
  if (agent.balanceService && !agent.disableBalanceCheck) {
87
88
  const hasSufficientBalance = agent.balanceService.hasSufficientBalance();
@@ -240,7 +241,7 @@ let GoogleAiService = class GoogleAiService extends base_ai_service_1.BaseAiServ
240
241
  logger_1.logger.log(`Cost for ${agent.agentName} message: ${cost} (markup: ${markup.toFixed(4)})`);
241
242
  // Decrement balance with markup
242
243
  if (agent.balanceService && cost > 0) {
243
- agent.balanceService.decrementBalance(cost, markup);
244
+ agent.balanceService.decrementBalance(cost, markup, agent);
244
245
  }
245
246
  }
246
247
  /**
@@ -256,7 +257,7 @@ let GoogleAiService = class GoogleAiService extends base_ai_service_1.BaseAiServ
256
257
  agent.totalCost += cost;
257
258
  logger_1.logger.log(`Image cost for ${agent.agentName}: $${cost.toFixed(4)}`);
258
259
  if (agent.balanceService && cost > 0)
259
- agent.balanceService.decrementBalance(cost, 0);
260
+ agent.balanceService.decrementBalance(cost, 0, agent);
260
261
  return;
261
262
  }
262
263
  logger_1.logger.warn(`No image price info found for model ${modelName}. Skipping cost tracking.`);
@@ -272,7 +273,7 @@ let GoogleAiService = class GoogleAiService extends base_ai_service_1.BaseAiServ
272
273
  logger_1.logger.log(`Cost for image generation: ${cost} (markup: ${markup.toFixed(4)})`);
273
274
  // Decrement balance with markup
274
275
  if (agent.balanceService && cost > 0) {
275
- agent.balanceService.decrementBalance(cost, markup);
276
+ agent.balanceService.decrementBalance(cost, markup, agent);
276
277
  }
277
278
  }
278
279
  /**
@@ -17,7 +17,7 @@ export declare class GrokAiService extends BaseAiService {
17
17
  */
18
18
  attachDocument(agent: Agent, fileName: string, fileData: Uint8Array): Promise<string>;
19
19
  finishAgent(agent: Agent): Promise<void>;
20
- textPrompt(agent: Agent, prompt: string, jsonSchema?: any, saveResponse?: boolean, promptInstructions?: string, _cacheConfig?: any, maxOutputChars?: number): Promise<any>;
20
+ textPrompt(agent: Agent, prompt: string, jsonSchema?: any, saveResponse?: boolean, promptInstructions?: string, _cacheConfig?: any, _maxOutputChars?: number): Promise<any>;
21
21
  /**
22
22
  * Adds a message to the agent history in the appropriate format for this service
23
23
  * @param agent The agent to add the message to
@@ -121,7 +121,8 @@ let GrokAiService = class GrokAiService extends base_ai_service_1.BaseAiService
121
121
  }
122
122
  async textPrompt(agent, prompt, jsonSchema = null, saveResponse = true, promptInstructions = null,
123
123
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
124
- _cacheConfig = null, maxOutputChars = 0) {
124
+ _cacheConfig = null, _maxOutputChars = 0 // eslint-disable-line @typescript-eslint/no-unused-vars
125
+ ) {
125
126
  // CHECK BALANCE BEFORE AI CALL (unless disabled)
126
127
  if (agent.balanceService && !agent.disableBalanceCheck) {
127
128
  const hasSufficientBalance = agent.balanceService.hasSufficientBalance();
@@ -307,7 +308,7 @@ let GrokAiService = class GrokAiService extends base_ai_service_1.BaseAiService
307
308
  }
308
309
  // Decrement balance with markup
309
310
  if (agent.balanceService && cost > 0) {
310
- agent.balanceService.decrementBalance(cost, markup);
311
+ agent.balanceService.decrementBalance(cost, markup, agent);
311
312
  }
312
313
  }
313
314
  };
@@ -9,6 +9,6 @@ export declare class MockAiService extends BaseAiService {
9
9
  preparedPrompt(agent: Agent, promptFileName: string, variables: any, saveResponse?: boolean, _cacheConfig?: any): Promise<any>;
10
10
  getMockFile(promptFileName: string, prompt: string, variables: any): string;
11
11
  instructedPrompt(agent: Agent, prompt: string, promptFileName: string, variables?: any, saveResponse?: boolean, cacheConfig?: any): Promise<any>;
12
- textPrompt(agent: Agent, prompt: string, jsonSchema?: any, saveResponse?: boolean, _promptInstructions?: string, _cacheConfig?: any, maxOutputChars?: number): Promise<any>;
12
+ textPrompt(agent: Agent, prompt: string, jsonSchema?: any, saveResponse?: boolean, _promptInstructions?: string, _cacheConfig?: any, _maxOutputChars?: number): Promise<any>;
13
13
  private trackMockCosts;
14
14
  }
@@ -177,7 +177,8 @@ let MockAiService = class MockAiService extends base_ai_service_1.BaseAiService
177
177
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
178
178
  _promptInstructions = null,
179
179
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
180
- _cacheConfig = null, maxOutputChars = 0) {
180
+ _cacheConfig = null, _maxOutputChars = 0 // eslint-disable-line @typescript-eslint/no-unused-vars
181
+ ) {
181
182
  // Generic mock response for direct calls
182
183
  const mockResponse = jsonSchema
183
184
  ? { action: 'SPEAK', content: 'Generic mock response' }
@@ -211,7 +212,7 @@ let MockAiService = class MockAiService extends base_ai_service_1.BaseAiService
211
212
  logger_1.logger.log(`Cost for ${agent.agentName} message: ${totalCost} (markup: ${markup.toFixed(4)})`);
212
213
  // Decrement balance with markup
213
214
  if (agent.balanceService) {
214
- await agent.balanceService.decrementBalance(totalCost, markup);
215
+ await agent.balanceService.decrementBalance(totalCost, markup, agent);
215
216
  }
216
217
  }
217
218
  };
@@ -435,7 +435,7 @@ let OpenAiService = OpenAiService_1 = class OpenAiService extends base_ai_servic
435
435
  }
436
436
  // Decrement balance with markup
437
437
  if (agent.balanceService && cost > 0) {
438
- agent.balanceService.decrementBalance(cost, markup);
438
+ agent.balanceService.decrementBalance(cost, markup, agent);
439
439
  }
440
440
  }
441
441
  computeImageCost(agent, centsPerImage) {
@@ -454,7 +454,7 @@ let OpenAiService = OpenAiService_1 = class OpenAiService extends base_ai_servic
454
454
  agent.totalCost += cost;
455
455
  logger_1.logger.log(`Image cost for ${agent.agentName}: $${cost.toFixed(4)}`);
456
456
  if (agent.balanceService && cost > 0) {
457
- agent.balanceService.decrementBalance(cost, 0);
457
+ agent.balanceService.decrementBalance(cost, 0, agent);
458
458
  }
459
459
  }
460
460
  /**
@@ -236,7 +236,7 @@ let SelfHostedAiService = class SelfHostedAiService extends base_ai_service_1.Ba
236
236
  agent.totalMarkup += markup;
237
237
  logger_1.logger.log(`Cost for ${agent.agentName} message: ${cost} (markup: ${markup.toFixed(4)})`);
238
238
  if (agent.balanceService && cost > 0) {
239
- agent.balanceService.decrementBalance(cost, markup);
239
+ agent.balanceService.decrementBalance(cost, markup, agent);
240
240
  }
241
241
  }
242
242
  };
@@ -16,7 +16,7 @@ export declare class TogetherAiService extends BaseAiService {
16
16
  * @param developer Whether the message is a system instruction from the developer
17
17
  */
18
18
  addToConversationHistory(agent: Agent, message: string, fromSelf?: boolean, developer?: boolean): void;
19
- textPrompt(agent: Agent, prompt: string, jsonSchema?: any, saveResponse?: boolean, promptInstructions?: string, _cacheConfig?: any, maxOutputChars?: number): Promise<any>;
19
+ textPrompt(agent: Agent, prompt: string, jsonSchema?: any, saveResponse?: boolean, promptInstructions?: string, _cacheConfig?: any, _maxOutputChars?: number): Promise<any>;
20
20
  /**
21
21
  * Compute the cost of a text message with markup for Together AI
22
22
  * Together AI doesn't support prompt caching, so this is a simple calculation
@@ -87,7 +87,8 @@ let TogetherAiService = class TogetherAiService extends base_ai_service_1.BaseAi
87
87
  }
88
88
  async textPrompt(agent, prompt, jsonSchema = null, saveResponse = true, promptInstructions = null,
89
89
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
90
- _cacheConfig = null, maxOutputChars = 0) {
90
+ _cacheConfig = null, _maxOutputChars = 0 // eslint-disable-line @typescript-eslint/no-unused-vars
91
+ ) {
91
92
  // CHECK BALANCE BEFORE AI CALL (unless disabled)
92
93
  if (agent.balanceService && !agent.disableBalanceCheck) {
93
94
  const hasSufficientBalance = agent.balanceService.hasSufficientBalance();
@@ -212,7 +213,7 @@ let TogetherAiService = class TogetherAiService extends base_ai_service_1.BaseAi
212
213
  logger_1.logger.log(`Cost for ${agent.agentName} message: ${cost} (markup: ${markup.toFixed(4)})`);
213
214
  // Decrement balance with markup
214
215
  if (agent.balanceService && cost > 0) {
215
- agent.balanceService.decrementBalance(cost, markup);
216
+ agent.balanceService.decrementBalance(cost, markup, agent);
216
217
  }
217
218
  }
218
219
  /**
@@ -229,7 +230,7 @@ let TogetherAiService = class TogetherAiService extends base_ai_service_1.BaseAi
229
230
  agent.totalCost += cost;
230
231
  logger_1.logger.log(`Image cost for ${agent.agentName}: $${cost.toFixed(4)}`);
231
232
  if (agent.balanceService && cost > 0)
232
- agent.balanceService.decrementBalance(cost, 0);
233
+ agent.balanceService.decrementBalance(cost, 0, agent);
233
234
  return;
234
235
  }
235
236
  logger_1.logger.warn(`No price info found for model ${agent.modelName}. Skipping cost tracking.`);
@@ -290,7 +291,7 @@ let TogetherAiService = class TogetherAiService extends base_ai_service_1.BaseAi
290
291
  logger_1.logger.log(`Cost for image generation: ${cost} (markup: ${markup.toFixed(4)})`);
291
292
  // Decrement balance with markup
292
293
  if (agent.balanceService && cost > 0) {
293
- agent.balanceService.decrementBalance(cost, markup);
294
+ agent.balanceService.decrementBalance(cost, markup, agent);
294
295
  }
295
296
  }
296
297
  /**
@@ -33,6 +33,10 @@ export interface AgentConfig {
33
33
  beginInstruction?: string;
34
34
  promptCacheTTL?: number;
35
35
  ownerRoomId?: string;
36
+ usageTags?: {
37
+ user?: string;
38
+ feature?: string;
39
+ };
36
40
  toolNames?: string[];
37
41
  useModerator?: boolean;
38
42
  /**
@@ -386,6 +386,8 @@ let AgentStoreService = class AgentStoreService {
386
386
  agent.templateAgentId = config.templateAgentId;
387
387
  // Restore room ownership (for agents cloned as part of published rooms)
388
388
  agent.ownerRoomId = config.ownerRoomId;
389
+ if (config.usageTags)
390
+ agent.usageTags = { ...config.usageTags };
389
391
  // Restore which pack the agent is filed under
390
392
  agent.pack = config.pack;
391
393
  agent.packAgentKey = config.packAgentKey;
@@ -499,6 +501,7 @@ let AgentStoreService = class AgentStoreService {
499
501
  beginInstruction: agent.beginInstruction,
500
502
  promptCacheTTL: agent.promptCacheTTL,
501
503
  ownerRoomId: agent.ownerRoomId, // NEW: Persist room ownership
504
+ usageTags: agent.usageTags,
502
505
  toolNames: agent.toolNames,
503
506
  useModerator: agent.useModerator,
504
507
  pack: agent.pack,
@@ -8,6 +8,7 @@ import { ArtifactService } from './artifact.service';
8
8
  import { UserPathsService } from '../config/user-paths.service';
9
9
  import { IConfigService } from '../config/env-config';
10
10
  import { BalanceService } from '../app/balance.service';
11
+ import { UsageTags } from '../app/usage-context';
11
12
  import { AgentStoreService } from './agent-store.service';
12
13
  export declare class Agent {
13
14
  id?: string;
@@ -32,6 +33,12 @@ export declare class Agent {
32
33
  isPublished: boolean;
33
34
  templateAgentId?: string;
34
35
  ownerRoomId?: string;
36
+ /**
37
+ * Who and what this agent's AI calls are for, recorded with every charge in
38
+ * the usage ledger (see BalanceService). Saved with the agent; wins over the
39
+ * tags of the context it runs in (runWithUsageTags).
40
+ */
41
+ usageTags?: UsageTags;
35
42
  /** The pack this agent is filed under. See {@link AgentConfig.pack}. */
36
43
  pack?: string;
37
44
  /** The pack template's key, when this agent came from one. */
@@ -31,6 +31,12 @@ class Agent {
31
31
  isPublished = false;
32
32
  templateAgentId;
33
33
  ownerRoomId; // The room this agent belongs to; it is hidden from the agent list and deleted with the room
34
+ /**
35
+ * Who and what this agent's AI calls are for, recorded with every charge in
36
+ * the usage ledger (see BalanceService). Saved with the agent; wins over the
37
+ * tags of the context it runs in (runWithUsageTags).
38
+ */
39
+ usageTags;
34
40
  /** The pack this agent is filed under. See {@link AgentConfig.pack}. */
35
41
  pack;
36
42
  /** The pack template's key, when this agent came from one. */
@@ -1,55 +1,183 @@
1
1
  import { UserPathsService } from '../config/user-paths.service';
2
2
  import { BalanceMessageService } from './balance-message.service';
3
+ import { UsageTags } from './usage-context';
4
+ /** The agent a charge is for; structural, so this file needs nothing from agent.ts. */
5
+ export interface UsageSource {
6
+ id?: string;
7
+ agentName?: string;
8
+ serviceName?: string;
9
+ modelName?: string;
10
+ usageTags?: UsageTags | null;
11
+ }
12
+ /** The monthly (or any period's) allowance: granted by the host, spent first, never carried over. */
13
+ export interface AllowanceState {
14
+ amount: number;
15
+ used: number;
16
+ /** ISO date-time the period began (when it was granted). */
17
+ periodStart: string | null;
18
+ /** The host's reference for the grant (e.g. the invoice that paid for it). */
19
+ reference: string | null;
20
+ }
21
+ /** What a user can spend: the allowance, then purchased credit. All in dollars. */
22
+ export interface CreditSummary {
23
+ allowance: AllowanceState & {
24
+ remaining: number;
25
+ };
26
+ /** Bought credit, kept until used. Negative only when the last call overdrew it. */
27
+ purchased: number;
28
+ /** What the next call can draw on: allowance remaining plus purchased. */
29
+ total: number;
30
+ }
31
+ /** One line of the usage ledger. */
32
+ export interface UsageEntry {
33
+ kind: 'charge' | 'grant' | 'purchase';
34
+ at: string;
35
+ /** Charge: what it cost, markup included. Grant or purchase: the amount. */
36
+ amount: number;
37
+ markup?: number;
38
+ /** Charge: how much came out of each pot. */
39
+ fromAllowance?: number;
40
+ fromPurchased?: number;
41
+ agentId?: string;
42
+ agentName?: string;
43
+ serviceName?: string;
44
+ modelName?: string;
45
+ tags?: UsageTags;
46
+ /** Grant: the host's reference. */
47
+ reference?: string;
48
+ }
49
+ /** A total of charges under one label. */
50
+ export interface UsageTotal {
51
+ key: string;
52
+ amount: number;
53
+ calls: number;
54
+ }
55
+ export interface UsageReport {
56
+ from: string;
57
+ to: string;
58
+ total: number;
59
+ calls: number;
60
+ fromAllowance: number;
61
+ fromPurchased: number;
62
+ /** By `tags.user`; untagged charges are under "". */
63
+ byUser: UsageTotal[];
64
+ /** By `tags.feature`, else the agent's name. */
65
+ byFeature: UsageTotal[];
66
+ /** By calendar day (UTC), YYYY-MM-DD. */
67
+ byDay: UsageTotal[];
68
+ /** The charges themselves, oldest first, when asked for. */
69
+ entries?: UsageEntry[];
70
+ }
3
71
  /**
4
- * Service for managing user balance
5
- * Tracks AI usage costs and enforces spending limits
72
+ * A user's AI credit: what they may spend, what they spent it on, and the
73
+ * limit that stops AI calls when it is gone.
74
+ *
75
+ * Credit sits in two pots, spent in this order:
76
+ * - **The allowance**, granted by the host for a period (for example, each
77
+ * month an invoice is paid). A new grant replaces it: unused allowance is not
78
+ * carried over. A user who is never granted one simply has none.
79
+ * - **Purchased credit**, added by payments ({@link addBalance}) and kept until
80
+ * used. New users start with `STARTING_BALANCE` here.
81
+ *
82
+ * The state is `userconfig/credits.json`; the single number Briyah kept before
83
+ * (`userconfig/balance`) is read once as purchased credit and then retired.
84
+ * Every charge, grant and purchase is also appended to the usage ledger,
85
+ * `usage/<yyyy-mm>.jsonl` in the user's data directory, with the agent and the
86
+ * usage tags it ran under (see usage-context.ts).
87
+ *
88
+ * A call is allowed while the total is not negative, as before: the last call
89
+ * may overdraw by its own cost, and the overdraft is taken out of the next
90
+ * allowance granted.
6
91
  */
7
92
  export declare class BalanceService {
8
93
  private userId;
9
94
  private userPaths;
10
- private balanceFilePath;
95
+ private creditsFilePath;
96
+ private legacyBalanceFilePath;
11
97
  private markupFilePath;
98
+ private usageDir;
12
99
  private startingBalance;
13
100
  private balanceMessageService?;
14
101
  constructor(userId: string, userPaths: UserPathsService, balanceMessageService?: BalanceMessageService);
15
- /**
16
- * Get current balance (loads from file)
17
- * @returns Current balance as number
18
- * @throws If balance file is corrupted
19
- */
102
+ /** What the next call can draw on: allowance remaining plus purchased credit. */
20
103
  getBalance(): number;
21
104
  /**
22
- * Get current markup (loads from file)
23
- * @returns Current markup total
24
- * @throws If markup file is corrupted
25
- */
26
- getMarkup(): number;
27
- /**
28
- * Check if user has sufficient balance to make AI calls
29
- * @returns true if balance >= 0, false otherwise
105
+ * Whether the user may make another AI call.
106
+ * @returns true while the total is not negative
30
107
  */
31
108
  hasSufficientBalance(): boolean;
32
109
  /**
33
- * Decrement balance by specified amount
34
- * @param amount Amount to subtract from balance
35
- * @param markup Amount to add to markup total
110
+ * Charges an AI call: out of the allowance first, the rest out of purchased
111
+ * credit (which the last call may overdraw), and records it in the ledger.
112
+ * @param amount What the call cost, markup included
113
+ * @param markup The markup part, also added to the platform's markup total
114
+ * @param source The agent the call was for, whose usage tags are recorded with it
36
115
  * @throws If amount is negative
37
116
  */
38
- decrementBalance(amount: number, markup?: number): void;
117
+ decrementBalance(amount: number, markup?: number, source?: UsageSource): void;
39
118
  /**
40
- * Add funds to balance
41
- * @param amount Amount to add to balance
119
+ * Adds purchased credit (after a successful payment). It is kept until used,
120
+ * whatever happens to the allowance.
42
121
  * @throws If amount is negative or zero
43
122
  */
44
123
  addBalance(amount: number): void;
45
124
  /**
46
- * Save balance to file
47
- * @param balance New balance value
125
+ * Starts a new allowance period: the allowance becomes `amount`, unspent, and
126
+ * whatever was left of the last one is gone. Purchased credit is untouched,
127
+ * except that an overdraft (purchased below zero) is paid out of the new
128
+ * allowance first.
129
+ *
130
+ * Applied once per reference: granting a reference already granted changes
131
+ * nothing, so a payment confirmed twice grants once.
132
+ *
133
+ * @param amount The new allowance in dollars (0 ends the allowance)
134
+ * @param options.reference The host's id for this grant, e.g. an invoice id
135
+ * @param options.periodStart When the period began; now when omitted
136
+ * @returns Whether it was applied, and the credit after it
137
+ */
138
+ grantAllowance(amount: number, options: {
139
+ reference: string;
140
+ periodStart?: Date | string;
141
+ }): {
142
+ granted: boolean;
143
+ credits: CreditSummary;
144
+ };
145
+ /** The allowance, purchased credit and total, as of now. */
146
+ getCredits(): CreditSummary;
147
+ /**
148
+ * What was spent between two moments (inclusive), with totals by user, by
149
+ * feature and by day. Defaults: from the start of the current allowance
150
+ * period (or of this month, without one) to now.
151
+ *
152
+ * @param options.entries Also return the charges themselves
48
153
  */
49
- private saveBalance;
154
+ getUsage(options?: {
155
+ from?: Date | string;
156
+ to?: Date | string;
157
+ entries?: boolean;
158
+ }): UsageReport;
159
+ /** Grants and purchases between two moments, oldest first. */
160
+ getCreditEvents(options?: {
161
+ from?: Date | string;
162
+ to?: Date | string;
163
+ }): UsageEntry[];
164
+ /**
165
+ * Get current markup (loads from file)
166
+ * @returns Current markup total
167
+ */
168
+ getMarkup(): number;
169
+ private summarize;
50
170
  /**
51
- * Save markup to file
52
- * @param markup
171
+ * The credit state, created on first use: from the old single balance file
172
+ * when there is one (it was all purchased credit, as far as anyone knew),
173
+ * otherwise STARTING_BALANCE.
53
174
  */
175
+ private readState;
176
+ private readLegacyBalance;
177
+ /** Writes the state through a temporary file, so a crash never leaves half a file. */
178
+ private writeState;
179
+ private appendUsage;
180
+ /** Ledger lines from `from` to `to` inclusive, oldest first. */
181
+ private readLedger;
54
182
  private saveMarkup;
55
183
  }