@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.cjs","names":["expandHighlights","params","formatResultsForLLM","WebSearchToolName","WebSearchToolDescription","createDefaultLogger","INTENT_PROPERTY","querySchema","dateSchema","imagesSchema","videosSchema","newsSchema","countrySchema","createSearchAPI","createSerperScraper","createTavilyScraper","createCrwScraper","createKeenableScraper","createFirecrawlScraper","createReranker","createSourceProcessor"],"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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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.cjs","names":["expandHighlights","params","formatResultsForLLM","WebSearchToolName","WebSearchToolDescription","createDefaultLogger","INTENT_PROPERTY","querySchema","dateSchema","imagesSchema","videosSchema","newsSchema","countrySchema","createSearchAPI","createSerperScraper","createTavilyScraper","createCrwScraper","createKeenableScraper","createFirecrawlScraper","createReranker","createSourceProcessor"],"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,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,EAC5C,WACA,OACA,MACA,SACA,YACA,QACA,QACA,MACA,UAW0B;CAE1B,MAAM,cAAyC,CAE7C,UAAU,WAAW;EACnB;EACA;EACA;EACA;CACF,CAAC,CACH;CAEA,IAAI,QACF,YAAY,KACV,UACG,WAAW;EACV;EACA;EACA;EACA;EACA,MAAM;CACR,CAAC,CAAC,CACD,OAAO,UAAU;EAChB,OAAO,MAAM,0BAA0B,KAAK;EAC5C,OAAO;GACL,SAAS;GACT,OAAO,yBAAyB,iBAAiB,QAAQ,MAAM,UAAU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mB,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,kBAAkBC,yBAAAA,sBAAsB;EACtC,GAAG;EACH,QAAQ,wBAAwB,UAAU;EAC1C,SAAS,kBAAkB,wBAAwB;EACnD,kBACE,wBAAwB,oBACxB,uBAAuB;EACzB;CACF,CAAC;MAED,kBAAkBC,kBAAAA,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,mBAAmBC,kBAAAA,eAAe;EACtC;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;CAED,IAAI,CAAC,kBACH,OAAO,KAAK,8CAA8C;CAG5D,MAAM,kBAAkBC,eAAAA,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"}
@@ -11,6 +11,23 @@ import { tool } from "@langchain/core/tools";
11
11
  /** Pattern to extract instructions from transfer ToolMessage content */
12
12
  const HANDOFF_INSTRUCTIONS_PATTERN = /(?:Instructions?|Context):\s*(.+)/is;
13
13
  const HANDOFF_INSTRUCTIONS_KEY = "handoff_instructions";
