@librechat/agents 3.3.6 → 3.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/cjs/graphs/MultiAgentGraph.cjs +21 -4
  2. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  3. package/dist/cjs/main.cjs +2 -0
  4. package/dist/cjs/messages/format.cjs +124 -15
  5. package/dist/cjs/messages/format.cjs.map +1 -1
  6. package/dist/cjs/messages/injected.cjs +10 -1
  7. package/dist/cjs/messages/injected.cjs.map +1 -1
  8. package/dist/cjs/prompts/activityLabel.cjs +29 -1
  9. package/dist/cjs/prompts/activityLabel.cjs.map +1 -1
  10. package/dist/cjs/run.cjs +7 -2
  11. package/dist/cjs/run.cjs.map +1 -1
  12. package/dist/cjs/summarization/node.cjs +55 -0
  13. package/dist/cjs/summarization/node.cjs.map +1 -1
  14. package/dist/cjs/tools/intentArg.cjs +78 -52
  15. package/dist/cjs/tools/intentArg.cjs.map +1 -1
  16. package/dist/cjs/tools/search/tool.cjs +5 -5
  17. package/dist/cjs/tools/search/tool.cjs.map +1 -1
  18. package/dist/esm/graphs/MultiAgentGraph.mjs +21 -4
  19. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  20. package/dist/esm/main.mjs +2 -2
  21. package/dist/esm/messages/format.mjs +124 -15
  22. package/dist/esm/messages/format.mjs.map +1 -1
  23. package/dist/esm/messages/injected.mjs +10 -1
  24. package/dist/esm/messages/injected.mjs.map +1 -1
  25. package/dist/esm/prompts/activityLabel.mjs +29 -1
  26. package/dist/esm/prompts/activityLabel.mjs.map +1 -1
  27. package/dist/esm/run.mjs +7 -2
  28. package/dist/esm/run.mjs.map +1 -1
  29. package/dist/esm/summarization/node.mjs +55 -0
  30. package/dist/esm/summarization/node.mjs.map +1 -1
  31. package/dist/esm/tools/intentArg.mjs +77 -53
  32. package/dist/esm/tools/intentArg.mjs.map +1 -1
  33. package/dist/esm/tools/search/tool.mjs +5 -5
  34. package/dist/esm/tools/search/tool.mjs.map +1 -1
  35. package/dist/types/messages/format.d.ts +9 -8
  36. package/dist/types/prompts/activityLabel.d.ts +8 -1
  37. package/dist/types/run.d.ts +1 -1
  38. package/dist/types/tools/intentArg.d.ts +74 -12
  39. package/dist/types/tools/search/tool.d.ts +5 -5
  40. package/dist/types/types/activityLabel.d.ts +8 -0
  41. package/dist/types/types/stream.d.ts +27 -2
  42. package/package.json +1 -1
  43. package/src/graphs/MultiAgentGraph.ts +18 -4
  44. package/src/messages/format.ts +222 -50
  45. package/src/messages/formatAgentMessages.test.ts +308 -6
  46. package/src/messages/injected.test.ts +18 -1
  47. package/src/messages/injected.ts +8 -1
  48. package/src/prompts/activityLabel.ts +48 -0
  49. package/src/run.ts +10 -1
  50. package/src/specs/activity-label-prompt.test.ts +93 -0
  51. package/src/summarization/__tests__/node.test.ts +188 -0
  52. package/src/summarization/node.ts +67 -0
  53. package/src/tools/__tests__/intentArg.test.ts +101 -25
  54. package/src/tools/intentArg.ts +102 -68
  55. package/src/tools/search/outcome.test.ts +1 -1
  56. package/src/tools/search/tool.ts +5 -5
  57. package/src/types/activityLabel.ts +8 -0
  58. package/src/types/stream.ts +28 -2
