@illuma-ai/agents 1.1.21 → 1.1.22

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 (241) hide show
  1. package/dist/cjs/graphs/Graph.cjs +12 -1
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/graphs/MultiAgentGraph.cjs +85 -1
  4. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  5. package/dist/cjs/run.cjs +20 -9
  6. package/dist/cjs/run.cjs.map +1 -1
  7. package/dist/esm/graphs/Graph.mjs +12 -1
  8. package/dist/esm/graphs/Graph.mjs.map +1 -1
  9. package/dist/esm/graphs/MultiAgentGraph.mjs +85 -1
  10. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  11. package/dist/esm/run.mjs +20 -9
  12. package/dist/esm/run.mjs.map +1 -1
  13. package/dist/types/graphs/MultiAgentGraph.d.ts +17 -0
  14. package/package.json +1 -1
  15. package/src/graphs/Graph.ts +12 -1
  16. package/src/graphs/MultiAgentGraph.ts +105 -1
  17. package/src/graphs/__tests__/multi-agent-delegate.test.ts +191 -0
  18. package/src/run.ts +20 -11
  19. package/src/scripts/test-bedrock-handoff-autonomous.ts +231 -0
  20. package/src/agents/AgentContext.js +0 -782
  21. package/src/agents/AgentContext.test.js +0 -421
  22. package/src/agents/__tests__/AgentContext.test.js +0 -678
  23. package/src/agents/__tests__/resolveStructuredOutputMode.test.js +0 -117
  24. package/src/common/enum.js +0 -192
  25. package/src/common/index.js +0 -3
  26. package/src/events.js +0 -166
  27. package/src/graphs/Graph.js +0 -1857
  28. package/src/graphs/MultiAgentGraph.js +0 -1092
  29. package/src/graphs/__tests__/structured-output.integration.test.js +0 -624
  30. package/src/graphs/__tests__/structured-output.test.js +0 -144
  31. package/src/graphs/contextManagement.e2e.test.js +0 -718
  32. package/src/graphs/contextManagement.test.js +0 -485
  33. package/src/graphs/handoffValidation.test.js +0 -276
  34. package/src/graphs/index.js +0 -3
  35. package/src/index.js +0 -28
  36. package/src/instrumentation.js +0 -21
  37. package/src/llm/anthropic/index.js +0 -319
  38. package/src/llm/anthropic/types.js +0 -46
  39. package/src/llm/anthropic/utils/message_inputs.js +0 -627
  40. package/src/llm/anthropic/utils/message_outputs.js +0 -290
  41. package/src/llm/anthropic/utils/output_parsers.js +0 -89
  42. package/src/llm/anthropic/utils/tools.js +0 -25
  43. package/src/llm/bedrock/__tests__/bedrock-caching.test.js +0 -392
  44. package/src/llm/bedrock/index.js +0 -303
  45. package/src/llm/bedrock/types.js +0 -2
  46. package/src/llm/bedrock/utils/index.js +0 -6
  47. package/src/llm/bedrock/utils/message_inputs.js +0 -463
  48. package/src/llm/bedrock/utils/message_outputs.js +0 -269
  49. package/src/llm/fake.js +0 -92
  50. package/src/llm/google/index.js +0 -215
  51. package/src/llm/google/types.js +0 -12
  52. package/src/llm/google/utils/common.js +0 -670
  53. package/src/llm/google/utils/tools.js +0 -111
  54. package/src/llm/google/utils/zod_to_genai_parameters.js +0 -47
  55. package/src/llm/openai/index.js +0 -1033
  56. package/src/llm/openai/types.js +0 -2
  57. package/src/llm/openai/utils/index.js +0 -756
  58. package/src/llm/openai/utils/isReasoningModel.test.js +0 -79
  59. package/src/llm/openrouter/index.js +0 -261
  60. package/src/llm/openrouter/reasoning.test.js +0 -181
  61. package/src/llm/providers.js +0 -36
  62. package/src/llm/text.js +0 -65
  63. package/src/llm/vertexai/index.js +0 -402
  64. package/src/messages/__tests__/tools.test.js +0 -392
  65. package/src/messages/cache.js +0 -404
  66. package/src/messages/cache.test.js +0 -1167
  67. package/src/messages/content.js +0 -48
  68. package/src/messages/content.test.js +0 -314
  69. package/src/messages/core.js +0 -359
  70. package/src/messages/ensureThinkingBlock.test.js +0 -997
  71. package/src/messages/format.js +0 -973
  72. package/src/messages/formatAgentMessages.test.js +0 -2278
  73. package/src/messages/formatAgentMessages.tools.test.js +0 -362
  74. package/src/messages/formatMessage.test.js +0 -608
  75. package/src/messages/ids.js +0 -18
  76. package/src/messages/index.js +0 -9
  77. package/src/messages/labelContentByAgent.test.js +0 -725
  78. package/src/messages/prune.js +0 -438
  79. package/src/messages/reducer.js +0 -60
  80. package/src/messages/shiftIndexTokenCountMap.test.js +0 -63
  81. package/src/messages/summarize.js +0 -146
  82. package/src/messages/summarize.test.js +0 -332
  83. package/src/messages/tools.js +0 -90
  84. package/src/mockStream.js +0 -81
  85. package/src/prompts/collab.js +0 -7
  86. package/src/prompts/index.js +0 -3
  87. package/src/prompts/taskmanager.js +0 -58
  88. package/src/run.js +0 -427
  89. package/src/schemas/index.js +0 -3
  90. package/src/schemas/schema-preparation.test.js +0 -370
  91. package/src/schemas/validate.js +0 -314
  92. package/src/schemas/validate.test.js +0 -264
  93. package/src/scripts/abort.js +0 -127
  94. package/src/scripts/ant_web_search.js +0 -130
  95. package/src/scripts/ant_web_search_edge_case.js +0 -133
  96. package/src/scripts/ant_web_search_error_edge_case.js +0 -119
  97. package/src/scripts/args.js +0 -41
  98. package/src/scripts/bedrock-cache-debug.js +0 -186
  99. package/src/scripts/bedrock-content-aggregation-test.js +0 -195
  100. package/src/scripts/bedrock-merge-test.js +0 -80
  101. package/src/scripts/bedrock-parallel-tools-test.js +0 -150
  102. package/src/scripts/caching.js +0 -106
  103. package/src/scripts/cli.js +0 -152
  104. package/src/scripts/cli2.js +0 -119
  105. package/src/scripts/cli3.js +0 -163
  106. package/src/scripts/cli4.js +0 -165
  107. package/src/scripts/cli5.js +0 -165
  108. package/src/scripts/code_exec.js +0 -171
  109. package/src/scripts/code_exec_files.js +0 -180
  110. package/src/scripts/code_exec_multi_session.js +0 -185
  111. package/src/scripts/code_exec_ptc.js +0 -265
  112. package/src/scripts/code_exec_session.js +0 -217
  113. package/src/scripts/code_exec_simple.js +0 -120
  114. package/src/scripts/content.js +0 -111
  115. package/src/scripts/empty_input.js +0 -125
  116. package/src/scripts/handoff-test.js +0 -96
  117. package/src/scripts/image.js +0 -138
  118. package/src/scripts/memory.js +0 -83
  119. package/src/scripts/multi-agent-chain.js +0 -271
  120. package/src/scripts/multi-agent-conditional.js +0 -185
  121. package/src/scripts/multi-agent-document-review-chain.js +0 -171
  122. package/src/scripts/multi-agent-hybrid-flow.js +0 -264
  123. package/src/scripts/multi-agent-parallel-start.js +0 -214
  124. package/src/scripts/multi-agent-parallel.js +0 -346
  125. package/src/scripts/multi-agent-sequence.js +0 -184
  126. package/src/scripts/multi-agent-supervisor.js +0 -324
  127. package/src/scripts/multi-agent-test.js +0 -147
  128. package/src/scripts/parallel-asymmetric-tools-test.js +0 -202
  129. package/src/scripts/parallel-full-metadata-test.js +0 -176
  130. package/src/scripts/parallel-tools-test.js +0 -256
  131. package/src/scripts/programmatic_exec.js +0 -277
  132. package/src/scripts/programmatic_exec_agent.js +0 -168
  133. package/src/scripts/search.js +0 -118
  134. package/src/scripts/sequential-full-metadata-test.js +0 -143
  135. package/src/scripts/simple.js +0 -174
  136. package/src/scripts/single-agent-metadata-test.js +0 -152
  137. package/src/scripts/stream.js +0 -113
  138. package/src/scripts/test-custom-prompt-key.js +0 -132
  139. package/src/scripts/test-handoff-input.js +0 -143
  140. package/src/scripts/test-handoff-preamble.js +0 -227
  141. package/src/scripts/test-handoff-steering.js +0 -353
  142. package/src/scripts/test-multi-agent-list-handoff.js +0 -318
  143. package/src/scripts/test-parallel-agent-labeling.js +0 -253
  144. package/src/scripts/test-parallel-handoffs.js +0 -229
  145. package/src/scripts/test-thinking-handoff-bedrock.js +0 -132
  146. package/src/scripts/test-thinking-handoff.js +0 -132
  147. package/src/scripts/test-thinking-to-thinking-handoff-bedrock.js +0 -140
  148. package/src/scripts/test-tool-before-handoff-role-order.js +0 -223
  149. package/src/scripts/test-tools-before-handoff.js +0 -187
  150. package/src/scripts/test_code_api.js +0 -263
  151. package/src/scripts/thinking-bedrock.js +0 -128
  152. package/src/scripts/thinking-vertexai.js +0 -130
  153. package/src/scripts/thinking.js +0 -134
  154. package/src/scripts/tool_search.js +0 -114
  155. package/src/scripts/tools.js +0 -125
  156. package/src/specs/agent-handoffs-bedrock.integration.test.js +0 -280
  157. package/src/specs/agent-handoffs.test.js +0 -924
  158. package/src/specs/anthropic.simple.test.js +0 -287
  159. package/src/specs/azure.simple.test.js +0 -381
  160. package/src/specs/cache.simple.test.js +0 -282
  161. package/src/specs/custom-event-await.test.js +0 -148
  162. package/src/specs/deepseek.simple.test.js +0 -189
  163. package/src/specs/emergency-prune.test.js +0 -308
  164. package/src/specs/moonshot.simple.test.js +0 -237
  165. package/src/specs/observability.integration.test.js +0 -1337
  166. package/src/specs/openai.simple.test.js +0 -233
  167. package/src/specs/openrouter.simple.test.js +0 -202
  168. package/src/specs/prune.test.js +0 -733
  169. package/src/specs/reasoning.test.js +0 -144
  170. package/src/specs/spec.utils.js +0 -4
  171. package/src/specs/thinking-handoff.test.js +0 -486
  172. package/src/specs/thinking-prune.test.js +0 -600
  173. package/src/specs/token-distribution-edge-case.test.js +0 -246
  174. package/src/specs/token-memoization.test.js +0 -32
  175. package/src/specs/tokens.test.js +0 -49
  176. package/src/specs/tool-error.test.js +0 -139
  177. package/src/splitStream.js +0 -204
  178. package/src/splitStream.test.js +0 -504
  179. package/src/stream.js +0 -650
  180. package/src/stream.test.js +0 -225
  181. package/src/test/mockTools.js +0 -340
  182. package/src/tools/BrowserTools.js +0 -245
  183. package/src/tools/Calculator.js +0 -38
  184. package/src/tools/Calculator.test.js +0 -225
  185. package/src/tools/CodeExecutor.js +0 -233
  186. package/src/tools/ProgrammaticToolCalling.js +0 -602
  187. package/src/tools/StreamingToolCallBuffer.js +0 -179
  188. package/src/tools/ToolNode.js +0 -930
  189. package/src/tools/ToolSearch.js +0 -904
  190. package/src/tools/__tests__/BrowserTools.test.js +0 -306
  191. package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.js +0 -276
  192. package/src/tools/__tests__/ProgrammaticToolCalling.test.js +0 -807
  193. package/src/tools/__tests__/StreamingToolCallBuffer.test.js +0 -175
  194. package/src/tools/__tests__/ToolApproval.test.js +0 -675
  195. package/src/tools/__tests__/ToolNode.recovery.test.js +0 -200
  196. package/src/tools/__tests__/ToolNode.session.test.js +0 -319
  197. package/src/tools/__tests__/ToolSearch.integration.test.js +0 -125
  198. package/src/tools/__tests__/ToolSearch.test.js +0 -812
  199. package/src/tools/__tests__/handlers.test.js +0 -799
  200. package/src/tools/__tests__/truncation-recovery.integration.test.js +0 -362
  201. package/src/tools/handlers.js +0 -306
  202. package/src/tools/schema.js +0 -25
  203. package/src/tools/search/anthropic.js +0 -34
  204. package/src/tools/search/content.js +0 -116
  205. package/src/tools/search/content.test.js +0 -133
  206. package/src/tools/search/firecrawl.js +0 -173
  207. package/src/tools/search/format.js +0 -198
  208. package/src/tools/search/highlights.js +0 -241
  209. package/src/tools/search/index.js +0 -3
  210. package/src/tools/search/jina-reranker.test.js +0 -106
  211. package/src/tools/search/rerankers.js +0 -165
  212. package/src/tools/search/schema.js +0 -102
  213. package/src/tools/search/search.js +0 -561
  214. package/src/tools/search/serper-scraper.js +0 -126
  215. package/src/tools/search/test.js +0 -129
  216. package/src/tools/search/tool.js +0 -453
  217. package/src/tools/search/types.js +0 -2
  218. package/src/tools/search/utils.js +0 -59
  219. package/src/types/graph.js +0 -24
  220. package/src/types/graph.test.js +0 -192
  221. package/src/types/index.js +0 -7
  222. package/src/types/llm.js +0 -2
  223. package/src/types/messages.js +0 -2
  224. package/src/types/run.js +0 -2
  225. package/src/types/stream.js +0 -2
  226. package/src/types/tools.js +0 -2
  227. package/src/utils/contextAnalytics.js +0 -79
  228. package/src/utils/contextAnalytics.test.js +0 -166
  229. package/src/utils/events.js +0 -26
  230. package/src/utils/graph.js +0 -11
  231. package/src/utils/handlers.js +0 -65
  232. package/src/utils/index.js +0 -10
  233. package/src/utils/llm.js +0 -21
  234. package/src/utils/llmConfig.js +0 -205
  235. package/src/utils/logging.js +0 -37
  236. package/src/utils/misc.js +0 -51
  237. package/src/utils/run.js +0 -69
  238. package/src/utils/schema.js +0 -21
  239. package/src/utils/title.js +0 -119
  240. package/src/utils/tokens.js +0 -92
  241. package/src/utils/toonFormat.js +0 -379
