π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(context-engine): account container message tokens in context budget (#17839)
Hardycacf310895c0
diff --git a/packages/context-engine/src/processors/TaskMessage.ts b/packages/context-engine/src/processors/TaskMessage.tsindex 06731a9e4b5..85fa8e9858c 100644--- a/packages/context-engine/src/processors/TaskMessage.ts+++ b/packages/context-engine/src/processors/TaskMessage.ts@@ -14,7 +14,7 @@ const log = debug('context-engine:processor:TaskMessageProcessor');/*** Default template for combining instruction and result*/-const DEFAULT_TEMPLATE = `[Task Result from {{agentName}}]+export const DEFAULT_TEMPLATE = `[Task Result from {{agentName}}]**Task Instruction:**{{instruction}}@@ -22,6 +22,21 @@ const DEFAULT_TEMPLATE = `[Task Result from {{agentName}}]**Task Result:**{{content}}`;+/**+ * Fill a task template with its placeholders. Shared by+ * {@link TaskMessageProcessor} (which emits the formatted text to the+ * provider) and the token accounting (which estimates the emitted text), so+ * the counted payload always mirrors the sent payload.+ */+export const formatTaskMessage = (+ template: string,+ values: { agentName: string; content: string; instruction: string },+): string =>+ template+ .replaceAll('{{agentName}}', values.agentName)+ .replaceAll('{{instruction}}', values.instruction)+ .replaceAll('{{content}}', values.content);+export interface TaskMessageConfig {/*** Custom template for formatting task messages@@ -78,7 +93,7 @@ export class TaskMessageProcessor extends BaseProcessor {}// Apply template- const formattedContent = this.applyTemplate(template, {+ const formattedContent = formatTaskMessage(template, {agentName: String(agentName),content: String(content),instruction: String(instruction),@@ -102,17 +117,4 @@ export class TaskMessageProcessor extends BaseProcessor {return this.markAsExecuted(clonedContext);}-- /**- * Apply template with placeholders- */- private applyTemplate(- template: string,- values: { agentName: string; content: string; instruction: string },- ): string {- return template- .replaceAll('{{agentName}}', values.agentName)- .replaceAll('{{instruction}}', values.instruction)- .replaceAll('{{content}}', values.content);- }}diff --git a/packages/context-engine/src/tokenAccounting/__tests__/index.test.ts b/packages/context-engine/src/tokenAccounting/__tests__/index.test.tsindex 7c34bdaa949..c8bbeca3d0a 100644--- a/packages/context-engine/src/tokenAccounting/__tests__/index.test.ts+++ b/packages/context-engine/src/tokenAccounting/__tests__/index.test.ts@@ -1,6 +1,8 @@import type { UIChatMessage } from '@lobechat/types';+import { estimateTokenCount } from 'tokenx';import { describe, expect, it } from 'vitest';+import { DEFAULT_TEMPLATE, formatTaskMessage } from '../../processors/TaskMessage';import { countContextTokens, DEFAULT_DRIFT_MULTIPLIER } from '../index';// Minimal helper β UIChatMessage has many optional fields; tests only set the@@ -414,6 +416,286 @@ describe('countContextTokens', () => {});});+ describe('assistantGroup children (conversation-flow flattened lists)', () => {+ it('counts the real assistant blocks and inline tool results', () => {+ const r = countContextTokens({+ messages: [+ mkMsg({ role: 'user', content: 'user prompt' }),+ mkMsg({+ role: 'assistantGroup',+ content: '',+ children: [+ {+ content: 'assistant text',+ id: 'a1',+ tools: [+ {+ apiName: 'readFile',+ arguments: '{"path":"/x","padding":"' + 'x'.repeat(1000) + '"}',+ id: 't1',+ identifier: 'fs',+ result: { content: 'big file content '.repeat(100), id: 'result-1' },+ type: 'default',+ },+ ],+ },+ { content: '', id: 'a2', usage: { totalOutputTokens: 42 } },+ ],+ }),+ ],+ });++ expect(r.messages).toHaveLength(2);+ expect(r.messages[1].bySource.content).toBeGreaterThan(100);+ expect(r.messages[1].bySource.toolCalls).toBeGreaterThan(0);+ expect(r.messages[1].bySource.toolCallId).toBeGreaterThan(0);+ expect(r.rawTotal).toBeGreaterThan(150);+ });++ it('counts tool result content (tools[].result.content) on plain assistant messages', () => {+ const r = countContextTokens({+ messages: [+ mkMsg({+ role: 'assistant',+ content: 'short',+ tools: [+ {+ apiName: 'search',+ arguments: '{}',+ id: 'c1',+ identifier: 'p',+ result: { content: 'search result payload '.repeat(200) },+ type: 'default',+ } as any,+ ],+ }),+ ],+ });++ expect(r.bySource.content).toBeGreaterThan(500);+ });++ it('keeps counting result content even on the assistant usage fast-path', () => {+ const r = countContextTokens({+ messages: [+ mkMsg({+ role: 'assistant',+ content: '',+ metadata: { usage: { totalOutputTokens: 42 } as any } as any,+ tools: [+ {+ apiName: 'search',+ arguments: '{}',+ id: 'c1',+ identifier: 'p',+ result: { content: 'result payload '.repeat(100) },+ type: 'default',+ } as any,+ ],+ }),+ ],+ });++ // 42 (recorded output) + result payload tokens+ expect(r.bySource.content).toBeGreaterThan(42);+ });+ });++ describe('tasks / groupTasks containers (subagent executions)', () => {+ it('counts each task content + metadata.instruction inside a tasks container', () => {+ const r = countContextTokens({+ messages: [+ mkMsg({+ role: 'tasks',+ content: '',+ tasks: [+ mkMsg({+ role: 'task',+ content: 'result text '.repeat(50),+ metadata: { instruction: 'very long subagent instruction '.repeat(80) } as any,+ }),+ mkMsg({ role: 'task', content: 'another result '.repeat(40) }),+ ],+ }),+ ],+ });++ // Both results AND both instructions ship inside the re-emitted template+ expect(r.bySource.content).toBeGreaterThan(500);+ expect(r.messages[0].bySource.content).toBe(r.bySource.content);+ expect(r.messages[0].bySource.reasoning).toBeUndefined();+ });++ it('counts groupTasks containers the same way', () => {+ const r = countContextTokens({+ messages: [+ mkMsg({+ role: 'groupTasks',+ content: '',+ tasks: [+ mkMsg({+ role: 'task',+ content: 'group task result '.repeat(45),+ metadata: { instruction: 'group task instruction '.repeat(45) } as any,+ }),+ ],+ }),+ ],+ });++ expect(r.bySource.content).toBeGreaterThan(200);+ });++ it('counts a standalone task message (content + instruction)', () => {+ const r = countContextTokens({+ messages: [+ mkMsg({+ role: 'task',+ content: 'result '.repeat(30),+ metadata: { instruction: 'instruction '.repeat(60) } as any,+ }),+ ],+ });++ expect(r.bySource.content).toBeGreaterThan(100);++ // instruction is counted on top of content (re-emitted inside the template)+ const withInstruction = countContextTokens({+ messages: [+ mkMsg({+ role: 'task',+ content: 'same',+ metadata: { instruction: 'long instruction '.repeat(50) } as any,+ }),+ ],+ });+ const withoutInstruction = countContextTokens({+ messages: [mkMsg({ role: 'task', content: 'same' })],+ });+ expect(withInstruction.bySource.content).toBeGreaterThan(withoutInstruction.bySource.content);+ });++ it('counts task content without instruction (TaskMessage fallback)', () => {+ // TaskMessageProcessor converts to assistant with plain content when no+ // instruction is present β the result text must still count.+ const r = countContextTokens({+ messages: [mkMsg({ role: 'task', content: 'plain result '.repeat(20) })],+ });++ expect(r.bySource.content).toBeGreaterThan(0);+ });++ it('estimates the exact template text the processor emits (headings + agentName)', () => {+ const content = 'short result';+ const instruction = 'do the thing '.repeat(10);+ const r = countContextTokens({+ messages: [mkMsg({ role: 'task', content, metadata: { instruction } as any })],+ });++ // Mirror of TaskMessageProcessor output for a task without identity fields.+ const expected = estimateTokenCount(+ formatTaskMessage(DEFAULT_TEMPLATE, {+ agentName: 'Sub Agent',+ content,+ instruction,+ }),+ );+ expect(r.bySource.content).toBe(expected);+ });++ it('counts the task agentName inside the template', () => {+ const anonymous = countContextTokens({+ messages: [mkMsg({ role: 'task', content: 'r', metadata: { instruction: 'i' } as any })],+ });+ const named = countContextTokens({+ messages: [+ mkMsg({+ role: 'task',+ agentName: 'A rather long agent persona name '.repeat(10),+ content: 'r',+ metadata: { instruction: 'i' } as any,+ } as any),+ ],+ });++ expect(named.bySource.content).toBeGreaterThan(anonymous.bySource.content);+ });+ });++ describe('agentCouncil members (broadcast)', () => {+ it('counts plain assistant members with tool results', () => {+ const r = countContextTokens({+ messages: [+ mkMsg({+ role: 'agentCouncil',+ content: '',+ members: [+ mkMsg({+ role: 'assistant',+ content: 'member reply '.repeat(40),+ tools: [+ {+ apiName: 'search',+ arguments: '{"q":"x"}',+ id: 'm1',+ identifier: 'p',+ result: { content: 'member result payload '.repeat(60) },+ type: 'default',+ } as any,+ ],+ }),+ ],+ }),+ ],+ });++ expect(r.bySource.content).toBeGreaterThan(200);+ expect(r.bySource.toolCalls).toBeGreaterThan(0);+ // tool.id ships as the flattened tool message's tool_call_id+ expect(r.bySource.toolCallId).toBeGreaterThan(0);+ expect(r.bySource.content).toBeGreaterThan(150);+ expect(r.bySource.toolCalls).toBeGreaterThan(0);+ expect(r.bySource.toolCallId).toBeGreaterThan(0);+ });++ it('counts nested assistantGroup members', () => {+ const r = countContextTokens({+ messages: [+ mkMsg({+ role: 'agentCouncil',+ content: '',+ members: [+ mkMsg({+ role: 'assistantGroup',+ content: '',+ children: [+ {+ content: 'nested assistant text '.repeat(30),+ id: 'n1',+ tools: [+ {+ apiName: 'readFile',+ arguments: '{}',+ id: 'n2',+ identifier: 'fs',+ result: { content: 'nested result '.repeat(50) },+ type: 'default',+ } as any,+ ],+ },+ ],+ }),+ ],+ }),+ ],+ });++ expect(r.bySource.content).toBeGreaterThan(150);+ expect(r.bySource.toolCalls).toBeGreaterThan(0);+ expect(r.bySource.toolCallId).toBeGreaterThan(0);+ });+ });+describe('aggregation', () => {it('sums bySource across multiple messages and tools', () => {const r = countContextTokens({diff --git a/packages/context-engine/src/tokenAccounting/index.ts b/packages/context-engine/src/tokenAccounting/index.tsindex 50969726cce..a6670719f08 100644--- a/packages/context-engine/src/tokenAccounting/index.ts+++ b/packages/context-engine/src/tokenAccounting/index.ts@@ -1,6 +1,8 @@// cspell:ignore tokenx+import type { AssistantContentBlock, UIChatMessage } from '@lobechat/types';import { estimateTokenCount } from 'tokenx';+import { DEFAULT_TEMPLATE, formatTaskMessage } from '../processors/TaskMessage';import type {ContextTokenAccounting,CountContextTokensParams,@@ -37,6 +39,10 @@ const bumpSource = (bySource[key] = (bySource[key] ?? 0) + amount;};+type AssistantTokenBlock =+ | AssistantContentBlock+ | Pick<UIChatMessage, 'content' | 'metadata' | 'reasoning' | 'tools' | 'usage'>;+/*** Account every token that will be sent to the provider for one chat request,* broken down by source category and per-item.@@ -48,17 +54,36 @@ const bumpSource = (* | `toolCalls` | `msg.tools[]` (lobe internal, not OpenAI's `tool_calls`) | `message.tool_calls` |* | `thoughtSignature` | `msg.tools[N].thoughtSignature` (Gemini-specific) | echoed back per tool call |* | `reasoning` | `msg.reasoning.content` / `msg.reasoning` (string variant) | echoed back next turn (thinking) |- * | `toolCallId` | `msg.tool_call_id` | `message.tool_call_id` |+ * | `toolCallId` | `msg.tool_call_id` + `tools[].id` (result-bearing) | `message.tool_call_id` |* | `toolDefinition` | top-level `tools[]` param | request `tools` array |*+ * **Container messages** β the conversation-flow flatteners pack real+ * conversation content into display-only wrappers that the context pipeline+ * restores before sending. Counting mirrors each flattening:+ *+ * - `assistantGroup` / `supervisor` β `children[]` (AssistantContentBlock:+ * content + tools + thoughtSignature + reasoning + `tools[].result.content` ++ * `tools[].id` as tool_call_id) β restored by GroupMessageFlatten+ * - `tasks` / `groupTasks` β `tasks[]` (real task messages; `content` ++ * `metadata.instruction` are re-emitted inside one assistant template by+ * TasksFlatten + TaskMessageProcessor)+ * - `agentCouncil` β `members[]` (assistant or nested assistantGroup)+ * β restored by AgentCouncilFlatten+ * - standalone `role: 'task'` messages use the same accounting as one+ * entry of a `tasks` container+ ** **What's NOT counted (intentionally)** β these are DB-only fields the* harness stores but doesn't ship to the provider:** `plugin`, `pluginState`, `pluginIntervention`, `pluginError`, `chunksList`,* `editorData`, `extra`, `fileList`, `imageList`, `videoList`, `metadata`- * (other than `metadata.usage.totalOutputTokens` shortcut for assistant)- *- * Counting them would over-estimate and trigger compression too early.+ * (other than `metadata.usage.totalOutputTokens` shortcut for assistant and+ * `metadata.instruction` for `task` messages, which ship in the template)+ * Also NOT counted: in-bubble `council` blocks (`AssistantContentBlock.council`)+ * and `taskCompletions` on group wrappers β both are UI-only denormalizations+ * (broadcast member replies / folded subagent completions) that GroupMessageFlatten+ * drops and never reach the provider. Counting them would over-estimate and+ * trigger compression too early.** **Token estimation accuracy***@@ -104,53 +129,170 @@ export const countContextTokens = ({const messageBreakdowns: MessageTokenBreakdown[] = messages.map((msg, index) => {const bySource: Partial<Record<TokenSourceType, number>> = {};- // Assistant fast-path: recorded usage covers content + tool_calls + reasoning- // produced by THIS turn's generation. Use it directly when available. Prefer- // the dedicated `usage` field, falling back to legacy `metadata.usage`.- const recordedOutputTokens =- msg.role === 'assistant'- ? (msg.usage?.totalOutputTokens ?? msg.metadata?.usage?.totalOutputTokens)- : undefined;+ const countToolResults = (tools: AssistantTokenBlock['tools']) => {+ if (!Array.isArray(tools) || tools.length === 0) return;- if (recordedOutputTokens && recordedOutputTokens > 0) {- bumpSource(bySource, 'content', recordedOutputTokens);- } else {- // Per-field estimation- bumpSource(bySource, 'content', estimate(msg.content));-- // Tool calls: lobe stores these on `msg.tools` (NOT OpenAI's `tool_calls`)- // We project to what's actually sent: id + apiName + arguments + type.- // Skipping internal-only fields (intervention, source, executor, result_msg_id)- // which don't ship to the provider.- // Gemini's `thoughtSignature` is preserved by ToolCallProcessor and- // forwarded by the Google context builder β count it under its own- // bucket since it's provider-specific and can be sizeable on every call.- if (msg.role === 'assistant' && Array.isArray(msg.tools) && msg.tools.length > 0) {- let tcSum = 0;- let sigSum = 0;- for (const tc of msg.tools) {- tcSum += estimate(tc.id);- tcSum += estimate(tc.apiName);- tcSum += estimate(tc.arguments);- tcSum += estimate(tc.type);- sigSum += estimate(tc.thoughtSignature);+ for (const tool of tools) {+ const result = (tool as { result?: { content?: unknown } }).result;+ if (!result) continue;++ bumpSource(bySource, 'content', estimate(result.content));+ bumpSource(bySource, 'toolCallId', estimate(tool.id));+ }+ };++ const countAssistant = (message: AssistantTokenBlock) => {+ // Assistant fast-path: recorded usage covers content + tool_calls + reasoning+ // produced by THIS turn's generation. Use it directly when available. Prefer+ // the dedicated `usage` field, falling back to legacy `metadata.usage`.+ const recordedOutputTokens =+ message.usage?.totalOutputTokens ?? message.metadata?.usage?.totalOutputTokens;++ if (recordedOutputTokens && recordedOutputTokens > 0) {+ bumpSource(bySource, 'content', recordedOutputTokens);+ } else {+ // Per-field estimation+ bumpSource(bySource, 'content', estimate(message.content));++ // Tool calls: lobe stores these on `msg.tools` (NOT OpenAI's `tool_calls`)+ // We project to what's actually sent: id + apiName + arguments + type.+ // Skipping internal-only fields (intervention, source, executor, result_msg_id)+ // which don't ship to the provider.+ // Gemini's `thoughtSignature` is preserved by ToolCallProcessor and+ // forwarded by the Google context builder β count it under its own+ // bucket since it's provider-specific and can be sizeable on every call.+ if (Array.isArray(message.tools) && message.tools.length > 0) {+ let tcSum = 0;+ let sigSum = 0;+ for (const tc of message.tools) {+ tcSum += estimate(tc.id);+ tcSum += estimate(tc.apiName);+ tcSum += estimate(tc.arguments);+ tcSum += estimate(tc.type);+ sigSum += estimate(tc.thoughtSignature);+ }+ bumpSource(bySource, 'toolCalls', tcSum);+ bumpSource(bySource, 'thoughtSignature', sigSum);+ }++ // Reasoning trace (thinking-mode models echo this back next turn)+ const reasoning = message.reasoning;+ if (reasoning) {+ const reasoningContent = typeof reasoning === 'string' ? reasoning : reasoning.content;+ bumpSource(bySource, 'reasoning', estimate(reasoningContent));}- bumpSource(bySource, 'toolCalls', tcSum);- bumpSource(bySource, 'thoughtSignature', sigSum);}+ };- // Reasoning trace (thinking-mode models echo this back next turn)- const reasoning = msg.reasoning;+ // `task` messages (subagent execution results) are re-emitted by+ // TaskMessageProcessor as assistant messages whose content is the full+ // instruction/result template (`[Task Result from {{agentName}}]` ++ // `{{instruction}}` + `{{content}}`). Mirror the processor exactly: when+ // `metadata.instruction` is present, estimate the formatted template+ // (static headings + agentName included), not just the two parts β short+ // results would otherwise undercount the shipped payload.+ const countTaskMessage = (task: UIChatMessage) => {+ const instruction = (task.metadata as { instruction?: unknown } | undefined)?.instruction;++ if (instruction) {+ const taskWithIdentity = task as UIChatMessage & {+ agentName?: string;+ meta?: { avatar?: string };+ };+ // Same resolution as TaskMessageProcessor: agentName || meta.avatar || 'Sub Agent'+ const agentName =+ taskWithIdentity.agentName || taskWithIdentity.meta?.avatar || 'Sub Agent';+ const formattedContent = formatTaskMessage(DEFAULT_TEMPLATE, {+ agentName: String(agentName),+ content: String(task.content || ''),+ instruction: String(instruction),+ });+ bumpSource(bySource, 'content', estimate(formattedContent));+ } else {+ // No instruction: TaskMessageProcessor converts to a plain assistant+ // message carrying only the result text.+ bumpSource(bySource, 'content', estimate(task.content));+ }++ const reasoning = task.reasoning;if (reasoning) {const reasoningContent = typeof reasoning === 'string' ? reasoning : reasoning.content;bumpSource(bySource, 'reasoning', estimate(reasoningContent));}- }+ };++ // assistantGroup / supervisor are display-only wrappers. Their children are+ // AssistantContentBlocks, which the context pipeline restores to assistant+ // messages followed by their inline tool results.+ const countGroupChildren = (children: AssistantContentBlock[]) => {+ for (const child of children) {+ countAssistant(child);+ countToolResults(child.tools);+ }+ };- // tool_call_id is sent regardless of fast-path (it's on `tool` role messages,- // not assistant)- if (msg.tool_call_id) {- bumpSource(bySource, 'toolCallId', estimate(msg.tool_call_id));+ if (+ (msg.role === 'assistantGroup' || msg.role === 'supervisor') &&+ Array.isArray(msg.children) &&+ msg.children.length > 0+ ) {+ countGroupChildren(msg.children);+ } else if (+ (msg.role === 'tasks' || msg.role === 'groupTasks') &&+ Array.isArray(msg.tasks) &&+ msg.tasks.length > 0+ ) {+ // TasksFlatten re-emits every entry as a `task` message, which+ // TaskMessageProcessor turns into an assistant template β count each+ // task the same way a standalone `task` message is counted.+ for (const task of msg.tasks) countTaskMessage(task);+ } else if (+ msg.role === 'agentCouncil' &&+ Array.isArray(msg.members) &&+ msg.members.length > 0+ ) {+ // AgentCouncilFlatten expands members into assistant + tool messages; a+ // member can itself be a nested assistantGroup container.+ for (const member of msg.members) {+ if (+ (member.role === 'assistantGroup' || member.role === 'supervisor') &&+ Array.isArray(member.children) &&+ member.children.length > 0+ ) {+ countGroupChildren(member.children);+ } else {+ countAssistant(member);+ countToolResults(member.tools);+ }+ }+ } else if (msg.role === 'task') {+ // Standalone task message (single subagent result) β same accounting as+ // one entry of a `tasks` container.+ countTaskMessage(msg);+ } else {+ if (msg.role === 'assistant') {+ countAssistant(msg);+ } else {+ bumpSource(bySource, 'content', estimate(msg.content));++ const reasoning = msg.reasoning;+ if (reasoning) {+ const reasoningContent = typeof reasoning === 'string' ? reasoning : reasoning.content;+ bumpSource(bySource, 'reasoning', estimate(reasoningContent));+ }+ }++ // Tool result content is shipped to the provider as the `tool` message β+ // group children carry it inline on `tools[].result.content`. Count it+ // regardless of the fast-path above (recorded assistant usage never covers+ // the results of its own tool calls).+ countToolResults(msg.tools);++ // tool_call_id is sent regardless of fast-path (it's on `tool` role messages,+ // not assistant)+ if (msg.tool_call_id) {+ bumpSource(bySource, 'toolCallId', estimate(msg.tool_call_id));+ }}let total = 0;