Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(agent-run): charge the run fee for server-dispatched external agents (#22602)

YuTengjing0bf1a622a654
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.interruptTask.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.interruptTask.test.ts
index 961b1232a1f..fabb0fcf15a 100644
--- a/apps/server/src/routers/lambda/__tests__/aiAgent.interruptTask.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.interruptTask.test.ts
@@ -1,6 +1,13 @@
// @vitest-environment node
import { type LobeChatDatabase } from '@lobechat/database';
-import { agents, chatGroups, sessions, threads, topics } from '@lobechat/database/schemas';
+import {
+ agentOperations,
+ agents,
+ chatGroups,
+ sessions,
+ threads,
+ topics,
+} from '@lobechat/database/schemas';
import { getTestDB } from '@lobechat/database/test-utils';
import { ThreadStatus, ThreadType } from '@lobechat/types';
import { eq } from 'drizzle-orm';
@@ -48,6 +55,13 @@ vi.mock('@/server/services/deviceGateway', () => ({
getScopedOnlineDevices: vi.fn(() => []),
}));
+const { mockSettleAgentRunFee } = vi.hoisted(() => ({
+ mockSettleAgentRunFee: vi.fn(),
+}));
+vi.mock('@/business/server/agent-run/runFee', () => ({
+ settleAgentRunFee: mockSettleAgentRunFee,
+}));
+
describe('aiAgentRouter.interruptTask', () => {
let serverDB: LobeChatDatabase;
let userId: string;
@@ -64,6 +78,7 @@ describe('aiAgentRouter.interruptTask', () => {
mockInterruptOperation.mockResolvedValue(true);
mockExecuteToolCall.mockReset();
mockExecuteToolCall.mockResolvedValue({ content: '{}', success: true });
+ mockSettleAgentRunFee.mockReset();
// Create test agent
const [agent] = await serverDB
@@ -376,6 +391,74 @@ describe('aiAgentRouter.interruptTask', () => {
},
);
+ // Regression: a stopped device CLI run never reaches CompletionLifecycle
+ // (heteroFinish skips a cancelled run), so its run fee stayed held until
+ // the hold expired instead of being charged or given back.
+ describe('run fee of a stopped device run', () => {
+ const seedRunningCodexRun = async (operationId: string) => {
+ await serverDB.insert(agentOperations).values({
+ id: operationId,
+ startedAt: new Date(Date.now() - 40_000),
+ status: 'running',
+ topicId: testTopicId,
+ userId,
+ });
+ await serverDB
+ .update(topics)
+ .set({
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'asst-fee',
+ deviceId: 'device-1',
+ heteroType: 'codex',
+ operationId,
+ },
+ },
+ })
+ .where(eq(topics.id, testTopicId));
+ mockExecuteToolCall.mockResolvedValue({ state: { exited: true }, success: true });
+ };
+
+ it('settles the fee as interrupted with the run duration once the device exits', async () => {
+ await seedRunningCodexRun('op-fee-stop');
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await caller.interruptTask({ operationId: 'op-fee-stop', topicId: testTopicId });
+
+ expect(mockSettleAgentRunFee).toHaveBeenCalledTimes(1);
+ const [params] = mockSettleAgentRunFee.mock.calls[0];
+ expect(params).toMatchObject({
+ operationId: 'op-fee-stop',
+ reason: 'interrupted',
+ userId,
+ });
+ expect(params.durationMs).toBeGreaterThanOrEqual(40_000);
+ });
+
+ it('does not settle the fee again when a repeated stop finds the run already settled', async () => {
+ await seedRunningCodexRun('op-fee-stop-twice');
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await caller.interruptTask({ operationId: 'op-fee-stop-twice', topicId: testTopicId });
+ await caller.interruptTask({ operationId: 'op-fee-stop-twice', topicId: testTopicId });
+
+ expect(mockSettleAgentRunFee).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps the stop successful when settling the fee fails', async () => {
+ await seedRunningCodexRun('op-fee-stop-fails');
+ mockSettleAgentRunFee.mockRejectedValue(new Error('billing down'));
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ const result = await caller.interruptTask({
+ operationId: 'op-fee-stop-fails',
+ topicId: testTopicId,
+ });
+
+ expect(result.success).toBe(true);
+ });
+ });
+
it('does not dispatch cancelHeteroTask when the operation has no deviceId', async () => {
// runningOperation with heteroType but no deviceId — e.g. a cloud-sandbox
// run that has no remote process to kill.
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroRunFee.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroRunFee.test.ts
new file mode 100644
index 00000000000..ce4149edac9
--- /dev/null
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroRunFee.test.ts
@@ -0,0 +1,322 @@
+import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from 'vitest';
+
+import { AgentOperationModel } from '@/database/models/agentOperation';
+import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';
+
+import { AiAgentService } from '../index';
+
+const {
+ mockDeviceFindByDeviceId,
+ mockDeviceFindWorkspaceDeviceById,
+ mockDispatchAgentRun,
+ mockGetHeterogeneousResumeSessionId,
+ mockMessageCreate,
+ mockMessageQuery,
+ mockResolveAttachmentsByFileIds,
+} = vi.hoisted(() => ({
+ mockDeviceFindByDeviceId: vi.fn(),
+ mockDeviceFindWorkspaceDeviceById: vi.fn(),
+ mockDispatchAgentRun: vi.fn().mockResolvedValue({ success: true }),
+ mockGetHeterogeneousResumeSessionId: vi.fn().mockResolvedValue(undefined),
+ mockMessageCreate: vi.fn(),
+ mockMessageQuery: vi.fn(),
+ mockResolveAttachmentsByFileIds: vi.fn(),
+}));
+
+// The real factory probes Redis synchronously and throws in the test env.
+vi.mock('@/server/modules/AgentRuntime/factory', () => ({
+ createAgentStateManager: vi.fn(function () {
+ return {
+ createOperationMetadata: vi.fn().mockResolvedValue(undefined),
+ };
+ }),
+ createStreamEventManager: () => ({
+ publishAgentRuntimeEnd: vi.fn().mockResolvedValue('end-event-id'),
+ publishAgentRuntimeInit: vi.fn().mockResolvedValue('init-event-id'),
+ }),
+ isRedisAvailable: vi.fn(function () {
+ return false;
+ }),
+}));
+
+const emptyResolvedAttachments = {
+ audioList: [],
+ fileList: [],
+ imageList: [],
+ orderedFileIds: [],
+ videoList: [],
+ warnings: [],
+};
+
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(function () {
+ return {};
+ }),
+}));
+
+vi.mock('../ingestAttachment', () => ({
+ ingestAttachment: vi.fn(),
+}));
+
+vi.mock('@/libs/trusted-client', () => ({
+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),
+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),
+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),
+}));
+
+const fees = vi.hoisted(() => ({
+ holdAgentRunFee: vi.fn(),
+ rebindAgentRunFee: vi.fn(),
+ releaseAgentRunFee: vi.fn(),
+}));
+const mockSignHeteroOperationJWT = vi.hoisted(() => vi.fn());
+
+vi.mock('@/business/server/agent-run/runFee', () => fees);
+
+vi.mock('@/libs/trpc/utils/internalJwt', () => ({
+ signHeteroOperationJWT: mockSignHeteroOperationJWT,
+ signUserJWT: vi.fn().mockResolvedValue('user-jwt'),
+}));
+
+vi.mock('@/database/models/message', () => ({
+ MessageModel: vi.fn().mockImplementation(function () {
+ return {
+ create: mockMessageCreate,
+ getLatestNonToolMessageId: vi.fn().mockResolvedValue(undefined),
+ getLatestSpineMessageId: vi.fn().mockResolvedValue(undefined),
+ query: mockMessageQuery,
+ update: vi.fn().mockResolvedValue({}),
+ };
+ }),
+}));
+
+const heteroAgentConfig = {
+ agencyConfig: { heterogeneousProvider: { type: 'claude-code' } },
+ chatConfig: {},
+ files: [],
+ id: 'agent-1',
+ knowledgeBases: [],
+ model: 'claude-code',
+ plugins: [],
+ provider: 'anthropic',
+ systemRole: 'You are a helpful assistant',
+};
+
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn().mockImplementation(function () {
+ return {
+ getAgentConfig: vi.fn().mockResolvedValue(heteroAgentConfig),
+ queryAgents: vi.fn().mockResolvedValue([]),
+ };
+ }),
+}));
+
+vi.mock('@/database/models/device', () => ({
+ DeviceModel: vi.fn().mockImplementation(function () {
+ return {
+ findByDeviceId: mockDeviceFindByDeviceId,
+ findWorkspaceDeviceById: mockDeviceFindWorkspaceDeviceById,
+ };
+ }),
+}));
+
+vi.mock('@/server/services/agent', () => ({
+ AgentService: vi.fn().mockImplementation(function () {
+ return {
+ getAgentConfig: vi.fn().mockResolvedValue(heteroAgentConfig),
+ };
+ }),
+}));
+
+vi.mock('@/database/models/plugin', () => ({
+ PluginModel: vi.fn().mockImplementation(function () {
+ return {
+ query: vi.fn().mockResolvedValue([]),
+ };
+ }),
+}));
+
+const topicMock = {
+ appendRunningOperationChild: vi.fn().mockResolvedValue(true),
+ create: vi.fn().mockResolvedValue({ id: 'topic-1', metadata: undefined }),
+ findById: vi.fn().mockResolvedValue(undefined),
+ patchRunningOperation: vi.fn().mockResolvedValue(true),
+ settleRunningOperation: vi.fn().mockResolvedValue({ status: 'settled' }),
+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),
+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),
+ updateMetadata: vi.fn().mockResolvedValue(undefined),
+};
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: vi.fn().mockImplementation(function () {
+ return topicMock;
+ }),
+}));
+
+vi.mock('@/database/models/thread', () => ({
+ ThreadModel: vi.fn().mockImplementation(function () {
+ return {
+ create: vi.fn(),
+ findById: vi.fn(),
+ update: vi.fn(),
+ };
+ }),
+}));
+
+vi.mock('@/server/services/market', () => ({
+ MarketService: vi.fn().mockImplementation(function () {
+ return {
+ getLobehubSkillManifests: vi.fn().mockResolvedValue([]),
+ market: {
+ creds: {
+ get: vi.fn(),
+ list: vi.fn().mockResolvedValue({ data: [] }),
+ },
+ },
+ };
+ }),
+}));
+
+vi.mock('@/server/services/heterogeneousAgent', () => ({
+ HeterogeneousAgentService: vi.fn().mockImplementation(function () {
+ return {
+ getHeterogeneousResumeSessionId: mockGetHeterogeneousResumeSessionId,
+ };
+ }),
+}));
+
+vi.mock('@/server/services/heterogeneousAgent/sandboxRunner', () => ({
+ spawnHeteroSandbox: vi.fn().mockResolvedValue(undefined),
+}));
+
+vi.mock('@/server/services/file/resolveAttachments', () => ({
+ resolveAttachmentsByFileIds: mockResolveAttachmentsByFileIds,
+}));
+
+vi.mock('@/server/services/document', () => ({
+ DocumentService: vi.fn().mockImplementation(function () {
+ return {
+ parseFile: vi.fn().mockResolvedValue({ content: '' }),
+ };
+ }),
+}));
+
+vi.mock('@/server/services/agentRuntime', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(function () {
+ return {
+ createOperation: vi.fn().mockResolvedValue({
+ autoStarted: true,
+ messageId: 'queue-msg-1',
+ operationId: 'op-123',
+ success: true,
+ }),
+ interruptOperation: vi.fn().mockResolvedValue(true),
+ };
+ }),
+}));
+
+vi.mock('@/server/modules/Mecha', () => ({
+ createServerAgentToolsEngine: vi.fn().mockReturnValue({
+ generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),
+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),
+ }),
+ serverMessagesEngine: vi.fn().mockResolvedValue([{ content: 'test', role: 'user' }]),
+}));
+
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: {
+ dispatchAgentRun: mockDispatchAgentRun,
+ executeToolCall: vi.fn().mockResolvedValue({ success: true }),
+ isConfigured: false,
+ queryDeviceList: vi.fn().mockResolvedValue([]),
+ resolveDeviceWorkspaceId: vi.fn().mockResolvedValue(undefined),
+ },
+}));
+
+vi.mock('@/server/services/deviceGateway/dispatchAuthorization', () => ({
+ resolveDeviceDispatchAuthorizationFailure: vi.fn().mockResolvedValue(undefined),
+}));
+
+vi.mock('@/server/services/heterogeneousAgent/remoteDeviceHeteroContext', () => ({
+ buildRemoteDeviceHeteroContext: vi.fn().mockReturnValue('device context'),
+}));
+
+describe('AiAgentService.execAgent - external agent run fee', () => {
+ let service: AiAgentService;
+ const spies: MockInstance[] = [];
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ spies.push(
+ vi.spyOn(AgentOperationModel.prototype, 'settleRunning').mockResolvedValue(true),
+ vi.spyOn(CompletionLifecycle.prototype, 'recordStart').mockResolvedValue(true),
+ );
+ for (const fn of Object.values(fees)) fn.mockReset();
+ mockSignHeteroOperationJWT.mockResolvedValue('op-jwt');
+ topicMock.create.mockResolvedValue({ id: 'topic-1', metadata: undefined });
+ topicMock.findById.mockResolvedValue(undefined);
+ mockMessageCreate.mockResolvedValue({ id: 'msg-1' });
+ mockMessageQuery.mockResolvedValue([]);
+ mockResolveAttachmentsByFileIds.mockResolvedValue({ ...emptyResolvedAttachments });
+ mockGetHeterogeneousResumeSessionId.mockResolvedValue(undefined);
+ mockDeviceFindByDeviceId.mockResolvedValue({ defaultCwd: '/Users/alice/repo' });
+ mockDeviceFindWorkspaceDeviceById.mockResolvedValue(undefined);
+ heteroAgentConfig.agencyConfig = {
+ boundDeviceId: 'device-1',
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'claude-code' },
+ } as any;
+
+ service = new AiAgentService({} as any, 'test-user-id');
+ });
+
+ afterEach(() => {
+ for (const spy of spies.splice(0)) spy.mockRestore();
+ });
+
+ it('holds the fee and leaves it on the dispatched operation for heteroFinish to settle', async () => {
+ const result = await service.execAgent({ agentId: 'agent-1', prompt: 'Fix the bug' });
+
+ expect(result.success).toBe(true);
+ expect(mockDispatchAgentRun).toHaveBeenCalled();
+ const [{ holderId }] = fees.holdAgentRunFee.mock.calls[0];
+ expect(fees.holdAgentRunFee).toHaveBeenCalledWith({ holderId, userId: 'test-user-id' });
+ expect(fees.rebindAgentRunFee).toHaveBeenCalledWith(
+ 'test-user-id',
+ holderId,
+ result.operationId,
+ );
+ expect(fees.releaseAgentRunFee).not.toHaveBeenCalled();
+ });
+
+ it('leaves a refused dispatch’s fee to the completion that settles its error', async () => {
+ heteroAgentConfig.agencyConfig = {
+ ...heteroAgentConfig.agencyConfig,
+ heterogeneousProvider: { authMode: 'api', type: 'claude-code' },
+ } as any;
+ const completeOperation = vi
+ .spyOn(CompletionLifecycle.prototype, 'completeOperation')
+ .mockResolvedValue(undefined);
+ spies.push(completeOperation);
+
+ const result = await service.execAgent({ agentId: 'agent-1', prompt: 'Fix the bug' });
+
+ expect(result.success).toBe(false);
+ expect(completeOperation.mock.calls[0].slice(0, 2)).toEqual([
+ expect.objectContaining({ operationId: result.operationId }),
+ 'error',
+ ]);
+ expect(fees.rebindAgentRunFee).toHaveBeenCalled();
+ expect(fees.releaseAgentRunFee).not.toHaveBeenCalled();
+ });
+
+ it('gives the fee back when the dispatch throws before the agent starts', async () => {
+ mockSignHeteroOperationJWT.mockRejectedValue(new Error('jwt down'));
+
+ await expect(service.execAgent({ agentId: 'agent-1', prompt: 'Fix the bug' })).rejects.toThrow(
+ 'Failed to sign operation JWT',
+ );
+
+ const [, , operationId] = fees.rebindAgentRunFee.mock.calls[0];
+ expect(fees.releaseAgentRunFee).toHaveBeenCalledWith('test-user-id', operationId);
+ });
+});
diff --git a/apps/server/src/services/aiAgent/intervention/InterventionController.ts b/apps/server/src/services/aiAgent/intervention/InterventionController.ts
index 7f4d1b5ffda..a1eeab703ee 100644
--- a/apps/server/src/services/aiAgent/intervention/InterventionController.ts
+++ b/apps/server/src/services/aiAgent/intervention/InterventionController.ts
@@ -12,6 +12,7 @@ import {
deriveAgentInterventionQueueDeduplicationId,
matchesAgentInterventionContinuationProvenance,
} from '@/business/server/agent-run/agentInterventionIdentity';
+import { settleAgentRunFee } from '@/business/server/agent-run/runFee';
import type { AgentOperationModel } from '@/database/models/agentOperation';
import type { MessageModel } from '@/database/models/message';
import { HumanApprovalAlreadyResolvedError } from '@/database/models/message';
@@ -48,6 +49,27 @@ export class InterventionController {
this.deps = deps;
}
+ /**
+ * Charges or gives back the fee of a device run the user stopped, by the same
+ * rule as any interrupted run: charged once it ran long enough, else returned.
+ * A billing failure must not fail the stop the user asked for.
+ */
+ private async settleInterruptedRunFee(operationId: string): Promise<void> {
+ try {
+ const operation = await this.deps.agentOperationModel.findById(operationId);
+ const startedAt = operation?.startedAt ?? operation?.createdAt;
+ const endedAt = operation?.completedAt ?? new Date();
+ await settleAgentRunFee({
+ durationMs: startedAt ? endedAt.getTime() - startedAt.getTime() : undefined,
+ operationId,
+ reason: 'interrupted',
+ userId: this.deps.userId,
+ });
+ } catch (error) {
+ console.error('[InterventionController] settleAgentRunFee failed', { error, operationId });
+ }
+ }
+
/**
* Mirrors whether the composer still holds user messages queued behind a
* run, so the run hands its turn back at the next step boundary.
@@ -225,7 +247,15 @@ export class InterventionController {
// acknowledged process exit is authoritative; settle only the owned old
// operation and its matching marker, preserving any newer run/outcome.
if (deviceCancellationConfirmed === true) {
- await this.deps.agentOperationModel.settleRunning(resolvedOperationId, 'interrupted');
+ const settled = await this.deps.agentOperationModel.settleRunning(
+ resolvedOperationId,
+ 'interrupted',
+ );
+ // The device run never reaches CompletionLifecycle (heteroFinish skips a
+ // cancelled run), so the stop that ends it also settles its run fee.
+ // Only the stop that actually retired the row settles, so a retry or a
+ // racing terminal callback cannot settle the fee twice.
+ if (settled) await this.settleInterruptedRunFee(resolvedOperationId);
if (resolvedTopicId) {
await this.deps.topicModel.settleRunningOperation(
resolvedTopicId,
diff --git a/apps/server/src/services/aiAgent/pipeline/execTurn.ts b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
index 33e1f652a54..e842bbea7e9 100644
--- a/apps/server/src/services/aiAgent/pipeline/execTurn.ts
+++ b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
@@ -300,7 +300,7 @@ export const execAgentTurn = async (
userId: deps.userId,
});
await claimRunFee(runFee, {
- hold: shouldHoldRunFee(params, { agentConfig, workspaceId: deps.workspaceId }),
+ hold: shouldHoldRunFee(params, { workspaceId: deps.workspaceId }),
userId: deps.userId,
});
@@ -527,7 +527,7 @@ export const execAgentTurn = async (
};
if (isHeteroAgent) {
- return dispatchHeteroAgent(
+ const heteroResult = await dispatchHeteroAgent(
{
bindTopicWorkingDirectory: (p) =>
bindTopicWorkingDirectory({ topicModel: deps.topicModel }, p),
@@ -552,7 +552,12 @@ export const execAgentTurn = async (
maxSteps,
memberDeviceOverride,
operationTaskId,
- onOperationCreated: params.onOperationCreated,
+ // The hetero run settles its fee on `heteroFinish` under this id, so the
+ // fee moves to it as soon as the durable operation row exists.
+ onOperationCreated: async (operationId) => {
+ await bindRunFee(runFee, deps.userId, operationId);
+ await params.onOperationCreated?.(operationId);
+ },
reservedOperationId: params.reservedOperationId,
parentOperationId,
pinnedHeterogeneousTopicModel: turn.pinnedHeterogeneousTopicModel,
@@ -564,6 +569,12 @@ export const execAgentTurn = async (
topicStartOwnerOperationId: params.topicStartOwnerOperationId,
},
);
+ // A returned dispatch is the run's from here: `heteroFinish` settles a
+ // started run and a refused dispatch settles its error through the same
+ // completion, so neither gives the fee back here. A dispatch that throws
+ // leaves it unstarted, and `execAgent` releases the fee.
+ runFee.handedOff = true;
+ return heteroResult;
}
// 4. Fetch user settings (memory config + timezone)
diff --git a/apps/server/src/services/aiAgent/pipeline/runFee.test.ts b/apps/server/src/services/aiAgent/pipeline/runFee.test.ts
index dfa97ec9b3c..f6e770b0ad7 100644
--- a/apps/server/src/services/aiAgent/pipeline/runFee.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/runFee.test.ts
@@ -1,8 +1,6 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import type { AgentConfigWithId } from '@/server/services/agent';
-
import type { InternalExecAgentParams } from '../types';
import {
bindRunFee,
@@ -20,7 +18,6 @@ const fees = vi.hoisted(() => ({
vi.mock('@/business/server/agent-run/runFee', () => fees);
-const agentConfig = { id: 'agt_1', model: 'gpt-4o' } as AgentConfigWithId;
const composerSend = {
agentId: 'agt_1',
interactiveStart: true,
@@ -28,10 +25,7 @@ const composerSend = {
} as InternalExecAgentParams;
const holds = (params: Partial<InternalExecAgentParams>, workspaceId?: string) =>
- shouldHoldRunFee({ ...composerSend, ...params } as InternalExecAgentParams, {
- agentConfig,
- workspaceId,
- });
+ shouldHoldRunFee({ ...composerSend, ...params } as InternalExecAgentParams, { workspaceId });
describe('shouldHoldRunFee', () => {
it('holds a fee for every run the user starts, foreground or background', () => {
@@ -56,17 +50,6 @@ describe('shouldHoldRunFee', () => {
expect(holds({ appContext: { orchestrationRole: 'member' } as any })).toBe(false);
expect(holds({}, 'ws_1')).toBe(false);
});
-
- it('holds no fee for external agents', () => {
- expect(
- shouldHoldRunFee(composerSend, {
- agentConfig: {
- ...agentConfig,
- agencyConfig: { heterogeneousProvider: { type: 'claude-code' } },
- } as AgentConfigWithId,
- }),
- ).toBe(false);
- });
});
describe('run fee claim', () => {
diff --git a/apps/server/src/services/aiAgent/pipeline/runFee.ts b/apps/server/src/services/aiAgent/pipeline/runFee.ts
index ee8261587cd..bc26cd8b896 100644
--- a/apps/server/src/services/aiAgent/pipeline/runFee.ts
+++ b/apps/server/src/services/aiAgent/pipeline/runFee.ts
@@ -1,4 +1,3 @@
-import { isHeterogeneousAgentModelId } from '@lobechat/const';
import { nanoid } from '@lobechat/utils';
import {
@@ -6,7 +5,6 @@ import {
rebindAgentRunFee,
releaseAgentRunFee,
} from '@/business/server/agent-run/runFee';
-import type { AgentConfigWithId } from '@/server/services/agent';
import type { InternalExecAgentParams } from '../types';
@@ -18,12 +16,15 @@ import type { InternalExecAgentParams } from '../types';
* - a continuation of a run already started (approval or tool-result resume,
* steer), which belongs to the run that held the fee;
* - a sub-agent or group member, which is a step of its root run;
- * - Workspace runs, which bill elsewhere;
- * - an external agent (Claude Code, Codex, …), which runs on the user's device.
+ * - Workspace runs, which bill elsewhere.
+ *
+ * An external agent (Claude Code, Codex, …) the server dispatches to a device
+ * or sandbox pays the fee like any other run: it is held here, bound to the
+ * hetero operation once that row exists, and settled by `heteroFinish`.
*/
export const shouldHoldRunFee = (
params: InternalExecAgentParams,
- { agentConfig, workspaceId }: { agentConfig: AgentConfigWithId; workspaceId?: string },
+ { workspaceId }: { workspaceId?: string },
): boolean => {
const { appContext } = params;
if (workspaceId) return false;
@@ -33,12 +34,6 @@ export const shouldHoldRunFee = (
appContext?.orchestrationRole === 'member'
)
return false;
- if (
- agentConfig.agencyConfig?.heterogeneousProvider?.type ||
- isHeterogeneousAgentModelId(agentConfig.model)
- )
- return false;
-
const continuesRun =
!!params.resume ||
!!params.resumeApproval ||