@@ -1,25 +0,0 @@
1
- import { tool } from '@langchain/core/tools';
2
- /**
3
- * Creates a schema-only tool for LLM binding in event-driven mode.
4
- * These tools have valid schemas for the LLM to understand but should
5
- * never be invoked directly - ToolNode handles execution via events.
6
- */
7
- export function createSchemaOnlyTool(definition) {
8
- const { name, description, parameters, responseFormat } = definition;
9
- return tool(async () => {
10
- throw new Error(`Tool "${name}" should not be invoked directly in event-driven mode. ` +
11
- 'ToolNode should dispatch ON_TOOL_EXECUTE events instead.');
12
- }, {
13
- name,
14
- description: description ?? '',
15
- schema: parameters ?? { type: 'object', properties: {} },
16
- responseFormat: responseFormat ?? 'content_and_artifact',
17
- });
18
- }
19
- /**
20
- * Creates schema-only tools for all definitions in an array.
21
- */
22
- export function createSchemaOnlyTools(definitions) {
23
- return definitions.map((def) => createSchemaOnlyTool(def));
24
- }
25
- //# sourceMappingURL=schema.js.map
@@ -1,34 +0,0 @@
1
- import { getAttribution } from './utils';
2
- /**
3
- * Coerces Anthropic web search results to the SearchResultData format
4
- * @param results - Array of Anthropic web search results
5
- * @param turn - The turn number to associate with these results
6
- * @returns SearchResultData with minimal ProcessedOrganic items
7
- */
8
- export function coerceAnthropicSearchResults({ results, turn = 0, }) {
9
- const organic = results
10
- .filter((result) => result.type === 'web_search_result')
11
- .map((result, index) => ({
12
- link: result.url,
13
- position: index + 1,
14
- title: result.title,
15
- date: result.page_age ?? undefined,
16
- attribution: getAttribution(result.url),
17
- }));
18
- return {
19
- turn,
20
- organic,
21
- };
22
- }
23
- /**
24
- * Helper function to check if an object is an Anthropic web search result
25
- */
26
- export function isAnthropicWebSearchResult(obj) {
27
- return (typeof obj === 'object' &&
28
- obj !== null &&
29
- 'type' in obj &&
30
- obj.type === 'web_search_result' &&
31
- 'url' in obj &&
32
- typeof obj.url === 'string');
33
- }
34
- //# sourceMappingURL=anthropic.js.map
@@ -1,116 +0,0 @@
1
- import * as cheerio from 'cheerio';
2
- export function processContent(html, markdown) {
3
- const linkMap = new Map();
4
- const imageMap = new Map();
5
- const videoMap = new Map();
6
- const iframeMap = new Map();
7
- const $ = cheerio.load(html, {
8
- xmlMode: false,
9
- });
10
- // Extract all media references
11
- $('a[href]').each((_, el) => {
12
- const href = $(el).attr('href');
13
- if (href != null && href) {
14
- linkMap.set(href, {
15
- originalUrl: href,
16
- title: $(el).attr('title'),
17
- text: $(el).text().trim(),
18
- });
19
- }
20
- });
21
- $('img[src]').each((_, el) => {
22
- const src = $(el).attr('src');
23
- if (src != null && src) {
24
- imageMap.set(src, {
25
- originalUrl: src,
26
- title: $(el).attr('alt') ?? $(el).attr('title'),
27
- });
28
- }
29
- });
30
- // Handle videos (dedicated video elements and video platforms in iframes)
31
- $('video[src], iframe[src*="youtube"], iframe[src*="vimeo"]').each((_, el) => {
32
- const src = $(el).attr('src');
33
- if (src != null && src) {
34
- videoMap.set(src, {
35
- originalUrl: src,
36
- title: $(el).attr('title'),
37
- });
38
- }
39
- });
40
- // Handle all other generic iframes that aren't already captured as videos
41
- $('iframe').each((_, el) => {
42
- const src = $(el).attr('src');
43
- if (src != null &&
44
- src &&
45
- !src.includes('youtube') &&
46
- !src.includes('vimeo')) {
47
- iframeMap.set(src, {
48
- originalUrl: src,
49
- title: $(el).attr('title'),
50
- });
51
- }
52
- });
53
- // Create lookup maps with indices
54
- const linkIndexMap = new Map();
55
- const imageIndexMap = new Map();
56
- const videoIndexMap = new Map();
57
- const iframeIndexMap = new Map();
58
- Array.from(linkMap.keys()).forEach((url, i) => linkIndexMap.set(url, i + 1));
59
- Array.from(imageMap.keys()).forEach((url, i) => imageIndexMap.set(url, i + 1));
60
- Array.from(videoMap.keys()).forEach((url, i) => videoIndexMap.set(url, i + 1));
61
- Array.from(iframeMap.keys()).forEach((url, i) => iframeIndexMap.set(url, i + 1));
62
- // Process the markdown
63
- let result = markdown;
64
- // Replace each URL one by one, starting with the longest URLs first to avoid partial matches
65
- const allUrls = [
66
- ...Array.from(imageMap.keys()).map((url) => ({
67
- url,
68
- type: 'image',
69
- idx: imageIndexMap.get(url),
70
- })),
71
- ...Array.from(videoMap.keys()).map((url) => ({
72
- url,
73
- type: 'video',
74
- idx: videoIndexMap.get(url),
75
- })),
76
- ...Array.from(iframeMap.keys()).map((url) => ({
77
- url,
78
- type: 'iframe',
79
- idx: iframeIndexMap.get(url),
80
- })),
81
- ...Array.from(linkMap.keys()).map((url) => ({
82
- url,
83
- type: 'link',
84
- idx: linkIndexMap.get(url),
85
- })),
86
- ].sort((a, b) => b.url.length - a.url.length);
87
- // Create a function to escape special characters in URLs for regex
88
- function escapeRegex(string) {
89
- return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
90
- }
91
- // Replace each URL in the markdown
92
- for (const { url, type, idx } of allUrls) {
93
- // Create a regex that captures URLs in markdown links
94
- const regex = new RegExp(`\\(${escapeRegex(url)}(?:\\s+"[^"]*")?\\)`, 'g');
95
- result = result.replace(regex, (match) => {
96
- // Keep any title attribute that might exist
97
- const titleMatch = match.match(/\s+"([^"]*)"/);
98
- const titlePart = titleMatch ? ` "${titleMatch[1]}"` : '';
99
- return `(${type}#${idx}${titlePart})`;
100
- });
101
- }
102
- iframeMap.clear();
103
- const links = Array.from(linkMap.values());
104
- linkMap.clear();
105
- const images = Array.from(imageMap.values());
106
- imageMap.clear();
107
- const videos = Array.from(videoMap.values());
108
- videoMap.clear();
109
- return {
110
- markdown: result,
111
- links,
112
- images,
113
- videos,
114
- };
115
- }
116
- //# sourceMappingURL=content.js.map
@@ -1,133 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-unused-vars */
2
- /* eslint-disable no-console */
3
- // content.test.ts
4
- import * as fs from 'fs';
5
- import { processContent } from './content';
6
- describe('Link Processor', () => {
7
- afterAll(() => {
8
- if (fs.existsSync('./temp.html')) {
9
- fs.unlinkSync('./temp.html');
10
- }
11
- if (fs.existsSync('./temp.md')) {
12
- fs.unlinkSync('./temp.md');
13
- }
14
- });
15
- // Basic functionality tests
16
- test('should replace basic links with references', () => {
17
- const html = `
18
- <p>Test with <a href="https://example.com/link" title="Example">a link</a></p>
19
- <p>And an <img src="https://example.com/img.jpg" alt="image"></p>
20
- <p>Plus a <video src="https://example.com/video.mp4"></video></p>
21
- `;
22
- const markdown = `
23
- Test with [a link](https://example.com/link "Example")
24
- And an ![image](https://example.com/img.jpg)
25
- Plus a [video](https://example.com/video.mp4)
26
- `;
27
- const result = processContent(html, markdown);
28
- expect(result.links.length).toBe(1);
29
- expect(result.images.length).toBe(1);
30
- expect(result.videos.length).toBe(1);
31
- expect(result.markdown).toContain('link#1');
32
- expect(result.markdown).toContain('image#1');
33
- expect(result.markdown).toContain('video#1');
34
- });
35
- // Edge case tests
36
- test('should handle links with parentheses and special characters', () => {
37
- const html = `
38
- <a href="https://example.com/page(1).html" title="Parens">Link with parens</a>
39
- <a href="https://example.com/path?query=test&param=value">Link with query</a>
40
- `;
41
- const markdown = `
42
- [Link with parens](https://example.com/page(1).html "Parens")
43
- [Link with query](https://example.com/path?query=test&param=value)
44
- `;
45
- const result = processContent(html, markdown);
46
- expect(result.links.length).toBe(2);
47
- expect(result.markdown).toContain('link#1');
48
- expect(result.markdown).toContain('link#2');
49
- });
50
- // Performance test with large files
51
- test('should process large files efficiently', () => {
52
- const html = fs.readFileSync('src/tools/search/test.html', 'utf-8');
53
- const markdown = fs.readFileSync('src/tools/search/test.md', 'utf-8');
54
- // const largeHtml = generateLargeHtml(1000); // 1000 links
55
- // fs.writeFileSync('./temp.html', largeHtml);
56
- // const largeMd = generateLargeMarkdown(1000); // 1000 links
57
- // fs.writeFileSync('./temp.md', largeMd);
58
- // const html = fs.readFileSync('./temp.html', 'utf-8');
59
- // const markdown = fs.readFileSync('./temp.md', 'utf-8');
60
- // Measure time taken to process
61
- const startTime = process.hrtime();
62
- const result = processContent(html, markdown);
63
- const elapsed = process.hrtime(startTime);
64
- const timeInMs = elapsed[0] * 1000 + elapsed[1] / 1000000;
65
- console.log(`Processed ${result.links.length} links, ${result.images.length} images, and ${result.videos.length} videos in ${timeInMs.toFixed(2)}ms`);
66
- // Basic validations for large file processing
67
- expect(result.links.length).toBeGreaterThan(0);
68
- expect(result.markdown).toContain('link#');
69
- // Check if all links were replaced (sample check)
70
- expect(result.markdown).not.toContain('https://example.com/link');
71
- });
72
- // Memory usage test
73
- test('should have reasonable memory usage', () => {
74
- const html = fs.readFileSync('src/tools/search/test.html', 'utf-8');
75
- const markdown = fs.readFileSync('src/tools/search/test.md', 'utf-8');
76
- const beforeMem = process.memoryUsage();
77
- processContent(html, markdown);
78
- const afterMem = process.memoryUsage();
79
- const heapUsed = (afterMem.heapUsed - beforeMem.heapUsed) / 1024 / 1024; // MB
80
- console.log(`Memory used: ${heapUsed.toFixed(2)} MB`);
81
- // This is a loose check - actual thresholds depend on your environment
82
- expect(heapUsed).toBeLessThan(100); // Should use less than 100MB additional heap
83
- });
84
- // Real-world file test (if available)
85
- test('should process real-world Wikipedia content', () => {
86
- // Try to find real-world test files if they exist
87
- const wikiHtml = 'src/tools/search/test.html';
88
- const wikiMd = 'src/tools/search/test.md';
89
- if (fs.existsSync(wikiHtml) && fs.existsSync(wikiMd)) {
90
- const html = fs.readFileSync(wikiHtml, 'utf-8');
91
- const markdown = fs.readFileSync(wikiMd, 'utf-8');
92
- const result = processContent(html, markdown);
93
- console.log(`Processed ${result.links.length} Wikipedia links, ${result.images.length} images, and ${result.videos.length} videos`);
94
- expect(result.links.length).toBeGreaterThan(10); // Wikipedia articles typically have many links
95
- expect(result.markdown).not.toMatch(/\]\(https?:\/\/[^\s")]+\)/); // No regular URLs should remain
96
- }
97
- else {
98
- console.log('Wikipedia test files not found, skipping this test');
99
- }
100
- });
101
- });
102
- // Helper function to generate large HTML test data
103
- function generateLargeHtml(linkCount) {
104
- let html = '<html><body>';
105
- for (let i = 1; i <= linkCount; i++) {
106
- html += `<p>Paragraph ${i} with <a href="https://example.com/link${i}" title="Link ${i}">link ${i}</a>`;
107
- if (i % 10 === 0) {
108
- html += ` and <img src="https://example.com/image${i / 10}.jpg" alt="Image ${i / 10}">`;
109
- }
110
- if (i % 50 === 0) {
111
- html += ` and <video src="https://example.com/video${i / 50}.mp4" title="Video ${i / 50}"></video>`;
112
- }
113
- html += '</p>';
114
- }
115
- html += '</body></html>';
116
- return html;
117
- }
118
- /** Helper function to generate large Markdown test data */
119
- function generateLargeMarkdown(linkCount) {
120
- let markdown = '# Test Document\n\n';
121
- for (let i = 1; i <= linkCount; i++) {
122
- markdown += `Paragraph ${i} with [link ${i}](https://example.com/link${i} "Link ${i}")`;
123
- if (i % 10 === 0) {
124
- markdown += ` and ![Image ${i / 10}](https://example.com/image${i / 10}.jpg)`;
125
- }
126
- if (i % 50 === 0) {
127
- markdown += ` and [Video ${i / 50}](https://example.com/video${i / 50}.mp4 "Video ${i / 50}")`;
128
- }
129
- markdown += '\n\n';
130
- }
131
- return markdown;
132
- }
133
- //# sourceMappingURL=content.test.js.map
@@ -1,173 +0,0 @@
1
- import axios from 'axios';
2
- import { processContent } from './content';
3
- import { createDefaultLogger } from './utils';
4
- /**
5
- * Firecrawl scraper implementation
6
- * Uses the Firecrawl API to scrape web pages
7
- */
8
- export class FirecrawlScraper {
9
- apiKey;
10
- apiUrl;
11
- version;
12
- defaultFormats;
13
- timeout;
14
- logger;
15
- includeTags;
16
- excludeTags;
17
- waitFor;
18
- maxAge;
19
- mobile;
20
- skipTlsVerification;
21
- blockAds;
22
- removeBase64Images;
23
- parsePDF;
24
- storeInCache;
25
- zeroDataRetention;
26
- headers;
27
- location;
28
- onlyMainContent;
29
- changeTrackingOptions;
30
- constructor(config = {}) {
31
- this.apiKey = config.apiKey ?? process.env.FIRECRAWL_API_KEY ?? '';
32
- this.version = config.version ?? 'v2';
33
- const baseUrl = config.apiUrl ??
34
- process.env.FIRECRAWL_BASE_URL ??
35
- 'https://api.firecrawl.dev';
36
- this.apiUrl = `${baseUrl.replace(/\/+$/, '')}/${this.version}/scrape`;
37
- this.defaultFormats = config.formats ?? ['markdown', 'rawHtml'];
38
- this.timeout = config.timeout ?? 7500;
39
- this.logger = config.logger || createDefaultLogger();
40
- this.includeTags = config.includeTags;
41
- this.excludeTags = config.excludeTags;
42
- this.waitFor = config.waitFor;
43
- this.maxAge = config.maxAge;
44
- this.mobile = config.mobile;
45
- this.skipTlsVerification = config.skipTlsVerification;
46
- this.blockAds = config.blockAds;
47
- this.removeBase64Images = config.removeBase64Images;
48
- this.parsePDF = config.parsePDF;
49
- this.storeInCache = config.storeInCache;
50
- this.zeroDataRetention = config.zeroDataRetention;
51
- this.headers = config.headers;
52
- this.location = config.location;
53
- this.onlyMainContent = config.onlyMainContent;
54
- this.changeTrackingOptions = config.changeTrackingOptions;
55
- if (!this.apiKey) {
56
- this.logger.warn('FIRECRAWL_API_KEY is not set. Scraping will not work.');
57
- }
58
- this.logger.debug(`Firecrawl scraper initialized with API URL: ${this.apiUrl}`);
59
- }
60
- /**
61
- * Scrape a single URL
62
- * @param url URL to scrape
63
- * @param options Scrape options
64
- * @returns Scrape response
65
- */
66
- async scrapeUrl(url, options = {}) {
67
- if (!this.apiKey) {
68
- return [
69
- url,
70
- {
71
- success: false,
72
- error: 'FIRECRAWL_API_KEY is not set',
73
- },
74
- ];
75
- }
76
- try {
77
- const payload = omitUndefined({
78
- url,
79
- formats: options.formats ?? this.defaultFormats,
80
- includeTags: options.includeTags ?? this.includeTags,
81
- excludeTags: options.excludeTags ?? this.excludeTags,
82
- headers: options.headers ?? this.headers,
83
- waitFor: options.waitFor ?? this.waitFor,
84
- timeout: options.timeout ?? this.timeout,
85
- onlyMainContent: options.onlyMainContent ?? this.onlyMainContent,
86
- maxAge: options.maxAge ?? this.maxAge,
87
- mobile: options.mobile ?? this.mobile,
88
- skipTlsVerification: options.skipTlsVerification ?? this.skipTlsVerification,
89
- parsePDF: options.parsePDF ?? this.parsePDF,
90
- location: options.location ?? this.location,
91
- removeBase64Images: options.removeBase64Images ?? this.removeBase64Images,
92
- blockAds: options.blockAds ?? this.blockAds,
93
- storeInCache: options.storeInCache ?? this.storeInCache,
94
- zeroDataRetention: options.zeroDataRetention ?? this.zeroDataRetention,
95
- changeTrackingOptions: options.changeTrackingOptions ?? this.changeTrackingOptions,
96
- });
97
- const response = await axios.post(this.apiUrl, payload, {
98
- headers: {
99
- 'Content-Type': 'application/json',
100
- Authorization: `Bearer ${this.apiKey}`,
101
- },
102
- timeout: this.timeout,
103
- });
104
- return [url, response.data];
105
- }
106
- catch (error) {
107
- const errorMessage = error instanceof Error ? error.message : String(error);
108
- return [
109
- url,
110
- {
111
- success: false,
112
- error: `Firecrawl API request failed: ${errorMessage}`,
113
- },
114
- ];
115
- }
116
- }
117
- /**
118
- * Extract content from scrape response
119
- * @param response Scrape response
120
- * @returns Extracted content or empty string if not available
121
- */
122
- extractContent(response) {
123
- if (!response.success || !response.data) {
124
- return ['', undefined];
125
- }
126
- if (response.data.markdown != null && response.data.html != null) {
127
- try {
128
- const { markdown, ...rest } = processContent(response.data.html, response.data.markdown);
129
- return [markdown, rest];
130
- }
131
- catch (error) {
132
- this.logger.error('Error processing content:', error);
133
- return [response.data.markdown, undefined];
134
- }
135
- }
136
- else if (response.data.markdown != null) {
137
- return [response.data.markdown, undefined];
138
- }
139
- // Fall back to HTML content
140
- if (response.data.html != null) {
141
- return [response.data.html, undefined];
142
- }
143
- // Fall back to raw HTML content
144
- if (response.data.rawHtml != null) {
145
- return [response.data.rawHtml, undefined];
146
- }
147
- return ['', undefined];
148
- }
149
- /**
150
- * Extract metadata from scrape response
151
- * @param response Scrape response
152
- * @returns Metadata object
153
- */
154
- extractMetadata(response) {
155
- if (!response.success || !response.data || !response.data.metadata) {
156
- return {};
157
- }
158
- return response.data.metadata;
159
- }
160
- }
161
- /**
162
- * Create a Firecrawl scraper instance
163
- * @param config Scraper configuration
164
- * @returns Firecrawl scraper instance
165
- */
166
- export const createFirecrawlScraper = (config = {}) => {
167
- return new FirecrawlScraper(config);
168
- };
169
- // Helper function to clean up payload for firecrawl
170
- function omitUndefined(obj) {
171
- return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined));
172
- }
173
- //# sourceMappingURL=firecrawl.js.map
@@ -1,198 +0,0 @@
1
- import { getDomainName, fileExtRegex } from './utils';
2
- function addHighlightSection() {
3
- return ['\n## Highlights', ''];
4
- }
5
- // Helper function to format a source (organic or top story)
6
- function formatSource(source, index, turn, sourceType, references) {
7
- /** Array of all lines to include in the output */
8
- const outputLines = [];
9
- // Add the title
10
- outputLines.push(`# ${sourceType.charAt(0).toUpperCase() + sourceType.slice(1)} ${index}: ${source.title != null && source.title ? `"${source.title}"` : '(no title)'}`);
11
- outputLines.push(`\nAnchor: \\ue202turn${turn}${sourceType}${index}`);
12
- outputLines.push(`URL: ${source.link}`);
13
- // Add optional fields
14
- if ('snippet' in source && source.snippet != null) {
15
- outputLines.push(`Summary: ${source.snippet}`);
16
- }
17
- if (source.date != null) {
18
- outputLines.push(`Date: ${source.date}`);
19
- }
20
- if (source.attribution != null) {
21
- outputLines.push(`Source: ${source.attribution}`);
22
- }
23
- // Add highlight section or empty line
24
- if ((source.highlights?.length ?? 0) > 0) {
25
- outputLines.push(...addHighlightSection());
26
- }
27
- else {
28
- outputLines.push('');
29
- }
30
- // Process highlights if they exist
31
- (source.highlights ?? [])
32
- .filter((h) => h.text.trim().length > 0)
33
- .forEach((h, hIndex) => {
34
- outputLines.push(`### Highlight ${hIndex + 1} [Relevance: ${h.score.toFixed(2)}]`);
35
- outputLines.push('');
36
- outputLines.push('```text');
37
- outputLines.push(h.text.trim());
38
- outputLines.push('```');
39
- outputLines.push('');
40
- if (h.references != null && h.references.length) {
41
- let hasHeader = false;
42
- const refLines = [];
43
- for (let j = 0; j < h.references.length; j++) {
44
- const ref = h.references[j];
45
- if (ref.reference.originalUrl.includes('mailto:')) {
46
- continue;
47
- }
48
- if (ref.type !== 'link') {
49
- continue;
50
- }
51
- if (fileExtRegex.test(ref.reference.originalUrl)) {
52
- continue;
53
- }
54
- references.push({
55
- type: ref.type,
56
- link: ref.reference.originalUrl,
57
- attribution: getDomainName(ref.reference.originalUrl),
58
- title: (((ref.reference.title ?? '') || ref.reference.text) ??
59
- '').split('\n')[0],
60
- });
61
- if (!hasHeader) {
62
- refLines.push('Core References:');
63
- hasHeader = true;
64
- }
65
- refLines.push(`- ${ref.type}#${ref.originalIndex + 1}: ${ref.reference.originalUrl}`);
66
- refLines.push(`\t- Anchor: \\ue202turn${turn}ref${references.length - 1}`);
67
- }
68
- if (hasHeader) {
69
- outputLines.push(...refLines);
70
- outputLines.push('');
71
- }
72
- }
73
- if (hIndex < (source.highlights?.length ?? 0) - 1) {
74
- outputLines.push('---');
75
- outputLines.push('');
76
- }
77
- });
78
- outputLines.push('');
79
- return outputLines.join('\n');
80
- }
81
- export function formatResultsForLLM(turn, results) {
82
- /** Array to collect all output lines */
83
- const outputLines = [];
84
- const addSection = (title) => {
85
- outputLines.push('');
86
- outputLines.push(`=== ${title} ===`);
87
- outputLines.push('');
88
- };
89
- const references = [];
90
- // Organic (web) results
91
- if (results.organic?.length != null && results.organic.length > 0) {
92
- addSection(`Web Results, Turn ${turn}`);
93
- for (let i = 0; i < results.organic.length; i++) {
94
- const r = results.organic[i];
95
- outputLines.push(formatSource(r, i, turn, 'search', references));
96
- delete results.organic[i].highlights;
97
- }
98
- }
99
- // Top stories (news)
100
- const topStories = results.topStories ?? [];
101
- if (topStories.length) {
102
- addSection('News Results');
103
- for (let i = 0; i < topStories.length; i++) {
104
- const r = topStories[i];
105
- outputLines.push(formatSource(r, i, turn, 'news', references));
106
- if (results.topStories?.[i]?.highlights) {
107
- delete results.topStories[i].highlights;
108
- }
109
- }
110
- }
111
- // // Images
112
- // const images = results.images ?? [];
113
- // if (images.length) {
114
- // addSection('Image Results');
115
- // const imageLines = images.map((img, i) => [
116
- // `Anchor: \ue202turn0image${i}`,
117
- // `Title: ${img.title ?? '(no title)'}`,
118
- // `Image URL: ${img.imageUrl}`,
119
- // ''
120
- // ].join('\n'));
121
- // outputLines.push(imageLines.join('\n'));
122
- // }
123
- // Knowledge Graph
124
- if (results.knowledgeGraph != null) {
125
- addSection('Knowledge Graph');
126
- const kgLines = [
127
- `**Title:** ${results.knowledgeGraph.title ?? '(no title)'}`,
128
- results.knowledgeGraph.type != null
129
- ? `**Type:** ${results.knowledgeGraph.type}`
130
- : '',
131
- results.knowledgeGraph.description != null
132
- ? `**Description:** ${results.knowledgeGraph.description}`
133
- : '',
134
- results.knowledgeGraph.descriptionSource != null
135
- ? `**Description Source:** ${results.knowledgeGraph.descriptionSource}`
136
- : '',
137
- results.knowledgeGraph.descriptionLink != null
138
- ? `**Description Link:** ${results.knowledgeGraph.descriptionLink}`
139
- : '',
140
- results.knowledgeGraph.imageUrl != null
141
- ? `**Image URL:** ${results.knowledgeGraph.imageUrl}`
142
- : '',
143
- results.knowledgeGraph.website != null
144
- ? `**Website:** ${results.knowledgeGraph.website}`
145
- : '',
146
- results.knowledgeGraph.attributes != null
147
- ? `**Attributes:**\n\`\`\`json\n${JSON.stringify(results.knowledgeGraph.attributes, null, 2)}\n\`\`\``
148
- : '',
149
- '',
150
- ].filter(Boolean);
151
- outputLines.push(kgLines.join('\n\n'));
152
- }
153
- // Answer Box
154
- if (results.answerBox != null) {
155
- addSection('Answer Box');
156
- const abLines = [
157
- results.answerBox.title != null
158
- ? `**Title:** ${results.answerBox.title}`
159
- : '',
160
- results.answerBox.snippet != null
161
- ? `**Snippet:** ${results.answerBox.snippet}`
162
- : '',
163
- results.answerBox.snippetHighlighted != null
164
- ? `**Snippet Highlighted:** ${results.answerBox.snippetHighlighted
165
- .map((s) => `\`${s}\``)
166
- .join(' ')}`
167
- : '',
168
- results.answerBox.link != null
169
- ? `**Link:** ${results.answerBox.link}`
170
- : '',
171
- '',
172
- ].filter(Boolean);
173
- outputLines.push(abLines.join('\n\n'));
174
- }
175
- // People also ask
176
- const peopleAlsoAsk = results.peopleAlsoAsk ?? [];
177
- if (peopleAlsoAsk.length) {
178
- addSection('People Also Ask');
179
- const paaLines = [];
180
- peopleAlsoAsk.forEach((p, i) => {
181
- const questionLines = [
182
- `### Question ${i + 1}:`,
183
- `"${p.question}"`,
184
- `${p.snippet != null && p.snippet ? `Snippet: ${p.snippet}` : ''}`,
185
- `${p.title != null && p.title ? `Title: ${p.title}` : ''}`,
186
- `${p.link != null && p.link ? `Link: ${p.link}` : ''}`,
187
- '',
188
- ].filter(Boolean);
189
- paaLines.push(questionLines.join('\n\n'));
190
- });
191
- outputLines.push(paaLines.join(''));
192
- }
193
- return {
194
- output: outputLines.join('\n').trim(),
195
- references,
196
- };
197
- }
198
- //# sourceMappingURL=format.js.map