14
+ /**
15
+ * Handoff and fan-in prompts that route work between agents. Built in-run and
16
+ * never persisted as standalone payload entries, so they are marked synthetic:
17
+ * `messagesStateReducer` would otherwise give them a plain UUID and downstream
18
+ * consumers — compaction coverage anchors — could not tell them apart from a
19
+ * message replayed out of the payload.
20
+ */
21
+ function buildRoutingPrompt(content) {
22
+ return new HumanMessage({
23
+ content,
24
+ additional_kwargs: {
25
+ role: "user",
26
+ isMeta: true,
27
+ source: "routing"
28
+ }
29
+ });
30
+ }
14
31
  function getHandoffInstructions(input, promptKey, hasHandoffInput) {
15
32
  if (!hasHandoffInput || !Object.prototype.hasOwnProperty.call(input, promptKey)) return null;
16
33
  const value = input[promptKey];
@@ -606,9 +623,9 @@ var MultiAgentGraph = class extends StandardGraph {
606
623
  if (lastMsg != null && lastMsg.getType() === "tool") messagesForAgent = [
607
624
  ...filteredMessages,
608
625
  new AIMessage(`[Processed tool result and transferring to ${agentId}]`),
609
- new HumanMessage(instructions)
626
+ buildRoutingPrompt(instructions)
610
627
  ];
611
- else messagesForAgent = [...filteredMessages, new HumanMessage(instructions)];
628
+ else messagesForAgent = [...filteredMessages, buildRoutingPrompt(instructions)];
612
629
  }
613
630
  /** Update token map if we have a token counter */
614
631
  if (agentContext?.tokenCounter && hasInstructions) {
@@ -742,12 +759,12 @@ var MultiAgentGraph = class extends StandardGraph {
742
759
  effectiveExcludeResults = excludeResults !== false && promptText !== "";
743
760
  } else promptText = prompt;
744
761
  if (promptText != null && promptText !== "") {
745
- if (effectiveExcludeResults == null || effectiveExcludeResults === false) return { messages: [new HumanMessage(promptText)] };
762
+ if (effectiveExcludeResults == null || effectiveExcludeResults === false) return { messages: [buildRoutingPrompt(promptText)] };
746
763
  /** When `excludeResults` is true, use agentMessages channel
747
764
  * to pass filtered messages + prompt to the destination agent
748
765
  */
749
766
  const filteredMessages = state.messages.slice(0, this.startIndex);
750
- const promptMessage = new HumanMessage(promptText);
767
+ const promptMessage = buildRoutingPrompt(promptText);
751
768
  return {
752
769
  messages: [promptMessage],
753
770
  agentMessages: messagesStateReducer(filteredMessages, [promptMessage])
@@ -1 +1 @@
1
- {"version":3,"file":"MultiAgentGraph.mjs","names":["aiMsg"],"sources":["../../../src/graphs/MultiAgentGraph.ts"],"sourcesContent":["import { tool } from '@langchain/core/tools';\nimport { PromptTemplate } from '@langchain/core/prompts';\nimport {\n AIMessage,\n ToolMessage,\n HumanMessage,\n getBufferString,\n} from '@langchain/core/messages';\nimport {\n END,\n START,\n Command,\n StateGraph,\n Annotation,\n messagesStateReducer,\n} from '@langchain/langgraph';\nimport type { BaseMessage, AIMessageChunk } from '@langchain/core/messages';\nimport type { LangGraphRunnableConfig } from '@langchain/langgraph';\nimport type { ToolRuntime } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { serializeToolContentBounded } from '@/utils/toolContent';\nimport { HARD_MAX_TOOL_RESULT_CHARS } from '@/utils/truncation';\nimport { StandardGraph } from './Graph';\nimport { Constants } from '@/common';\n\n/** Pattern to extract instructions from transfer ToolMessage content */\nconst HANDOFF_INSTRUCTIONS_PATTERN = /(?:Instructions?|Context):\\s*(.+)/is;\nconst HANDOFF_INSTRUCTIONS_KEY = 'handoff_instructions';\n\nfunction getHandoffInstructions(\n input: Record<string, unknown>,\n promptKey: string,\n hasHandoffInput: boolean\n): string | null {\n if (\n !hasHandoffInput ||\n !Object.prototype.hasOwnProperty.call(input, promptKey)\n ) {\n return null;\n }\n const value = input[promptKey];\n return typeof value === 'string' ? value : null;\n}\n\nfunction formatHandoffPromptLabel(promptKey: string): string {\n return promptKey.charAt(0).toUpperCase() + promptKey.slice(1);\n}\n\nfunction extractLegacyHandoffInstructions(\n content: string,\n promptLabels: Set<string> | undefined\n): string | null {\n let markerIndex = -1;\n let markerLength = 0;\n for (const label of promptLabels ?? []) {\n const marker = `\\n\\n${label}:`;\n const index = content.indexOf(marker);\n if (index >= 0 && (markerIndex < 0 || index < markerIndex)) {\n markerIndex = index;\n markerLength = marker.length;\n }\n }\n if (markerIndex >= 0) {\n return content.slice(markerIndex + markerLength).trim();\n }\n return content.match(HANDOFF_INSTRUCTIONS_PATTERN)?.[1]?.trim() ?? null;\n}\n\nfunction isValidHandoffGroupId(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;\n}\n\nfunction withHandoffGroupMetadata(\n config: LangGraphRunnableConfig | undefined,\n groupId: number | undefined\n): LangGraphRunnableConfig {\n return {\n ...config,\n metadata: {\n ...config?.metadata,\n [Constants.HANDOFF_GROUP_ID]: groupId ?? null,\n },\n };\n}\n\n/**\n * MultiAgentGraph extends StandardGraph to support dynamic multi-agent workflows\n * with handoffs, fan-in/fan-out, and other composable patterns.\n *\n * Key behavior:\n * - Agents with ONLY handoff edges: Can dynamically route to any handoff destination\n * - Agents with ONLY direct edges: Always follow their direct edges\n * - Agents with BOTH: Use Command for exclusive routing (handoff OR direct, not both)\n * - If handoff occurs: Only the handoff destination executes\n * - If no handoff: Direct edges execute (potentially in parallel)\n *\n * This enables the common pattern where an agent either delegates (handoff)\n * OR continues its workflow (direct edges), but not both simultaneously.\n */\nexport class MultiAgentGraph extends StandardGraph {\n private edges: t.GraphEdge[];\n private startingNodes: Set<string> = new Set();\n private directEdges: t.GraphEdge[] = [];\n private handoffEdges: t.GraphEdge[] = [];\n private handoffPromptLabels: Map<string, Set<string>> = new Map();\n /**\n * Map of agentId to parallel group info.\n * Contains groupId (incrementing number reflecting execution order) for agents in parallel groups.\n * Sequential agents (not in any parallel group) have undefined entry.\n *\n * Example for: researcher -> [analyst1, analyst2, analyst3] -> summarizer\n * - researcher: undefined (sequential, order 0)\n * - analyst1, analyst2, analyst3: { groupId: 1 } (parallel group, order 1)\n * - summarizer: undefined (sequential, order 2)\n */\n private agentParallelGroups: Map<string, number> = new Map();\n\n constructor(input: t.MultiAgentGraphInput) {\n super(input);\n this.edges = input.edges;\n this.validateEdgeAgents();\n this.categorizeEdges();\n this.analyzeGraph();\n this.createHandoffTools();\n }\n\n /**\n * Fails fast when an edge references an agent that is not in\n * `agentContexts`. Without this check, the underlying LangGraph\n * `StateGraph.compile()` would throw the opaque\n * `Found edge ending at unknown node \"<id>\"` error after graph\n * construction — far from the true root cause.\n *\n * This catches the common misuse of passing `edges` into a multi-agent\n * config without also passing the corresponding sub-agent configs in\n * `agents` (e.g. a host that forgot to pre-load handoff targets).\n */\n private validateEdgeAgents(): void {\n const known = new Set(this.agentContexts.keys());\n const unknown = new Set<string>();\n for (const edge of this.edges) {\n const participants = [\n ...(Array.isArray(edge.from) ? edge.from : [edge.from]),\n ...(Array.isArray(edge.to) ? edge.to : [edge.to]),\n ];\n for (const id of participants) {\n if (typeof id === 'string' && !known.has(id)) {\n unknown.add(id);\n }\n }\n }\n if (unknown.size === 0) {\n return;\n }\n const missing = Array.from(unknown)\n .map((id) => `\"${id}\"`)\n .join(', ');\n throw new Error(\n `MultiAgentGraph: edges reference agent(s) not present in agents: [${missing}]. ` +\n 'Ensure every agent referenced by an edge is also included in the `agents` array, ' +\n 'or filter orphaned edges before constructing the graph.'\n );\n }\n\n /**\n * Categorize edges into handoff and direct types\n */\n private categorizeEdges(): void {\n for (const edge of this.edges) {\n // Default behavior: edges with conditions or explicit 'handoff' type are handoff edges\n // Edges with explicit 'direct' type or multi-destination without conditions are direct edges\n if (edge.edgeType === 'direct') {\n this.directEdges.push(edge);\n } else if (edge.edgeType === 'handoff' || edge.condition != null) {\n this.handoffEdges.push(edge);\n } else {\n // Default: single-to-single edges are handoff, single-to-multiple are direct\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n\n if (sources.length === 1 && destinations.length > 1) {\n // Fan-out pattern defaults to direct\n this.directEdges.push(edge);\n } else {\n // Everything else defaults to handoff\n this.handoffEdges.push(edge);\n }\n }\n }\n }\n\n /**\n * Analyze graph structure to determine starting nodes and connections\n */\n private analyzeGraph(): void {\n const hasIncomingEdge = new Set<string>();\n\n // Track all nodes that have incoming edges\n for (const edge of this.edges) {\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n destinations.forEach((dest) => hasIncomingEdge.add(dest));\n }\n\n // Starting nodes are those without incoming edges\n for (const agentId of this.agentContexts.keys()) {\n if (!hasIncomingEdge.has(agentId)) {\n this.startingNodes.add(agentId);\n }\n }\n\n // If no starting nodes found, use the first agent\n if (this.startingNodes.size === 0 && this.agentContexts.size > 0) {\n this.startingNodes.add(this.agentContexts.keys().next().value!);\n }\n\n // Determine if graph has parallel execution capability\n this.computeParallelCapability();\n }\n\n /**\n * Compute parallel groups by traversing the graph in execution order.\n * Assigns incrementing group IDs that reflect the sequential order of execution.\n *\n * For: researcher -> [analyst1, analyst2, analyst3] -> summarizer\n * - researcher: no group (first sequential node)\n * - analyst1, analyst2, analyst3: groupId 1 (first parallel group)\n * - summarizer: no group (next sequential node)\n *\n * This allows frontend to render in order:\n * Row 0: researcher\n * Row 1: [analyst1, analyst2, analyst3] (grouped)\n * Row 2: summarizer\n */\n private computeParallelCapability(): void {\n let groupCounter = 1; // Start at 1, 0 reserved for \"no group\"\n\n // Check 1: Multiple starting nodes means parallel from the start (group 1)\n if (this.startingNodes.size > 1) {\n for (const agentId of this.startingNodes) {\n this.agentParallelGroups.set(agentId, groupCounter);\n }\n groupCounter++;\n }\n\n // Check 2: Traverse direct edges in order to find fan-out patterns\n // Build a simple execution order by following edges from starting nodes\n const visited = new Set<string>();\n const queue: string[] = [...this.startingNodes];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (visited.has(current)) continue;\n visited.add(current);\n\n // Find direct edges from this node\n for (const edge of this.directEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (!sources.includes(current)) continue;\n\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n\n // Fan-out: multiple destinations = parallel group\n if (destinations.length > 1) {\n for (const dest of destinations) {\n // Only set if not already in a group (first group wins)\n if (!this.agentParallelGroups.has(dest)) {\n this.agentParallelGroups.set(dest, groupCounter);\n }\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n groupCounter++;\n } else {\n // Single destination - add to queue for traversal\n for (const dest of destinations) {\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n }\n }\n\n // Also follow handoff edges for traversal (but they don't create parallel groups)\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (!sources.includes(current)) continue;\n\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const dest of destinations) {\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n }\n }\n }\n\n /**\n * Get the parallel group ID for an agent, if any.\n * Returns undefined if the agent is not part of a parallel group.\n * Group IDs are incrementing numbers reflecting execution order.\n */\n getParallelGroupId(agentId: string): number | undefined {\n return this.agentParallelGroups.get(agentId);\n }\n\n /**\n * Override to indicate this is a multi-agent graph.\n * Enables agentId to be included in RunStep for frontend agent labeling.\n */\n protected override isMultiAgentGraph(): boolean {\n return true;\n }\n\n /**\n * Override base class method to provide parallel group IDs for run steps.\n */\n protected override getParallelGroupIdForAgent(\n agentId: string\n ): number | undefined {\n return this.agentParallelGroups.get(agentId);\n }\n\n /**\n * Create handoff tools for agents based on handoff edges only\n */\n private createHandoffTools(): void {\n // Group handoff edges by source agent(s)\n const handoffsByAgent = new Map<string, t.GraphEdge[]>();\n\n // Only process handoff edges for tool creation\n for (const edge of this.handoffEdges) {\n if (typeof edge.prompt === 'string') {\n const label = formatHandoffPromptLabel(\n edge.promptKey ?? 'instructions'\n );\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const destination of destinations) {\n const labels =\n this.handoffPromptLabels.get(destination) ?? new Set<string>();\n labels.add(label);\n this.handoffPromptLabels.set(destination, labels);\n }\n }\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n sources.forEach((source) => {\n if (!handoffsByAgent.has(source)) {\n handoffsByAgent.set(source, []);\n }\n handoffsByAgent.get(source)!.push(edge);\n });\n }\n\n // Create handoff tools for each agent\n for (const [agentId, edges] of handoffsByAgent) {\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) continue;\n\n // Create handoff tools for this agent's outgoing edges\n const handoffTools: t.GenericTool[] = [];\n const sourceAgentName = agentContext.name ?? agentId;\n for (const edge of edges) {\n handoffTools.push(\n ...this.createHandoffToolsForEdge(edge, agentId, sourceAgentName)\n );\n }\n\n if (!agentContext.graphTools) {\n agentContext.graphTools = [];\n }\n agentContext.graphTools.push(...handoffTools);\n }\n }\n\n /**\n * Create handoff tools for an edge (handles multiple destinations)\n * @param edge - The graph edge defining the handoff\n * @param sourceAgentId - The ID of the agent that will perform the handoff\n * @param sourceAgentName - The human-readable name of the source agent\n */\n private createHandoffToolsForEdge(\n edge: t.GraphEdge,\n sourceAgentId: string,\n sourceAgentName: string\n ): t.GenericTool[] {\n const tools: t.GenericTool[] = [];\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n\n /** If there's a condition, create a single conditional handoff tool */\n if (edge.condition != null) {\n const toolName = 'conditional_transfer';\n const toolDescription =\n edge.description ?? 'Conditionally transfer control based on state';\n\n /** Check if we have a prompt for handoff input */\n const hasHandoffInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const handoffInputDescription = hasHandoffInput ? edge.prompt : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (rawInput, runtime: ToolRuntime) => {\n const input = rawInput as Record<string, unknown>;\n const state = runtime.state as t.BaseGraphState;\n const toolCallId = runtime.toolCall?.id ?? 'unknown';\n\n /** Evaluated condition */\n const result = edge.condition!(state);\n let destination: string;\n\n if (typeof result === 'boolean') {\n /** If true, use first destination; if false, don't transfer */\n if (!result) return null;\n destination = destinations[0];\n } else if (typeof result === 'string') {\n destination = result;\n } else {\n /** Array of destinations - for now, use the first */\n destination = Array.isArray(result) ? result[0] : destinations[0];\n }\n\n const handoffInstructions = getHandoffInstructions(\n input,\n promptKey,\n hasHandoffInput\n );\n let content = `Conditionally transferred to ${destination}`;\n if (handoffInstructions !== null) {\n content += `\\n\\n${formatHandoffPromptLabel(promptKey)}: ${handoffInstructions}`;\n }\n\n const toolMessage = new ToolMessage({\n content,\n name: toolName,\n tool_call_id: toolCallId,\n additional_kwargs: {\n /** Store destination for programmatic access in handoff detection */\n handoff_destination: destination,\n /** Store source agent name for receiving agent to know who handed off */\n handoff_source_name: sourceAgentName,\n ...(handoffInstructions !== null && {\n [HANDOFF_INSTRUCTIONS_KEY]: handoffInstructions,\n }),\n },\n });\n\n return new Command({\n goto: destination,\n update: { messages: state.messages.concat(toolMessage) },\n graph: Command.PARENT,\n });\n },\n {\n name: toolName,\n schema: hasHandoffInput\n ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: handoffInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n } else {\n /** Create individual tools for each destination */\n for (const destination of destinations) {\n const toolName = `${Constants.LC_TRANSFER_TO_}${destination}`;\n const toolDescription =\n edge.description ?? `Transfer control to agent '${destination}'`;\n\n /** Check if we have a prompt for handoff input */\n const hasHandoffInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const handoffInputDescription = hasHandoffInput\n ? edge.prompt\n : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (rawInput, runtime: ToolRuntime) => {\n const input = rawInput as Record<string, unknown>;\n const toolCallId = runtime.toolCall?.id ?? 'unknown';\n\n const handoffInstructions = getHandoffInstructions(\n input,\n promptKey,\n hasHandoffInput\n );\n let content = `Successfully transferred to ${destination}`;\n if (handoffInstructions !== null) {\n content += `\\n\\n${formatHandoffPromptLabel(promptKey)}: ${handoffInstructions}`;\n }\n\n const toolMessage = new ToolMessage({\n content,\n name: toolName,\n tool_call_id: toolCallId,\n additional_kwargs: {\n /** Store source agent name for receiving agent to know who handed off */\n handoff_source_name: sourceAgentName,\n ...(handoffInstructions !== null && {\n [HANDOFF_INSTRUCTIONS_KEY]: handoffInstructions,\n }),\n },\n });\n\n const state = runtime.state as t.BaseGraphState;\n\n /**\n * For parallel handoff support:\n * Build messages that include ONLY this tool call's context.\n * This prevents errors when LLM calls multiple transfers simultaneously -\n * each destination gets a valid AIMessage with matching tool_call and tool_result.\n *\n * Strategy:\n * 1. Find the AIMessage containing this tool call\n * 2. Create a filtered AIMessage with ONLY this tool_call\n * 3. Include all messages before the AIMessage plus the filtered pair\n */\n const messages = state.messages;\n let filteredMessages = messages;\n let aiMessageIndex = -1;\n\n /** Find the AIMessage containing this tool call */\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg.getType() === 'ai') {\n const aiMsg = msg as AIMessage;\n const hasThisCall = aiMsg.tool_calls?.some(\n (tc) => tc.id === toolCallId\n );\n if (hasThisCall === true) {\n aiMessageIndex = i;\n break;\n }\n }\n }\n\n if (aiMessageIndex >= 0) {\n const originalAiMsg = messages[aiMessageIndex] as AIMessage;\n const thisToolCall = originalAiMsg.tool_calls?.find(\n (tc) => tc.id === toolCallId\n );\n\n if (\n thisToolCall != null &&\n (originalAiMsg.tool_calls?.length ?? 0) > 1\n ) {\n /**\n * Multiple tool calls - create filtered AIMessage with ONLY this call.\n * This ensures valid message structure for parallel handoffs.\n */\n const filteredAiMsg = new AIMessage({\n content: originalAiMsg.content,\n tool_calls: [thisToolCall],\n id: originalAiMsg.id,\n });\n\n filteredMessages = [\n ...messages.slice(0, aiMessageIndex),\n filteredAiMsg,\n toolMessage,\n ];\n } else {\n /** Single tool call - use messages as-is */\n filteredMessages = messages.concat(toolMessage);\n }\n } else {\n /** Fallback - append tool message */\n filteredMessages = messages.concat(toolMessage);\n }\n\n return new Command({\n goto: destination,\n update: { messages: filteredMessages },\n graph: Command.PARENT,\n });\n },\n {\n name: toolName,\n schema: hasHandoffInput\n ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: handoffInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n }\n }\n\n return tools;\n }\n\n /**\n * Create a complete agent subgraph (similar to createReactAgent)\n */\n private createAgentSubgraph(agentId: string): t.CompiledAgentWorfklow {\n /** This is essentially the same as `createAgentNode` from `StandardGraph` */\n return this.createAgentNode(agentId);\n }\n\n /**\n * Detects if the current agent is receiving a handoff and processes the messages accordingly.\n * Returns filtered messages with the transfer tool call/message removed, plus any instructions,\n * source agent, and parallel sibling information extracted from the transfer.\n *\n * Supports both single handoffs (last message is the transfer) and parallel handoffs\n * (multiple transfer ToolMessages, need to find the one targeting this agent).\n *\n * @param messages - Current state messages\n * @param agentId - The agent ID to check for handoff reception\n * @returns Object with filtered messages, extracted instructions, source agent, and parallel siblings\n */\n private processHandoffReception(\n messages: BaseMessage[],\n agentId: string\n ): {\n filteredMessages: BaseMessage[];\n instructions: string | null;\n sourceAgentName: string | null;\n parallelSiblings: string[];\n parallelGroupId?: number;\n } | null {\n if (messages.length === 0) return null;\n\n /**\n * A handoff is active only while resolving the most recent assistant\n * tool-call round. Older transfer results remain in conversation history,\n * but must not be reused when this agent is reached later through a direct\n * edge or cycle.\n */\n const activeTransferToolCallIds = new Set<string>();\n let activeToolMessageStartIndex = messages.length;\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg.getType() === 'tool') continue;\n\n if (msg.getType() === 'ai') {\n const aiMsg = msg as AIMessage | AIMessageChunk;\n for (const toolCall of aiMsg.tool_calls ?? []) {\n if (\n toolCall.id != null &&\n (toolCall.name.startsWith(Constants.LC_TRANSFER_TO_) ||\n toolCall.name === 'conditional_transfer')\n ) {\n activeTransferToolCallIds.add(toolCall.id);\n }\n }\n activeToolMessageStartIndex = i + 1;\n }\n break;\n }\n\n if (activeTransferToolCallIds.size === 0) return null;\n\n /**\n * Search for a transfer ToolMessage targeting this agent.\n * For parallel handoffs, multiple transfer messages may exist - find ours.\n * Search backwards from the end to find the most recent transfer to this agent.\n */\n let toolMessage: ToolMessage | null = null;\n let toolMessageIndex = -1;\n\n for (let i = messages.length - 1; i >= activeToolMessageStartIndex; i--) {\n const msg = messages[i];\n if (msg.getType() !== 'tool') continue;\n\n const candidateMsg = msg as ToolMessage;\n const toolName = candidateMsg.name;\n\n if (\n typeof toolName !== 'string' ||\n !activeTransferToolCallIds.has(candidateMsg.tool_call_id)\n ) {\n continue;\n }\n\n /** Check for standard transfer pattern */\n const isTransferMessage = toolName.startsWith(Constants.LC_TRANSFER_TO_);\n const isConditionalTransfer = toolName === 'conditional_transfer';\n\n if (!isTransferMessage && !isConditionalTransfer) continue;\n\n /** Extract destination from tool name or additional_kwargs */\n let destinationAgent: string | null = null;\n\n if (isTransferMessage) {\n destinationAgent = toolName.replace(Constants.LC_TRANSFER_TO_, '');\n } else if (isConditionalTransfer) {\n const handoffDest = candidateMsg.additional_kwargs.handoff_destination;\n destinationAgent = typeof handoffDest === 'string' ? handoffDest : null;\n }\n\n /** Check if this transfer targets our agent */\n if (destinationAgent === agentId) {\n toolMessage = candidateMsg;\n toolMessageIndex = i;\n break;\n }\n }\n\n /** No transfer targeting this agent found */\n if (toolMessage === null || toolMessageIndex < 0) return null;\n\n /** Extract instructions from the ToolMessage content */\n const contentStr =\n typeof toolMessage.content === 'string'\n ? toolMessage.content\n : serializeToolContentBounded(\n toolMessage.content,\n HARD_MAX_TOOL_RESULT_CHARS\n );\n\n const structuredInstructions =\n toolMessage.additional_kwargs[HANDOFF_INSTRUCTIONS_KEY];\n const instructions =\n typeof structuredInstructions === 'string'\n ? structuredInstructions.trim()\n : extractLegacyHandoffInstructions(\n contentStr,\n this.handoffPromptLabels.get(agentId)\n );\n\n /** Extract source agent name from additional_kwargs */\n const handoffSourceName = toolMessage.additional_kwargs.handoff_source_name;\n const sourceAgentName =\n typeof handoffSourceName === 'string' ? handoffSourceName : null;\n\n /** Extract parallel siblings (set by ToolNode for parallel handoffs) */\n const rawSiblings = toolMessage.additional_kwargs.handoff_parallel_siblings;\n const siblingIds: string[] = Array.isArray(rawSiblings)\n ? rawSiblings.filter((s): s is string => typeof s === 'string')\n : [];\n /** Convert IDs to display names */\n const parallelSiblings = siblingIds.map((id) => {\n const ctx = this.agentContexts.get(id);\n return ctx?.name ?? id;\n });\n const storedParallelGroupId =\n toolMessage.additional_kwargs[Constants.HANDOFF_GROUP_ID];\n const parallelGroupId = isValidHandoffGroupId(storedParallelGroupId)\n ? storedParallelGroupId\n : undefined;\n\n /** Get the tool_call_id to find and filter the AI message's tool call */\n const toolCallId = toolMessage.tool_call_id;\n\n /**\n * Collect all transfer tool_call_ids to filter out.\n * For parallel handoffs, we filter ALL transfer messages (not just ours)\n * to give the receiving agent a clean context without handoff noise.\n */\n const transferToolCallIds = new Set<string>([toolCallId]);\n for (const msg of messages) {\n if (msg.getType() === 'tool') {\n const tm = msg as ToolMessage;\n const tName = tm.name;\n if (\n typeof tName === 'string' &&\n (tName.startsWith(Constants.LC_TRANSFER_TO_) ||\n tName === 'conditional_transfer')\n ) {\n transferToolCallIds.add(tm.tool_call_id);\n }\n } else if (msg.getType() === 'ai') {\n const aiMsg = msg as AIMessage | AIMessageChunk;\n for (const toolCall of aiMsg.tool_calls ?? []) {\n if (\n toolCall.id != null &&\n (toolCall.name.startsWith(Constants.LC_TRANSFER_TO_) ||\n toolCall.name === 'conditional_transfer')\n ) {\n transferToolCallIds.add(toolCall.id);\n }\n }\n }\n }\n\n /** Filter out all transfer messages */\n const filteredMessages: BaseMessage[] = [];\n\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n const msgType = msg.getType();\n\n /** Skip transfer ToolMessages */\n if (msgType === 'tool') {\n const tm = msg as ToolMessage;\n if (transferToolCallIds.has(tm.tool_call_id)) {\n continue;\n }\n }\n\n if (msgType === 'ai') {\n /** Check if this AI message contains any transfer tool calls */\n const aiMsg = msg as AIMessage | AIMessageChunk;\n const toolCalls = aiMsg.tool_calls;\n\n if (toolCalls && toolCalls.length > 0) {\n /** Filter out all transfer tool calls */\n const remainingToolCalls = toolCalls.filter(\n (tc) => tc.id == null || !transferToolCallIds.has(tc.id)\n );\n\n const hasTransferCalls = remainingToolCalls.length < toolCalls.length;\n\n if (hasTransferCalls) {\n if (\n remainingToolCalls.length > 0 ||\n (typeof aiMsg.content === 'string' && aiMsg.content.trim())\n ) {\n /** Keep the message but without transfer tool calls */\n const filteredAiMsg = new AIMessage({\n content: aiMsg.content,\n tool_calls: remainingToolCalls,\n id: aiMsg.id,\n });\n filteredMessages.push(filteredAiMsg);\n }\n /** If no remaining content or tool calls, skip this message entirely */\n continue;\n }\n }\n }\n\n /** Keep all other messages */\n filteredMessages.push(msg);\n }\n\n return {\n filteredMessages,\n instructions,\n sourceAgentName,\n parallelSiblings,\n parallelGroupId,\n };\n }\n\n /**\n * Create the multi-agent workflow with dynamic handoffs\n */\n override createWorkflow(): t.CompiledMultiAgentWorkflow {\n this.hasCompiledCheckpointer = this.compileOptions?.checkpointer != null;\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: (a, b) => {\n if (!this.messages.length) {\n this.startIndex = a.length + b.length;\n }\n const result = messagesStateReducer(a, b);\n this.messages = result;\n return result;\n },\n default: () => [],\n }),\n /** Channel for passing filtered messages to agents when excludeResults is true */\n agentMessages: Annotation<BaseMessage[]>({\n /** Replaces state entirely */\n reducer: (a, b) => b,\n default: () => [],\n }),\n });\n\n const builder = new StateGraph(StateAnnotation);\n\n // Add all agents as complete subgraphs\n for (const [agentId] of this.agentContexts) {\n // Get all possible destinations for this agent\n const handoffDestinations = new Set<string>();\n const directDestinations = new Set<string>();\n\n // Check handoff edges for destinations\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (sources.includes(agentId) === true) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((dest) => handoffDestinations.add(dest));\n }\n }\n\n // Check direct edges for destinations\n for (const edge of this.directEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (sources.includes(agentId) === true) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((dest) => directDestinations.add(dest));\n }\n }\n\n /** Check if this agent has BOTH handoff and direct edges */\n const hasHandoffEdges = handoffDestinations.size > 0;\n const hasDirectEdges = directDestinations.size > 0;\n const needsCommandRouting = hasHandoffEdges && hasDirectEdges;\n\n /** Collect all possible destinations for this agent */\n const allDestinations = new Set([\n ...handoffDestinations,\n ...directDestinations,\n ]);\n if (handoffDestinations.size > 0 || directDestinations.size === 0) {\n allDestinations.add(END);\n }\n\n /** Agent subgraph (includes agent + tools) */\n const agentSubgraph = this.createAgentSubgraph(agentId);\n\n /** Wrapper function that handles agentMessages channel, handoff reception, and conditional routing */\n const agentWrapper = async (\n state: t.MultiAgentGraphState,\n config?: LangGraphRunnableConfig\n ): Promise<t.MultiAgentGraphState | Command> => {\n let result: t.MultiAgentGraphState;\n\n /**\n * Check if this agent is receiving a handoff.\n * If so, filter out the transfer messages and inject instructions as preamble.\n * This prevents the receiving agent from seeing the transfer as \"completed work\"\n * and prematurely producing an end token.\n */\n const handoffContext = this.processHandoffReception(\n state.messages,\n agentId\n );\n const agentContext = this.agentContexts.get(agentId);\n\n if (\n handoffContext?.sourceAgentName != null &&\n handoffContext.sourceAgentName !== ''\n ) {\n agentContext?.setHandoffContext(\n handoffContext.sourceAgentName,\n handoffContext.parallelSiblings\n );\n } else {\n agentContext?.clearHandoffContext();\n }\n\n if (handoffContext !== null) {\n const { filteredMessages, instructions, parallelGroupId } =\n handoffContext;\n\n /** Build messages for the receiving agent */\n let messagesForAgent = filteredMessages;\n\n /**\n * If there are instructions, inject them as a HumanMessage to\n * ground the receiving agent.\n *\n * When the last filtered message is a ToolMessage (e.g. from a\n * non-handoff tool the router called before handing off), a\n * synthetic AIMessage is inserted first to satisfy the\n * tool → assistant role ordering required by chat APIs. Without\n * this bridge, appending a HumanMessage directly after a\n * ToolMessage causes \"400 Unexpected role 'user' after role\n * 'tool'\" errors (see issue #54).\n */\n const hasInstructions = instructions !== null && instructions !== '';\n if (hasInstructions) {\n const lastMsg =\n filteredMessages.length > 0\n ? filteredMessages[filteredMessages.length - 1]\n : null;\n\n if (lastMsg != null && lastMsg.getType() === 'tool') {\n messagesForAgent = [\n ...filteredMessages,\n new AIMessage(\n `[Processed tool result and transferring to ${agentId}]`\n ),\n new HumanMessage(instructions),\n ];\n } else {\n messagesForAgent = [\n ...filteredMessages,\n new HumanMessage(instructions),\n ];\n }\n }\n\n /** Update token map if we have a token counter */\n if (agentContext?.tokenCounter && hasInstructions) {\n const freshTokenMap: Record<string, number> = {};\n for (\n let i = 0;\n i < Math.min(filteredMessages.length, this.startIndex);\n i++\n ) {\n const tokenCount = agentContext.indexTokenCountMap[i];\n if (tokenCount !== undefined) {\n freshTokenMap[i] = tokenCount;\n }\n }\n /** Add tokens for the bridge AIMessage + instructions HumanMessage */\n for (\n let i = filteredMessages.length;\n i < messagesForAgent.length;\n i++\n ) {\n freshTokenMap[i] = agentContext.tokenCounter(messagesForAgent[i]);\n }\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: messagesForAgent,\n };\n result = await agentSubgraph.invoke(\n transformedState,\n withHandoffGroupMetadata(config, parallelGroupId)\n );\n result = {\n ...result,\n agentMessages: [],\n };\n } else if (\n state.agentMessages != null &&\n state.agentMessages.length > 0\n ) {\n /**\n * When using agentMessages (excludeResults=true), we need to update\n * the token map to account for the new prompt message\n */\n if (agentContext && agentContext.tokenCounter) {\n /** The agentMessages contains:\n * 1. Filtered messages (0 to startIndex) - already have token counts\n * 2. New prompt message - needs token counting\n */\n const freshTokenMap: Record<string, number> = {};\n\n /** Copy existing token counts for filtered messages (0 to startIndex) */\n for (let i = 0; i < this.startIndex; i++) {\n const tokenCount = agentContext.indexTokenCountMap[i];\n if (tokenCount !== undefined) {\n freshTokenMap[i] = tokenCount;\n }\n }\n\n /** Calculate tokens only for the new prompt message (last message) */\n const promptMessageIndex = state.agentMessages.length - 1;\n if (promptMessageIndex >= this.startIndex) {\n const promptMessage = state.agentMessages[promptMessageIndex];\n freshTokenMap[promptMessageIndex] =\n agentContext.tokenCounter(promptMessage);\n }\n\n /** Update the agent's token map with instructions added */\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n /** Temporary state with messages replaced by `agentMessages` */\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: state.agentMessages,\n };\n result = await agentSubgraph.invoke(transformedState, config);\n result = {\n ...result,\n /** Clear agentMessages for next agent */\n agentMessages: [],\n };\n } else {\n result = await agentSubgraph.invoke(state, config);\n }\n\n /** If agent has both handoff and direct edges, use Command for exclusive routing */\n if (needsCommandRouting) {\n /** Check if a handoff occurred */\n const lastMessage = result.messages[\n result.messages.length - 1\n ] as BaseMessage | null;\n if (\n lastMessage != null &&\n lastMessage.getType() === 'tool' &&\n typeof lastMessage.name === 'string' &&\n lastMessage.name.startsWith(Constants.LC_TRANSFER_TO_)\n ) {\n /** Handoff occurred - extract destination and navigate there exclusively */\n const handoffDest = lastMessage.name.replace(\n Constants.LC_TRANSFER_TO_,\n ''\n );\n return new Command({\n update: result,\n goto: handoffDest,\n });\n } else {\n /** No handoff - proceed with direct edges */\n const directDests = Array.from(directDestinations);\n if (directDests.length === 1) {\n return new Command({\n update: result,\n goto: directDests[0],\n });\n } else if (directDests.length > 1) {\n /** Multiple direct destinations - they'll run in parallel */\n return new Command({\n update: result,\n goto: directDests,\n });\n }\n }\n }\n\n /** No special routing needed - return state normally */\n return result;\n };\n\n /** Wrapped agent as a node with its possible destinations */\n builder.addNode(agentId, agentWrapper, {\n ends: Array.from(allDestinations),\n });\n }\n\n // Add starting edges for all starting nodes\n for (const startNode of this.startingNodes) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(START, startNode);\n }\n\n /**\n * Add direct edges for automatic transitions\n * Group edges by destination to handle fan-in scenarios\n */\n const edgesByDestination = new Map<string, t.GraphEdge[]>();\n\n for (const edge of this.directEdges) {\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const destination of destinations) {\n if (!edgesByDestination.has(destination)) {\n edgesByDestination.set(destination, []);\n }\n edgesByDestination.get(destination)!.push(edge);\n }\n }\n\n for (const [destination, edges] of edgesByDestination) {\n /** Checks if this is a fan-in scenario with prompt instructions */\n const edgesWithPrompt = edges.filter(\n (edge) => edge.prompt != null && edge.prompt !== ''\n );\n\n if (edgesWithPrompt.length > 0) {\n /**\n * Single wrapper node for destination (Fan-in with prompt)\n */\n const wrapperNodeId = `fan_in_${destination}_prompt`;\n /**\n * First edge's `prompt`\n * (they should all be the same for fan-in)\n */\n const prompt = edgesWithPrompt[0].prompt;\n /**\n * First edge's `excludeResults` flag\n * (they should all be the same for fan-in)\n */\n const excludeResults = edgesWithPrompt[0].excludeResults;\n\n builder.addNode(wrapperNodeId, async (state: t.BaseGraphState) => {\n let promptText: string | undefined;\n let effectiveExcludeResults = excludeResults;\n\n if (typeof prompt === 'function') {\n promptText = await prompt(state.messages, this.startIndex);\n } else if (prompt != null) {\n if (prompt.includes('{results}')) {\n const resultsMessages = state.messages.slice(this.startIndex);\n const resultsString = getBufferString(resultsMessages);\n const promptTemplate = PromptTemplate.fromTemplate(prompt);\n const result = await promptTemplate.invoke({\n results: resultsString,\n });\n promptText = result.value;\n effectiveExcludeResults =\n excludeResults !== false && promptText !== '';\n } else {\n promptText = prompt;\n }\n }\n\n if (promptText != null && promptText !== '') {\n if (\n effectiveExcludeResults == null ||\n effectiveExcludeResults === false\n ) {\n return {\n messages: [new HumanMessage(promptText)],\n };\n }\n\n /** When `excludeResults` is true, use agentMessages channel\n * to pass filtered messages + prompt to the destination agent\n */\n const filteredMessages = state.messages.slice(0, this.startIndex);\n const promptMessage = new HumanMessage(promptText);\n return {\n messages: [promptMessage],\n agentMessages: messagesStateReducer(filteredMessages, [\n promptMessage,\n ]),\n };\n }\n\n /** No prompt needed, return empty update */\n return {};\n });\n\n /** Add edges from all sources to the wrapper, then wrapper to destination */\n for (const edge of edges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n for (const source of sources) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(source, wrapperNodeId);\n }\n }\n\n /** Single edge from wrapper to destination */\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(wrapperNodeId, destination);\n } else {\n /** No prompt instructions, add direct edges (skip if source uses Command routing) */\n for (const edge of edges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n for (const source of sources) {\n /** Check if this source node has both handoff and direct edges */\n const sourceHandoffEdges = this.handoffEdges.filter((e) => {\n const eSources = Array.isArray(e.from) ? e.from : [e.from];\n return eSources.includes(source);\n });\n const sourceDirectEdges = this.directEdges.filter((e) => {\n const eSources = Array.isArray(e.from) ? e.from : [e.from];\n return eSources.includes(source);\n });\n\n /** Skip adding edge if source uses Command routing (has both types) */\n if (sourceHandoffEdges.length > 0 && sourceDirectEdges.length > 0) {\n continue;\n }\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(source, destination);\n }\n }\n }\n }\n\n return builder.compile(this.compileOptions as unknown as never);\n }\n}\n"],"mappings":";;;;;;;;;;;AA0BA,MAAM,+BAA+B;AACrC,MAAM,2BAA2B;AAEjC,SAAS,uBACP,OACA,WACA,iBACe;CACf,IACE,CAAC,mBACD,CAAC,OAAO,UAAU,eAAe,KAAK,OAAO,SAAS,GAEtD,OAAO;CAET,MAAM,QAAQ,MAAM;CACpB,OAAO,OAAO,UAAU,WAAW,QAAQ;AAC7C;AAEA,SAAS,yBAAyB,WAA2B;CAC3D,OAAO,UAAU,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,UAAU,MAAM,CAAC;AAC9D;AAEA,SAAS,iCACP,SACA,cACe;CACf,IAAI,cAAc;CAClB,IAAI,eAAe;CACnB,KAAK,MAAM,SAAS,gBAAgB,CAAC,GAAG;EACtC,MAAM,SAAS,OAAO,MAAM;EAC5B,MAAM,QAAQ,QAAQ,QAAQ,MAAM;EACpC,IAAI,SAAS,MAA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ourcesContent":["import { tool } from '@langchain/core/tools';\nimport { PromptTemplate } from '@langchain/core/prompts';\nimport {\n AIMessage,\n ToolMessage,\n HumanMessage,\n getBufferString,\n} from '@langchain/core/messages';\nimport {\n END,\n START,\n Command,\n StateGraph,\n Annotation,\n messagesStateReducer,\n} from '@langchain/langgraph';\nimport type { BaseMessage, AIMessageChunk } from '@langchain/core/messages';\nimport type { LangGraphRunnableConfig } from '@langchain/langgraph';\nimport type { ToolRuntime } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { serializeToolContentBounded } from '@/utils/toolContent';\nimport { HARD_MAX_TOOL_RESULT_CHARS } from '@/utils/truncation';\nimport { StandardGraph } from './Graph';\nimport { Constants } from '@/common';\n\n/** Pattern to extract instructions from transfer ToolMessage content */\nconst HANDOFF_INSTRUCTIONS_PATTERN = /(?:Instructions?|Context):\\s*(.+)/is;\nconst HANDOFF_INSTRUCTIONS_KEY = 'handoff_instructions';\n\n/**\n * Handoff and fan-in prompts that route work between agents. Built in-run and\n * never persisted as standalone payload entries, so they are marked synthetic:\n * `messagesStateReducer` would otherwise give them a plain UUID and downstream\n * consumers — compaction coverage anchors — could not tell them apart from a\n * message replayed out of the payload.\n */\nfunction buildRoutingPrompt(content: string): HumanMessage {\n return new HumanMessage({\n content,\n additional_kwargs: { role: 'user', isMeta: true, source: 'routing' },\n });\n}\n\nfunction getHandoffInstructions(\n input: Record<string, unknown>,\n promptKey: string,\n hasHandoffInput: boolean\n): string | null {\n if (\n !hasHandoffInput ||\n !Object.prototype.hasOwnProperty.call(input, promptKey)\n ) {\n return null;\n }\n const value = input[promptKey];\n return typeof value === 'string' ? value : null;\n}\n\nfunction formatHandoffPromptLabel(promptKey: string): string {\n return promptKey.charAt(0).toUpperCase() + promptKey.slice(1);\n}\n\nfunction extractLegacyHandoffInstructions(\n content: string,\n promptLabels: Set<string> | undefined\n): string | null {\n let markerIndex = -1;\n let markerLength = 0;\n for (const label of promptLabels ?? []) {\n const marker = `\\n\\n${label}:`;\n const index = content.indexOf(marker);\n if (index >= 0 && (markerIndex < 0 || index < markerIndex)) {\n markerIndex = index;\n markerLength = marker.length;\n }\n }\n if (markerIndex >= 0) {\n return content.slice(markerIndex + markerLength).trim();\n }\n return content.match(HANDOFF_INSTRUCTIONS_PATTERN)?.[1]?.trim() ?? null;\n}\n\nfunction isValidHandoffGroupId(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;\n}\n\nfunction withHandoffGroupMetadata(\n config: LangGraphRunnableConfig | undefined,\n groupId: number | undefined\n): LangGraphRunnableConfig {\n return {\n ...config,\n metadata: {\n ...config?.metadata,\n [Constants.HANDOFF_GROUP_ID]: groupId ?? null,\n },\n };\n}\n\n/**\n * MultiAgentGraph extends StandardGraph to support dynamic multi-agent workflows\n * with handoffs, fan-in/fan-out, and other composable patterns.\n *\n * Key behavior:\n * - Agents with ONLY handoff edges: Can dynamically route to any handoff destination\n * - Agents with ONLY direct edges: Always follow their direct edges\n * - Agents with BOTH: Use Command for exclusive routing (handoff OR direct, not both)\n * - If handoff occurs: Only the handoff destination executes\n * - If no handoff: Direct edges execute (potentially in parallel)\n *\n * This enables the common pattern where an agent either delegates (handoff)\n * OR continues its workflow (direct edges), but not both simultaneously.\n */\nexport class MultiAgentGraph extends StandardGraph {\n private edges: t.GraphEdge[];\n private startingNodes: Set<string> = new Set();\n private directEdges: t.GraphEdge[] = [];\n private handoffEdges: t.GraphEdge[] = [];\n private handoffPromptLabels: Map<string, Set<string>> = new Map();\n /**\n * Map of agentId to parallel group info.\n * Contains groupId (incrementing number reflecting execution order) for agents in parallel groups.\n * Sequential agents (not in any parallel group) have undefined entry.\n *\n * Example for: researcher -> [analyst1, analyst2, analyst3] -> summarizer\n * - researcher: undefined (sequential, order 0)\n * - analyst1, analyst2, analyst3: { groupId: 1 } (parallel group, order 1)\n * - summarizer: undefined (sequential, order 2)\n */\n private agentParallelGroups: Map<string, number> = new Map();\n\n constructor(input: t.MultiAgentGraphInput) {\n super(input);\n this.edges = input.edges;\n this.validateEdgeAgents();\n this.categorizeEdges();\n this.analyzeGraph();\n this.createHandoffTools();\n }\n\n /**\n * Fails fast when an edge references an agent that is not in\n * `agentContexts`. Without this check, the underlying LangGraph\n * `StateGraph.compile()` would throw the opaque\n * `Found edge ending at unknown node \"<id>\"` error after graph\n * construction — far from the true root cause.\n *\n * This catches the common misuse of passing `edges` into a multi-agent\n * config without also passing the corresponding sub-agent configs in\n * `agents` (e.g. a host that forgot to pre-load handoff targets).\n */\n private validateEdgeAgents(): void {\n const known = new Set(this.agentContexts.keys());\n const unknown = new Set<string>();\n for (const edge of this.edges) {\n const participants = [\n ...(Array.isArray(edge.from) ? edge.from : [edge.from]),\n ...(Array.isArray(edge.to) ? edge.to : [edge.to]),\n ];\n for (const id of participants) {\n if (typeof id === 'string' && !known.has(id)) {\n unknown.add(id);\n }\n }\n }\n if (unknown.size === 0) {\n return;\n }\n const missing = Array.from(unknown)\n .map((id) => `\"${id}\"`)\n .join(', ');\n throw new Error(\n `MultiAgentGraph: edges reference agent(s) not present in agents: [${missing}]. ` +\n 'Ensure every agent referenced by an edge is also included in the `agents` array, ' +\n 'or filter orphaned edges before constructing the graph.'\n );\n }\n\n /**\n * Categorize edges into handoff and direct types\n */\n private categorizeEdges(): void {\n for (const edge of this.edges) {\n // Default behavior: edges with conditions or explicit 'handoff' type are handoff edges\n // Edges with explicit 'direct' type or multi-destination without conditions are direct edges\n if (edge.edgeType === 'direct') {\n this.directEdges.push(edge);\n } else if (edge.edgeType === 'handoff' || edge.condition != null) {\n this.handoffEdges.push(edge);\n } else {\n // Default: single-to-single edges are handoff, single-to-multiple are direct\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n\n if (sources.length === 1 && destinations.length > 1) {\n // Fan-out pattern defaults to direct\n this.directEdges.push(edge);\n } else {\n // Everything else defaults to handoff\n this.handoffEdges.push(edge);\n }\n }\n }\n }\n\n /**\n * Analyze graph structure to determine starting nodes and connections\n */\n private analyzeGraph(): void {\n const hasIncomingEdge = new Set<string>();\n\n // Track all nodes that have incoming edges\n for (const edge of this.edges) {\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n destinations.forEach((dest) => hasIncomingEdge.add(dest));\n }\n\n // Starting nodes are those without incoming edges\n for (const agentId of this.agentContexts.keys()) {\n if (!hasIncomingEdge.has(agentId)) {\n this.startingNodes.add(agentId);\n }\n }\n\n // If no starting nodes found, use the first agent\n if (this.startingNodes.size === 0 && this.agentContexts.size > 0) {\n this.startingNodes.add(this.agentContexts.keys().next().value!);\n }\n\n // Determine if graph has parallel execution capability\n this.computeParallelCapability();\n }\n\n /**\n * Compute parallel groups by traversing the graph in execution order.\n * Assigns incrementing group IDs that reflect the sequential order of execution.\n *\n * For: researcher -> [analyst1, analyst2, analyst3] -> summarizer\n * - researcher: no group (first sequential node)\n * - analyst1, analyst2, analyst3: groupId 1 (first parallel group)\n * - summarizer: no group (next sequential node)\n *\n * This allows frontend to render in order:\n * Row 0: researcher\n * Row 1: [analyst1, analyst2, analyst3] (grouped)\n * Row 2: summarizer\n */\n private computeParallelCapability(): void {\n let groupCounter = 1; // Start at 1, 0 reserved for \"no group\"\n\n // Check 1: Multiple starting nodes means parallel from the start (group 1)\n if (this.startingNodes.size > 1) {\n for (const agentId of this.startingNodes) {\n this.agentParallelGroups.set(agentId, groupCounter);\n }\n groupCounter++;\n }\n\n // Check 2: Traverse direct edges in order to find fan-out patterns\n // Build a simple execution order by following edges from starting nodes\n const visited = new Set<string>();\n const queue: string[] = [...this.startingNodes];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (visited.has(current)) continue;\n visited.add(current);\n\n // Find direct edges from this node\n for (const edge of this.directEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (!sources.includes(current)) continue;\n\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n\n // Fan-out: multiple destinations = parallel group\n if (destinations.length > 1) {\n for (const dest of destinations) {\n // Only set if not already in a group (first group wins)\n if (!this.agentParallelGroups.has(dest)) {\n this.agentParallelGroups.set(dest, groupCounter);\n }\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n groupCounter++;\n } else {\n // Single destination - add to queue for traversal\n for (const dest of destinations) {\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n }\n }\n\n // Also follow handoff edges for traversal (but they don't create parallel groups)\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (!sources.includes(current)) continue;\n\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const dest of destinations) {\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n }\n }\n }\n\n /**\n * Get the parallel group ID for an agent, if any.\n * Returns undefined if the agent is not part of a parallel group.\n * Group IDs are incrementing numbers reflecting execution order.\n */\n getParallelGroupId(agentId: string): number | undefined {\n return this.agentParallelGroups.get(agentId);\n }\n\n /**\n * Override to indicate this is a multi-agent graph.\n * Enables agentId to be included in RunStep for frontend agent labeling.\n */\n protected override isMultiAgentGraph(): boolean {\n return true;\n }\n\n /**\n * Override base class method to provide parallel group IDs for run steps.\n */\n protected override getParallelGroupIdForAgent(\n agentId: string\n ): number | undefined {\n return this.agentParallelGroups.get(agentId);\n }\n\n /**\n * Create handoff tools for agents based on handoff edges only\n */\n private createHandoffTools(): void {\n // Group handoff edges by source agent(s)\n const handoffsByAgent = new Map<string, t.GraphEdge[]>();\n\n // Only process handoff edges for tool creation\n for (const edge of this.handoffEdges) {\n if (typeof edge.prompt === 'string') {\n const label = formatHandoffPromptLabel(\n edge.promptKey ?? 'instructions'\n );\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const destination of destinations) {\n const labels =\n this.handoffPromptLabels.get(destination) ?? new Set<string>();\n labels.add(label);\n this.handoffPromptLabels.set(destination, labels);\n }\n }\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n sources.forEach((source) => {\n if (!handoffsByAgent.has(source)) {\n handoffsByAgent.set(source, []);\n }\n handoffsByAgent.get(source)!.push(edge);\n });\n }\n\n // Create handoff tools for each agent\n for (const [agentId, edges] of handoffsByAgent) {\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) continue;\n\n // Create handoff tools for this agent's outgoing edges\n const handoffTools: t.GenericTool[] = [];\n const sourceAgentName = agentContext.name ?? agentId;\n for (const edge of edges) {\n handoffTools.push(\n ...this.createHandoffToolsForEdge(edge, agentId, sourceAgentName)\n );\n }\n\n if (!agentContext.graphTools) {\n agentContext.graphTools = [];\n }\n agentContext.graphTools.push(...handoffTools);\n }\n }\n\n /**\n * Create handoff tools for an edge (handles multiple destinations)\n * @param edge - The graph edge defining the handoff\n * @param sourceAgentId - The ID of the agent that will perform the handoff\n * @param sourceAgentName - The human-readable name of the source agent\n */\n private createHandoffToolsForEdge(\n edge: t.GraphEdge,\n sourceAgentId: string,\n sourceAgentName: string\n ): t.GenericTool[] {\n const tools: t.GenericTool[] = [];\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n\n /** If there's a condition, create a single conditional handoff tool */\n if (edge.condition != null) {\n const toolName = 'conditional_transfer';\n const toolDescription =\n edge.description ?? 'Conditionally transfer control based on state';\n\n /** Check if we have a prompt for handoff input */\n const hasHandoffInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const handoffInputDescription = hasHandoffInput ? edge.prompt : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (rawInput, runtime: ToolRuntime) => {\n const input = rawInput as Record<string, unknown>;\n const state = runtime.state as t.BaseGraphState;\n const toolCallId = runtime.toolCall?.id ?? 'unknown';\n\n /** Evaluated condition */\n const result = edge.condition!(state);\n let destination: string;\n\n if (typeof result === 'boolean') {\n /** If true, use first destination; if false, don't transfer */\n if (!result) return null;\n destination = destinations[0];\n } else if (typeof result === 'string') {\n destination = result;\n } else {\n /** Array of destinations - for now, use the first */\n destination = Array.isArray(result) ? result[0] : destinations[0];\n }\n\n const handoffInstructions = getHandoffInstructions(\n input,\n promptKey,\n hasHandoffInput\n );\n let content = `Conditionally transferred to ${destination}`;\n if (handoffInstructions !== null) {\n content += `\\n\\n${formatHandoffPromptLabel(promptKey)}: ${handoffInstructions}`;\n }\n\n const toolMessage = new ToolMessage({\n content,\n name: toolName,\n tool_call_id: toolCallId,\n additional_kwargs: {\n /** Store destination for programmatic access in handoff detection */\n handoff_destination: destination,\n /** Store source agent name for receiving agent to know who handed off */\n handoff_source_name: sourceAgentName,\n ...(handoffInstructions !== null && {\n [HANDOFF_INSTRUCTIONS_KEY]: handoffInstructions,\n }),\n },\n });\n\n return new Command({\n goto: destination,\n update: { messages: state.messages.concat(toolMessage) },\n graph: Command.PARENT,\n });\n },\n {\n name: toolName,\n schema: hasHandoffInput\n ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: handoffInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n } else {\n /** Create individual tools for each destination */\n for (const destination of destinations) {\n const toolName = `${Constants.LC_TRANSFER_TO_}${destination}`;\n const toolDescription =\n edge.description ?? `Transfer control to agent '${destination}'`;\n\n /** Check if we have a prompt for handoff input */\n const hasHandoffInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const handoffInputDescription = hasHandoffInput\n ? edge.prompt\n : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (rawInput, runtime: ToolRuntime) => {\n const input = rawInput as Record<string, unknown>;\n const toolCallId = runtime.toolCall?.id ?? 'unknown';\n\n const handoffInstructions = getHandoffInstructions(\n input,\n promptKey,\n hasHandoffInput\n );\n let content = `Successfully transferred to ${destination}`;\n if (handoffInstructions !== null) {\n content += `\\n\\n${formatHandoffPromptLabel(promptKey)}: ${handoffInstructions}`;\n }\n\n const toolMessage = new ToolMessage({\n content,\n name: toolName,\n tool_call_id: toolCallId,\n additional_kwargs: {\n /** Store source agent name for receiving agent to know who handed off */\n handoff_source_name: sourceAgentName,\n ...(handoffInstructions !== null && {\n [HANDOFF_INSTRUCTIONS_KEY]: handoffInstructions,\n }),\n },\n });\n\n const state = runtime.state as t.BaseGraphState;\n\n /**\n * For parallel handoff support:\n * Build messages that include ONLY this tool call's context.\n * This prevents errors when LLM calls multiple transfers simultaneously -\n * each destination gets a valid AIMessage with matching tool_call and tool_result.\n *\n * Strategy:\n * 1. Find the AIMessage containing this tool call\n * 2. Create a filtered AIMessage with ONLY this tool_call\n * 3. Include all messages before the AIMessage plus the filtered pair\n */\n const messages = state.messages;\n let filteredMessages = messages;\n let aiMessageIndex = -1;\n\n /** Find the AIMessage containing this tool call */\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg.getType() === 'ai') {\n const aiMsg = msg as AIMessage;\n const hasThisCall = aiMsg.tool_calls?.some(\n (tc) => tc.id === toolCallId\n );\n if (hasThisCall === true) {\n aiMessageIndex = i;\n break;\n }\n }\n }\n\n if (aiMessageIndex >= 0) {\n const originalAiMsg = messages[aiMessageIndex] as AIMessage;\n const thisToolCall = originalAiMsg.tool_calls?.find(\n (tc) => tc.id === toolCallId\n );\n\n if (\n thisToolCall != null &&\n (originalAiMsg.tool_calls?.length ?? 0) > 1\n ) {\n /**\n * Multiple tool calls - create filtered AIMessage with ONLY this call.\n * This ensures valid message structure for parallel handoffs.\n */\n const filteredAiMsg = new AIMessage({\n content: originalAiMsg.content,\n tool_calls: [thisToolCall],\n id: originalAiMsg.id,\n });\n\n filteredMessages = [\n ...messages.slice(0, aiMessageIndex),\n filteredAiMsg,\n toolMessage,\n ];\n } else {\n /** Single tool call - use messages as-is */\n filteredMessages = messages.concat(toolMessage);\n }\n } else {\n /** Fallback - append tool message */\n filteredMessages = messages.concat(toolMessage);\n }\n\n return new Command({\n goto: destination,\n update: { messages: filteredMessages },\n graph: Command.PARENT,\n });\n },\n {\n name: toolName,\n schema: hasHandoffInput\n ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: handoffInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n }\n }\n\n return tools;\n }\n\n /**\n * Create a complete agent subgraph (similar to createReactAgent)\n */\n private createAgentSubgraph(agentId: string): t.CompiledAgentWorfklow {\n /** This is essentially the same as `createAgentNode` from `StandardGraph` */\n return this.createAgentNode(agentId);\n }\n\n /**\n * Detects if the current agent is receiving a handoff and processes the messages accordingly.\n * Returns filtered messages with the transfer tool call/message removed, plus any instructions,\n * source agent, and parallel sibling information extracted from the transfer.\n *\n * Supports both single handoffs (last message is the transfer) and parallel handoffs\n * (multiple transfer ToolMessages, need to find the one targeting this agent).\n *\n * @param messages - Current state messages\n * @param agentId - The agent ID to check for handoff reception\n * @returns Object with filtered messages, extracted instructions, source agent, and parallel siblings\n */\n private processHandoffReception(\n messages: BaseMessage[],\n agentId: string\n ): {\n filteredMessages: BaseMessage[];\n instructions: string | null;\n sourceAgentName: string | null;\n parallelSiblings: string[];\n parallelGroupId?: number;\n } | null {\n if (messages.length === 0) return null;\n\n /**\n * A handoff is active only while resolving the most recent assistant\n * tool-call round. Older transfer results remain in conversation history,\n * but must not be reused when this agent is reached later through a direct\n * edge or cycle.\n */\n const activeTransferToolCallIds = new Set<string>();\n let activeToolMessageStartIndex = messages.length;\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg.getType() === 'tool') continue;\n\n if (msg.getType() === 'ai') {\n const aiMsg = msg as AIMessage | AIMessageChunk;\n for (const toolCall of aiMsg.tool_calls ?? []) {\n if (\n toolCall.id != null &&\n (toolCall.name.startsWith(Constants.LC_TRANSFER_TO_) ||\n toolCall.name === 'conditional_transfer')\n ) {\n activeTransferToolCallIds.add(toolCall.id);\n }\n }\n activeToolMessageStartIndex = i + 1;\n }\n break;\n }\n\n if (activeTransferToolCallIds.size === 0) return null;\n\n /**\n * Search for a transfer ToolMessage targeting this agent.\n * For parallel handoffs, multiple transfer messages may exist - find ours.\n * Search backwards from the end to find the most recent transfer to this agent.\n */\n let toolMessage: ToolMessage | null = null;\n let toolMessageIndex = -1;\n\n for (let i = messages.length - 1; i >= activeToolMessageStartIndex; i--) {\n const msg = messages[i];\n if (msg.getType() !== 'tool') continue;\n\n const candidateMsg = msg as ToolMessage;\n const toolName = candidateMsg.name;\n\n if (\n typeof toolName !== 'string' ||\n !activeTransferToolCallIds.has(candidateMsg.tool_call_id)\n ) {\n continue;\n }\n\n /** Check for standard transfer pattern */\n const isTransferMessage = toolName.startsWith(Constants.LC_TRANSFER_TO_);\n const isConditionalTransfer = toolName === 'conditional_transfer';\n\n if (!isTransferMessage && !isConditionalTransfer) continue;\n\n /** Extract destination from tool name or additional_kwargs */\n let destinationAgent: string | null = null;\n\n if (isTransferMessage) {\n destinationAgent = toolName.replace(Constants.LC_TRANSFER_TO_, '');\n } else if (isConditionalTransfer) {\n const handoffDest = candidateMsg.additional_kwargs.handoff_destination;\n destinationAgent = typeof handoffDest === 'string' ? handoffDest : null;\n }\n\n /** Check if this transfer targets our agent */\n if (destinationAgent === agentId) {\n toolMessage = candidateMsg;\n toolMessageIndex = i;\n break;\n }\n }\n\n /** No transfer targeting this agent found */\n if (toolMessage === null || toolMessageIndex < 0) return null;\n\n /** Extract instructions from the ToolMessage content */\n const contentStr =\n typeof toolMessage.content === 'string'\n ? toolMessage.content\n : serializeToolContentBounded(\n toolMessage.content,\n HARD_MAX_TOOL_RESULT_CHARS\n );\n\n const structuredInstructions =\n toolMessage.additional_kwargs[HANDOFF_INSTRUCTIONS_KEY];\n const instructions =\n typeof structuredInstructions === 'string'\n ? structuredInstructions.trim()\n : extractLegacyHandoffInstructions(\n contentStr,\n this.handoffPromptLabels.get(agentId)\n );\n\n /** Extract source agent name from additional_kwargs */\n const handoffSourceName = toolMessage.additional_kwargs.handoff_source_name;\n const sourceAgentName =\n typeof handoffSourceName === 'string' ? handoffSourceName : null;\n\n /** Extract parallel siblings (set by ToolNode for parallel handoffs) */\n const rawSiblings = toolMessage.additional_kwargs.handoff_parallel_siblings;\n const siblingIds: string[] = Array.isArray(rawSiblings)\n ? rawSiblings.filter((s): s is string => typeof s === 'string')\n : [];\n /** Convert IDs to display names */\n const parallelSiblings = siblingIds.map((id) => {\n const ctx = this.agentContexts.get(id);\n return ctx?.name ?? id;\n });\n const storedParallelGroupId =\n toolMessage.additional_kwargs[Constants.HANDOFF_GROUP_ID];\n const parallelGroupId = isValidHandoffGroupId(storedParallelGroupId)\n ? storedParallelGroupId\n : undefined;\n\n /** Get the tool_call_id to find and filter the AI message's tool call */\n const toolCallId = toolMessage.tool_call_id;\n\n /**\n * Collect all transfer tool_call_ids to filter out.\n * For parallel handoffs, we filter ALL transfer messages (not just ours)\n * to give the receiving agent a clean context without handoff noise.\n */\n const transferToolCallIds = new Set<string>([toolCallId]);\n for (const msg of messages) {\n if (msg.getType() === 'tool') {\n const tm = msg as ToolMessage;\n const tName = tm.name;\n if (\n typeof tName === 'string' &&\n (tName.startsWith(Constants.LC_TRANSFER_TO_) ||\n tName === 'conditional_transfer')\n ) {\n transferToolCallIds.add(tm.tool_call_id);\n }\n } else if (msg.getType() === 'ai') {\n const aiMsg = msg as AIMessage | AIMessageChunk;\n for (const toolCall of aiMsg.tool_calls ?? []) {\n if (\n toolCall.id != null &&\n (toolCall.name.startsWith(Constants.LC_TRANSFER_TO_) ||\n toolCall.name === 'conditional_transfer')\n ) {\n transferToolCallIds.add(toolCall.id);\n }\n }\n }\n }\n\n /** Filter out all transfer messages */\n const filteredMessages: BaseMessage[] = [];\n\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n const msgType = msg.getType();\n\n /** Skip transfer ToolMessages */\n if (msgType === 'tool') {\n const tm = msg as ToolMessage;\n if (transferToolCallIds.has(tm.tool_call_id)) {\n continue;\n }\n }\n\n if (msgType === 'ai') {\n /** Check if this AI message contains any transfer tool calls */\n const aiMsg = msg as AIMessage | AIMessageChunk;\n const toolCalls = aiMsg.tool_calls;\n\n if (toolCalls && toolCalls.length > 0) {\n /** Filter out all transfer tool calls */\n const remainingToolCalls = toolCalls.filter(\n (tc) => tc.id == null || !transferToolCallIds.has(tc.id)\n );\n\n const hasTransferCalls = remainingToolCalls.length < toolCalls.length;\n\n if (hasTransferCalls) {\n if (\n remainingToolCalls.length > 0 ||\n (typeof aiMsg.content === 'string' && aiMsg.content.trim())\n ) {\n /** Keep the message but without transfer tool calls */\n const filteredAiMsg = new AIMessage({\n content: aiMsg.content,\n tool_calls: remainingToolCalls,\n id: aiMsg.id,\n });\n filteredMessages.push(filteredAiMsg);\n }\n /** If no remaining content or tool calls, skip this message entirely */\n continue;\n }\n }\n }\n\n /** Keep all other messages */\n filteredMessages.push(msg);\n }\n\n return {\n filteredMessages,\n instructions,\n sourceAgentName,\n parallelSiblings,\n parallelGroupId,\n };\n }\n\n /**\n * Create the multi-agent workflow with dynamic handoffs\n */\n override createWorkflow(): t.CompiledMultiAgentWorkflow {\n this.hasCompiledCheckpointer = this.compileOptions?.checkpointer != null;\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: (a, b) => {\n if (!this.messages.length) {\n this.startIndex = a.length + b.length;\n }\n const result = messagesStateReducer(a, b);\n this.messages = result;\n return result;\n },\n default: () => [],\n }),\n /** Channel for passing filtered messages to agents when excludeResults is true */\n agentMessages: Annotation<BaseMessage[]>({\n /** Replaces state entirely */\n reducer: (a, b) => b,\n default: () => [],\n }),\n });\n\n const builder = new StateGraph(StateAnnotation);\n\n // Add all agents as complete subgraphs\n for (const [agentId] of this.agentContexts) {\n // Get all possible destinations for this agent\n const handoffDestinations = new Set<string>();\n const directDestinations = new Set<string>();\n\n // Check handoff edges for destinations\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (sources.includes(agentId) === true) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((dest) => handoffDestinations.add(dest));\n }\n }\n\n // Check direct edges for destinations\n for (const edge of this.directEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (sources.includes(agentId) === true) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((dest) => directDestinations.add(dest));\n }\n }\n\n /** Check if this agent has BOTH handoff and direct edges */\n const hasHandoffEdges = handoffDestinations.size > 0;\n const hasDirectEdges = directDestinations.size > 0;\n const needsCommandRouting = hasHandoffEdges && hasDirectEdges;\n\n /** Collect all possible destinations for this agent */\n const allDestinations = new Set([\n ...handoffDestinations,\n ...directDestinations,\n ]);\n if (handoffDestinations.size > 0 || directDestinations.size === 0) {\n allDestinations.add(END);\n }\n\n /** Agent subgraph (includes agent + tools) */\n const agentSubgraph = this.createAgentSubgraph(agentId);\n\n /** Wrapper function that handles agentMessages channel, handoff reception, and conditional routing */\n const agentWrapper = async (\n state: t.MultiAgentGraphState,\n config?: LangGraphRunnableConfig\n ): Promise<t.MultiAgentGraphState | Command> => {\n let result: t.MultiAgentGraphState;\n\n /**\n * Check if this agent is receiving a handoff.\n * If so, filter out the transfer messages and inject instructions as preamble.\n * This prevents the receiving agent from seeing the transfer as \"completed work\"\n * and prematurely producing an end token.\n */\n const handoffContext = this.processHandoffReception(\n state.messages,\n agentId\n );\n const agentContext = this.agentContexts.get(agentId);\n\n if (\n handoffContext?.sourceAgentName != null &&\n handoffContext.sourceAgentName !== ''\n ) {\n agentContext?.setHandoffContext(\n handoffContext.sourceAgentName,\n handoffContext.parallelSiblings\n );\n } else {\n agentContext?.clearHandoffContext();\n }\n\n if (handoffContext !== null) {\n const { filteredMessages, instructions, parallelGroupId } =\n handoffContext;\n\n /** Build messages for the receiving agent */\n let messagesForAgent = filteredMessages;\n\n /**\n * If there are instructions, inject them as a HumanMessage to\n * ground the receiving agent.\n *\n * When the last filtered message is a ToolMessage (e.g. from a\n * non-handoff tool the router called before handing off), a\n * synthetic AIMessage is inserted first to satisfy the\n * tool → assistant role ordering required by chat APIs. Without\n * this bridge, appending a HumanMessage directly after a\n * ToolMessage causes \"400 Unexpected role 'user' after role\n * 'tool'\" errors (see issue #54).\n */\n const hasInstructions = instructions !== null && instructions !== '';\n if (hasInstructions) {\n const lastMsg =\n filteredMessages.length > 0\n ? filteredMessages[filteredMessages.length - 1]\n : null;\n\n if (lastMsg != null && lastMsg.getType() === 'tool') {\n messagesForAgent = [\n ...filteredMessages,\n new AIMessage(\n `[Processed tool result and transferring to ${agentId}]`\n ),\n buildRoutingPrompt(instructions),\n ];\n } else {\n messagesForAgent = [\n ...filteredMessages,\n buildRoutingPrompt(instructions),\n ];\n }\n }\n\n /** Update token map if we have a token counter */\n if (agentContext?.tokenCounter && hasInstructions) {\n const freshTokenMap: Record<string, number> = {};\n for (\n let i = 0;\n i < Math.min(filteredMessages.length, this.startIndex);\n i++\n ) {\n const tokenCount = agentContext.indexTokenCountMap[i];\n if (tokenCount !== undefined) {\n freshTokenMap[i] = tokenCount;\n }\n }\n /** Add tokens for the bridge AIMessage + instructions HumanMessage */\n for (\n let i = filteredMessages.length;\n i < messagesForAgent.length;\n i++\n ) {\n freshTokenMap[i] = agentContext.tokenCounter(messagesForAgent[i]);\n }\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: messagesForAgent,\n };\n result = await agentSubgraph.invoke(\n transformedState,\n withHandoffGroupMetadata(config, parallelGroupId)\n );\n result = {\n ...result,\n agentMessages: [],\n };\n } else if (\n state.agentMessages != null &&\n state.agentMessages.length > 0\n ) {\n /**\n * When using agentMessages (excludeResults=true), we need to update\n * the token map to account for the new prompt message\n */\n if (agentContext && agentContext.tokenCounter) {\n /** The agentMessages contains:\n * 1. Filtered messages (0 to startIndex) - already have token counts\n * 2. New prompt message - needs token counting\n */\n const freshTokenMap: Record<string, number> = {};\n\n /** Copy existing token counts for filtered messages (0 to startIndex) */\n for (let i = 0; i < this.startIndex; i++) {\n const tokenCount = agentContext.indexTokenCountMap[i];\n if (tokenCount !== undefined) {\n freshTokenMap[i] = tokenCount;\n }\n }\n\n /** Calculate tokens only for the new prompt message (last message) */\n const promptMessageIndex = state.agentMessages.length - 1;\n if (promptMessageIndex >= this.startIndex) {\n const promptMessage = state.agentMessages[promptMessageIndex];\n freshTokenMap[promptMessageIndex] =\n agentContext.tokenCounter(promptMessage);\n }\n\n /** Update the agent's token map with instructions added */\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n /** Temporary state with messages replaced by `agentMessages` */\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: state.agentMessages,\n };\n result = await agentSubgraph.invoke(transformedState, config);\n result = {\n ...result,\n /** Clear agentMessages for next agent */\n agentMessages: [],\n };\n } else {\n result = await agentSubgraph.invoke(state, config);\n }\n\n /** If agent has both handoff and direct edges, use Command for exclusive routing */\n if (needsCommandRouting) {\n /** Check if a handoff occurred */\n const lastMessage = result.messages[\n result.messages.length - 1\n ] as BaseMessage | null;\n if (\n lastMessage != null &&\n lastMessage.getType() === 'tool' &&\n typeof lastMessage.name === 'string' &&\n lastMessage.name.startsWith(Constants.LC_TRANSFER_TO_)\n ) {\n /** Handoff occurred - extract destination and navigate there exclusively */\n const handoffDest = lastMessage.name.replace(\n Constants.LC_TRANSFER_TO_,\n ''\n );\n return new Command({\n update: result,\n goto: handoffDest,\n });\n } else {\n /** No handoff - proceed with direct edges */\n const directDests = Array.from(directDestinations);\n if (directDests.length === 1) {\n return new Command({\n update: result,\n goto: directDests[0],\n });\n } else if (directDests.length > 1) {\n /** Multiple direct destinations - they'll run in parallel */\n return new Command({\n update: result,\n goto: directDests,\n });\n }\n }\n }\n\n /** No special routing needed - return state normally */\n return result;\n };\n\n /** Wrapped agent as a node with its possible destinations */\n builder.addNode(agentId, agentWrapper, {\n ends: Array.from(allDestinations),\n });\n }\n\n // Add starting edges for all starting nodes\n for (const startNode of this.startingNodes) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(START, startNode);\n }\n\n /**\n * Add direct edges for automatic transitions\n * Group edges by destination to handle fan-in scenarios\n */\n const edgesByDestination = new Map<string, t.GraphEdge[]>();\n\n for (const edge of this.directEdges) {\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const destination of destinations) {\n if (!edgesByDestination.has(destination)) {\n edgesByDestination.set(destination, []);\n }\n edgesByDestination.get(destination)!.push(edge);\n }\n }\n\n for (const [destination, edges] of edgesByDestination) {\n /** Checks if this is a fan-in scenario with prompt instructions */\n const edgesWithPrompt = edges.filter(\n (edge) => edge.prompt != null && edge.prompt !== ''\n );\n\n if (edgesWithPrompt.length > 0) {\n /**\n * Single wrapper node for destination (Fan-in with prompt)\n */\n const wrapperNodeId = `fan_in_${destination}_prompt`;\n /**\n * First edge's `prompt`\n * (they should all be the same for fan-in)\n */\n const prompt = edgesWithPrompt[0].prompt;\n /**\n * First edge's `excludeResults` flag\n * (they should all be the same for fan-in)\n */\n const excludeResults = edgesWithPrompt[0].excludeResults;\n\n builder.addNode(wrapperNodeId, async (state: t.BaseGraphState) => {\n let promptText: string | undefined;\n let effectiveExcludeResults = excludeResults;\n\n if (typeof prompt === 'function') {\n promptText = await prompt(state.messages, this.startIndex);\n } else if (prompt != null) {\n if (prompt.includes('{results}')) {\n const resultsMessages = state.messages.slice(this.startIndex);\n const resultsString = getBufferString(resultsMessages);\n const promptTemplate = PromptTemplate.fromTemplate(prompt);\n const result = await promptTemplate.invoke({\n results: resultsString,\n });\n promptText = result.value;\n effectiveExcludeResults =\n excludeResults !== false && promptText !== '';\n } else {\n promptText = prompt;\n }\n }\n\n if (promptText != null && promptText !== '') {\n if (\n effectiveExcludeResults == null ||\n effectiveExcludeResults === false\n ) {\n return {\n messages: [buildRoutingPrompt(promptText)],\n };\n }\n\n /** When `excludeResults` is true, use agentMessages channel\n * to pass filtered messages + prompt to the destination agent\n */\n const filteredMessages = state.messages.slice(0, this.startIndex);\n const promptMessage = buildRoutingPrompt(promptText);\n return {\n messages: [promptMessage],\n agentMessages: messagesStateReducer(filteredMessages, [\n promptMessage,\n ]),\n };\n }\n\n /** No prompt needed, return empty update */\n return {};\n });\n\n /** Add edges from all sources to the wrapper, then wrapper to destination */\n for (const edge of edges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n for (const source of sources) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(source, wrapperNodeId);\n }\n }\n\n /** Single edge from wrapper to destination */\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(wrapperNodeId, destination);\n } else {\n /** No prompt instructions, add direct edges (skip if source uses Command routing) */\n for (const edge of edges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n for (const source of sources) {\n /** Check if this source node has both handoff and direct edges */\n const sourceHandoffEdges = this.handoffEdges.filter((e) => {\n const eSources = Array.isArray(e.from) ? e.from : [e.from];\n return eSources.includes(source);\n });\n const sourceDirectEdges = this.directEdges.filter((e) => {\n const eSources = Array.isArray(e.from) ? e.from : [e.from];\n return eSources.includes(source);\n });\n\n /** Skip adding edge if source uses Command routing (has both types) */\n if (sourceHandoffEdges.length > 0 && sourceDirectEdges.length > 0) {\n continue;\n }\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(source, destination);\n }\n }\n }\n }\n\n return builder.compile(this.compileOptions as unknown as never);\n }\n}\n"],"mappings":";;;;;;;;;;;AA0BA,MAAM,+BAA+B;AACrC,MAAM,2BAA2B;;;;;;;;AASjC,SAAS,mBAAmB,SAA+B;CACzD,OAAO,IAAI,aAAa;EACtB;EACA,mBAAmB;GAAE,MAAM;GAAQ,QAAQ;GAAM,QAAQ;EAAU;CACrE,CAAC;AACH;AAEA,SAAS,uBACP,OACA,WACA,iBACe;CACf,IACE,CAAC,mBACD,CAAC,OAAO,UAAU,eAAe,KAAK,OAAO,SAAS,GAEtD,OAAO;CAET,MAAM,QAAQ,MAAM;CACpB,OAAO,OA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,IAAI,IAAI,EAAE,OAAO,CAAC,EAAE,IAAI,EAAA,CACzC,SAAS,MAAM;KACjC,CAAC;;KAGD,IAAI,mBAAmB,SAAS,KAAK,kBAAkB,SAAS,GAC9D;;KAKF,QAAQ,QAAQ,QAAQ,WAAW;IACrC;GACF;EAEJ;EAEA,OAAO,QAAQ,QAAQ,KAAK,cAAkC;CAChE;AACF"}
package/dist/esm/main.mjs CHANGED
@@ -25,7 +25,7 @@ import "./messages/index.mjs";
25
25
  import { joinKeys, resetIfNotEmpty } from "./utils/graph.mjs";
26
26
  import { isAnthropicLike, isGoogleLike, isOpenAILike } from "./utils/llm.mjs";
27
27
  import { handleServerToolResult, handleToolCallChunks, handleToolCalls, toolResultTypes } from "./tools/handlers.mjs";
28
- import { INTENT_ARG, INTENT_DESCRIPTION, INTENT_PROPERTY, applyOutcome, isIntentLabelProperty, outcomeFieldsFromResult, readIntent, readOutcomeFields, resolveToolOutcome, stripIntent, withIntent } from "./tools/intentArg.mjs";
28
+ import { INTENT_ARG, INTENT_DESCRIPTION, INTENT_LABEL_MARKER, INTENT_PROPERTY, applyOutcome, isIntentLabelProperty, outcomeFieldsFromResult, readIntent, readOutcomeFields, resolveToolOutcome, stripIntent, withIntent, withoutIntent } from "./tools/intentArg.mjs";
29
29
  import { ChatModelStreamHandler, SDK_STREAM_DISPATCH, createContentAggregator, dispatchesChatModelStream, getChunkContent } from "./stream.mjs";
30
30
  import { HandlerRegistry, LLMStreamHandler, ModelEndHandler, TestChatStreamHandler, TestLLMStreamHandler, ToolEndHandler, composeEventHandlers, createMetadataAggregator } from "./events.mjs";
31
31
  import { createHandlers } from "./utils/handlers.mjs";
@@ -102,4 +102,4 @@ import { Runnable, RunnableLambda, RunnableSequence } from "./langchain/runnable
102
102
  import { DynamicStructuredTool, StructuredTool, Tool, tool } from "./langchain/tools.mjs";
103
103
  import "./langchain/index.mjs";
104
104
  import { BaseCheckpointSaver, Command, INTERRUPT, MemorySaver, interrupt, isInterrupted } from "@langchain/langgraph";
105
- export { AIMessage, AIMessageChunk, ANTHROPIC_TOOL_TOKEN_MULTIPLIER, AgentSession, BASH_SHELL_GUIDANCE, BaseCheckpointSaver, BaseMessage, BaseMessageChunk, BashExecutionToolDefinition, BashExecutionToolDescription, BashExecutionToolName, BashExecutionToolSchema, BashProgrammaticToolCallingDefinition, BashProgrammaticToolCallingDescription, BashProgrammaticToolCallingName, BashProgrammaticToolCallingSchema, BashToolOutputReferencesGuide, CALIBRATION_RATIO_MAX, CALIBRATION_RATIO_MIN, CLOUDFLARE_BASH_CODING_TOOL_NAMES, CLOUDFLARE_CODING_TOOL_NAMES, CODE_API_AUTHORIZATION_ERROR_MESSAGE, CODE_API_EXECUTION_FAILED_ERROR_MESSAGE, CODE_API_INVALID_REQUEST_ERROR_MESSAGE, CODE_API_RATE_LIMITED_ERROR_MESSAGE, CODE_API_UNAVAILABLE_ERROR_MESSAGE, CODE_ARTIFACT_PATH_GUIDANCE, CODE_EXECUTION_TOOLS, Calculator, CalculatorSchema, CalculatorToolDefinition, CalculatorToolDescription, CalculatorToolName, Callback, ChatModelStreamHandler, ChatOpenRouter, CloudflareBashExecutionToolDescription, CloudflareCodeExecutionToolDescription, CodeApiRequestError, CodeExecutionToolDefinition, CodeExecutionToolDescription, CodeExecutionToolName, CodeExecutionToolSchema, Command, CommonEvents, CompileCheckToolName, Constants, ContentTypes, CustomOpenAIClient, DATE_RANGE, DEFAULT_CONTEXT_PRUNING_SETTINGS, DEFAULT_COUNTRY_DESCRIPTION, DEFAULT_HOOK_TIMEOUT_MS, DEFAULT_MAX_SEALS, DEFAULT_PROMPT_CACHE_TTL, DEFAULT_QUERY_DESCRIPTION, DEFAULT_RECURSION_LIMIT, DEFAULT_RESERVE_RATIO, DEFAULT_RETAIN_RECENT_TURNS, DEFAULT_TOOL_TOKEN_MULTIPLIER, DynamicStructuredTool, EnvVar, FAILED_EXECUTION_FILE_REMINDER, FakeChatModel, Graph, GraphEvents, GraphNodeActions, GraphNodeKeys, HARD_MAX_TOOL_RESULT_CHARS, HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE, HOOK_EVENTS, HOOK_INJECTED_MESSAGES_CAPABLE, HOOK_PREEMPT_BOUNDARY_CAPABLE, HandlerRegistry, HookRegistry, HumanMessage, IMAGE_TOKEN_SAFETY_MARGIN, INTENT_ARG, INTENT_DESCRIPTION, INTENT_PROPERTY, INTERRUPT, JsonlSessionStore, LLMStreamHandler, LOCAL_CODING_BUNDLE_NAMES, LOCAL_CODING_TOOL_NAMES, LOCAL_SPAWN_TIMEOUT_MS, LocalBashExecutionToolDescription, LocalCodeExecutionToolDescription, LocalEditFileToolName, LocalEditFileToolSchema, LocalFileCheckpointerImpl, LocalGlobSearchToolName, LocalGlobSearchToolSchema, LocalGrepSearchToolName, LocalGrepSearchToolSchema, LocalListDirectoryToolName, LocalListDirectoryToolSchema, LocalReadFileToolSchema, LocalWriteFileToolName, LocalWriteFileToolSchema, MAX_CACHE_SIZE, MAX_PATTERN_LENGTH, MemorySaver, ModelEndHandler, MultiAgentGraph, ORIGINAL_CONTENT_MAX_CHARS, PREDECESSOR_HANDOFF_CUE, PREEMPT_BOUNDARY_HOOK_TIMEOUT_MS, ProgrammaticToolCallingDefinition, ProgrammaticToolCallingDescription, ProgrammaticToolCallingName, ProgrammaticToolCallingSchema, PromptTemplate, Providers, REMOVE_ALL_MESSAGES, REPLY_PRIMER_TOKENS, ReadFileToolDefinition, ReadFileToolDescription, ReadFileToolName, ReadFileToolSchema, Run, Runnable, RunnableCallable, RunnableLambda, RunnableSequence, SDK_STREAM_DISPATCH, STATEFUL_BASH_NOTE, STATEFUL_ENV_NOTE, SessionManager, SkillToolDefinition, SkillToolDescription, SkillToolName, SkillToolSchema, StandardGraph, StatefulBashExecutionToolDescription, StatefulCodeExecutionToolDescription, StepTypes, StructuredTool, SubagentExecutor, SubagentToolDefinition, SubagentToolDescription, SubagentToolName, SubagentToolSchema, SystemMessage, TMP_SCRATCH_OUTPUT_REMINDER, TestChatStreamHandler, TestLLMStreamHandler, TitleMethod, TokenEncoderManager, Tool, ToolCallTypes, ToolEndHandler, ToolMessage, ToolNode, ToolSearchToolDefinition, ToolSearchToolDescription, ToolSearchToolName, ToolSearchToolSchema, WebSearchToolDefinition, WebSearchToolDescription, WebSearchToolName, WebSearchToolSchema, _createBashProgramForTests, _resetLocalEngineWarningsForTests, _resetRipgrepCacheForTests, _resetSyntaxCheckProbeCacheForTests, _resetUnrecognizedTriggerWarnings, addBedrockCacheControl, addBedrockTailCacheControl, addCacheControl, addCacheControlToStablePrefixMessages, addTailCacheControl, appendCodeSessionFileSummary, appendFailedExecutionFileReminder, appendPredecessorHandoffCue, appendTmpScratchReminder, applyContextPruning, applyEdit, applyOutcome, applyPreToolUseHooksForBridge, apportionTokenCounts, askUserQuestion, attemptInvoke, bashAstFindingsToErrors, buildAnthropicCacheControl, buildBashExecutionToolDescription, buildBashExecutionToolSchema, buildBedrockCachePoint, buildChildInputs, buildCodeApiExecutionErrorMessage, buildCodeApiHttpErrorMessage, buildCodeExecutionToolDescription, buildCodeExecutionToolSchema, buildSandboxRuntimeConfig, buildSubagentToolParams, calculateMaxToolCallInputChars, calculateMaxToolResultChars, calculateMaxTotalToolOutputSize, calculateTotalTokens, canSealPreempt, checkValidNumber, clampCalibrationRatio, classifyAttachment, clientExecTimeoutMs, clientFsTimeoutMs, cloneMessage, coalesceAdjacentUserTurns, composeEventHandlers, convertInjectedMessages, convertMessagesToContent, countNestedGroups, countrySchema, createAgentSession, createBashExecutionTool, createBashProgrammaticToolCallingSchema, createBashProgrammaticToolCallingTool, createCloudflareBashExecutionTool, createCloudflareBashProgrammaticToolCallingTool, createCloudflareBridgeRuntime, createCloudflareCodeExecutionTool, createCloudflareCodingToolBundle, createCloudflareCodingTools, createCloudflareExecutionTool, createCloudflareLocalExecutionConfig, createCloudflareProgrammaticToolCallingTool, createCloudflareWorkspaceFS, createCodeExecutionTool, createCompileCheckTool, createCompileCheckToolDefinition, createContentAggregator, createFakeStreamingLLM, createHandlers, createLocalBashExecutionTool, createLocalBashProgrammaticToolCallingTool, createLocalCodeExecutionTool, createLocalCodingToolBundle, createLocalCodingToolDefinitions, createLocalCodingToolRegistry, createLocalCodingTools, createLocalEditFileTool, createLocalFileCheckpointer, createLocalGlobSearchTool, createLocalGrepSearchTool, createLocalListDirectoryTool, createLocalProgrammaticToolCallingTool, createLocalReadFileTool, createLocalWriteFileTool, createMetadataAggregator, createProgrammaticToolCallingSchema, createProgrammaticToolCallingTool, createPruneMessages, createRemoveAllMessage, createRunHandlers, createSchemaOnlyTool, createSchemaOnlyTools, createSearchTool, createSubagentToolDefinition, createTokenCounter, createToolErrorOwnership, createToolPolicyHook, createToolSearch, createWorkspacePolicyHook, dateSchema, decodeFile, defaultOmitOptions, deserializeMessage, dispatchesChatModelStream, emptyOutputMessage, encodeFile, encodingForModel, enforceOriginalContentCap, ensureThinkingBlockInMessages, escapeRegexSpecialChars, estimateAnthropicImageTokens, estimateDocumentBlockTokens, estimateImageBlockTokens, estimateOpenAIImageTokens, estimateTimedMediaBlockTokens, execWithClientTimeout, executeCloudflareBash, executeCloudflareCode, executeHooks, executeLocalBash, executeLocalBashWithArgs, executeLocalCode, executeParallelSearches, executeTools, extractErrorMessage, extractImageDimensions, extractMcpServerName, extractTextFromContent, extractToolDiscoveries, extractUsedBashToolNames, extractUsedToolNames, fetchSessionFiles, filterBashToolsByUsage, filterSubagentResult, filterToolsByUsage, findLastIndex, foldToolBlocksForToollessAgent, formatAgentMessages, formatAnthropicArtifactContent, formatAnthropicMessage, formatArtifactPayload, formatCloudflareOutput, formatCompletedResponse, formatContentStrings, formatFromLangChain, formatLangChainMessages, formatMediaMessage, formatMessage, formatServerListing, formatSkillCatalog, getAvailableMcpServers, getBaseToolName, getBufferString, getChatModelClass, getChunkContent, getCloudflareWorkspaceRoot, getCodeBaseURL, getContextOverflowInfo, getConverseOverrideMessage, getDeferredToolsListing, getLocalCwd, getLocalSessionId, getMaxOutputTokensKey, getMessageId, getMessagesWithinTokenLimit, getReadRoots, getSpawn, getTokenCountForMessage, getWorkspaceFS, getWorkspaceRoots, getWriteRoots, handleServerToolResult, handleToolCallChunks, handleToolCalls, hasNestedQuantifier, hasNestedQuantifiers, hasToolSearchInCurrentTurn, hasUnsafeStructuredSerialization, imageAttachmentContent, imagesSchema, initializeModel, interrupt, isAIMessage, isAnthropicLike, isBaseMessage, isContextOverflowError, isDangerousPattern, isFromAnyMcpServer, isFromMcpServer, isGoogleLike, isIntentLabelProperty, isInterrupted, isLegacyConvertible, isLikelyContextOverflowError, isOpenAILike, isPresent, isSyntheticProviderContextMessage, isThinkingEnabled, isToolMessage, isZodSchema, joinKeys, labelContentByAgent, locateEdit, makeIsDeferred, makeRequest, maskConsumedToolResults, matchesQuery, messagesStateReducer, modifyDeltaProperties, newsSchema, normalizeBashToolResultsForReplay, normalizeCodeApiRequestError, normalizeServerFilter, normalizeToBashIdentifier, normalizeToPythonIdentifier, outcomeFieldsFromResult, parseBooleanEnv, partitionAndMarkAnthropicToolCache, performLocalSearch, preFlightTruncateToolCallInputs, preFlightTruncateToolResults, projectAgentContextUsage, projectAnthropicArtifactContent, projectArtifactPayload, projectCacheControlledToolOutputsToText, projectComputerCallOutputsToText, projectOpenAIChatToolMessageContent, projectOpenAIResponsesToolMessageContent, projectOpenAIToolMessageContent, projectOpenRouterToolMessageContent, projectSingleTextToolOutputsToText, projectStructuredToolOutputsToText, projectToolCallInputs, projectToolStreamContentForProvider, querySchema, readIntent, readOutcomeFields, removePredecessorHandoffCue, repairOrphanedToolMessages, resetIfNotEmpty, resolveBedrockPromptCacheTtl, resolveCloudflareSandbox, resolveCodeApiAuthHeaders, resolveContextPruningSettings, resolveLocalExecutionConfig, resolveLocalExecutionTools, resolveLocalToolRegistry, resolveLocalToolsForBinding, resolvePromptCacheTtl, resolveSearchOutcome, resolveSubagentConfigs, resolveToolOutcome, resolveWorkspacePath, resolveWorkspacePathSafe, runBashAstChecks, runPostEditSyntaxCheck, sanitizeOrphanToolBlocks, sanitizeRegex, serializeMessage, serializeToolCallInput, shellQuote, shiftIndexTokenCountMap, shouldTriggerSummarization, sleep, spawnLocalProcess, splitAtRecencyBoundary, strictAlternationProviders, stripAnthropicCacheControl, stripBedrockCacheControl, stripCodeSessionFileSummary, stripIntent, summarizeEvent, supportsBedrockToolCache, syncBudgetDerivedFields, toJsonSchema, tool, toolResultTypes, toolsCondition, truncateLocalOutput, truncateToolInput, truncateToolResultContent, tryFallbackProviders, unescapeObject, unwrapToolResponse, validateBashCommand, validateCloudflareBashCommand, videosSchema, withClientTimeout, withIntent, withMessageRole };
105
+ export { AIMessage, AIMessageChunk, ANTHROPIC_TOOL_TOKEN_MULTIPLIER, AgentSession, BASH_SHELL_GUIDANCE, BaseCheckpointSaver, BaseMessage, BaseMessageChunk, BashExecutionToolDefinition, BashExecutionToolDescription, BashExecutionToolName, BashExecutionToolSchema, BashProgrammaticToolCallingDefinition, BashProgrammaticToolCallingDescription, BashProgrammaticToolCallingName, BashProgrammaticToolCallingSchema, BashToolOutputReferencesGuide, CALIBRATION_RATIO_MAX, CALIBRATION_RATIO_MIN, CLOUDFLARE_BASH_CODING_TOOL_NAMES, CLOUDFLARE_CODING_TOOL_NAMES, CODE_API_AUTHORIZATION_ERROR_MESSAGE, CODE_API_EXECUTION_FAILED_ERROR_MESSAGE, CODE_API_INVALID_REQUEST_ERROR_MESSAGE, CODE_API_RATE_LIMITED_ERROR_MESSAGE, CODE_API_UNAVAILABLE_ERROR_MESSAGE, CODE_ARTIFACT_PATH_GUIDANCE, CODE_EXECUTION_TOOLS, Calculator, CalculatorSchema, CalculatorToolDefinition, CalculatorToolDescription, CalculatorToolName, Callback, ChatModelStreamHandler, ChatOpenRouter, CloudflareBashExecutionToolDescription, CloudflareCodeExecutionToolDescription, CodeApiRequestError, CodeExecutionToolDefinition, CodeExecutionToolDescription, CodeExecutionToolName, CodeExecutionToolSchema, Command, CommonEvents, CompileCheckToolName, Constants, ContentTypes, CustomOpenAIClient, DATE_RANGE, DEFAULT_CONTEXT_PRUNING_SETTINGS, DEFAULT_COUNTRY_DESCRIPTION, DEFAULT_HOOK_TIMEOUT_MS, DEFAULT_MAX_SEALS, DEFAULT_PROMPT_CACHE_TTL, DEFAULT_QUERY_DESCRIPTION, DEFAULT_RECURSION_LIMIT, DEFAULT_RESERVE_RATIO, DEFAULT_RETAIN_RECENT_TURNS, DEFAULT_TOOL_TOKEN_MULTIPLIER, DynamicStructuredTool, EnvVar, FAILED_EXECUTION_FILE_REMINDER, FakeChatModel, Graph, GraphEvents, GraphNodeActions, GraphNodeKeys, HARD_MAX_TOOL_RESULT_CHARS, HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE, HOOK_EVENTS, HOOK_INJECTED_MESSAGES_CAPABLE, HOOK_PREEMPT_BOUNDARY_CAPABLE, HandlerRegistry, HookRegistry, HumanMessage, IMAGE_TOKEN_SAFETY_MARGIN, INTENT_ARG, INTENT_DESCRIPTION, INTENT_LABEL_MARKER, INTENT_PROPERTY, INTERRUPT, JsonlSessionStore, LLMStreamHandler, LOCAL_CODING_BUNDLE_NAMES, LOCAL_CODING_TOOL_NAMES, LOCAL_SPAWN_TIMEOUT_MS, LocalBashExecutionToolDescription, LocalCodeExecutionToolDescription, LocalEditFileToolName, LocalEditFileToolSchema, LocalFileCheckpointerImpl, LocalGlobSearchToolName, LocalGlobSearchToolSchema, LocalGrepSearchToolName, LocalGrepSearchToolSchema, LocalListDirectoryToolName, LocalListDirectoryToolSchema, LocalReadFileToolSchema, LocalWriteFileToolName, LocalWriteFileToolSchema, MAX_CACHE_SIZE, MAX_PATTERN_LENGTH, MemorySaver, ModelEndHandler, MultiAgentGraph, ORIGINAL_CONTENT_MAX_CHARS, PREDECESSOR_HANDOFF_CUE, PREEMPT_BOUNDARY_HOOK_TIMEOUT_MS, ProgrammaticToolCallingDefinition, ProgrammaticToolCallingDescription, ProgrammaticToolCallingName, ProgrammaticToolCallingSchema, PromptTemplate, Providers, REMOVE_ALL_MESSAGES, REPLY_PRIMER_TOKENS, ReadFileToolDefinition, ReadFileToolDescription, ReadFileToolName, ReadFileToolSchema, Run, Runnable, RunnableCallable, RunnableLambda, RunnableSequence, SDK_STREAM_DISPATCH, STATEFUL_BASH_NOTE, STATEFUL_ENV_NOTE, SessionManager, SkillToolDefinition, SkillToolDescription, SkillToolName, SkillToolSchema, StandardGraph, StatefulBashExecutionToolDescription, StatefulCodeExecutionToolDescription, StepTypes, StructuredTool, SubagentExecutor, SubagentToolDefinition, SubagentToolDescription, SubagentToolName, SubagentToolSchema, SystemMessage, TMP_SCRATCH_OUTPUT_REMINDER, TestChatStreamHandler, TestLLMStreamHandler, TitleMethod, TokenEncoderManager, Tool, ToolCallTypes, ToolEndHandler, ToolMessage, ToolNode, ToolSearchToolDefinition, ToolSearchToolDescription, ToolSearchToolName, ToolSearchToolSchema, WebSearchToolDefinition, WebSearchToolDescription, WebSearchToolName, WebSearchToolSchema, _createBashProgramForTests, _resetLocalEngineWarningsForTests, _resetRipgrepCacheForTests, _resetSyntaxCheckProbeCacheForTests, _resetUnrecognizedTriggerWarnings, addBedrockCacheControl, addBedrockTailCacheControl, addCacheControl, addCacheControlToStablePrefixMessages, addTailCacheControl, appendCodeSessionFileSummary, appendFailedExecutionFileReminder, appendPredecessorHandoffCue, appendTmpScratchReminder, applyContextPruning, applyEdit, applyOutcome, applyPreToolUseHooksForBridge, apportionTokenCounts, askUserQuestion, attemptInvoke, bashAstFindingsToErrors, buildAnthropicCacheControl, buildBashExecutionToolDescription, buildBashExecutionToolSchema, buildBedrockCachePoint, buildChildInputs, buildCodeApiExecutionErrorMessage, buildCodeApiHttpErrorMessage, buildCodeExecutionToolDescription, buildCodeExecutionToolSchema, buildSandboxRuntimeConfig, buildSubagentToolParams, calculateMaxToolCallInputChars, calculateMaxToolResultChars, calculateMaxTotalToolOutputSize, calculateTotalTokens, canSealPreempt, checkValidNumber, clampCalibrationRatio, classifyAttachment, clientExecTimeoutMs, clientFsTimeoutMs, cloneMessage, coalesceAdjacentUserTurns, composeEventHandlers, convertInjectedMessages, convertMessagesToContent, countNestedGroups, countrySchema, createAgentSession, createBashExecutionTool, createBashProgrammaticToolCallingSchema, createBashProgrammaticToolCallingTool, createCloudflareBashExecutionTool, createCloudflareBashProgrammaticToolCallingTool, createCloudflareBridgeRuntime, createCloudflareCodeExecutionTool, createCloudflareCodingToolBundle, createCloudflareCodingTools, createCloudflareExecutionTool, createCloudflareLocalExecutionConfig, createCloudflareProgrammaticToolCallingTool, createCloudflareWorkspaceFS, createCodeExecutionTool, createCompileCheckTool, createCompileCheckToolDefinition, createContentAggregator, createFakeStreamingLLM, createHandlers, createLocalBashExecutionTool, createLocalBashProgrammaticToolCallingTool, createLocalCodeExecutionTool, createLocalCodingToolBundle, createLocalCodingToolDefinitions, createLocalCodingToolRegistry, createLocalCodingTools, createLocalEditFileTool, createLocalFileCheckpointer, createLocalGlobSearchTool, createLocalGrepSearchTool, createLocalListDirectoryTool, createLocalProgrammaticToolCallingTool, createLocalReadFileTool, createLocalWriteFileTool, createMetadataAggregator, createProgrammaticToolCallingSchema, createProgrammaticToolCallingTool, createPruneMessages, createRemoveAllMessage, createRunHandlers, createSchemaOnlyTool, createSchemaOnlyTools, createSearchTool, createSubagentToolDefinition, createTokenCounter, createToolErrorOwnership, createToolPolicyHook, createToolSearch, createWorkspacePolicyHook, dateSchema, decodeFile, defaultOmitOptions, deserializeMessage, dispatchesChatModelStream, emptyOutputMessage, encodeFile, encodingForModel, enforceOriginalContentCap, ensureThinkingBlockInMessages, escapeRegexSpecialChars, estimateAnthropicImageTokens, estimateDocumentBlockTokens, estimateImageBlockTokens, estimateOpenAIImageTokens, estimateTimedMediaBlockTokens, execWithClientTimeout, executeCloudflareBash, executeCloudflareCode, executeHooks, executeLocalBash, executeLocalBashWithArgs, executeLocalCode, executeParallelSearches, executeTools, extractErrorMessage, extractImageDimensions, extractMcpServerName, extractTextFromContent, extractToolDiscoveries, extractUsedBashToolNames, extractUsedToolNames, fetchSessionFiles, filterBashToolsByUsage, filterSubagentResult, filterToolsByUsage, findLastIndex, foldToolBlocksForToollessAgent, formatAgentMessages, formatAnthropicArtifactContent, formatAnthropicMessage, formatArtifactPayload, formatCloudflareOutput, formatCompletedResponse, formatContentStrings, formatFromLangChain, formatLangChainMessages, formatMediaMessage, formatMessage, formatServerListing, formatSkillCatalog, getAvailableMcpServers, getBaseToolName, getBufferString, getChatModelClass, getChunkContent, getCloudflareWorkspaceRoot, getCodeBaseURL, getContextOverflowInfo, getConverseOverrideMessage, getDeferredToolsListing, getLocalCwd, getLocalSessionId, getMaxOutputTokensKey, getMessageId, getMessagesWithinTokenLimit, getReadRoots, getSpawn, getTokenCountForMessage, getWorkspaceFS, getWorkspaceRoots, getWriteRoots, handleServerToolResult, handleToolCallChunks, handleToolCalls, hasNestedQuantifier, hasNestedQuantifiers, hasToolSearchInCurrentTurn, hasUnsafeStructuredSerialization, imageAttachmentContent, imagesSchema, initializeModel, interrupt, isAIMessage, isAnthropicLike, isBaseMessage, isContextOverflowError, isDangerousPattern, isFromAnyMcpServer, isFromMcpServer, isGoogleLike, isIntentLabelProperty, isInterrupted, isLegacyConvertible, isLikelyContextOverflowError, isOpenAILike, isPresent, isSyntheticProviderContextMessage, isThinkingEnabled, isToolMessage, isZodSchema, joinKeys, labelContentByAgent, locateEdit, makeIsDeferred, makeRequest, maskConsumedToolResults, matchesQuery, messagesStateReducer, modifyDeltaProperties, newsSchema, normalizeBashToolResultsForReplay, normalizeCodeApiRequestError, normalizeServerFilter, normalizeToBashIdentifier, normalizeToPythonIdentifier, outcomeFieldsFromResult, parseBooleanEnv, partitionAndMarkAnthropicToolCache, performLocalSearch, preFlightTruncateToolCallInputs, preFlightTruncateToolResults, projectAgentContextUsage, projectAnthropicArtifactContent, projectArtifactPayload, projectCacheControlledToolOutputsToText, projectComputerCallOutputsToText, projectOpenAIChatToolMessageContent, projectOpenAIResponsesToolMessageContent, projectOpenAIToolMessageContent, projectOpenRouterToolMessageContent, projectSingleTextToolOutputsToText, projectStructuredToolOutputsToText, projectToolCallInputs, projectToolStreamContentForProvider, querySchema, readIntent, readOutcomeFields, removePredecessorHandoffCue, repairOrphanedToolMessages, resetIfNotEmpty, resolveBedrockPromptCacheTtl, resolveCloudflareSandbox, resolveCodeApiAuthHeaders, resolveContextPruningSettings, resolveLocalExecutionConfig, resolveLocalExecutionTools, resolveLocalToolRegistry, resolveLocalToolsForBinding, resolvePromptCacheTtl, resolveSearchOutcome, resolveSubagentConfigs, resolveToolOutcome, resolveWorkspacePath, resolveWorkspacePathSafe, runBashAstChecks, runPostEditSyntaxCheck, sanitizeOrphanToolBlocks, sanitizeRegex, serializeMessage, serializeToolCallInput, shellQuote, shiftIndexTokenCountMap, shouldTriggerSummarization, sleep, spawnLocalProcess, splitAtRecencyBoundary, strictAlternationProviders, stripAnthropicCacheControl, stripBedrockCacheControl, stripCodeSessionFileSummary, stripIntent, summarizeEvent, supportsBedrockToolCache, syncBudgetDerivedFields, toJsonSchema, tool, toolResultTypes, toolsCondition, truncateLocalOutput, truncateToolInput, truncateToolResultContent, tryFallbackProviders, unescapeObject, unwrapToolResponse, validateBashCommand, validateCloudflareBashCommand, videosSchema, withClientTimeout, withIntent, withMessageRole, withoutIntent };