From 762452efcc85fb4c233fdcd0ce6a45e86c719ae6 Mon Sep 17 00:00:00 2001 From: Muhammed Nihal P N Date: Mon, 28 Sep 2026 13:17:43 +0530 Subject: [PATCH] feat(agents): add agent-level billing mode --- api/app/clients/BaseClient.js | 1 + .../tools/structured/GeminiImageGen.js | 25 ++- api/app/clients/tools/util/handleTools.js | 1 + api/server/controllers/agents/client.js | 10 +- api/server/controllers/agents/openai.js | 4 +- api/server/controllers/agents/responses.js | 7 +- api/server/controllers/agents/v1.js | 27 +++- api/server/controllers/agents/v1.spec.js | 111 +++++++++++++ .../services/Endpoints/agents/initialize.js | 1 + api/server/services/Schedules/access.js | 8 +- api/server/services/Schedules/index.js | 3 +- api/server/services/ToolService.js | 2 + packages/api/src/agents/transactions.spec.ts | 148 ++++++++++++++++++ packages/api/src/agents/transactions.ts | 2 + packages/api/src/agents/usage.spec.ts | 62 ++++++++ packages/api/src/agents/usage.ts | 31 ++++ packages/api/src/agents/validation.ts | 3 + packages/api/src/schedules/fire.ts | 2 +- packages/api/src/schedules/gate.spec.ts | 2 + packages/api/src/schedules/service.spec.ts | 62 ++++++++ packages/api/src/schedules/service.ts | 8 +- packages/api/src/schedules/types.ts | 2 +- packages/data-provider/src/schemas.ts | 8 + packages/data-provider/src/types/agents.ts | 9 +- packages/data-schemas/src/schema/agent.ts | 5 + .../data-schemas/src/schema/transaction.ts | 10 ++ packages/data-schemas/src/types/agent.ts | 2 + .../data-schemas/src/types/transaction.ts | 2 + 28 files changed, 543 insertions(+), 15 deletions(-) diff --git a/api/app/clients/BaseClient.js b/api/app/clients/BaseClient.js index 4e74116405..e9d20da1b6 100644 --- a/api/app/clients/BaseClient.js +++ b/api/app/clients/BaseClient.js @@ -1016,6 +1016,7 @@ class BaseClient { try { if ( balanceConfig?.enabled && + this.options.agent?.billing_mode !== 'agent' && supportsBalanceCheck[this.options.endpointType ?? this.options.endpoint] ) { const balanceAdmission = checkBalance( diff --git a/api/app/clients/tools/structured/GeminiImageGen.js b/api/app/clients/tools/structured/GeminiImageGen.js index 04265bbba9..af626d0094 100644 --- a/api/app/clients/tools/structured/GeminiImageGen.js +++ b/api/app/clients/tools/structured/GeminiImageGen.js @@ -11,6 +11,7 @@ const { getBalanceConfig, getEnvProxyDispatcher, getTransactionsConfig, + applyAgentBillingMode, } = require('@librechat/api'); const { getStrategyFunctions } = require('~/server/services/Files/strategies'); const { spendTokens, getFiles } = require('~/models'); @@ -251,15 +252,24 @@ function checkForSafetyBlock(response) { * @param {string} params.conversationId - The conversation ID * @param {string} params.model - The model name * @param {string} [params.messageId] - The response message ID for transaction correlation + * @param {string} [params.rootAgentBillingMode] - Billing mode of the root agent */ -async function recordTokenUsage({ usageMetadata, req, userId, conversationId, model, messageId }) { +async function recordTokenUsage({ + usageMetadata, + req, + userId, + conversationId, + model, + messageId, + rootAgentBillingMode, +}) { if (!usageMetadata) { logger.debug('[GeminiImageGen] No usage metadata available for balance tracking'); return; } const appConfig = req?.config; - const balance = getBalanceConfig(appConfig); + const balance = applyAgentBillingMode(getBalanceConfig(appConfig), rootAgentBillingMode); const transactions = getTransactionsConfig(appConfig); // Skip if neither balance nor transactions are enabled @@ -316,7 +326,15 @@ function createGeminiImageTool(fields = {}) { throw new Error('This tool is only available for agents.'); } - const { req, imageFiles = [], userId, fileStrategy, GEMINI_API_KEY, GOOGLE_KEY } = fields; + const { + req, + imageFiles = [], + userId, + fileStrategy, + GEMINI_API_KEY, + GOOGLE_KEY, + rootAgentBillingMode, + } = fields; const imageOutputType = fields.imageOutputType || EImageOutputType.PNG; @@ -456,6 +474,7 @@ function createGeminiImageTool(fields = {}) { messageId, conversationId, model: geminiModel, + rootAgentBillingMode, }).catch((error) => { logger.error('[GeminiImageGen] Failed to record token usage:', error); }); diff --git a/api/app/clients/tools/util/handleTools.js b/api/app/clients/tools/util/handleTools.js index 27af41b89c..6ccd528560 100644 --- a/api/app/clients/tools/util/handleTools.js +++ b/api/app/clients/tools/util/handleTools.js @@ -207,6 +207,7 @@ const loadTools = async ({ imageFiles, userId: user, fileStrategy, + rootAgentBillingMode: options.rootAgentBillingMode, }); }, }; diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.js index 1a68393c4f..adc1555f3d 100644 --- a/api/server/controllers/agents/client.js +++ b/api/server/controllers/agents/client.js @@ -25,6 +25,7 @@ const { applyContextToAgent, isMemoryAgentEnabled, recordCollectedUsage, + applyAgentBillingMode, resolveRunUsageContext, getScheduleMCPExecution, createScheduledMCPPolicyRecorder, @@ -3819,6 +3820,7 @@ class AgentClient extends BaseClient { */ async recordCollectedUsage({ model, + rootAgentId = this.options.agent?.id, balance, transactions, context = 'message', @@ -3858,6 +3860,7 @@ class AgentClient extends BaseClient { * `undefined` is its meaningful value. Reading that as "no override" is * what silently restored the primary's custom rates. */ const overrideTokenConfig = crossEndpoint === true; + const billingBalance = applyAgentBillingMode(balance, this.options.agent?.billing_mode); const result = await recordCollectedUsage( { spendTokens: db.spendTokens, @@ -3872,7 +3875,8 @@ class AgentClient extends BaseClient { model: model ?? this.model ?? this.options.agent.model_parameters.model, context, messageId: this.responseMessageId, - balance, + rootAgentId, + balance: billingBalance, transactions, endpointTokenConfig: overrideTokenConfig ? endpointTokenConfig @@ -4005,10 +4009,12 @@ class AgentClient extends BaseClient { */ buildDetachedSubagentUsageRecorder(balance, transactions) { const options = this.options; + const billingBalance = applyAgentBillingMode(balance, options?.agent?.billing_mode); const billing = { user: this.user ?? options?.req?.user?.id, conversationId: this.conversationId, messageId: this.responseMessageId, + rootAgentId: options?.agent?.id, model: this.model ?? options?.agent?.model_parameters?.model, endpointTokenConfig: options?.endpointTokenConfig, endpointTokenConfigByAgentId: options?.endpointTokenConfigByAgentId, @@ -4027,7 +4033,7 @@ class AgentClient extends BaseClient { }, isPrincipalActive: db.isAgentTriggerPrincipalActive, }, - { ...billing, balance, transactions }, + { ...billing, balance: billingBalance, transactions }, ); } diff --git a/api/server/controllers/agents/openai.js b/api/server/controllers/agents/openai.js index 18d13e5475..cac9e113d6 100644 --- a/api/server/controllers/agents/openai.js +++ b/api/server/controllers/agents/openai.js @@ -37,6 +37,7 @@ const { extractManualSkills, createErrorResponse, recordCollectedUsage, + applyAgentBillingMode, createSubagentUsageSink, getTransactionsConfig, resolveAgentTokenConfig, @@ -1170,6 +1171,7 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => { // Record token usage against balance const balanceConfig = getBalanceConfig(appConfig); + const billingBalance = applyAgentBillingMode(balanceConfig, agent?.billing_mode); const transactionsConfig = getTransactionsConfig(appConfig); execution.track( recordCollectedUsage( @@ -1191,7 +1193,7 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => { collectedUsage, context: 'message', messageId: responseId, - balance: balanceConfig, + balance: billingBalance, transactions: transactionsConfig, model: primaryConfig.model || agent.model_parameters?.model, endpointTokenConfig: primaryConfig.endpointTokenConfig, diff --git a/api/server/controllers/agents/responses.js b/api/server/controllers/agents/responses.js index 0803fe1774..b9c1ced164 100644 --- a/api/server/controllers/agents/responses.js +++ b/api/server/controllers/agents/responses.js @@ -29,6 +29,7 @@ const { injectSkillPrimes, extractManualSkills, recordCollectedUsage, + applyAgentBillingMode, createSubagentUsageSink, getTransactionsConfig, resolveAgentTokenConfig, @@ -1391,6 +1392,7 @@ const executeResponse = async (envelope, { req, res }) => { // Record token usage against balance const balanceConfig = getBalanceConfig(appConfig); + const billingBalance = applyAgentBillingMode(balanceConfig, agent?.billing_mode); const transactionsConfig = getTransactionsConfig(appConfig); execution.track( recordCollectedUsage( @@ -1412,7 +1414,7 @@ const executeResponse = async (envelope, { req, res }) => { collectedUsage, context: 'message', messageId: responseId, - balance: balanceConfig, + balance: billingBalance, transactions: transactionsConfig, model: primaryConfig.model || agent.model_parameters?.model, endpointTokenConfig: primaryConfig.endpointTokenConfig, @@ -1630,6 +1632,7 @@ const executeResponse = async (envelope, { req, res }) => { // Record token usage against balance const balanceConfig = getBalanceConfig(appConfig); + const billingBalance = applyAgentBillingMode(balanceConfig, agent?.billing_mode); const transactionsConfig = getTransactionsConfig(appConfig); execution.track( recordCollectedUsage( @@ -1651,7 +1654,7 @@ const executeResponse = async (envelope, { req, res }) => { collectedUsage, context: 'message', messageId: responseId, - balance: balanceConfig, + balance: billingBalance, transactions: transactionsConfig, model: primaryConfig.model || agent.model_parameters?.model, endpointTokenConfig: primaryConfig.endpointTokenConfig, diff --git a/api/server/controllers/agents/v1.js b/api/server/controllers/agents/v1.js index e8292bf687..eba0515e6b 100644 --- a/api/server/controllers/agents/v1.js +++ b/api/server/controllers/agents/v1.js @@ -2,7 +2,7 @@ const { z } = require('zod'); const { load } = require('js-yaml'); const fs = require('fs').promises; const { nanoid } = require('nanoid'); -const { logger } = require('@librechat/data-schemas'); +const { logger, SystemCapabilities } = require('@librechat/data-schemas'); const { refreshS3Url, splitMCPToolKey, @@ -93,6 +93,14 @@ const { userCanUseMCPServers, } = require('~/server/services/MCP'); const { hasCapability } = require('~/server/middleware/roles/capabilities'); + +/** + * Billing mode changes are privileged because they change who is charged + * for an agent's model usage. + */ +const canManageAgentBilling = async (req) => + hasCapability(req.user, SystemCapabilities.MANAGE_AGENTS); + const { attachOwnerContacts } = require('~/server/services/Agents/ownerContact'); const { instructionsPromptAccess } = require('~/server/services/Agents/instructionsPrompt'); const { getMCPServersRegistry } = require('~/config'); @@ -731,6 +739,13 @@ const createAgentHandler = async (req, res) => { const validatedData = agentCreateSchema.parse(req.body); const { tools = [], ...agentData } = removeNullishValues(validatedData); + if (agentData.billing_mode !== undefined && !(await canManageAgentBilling(req))) { + return res.status(403).json({ + error: 'Only users with MANAGE_AGENTS can configure agent billing mode.', + status: 'error', + }); + } + if ( (!isCodeInterpreterCapabilityEnabled(req) || !tools.includes(Tools.execute_code)) && agentData.tool_options != null @@ -1063,6 +1078,15 @@ const updateAgentHandler = async (req, res) => { if (!validateAgentCodeEnvironmentAllowlist(req, res, validatedData.code_environment_ids)) { return; } + + if (validatedData.billing_mode !== undefined && !(await canManageAgentBilling(req))) { + return res.status(403).json({ + error: 'Only users with MANAGE_AGENTS can configure agent billing mode.', + status: 'error', + }); + } + + // Preserve explicit null for avatar to allow resetting the avatar const { avatar: avatarField, @@ -1455,6 +1479,7 @@ const duplicateAgentHandler = async (req, res) => { tool_resources: _tool_resources = {}, versions: _versions, __v: _v, + billing_mode: _billingMode, ...cloneData } = agent; cloneData.name = `${agent.name} (${new Date().toLocaleString('en-US', { diff --git a/api/server/controllers/agents/v1.spec.js b/api/server/controllers/agents/v1.spec.js index 228dab81aa..45897345b7 100644 --- a/api/server/controllers/agents/v1.spec.js +++ b/api/server/controllers/agents/v1.spec.js @@ -401,6 +401,67 @@ describe('Agent Controllers - Mass Assignment Protection', () => { }); describe('createAgentHandler', () => { + test('rejects billing_mode configuration without MANAGE_AGENTS', async () => { + mockReq.body = { + name: 'Agent Billing Restricted', + provider: 'openai', + model: 'gpt-4', + billing_mode: 'agent', + }; + + await createAgentHandler(mockReq, mockRes); + + expect(mockRes.status).toHaveBeenCalledWith(403); + expect(mockRes.json).toHaveBeenCalledWith({ + error: 'Only users with MANAGE_AGENTS can configure agent billing mode.', + status: 'error', + }); + expect(await Agent.countDocuments()).toBe(0); + }); + + test('allows billing_mode configuration with MANAGE_AGENTS', async () => { + await db.grantCapability({ + principalType: PrincipalType.ROLE, + principalId: mockReq.user.role, + capability: SystemCapabilities.MANAGE_AGENTS, + }); + + mockReq.body = { + name: 'Agent Billing Enabled', + provider: 'openai', + model: 'gpt-4', + billing_mode: 'agent', + }; + + await createAgentHandler(mockReq, mockRes); + + expect(mockRes.status).toHaveBeenCalledWith(201); + + const createdAgent = mockRes.json.mock.calls[0][0]; + expect(createdAgent.billing_mode).toBe('agent'); + + await db.revokeCapability({ + principalType: PrincipalType.ROLE, + principalId: mockReq.user.role, + capability: SystemCapabilities.MANAGE_AGENTS, + }); + }); + + test('preserves user billing mode as the default when omitted', async () => { + mockReq.body = { + name: 'Default User Billing', + provider: 'openai', + model: 'gpt-4', + }; + + await createAgentHandler(mockReq, mockRes); + + expect(mockRes.status).toHaveBeenCalledWith(201); + + const createdAgent = mockRes.json.mock.calls[0][0]; + expect(createdAgent.billing_mode).toBe('user'); + }); + test('removes programmatic tool options when Code Interpreter capability is disabled', async () => { mockReq.body = { name: 'Invalid Programmatic Agent', @@ -1635,6 +1696,56 @@ describe('Agent Controllers - Mass Assignment Protection', () => { }); describe('updateAgentHandler', () => { + test('rejects billing_mode changes without MANAGE_AGENTS', async () => { + const agent = await Agent.create({ + id: `agent_${nanoid(12)}`, + name: 'Existing Billing Agent', + provider: 'openai', + model: 'gpt-4', + author: mockReq.user.id, + }); + + mockReq.params.id = agent.id; + mockReq.body = { billing_mode: 'agent' }; + + await updateAgentHandler(mockReq, mockRes); + + expect(mockRes.status).toHaveBeenCalledWith(403); + + const unchanged = await Agent.findOne({ id: agent.id }).lean(); + expect(unchanged.billing_mode).toBe('user'); + }); + + test('allows billing_mode changes with MANAGE_AGENTS', async () => { + await db.grantCapability({ + principalType: PrincipalType.ROLE, + principalId: mockReq.user.role, + capability: SystemCapabilities.MANAGE_AGENTS, + }); + + const agent = await Agent.create({ + id: `agent_${nanoid(12)}`, + name: 'Existing Billing Agent', + provider: 'openai', + model: 'gpt-4', + author: mockReq.user.id, + }); + + mockReq.params.id = agent.id; + mockReq.body = { billing_mode: 'agent' }; + + await updateAgentHandler(mockReq, mockRes); + + const updated = await Agent.findOne({ id: agent.id }).lean(); + expect(updated.billing_mode).toBe('agent'); + + await db.revokeCapability({ + principalType: PrincipalType.ROLE, + principalId: mockReq.user.role, + capability: SystemCapabilities.MANAGE_AGENTS, + }); + }); + let existingAgentId; let existingAgentAuthorId; diff --git a/api/server/services/Endpoints/agents/initialize.js b/api/server/services/Endpoints/agents/initialize.js index a76b677ac5..adf3dc3ba6 100644 --- a/api/server/services/Endpoints/agents/initialize.js +++ b/api/server/services/Endpoints/agents/initialize.js @@ -522,6 +522,7 @@ const initializeClientWithProvider = async ({ userMCPAuthMap: ctx.userMCPAuthMap, upstreamTokenProvider, upstreamTokenProviderResolver, + rootAgentBillingMode: (await primaryAgentPromise)?.billing_mode, tool_resources: ctx.tool_resources, actionsEnabled: ctx.actionsEnabled, accessibleMcpServerNames: ctx.accessibleMcpServerNames, diff --git a/api/server/services/Schedules/access.js b/api/server/services/Schedules/access.js index a278b4e339..34304c7feb 100644 --- a/api/server/services/Schedules/access.js +++ b/api/server/services/Schedules/access.js @@ -15,4 +15,10 @@ const resolveAgentFireAccess = createResolveAgentFireAccess({ checkPermission, }); -module.exports = { resolveAgentFireAccess }; +const getAgentBillingMode = async (agentId) => { + const agent = await mongoose.models.Agent.findOne({ id: agentId }).select('billing_mode').lean(); + + return agent?.billing_mode; +}; + +module.exports = { resolveAgentFireAccess, getAgentBillingMode }; diff --git a/api/server/services/Schedules/index.js b/api/server/services/Schedules/index.js index d81891bb82..08b15013e2 100644 --- a/api/server/services/Schedules/index.js +++ b/api/server/services/Schedules/index.js @@ -17,7 +17,7 @@ function getService() { enqueueAgentTrigger, getAgentTriggerDelivery, } = require('~/server/services/Agents/triggers'); - const { resolveAgentFireAccess } = require('./access'); + const { resolveAgentFireAccess, getAgentBillingMode } = require('./access'); const methods = require('~/models'); const isUserDeleting = async (userId) => !(await methods.isAgentTriggerPrincipalActive(userId)); @@ -45,6 +45,7 @@ function getService() { // deferred Retry-After) or a dead-letter apart from a genuinely orphaned run. getTriggerDelivery: getAgentTriggerDelivery, resolveAgentFireAccess, + getAgentBillingMode, // Chat projects are user-owned, so this scoped read is both the existence and the // authorization check the fire-time destination precheck needs. getChatProject: (userId, projectId) => methods.getChatProject(userId, projectId), diff --git a/api/server/services/ToolService.js b/api/server/services/ToolService.js index 16bdb21fec..aabf05067c 100644 --- a/api/server/services/ToolService.js +++ b/api/server/services/ToolService.js @@ -2188,6 +2188,7 @@ async function loadToolsForExecution({ actionsEnabled, accessibleMcpServerNames, runFileCodeExecutionContext, + rootAgentBillingMode, }) { const appConfig = req.config; const allLoadedTools = []; @@ -2524,6 +2525,7 @@ async function loadToolsForExecution({ requestScopedConnections: mcpRequestScopedConnections, upstreamTokenProvider, upstreamTokenProviderResolver, + rootAgentBillingMode, [Tools.web_search]: webSearchCallbacks, }, webSearch: appConfig?.webSearch, diff --git a/packages/api/src/agents/transactions.spec.ts b/packages/api/src/agents/transactions.spec.ts index 8027660a45..7d47de3d79 100644 --- a/packages/api/src/agents/transactions.spec.ts +++ b/packages/api/src/agents/transactions.spec.ts @@ -65,6 +65,67 @@ const mockPricing: PricingFns = { getCacheMultiplier: jest.fn().mockReturnValue(null), }; +describe('transaction agent attribution', () => { + const pricing: PricingFns = { + getMultiplier: () => 1, + getCacheMultiplier: () => 1, + }; + + it('preserves agentId and rootAgentId in standard token transactions', () => { + const entries = prepareTokenSpend( + { + user: 'user-1', + conversationId: 'conversation-1', + context: 'completion', + model: 'test-model', + agentId: 'agent-child', + rootAgentId: 'agent-root', + transactions: { enabled: true }, + }, + { + promptTokens: 10, + completionTokens: 5, + }, + pricing, + ); + + expect(entries).toHaveLength(2); + expect(entries[0].doc.agentId).toBe('agent-child'); + expect(entries[0].doc.rootAgentId).toBe('agent-root'); + expect(entries[1].doc.agentId).toBe('agent-child'); + expect(entries[1].doc.rootAgentId).toBe('agent-root'); + }); + + it('preserves agentId and rootAgentId in structured token transactions', () => { + const entries = prepareStructuredTokenSpend( + { + user: 'user-1', + conversationId: 'conversation-1', + context: 'completion', + model: 'test-model', + agentId: 'agent-child', + rootAgentId: 'agent-root', + transactions: { enabled: true }, + }, + { + promptTokens: { + input: 10, + write: 2, + read: 3, + }, + completionTokens: 5, + }, + pricing, + ); + + expect(entries).toHaveLength(2); + expect(entries[0].doc.agentId).toBe('agent-child'); + expect(entries[0].doc.rootAgentId).toBe('agent-root'); + expect(entries[1].doc.agentId).toBe('agent-child'); + expect(entries[1].doc.rootAgentId).toBe('agent-root'); + }); +}); + describe('prepareTokenSpend', () => { beforeEach(() => { jest.clearAllMocks(); @@ -499,3 +560,90 @@ describe('end-to-end: prepare → bulk write → verify', () => { expect(bal!.tokenCredits).toBeLessThan(5000); }); }); + +describe('bulkWriteTransactions balance behavior', () => { + it('does not update balance when all prepared entries have balance disabled', async () => { + const insertMany = jest.fn().mockResolvedValue(undefined); + const updateBalance = jest.fn().mockResolvedValue(undefined); + + await bulkWriteTransactions( + { + user: 'user-1', + docs: [ + { + doc: { + user: 'user-1', + conversationId: 'conversation-1', + tokenType: 'prompt', + model: 'test-model', + context: 'message', + rawAmount: -1, + tokenValue: 1000, + }, + tokenValue: 1000, + balance: { + enabled: false, + }, + }, + ], + }, + { + insertMany, + updateBalance, + }, + ); + + expect(insertMany).toHaveBeenCalledTimes(1); + expect(insertMany).toHaveBeenCalledWith([ + { + user: 'user-1', + conversationId: 'conversation-1', + tokenType: 'prompt', + model: 'test-model', + context: 'message', + rawAmount: -1, + tokenValue: 1000, + }, + ]); + expect(updateBalance).not.toHaveBeenCalled(); + }); + + it('updates balance when a prepared entry enables balance deduction', async () => { + const insertMany = jest.fn().mockResolvedValue(undefined); + const updateBalance = jest.fn().mockResolvedValue(undefined); + + await bulkWriteTransactions( + { + user: 'user-1', + docs: [ + { + doc: { + user: 'user-1', + conversationId: 'conversation-1', + tokenType: 'prompt', + model: 'test-model', + context: 'message', + rawAmount: -1, + tokenValue: 1000, + }, + tokenValue: 1000, + balance: { + enabled: true, + }, + }, + ], + }, + { + insertMany, + updateBalance, + }, + ); + + expect(insertMany).toHaveBeenCalledTimes(1); + expect(updateBalance).toHaveBeenCalledTimes(1); + expect(updateBalance).toHaveBeenCalledWith({ + user: 'user-1', + incrementValue: 1000, + }); + }); +}); diff --git a/packages/api/src/agents/transactions.ts b/packages/api/src/agents/transactions.ts index 146c9d5ce1..2f1314ae09 100644 --- a/packages/api/src/agents/transactions.ts +++ b/packages/api/src/agents/transactions.ts @@ -85,6 +85,8 @@ export interface TxMetadata { context: string; messageId?: string; conversationId: string; + agentId?: string; + rootAgentId?: string; balance?: Partial | null; transactions?: Partial; endpointTokenConfig?: EndpointTokenConfig; diff --git a/packages/api/src/agents/usage.spec.ts b/packages/api/src/agents/usage.spec.ts index 7dbda10b09..f49c08c0b2 100644 --- a/packages/api/src/agents/usage.spec.ts +++ b/packages/api/src/agents/usage.spec.ts @@ -20,6 +20,7 @@ import { computeSummaryUsedTokens, priorRunOutputTokens, resolveRetainedToolTokens, + applyAgentBillingMode, } from './usage'; import { runWithDetachedSubagentUsage } from './subagentTaskContext'; import Tokenizer from '~/utils/tokenizer'; @@ -2897,3 +2898,64 @@ describe('hasRecordedPrimaryUsage', () => { expect(hasRecordedPrimaryUsage(undefined)).toBe(false); }); }); + +describe('applyAgentBillingMode', () => { + it('disables user balance deduction for agent-billed runs', () => { + const balance = { + enabled: true, + startBalance: 100, + autoRefill: false, + }; + + const result = applyAgentBillingMode(balance, 'agent'); + + expect(result).toEqual({ + ...balance, + enabled: false, + }); + + // The helper must not mutate the caller's config. + expect(balance.enabled).toBe(true); + }); + + it('preserves balance configuration for user-billed runs', () => { + const balance = { + enabled: true, + startBalance: 100, + }; + + expect(applyAgentBillingMode(balance, 'user')).toEqual(balance); + }); + + it('preserves legacy behavior when billing_mode is absent', () => { + const balance = { + enabled: true, + startBalance: 100, + }; + + expect(applyAgentBillingMode(balance, undefined)).toEqual(balance); + }); + + it('preserves disabled balance configuration', () => { + const balance = { + enabled: false, + startBalance: 100, + }; + + expect(applyAgentBillingMode(balance, 'agent')).toEqual(balance); + }); + + it('preserves the transaction configuration independently', () => { + const balance = { + enabled: true, + }; + const transactions = { + enabled: true, + }; + + const result = applyAgentBillingMode(balance, 'agent'); + + expect(result?.enabled).toBe(false); + expect(transactions.enabled).toBe(true); + }); +}); diff --git a/packages/api/src/agents/usage.ts b/packages/api/src/agents/usage.ts index 52158b175c..197c9688a7 100644 --- a/packages/api/src/agents/usage.ts +++ b/packages/api/src/agents/usage.ts @@ -848,6 +848,29 @@ export async function recordFallbackTokenUsage( } } +/** + * Applies the root agent's billing mode to the balance configuration. + * + * Agent-billed runs still create transaction records and remain fully + * attributable for reporting. Only the user's balance mutation is disabled. + * + * The default is deliberately unchanged: missing/unknown billing_mode means + * user billing. + */ +export function applyAgentBillingMode( + balance: Partial | null | undefined, + billingMode?: string, +): Partial | null | undefined { + if (billingMode !== 'agent' || balance == null) { + return balance; + } + + return { + ...balance, + enabled: false, + }; +} + export interface RecordUsageParams { user: string; conversationId: string; @@ -855,6 +878,8 @@ export interface RecordUsageParams { model?: string; context?: string; messageId?: string; + /** Root agent controlling billing for the complete run. */ + rootAgentId?: string; balance?: Partial | null; transactions?: Partial; endpointTokenConfig?: EndpointTokenConfig; @@ -879,6 +904,8 @@ export interface DetachedSubagentUsageRecorderParams { conversationId: string; model?: string; messageId?: string; + /** Root agent whose billing mode controls detached child usage. */ + rootAgentId?: string; balance?: Partial | null; transactions?: Partial; endpointTokenConfig?: EndpointTokenConfig; @@ -901,6 +928,7 @@ export async function recordCollectedUsage( model, balance, messageId, + rootAgentId, transactions, conversationId, collectedUsage, @@ -966,6 +994,8 @@ export async function recordCollectedUsage( messageId, transactions, conversationId, + /** Root agent whose billing mode controls this complete run. */ + rootAgentId, /** Price with the producing agent's endpoint config when a resolver is * provided (multi-endpoint graphs); it owns the fallback to the primary * config, so `undefined` here means built-in pricing, not the batch one. */ @@ -1092,6 +1122,7 @@ export function createDetachedSubagentUsageRecorder( model: billing.model, context: 'subagent', messageId: billing.messageId, + rootAgentId: billing.rootAgentId, balance: billing.balance, transactions: billing.transactions, endpointTokenConfig: billing.endpointTokenConfig, diff --git a/packages/api/src/agents/validation.ts b/packages/api/src/agents/validation.ts index e1569bbeab..29b07344e2 100644 --- a/packages/api/src/agents/validation.ts +++ b/packages/api/src/agents/validation.ts @@ -5,6 +5,7 @@ import { MAX_AGENT_CODE_ENVIRONMENT_CHOICES, MemoryScope, SkillsScope, + AgentBillingMode, getMaxSubagents, agentGitIdentitySchema, resolveModelCatalogKey, @@ -446,6 +447,7 @@ type AgentBaseShape = { skill_authoring_enabled: z.ZodOptional; skills_scope: z.ZodOptional>; memory_scope: z.ZodOptional>; + billing_mode: z.ZodOptional>; /** @deprecated Use edges instead */ agent_ids: z.ZodOptional>; edges: z.ZodOptional>; @@ -481,6 +483,7 @@ export const agentBaseSchema: z.ZodObject = z.object({ skill_authoring_enabled: z.boolean().optional(), skills_scope: z.nativeEnum(SkillsScope).optional(), memory_scope: z.nativeEnum(MemoryScope).optional(), + billing_mode: z.nativeEnum(AgentBillingMode).optional(), /** @deprecated Use edges instead */ agent_ids: z.array(z.string()).optional(), edges: z.array(graphEdgeSchema).optional(), diff --git a/packages/api/src/schedules/fire.ts b/packages/api/src/schedules/fire.ts index 48ad22cf7a..308b287be9 100644 --- a/packages/api/src/schedules/fire.ts +++ b/packages/api/src/schedules/fire.ts @@ -356,7 +356,7 @@ export async function fireSchedule( ); } - if (await deps.isOutOfBalance(user)) { + if (await deps.isOutOfBalance(user, schedule.agent_id)) { // Revalidate BEFORE writing the skip. Everything above (user, config, permission // and balance lookups) can outlast the 5-minute lease, and a skip is not a no-op: // it stamps the card and walks the balance-skip streak toward auto-disable. Under diff --git a/packages/api/src/schedules/gate.spec.ts b/packages/api/src/schedules/gate.spec.ts index b56c997d6e..f1163383c6 100644 --- a/packages/api/src/schedules/gate.spec.ts +++ b/packages/api/src/schedules/gate.spec.ts @@ -33,6 +33,7 @@ function makeService(base: Cfg, merged: Cfg = base) { initializeNullBalance: jest.fn(async () => null), preflightMCP: jest.fn().mockResolvedValue([]), resolveAgentFireAccess: jest.fn(async () => 'ok' as const), + getAgentBillingMode: jest.fn(async () => 'user' as const), getChatProject: jest.fn(async () => ({ _id: 'proj-1' })), isUserDeleting: jest.fn(async () => false), enqueueAgentTrigger: jest.fn(async () => undefined), @@ -169,6 +170,7 @@ describe('v1 experimental gate, asserted at real entry points', () => { initializeNullBalance: jest.fn(), preflightMCP: jest.fn().mockResolvedValue([]), resolveAgentFireAccess: jest.fn(), + getAgentBillingMode: jest.fn(), getChatProject: jest.fn(), } as unknown as SchedulesServiceDeps), ).toThrow(/isUserDeleting/); diff --git a/packages/api/src/schedules/service.spec.ts b/packages/api/src/schedules/service.spec.ts index 2f16fc8728..6c606926bb 100644 --- a/packages/api/src/schedules/service.spec.ts +++ b/packages/api/src/schedules/service.spec.ts @@ -79,6 +79,7 @@ function makeService( initializeNullBalance: jest.fn(async () => null), preflightMCP: jest.fn().mockResolvedValue([]), resolveAgentFireAccess: jest.fn(async () => 'ok' as const), + getAgentBillingMode: jest.fn(async () => 'user' as const), getChatProject: jest.fn(async () => ({ _id: 'proj-1' })), isUserDeleting: jest.fn(async () => false), enqueueAgentTrigger, @@ -187,6 +188,7 @@ describe('balance initialization', () => { initializeNullBalance, preflightMCP: jest.fn().mockResolvedValue([]), resolveAgentFireAccess: jest.fn(async () => 'ok' as const), + getAgentBillingMode: jest.fn(async () => 'user' as const), getChatProject: jest.fn(async () => ({ _id: 'proj-1' })), isUserDeleting: jest.fn(async () => false), enqueueAgentTrigger: jest.fn(async () => undefined), @@ -315,6 +317,7 @@ describe('balance initialization', () => { initializeNullBalance, preflightMCP: jest.fn().mockResolvedValue([]), resolveAgentFireAccess: jest.fn(async () => 'ok' as const), + getAgentBillingMode: jest.fn(async () => 'user' as const), getChatProject: jest.fn(async () => ({ _id: 'proj-1' })), isUserDeleting: jest.fn(async () => false), enqueueAgentTrigger: jest.fn(async () => undefined), @@ -1987,6 +1990,7 @@ describe('scheduled resume capacity', () => { initializeNullBalance: jest.fn(async () => null), preflightMCP: jest.fn().mockResolvedValue([]), resolveAgentFireAccess: jest.fn(async () => 'ok' as const), + getAgentBillingMode: jest.fn(async () => 'user' as const), getChatProject: jest.fn(async () => ('project' in over ? over.project : { _id: 'proj-1' })), isUserDeleting: jest.fn(async () => false), enqueueAgentTrigger: jest.fn(async () => undefined), @@ -2744,6 +2748,64 @@ it('interrupts an A3 admission wait at shutdown without a model-visible policy r await outcome; signal.mockRestore(); } +describe('agent billing balance gate', () => { + const makeBalanceGateService = (billingMode: 'user' | 'agent' | undefined) => { + const getAppConfig = jest.fn(async () => ({ + interface: { schedules: true }, + balance: { enabled: true }, + })); + const getAgentBillingMode = jest.fn(async () => billingMode); + + const service = createSchedulesService({ + methods: {} as unknown as SchedulesServiceDeps['methods'], + getAppConfig, + findUserById: jest.fn(async () => null), + findBalance: jest.fn(async () => ({ tokenCredits: 0 })), + upsertBalance: jest.fn(async () => null), + initializeNullBalance: jest.fn(async () => null), + preflightMCP: jest.fn().mockResolvedValue([]), + resolveAgentFireAccess: jest.fn(async () => 'ok' as const), + getAgentBillingMode, + getChatProject: jest.fn(async () => ({ _id: 'proj-1' })), + isUserDeleting: jest.fn(async () => false), + enqueueAgentTrigger: jest.fn(async () => undefined), + getTriggerDelivery: jest.fn(async () => null), + } as unknown as SchedulesServiceDeps); + + return { service, getAppConfig, getAgentBillingMode }; + }; + + it('does not gate a separately billed scheduled agent on user balance', async () => { + const { service, getAppConfig, getAgentBillingMode } = makeBalanceGateService('agent'); + + await expect( + service.engineDeps.isOutOfBalance({ id: 'user-1' } as never, 'agent-1'), + ).resolves.toBe(false); + + expect(getAgentBillingMode).toHaveBeenCalledWith('agent-1'); + expect(getAppConfig).not.toHaveBeenCalled(); + }); + + it('preserves the existing user balance gate for user-billed agents', async () => { + const { service, getAppConfig, getAgentBillingMode } = makeBalanceGateService('user'); + + await expect( + service.engineDeps.isOutOfBalance({ id: 'user-1' } as never, 'agent-1'), + ).resolves.toBe(true); + + expect(getAgentBillingMode).toHaveBeenCalledWith('agent-1'); + expect(getAppConfig).toHaveBeenCalled(); + }); + + it('preserves the legacy balance gate when no agent is supplied', async () => { + const { service, getAppConfig, getAgentBillingMode } = makeBalanceGateService(undefined); + + await expect(service.engineDeps.isOutOfBalance({ id: 'user-1' } as never)).resolves.toBe(true); + + expect(getAgentBillingMode).not.toHaveBeenCalled(); + expect(getAppConfig).toHaveBeenCalled(); + }); + }); describe('scheduled reset policy synchronization', () => { diff --git a/packages/api/src/schedules/service.ts b/packages/api/src/schedules/service.ts index 5592aed9a6..6b13e000fb 100644 --- a/packages/api/src/schedules/service.ts +++ b/packages/api/src/schedules/service.ts @@ -195,6 +195,7 @@ export interface SchedulesServiceDeps { agentId: string, user: ScheduleUserContext, ) => Promise<'ok' | 'missing' | 'forbidden'>; + getAgentBillingMode: (agentId: string) => Promise<'user' | 'agent' | undefined>; /** Loads a chat project scoped to its owner, or null when it does not exist for * them. Chat projects are user-owned, so this is both the existence check and the * authorization check. */ @@ -644,6 +645,7 @@ export function createSchedulesService( 'upsertBalance', 'initializeNullBalance', 'resolveAgentFireAccess', + 'getAgentBillingMode', 'getChatProject', 'isUserDeleting', 'enqueueAgentTrigger', @@ -700,7 +702,11 @@ export function createSchedulesService( const role = await methods.getRoleByName(user.role); return role?.permissions?.[PermissionTypes.SCHEDULES]?.[Permissions.USE] === true; }, - isOutOfBalance: async (user) => { + isOutOfBalance: async (user, agentId) => { + if (agentId != null && (await deps.getAgentBillingMode(agentId)) === 'agent') { + return false; + } + const appConfig = await deps.getAppConfig(getAppConfigOptionsFromUser(user)); const balanceConfig = getBalanceConfig(appConfig); if (balanceConfig?.enabled !== true) { diff --git a/packages/api/src/schedules/types.ts b/packages/api/src/schedules/types.ts index 6d1dcd15ed..97c2535a43 100644 --- a/packages/api/src/schedules/types.ts +++ b/packages/api/src/schedules/types.ts @@ -193,7 +193,7 @@ export interface ScheduleEngineDeps { /** Loads the owning user (id + tenant) or null when deleted/disabled. */ getUserContext: (userId: string | Types.ObjectId) => Promise; /** Whether the balance feature gates this user and they are out of credits. */ - isOutOfBalance: (user: ScheduleUserContext) => Promise; + isOutOfBalance: (user: ScheduleUserContext, agentId?: string) => Promise; /** Live agent access for the owner: 'missing' (deleted) vs 'forbidden' (ACL revoked). */ agentAccess: ( agentId: string, diff --git a/packages/data-provider/src/schemas.ts b/packages/data-provider/src/schemas.ts index 0efafbaf1b..9d759ac166 100644 --- a/packages/data-provider/src/schemas.ts +++ b/packages/data-provider/src/schemas.ts @@ -458,6 +458,8 @@ export const defaultAgentFormValues = { | undefined, /** Memory partition: 'agent' isolates memories per (user, agent); default shared pool */ memory_scope: undefined as MemoryScope | undefined, + /** Usage billing owner; legacy/default behavior charges the invoking user. */ + billing_mode: undefined as AgentBillingMode | undefined, }; export const ImageVisionTool: FunctionTool = { @@ -1047,6 +1049,12 @@ export enum MemoryScope { agent = 'agent', } +/** Determines whether an agent's usage is charged to the invoking user or the agent. */ +export enum AgentBillingMode { + user = 'user', + agent = 'agent', +} + /** Catalog exposure for a persisted agent with skills enabled. */ export enum SkillsScope { all = 'all', diff --git a/packages/data-provider/src/types/agents.ts b/packages/data-provider/src/types/agents.ts index f7542c1079..25fbf19c37 100644 --- a/packages/data-provider/src/types/agents.ts +++ b/packages/data-provider/src/types/agents.ts @@ -7,7 +7,14 @@ import type { ToolApprovalGrantBinding, } from './tools'; import type { TPromptGroupSource, NativePromptSelection, LangfusePromptSelection } from '../types'; -import type { TAttachment, TPlugin, AgentProvider, MemoryScope, SkillsScope } from 'src/schemas'; +import type { + TAttachment, + TPlugin, + AgentProvider, + MemoryScope, + SkillsScope, + AgentBillingMode, +} from 'src/schemas'; import type { TTokenUsageEvent, TContextUsageEvent, TPendingSteer } from './runs'; import type { StatefulCodeEnvironment } from '../stateful-code'; import type { SummaryContentPart } from './content'; diff --git a/packages/data-schemas/src/schema/agent.ts b/packages/data-schemas/src/schema/agent.ts index be6e471585..e87f695372 100644 --- a/packages/data-schemas/src/schema/agent.ts +++ b/packages/data-schemas/src/schema/agent.ts @@ -184,6 +184,11 @@ const agentSchema: Schema = new Schema( enum: ['user', 'agent'], default: undefined, }, + billing_mode: { + type: String, + enum: ['user', 'agent'], + default: 'user', + }, tenantId: { type: String, index: true, diff --git a/packages/data-schemas/src/schema/transaction.ts b/packages/data-schemas/src/schema/transaction.ts index bb41494696..ef1f7bdda3 100644 --- a/packages/data-schemas/src/schema/transaction.ts +++ b/packages/data-schemas/src/schema/transaction.ts @@ -15,6 +15,8 @@ export interface ITransaction extends Document { writeTokens?: number; readTokens?: number; messageId?: string; + agentId?: string; + rootAgentId?: string; createdAt?: Date; updatedAt?: Date; tenantId?: string; @@ -55,6 +57,14 @@ const transactionSchema: Schema = new Schema( writeTokens: { type: Number }, readTokens: { type: Number }, messageId: { type: String }, + agentId: { + type: String, + index: true, + }, + rootAgentId: { + type: String, + index: true, + }, tenantId: { type: String, index: true, diff --git a/packages/data-schemas/src/types/agent.ts b/packages/data-schemas/src/types/agent.ts index 9fe0945970..623c2da74a 100644 --- a/packages/data-schemas/src/types/agent.ts +++ b/packages/data-schemas/src/types/agent.ts @@ -3,6 +3,7 @@ import type { GraphEdge, MemoryScope, SkillsScope, + AgentBillingMode, AgentToolOptions, AgentToolResources, AgentSubagentsConfig, @@ -67,5 +68,6 @@ export interface IAgent extends Omit { subagents?: AgentSubagentsConfig; /** Memory partition: 'agent' isolates memories per (user, agent); default shared pool */ memory_scope?: MemoryScope; + billing_mode?: AgentBillingMode; tenantId?: string; } diff --git a/packages/data-schemas/src/types/transaction.ts b/packages/data-schemas/src/types/transaction.ts index 978d7fd62b..b2965374a6 100644 --- a/packages/data-schemas/src/types/transaction.ts +++ b/packages/data-schemas/src/types/transaction.ts @@ -14,4 +14,6 @@ export interface TransactionData { messageId?: string; inputTokenCount?: number; rateDetail?: Record; + agentId?: string; + rootAgentId?: string; }