@@ -1 +1 @@
1
- {"version":3,"file":"tool.mjs","names":["params"],"sources":["../../../../src/tools/search/tool.ts"],"sourcesContent":["import { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type { RunnableConfig } from '@langchain/core/runnables';\nimport type * as t from './types';\nimport {\n WebSearchToolDescription,\n WebSearchToolName,\n countrySchema,\n imagesSchema,\n videosSchema,\n querySchema,\n dateSchema,\n newsSchema,\n DATE_RANGE,\n} from './schema';\nimport { createSearchAPI, createSourceProcessor } from './search';\nimport { createKeenableScraper } from './keenable-scraper';\nimport { createSerperScraper } from './serper-scraper';\nimport { createTavilyScraper } from './tavily-scraper';\nimport { createFirecrawlScraper } from './firecrawl';\nimport { INTENT_PROPERTY } from '@/tools/intentArg';\nimport { createCrwScraper } from './crw-scraper';\nimport { expandHighlights } from './highlights';\nimport { formatResultsForLLM } from './format';\nimport { createDefaultLogger } from './utils';\nimport { createReranker } from './rerankers';\nimport { Constants } from '@/common';\n\n/**\n * Settled label for a `web_search` call's intent (see `intentArg.ts`).\n *\n * Counts the result kinds `formatResultsForLLM` actually renders —\n * `references` only tracks links embedded in extracted highlights, so it\n * undercounts ordinary results and can overcount when one highlight embeds\n * several links.\n *\n * A caught provider or processing failure is reported through `data.error`\n * while the tool still returns NORMALLY, so that case must author its own\n * label: the `ToolMessage` carries success status, and a bare intent would\n * otherwise settle mechanically from \"Searching…\" to \"Searched…\" and present\n * a failed search as a successful one.\n *\n * Returns undefined for a genuine zero-result search, leaving the host's\n * mechanical past-tense transform to label it.\n */\nexport function resolveSearchOutcome(\n data: t.SearchResultData,\n query: string\n): string | undefined {\n if (data.error != null && data.error !== '') {\n return `Search failed for \"${query}\"`;\n }\n const count =\n (data.organic?.length ?? 0) +\n (data.topStories?.length ?? 0) +\n (data.news?.length ?? 0) +\n (data.images?.length ?? 0) +\n (data.videos?.length ?? 0) +\n (data.places?.length ?? 0) +\n (data.peopleAlsoAsk?.length ?? 0) +\n (data.knowledgeGraph != null ? 1 : 0) +\n (data.answerBox != null ? 1 : 0);\n if (count === 0) {\n return undefined;\n }\n return `Found ${count} result${count === 1 ? '' : 's'} for \"${query}\"`;\n}\n\n/**\n * Executes parallel searches and merges the results,\n * deduplicating top stories by link\n */\nexport async function executeParallelSearches({\n searchAPI,\n query,\n date,\n country,\n safeSearch,\n images,\n videos,\n news,\n logger,\n}: {\n searchAPI: ReturnType<typeof createSearchAPI>;\n query: string;\n date?: DATE_RANGE;\n country?: string;\n safeSearch: t.SearchToolConfig['safeSearch'];\n images: boolean;\n videos: boolean;\n news: boolean;\n logger: t.Logger;\n}): Promise<t.SearchResult> {\n // Prepare all search tasks to run in parallel\n const searchTasks: Promise<t.SearchResult>[] = [\n // Main search\n searchAPI.getSources({\n query,\n date,\n country,\n safeSearch,\n }),\n ];\n\n if (images) {\n searchTasks.push(\n searchAPI\n .getSources({\n query,\n date,\n country,\n safeSearch,\n type: 'images',\n })\n .catch((error) => {\n logger.error('Error fetching images:', error);\n return {\n success: false,\n error: `Images search failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n })\n );\n }\n if (videos) {\n searchTasks.push(\n searchAPI\n .getSources({\n query,\n date,\n country,\n safeSearch,\n type: 'videos',\n })\n .catch((error) => {\n logger.error('Error fetching videos:', error);\n return {\n success: false,\n error: `Videos search failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n })\n );\n }\n if (news) {\n searchTasks.push(\n searchAPI\n .getSources({\n query,\n date,\n country,\n safeSearch,\n type: 'news',\n })\n .catch((error) => {\n logger.error('Error fetching news:', error);\n return {\n success: false,\n error: `News search failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n })\n );\n }\n\n // Run all searches in parallel\n const results = await Promise.all(searchTasks);\n\n // Get the main search result (first result)\n const mainResult = results[0];\n if (!mainResult.success) {\n throw new Error(mainResult.error ?? 'Search failed');\n }\n\n // Merge additional results with the main results\n const mergedResults = { ...mainResult.data };\n\n // Convert existing news to topStories if present\n if (mergedResults.news !== undefined && mergedResults.news.length > 0) {\n const existingNewsAsTopStories = mergedResults.news\n .filter((newsItem) => newsItem.link !== undefined && newsItem.link !== '')\n .map((newsItem) => ({\n title: newsItem.title ?? '',\n link: newsItem.link ?? '',\n source: newsItem.source ?? '',\n date: newsItem.date ?? '',\n imageUrl: newsItem.imageUrl ?? '',\n processed: false,\n }));\n mergedResults.topStories = [\n ...(mergedResults.topStories ?? []),\n ...existingNewsAsTopStories,\n ];\n delete mergedResults.news;\n }\n\n results.slice(1).forEach((result) => {\n if (result.success && result.data !== undefined) {\n if (result.data.images !== undefined && result.data.images.length > 0) {\n mergedResults.images = [\n ...(mergedResults.images ?? []),\n ...result.data.images,\n ];\n }\n if (result.data.videos !== undefined && result.data.videos.length > 0) {\n mergedResults.videos = [\n ...(mergedResults.videos ?? []),\n ...result.data.videos,\n ];\n }\n if (result.data.news !== undefined && result.data.news.length > 0) {\n const newsAsTopStories = result.data.news.map((newsItem) => ({\n ...newsItem,\n link: newsItem.link ?? '',\n }));\n mergedResults.topStories = [\n ...(mergedResults.topStories ?? []),\n ...newsAsTopStories,\n ];\n }\n }\n });\n\n if (\n mergedResults.topStories !== undefined &&\n mergedResults.topStories.length > 1\n ) {\n /** The main search's own news results and the parallel news sub-search\n * frequently return the same stories — keep the first occurrence of each\n * link so duplicates aren't scraped, reranked, and formatted repeatedly */\n const seenLinks = new Set<string>();\n mergedResults.topStories = mergedResults.topStories.filter((story) => {\n if (!story.link || seenLinks.has(story.link)) {\n return false;\n }\n seenLinks.add(story.link);\n return true;\n });\n }\n\n return { success: true, data: mergedResults };\n}\n\nfunction createSearchProcessor({\n searchAPI,\n safeSearch,\n supportsImages,\n supportsVideos,\n supportsNews,\n sourceProcessor,\n onGetHighlights,\n mainExpandBy,\n separatorExpandBy,\n logger,\n}: {\n safeSearch: t.SearchToolConfig['safeSearch'];\n supportsImages: boolean;\n supportsVideos: boolean;\n supportsNews: boolean;\n searchAPI: ReturnType<typeof createSearchAPI>;\n sourceProcessor: ReturnType<typeof createSourceProcessor>;\n onGetHighlights: t.SearchToolConfig['onGetHighlights'];\n mainExpandBy: t.SearchToolConfig['mainExpandBy'];\n separatorExpandBy: t.SearchToolConfig['separatorExpandBy'];\n logger: t.Logger;\n}) {\n return async function ({\n query,\n date,\n country,\n proMode = true,\n maxSources = 5,\n onSearchResults,\n images = false,\n videos = false,\n news = false,\n }: {\n query: string;\n country?: string;\n date?: DATE_RANGE;\n proMode?: boolean;\n maxSources?: number;\n onSearchResults: t.SearchToolConfig['onSearchResults'];\n images?: boolean;\n videos?: boolean;\n news?: boolean;\n }): Promise<t.SearchResultData> {\n try {\n // Execute parallel searches and merge results\n const searchResult = await executeParallelSearches({\n searchAPI,\n query,\n date,\n country,\n safeSearch,\n images: supportsImages && images,\n videos: supportsVideos && videos,\n news: supportsNews && news,\n logger,\n });\n\n onSearchResults?.(searchResult);\n\n const processedSources = await sourceProcessor.processSources({\n query,\n news,\n result: searchResult,\n proMode,\n onGetHighlights,\n numElements: maxSources,\n });\n\n return expandHighlights(\n processedSources,\n mainExpandBy,\n separatorExpandBy\n );\n } catch (error) {\n logger.error('Error in search:', error);\n return {\n organic: [],\n topStories: [],\n images: [],\n videos: [],\n news: [],\n relatedSearches: [],\n error: error instanceof Error ? error.message : String(error),\n };\n }\n };\n}\n\nfunction createOnSearchResults({\n runnableConfig,\n onSearchResults,\n}: {\n runnableConfig: RunnableConfig;\n onSearchResults: t.SearchToolConfig['onSearchResults'];\n}) {\n return function (results: t.SearchResult): void {\n if (!onSearchResults) {\n return;\n }\n onSearchResults(results, runnableConfig);\n };\n}\n\nfunction createTool({\n schema,\n search,\n maxOutputChars,\n onSearchResults: _onSearchResults,\n}: {\n schema: Record<string, unknown>;\n search: ReturnType<typeof createSearchProcessor>;\n maxOutputChars?: number;\n onSearchResults: t.SearchToolConfig['onSearchResults'];\n}): DynamicStructuredTool {\n return tool(\n async (rawParams, runnableConfig) => {\n const params = rawParams as SearchToolParams;\n const { query, date, country: _c, images, videos, news } = params;\n const country = typeof _c === 'string' && _c ? _c : undefined;\n const searchResult = await search({\n query,\n date,\n country,\n images,\n videos,\n news,\n onSearchResults: createOnSearchResults({\n runnableConfig,\n onSearchResults: _onSearchResults,\n }),\n });\n const turn = runnableConfig.toolCall?.turn ?? 0;\n const { output, references } = formatResultsForLLM(\n turn,\n searchResult,\n maxOutputChars\n );\n const data: t.SearchResultData = { turn, ...searchResult, references };\n const outcome = resolveSearchOutcome(data, query);\n return [\n output,\n { [Constants.WEB_SEARCH]: data, ...(outcome != null && { outcome }) },\n ];\n },\n {\n name: WebSearchToolName,\n description: WebSearchToolDescription,\n schema: schema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\n/**\n * Creates a search tool with configurable search and scraper providers.\n *\n * Search providers: Serper (Google results), SearXNG (self-hosted meta-search), Tavily (AI-optimized), fastCRW (Firecrawl-compatible, self-host or cloud).\n * Scraper providers: Firecrawl (default, full-featured), Serper (lightweight), Tavily (batch extraction), fastCRW (Firecrawl-compatible, self-host or cloud).\n *\n * The country schema field is exposed to the LLM for providers that support localized results.\n */\n/** Input params type for search tool */\ninterface SearchToolParams {\n query: string;\n date?: DATE_RANGE;\n country?: string;\n images?: boolean;\n videos?: boolean;\n news?: boolean;\n}\n\nexport const createSearchTool = (\n config: t.SearchToolConfig = {}\n): DynamicStructuredTool => {\n const {\n searchProvider = 'serper',\n serperApiKey,\n searxngInstanceUrl,\n searxngApiKey,\n tavilyApiKey,\n tavilySearchUrl,\n tavilyExtractUrl,\n tavilySearchOptions,\n keenableApiKey,\n keenableApiUrl,\n keenableSearchOptions,\n keenableScraperOptions,\n rerankerType = 'cohere',\n rerankerTimeout,\n topResults = 5,\n maxContentLength,\n chunkSize,\n chunkOverlap,\n mainExpandBy,\n separatorExpandBy,\n maxOutputChars,\n strategies = ['no_extraction'],\n filterContent = true,\n safeSearch = 1,\n scraperProvider = 'firecrawl',\n firecrawlApiKey,\n firecrawlApiUrl,\n firecrawlVersion,\n firecrawlOptions,\n serperScraperOptions,\n tavilyScraperOptions,\n crwApiKey,\n crwApiUrl,\n crwSearchOptions,\n crwScraperOptions,\n scraperTimeout,\n jinaApiKey,\n jinaApiUrl,\n cohereApiKey,\n onSearchResults: _onSearchResults,\n onGetHighlights,\n } = config;\n\n const logger = config.logger || createDefaultLogger();\n const effectiveTavilySearchOptions =\n searchProvider === 'tavily' && config.safeSearch != null\n ? {\n ...tavilySearchOptions,\n safeSearch: config.safeSearch !== 0,\n }\n : tavilySearchOptions;\n\n const schemaProperties: Record<string, unknown> = {\n intent: { ...INTENT_PROPERTY },\n query: querySchema,\n date: dateSchema,\n images: imagesSchema,\n videos: videosSchema,\n news: newsSchema,\n };\n\n if (searchProvider === 'serper' || searchProvider === 'tavily') {\n schemaProperties.country = countrySchema;\n }\n\n const toolSchema = {\n type: 'object',\n properties: schemaProperties,\n required: ['query'],\n };\n\n const searchAPI = createSearchAPI({\n searchProvider,\n serperApiKey,\n searxngInstanceUrl,\n searxngApiKey,\n tavilyApiKey,\n tavilySearchUrl,\n tavilySearchOptions: effectiveTavilySearchOptions,\n keenableApiKey,\n keenableApiUrl,\n keenableSearchOptions,\n crwApiKey,\n crwApiUrl,\n crwSearchOptions,\n });\n\n /** Create scraper based on scraperProvider */\n let scraperInstance: t.BaseScraper;\n\n if (scraperProvider === 'serper') {\n scraperInstance = createSerperScraper({\n ...serperScraperOptions,\n apiKey: serperApiKey,\n timeout: scraperTimeout ?? serperScraperOptions?.timeout,\n logger,\n });\n } else if (scraperProvider === 'tavily') {\n scraperInstance = createTavilyScraper({\n ...tavilyScraperOptions,\n apiKey:\n tavilyScraperOptions?.apiKey ??\n tavilyApiKey ??\n process.env.TAVILY_API_KEY,\n apiUrl: tavilyScraperOptions?.apiUrl ?? tavilyExtractUrl,\n timeout: scraperTimeout ?? tavilyScraperOptions?.timeout,\n logger,\n });\n } else if (scraperProvider === 'crw') {\n scraperInstance = createCrwScraper({\n ...crwScraperOptions,\n apiKey: crwScraperOptions?.apiKey ?? crwApiKey ?? process.env.CRW_API_KEY,\n apiUrl: crwScraperOptions?.apiUrl ?? crwApiUrl,\n timeout: scraperTimeout ?? crwScraperOptions?.timeout,\n formats: crwScraperOptions?.formats ?? ['markdown', 'rawHtml'],\n logger,\n });\n } else if (scraperProvider === 'keenable') {\n scraperInstance = createKeenableScraper({\n ...keenableScraperOptions,\n apiKey: keenableScraperOptions?.apiKey ?? keenableApiKey,\n timeout: scraperTimeout ?? keenableScraperOptions?.timeout,\n attributionTitle:\n keenableScraperOptions?.attributionTitle ??\n keenableSearchOptions?.attributionTitle,\n logger,\n });\n } else {\n scraperInstance = createFirecrawlScraper({\n ...firecrawlOptions,\n apiKey: firecrawlApiKey ?? process.env.FIRECRAWL_API_KEY,\n apiUrl: firecrawlApiUrl,\n version: firecrawlVersion,\n timeout: scraperTimeout ?? firecrawlOptions?.timeout,\n formats: firecrawlOptions?.formats ?? ['markdown', 'rawHtml'],\n logger,\n });\n }\n\n const selectedReranker = createReranker({\n rerankerType,\n jinaApiKey,\n jinaApiUrl,\n cohereApiKey,\n rerankerTimeout,\n logger,\n });\n\n if (!selectedReranker) {\n logger.warn('No reranker selected. Using default ranking.');\n }\n\n const sourceProcessor = createSourceProcessor(\n {\n reranker: selectedReranker,\n topResults,\n maxContentLength,\n chunkSize,\n chunkOverlap,\n strategies,\n filterContent,\n logger,\n },\n scraperInstance\n );\n\n const search = createSearchProcessor({\n searchAPI,\n safeSearch,\n // Keenable is organic-only: its API ignores `type`, so image/news\n // sub-searches would spend rate limit and merge nothing.\n supportsImages: searchProvider !== 'keenable',\n supportsVideos:\n searchProvider !== 'tavily' &&\n searchProvider !== 'keenable' &&\n searchProvider !== 'crw',\n supportsNews: searchProvider !== 'keenable',\n sourceProcessor,\n onGetHighlights,\n mainExpandBy,\n separatorExpandBy,\n logger,\n });\n\n return createTool({\n search,\n schema: toolSchema,\n maxOutputChars,\n onSearchResults: _onSearchResults,\n });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,SAAgB,qBACd,MACA,OACoB;CACpB,IAAI,KAAK,SAAS,QAAQ,KAAK,UAAU,IACvC,OAAO,sBAAsB,MAAM;CAErC,MAAM,SACH,KAAK,SAAS,UAAU,MACxB,KAAK,YAAY,UAAU,MAC3B,KAAK,MAAM,UAAU,MACrB,KAAK,QAAQ,UAAU,MACvB,KAAK,QAAQ,UAAU,MACvB,KAAK,QAAQ,UAAU,MACvB,KAAK,eAAe,UAAU,MAC9B,KAAK,kBAAkB,OAAO,IAAI,MAClC,KAAK,aAAa,OAAO,IAAI;CAChC,IAAI,UAAU,GACZ;CAEF,OAAO,SAAS,MAAM,SAAS,UAAU,IAAI,KAAK,IAAI,QAAQ,MAAM;AACtE;;;;;AAMA,eAAsB,wBAAwB,EAC5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,UACtB,gBACA,QAAQ,IAAI;EACd,QAAQ,sBAAsB,UAAU;EACxC,SAAS,kBAAkB,sBAAsB;EACjD;CACF,CAAC;MACI,IAAI,oBAAoB,OAC7B,kBAAkB,iBAAiB;EACjC,GAAG;EACH,QAAQ,mBAAmB,UAAU,aAAa,QAAQ,IAAI;EAC9D,QAAQ,mBAAmB,UAAU;EACrC,SAAS,kBAAkB,mBAAmB;EAC9C,SAAS,mBAAmB,WAAW,CAAC,YAAY,SAAS;EAC7D;CACF,CAAC;MACI,IAAI,oBAAoB,YAC7B,kBAAkB,sBAAsB;EACtC,GAAG;EACH,QAAQ,wBAAwB,UAAU;EAC1C,SAAS,kBAAkB,wBAAwB;EACnD,kBACE,wBAAwB,oBACxB,uBAAuB;EACzB;CACF,CAAC;MAED,kBAAkB,uBAAuB;EACvC,GAAG;EACH,QAAQ,mBAAmB,QAAQ,IAAI;EACvC,QAAQ;EACR,SAAS;EACT,SAAS,kBAAkB,kBAAkB;EAC7C,SAAS,kBAAkB,WAAW,CAAC,YAAY,SAAS;EAC5D;CACF,CAAC;CAGH,MAAM,mBAAmB,eAAe;EACtC;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;CAED,IAAI,CAAC,kBACH,OAAO,KAAK,8CAA8C;CAG5D,MAAM,kBAAkB,sBACtB;EACE,UAAU;EACV;EACA;EACA;EACA;EACA;EACA;EACA;CACF,GACA,eACF;CAoBA,OAAO,WAAW;EAChB,QAnBa,sBAAsB;GACnC;GACA;GAGA,gBAAgB,mBAAmB;GACnC,gBACE,mBAAmB,YACnB,mBAAmB,cACnB,mBAAmB;GACrB,cAAc,mBAAmB;GACjC;GACA;GACA;GACA;GACA;EACF,CAGO;EACL,QAAQ;EACR;EACA,iBAAiB;CACnB,CAAC;AACH"}
1
+ {"version":3,"file":"tool.mjs","names":["params"],"sources":["../../../../src/tools/search/tool.ts"],"sourcesContent":["import { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type { RunnableConfig } from '@langchain/core/runnables';\nimport type * as t from './types';\nimport {\n WebSearchToolDescription,\n WebSearchToolName,\n countrySchema,\n imagesSchema,\n videosSchema,\n querySchema,\n dateSchema,\n newsSchema,\n DATE_RANGE,\n} from './schema';\nimport { createSearchAPI, createSourceProcessor } from './search';\nimport { createKeenableScraper } from './keenable-scraper';\nimport { createSerperScraper } from './serper-scraper';\nimport { createTavilyScraper } from './tavily-scraper';\nimport { createFirecrawlScraper } from './firecrawl';\nimport { INTENT_PROPERTY } from '@/tools/intentArg';\nimport { createCrwScraper } from './crw-scraper';\nimport { expandHighlights } from './highlights';\nimport { formatResultsForLLM } from './format';\nimport { createDefaultLogger } from './utils';\nimport { createReranker } from './rerankers';\nimport { Constants } from '@/common';\n\n/**\n * Settled label for a `web_search` call's intent (see `intentArg.ts`).\n *\n * Counts the result kinds `formatResultsForLLM` actually renders —\n * `references` only tracks links embedded in extracted highlights, so it\n * undercounts ordinary results and can overcount when one highlight embeds\n * several links.\n *\n * A caught provider or processing failure is reported through `data.error`\n * while the tool still returns NORMALLY, so that case must author its own\n * label: the `ToolMessage` carries success status, so without an authored\n * outcome the in-flight intent (\"Searching…\") would stand as the settled\n * label and present a failed search as an ordinary one.\n *\n * Returns undefined for a genuine zero-result search, leaving the\n * model-authored intent to stand unchanged as the label.\n */\nexport function resolveSearchOutcome(\n data: t.SearchResultData,\n query: string\n): string | undefined {\n if (data.error != null && data.error !== '') {\n return `Search failed for \"${query}\"`;\n }\n const count =\n (data.organic?.length ?? 0) +\n (data.topStories?.length ?? 0) +\n (data.news?.length ?? 0) +\n (data.images?.length ?? 0) +\n (data.videos?.length ?? 0) +\n (data.places?.length ?? 0) +\n (data.peopleAlsoAsk?.length ?? 0) +\n (data.knowledgeGraph != null ? 1 : 0) +\n (data.answerBox != null ? 1 : 0);\n if (count === 0) {\n return undefined;\n }\n return `Found ${count} result${count === 1 ? '' : 's'} for \"${query}\"`;\n}\n\n/**\n * Executes parallel searches and merges the results,\n * deduplicating top stories by link\n */\nexport async function executeParallelSearches({\n searchAPI,\n query,\n date,\n country,\n safeSearch,\n images,\n videos,\n news,\n logger,\n}: {\n searchAPI: ReturnType<typeof createSearchAPI>;\n query: string;\n date?: DATE_RANGE;\n country?: string;\n safeSearch: t.SearchToolConfig['safeSearch'];\n images: boolean;\n videos: boolean;\n news: boolean;\n logger: t.Logger;\n}): Promise<t.SearchResult> {\n // Prepare all search tasks to run in parallel\n const searchTasks: Promise<t.SearchResult>[] = [\n // Main search\n searchAPI.getSources({\n query,\n date,\n country,\n safeSearch,\n }),\n ];\n\n if (images) {\n searchTasks.push(\n searchAPI\n .getSources({\n query,\n date,\n country,\n safeSearch,\n type: 'images',\n })\n .catch((error) => {\n logger.error('Error fetching images:', error);\n return {\n success: false,\n error: `Images search failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n })\n );\n }\n if (videos) {\n searchTasks.push(\n searchAPI\n .getSources({\n query,\n date,\n country,\n safeSearch,\n type: 'videos',\n })\n .catch((error) => {\n logger.error('Error fetching videos:', error);\n return {\n success: false,\n error: `Videos search failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n })\n );\n }\n if (news) {\n searchTasks.push(\n searchAPI\n .getSources({\n query,\n date,\n country,\n safeSearch,\n type: 'news',\n })\n .catch((error) => {\n logger.error('Error fetching news:', error);\n return {\n success: false,\n error: `News search failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n })\n );\n }\n\n // Run all searches in parallel\n const results = await Promise.all(searchTasks);\n\n // Get the main search result (first result)\n const mainResult = results[0];\n if (!mainResult.success) {\n throw new Error(mainResult.error ?? 'Search failed');\n }\n\n // Merge additional results with the main results\n const mergedResults = { ...mainResult.data };\n\n // Convert existing news to topStories if present\n if (mergedResults.news !== undefined && mergedResults.news.length > 0) {\n const existingNewsAsTopStories = mergedResults.news\n .filter((newsItem) => newsItem.link !== undefined && newsItem.link !== '')\n .map((newsItem) => ({\n title: newsItem.title ?? '',\n link: newsItem.link ?? '',\n source: newsItem.source ?? '',\n date: newsItem.date ?? '',\n imageUrl: newsItem.imageUrl ?? '',\n processed: false,\n }));\n mergedResults.topStories = [\n ...(mergedResults.topStories ?? []),\n ...existingNewsAsTopStories,\n ];\n delete mergedResults.news;\n }\n\n results.slice(1).forEach((result) => {\n if (result.success && result.data !== undefined) {\n if (result.data.images !== undefined && result.data.images.length > 0) {\n mergedResults.images = [\n ...(mergedResults.images ?? []),\n ...result.data.images,\n ];\n }\n if (result.data.videos !== undefined && result.data.videos.length > 0) {\n mergedResults.videos = [\n ...(mergedResults.videos ?? []),\n ...result.data.videos,\n ];\n }\n if (result.data.news !== undefined && result.data.news.length > 0) {\n const newsAsTopStories = result.data.news.map((newsItem) => ({\n ...newsItem,\n link: newsItem.link ?? '',\n }));\n mergedResults.topStories = [\n ...(mergedResults.topStories ?? []),\n ...newsAsTopStories,\n ];\n }\n }\n });\n\n if (\n mergedResults.topStories !== undefined &&\n mergedResults.topStories.length > 1\n ) {\n /** The main search's own news results and the parallel news sub-search\n * frequently return the same stories — keep the first occurrence of each\n * link so duplicates aren't scraped, reranked, and formatted repeatedly */\n const seenLinks = new Set<string>();\n mergedResults.topStories = mergedResults.topStories.filter((story) => {\n if (!story.link || seenLinks.has(story.link)) {\n return false;\n }\n seenLinks.add(story.link);\n return true;\n });\n }\n\n return { success: true, data: mergedResults };\n}\n\nfunction createSearchProcessor({\n searchAPI,\n safeSearch,\n supportsImages,\n supportsVideos,\n supportsNews,\n sourceProcessor,\n onGetHighlights,\n mainExpandBy,\n separatorExpandBy,\n logger,\n}: {\n safeSearch: t.SearchToolConfig['safeSearch'];\n supportsImages: boolean;\n supportsVideos: boolean;\n supportsNews: boolean;\n searchAPI: ReturnType<typeof createSearchAPI>;\n sourceProcessor: ReturnType<typeof createSourceProcessor>;\n onGetHighlights: t.SearchToolConfig['onGetHighlights'];\n mainExpandBy: t.SearchToolConfig['mainExpandBy'];\n separatorExpandBy: t.SearchToolConfig['separatorExpandBy'];\n logger: t.Logger;\n}) {\n return async function ({\n query,\n date,\n country,\n proMode = true,\n maxSources = 5,\n onSearchResults,\n images = false,\n videos = false,\n news = false,\n }: {\n query: string;\n country?: string;\n date?: DATE_RANGE;\n proMode?: boolean;\n maxSources?: number;\n onSearchResults: t.SearchToolConfig['onSearchResults'];\n images?: boolean;\n videos?: boolean;\n news?: boolean;\n }): Promise<t.SearchResultData> {\n try {\n // Execute parallel searches and merge results\n const searchResult = await executeParallelSearches({\n searchAPI,\n query,\n date,\n country,\n safeSearch,\n images: supportsImages && images,\n videos: supportsVideos && videos,\n news: supportsNews && news,\n logger,\n });\n\n onSearchResults?.(searchResult);\n\n const processedSources = await sourceProcessor.processSources({\n query,\n news,\n result: searchResult,\n proMode,\n onGetHighlights,\n numElements: maxSources,\n });\n\n return expandHighlights(\n processedSources,\n mainExpandBy,\n separatorExpandBy\n );\n } catch (error) {\n logger.error('Error in search:', error);\n return {\n organic: [],\n topStories: [],\n images: [],\n videos: [],\n news: [],\n relatedSearches: [],\n error: error instanceof Error ? error.message : String(error),\n };\n }\n };\n}\n\nfunction createOnSearchResults({\n runnableConfig,\n onSearchResults,\n}: {\n runnableConfig: RunnableConfig;\n onSearchResults: t.SearchToolConfig['onSearchResults'];\n}) {\n return function (results: t.SearchResult): void {\n if (!onSearchResults) {\n return;\n }\n onSearchResults(results, runnableConfig);\n };\n}\n\nfunction createTool({\n schema,\n search,\n maxOutputChars,\n onSearchResults: _onSearchResults,\n}: {\n schema: Record<string, unknown>;\n search: ReturnType<typeof createSearchProcessor>;\n maxOutputChars?: number;\n onSearchResults: t.SearchToolConfig['onSearchResults'];\n}): DynamicStructuredTool {\n return tool(\n async (rawParams, runnableConfig) => {\n const params = rawParams as SearchToolParams;\n const { query, date, country: _c, images, videos, news } = params;\n const country = typeof _c === 'string' && _c ? _c : undefined;\n const searchResult = await search({\n query,\n date,\n country,\n images,\n videos,\n news,\n onSearchResults: createOnSearchResults({\n runnableConfig,\n onSearchResults: _onSearchResults,\n }),\n });\n const turn = runnableConfig.toolCall?.turn ?? 0;\n const { output, references } = formatResultsForLLM(\n turn,\n searchResult,\n maxOutputChars\n );\n const data: t.SearchResultData = { turn, ...searchResult, references };\n const outcome = resolveSearchOutcome(data, query);\n return [\n output,\n { [Constants.WEB_SEARCH]: data, ...(outcome != null && { outcome }) },\n ];\n },\n {\n name: WebSearchToolName,\n description: WebSearchToolDescription,\n schema: schema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\n/**\n * Creates a search tool with configurable search and scraper providers.\n *\n * Search providers: Serper (Google results), SearXNG (self-hosted meta-search), Tavily (AI-optimized), fastCRW (Firecrawl-compatible, self-host or cloud).\n * Scraper providers: Firecrawl (default, full-featured), Serper (lightweight), Tavily (batch extraction), fastCRW (Firecrawl-compatible, self-host or cloud).\n *\n * The country schema field is exposed to the LLM for providers that support localized results.\n */\n/** Input params type for search tool */\ninterface SearchToolParams {\n query: string;\n date?: DATE_RANGE;\n country?: string;\n images?: boolean;\n videos?: boolean;\n news?: boolean;\n}\n\nexport const createSearchTool = (\n config: t.SearchToolConfig = {}\n): DynamicStructuredTool => {\n const {\n searchProvider = 'serper',\n serperApiKey,\n searxngInstanceUrl,\n searxngApiKey,\n tavilyApiKey,\n tavilySearchUrl,\n tavilyExtractUrl,\n tavilySearchOptions,\n keenableApiKey,\n keenableApiUrl,\n keenableSearchOptions,\n keenableScraperOptions,\n rerankerType = 'cohere',\n rerankerTimeout,\n topResults = 5,\n maxContentLength,\n chunkSize,\n chunkOverlap,\n mainExpandBy,\n separatorExpandBy,\n maxOutputChars,\n strategies = ['no_extraction'],\n filterContent = true,\n safeSearch = 1,\n scraperProvider = 'firecrawl',\n firecrawlApiKey,\n firecrawlApiUrl,\n firecrawlVersion,\n firecrawlOptions,\n serperScraperOptions,\n tavilyScraperOptions,\n crwApiKey,\n crwApiUrl,\n crwSearchOptions,\n crwScraperOptions,\n scraperTimeout,\n jinaApiKey,\n jinaApiUrl,\n cohereApiKey,\n onSearchResults: _onSearchResults,\n onGetHighlights,\n } = config;\n\n const logger = config.logger || createDefaultLogger();\n const effectiveTavilySearchOptions =\n searchProvider === 'tavily' && config.safeSearch != null\n ? {\n ...tavilySearchOptions,\n safeSearch: config.safeSearch !== 0,\n }\n : tavilySearchOptions;\n\n const schemaProperties: Record<string, unknown> = {\n intent: { ...INTENT_PROPERTY },\n query: querySchema,\n date: dateSchema,\n images: imagesSchema,\n videos: videosSchema,\n news: newsSchema,\n };\n\n if (searchProvider === 'serper' || searchProvider === 'tavily') {\n schemaProperties.country = countrySchema;\n }\n\n const toolSchema = {\n type: 'object',\n properties: schemaProperties,\n required: ['query'],\n };\n\n const searchAPI = createSearchAPI({\n searchProvider,\n serperApiKey,\n searxngInstanceUrl,\n searxngApiKey,\n tavilyApiKey,\n tavilySearchUrl,\n tavilySearchOptions: effectiveTavilySearchOptions,\n keenableApiKey,\n keenableApiUrl,\n keenableSearchOptions,\n crwApiKey,\n crwApiUrl,\n crwSearchOptions,\n });\n\n /** Create scraper based on scraperProvider */\n let scraperInstance: t.BaseScraper;\n\n if (scraperProvider === 'serper') {\n scraperInstance = createSerperScraper({\n ...serperScraperOptions,\n apiKey: serperApiKey,\n timeout: scraperTimeout ?? serperScraperOptions?.timeout,\n logger,\n });\n } else if (scraperProvider === 'tavily') {\n scraperInstance = createTavilyScraper({\n ...tavilyScraperOptions,\n apiKey:\n tavilyScraperOptions?.apiKey ??\n tavilyApiKey ??\n process.env.TAVILY_API_KEY,\n apiUrl: tavilyScraperOptions?.apiUrl ?? tavilyExtractUrl,\n timeout: scraperTimeout ?? tavilyScraperOptions?.timeout,\n logger,\n });\n } else if (scraperProvider === 'crw') {\n scraperInstance = createCrwScraper({\n ...crwScraperOptions,\n apiKey: crwScraperOptions?.apiKey ?? crwApiKey ?? process.env.CRW_API_KEY,\n apiUrl: crwScraperOptions?.apiUrl ?? crwApiUrl,\n timeout: scraperTimeout ?? crwScraperOptions?.timeout,\n formats: crwScraperOptions?.formats ?? ['markdown', 'rawHtml'],\n logger,\n });\n } else if (scraperProvider === 'keenable') {\n scraperInstance = createKeenableScraper({\n ...keenableScraperOptions,\n apiKey: keenableScraperOptions?.apiKey ?? keenableApiKey,\n timeout: scraperTimeout ?? keenableScraperOptions?.timeout,\n attributionTitle:\n keenableScraperOptions?.attributionTitle ??\n keenableSearchOptions?.attributionTitle,\n logger,\n });\n } else {\n scraperInstance = createFirecrawlScraper({\n ...firecrawlOptions,\n apiKey: firecrawlApiKey ?? process.env.FIRECRAWL_API_KEY,\n apiUrl: firecrawlApiUrl,\n version: firecrawlVersion,\n timeout: scraperTimeout ?? firecrawlOptions?.timeout,\n formats: firecrawlOptions?.formats ?? ['markdown', 'rawHtml'],\n logger,\n });\n }\n\n const selectedReranker = createReranker({\n rerankerType,\n jinaApiKey,\n jinaApiUrl,\n cohereApiKey,\n rerankerTimeout,\n logger,\n });\n\n if (!selectedReranker) {\n logger.warn('No reranker selected. Using default ranking.');\n }\n\n const sourceProcessor = createSourceProcessor(\n {\n reranker: selectedReranker,\n topResults,\n maxContentLength,\n chunkSize,\n chunkOverlap,\n strategies,\n filterContent,\n logger,\n },\n scraperInstance\n );\n\n const search = createSearchProcessor({\n searchAPI,\n safeSearch,\n // Keenable is organic-only: its API ignores `type`, so image/news\n // sub-searches would spend rate limit and merge nothing.\n supportsImages: searchProvider !== 'keenable',\n supportsVideos:\n searchProvider !== 'tavily' &&\n searchProvider !== 'keenable' &&\n searchProvider !== 'crw',\n supportsNews: searchProvider !== 'keenable',\n sourceProcessor,\n onGetHighlights,\n mainExpandBy,\n separatorExpandBy,\n logger,\n });\n\n return createTool({\n search,\n schema: toolSchema,\n maxOutputChars,\n onSearchResults: _onSearchResults,\n });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,SAAgB,qBACd,MACA,OACoB;CACpB,IAAI,KAAK,SAAS,QAAQ,KAAK,UAAU,IACvC,OAAO,sBAAsB,MAAM;CAErC,MAAM,SACH,KAAK,SAAS,UAAU,MACxB,KAAK,YAAY,UA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nC;GACA;GAGA,gBAAgB,mBAAmB;GACnC,gBACE,mBAAmB,YACnB,mBAAmB,cACnB,mBAAmB;GACrB,cAAc,mBAAmB;GACjC;GACA;GACA;GACA;GACA;EACF,CAGO;EACL,QAAQ;EACR;EACA,iBAAiB;CACnB,CAAC;AACH"}
@@ -114,6 +114,12 @@ interface FormatAgentMessagesOptions {
114
114
  export declare const labelContentByAgent: (contentParts: MessageContentComplex[], agentIdMap?: Record<number, string>, agentNames?: Record<string, string>, options?: {
115
115
  labelNonTransferContent?: boolean;
116
116
  }) => MessageContentComplex[];
117
+ type SummaryTokenAdjustment = {
118
+ original: number;
119
+ adjusted: number;
120
+ remainingChars: number;
121
+ totalChars: number;
122
+ };
117
123
  /**
118
124
  * Formats an array of messages for LangChain, handling tool calls and creating ToolMessage instances.
119
125
  *
@@ -133,14 +139,9 @@ export declare const formatAgentMessages: (payload: TPayload, indexTokenCountMap
133
139
  text: string;
134
140
  tokenCount: number;
135
141
  };
136
- /** When a summary boundary sliced content from a message, the token count
137
- * was proportionally reduced. Returned so the caller can log it. */
138
- boundaryTokenAdjustment?: {
139
- original: number;
140
- adjusted: number;
141
- remainingChars: number;
142
- totalChars: number;
143
- };
142
+ /** When a positional summary boundary sliced content from a message, the token
143
+ * count was proportionally reduced. Returned so the caller can log it. */
144
+ boundaryTokenAdjustment?: SummaryTokenAdjustment;
144
145
  };
145
146
  /**
146
147
  * Adds a value at key 0 for system messages and shifts all key indices by one in an indexTokenCountMap.
@@ -16,6 +16,13 @@ export type BuildActivityLabelPromptParams = {
16
16
  charLimit: number;
17
17
  thinkingExcerpts?: string[];
18
18
  lastAssistantText?: string;
19
+ /**
20
+ * Headers already committed for earlier batches in this run, in run order
21
+ * with the most recent last. Rendered ahead of the block context so the
22
+ * label continues the run's story instead of restating a line the user is
23
+ * already reading. Capped at {@link MAX_PREVIOUS_LABELS}.
24
+ */
25
+ previousLabels?: string[];
19
26
  /**
20
27
  * Resolved tool-output tracing policy. The label prompt becomes Langfuse
21
28
  * generation input, so outputs/errors excluded from tracing (global
@@ -28,4 +35,4 @@ export type BuildActivityLabelPromptParams = {
28
35
  * Builds the user prompt for a fast-model activity label. Pure — exported
29
36
  * for direct testing of redaction and truncation behavior.
30
37
  */
31
- export declare function buildActivityLabelPrompt({ entries, charLimit, thinkingExcerpts, lastAssistantText, redaction, }: BuildActivityLabelPromptParams): string;
38
+ export declare function buildActivityLabelPrompt({ entries, charLimit, thinkingExcerpts, lastAssistantText, previousLabels, redaction, }: BuildActivityLabelPromptParams): string;
@@ -227,7 +227,7 @@ export declare class Run<_T extends t.BaseGraphState> {
227
227
  * comes from `lastAssistantText`, content from reasoning excerpts and
228
228
  * tool entries.
229
229
  */
230
- generateActivityLabel({ provider, clientOptions, entries, thinkingExcerpts, lastAssistantText, prompt, charLimit, chainOptions, traceSeed, agentId, }: t.RunActivityLabelOptions): Promise<{
230
+ generateActivityLabel({ provider, clientOptions, entries, thinkingExcerpts, lastAssistantText, previousLabels, prompt, charLimit, chainOptions, traceSeed, agentId, }: t.RunActivityLabelOptions): Promise<{
231
231
  label?: string;
232
232
  }>;
233
233
  }
@@ -8,8 +8,9 @@
8
8
  * args, so a host UI can render it as the call's live status label before the
9
9
  * rest of the args exist. When the call settles, {@link applyOutcome} edits
10
10
  * the sentence in place into its outcome form — a tool-supplied replacement
11
- * (`outcome`), a tool-supplied span edit (`outcome_patch`), or a mechanical
12
- * present-progressive→past-tense transform of the leading verb.
11
+ * (`outcome`) or a tool-supplied span edit (`outcome_patch`). Absent either,
12
+ * the label is left exactly as the model wrote it: completion is a UI state
13
+ * (the shimmer stopping, the icon settling), not a tense change.
13
14
  *
14
15
  * The arg is always optional (never listed in `required`): the same schemas
15
16
  * are callable from programmatic tool calling, where no UI renders a label
@@ -20,7 +21,28 @@
20
21
  import type { JsonSchemaType, OutcomePatch } from '@/types';
21
22
  /** Argument carrying the model-authored label for a tool call. */
22
23
  export declare const INTENT_ARG = "intent";
23
- /** Model-facing instruction for the injected `intent` property. */
24
+ /**
25
+ * Opening words of {@link INTENT_DESCRIPTION}, and the discriminator that
26
+ * tells the injected LABEL apart from a tool's own business parameter that
27
+ * merely shares the name `intent`.
28
+ *
29
+ * Exported because host applications reimplement the same strip/sanitize
30
+ * passes and would otherwise duplicate this as a string literal: if the two
31
+ * copies drift, the host silently stops recognizing SDK-native labels and
32
+ * fails OPEN (labels stay in schemas, opt-outs stop working) with no error.
33
+ * Any edit to the description must preserve this prefix verbatim.
34
+ */
35
+ export declare const INTENT_LABEL_MARKER = "ALWAYS write this field FIRST";
36
+ /**
37
+ * Model-facing instruction for the injected `intent` property.
38
+ *
39
+ * Deliberately terse — it is repeated on every opted-in tool schema, on every
40
+ * request, so each sentence is paid for many times over. What remains is
41
+ * load-bearing: first-position placement (the entire streaming mechanism),
42
+ * the one-sentence present-progressive form, who reads it, and the sibling
43
+ * rule, without which models emit identical labels for parallel calls to one
44
+ * tool and defeat the feature's headline case.
45
+ */
24
46
  export declare const INTENT_DESCRIPTION: string;
25
47
  /**
26
48
  * Canonical (frozen) shape of the injected property. Always embed a COPY
@@ -37,6 +59,35 @@ export declare const INTENT_PROPERTY: JsonSchemaType;
37
59
  * parameter the tool actually needs.
38
60
  */
39
61
  export declare function isIntentLabelProperty(property: unknown): boolean;
62
+ /**
63
+ * Schema shape accepted by {@link withoutIntent}.
64
+ *
65
+ * `required` is widened to `readonly string[]` because the SDK's own native
66
+ * schemas are declared `as const` — their `required` is a readonly tuple, and
67
+ * a mutable `string[]` parameter would reject the very schemas this helper
68
+ * exists for (TS2345), forcing embedders to cast to use the advertised API.
69
+ */
70
+ export type IntentStrippableSchema = Omit<JsonSchemaType, 'required'> & {
71
+ required?: readonly string[];
72
+ };
73
+ /**
74
+ * Returns a copy of `parameters` without the injected intent LABEL — the
75
+ * opt-out for consumers that render no status label and should not pay for
76
+ * the property.
77
+ *
78
+ * The SDK's native schemas carry the label unconditionally, so without this
79
+ * an embedder has no lever at all: `withIntent` is applied at module scope.
80
+ * Marker-guarded, so a tool's own business parameter named `intent` is never
81
+ * removed. Returns the input unchanged when there is nothing to strip.
82
+ *
83
+ * `required` is pruned alongside the property: a schema that lists `intent`
84
+ * as required (strict-mode normalization does exactly that, since OpenAI
85
+ * strict function schemas require every property to appear in `required`)
86
+ * would otherwise be left naming a property it no longer declares, which is
87
+ * invalid JSON Schema and gets rejected by the provider instead of quietly
88
+ * opting out.
89
+ */
90
+ export declare function withoutIntent(parameters?: IntentStrippableSchema): JsonSchemaType | undefined;
40
91
  /**
41
92
  * Returns a copy of the parameters schema with `intent` prepended as the
42
93
  * FIRST property (object key order is insertion order and every provider
@@ -63,8 +114,18 @@ export declare function stripIntent(args: unknown): unknown;
63
114
  * 1. `outcome` — full replacement authored by the tool.
64
115
  * 2. `outcome_patch` — first occurrence of `from` in the intent replaced
65
116
  * with `to` (case-sensitive); no-op when `from` is absent or empty.
66
- * 3. Mechanical transform — the leading word mapped present-progressive →
67
- * past tense; an unknown leading word leaves the intent unchanged.
117
+ * 3. Otherwise the intent is returned UNCHANGED.
118
+ *
119
+ * There is deliberately no mechanical present-progressive→past-tense rewrite.
120
+ * Such a transform can only be a closed list of English verbs, which makes it
121
+ * wrong in three ways at once: it never fires for the non-English labels this
122
+ * feature expects (the model answers in the user's language), it fires for
123
+ * some sibling calls and not others inside one group — "Searched…" beside
124
+ * "Recording…" — and it quietly enumerates a vocabulary in a feature whose
125
+ * premise is that the sentence is free-form. Completion is conveyed by UI
126
+ * state (the shimmer stopping, the icon settling), which is language-neutral
127
+ * and always consistent; a tool that wants past tense says so explicitly via
128
+ * `outcome` or `outcome_patch`.
68
129
  *
69
130
  * Returns undefined when there is neither an intent nor an outcome, so
70
131
  * callers fall back to their default label. Pure and dependency-free — host
@@ -77,15 +138,16 @@ export declare function applyOutcome(intent: string | undefined, result?: {
77
138
  /**
78
139
  * Resolves the settled label to emit on a completion event: only when the
79
140
  * tool actually authored `outcome`/`outcome_patch` fields. Returns undefined
80
- * otherwise the mechanical transform of a bare intent is left to the host
81
- * so the wire never carries a label the host can derive itself. The result
82
- * is collapsed to a bounded single line before emission.
141
+ * otherwise, so the wire never carries a label the host already has a bare
142
+ * intent needs no settled form, because it is displayed unchanged and the UI
143
+ * conveys completion through its own state. Hosts must NOT rewrite it (see
144
+ * {@link applyOutcome} for why a tense transform is deliberately absent). The
145
+ * result is collapsed to a bounded single line before emission.
83
146
  *
84
147
  * For failed calls (`isError`), only tool-AUTHORED text may label the call:
85
- * an explicit `outcome`, or a patch whose `from` actually matches the
86
- * intent. An unmatched patch must not fall through to the mechanical
87
- * past-tense transform wording drift in a failure patch would otherwise
88
- * render a success-looking label for an error.
148
+ * an explicit `outcome`, or a patch whose `from` actually matches the intent.
149
+ * An unmatched patch resolves to undefined rather than silently reusing the
150
+ * in-flight intent, so a failure is never labelled as though it succeeded.
89
151
  */
90
152
  export declare function resolveToolOutcome(args: unknown, fields?: {
91
153
  outcome?: string;
@@ -12,12 +12,12 @@ import { createSearchAPI } from './search';
12
12
  *
13
13
  * A caught provider or processing failure is reported through `data.error`
14
14
  * while the tool still returns NORMALLY, so that case must author its own
15
- * label: the `ToolMessage` carries success status, and a bare intent would
16
- * otherwise settle mechanically from "Searching…" to "Searched…" and present
17
- * a failed search as a successful one.
15
+ * label: the `ToolMessage` carries success status, so without an authored
16
+ * outcome the in-flight intent ("Searching…") would stand as the settled
17
+ * label and present a failed search as an ordinary one.
18
18
  *
19
- * Returns undefined for a genuine zero-result search, leaving the host's
20
- * mechanical past-tense transform to label it.
19
+ * Returns undefined for a genuine zero-result search, leaving the
20
+ * model-authored intent to stand unchanged as the label.
21
21
  */
22
22
  export declare function resolveSearchOutcome(data: t.SearchResultData, query: string): string | undefined;
23
23
  /**
@@ -36,6 +36,14 @@ export type RunActivityLabelOptions = {
36
36
  thinkingExcerpts?: string[];
37
37
  /** Assistant's last text before the block (~200 chars), as intent context. */
38
38
  lastAssistantText?: string;
39
+ /**
40
+ * Headers already committed for earlier batches in this run (run order,
41
+ * most recent last). Continuity context: the prompt shows them so the new
42
+ * header extends the run's story instead of restating a line already on
43
+ * screen. Hosts should pass only COMMITTED labels — a pending slot's text
44
+ * is empty and a dropped fill never surfaced to the user.
45
+ */
46
+ previousLabels?: string[];
39
47
  /** Override for the default label system prompt. */
40
48
  prompt?: string;
41
49
  /** Per-entry serialization cap for the prompt. Default 600. */
@@ -101,8 +101,14 @@ export type ProcessedToolCall = {
101
101
  /**
102
102
  * Settled label for the call, resolved from the tool-supplied
103
103
  * `outcome`/`outcome_patch` result fields against the model-authored
104
- * `intent` arg. Only present when the tool authored one — hosts apply
105
- * the mechanical intent transform themselves when absent.
104
+ * `intent` arg. Present ONLY when the tool authored one.
105
+ *
106
+ * When absent, display the `intent` arg unchanged — do NOT rewrite its
107
+ * tense. A gerund→past-tense rewrite can only be a closed list of English
108
+ * verbs, so it never fires for the non-English labels this feature expects
109
+ * and fires for some sibling calls but not others within one group.
110
+ * Completion belongs to UI state (the shimmer stopping, the icon settling),
111
+ * which is language-neutral and always consistent.
106
112
  */
107
113
  outcome?: string;
108
114
  };
@@ -227,10 +233,29 @@ export type SummaryBoundary = {
227
233
  messageId: string;
228
234
  contentIndex: number;
229
235
  };
236
+ /**
237
+ * Semantic extent of a summary: the first source message compaction retained
238
+ * verbatim, meaning everything before it is covered. Distinct from `boundary`,
239
+ * which records where the block was emitted — a retained recency tail sits
240
+ * *before* the block's own position, so position alone cannot say what the
241
+ * summary replaced.
242
+ *
243
+ * Anchored to the retained side rather than the covered side so that a source
244
+ * message expanding into several messages (a steer splits an assistant entry
245
+ * into pre-steer, steer, and post-steer entries sharing one ID) stays whole:
246
+ * such a message is the retained anchor and survives intact.
247
+ */
248
+ export type SummaryCoverage = {
249
+ retainedFromMessageId: string;
250
+ };
230
251
  export type SummaryContentBlock = {
231
252
  type: ContentTypes.SUMMARY;
232
253
  content?: MessageContentComplex[];
254
+ /** Injection budget: provider output-token space when usage was reported, plus
255
+ * the wrapper added at injection time. Not comparable with per-message counts
256
+ * such as `indexTokenCountMap`, which are in the consumer's own tokenizer. */
233
257
  tokenCount?: number;
258
+ coverage?: SummaryCoverage;
234
259
  boundary?: SummaryBoundary;
235
260
  summaryVersion?: number;
236
261
  model?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@librechat/agents",
3
- "version": "3.3.6",
3
+ "version": "3.3.8",
4
4
  "main": "./dist/cjs/main.cjs",
5
5
  "module": "./dist/esm/main.mjs",
6
6
  "types": "./dist/types/index.d.ts",
@@ -27,6 +27,20 @@ import { Constants } from '@/common';
27
27
  const HANDOFF_INSTRUCTIONS_PATTERN = /(?:Instructions?|Context):\s*(.+)/is;
28
28
  const HANDOFF_INSTRUCTIONS_KEY = 'handoff_instructions';
29
29
 
30
+ /**
31
+ * Handoff and fan-in prompts that route work between agents. Built in-run and
32
+ * never persisted as standalone payload entries, so they are marked synthetic:
33
+ * `messagesStateReducer` would otherwise give them a plain UUID and downstream
34
+ * consumers — compaction coverage anchors — could not tell them apart from a
35
+ * message replayed out of the payload.
36
+ */
37
+ function buildRoutingPrompt(content: string): HumanMessage {
38
+ return new HumanMessage({
39
+ content,
40
+ additional_kwargs: { role: 'user', isMeta: true, source: 'routing' },
41
+ });
42
+ }
43
+
30
44
  function getHandoffInstructions(
31
45
  input: Record<string, unknown>,
32
46
  promptKey: string,
@@ -986,12 +1000,12 @@ export class MultiAgentGraph extends StandardGraph {
986
1000
  new AIMessage(
987
1001
  `[Processed tool result and transferring to ${agentId}]`
988
1002
  ),
989
- new HumanMessage(instructions),
1003
+ buildRoutingPrompt(instructions),
990
1004
  ];
991
1005
  } else {
992
1006
  messagesForAgent = [
993
1007
  ...filteredMessages,
994
- new HumanMessage(instructions),
1008
+ buildRoutingPrompt(instructions),
995
1009
  ];
996
1010
  }
997
1011
  }
@@ -1204,7 +1218,7 @@ export class MultiAgentGraph extends StandardGraph {
1204
1218
  effectiveExcludeResults === false
1205
1219
  ) {
1206
1220
  return {
1207
- messages: [new HumanMessage(promptText)],
1221
+ messages: [buildRoutingPrompt(promptText)],
1208
1222
  };
1209
1223
  }
1210
1224
 
@@ -1212,7 +1226,7 @@ export class MultiAgentGraph extends StandardGraph {
1212
1226
  * to pass filtered messages + prompt to the destination agent
1213
1227
  */
1214
1228
  const filteredMessages = state.messages.slice(0, this.startIndex);
1215
- const promptMessage = new HumanMessage(promptText);
1229
+ const promptMessage = buildRoutingPrompt(promptText);
1216
1230
  return {
1217
1231
  messages: [promptMessage],
1218
1232
  agentMessages: messagesStateReducer(filteredMessages, [