Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

feat(chat): see what task agents cost in each chat turn (#16576)

Hazem Adel58ac3b0a8188
diff --git a/.agents/skills/ai-task/sql/cost-watch.sql b/.agents/skills/ai-task/sql/cost-watch.sql
index b6f0f72338b..0ae6467a311 100644
--- a/.agents/skills/ai-task/sql/cost-watch.sql
+++ b/.agents/skills/ai-task/sql/cost-watch.sql
@@ -6,6 +6,8 @@ select
countIf(not mapContains(LogAttributes, 'inputTokens')) as turns_without_tokens,
round(avgIf(toUInt64OrZero(LogAttributes['inputTokens']), mapContains(LogAttributes, 'inputTokens'))) as avg_input,
round(avgIf(toUInt64OrZero(LogAttributes['cacheWriteTokens']), mapContains(LogAttributes, 'cacheWriteTokens'))) as avg_cache_write,
+ countIf(toUInt64OrZero(LogAttributes['taskInputTokens']) > 0) as turns_with_tasks,
+ round(avgIf(toUInt64OrZero(LogAttributes['taskInputTokens']), toUInt64OrZero(LogAttributes['taskInputTokens']) > 0)) as avg_task_input,
round(sumIf(toUInt64OrZero(LogAttributes['cacheReadTokens']), mapContains(LogAttributes, 'inputTokens')) / sumIf(toUInt64OrZero(LogAttributes['inputTokens']), mapContains(LogAttributes, 'inputTokens')) * 100, 1) as cache_read_pct
from default.otel_logs
where Timestamp > now() - interval __DAYS__ day
diff --git a/brain/knowledge/ai-intelligence/ai-agents.md b/brain/knowledge/ai-intelligence/ai-agents.md
index 25a1c3c6e5b..d7b393fff16 100644
--- a/brain/knowledge/ai-intelligence/ai-agents.md
+++ b/brain/knowledge/ai-intelligence/ai-agents.md
@@ -39,6 +39,7 @@ Three things follow. `run_agent` has two modes: pointed at a saved agent (`agent
- **A chat turn's data lives in jsonb, so recording something per turn needs no migration.** `agent_conversation.messages` is a `jsonb` column and each entry is a `PersistedAgentMessageSchema`, which already carries optional per-turn fields (`thinkingDurationMs`, `feedback`). Adding another optional one is a zod field plus a `@activepieces/shared` patch bump — no column, no migration, no rollback flag. The conversation row itself only has `modelName`, which is why "record it on the conversation" is usually the wrong instinct: a user can switch tier mid-conversation, so anything that describes one turn belongs on the message, not the row.
- **But the server does not build those messages, so "no migration" does not mean "cheap".** `messages` arrives already assembled from the worker over RPC (`saveAgentMessages` in `rpc/conversation-rpc.ts`), and the server only persists it and bills off it. Putting a new per-turn field on a message therefore means changing the RPC request schema and the worker that fills it, not editing a server file. Costing this off the jsonb shape alone gave an estimate of about an hour for work that is really a change to the engine contract. Check who authors the object before you price a change to it.
+- **A turn's `inputTokens` counts only the main chat.** Task and researcher tokens go in `taskInputTokens` and `taskOutputTokens` on the same `Chat message completed` log. They're summed by `taskTokensOf` from the `tokens` each `ap_run_task` or `ap_deep_research` result carries, which is kept out of what the model reads. On a managed key, task tokens bill at cost because tasks reuse the turn's billing-wrapped models. On an own key, the turn pays one message credit plus the paid calls the tasks report in `billedToolCalls`.
- **`CHAT_HIDDEN_TOOL_NAMES` is load-bearing for the MCP Activity feed, not just for chat UX.** The chat reaches the MCP server as an ordinary HTTP client, and `mcp_activity` records `ap_run_action`. The only thing keeping chat activity out of that feed is `ap_run_action` sitting in `CHAT_HIDDEN_TOOL_NAMES` (`core/shared/src/lib/ee/agent/tool-phases.ts`), filtered worker-side in `agent-mcp-client.ts`. Remove it and the chat starts writing rows into a tab meant for external MCP clients, with no test failing. See the MCP Server page for the enforcement that was designed and deliberately not built.
- Gated by `platform.plan.agentsEnabled`; when off, the step type is hidden from the piece selector. Off by default on Community, on for Cloud plans that include it.
- External MCP tools are validated server-side via `POST /v1/projects/:projectId/agent-tools/mcp/validate` — a JSON-RPC `initialize` → `notifications/initialized` → `tools/list` handshake returning tool names. Outbound call routes through `apAxios` with `ssrf-agents.ts` rejecting private/loopback/link-local/meta IPs (allow ranges via `AP_SSRF_ALLOW_LIST`, CIDR). All error paths collapse to one generic message to avoid leaking reachability.
diff --git a/packages/server/api/test/unit/app/ee/agent/chat-turn-charge.test.ts b/packages/server/api/test/unit/app/ee/agent/chat-turn-charge.test.ts
new file mode 100644
index 00000000000..a48a4770d7a
--- /dev/null
+++ b/packages/server/api/test/unit/app/ee/agent/chat-turn-charge.test.ts
@@ -0,0 +1,118 @@
+import { AIProviderName } from '@activepieces/core-utils'
+import { AgentConversation, AgentConversationStatus, AgentRunSource, apId, PersistedAgentMessage, PersistedAgentPart, PersistedAgentPartType, PersistedAgentRole, PersistedToolCallStatus } from '@activepieces/shared'
+import { FastifyBaseLogger } from 'fastify'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const { trackBillingAndSendTelemetry, resolveChatProviderName } = vi.hoisted(() => ({
+ trackBillingAndSendTelemetry: vi.fn(),
+ resolveChatProviderName: vi.fn(),
+}))
+
+vi.mock('../../../../../src/app/platform/billing-and-telemetry', () => ({
+ trackBillingAndSendTelemetry: (...args: unknown[]) => trackBillingAndSendTelemetry(...args),
+}))
+
+vi.mock('../../../../../src/app/ee/platform/platform-plan/platform-plan.service', () => ({
+ platformPlanService: () => ({
+ getOrCreateForPlatform: async () => ({ plan: 'standard', licenseKey: null }),
+ }),
+}))
+
+vi.mock('../../../../../src/app/ee/agent/agent-helpers', () => ({
+ agentHelpers: {
+ resolveChatProviderName: (...args: unknown[]) => resolveChatProviderName(...args),
+ surfaceOf: () => 'chat',
+ resolveModelIdForAnalytics: () => 'model',
+ resolveTier: () => ({ id: 'smart' }),
+ },
+}))
+
+vi.mock('../../../../../src/app/ee/agent/history/agent-history', () => ({
+ agentHistory: {
+ resolveMessages: ({ conversation }: { conversation: AgentConversation }) => conversation.uiMessages ?? [],
+ },
+}))
+
+import { chatToolBilling } from '../../../../../src/app/ee/agent/chat-tool-billing'
+
+describe('chatToolBilling.chargeForLatestTurn with task agents', () => {
+ beforeEach(() => {
+ trackBillingAndSendTelemetry.mockReset()
+ resolveChatProviderName.mockReset()
+ })
+
+ it('charges a managed-key turn no message credit, only the paid calls its tasks made', async () => {
+ resolveChatProviderName.mockResolvedValue(AIProviderName.ACTIVEPIECES)
+
+ await chatToolBilling.chargeForLatestTurn({ conversation: conversationWithTwoTasks(), log: LOG })
+
+ expect(trackBillingAndSendTelemetry).toHaveBeenCalledWith(expect.objectContaining({
+ credits: expect.objectContaining({ value: 3, properties: expect.objectContaining({ messages: 0, toolCalls: 3 }) }),
+ }))
+ })
+
+ it('charges an own-key turn one message credit, once, plus the paid calls its tasks made', async () => {
+ resolveChatProviderName.mockResolvedValue(AIProviderName.OPENAI)
+
+ await chatToolBilling.chargeForLatestTurn({ conversation: conversationWithTwoTasks(), log: LOG })
+
+ expect(trackBillingAndSendTelemetry).toHaveBeenCalledWith(expect.objectContaining({
+ credits: expect.objectContaining({ value: 4, properties: expect.objectContaining({ messages: 1, toolCalls: 3 }) }),
+ }))
+ })
+})
+
+function conversationWithTwoTasks(): AgentConversation {
+ const messages: PersistedAgentMessage[] = [
+ { role: PersistedAgentRole.USER, parts: [{ type: PersistedAgentPartType.TEXT, text: 'research and build' }] },
+ { role: PersistedAgentRole.ASSISTANT, parts: [
+ taskPart({ toolName: 'ap_run_task', billedToolCalls: [{ toolName: 'ap_execute_action', output: {} }, { toolName: 'ap_explore_data', output: {} }] }),
+ taskPart({ toolName: 'ap_deep_research', billedToolCalls: [{ toolName: 'ap_scrape_url', output: {} }, { toolName: 'ap_fetch_url', output: {} }] }),
+ ] },
+ ]
+ const now = new Date().toISOString()
+ return {
+ id: apId(),
+ created: now,
+ updated: now,
+ platformId: apId(),
+ projectId: apId(),
+ userId: apId(),
+ agentId: null,
+ flowRunId: null,
+ aiCredits: null,
+ source: AgentRunSource.CHAT,
+ title: null,
+ modelName: null,
+ modelTierId: null,
+ status: AgentConversationStatus.IDLE,
+ activeRunId: null,
+ messages: [],
+ uiMessages: messages,
+ summary: null,
+ summarizedUpToIndex: null,
+ }
+}
+
+function taskPart({ toolName, billedToolCalls }: { toolName: string, billedToolCalls: { toolName: string, output: unknown }[] }): PersistedAgentPart {
+ return {
+ type: PersistedAgentPartType.TOOL_CALL,
+ toolCallId: `${toolName}-1`,
+ toolName,
+ input: {},
+ status: PersistedToolCallStatus.COMPLETED,
+ output: { status: 'done', billedToolCalls, tokens: { input: 1000, output: 100 } },
+ }
+}
+
+const LOG: FastifyBaseLogger = {
+ level: 'info',
+ fatal: vi.fn(),
+ error: vi.fn(),
+ warn: vi.fn(),
+ info: vi.fn(),
+ debug: vi.fn(),
+ trace: vi.fn(),
+ silent: vi.fn(),
+ child: () => LOG,
+}
diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts
index cef1c4b0d88..742baab5e55 100644
--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts
+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts
@@ -13,7 +13,7 @@ import { creditLedger } from './credit-ledger'
import { declinedActions } from './declined-actions'
import { classifyAgentRunError, delayWithJitter, drainOf, firstStepUsesFastModel, isTransientFailureText, NO_STEP_CONTENT, runAgentTurn, StreamDrain, trackStepContent, TurnModel } from './run-agent-turn'
import { taskContext } from './tools/task-context'
-import { createTaskSubagentTools } from './tools/task-subagent-tools'
+import { createTaskSubagentTools, taskTokensOf } from './tools/task-subagent-tools'
const BATCH_SIZE = 10
const BATCH_FLUSH_MS = 50
@@ -384,6 +384,7 @@ export const executeAgentRunJob: JobHandler<ExecuteAgentRunJobData, FireAndForge
}
const autoTitle = await autoTitlePromise
+ const taskTokens = taskTokensOf({ parts: uiParts })
log.info({
conversation: { id: conversationId },
@@ -396,6 +397,8 @@ export const executeAgentRunJob: JobHandler<ExecuteAgentRunJobData, FireAndForge
model: { id: turn.answeredBy.modelId },
finishReason: turn.finishReason,
truncatedAfterRetries,
+ taskInputTokens: taskTokens.input,
+ taskOutputTokens: taskTokens.output,
}, 'Chat message completed')
const thinkingDurationMs = Date.now() - thinkingStartTime
diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/run-agent-turn.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/run-agent-turn.ts
index 52ad072966e..71cd4daf811 100644
--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/run-agent-turn.ts
+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/run-agent-turn.ts
@@ -242,7 +242,9 @@ export async function runAgentTurn({ models, fastModel, systemPrompt, messages,
log.warn({ tool: { name: toolCall.toolName, durationMs: toolExecutionMs }, error: toolOutput.error }, 'Tool call failed')
}
},
- onStepEnd: ({ content, response }) => {
+ onStepEnd: ({ content, response, usage: stepUsage }) => {
+ totalInputTokens += stepUsage.inputTokens ?? 0
+ totalOutputTokens += stepUsage.outputTokens ?? 0
uiParts.push(...agentAiUtils.buildStepParts({ content: content as ContentPartLike[] }))
currentAttemptMessages = [...currentAttemptMessages, ...agentAiUtils.collectStepMessages([{ response }])]
const responseMessages = [...accumulatedResponseMessages, ...currentAttemptMessages]
@@ -315,8 +317,6 @@ export async function runAgentTurn({ models, fastModel, systemPrompt, messages,
const stepMessages = agentAiUtils.collectStepMessages(steps)
earlierAttemptToolCalls = [...earlierAttemptToolCalls, ...completedToolCalls(steps)]
usage = attemptUsage
- totalInputTokens += attemptUsage.inputTokens ?? 0
- totalOutputTokens += attemptUsage.outputTokens ?? 0
lastFinishReason = finishReason
logTurnPerformance({ performance: finalStep.performance, modelId: current().modelId, stepCount: steps.length, log })
diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/task-subagent-tools.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/task-subagent-tools.ts
index 13788c66a38..29a7f2faa99 100644
--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/task-subagent-tools.ts
+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/task-subagent-tools.ts
@@ -24,14 +24,14 @@ export function createTaskSubagentTools({ tools, taskPrompt, ...rest }: Omit<Tas
[TASK_TOOL_NAME]: tool({
description: 'Hand one self-contained goal to a focused sub-agent with its own fresh context and the same tools you have (read, search, build, update, execute; risky actions still ask the user for approval). Use it when it buys something: independent goals that can run in parallel (several calls in one step run at once), or noisy preparation with a short answer (going through many records or runs, investigating a failure). Build flows yourself, even several at once, and make small edits yourself. It cannot ask the user anything: when it needs something only the user can give it finishes as blocked and says what; ask the user for it in your own words, then pass their answer back. Pass taskId to continue a task you started earlier in this conversation (after a block, or for a follow-up on what it built).',
inputSchema: taskInput,
- toModelOutput: ({ output }) => ({ type: 'text', value: JSON.stringify(omit(output, ['activity', 'billedToolCalls'])) }),
+ toModelOutput: ({ output }) => ({ type: 'text', value: JSON.stringify(omit(output, ['activity', 'billedToolCalls', 'tokens'])) }),
execute: async ({ title, brief, taskId }, { toolCallId }) => runTask({ deps, title, brief, taskId, progressId: toolCallId }),
}),
...(searchAvailable ? {
[RESEARCH_TOOL_NAME]: tool({
description: 'Research one or more subjects in depth on the live web. One sub-agent per subject runs in parallel: it searches, reads the actual pages and returns a short sourced brief, and the user watches the research live. Use it whenever the answer needs facts from real pages, such as comparing tools or vendors, pricing and plans, reviews and complaints, competitors, or API docs. Prefer it over several ap_web_search calls. Use ap_web_search only for one quick fact. Compare the briefs and do the final step yourself (the recommendation, the image, the build).',
inputSchema: researchInput,
- toModelOutput: ({ output }) => ({ type: 'text', value: JSON.stringify({ tasks: output.tasks.map((task: TaskRunOutput) => omit(task, ['activity', 'billedToolCalls'])) }) }),
+ toModelOutput: ({ output }) => ({ type: 'text', value: JSON.stringify({ tasks: output.tasks.map((task: TaskRunOutput) => omit(task, ['activity', 'billedToolCalls', 'tokens'])) }) }),
execute: async ({ question, subjects, context }, { toolCallId }) => {
const researchSlot = pLimit(RESEARCHERS_AT_ONCE)
const tasks = await Promise.all(subjects.map((subject, index) => researchSlot(() => runTask({
@@ -41,13 +41,19 @@ export function createTaskSubagentTools({ tools, taskPrompt, ...rest }: Omit<Tas
progressId: subagentProgressId.forSubject({ toolCallId, index }),
kind: 'research',
}))))
- return { tasks, billedToolCalls: tasks.flatMap((task) => task.billedToolCalls ?? []) }
+ return { tasks, billedToolCalls: tasks.flatMap((task) => task.billedToolCalls ?? []), tokens: sumTokens(tasks.map((task) => task.tokens ?? NO_TOKENS)) }
},
}),
} : {}),
}
}
+export function taskTokensOf({ parts }: { parts: PersistedAgentPart[] }): TaskTokens {
+ return sumTokens(parts.flatMap((part) => part.type === PersistedAgentPartType.TOOL_CALL && SUB_AGENT_TOOL_NAMES.includes(part.toolName) && isObject(part.output) && isTaskTokens(part.output['tokens'])
+ ? [part.output['tokens']]
+ : []))
+}
+
async function runTask({ deps, title, brief, taskId, progressId, kind = 'task' }: {
deps: TaskDeps
title: string
@@ -125,6 +131,7 @@ async function runTask({ deps, title, brief, taskId, progressId, kind = 'task' }
...(isNil(result.needs) ? {} : { needs: result.needs }),
activity,
billedToolCalls: billedToolCalls(turn.uiParts),
+ tokens: { input: turn.totalInputTokens, output: turn.totalOutputTokens },
}
}
@@ -188,6 +195,8 @@ async function continueTurn({ title, turnParams, previous, request, overrides }:
return {
...next,
uiParts: [...previous.uiParts, ...next.uiParts],
+ totalInputTokens: previous.totalInputTokens + next.totalInputTokens,
+ totalOutputTokens: previous.totalOutputTokens + next.totalOutputTokens,
accumulatedResponseMessages: [...previous.accumulatedResponseMessages, requestMessage, ...next.accumulatedResponseMessages],
}
}
@@ -366,6 +375,14 @@ function searchResults(output: unknown): SubagentLink[] {
})
}
+function sumTokens(tokens: TaskTokens[]): TaskTokens {
+ return tokens.reduce((total, next) => ({ input: total.input + next.input, output: total.output + next.output }), NO_TOKENS)
+}
+
+function isTaskTokens(value: unknown): value is TaskTokens {
+ return isObject(value) && typeof value['input'] === 'number' && typeof value['output'] === 'number'
+}
+
function billedToolCalls(parts: PersistedAgentPart[]): { toolName: string, output: unknown }[] {
return parts.flatMap((part) => part.type === PersistedAgentPartType.TOOL_CALL && part.status === PersistedToolCallStatus.COMPLETED && chatBilling.isFlatBilledToolCall({ toolName: part.toolName, output: part.output })
? [{ toolName: part.toolName, output: billingOutput(part.output) }]
@@ -427,6 +444,8 @@ const STATUS_BY_RESULT: Record<TaskResult['status'], FinishAgentTaskRequest['sta
const TASK_TOOL_NAME = 'ap_run_task'
const RESEARCH_TOOL_NAME = 'ap_deep_research'
+const SUB_AGENT_TOOL_NAMES = [TASK_TOOL_NAME, RESEARCH_TOOL_NAME]
+const NO_TOKENS: TaskTokens = { input: 0, output: 0 }
const RESEARCHERS_AT_ONCE = 4
const TASK_SKILL_SURFACE: SkillSurface = 'CHAT'
const REPORT_REQUEST = `You stopped without reporting. Call ${TASK_COMPLETION_TOOL_NAME} now with your result.`
@@ -503,4 +522,10 @@ type TaskRunOutput = {
needs?: string
activity?: SubagentActivity
billedToolCalls?: { toolName: string, output: unknown }[]
+ tokens?: TaskTokens
+}
+
+export type TaskTokens = {
+ input: number
+ output: number
}
diff --git a/packages/server/worker/test/lib/execute/jobs/ee/agent/run-agent-turn-fallback.test.ts b/packages/server/worker/test/lib/execute/jobs/ee/agent/run-agent-turn-fallback.test.ts
index f9a3b805d6a..8339fea33fa 100644
--- a/packages/server/worker/test/lib/execute/jobs/ee/agent/run-agent-turn-fallback.test.ts
+++ b/packages/server/worker/test/lib/execute/jobs/ee/agent/run-agent-turn-fallback.test.ts
@@ -35,6 +35,17 @@ describe('a platform tier chat turn', () => {
expect(JSON.stringify(backup.doStreamCalls[0].prompt)).toContain('found')
})
+ it('counts the tokens of a step that finished before a later step failed', async () => {
+ const turn = await runTurn({
+ models: [tierModel({ modelId: 'main', model: failingModel({ statusCode: 503 }) }), tierModel({ modelId: 'backup', model: answeringModel('done') })],
+ fastModel: tierModel({ modelId: 'fast', model: searchingModel() }),
+ search: vi.fn(async () => ({ content: [{ type: 'text', text: 'found' }] })),
+ })
+
+ expect(turn.totalInputTokens).toBe(2)
+ expect(turn.totalOutputTokens).toBe(2)
+ })
+
it('does not fall back once the failing step already sent text to the user', async () => {
const backup = answeringModel('from backup')
@@ -261,5 +272,5 @@ function textOf(turn: Awaited<ReturnType<typeof runAgentTurn>>): string {
}
const TIER = { id: 'fast', thinkingBudget: 0, modelId: 'main' }
-const USAGE = { inputTokens: 1, outputTokens: 1, totalTokens: 2 }
+const USAGE = { inputTokens: { total: 1, noCache: 1, cacheRead: 0, cacheWrite: 0 }, outputTokens: { total: 1, text: 1, reasoning: 0 } }
const SILENT_LOG = { debug: () => undefined, info: () => undefined, warn: () => undefined, error: () => undefined }
diff --git a/packages/server/worker/test/lib/execute/jobs/ee/agent/task-subagent-tools.test.ts b/packages/server/worker/test/lib/execute/jobs/ee/agent/task-subagent-tools.test.ts
index 5ca2d0e3cae..5ad44b6e866 100644
--- a/packages/server/worker/test/lib/execute/jobs/ee/agent/task-subagent-tools.test.ts
+++ b/packages/server/worker/test/lib/execute/jobs/ee/agent/task-subagent-tools.test.ts
@@ -10,8 +10,9 @@ vi.mock('../../../../../../src/lib/execute/jobs/ee/agent/run-agent-turn', () =>
}))
import { RunAgentTurnParams } from '../../../../../../src/lib/execute/jobs/ee/agent/run-agent-turn'
-import { createTaskSubagentTools } from '../../../../../../src/lib/execute/jobs/ee/agent/tools/task-subagent-tools'
+import { buildSkillSurface } from '../../../../../../src/lib/execute/jobs/ee/agent/tools/skill-tools'
import { taskContext } from '../../../../../../src/lib/execute/jobs/ee/agent/tools/task-context'
+import { createTaskSubagentTools, taskTokensOf } from '../../../../../../src/lib/execute/jobs/ee/agent/tools/task-subagent-tools'
describe('createTaskSubagentTools', () => {
beforeEach(() => {
@@ -466,6 +467,78 @@ describe('createTaskSubagentTools', () => {
expect(Object.keys(runAgentTurn.mock.calls[0][0].tools).filter((name) => name.includes('agent'))).toEqual([])
})
+ it('reports the tokens it used, adding up the turns it continued after a cut-off, and keeps them out of what the main model reads', async () => {
+ runAgentTurn
+ .mockResolvedValueOnce({ ...turnResult(), streamError: new Error('stream dropped') })
+ .mockImplementationOnce(async (params: { tools: ToolSet }) => {
+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: 'ok', artifacts: [] }, EXECUTION_OPTIONS)
+ return { ...turnResult(), totalInputTokens: 400, totalOutputTokens: 40 }
+ })
+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_web_search']) })
+
+ const result = await tasks['ap_run_task'].execute?.({ title: 'Research', brief: 'Find out' }, EXECUTION_OPTIONS)
+ const modelOutput = await tasks['ap_run_task'].toModelOutput?.({ toolCallId: 'call-1', input: {}, output: result })
+
+ expect(result).toMatchObject({ tokens: { input: 1400, output: 140 } })
+ expect(JSON.stringify(modelOutput)).not.toContain('tokens')
+ })
+
+ it('runs a task on the chat turn\'s own models, so its tokens bill through the same metered models as the chat', async () => {
+ runAgentTurn.mockImplementation(async (params: { tools: ToolSet }) => {
+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: 'ok', artifacts: [] }, EXECUTION_OPTIONS)
+ return turnResult()
+ })
+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_build_flow']) })
+
+ await tasks['ap_run_task'].execute?.({ title: 'Build', brief: 'Build it' }, EXECUTION_OPTIONS)
+
+ expect(runAgentTurn.mock.calls[0][0].models).toBe(MODELS)
+ })
+
+ it('adds up the tokens of every researcher in deep research', async () => {
+ runAgentTurn.mockImplementation(async (params: { tools: ToolSet }) => {
+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: 'ok', artifacts: [] }, EXECUTION_OPTIONS)
+ return turnResult()
+ })
+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_web_search', 'ap_fetch_url']) })
+
+ const result = await tasks['ap_deep_research'].execute?.({ question: 'Pricing', subjects: ['Asana', 'ClickUp', 'Monday'] }, EXECUTION_OPTIONS)
+
+ expect(result).toMatchObject({ tokens: { input: 3000, output: 300 } })
+ })
+
+ it('adds up task and research tokens from a turn, ignoring other tools and calls without tokens', () => {
+ const parts = [
+ { type: PersistedAgentPartType.TOOL_CALL, toolCallId: 'a', toolName: 'ap_run_task', input: {}, status: PersistedToolCallStatus.COMPLETED, output: { tokens: { input: 1000, output: 100 } } },
+ { type: PersistedAgentPartType.TOOL_CALL, toolCallId: 'b', toolName: 'ap_deep_research', input: {}, status: PersistedToolCallStatus.COMPLETED, output: { tokens: { input: 3000, output: 300 } } },
+ { type: PersistedAgentPartType.TOOL_CALL, toolCallId: 'c', toolName: 'ap_web_search', input: {}, status: PersistedToolCallStatus.COMPLETED, output: { tokens: { input: 99, output: 9 } } },
+ { type: PersistedAgentPartType.TOOL_CALL, toolCallId: 'd', toolName: 'ap_run_task', input: {}, status: PersistedToolCallStatus.ERROR },
+ ] as const
+
+ expect(taskTokensOf({ parts: [...parts] })).toEqual({ input: 4000, output: 400 })
+ })
+
+ it('lets a task load a skill and use its tools, but never attaches a tool the task does not have', async () => {
+ runAgentTurn.mockImplementation(async (params: { tools: ToolSet }) => {
+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: 'ok', artifacts: [] }, EXECUTION_OPTIONS)
+ return turnResult()
+ })
+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_web_search', 'ap_fetch_url', 'ap_scrape_url', 'ap_send_email', 'ap_build_flow', 'ap_add_step', 'ap_test_flow']) })
+ await tasks['ap_run_task'].execute?.({ title: 'Research', brief: 'Find out' }, EXECUTION_OPTIONS)
+ const params: RunAgentTurnParams = runAgentTurn.mock.calls[0][0]
+ if (params.skills === undefined) {
+ throw new Error('a task runs without skills')
+ }
+ const surface = buildSkillSurface({ tools: params.tools, surface: params.skills.surface, guides: params.skills.guides, onSkillLoaded: vi.fn(), canAffordPaidTool: () => true })
+
+ await surface.tools['ap_load_skill']?.execute?.({ skills: ['web_and_media', 'flow_building'] }, EXECUTION_OPTIONS)
+
+ expect(surface.attachedToolNames()).toEqual(expect.arrayContaining(['ap_fetch_url', 'ap_build_flow', 'ap_add_step']))
+ expect(surface.attachedToolNames()).not.toContain('ap_send_email')
+ expect(surface.attachedToolNames()).not.toContain('ap_deep_research')
+ expect(surface.attachedToolNames()).not.toContain('ap_run_task')
+ })
+
it('offers research only when web search is available', () => {
expect(createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_build_flow']) })).not.toHaveProperty('ap_deep_research')
})
@@ -490,6 +563,8 @@ function turnResult(): Record<string, unknown> {
creditsExhausted: false,
budgetExceeded: false,
truncatedAfterRetries: false,
+ totalInputTokens: 1000,
+ totalOutputTokens: 100,
}
}