feat(agents): add agent-level billing mode

This commit is contained in:
Muhammed Nihal P N 2026-09-28 13:17:43 +05:30
parent 44eb8fea36
commit 762452efcc
28 changed files with 543 additions and 15 deletions

View file

@ -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(

View file

@ -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);
});

View file

@ -207,6 +207,7 @@ const loadTools = async ({
imageFiles,
userId: user,
fileStrategy,
rootAgentBillingMode: options.rootAgentBillingMode,
});
},
};

View file

@ -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 },
);
}

View file

@ -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,

View file

@ -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,

View file

@ -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', {

View file

@ -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;

View file

@ -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,

View file

@ -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 };

View file

@ -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),

View file

@ -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,

View file

@ -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,
});
});
});

View file

@ -85,6 +85,8 @@ export interface TxMetadata {
context: string;
messageId?: string;
conversationId: string;
agentId?: string;
rootAgentId?: string;
balance?: Partial<TCustomConfig['balance']> | null;
transactions?: Partial<TTransactionsConfig>;
endpointTokenConfig?: EndpointTokenConfig;

View file

@ -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);
});
});

View file

@ -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<TCustomConfig['balance']> | null | undefined,
billingMode?: string,
): Partial<TCustomConfig['balance']> | 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<TCustomConfig['balance']> | null;
transactions?: Partial<TTransactionsConfig>;
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<TCustomConfig['balance']> | null;
transactions?: Partial<TTransactionsConfig>;
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,

View file

@ -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<z.ZodBoolean>;
skills_scope: z.ZodOptional<z.ZodEnum<typeof SkillsScope>>;
memory_scope: z.ZodOptional<z.ZodEnum<typeof MemoryScope>>;
billing_mode: z.ZodOptional<z.ZodNativeEnum<typeof AgentBillingMode>>;
/** @deprecated Use edges instead */
agent_ids: z.ZodOptional<z.ZodArray<z.ZodString>>;
edges: z.ZodOptional<z.ZodArray<typeof graphEdgeSchema>>;
@ -481,6 +483,7 @@ export const agentBaseSchema: z.ZodObject<AgentBaseShape> = 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(),

View file

@ -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

View file

@ -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/);

View file

@ -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', () => {

View file

@ -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) {

View file

@ -193,7 +193,7 @@ export interface ScheduleEngineDeps {
/** Loads the owning user (id + tenant) or null when deleted/disabled. */
getUserContext: (userId: string | Types.ObjectId) => Promise<ScheduleUserContext | null>;
/** Whether the balance feature gates this user and they are out of credits. */
isOutOfBalance: (user: ScheduleUserContext) => Promise<boolean>;
isOutOfBalance: (user: ScheduleUserContext, agentId?: string) => Promise<boolean>;
/** Live agent access for the owner: 'missing' (deleted) vs 'forbidden' (ACL revoked). */
agentAccess: (
agentId: string,

View file

@ -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',

View file

@ -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';

View file

@ -184,6 +184,11 @@ const agentSchema: Schema<IAgent> = new Schema<IAgent>(
enum: ['user', 'agent'],
default: undefined,
},
billing_mode: {
type: String,
enum: ['user', 'agent'],
default: 'user',
},
tenantId: {
type: String,
index: true,

View file

@ -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<ITransaction> = 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,

View file

@ -3,6 +3,7 @@ import type {
GraphEdge,
MemoryScope,
SkillsScope,
AgentBillingMode,
AgentToolOptions,
AgentToolResources,
AgentSubagentsConfig,
@ -67,5 +68,6 @@ export interface IAgent extends Omit<Document, 'model'> {
subagents?: AgentSubagentsConfig;
/** Memory partition: 'agent' isolates memories per (user, agent); default shared pool */
memory_scope?: MemoryScope;
billing_mode?: AgentBillingMode;
tenantId?: string;
}

View file

@ -14,4 +14,6 @@ export interface TransactionData {
messageId?: string;
inputTokenCount?: number;
rateDetail?: Record<string, number>;
agentId?: string;
rootAgentId?: string;
}