🤯 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
✨ feat(claude-code): synthesize WebSearch results and render structured metadata (#18001)
AmAzing-b993126238ac
diff --git a/packages/builtin-tool-claude-code/src/client/Render/WebSearch/index.tsx b/packages/builtin-tool-claude-code/src/client/Render/WebSearch/index.tsxindex 67012cefa8f..c6d112da2a6 100644--- a/packages/builtin-tool-claude-code/src/client/Render/WebSearch/index.tsx+++ b/packages/builtin-tool-claude-code/src/client/Render/WebSearch/index.tsx@@ -1,26 +1,148 @@'use client';import type { BuiltinRenderProps } from '@lobechat/types';-import { Highlighter } from '@lobehub/ui';+import { Flexbox, Highlighter, Text } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';import { memo } from 'react';-import type { WebSearchArgs } from '../../../types';--const WebSearch = memo<BuiltinRenderProps<WebSearchArgs>>(({ content }) => {- if (!content) return null;-- return (- <Highlighter- wrap- language={'text'}- showLanguage={false}- style={{ maxHeight: 240, overflow: 'auto' }}- variant={'borderless'}- >- {content}- </Highlighter>- );-});+import type { WebSearchArgs, WebSearchPluginState, WebSearchResult } from '../../../types';++const styles = createStaticStyles(({ css, cssVar }) => ({+ hostname: css`+ overflow: hidden;++ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ metadata: css`+ overflow: hidden;++ min-width: 0;++ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ queryRow: css`+ align-items: center;+ justify-content: space-between;++ min-width: 0;+ padding-block: 2px;+ padding-inline: 4px;+ `,+ resultItem: css`+ min-width: 0;+ padding-block: 5px;+ padding-inline: 4px;+ border-block-end: 1px solid ${cssVar.colorSplit};++ &:last-child {+ border-block-end: 0;+ }+ `,+ root: css`+ overflow: auto;+ min-width: 0;+ max-height: 280px;+ padding-block: 2px;+ `,+ snippet: css`+ font-size: 12px;+ line-height: 1.45;+ color: ${cssVar.colorTextSecondary};+ `,+ title: css`+ overflow: hidden;++ font-size: 13px;+ font-weight: 500;+ line-height: 1.45;+ color: ${cssVar.colorText};+ text-overflow: ellipsis;+ white-space: nowrap;++ &:hover {+ color: ${cssVar.colorLink};+ }+ `,+}));++const getWebSearchHostname = (link: string): string | undefined => {+ try {+ const url = new URL(link);+ return url.protocol === 'http:' || url.protocol === 'https:'+ ? url.hostname || undefined+ : undefined;+ } catch {+ return;+ }+};++const isWebSearchResult = (value: unknown): value is WebSearchResult => {+ if (!value || typeof value !== 'object') return false;++ const { link } = value as Partial<WebSearchResult>;+ return typeof link === 'string' && !!getWebSearchHostname(link);+};++const WebSearch = memo<BuiltinRenderProps<WebSearchArgs, WebSearchPluginState>>(+ ({ args, content, pluginState }) => {+ const results = pluginState?.results?.filter(isWebSearchResult) ?? [];++ if (results.length === 0) {+ if (!content) return null;++ return (+ <Highlighter+ wrap+ language={'text'}+ showLanguage={false}+ style={{ maxHeight: 240, overflow: 'auto' }}+ variant={'borderless'}+ >+ {content}+ </Highlighter>+ );+ }++ const query = pluginState?.query || args?.query;+ const duration =+ typeof pluginState?.durationSeconds === 'number' &&+ Number.isFinite(pluginState.durationSeconds) &&+ pluginState.durationSeconds >= 0+ ? `${pluginState.durationSeconds.toFixed(2)}s`+ : undefined;++ return (+ <Flexbox className={styles.root} gap={0}>+ {(query || duration) && (+ <Flexbox horizontal className={styles.queryRow} gap={8}>+ <span className={styles.metadata}>{query}</span>+ {duration && <span className={styles.metadata}>{duration}</span>}+ </Flexbox>+ )}+ {results.map((result, index) => {+ const hostname = getWebSearchHostname(result.link);+ const title = result.title || hostname || result.link;++ return (+ <Flexbox className={styles.resultItem} gap={3} key={`${result.link}-${index}`}>+ <a href={result.link} rel={'noreferrer'} target={'_blank'}>+ <span className={styles.title}>{title}</span>+ </a>+ <Text className={styles.hostname}>{hostname || result.link}</Text>+ {result.snippet && <Text className={styles.snippet}>{result.snippet}</Text>}+ </Flexbox>+ );+ })}+ </Flexbox>+ );+ },+);WebSearch.displayName = 'ClaudeCodeWebSearch';diff --git a/packages/builtin-tool-claude-code/src/types.ts b/packages/builtin-tool-claude-code/src/types.tsindex d5a63ebcedc..d52e110d1b7 100644--- a/packages/builtin-tool-claude-code/src/types.ts+++ b/packages/builtin-tool-claude-code/src/types.ts@@ -300,6 +300,21 @@ export interface WebSearchArgs {query?: string;}+/** Structured source metadata synthesized from compatible WebSearch results. */+export interface WebSearchResult {+ hostname?: string;+ link: string;+ snippet?: string;+ title?: string;+}++/** Bounded WebSearch result state persisted alongside the text fallback. */+export interface WebSearchPluginState {+ durationSeconds?: number;+ query?: string;+ results?: WebSearchResult[];+}+/*** Arguments for CC's built-in `WebFetch` tool. CC fetches a URL and asks the* model to extract `prompt` from the page; the tool_result is the model'sdiff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.test.tsindex 88442cea31b..f4963eaea0d 100644--- a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts@@ -994,6 +994,197 @@ describe('ClaudeCodeAdapter', () => {const result = events.find((e) => e.type === 'tool_result');expect(result!.data.isError).toBe(true);});++ it('preserves structured WebSearch sources alongside the text fallback', () => {+ const adapter = new ClaudeCodeAdapter();+ const content = 'Web search results for query: "TradingView copper futures symbol ticker"';+ adapter.adapt({ subtype: 'init', type: 'system' });+ adapter.adapt({+ message: {+ content: [+ {+ id: 'ws1',+ input: { query: 'TradingView copper futures symbol ticker' },+ name: 'WebSearch',+ type: 'tool_use',+ },+ ],+ id: 'msg_1',+ },+ type: 'assistant',+ });++ const events = adapter.adapt({+ message: {+ content: [{ content, tool_use_id: 'ws1', type: 'tool_result' }],+ role: 'user',+ },+ tool_use_result: {+ durationSeconds: 2.938580792,+ query: 'TradingView copper futures symbol ticker',+ results: [+ {+ hostLogo: 'data:image/png;base64,not-persisted',+ hostname: 'www.tradingview.com',+ link: 'https://www.tradingview.com/symbols/COMEX-HG1!/',+ snippet: 'The current price of Copper Futures is 6.7190 USD',+ title: 'HG1! Charts and Quotes - Futures',+ },+ ],+ },+ type: 'user',+ });++ const result = events.find((event) => event.type === 'tool_result');+ const end = events.find((event) => event.type === 'tool_end');+ const pluginState = {+ durationSeconds: 2.938580792,+ query: 'TradingView copper futures symbol ticker',+ results: [+ {+ hostname: 'www.tradingview.com',+ link: 'https://www.tradingview.com/symbols/COMEX-HG1!/',+ snippet: 'The current price of Copper Futures is 6.7190 USD',+ title: 'HG1! Charts and Quotes - Futures',+ },+ ],+ };++ expect(result?.data).toMatchObject({+ content,+ isError: false,+ pluginState,+ toolCallId: 'ws1',+ });+ expect(end?.data.result).toEqual({ content, state: pluginState, success: true });+ });++ it('bounds and filters structured WebSearch metadata before persistence', () => {+ const adapter = new ClaudeCodeAdapter();+ adapter.adapt({ subtype: 'init', type: 'system' });+ adapter.adapt({+ message: {+ content: [+ { id: 'ws1', input: { query: 'bounded search' }, name: 'WebSearch', type: 'tool_use' },+ ],+ id: 'msg_1',+ },+ type: 'assistant',+ });++ const validResults = Array.from({ length: 10 }, (_, index) => ({+ hostname: index === 0 ? 'trusted.example' : `example-${index}.com`,+ link: index === 0 ? 'https://evil.example/0' : `https://example.com/${index}`,+ snippet: index === 0 ? 's'.repeat(3000) : `Snippet ${index}`,+ title: index === 0 ? '😀'.repeat(400) : `Result ${index}`,+ }));+ const events = adapter.adapt({+ message: {+ content: [{ content: 'bounded output', tool_use_id: 'ws1', type: 'tool_result' }],+ role: 'user',+ },+ tool_use_result: {+ durationSeconds: -1,+ query: ` ${'q'.repeat(600)} `,+ results: [+ { link: 'javascript:alert(1)', title: 'Unsafe result' },+ { link: `https://example.com/${'x'.repeat(2048)}`, title: 'Oversized URL' },+ ...validResults,+ ],+ },+ type: 'user',+ });++ const pluginState = events.find((event) => event.type === 'tool_result')?.data.pluginState;+ expect(pluginState.query).toHaveLength(512);+ expect(pluginState).not.toHaveProperty('durationSeconds');+ expect(pluginState.results).toHaveLength(8);+ expect(pluginState.results[0]).toMatchObject({+ hostname: 'evil.example',+ link: 'https://evil.example/0',+ snippet: 's'.repeat(2048),+ });+ expect(pluginState.results[0].title).toHaveLength(512);+ expect(pluginState.results).not.toContainEqual(+ expect.objectContaining({ title: 'Unsafe result' }),+ );+ });++ it('does not synthesize successful WebSearch state for an error result', () => {+ const adapter = new ClaudeCodeAdapter();+ adapter.adapt({ subtype: 'init', type: 'system' });+ adapter.adapt({+ message: {+ content: [+ { id: 'ws1', input: { query: 'failing search' }, name: 'WebSearch', type: 'tool_use' },+ ],+ id: 'msg_1',+ },+ type: 'assistant',+ });++ const events = adapter.adapt({+ message: {+ content: [+ {+ content: 'Unable to connect to search provider',+ is_error: true,+ tool_use_id: 'ws1',+ type: 'tool_result',+ },+ ],+ role: 'user',+ },+ tool_use_result: {+ isHardFailure: true,+ query: 'failing search',+ results: [+ {+ link: 'https://example.com/should-not-persist',+ title: 'Stale result',+ },+ ],+ },+ type: 'user',+ });++ const result = events.find((event) => event.type === 'tool_result');+ const end = events.find((event) => event.type === 'tool_end');+ expect(result?.data).toMatchObject({+ content: 'Unable to connect to search provider',+ isError: true,+ });+ expect(result?.data.pluginState).toBeUndefined();+ expect(end?.data.result).not.toHaveProperty('state');+ });++ it('ignores structured search-shaped metadata for non-WebSearch tools', () => {+ const adapter = new ClaudeCodeAdapter();+ adapter.adapt({ subtype: 'init', type: 'system' });+ adapter.adapt({+ message: {+ content: [{ id: 'read1', input: {}, name: 'Read', type: 'tool_use' }],+ id: 'msg_1',+ },+ type: 'assistant',+ });++ const events = adapter.adapt({+ message: {+ content: [{ content: 'file contents', tool_use_id: 'read1', type: 'tool_result' }],+ role: 'user',+ },+ tool_use_result: {+ query: 'spoofed search',+ results: [{ link: 'https://example.com', title: 'Should not persist' }],+ },+ type: 'user',+ });++ expect(+ events.find((event) => event.type === 'tool_result')?.data.pluginState,+ ).toBeUndefined();+ });});describe('ToolSearch tool_reference content ()', () => {diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.tsindex dd388a0effd..f0a04368f17 100644--- a/packages/heterogeneous-agents/src/adapters/claudeCode.ts+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.ts@@ -83,6 +83,20 @@ const CC_TODO_WRITE_TOOL_NAME = 'TodoWrite';const CC_TASK_CREATE_TOOL_NAME = 'TaskCreate';const CC_TASK_UPDATE_TOOL_NAME = 'TaskUpdate';const CC_TASK_LIST_TOOL_NAME = 'TaskList';+const CC_WEB_SEARCH_TOOL_NAME = 'WebSearch';++/**+ * Qoder includes the structured WebSearch response beside the model-facing+ * text block. Keep the persisted state bounded: the raw provider payload can+ * contain extra fields (for example host logos) and is not safe to store as-is.+ */+const WEB_SEARCH_MAX_RESULTS = 8;+const WEB_SEARCH_MAX_RESULT_CANDIDATES = 32;+const WEB_SEARCH_MAX_QUERY_LENGTH = 512;+const WEB_SEARCH_MAX_TITLE_LENGTH = 512;+const WEB_SEARCH_MAX_LINK_LENGTH = 2048;+const WEB_SEARCH_MAX_SNIPPET_LENGTH = 2048;+const WEB_SEARCH_MAX_HOSTNAME_LENGTH = 255;/*** tool_result confirmation emitted by CC for a successful `TaskCreate`.@@ -193,6 +207,19 @@ interface ClaudeCodeTaskEntry {subject: string;}+interface SynthesizedWebSearchResult {+ hostname: string;+ link: string;+ snippet?: string;+ title?: string;+}++interface SynthesizedWebSearchPluginState {+ durationSeconds?: number;+ query?: string;+ results?: SynthesizedWebSearchResult[];+}+const CLAUDE_CODE_CLI_INSTALL_DOCS_URL =getHeterogeneousAgentConfigOrThrow('claude-code').auth.docsUrl;@@ -434,6 +461,95 @@ const asRecord = (value: unknown): Record<string, unknown> | undefined =>? (value as Record<string, unknown>): undefined;+const normalizeBoundedString = (value: unknown, maxLength: number): string | undefined => {+ if (typeof value !== 'string') return;++ const trimmed = value.trim();+ if (!trimmed) return;++ let normalized = trimmed.slice(0, maxLength);+ const finalCodeUnit = normalized.charCodeAt(normalized.length - 1);+ if (finalCodeUnit >= 0xd800 && finalCodeUnit <= 0xdbff) normalized = normalized.slice(0, -1);++ return normalized || undefined;+};++const normalizeWebSearchLink = (+ value: unknown,+): Pick<SynthesizedWebSearchResult, 'hostname' | 'link'> | undefined => {+ if (typeof value !== 'string') return;++ const link = value.trim();+ if (!link || link.length > WEB_SEARCH_MAX_LINK_LENGTH) return;++ try {+ const url = new URL(link);+ if (+ (url.protocol !== 'http:' && url.protocol !== 'https:') ||+ !url.hostname ||+ url.hostname.length > WEB_SEARCH_MAX_HOSTNAME_LENGTH+ ) {+ return;+ }++ return { hostname: url.hostname, link };+ } catch {+ return;+ }+};++/**+ * Normalize Qoder's top-level `tool_use_result` into the bounded plugin state+ * consumed by the WebSearch card. This intentionally accepts only the known+ * source fields instead of persisting the provider payload wholesale.+ */+const synthesizeWebSearchPluginState = (+ toolUseResult: unknown,+): SynthesizedWebSearchPluginState | undefined => {+ const raw = asRecord(toolUseResult);+ if (!raw) return;++ const query = normalizeBoundedString(raw.query, WEB_SEARCH_MAX_QUERY_LENGTH);+ const durationSeconds =+ typeof raw.durationSeconds === 'number' &&+ Number.isFinite(raw.durationSeconds) &&+ raw.durationSeconds >= 0+ ? raw.durationSeconds+ : undefined;++ const rawResults = Array.isArray(raw.results) ? raw.results : undefined;+ const hasResults = rawResults !== undefined;+ const results: SynthesizedWebSearchResult[] = [];+ if (rawResults) {+ for (const value of rawResults.slice(0, WEB_SEARCH_MAX_RESULT_CANDIDATES)) {+ if (results.length >= WEB_SEARCH_MAX_RESULTS) break;++ const result = asRecord(value);+ if (!result) continue;++ const normalizedLink = normalizeWebSearchLink(result.link);+ if (!normalizedLink) continue;++ const title = normalizeBoundedString(result.title, WEB_SEARCH_MAX_TITLE_LENGTH);+ const snippet = normalizeBoundedString(result.snippet, WEB_SEARCH_MAX_SNIPPET_LENGTH);++ results.push({+ ...normalizedLink,+ ...(snippet ? { snippet } : {}),+ ...(title ? { title } : {}),+ });+ }+ }++ if (!query && durationSeconds === undefined && !hasResults) return;++ return {+ ...(durationSeconds === undefined ? {} : { durationSeconds }),+ ...(query ? { query } : {}),+ ...(hasResults ? { results } : {}),+ };+};+const getPathValue = (raw: Record<string, unknown>, path: string[]): unknown => {let current: unknown = raw;for (const key of path) {@@ -1668,6 +1784,13 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {const content = raw.message?.content;if (!Array.isArray(content)) return [];+ // `tool_use_result` is event-level and carries no tool id. Associate it+ // only when the event has exactly one tool_result block; otherwise it is+ // impossible to attach the provider metadata without risking cross-tool+ // state corruption.+ const toolResultCount = content.filter((block) => block?.type === 'tool_result').length;+ const structuredToolUseResult = toolResultCount === 1 ? raw.tool_use_result : undefined;+const subagentCtx: SubagentEventContext | undefined = raw.parent_tool_use_id? { parentToolCallId: raw.parent_tool_use_id }: undefined;@@ -1751,11 +1874,20 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {? this.applyTaskToolResult(toolCallId, !!block.is_error, resultContent): undefined;- // Images are mutually exclusive with Todo/Task results in practice (a- // `Read` is neither), but merge defensively so a future producer that- // carries both doesn't clobber one. `data` is still raw base64 here; the- // runtime pipeline uploads and rewrites these entries before persistence.- let pluginState: Record<string, any> | undefined = todoWritePluginState ?? taskPluginState;+ const webSearchPluginState =+ !block.is_error && this.toolPayloadById.get(toolCallId)?.apiName === CC_WEB_SEARCH_TOOL_NAME+ ? synthesizeWebSearchPluginState(structuredToolUseResult)+ : undefined;++ // These result types are mutually exclusive in practice, but merge+ // defensively so a future producer carrying multiple structured fields+ // cannot clobber an existing state fragment. Image `data` is still raw+ // base64 here; the runtime pipeline uploads and rewrites it before+ // persistence.+ let pluginState: Record<string, any> | undefined;+ for (const state of [todoWritePluginState, taskPluginState, webSearchPluginState]) {+ if (state) pluginState = { ...pluginState, ...state };+ }if (images.length > 0) {pluginState = { ...pluginState, images };}diff --git a/packages/heterogeneous-agents/src/adapters/qoder.test.ts b/packages/heterogeneous-agents/src/adapters/qoder.test.tsindex c0bc4bfb0f1..4df3bf1e21d 100644--- a/packages/heterogeneous-agents/src/adapters/qoder.test.ts+++ b/packages/heterogeneous-agents/src/adapters/qoder.test.ts@@ -119,6 +119,70 @@ describe('QoderAdapter', () => {});});+ it('preserves Qoder WebSearch structured sources on tool_result and tool_end', () => {+ const adapter = new QoderAdapter();+ adapter.adapt({ subtype: 'init', type: 'system' });+ adapter.adapt({+ message: {+ content: [+ {+ id: 'web-search-1',+ input: { query: 'TradingView copper futures symbol ticker' },+ name: 'WebSearch',+ type: 'tool_use',+ },+ ],+ id: 'msg-search',+ },+ type: 'assistant',+ });++ const events = adapter.adapt({+ message: {+ content: [+ {+ content: 'Web search results for query: "TradingView copper futures symbol ticker"',+ tool_use_id: 'web-search-1',+ type: 'tool_result',+ },+ ],+ role: 'user',+ },+ tool_use_result: {+ durationSeconds: 2.938580792,+ query: 'TradingView copper futures symbol ticker',+ results: [+ {+ hostname: 'www.tradingview.com',+ link: 'https://www.tradingview.com/symbols/COMEX-HG1!/',+ snippet: 'The current price of Copper Futures is 6.7190 USD',+ title: 'HG1! Charts and Quotes - Futures',+ },+ ],+ },+ type: 'user',+ });++ const result = events.find((event) => event.type === 'tool_result');+ const end = events.find((event) => event.type === 'tool_end');+ expect(result?.data.pluginState).toEqual({+ durationSeconds: 2.938580792,+ query: 'TradingView copper futures symbol ticker',+ results: [+ {+ hostname: 'www.tradingview.com',+ link: 'https://www.tradingview.com/symbols/COMEX-HG1!/',+ snippet: 'The current price of Copper Futures is 6.7190 USD',+ title: 'HG1! Charts and Quotes - Futures',+ },+ ],+ });+ expect(end?.data).toMatchObject({+ payload: { toolCalling: { identifier: 'qoder' } },+ result: { state: result?.data.pluginState, success: true },+ });+ });+it('emits one structured Qoder auth error even though Qoder exits successfully', () => {const adapter = new QoderAdapter();adapter.adapt({ subtype: 'init', type: 'system' });