Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(llma): Extend logic to hide further internal messages (#60736)

Marcel Poelker0f676235ebe4
diff --git a/products/ai_observability/frontend/ConversationDisplay/TranscriptBubbleStream.test.ts b/products/ai_observability/frontend/ConversationDisplay/TranscriptBubbleStream.test.ts
index b5e95d986714..1cc3258be809 100644
--- a/products/ai_observability/frontend/ConversationDisplay/TranscriptBubbleStream.test.ts
+++ b/products/ai_observability/frontend/ConversationDisplay/TranscriptBubbleStream.test.ts
@@ -136,9 +136,9 @@ describe('buildStreamItems — scaffold detection + grouping', () => {
it('groups a single scaffold-only user message into a one-pill group', () => {
const items = buildStreamItems([userText('<system_reminder>foo</system_reminder>')])
expect(items).toHaveLength(1)
- expect(items[0].kind).toBe('scaffold-group')
- if (items[0].kind === 'scaffold-group') {
- expect(items[0].tagNames).toEqual(['system_reminder'])
+ expect(items[0].kind).toBe('internal-group')
+ if (items[0].kind === 'internal-group') {
+ expect(items[0].labels).toEqual(['system_reminder'])
expect(items[0].messages).toHaveLength(1)
}
})
@@ -153,10 +153,10 @@ describe('buildStreamItems — scaffold detection + grouping', () => {
userText('what changed?'),
assistant('looking into it...'),
])
- expect(items.map((i) => i.kind)).toEqual(['scaffold-group', 'bubble', 'bubble'])
- if (items[0].kind === 'scaffold-group') {
+ expect(items.map((i) => i.kind)).toEqual(['internal-group', 'bubble', 'bubble'])
+ if (items[0].kind === 'internal-group') {
expect(items[0].messages).toHaveLength(4)
- expect(items[0].tagNames).toEqual(['system_reminder', 'system_reminder', 'voice_mode', 'attached_context'])
+ expect(items[0].labels).toEqual(['system_reminder', 'system_reminder', 'voice_mode', 'attached_context'])
}
if (items[1].kind === 'bubble') {
expect(items[1].text).toBe('what changed?')
@@ -172,7 +172,7 @@ describe('buildStreamItems — scaffold detection + grouping', () => {
userText('<voice_mode>off</voice_mode>'),
assistant('reply'),
])
- expect(items.map((i) => i.kind)).toEqual(['scaffold-group', 'bubble', 'scaffold-group', 'bubble'])
+ expect(items.map((i) => i.kind)).toEqual(['internal-group', 'bubble', 'internal-group', 'bubble'])
})
it('does not classify an assistant-role wrapper as scaffold (models can emit `<system_reminder>` in output)', () => {
@@ -211,13 +211,189 @@ describe('buildStreamItems — scaffold detection + grouping', () => {
userText('<system_reminder>x</system_reminder>'),
assistant('reply'),
])
- expect(items.map((i) => i.kind)).toEqual(['bubble', 'scaffold-group', 'bubble'])
- if (items[1].kind === 'scaffold-group') {
+ expect(items.map((i) => i.kind)).toEqual(['bubble', 'internal-group', 'bubble'])
+ if (items[1].kind === 'internal-group') {
expect(items[1].messages).toHaveLength(1)
}
})
})
+describe('buildStreamItems — internal messages (thinking, tool_result) collapse into the same pill', () => {
+ const userText = (text: string): CompatMessage => ({ role: 'user', content: text })
+ const assistant = (text: string): CompatMessage => ({ role: 'assistant', content: text })
+ const thinking = (text: string): CompatMessage => ({ role: 'assistant (thinking)', content: text })
+ const toolResult = (text: string): CompatMessage =>
+ ({
+ role: 'assistant (tool result)',
+ content: text,
+ tool_call_id: 'toolu_1',
+ }) as unknown as CompatMessage
+
+ it('hides an assistant (thinking) bubble inside an internal-group pill', () => {
+ const items = buildStreamItems([userText('What is 2+2?'), thinking('Let me work through this'), assistant('4')])
+ expect(items.map((i) => i.kind)).toEqual(['bubble', 'internal-group', 'bubble'])
+ if (items[1].kind === 'internal-group') {
+ expect(items[1].labels).toEqual(['thinking'])
+ }
+ })
+
+ it('hides an assistant (tool result) bubble inside an internal-group pill', () => {
+ const items = buildStreamItems([
+ userText('Look up the order'),
+ toolResult('<row id="42">paid</row>'),
+ assistant('Your order is paid.'),
+ ])
+ expect(items.map((i) => i.kind)).toEqual(['bubble', 'internal-group', 'bubble'])
+ if (items[1].kind === 'internal-group') {
+ expect(items[1].labels).toEqual(['tool_result'])
+ }
+ })
+
+ it('collapses a thinking + tool_result run into a single pill', () => {
+ const items = buildStreamItems([
+ userText('Build me a funnel for trial conversions.'),
+ thinking('First I need to look up the schema.'),
+ toolResult('events: $pageview, signup_completed, trial_started, ...'),
+ thinking('Now I can compose the funnel.'),
+ toolResult('insight created: id=aqc0'),
+ assistant("Here's your funnel: ..."),
+ ])
+ expect(items.map((i) => i.kind)).toEqual(['bubble', 'internal-group', 'bubble'])
+ if (items[1].kind === 'internal-group') {
+ expect(items[1].messages).toHaveLength(4)
+ expect(items[1].labels).toEqual(['thinking', 'tool_result', 'thinking', 'tool_result'])
+ }
+ })
+
+ it('produces separate pills when a real assistant reply interrupts the internal run', () => {
+ const items = buildStreamItems([
+ userText('Question one'),
+ thinking('first round of reasoning'),
+ toolResult('first tool result'),
+ assistant('Intermediate answer.'),
+ thinking('second round of reasoning'),
+ toolResult('second tool result'),
+ assistant('Final answer.'),
+ ])
+ expect(items.map((i) => i.kind)).toEqual(['bubble', 'internal-group', 'bubble', 'internal-group', 'bubble'])
+ })
+
+ it('coalesces a scaffold + thinking + tool_result run into a single pill', () => {
+ const items = buildStreamItems([
+ userText('<system_reminder>be concise</system_reminder>'),
+ thinking('let me think'),
+ toolResult('lookup result'),
+ assistant('done'),
+ ])
+ expect(items.map((i) => i.kind)).toEqual(['internal-group', 'bubble'])
+ if (items[0].kind === 'internal-group') {
+ expect(items[0].labels).toEqual(['system_reminder', 'thinking', 'tool_result'])
+ }
+ })
+
+ it('hides a user-role message whose content is only Anthropic typed tool_result parts', () => {
+ const userToolResultBlob: CompatMessage = {
+ role: 'user',
+ content: [
+ { type: 'tool_result', tool_use_id: 't1', content: 'row 1' },
+ { type: 'tool_result', tool_use_id: 't2', content: 'row 2' },
+ ] as unknown as CompatMessage['content'],
+ }
+ const items = buildStreamItems([userText('Look up two orders'), userToolResultBlob, assistant('Done.')])
+ expect(items.map((i) => i.kind)).toEqual(['bubble', 'internal-group', 'bubble'])
+ if (items[1].kind === 'internal-group') {
+ expect(items[1].labels).toEqual(['tool_result'])
+ }
+ })
+
+ it('hides a custom `{type:"function", tool_name, content}` user-role tool result', () => {
+ // No nested `function` object — distinguishes from a tool CALL.
+ const userFunctionResult: CompatMessage = {
+ role: 'user',
+ content: [
+ {
+ type: 'function',
+ tool_name: 'fetch_account_context',
+ content: '<current_account_data>...</current_account_data>',
+ },
+ ] as unknown as CompatMessage['content'],
+ }
+ const items = buildStreamItems([
+ userText('What is this account?'),
+ userFunctionResult,
+ assistant('Summary: ...'),
+ ])
+ expect(items.map((i) => i.kind)).toEqual(['bubble', 'internal-group', 'bubble'])
+ if (items[1].kind === 'internal-group') {
+ expect(items[1].labels).toEqual(['tool_result'])
+ }
+ })
+
+ it('does NOT hide a user-role message that mixes a tool_result part with real user text', () => {
+ const mixed: CompatMessage = {
+ role: 'user',
+ content: [
+ { type: 'tool_result', tool_use_id: 't1', content: 'data' },
+ { type: 'text', text: 'please summarize the above' },
+ ] as unknown as CompatMessage['content'],
+ }
+ const items = buildStreamItems([mixed])
+ expect(items.map((i) => i.kind)).toEqual(['bubble'])
+ })
+
+ it('does NOT classify an assistant-role message whose text mentions "thinking" as internal', () => {
+ // Only the synthetic `assistant (thinking)` role triggers hiding — not the substring.
+ const items = buildStreamItems([{ role: 'assistant', content: 'I was thinking we should ...' }])
+ expect(items.map((i) => i.kind)).toEqual(['bubble'])
+ })
+
+ it('preserves the role of the first hidden message on the group (alignment is label-based; role kept for analytics)', () => {
+ const items = buildStreamItems([thinking('first reasoning step')])
+ expect(items).toHaveLength(1)
+ if (items[0].kind === 'internal-group') {
+ expect(items[0].role).toBe('assistant (thinking)')
+ }
+ })
+
+ it('groups Anthropic typed tool_result parts under the `tool_result` label (renders agent-side)', () => {
+ const userToolResultBlob: CompatMessage = {
+ role: 'user',
+ content: [
+ { type: 'tool_result', tool_use_id: 't1', content: 'row 1' },
+ { type: 'tool_result', tool_use_id: 't2', content: 'row 2' },
+ ] as unknown as CompatMessage['content'],
+ }
+ const items = buildStreamItems([userToolResultBlob])
+ if (items[0].kind === 'internal-group') {
+ expect(items[0].labels.every((l) => l === 'tool_result')).toBe(true)
+ }
+ })
+
+ it('groups custom function-shape user-role tool_result under the `tool_result` label', () => {
+ const userFunctionResult: CompatMessage = {
+ role: 'user',
+ content: [
+ {
+ type: 'function',
+ tool_name: 'fetch_account_context',
+ content: '<current_account_data>...</current_account_data>',
+ },
+ ] as unknown as CompatMessage['content'],
+ }
+ const items = buildStreamItems([userFunctionResult])
+ if (items[0].kind === 'internal-group') {
+ expect(items[0].labels).toEqual(['tool_result'])
+ }
+ })
+
+ it('groups scaffold tags under their tag-name label (renders user-side)', () => {
+ const items = buildStreamItems([{ role: 'user', content: '<system_reminder>foo</system_reminder>' }])
+ if (items[0].kind === 'internal-group') {
+ expect(items[0].labels).toEqual(['system_reminder'])
+ }
+ })
+})
+
describe('captureUnrenderableMessageOnce', () => {
const imageMessage = (url: string): CompatMessage => ({
role: 'user',
diff --git a/products/ai_observability/frontend/ConversationDisplay/TranscriptBubbleStream.tsx b/products/ai_observability/frontend/ConversationDisplay/TranscriptBubbleStream.tsx
index 0be5b5dd12c4..0c88d52ae632 100644
--- a/products/ai_observability/frontend/ConversationDisplay/TranscriptBubbleStream.tsx
+++ b/products/ai_observability/frontend/ConversationDisplay/TranscriptBubbleStream.tsx
@@ -9,9 +9,13 @@ import { MessageTemplate } from 'scenes/max/messages/MessageTemplate'
import { CompatMessage } from '../types'
import {
AVAILABLE_TOOLS_ROLE,
+ INTERNAL_THINKING_ROLE,
+ INTERNAL_TOOL_RESULT_ROLE,
+ extractInternalContent,
+ extractText,
extractTextContent,
getScaffoldTagName,
- hasStringContentField,
+ isInternalToolResultUserMessage,
isToolStepItem,
} from '../utils'
@@ -21,27 +25,6 @@ import {
// one click away via "Show steps".
const HIDDEN_ROLES = new Set<string>(['system', AVAILABLE_TOOLS_ROLE])
-function extractText(message: CompatMessage): string {
- const content = message.content
- if (typeof content === 'string') {
- return content
- }
- if (Array.isArray(content)) {
- const parts: string[] = []
- for (const part of content) {
- const text = extractTextContent(part)
- if (text !== undefined) {
- parts.push(text)
- }
- }
- return parts.join('\n')
- }
- if (hasStringContentField(content)) {
- return content.content
- }
- return ''
-}
-
function isUnrenderableContentItem(item: unknown): boolean {
return extractTextContent(item) === undefined && !isToolStepItem(item)
}
@@ -91,15 +74,42 @@ export function captureUnrenderableMessageOnce(message: CompatMessage, seen: Set
}
// An item in the rendered transcript stream. Bubbles render as `MessageTemplate`s.
-// Scaffold groups render as a single collapsed pill where the hidden messages
+// Internal groups render as a single collapsed pill where the hidden messages
// would have sat — preserving chronological position without polluting the chat.
+// "Internal" covers framework prompt scaffolds, model reasoning/thinking parts,
+// and tool-call results — anything the user didn't write and didn't ask to see.
type StreamItem =
| { kind: 'bubble'; message: CompatMessage; text: string; nonText: boolean }
- | { kind: 'scaffold-group'; messages: CompatMessage[]; tagNames: string[]; role: string }
+ | { kind: 'internal-group'; messages: CompatMessage[]; labels: string[]; role: string }
type SessionEntry =
| { kind: 'bubble'; message: CompatMessage; text: string; nonText: boolean }
- | { kind: 'scaffold'; message: CompatMessage; scaffoldTag: string }
+ | { kind: 'internal'; message: CompatMessage; label: string }
+
+// Returns a short label identifying *why* a message is internal. Returns
+// `undefined` for messages that should render as normal bubbles.
+function getInternalLabel(message: CompatMessage): string | undefined {
+ if (message.role === INTERNAL_THINKING_ROLE) {
+ return 'thinking'
+ }
+ if (message.role === INTERNAL_TOOL_RESULT_ROLE) {
+ return 'tool_result'
+ }
+ const scaffoldTag = getScaffoldTagName(message)
+ if (scaffoldTag !== undefined) {
+ return scaffoldTag
+ }
+ if (isInternalToolResultUserMessage(message)) {
+ return 'tool_result'
+ }
+ return undefined
+}
+
+const AGENT_SIDE_LABELS = new Set<string>(['thinking', 'tool_result'])
+
+function pillSideFor(labels: string[]): 'left' | 'right' {
+ return labels.length > 0 && AGENT_SIDE_LABELS.has(labels[0]) ? 'left' : 'right'
+}
function classifyMessages(messages: CompatMessage[]): SessionEntry[] {
const result: SessionEntry[] = []
@@ -107,9 +117,9 @@ function classifyMessages(messages: CompatMessage[]): SessionEntry[] {
if (HIDDEN_ROLES.has(message.role)) {
continue
}
- const scaffoldTag = getScaffoldTagName(message)
- if (scaffoldTag !== undefined) {
- result.push({ kind: 'scaffold', message, scaffoldTag })
+ const internalLabel = getInternalLabel(message)
+ if (internalLabel !== undefined) {
+ result.push({ kind: 'internal', message, label: internalLabel })
continue
}
const text = extractText(message)
@@ -122,27 +132,24 @@ function classifyMessages(messages: CompatMessage[]): SessionEntry[] {
return result
}
-function groupScaffolds(classified: SessionEntry[]): StreamItem[] {
+function groupInternal(classified: SessionEntry[]): StreamItem[] {
const result: StreamItem[] = []
- let pendingScaffolds: Extract<SessionEntry, { kind: 'scaffold' }>[] = []
+ let pending: Extract<SessionEntry, { kind: 'internal' }>[] = []
const makeGroup = (): void => {
- if (pendingScaffolds.length === 0) {
+ if (pending.length === 0) {
return
}
result.push({
- kind: 'scaffold-group',
- messages: pendingScaffolds.map((b) => b.message),
- tagNames: pendingScaffolds.map((b) => b.scaffoldTag),
- // All pending scaffolds share the same role (the predicate only
- // accepts `role: 'user'`), so picking the first is sufficient and
- // future-proof if we relax the predicate later.
- role: pendingScaffolds[0].message.role,
+ kind: 'internal-group',
+ messages: pending.map((b) => b.message),
+ labels: pending.map((b) => b.label),
+ role: pending[0].message.role,
})
- pendingScaffolds = []
+ pending = []
}
for (const item of classified) {
- if (item.kind === 'scaffold') {
- pendingScaffolds.push(item)
+ if (item.kind === 'internal') {
+ pending.push(item)
continue
}
makeGroup()
@@ -154,7 +161,7 @@ function groupScaffolds(classified: SessionEntry[]): StreamItem[] {
// Exported so the test can pin the grouping logic without rendering React.
export function buildStreamItems(messages: CompatMessage[]): StreamItem[] {
- return groupScaffolds(classifyMessages(messages))
+ return groupInternal(classifyMessages(messages))
}
/**
@@ -205,30 +212,29 @@ export function TranscriptBubbleStream({
{item.nonText && <div className="italic text-muted text-xs mt-1">(has attachments)</div>}
</MessageTemplate>
) : (
- <ScaffoldGroupPill key={i} messages={item.messages} tagNames={item.tagNames} role={item.role} />
+ <InternalGroupPill key={i} messages={item.messages} labels={item.labels} role={item.role} />
)
)}
</div>
)
}
-function ScaffoldGroupPill({
+function InternalGroupPill({
messages,
- tagNames,
- role,
+ labels,
+ role: _role,
}: {
messages: CompatMessage[]
- tagNames: string[]
+ labels: string[]
role: string
}): JSX.Element {
const [expanded, setExpanded] = useState(false)
- const distinctTags = useMemo(() => Array.from(new Set(tagNames)), [tagNames])
+ const distinctLabels = useMemo(() => Array.from(new Set(labels)), [labels])
const count = messages.length
- const label = count === 1 ? '1 hidden context block' : `${count} hidden context blocks`
- // Mirror the bubble-alignment convention: user-role on the right, everything else on the left.
- const isUser = role === 'user'
- const alignSelf = isUser ? 'self-end' : 'self-start'
- const buttonAlignSelf = isUser ? 'self-end' : 'self-start'
+ const label = count === 1 ? '1 hidden internal message' : `${count} hidden internal messages`
+ const side = pillSideFor(labels)
+ const alignSelf = side === 'right' ? 'self-end' : 'self-start'
+ const buttonAlignSelf = side === 'right' ? 'self-end' : 'self-start'
return (
<div className={`flex flex-col gap-1 text-xs text-muted max-w-[75%] ${alignSelf}`}>
<button
@@ -238,7 +244,9 @@ function ScaffoldGroupPill({
>
<IconChevronRight className={`transition-transform ${expanded ? 'rotate-90' : ''}`} />
<span>{expanded ? `Hide ${label}` : `Show ${label}`}</span>
- {distinctTags.length > 0 && <span className="font-mono opacity-60">— {distinctTags.join(', ')}</span>}
+ {distinctLabels.length > 0 && (
+ <span className="font-mono opacity-60">— {distinctLabels.join(', ')}</span>
+ )}
</button>
{expanded && (
<div className="flex flex-col gap-1.5 opacity-70">
@@ -247,7 +255,7 @@ function ScaffoldGroupPill({
key={i}
className="font-mono whitespace-pre-wrap break-words text-xs m-0 px-2 py-1 bg-bg-light rounded border"
>
- {extractText(m)}
+ {extractInternalContent(m)}
</pre>
))}
</div>
diff --git a/products/ai_observability/frontend/utils.test.ts b/products/ai_observability/frontend/utils.test.ts
index 1d023384b837..4451233a3f72 100644
--- a/products/ai_observability/frontend/utils.test.ts
+++ b/products/ai_observability/frontend/utils.test.ts
@@ -14,9 +14,11 @@ import {
hasCostBreakdown,
hasStringContentField,
isEmptyJSONStructure,
+ isInternalToolResultUserMessage,
isLangChainMessage,
isInternalScaffoldMessage,
isTextContentItem,
+ isToolResult,
isToolStepItem,
looksLikeXml,
normalizeMessage,
@@ -1306,6 +1308,95 @@ describe('AI observability utils', () => {
})
})
+ describe('isToolResult', () => {
+ it.each<[name: string, item: unknown]>([
+ ['Anthropic typed tool_result', { type: 'tool_result', tool_use_id: 'toolu_1', content: 'ok' }],
+ [
+ 'Vercel SDK tool-result',
+ { type: 'tool-result', toolCallId: 'a', toolName: 'search_docs', output: { ok: true } },
+ ],
+ [
+ 'OpenAI Responses function_call_output',
+ { type: 'function_call_output', call_id: 'c1', output: 'opaque' },
+ ],
+ [
+ 'custom {type:"function", tool_name, content}',
+ { type: 'function', tool_name: 'lookup', content: 'opaque' },
+ ],
+ ])('returns true for: %s', (_, item) => {
+ expect(isToolResult(item)).toBe(true)
+ })
+
+ it.each<[name: string, item: unknown]>([
+ ['plain text part', { type: 'text', text: 'hi' }],
+ ['Anthropic tool_use (a tool CALL, not a result)', { type: 'tool_use', id: 't1', name: 'x', input: {} }],
+ [
+ 'OpenAI tool CALL with nested function object',
+ { type: 'function', function: { name: 'get_weather', arguments: '{}' } },
+ ],
+ ['Vercel SDK tool-call', { type: 'tool-call', toolCallId: 'a', toolName: 'x', input: {} }],
+ ['image part', { type: 'image_url', image_url: { url: 'x' } }],
+ ['null', null],
+ ['plain string', 'hello'],
+ ['function-typed item without tool_name', { type: 'function' }],
+ ])('returns false for: %s', (_, item) => {
+ expect(isToolResult(item)).toBe(false)
+ })
+ })
+
+ describe('isInternalToolResultUserMessage', () => {
+ it('returns true for a user message whose content is only typed tool_result parts', () => {
+ const message: CompatMessage = {
+ role: 'user',
+ content: [
+ { type: 'tool_result', tool_use_id: 't1', content: 'value-1' },
+ { type: 'tool_result', tool_use_id: 't2', content: 'value-2' },
+ ] as unknown as CompatMessage['content'],
+ }
+ expect(isInternalToolResultUserMessage(message)).toBe(true)
+ })
+
+ it('returns true for the custom `{type:"function", tool_name, content}` shape', () => {
+ const message: CompatMessage = {
+ role: 'user',
+ content: [
+ { type: 'function', tool_name: 'lookup', content: 'opaque' },
+ ] as unknown as CompatMessage['content'],
+ }
+ expect(isInternalToolResultUserMessage(message)).toBe(true)
+ })
+
+ it('returns false when a tool-result part sits alongside real user text', () => {
+ // Hiding would drop the user's prose.
+ const message: CompatMessage = {
+ role: 'user',
+ content: [
+ { type: 'tool_result', tool_use_id: 't1', content: 'value' },
+ { type: 'text', text: 'and please summarize the above' },
+ ] as unknown as CompatMessage['content'],
+ }
+ expect(isInternalToolResultUserMessage(message)).toBe(false)
+ })
+
+ it('returns false for an empty content array', () => {
+ expect(isInternalToolResultUserMessage({ role: 'user', content: [] })).toBe(false)
+ })
+
+ it('returns false for an assistant-role message even if its content is tool-result-shaped', () => {
+ const message: CompatMessage = {
+ role: 'assistant',
+ content: [
+ { type: 'tool_result', tool_use_id: 't1', content: 'value' },
+ ] as unknown as CompatMessage['content'],
+ }
+ expect(isInternalToolResultUserMessage(message)).toBe(false)
+ })
+
+ it('returns false for a flat-string user message (text body, not a parts list)', () => {
+ expect(isInternalToolResultUserMessage({ role: 'user', content: 'follow-up question' })).toBe(false)
+ })
+ })
+
describe('formatLLMEventTitle', () => {
it('formats LLMTrace with traceName', () => {
const trace: LLMTrace = {
diff --git a/products/ai_observability/frontend/utils.ts b/products/ai_observability/frontend/utils.ts
index eb6d1ce20c78..0869eaf85ea0 100644
--- a/products/ai_observability/frontend/utils.ts
+++ b/products/ai_observability/frontend/utils.ts
@@ -455,6 +455,46 @@ export function extractTextContent(item: unknown): string | undefined {
return undefined
}
+// Pulls the user-visible text out of a whole message. Walks a content array (joining
+// per-part text), falls back to the `{type, content: string}` legacy wrapper, and
+// otherwise returns '' (caller decides what to do with an empty string).
+export function extractText(message: CompatMessage): string {
+ const content = message.content
+ if (typeof content === 'string') {
+ return content
+ }
+ if (Array.isArray(content)) {
+ const parts: string[] = []
+ for (const part of content) {
+ const text = extractTextContent(part)
+ if (text !== undefined) {
+ parts.push(text)
+ }
+ }
+ return parts.join('\n')
+ }
+ if (hasStringContentField(content)) {
+ return content.content
+ }
+ return ''
+}
+
+// Like `extractText`, but with one extra fallback for the custom function-shape
+// tool-result user message (`{role:'user', content:[{type:'function', tool_name, content}]}`).
+export function extractInternalContent(message: CompatMessage): string {
+ const text = extractText(message)
+ if (text.length > 0) {
+ return text
+ }
+ if (Array.isArray(message.content)) {
+ return message.content
+ .map((p) => (isObject(p) && isString(p.content) ? p.content : ''))
+ .filter(Boolean)
+ .join('\n')
+ }
+ return ''
+}
+
export function isAnthropicToolCallMessage(output: unknown): output is AnthropicToolCallMessage {
return !!output && typeof output === 'object' && 'type' in output && output.type === 'tool_use'
}
@@ -514,6 +554,35 @@ export function isInternalScaffoldMessage(message: CompatMessage): boolean {
return getScaffoldTagName(message) !== undefined
}
+// Matches tool-result-shaped content {type: 'function', tool_name: string, content: ...}`
+// with NO nested `function` object to distinguish from a tool call
+function isCustomFunctionToolResult(item: unknown): boolean {
+ return isObject(item) && item.type === 'function' && isString(item.tool_name) && !isObject(item.function)
+}
+
+export function isToolResult(item: unknown): boolean {
+ return (
+ isAnthropicToolResultMessage(item) ||
+ isVercelSDKToolResultMessage(item) ||
+ isOpenAIResponsesFunctionCallOutput(item) ||
+ isCustomFunctionToolResult(item)
+ )
+}
+
+// A user-role message whose content is exclusively tool-results is framework-emitted
+// noise (the user did not write it, their agent appended tool responses into the
+// conversation history).
+export function isInternalToolResultUserMessage(message: CompatMessage): boolean {
+ if (message.role !== 'user') {
+ return false
+ }
+ const { content } = message
+ if (!Array.isArray(content) || content.length === 0) {
+ return false
+ }
+ return content.every(isToolResult)
+}
+
export function isToolStepItem(item: unknown): boolean {
if (
isAnthropicToolCallMessage(item) ||
@@ -1223,14 +1292,14 @@ export function normalizeMessage(rawMessage: unknown, defaultRole: string): Comp
if (isAnthropicThinkingMessage(rawMessage)) {
return [
{
- role: normalizeRole('assistant (thinking)', roleToUse),
+ role: normalizeRole(INTERNAL_THINKING_ROLE, roleToUse),
content: rawMessage.thinking,
},
]
}
// Tool result completion
if (isAnthropicToolResultMessage(rawMessage)) {
- const toolResultRole = normalizeRole('assistant (tool result)', roleToUse)
+ const toolResultRole = normalizeRole(INTERNAL_TOOL_RESULT_ROLE, roleToUse)
if (Array.isArray(rawMessage.content)) {
return rawMessage.content
.map((content) => normalizeMessage(content, toolResultRole))
@@ -1273,7 +1342,7 @@ export function normalizeMessage(rawMessage: unknown, defaultRole: string): Comp
if (isOpenAIResponsesFunctionCallOutput(rawMessage)) {
return [
{
- role: normalizeRole('assistant (tool result)', roleToUse),
+ role: normalizeRole(INTERNAL_TOOL_RESULT_ROLE, roleToUse),
content: rawMessage.output,
tool_call_id: rawMessage.call_id,
},
@@ -1289,7 +1358,7 @@ export function normalizeMessage(rawMessage: unknown, defaultRole: string): Comp
}
return [
{
- role: normalizeRole('assistant (thinking)', roleToUse),
+ role: normalizeRole(INTERNAL_THINKING_ROLE, roleToUse),
content: summaryText,
},
]
@@ -1346,7 +1415,7 @@ export function normalizeMessage(rawMessage: unknown, defaultRole: string): Comp
}
return [
{
- role: normalizeRole('assistant (tool result)', roleToUse),
+ role: normalizeRole(INTERNAL_TOOL_RESULT_ROLE, roleToUse),
content,
tool_call_id: rawMessage.toolCallId,
},
@@ -1471,6 +1540,9 @@ export function normalizeMessage(rawMessage: unknown, defaultRole: string): Comp
// as a pseudo-message
export const AVAILABLE_TOOLS_ROLE = 'available tools'
+export const INTERNAL_THINKING_ROLE = 'assistant (thinking)'
+export const INTERNAL_TOOL_RESULT_ROLE = 'assistant (tool result)'
+
// Returns the tool names invoked across events in chronological order (duplicates preserved)
export function getToolNamesCalled(events: LLMTraceEvent[]): string[] {
const sorted = [...events].sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime())