@illuma-ai/agents 1.1.21 → 1.1.23

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 (244) 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 +105 -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/cjs/utils/llm.cjs.map +1 -1
  8. package/dist/esm/graphs/Graph.mjs +12 -1
  9. package/dist/esm/graphs/Graph.mjs.map +1 -1
  10. package/dist/esm/graphs/MultiAgentGraph.mjs +105 -1
  11. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  12. package/dist/esm/run.mjs +20 -9
  13. package/dist/esm/run.mjs.map +1 -1
  14. package/dist/esm/utils/llm.mjs.map +1 -1
  15. package/dist/types/graphs/MultiAgentGraph.d.ts +17 -0
  16. package/package.json +1 -1
  17. package/src/graphs/Graph.ts +13 -1
  18. package/src/graphs/MultiAgentGraph.ts +128 -1
  19. package/src/graphs/__tests__/multi-agent-delegate.test.ts +205 -0
  20. package/src/run.ts +20 -11
  21. package/src/scripts/test-bedrock-handoff-autonomous.ts +231 -0
  22. package/src/utils/llm.ts +1 -0
  23. package/src/agents/AgentContext.js +0 -782
  24. package/src/agents/AgentContext.test.js +0 -421
  25. package/src/agents/__tests__/AgentContext.test.js +0 -678
  26. package/src/agents/__tests__/resolveStructuredOutputMode.test.js +0 -117
  27. package/src/common/enum.js +0 -192
  28. package/src/common/index.js +0 -3
  29. package/src/events.js +0 -166
  30. package/src/graphs/Graph.js +0 -1857
  31. package/src/graphs/MultiAgentGraph.js +0 -1092
  32. package/src/graphs/__tests__/structured-output.integration.test.js +0 -624
  33. package/src/graphs/__tests__/structured-output.test.js +0 -144
  34. package/src/graphs/contextManagement.e2e.test.js +0 -718
  35. package/src/graphs/contextManagement.test.js +0 -485
  36. package/src/graphs/handoffValidation.test.js +0 -276
  37. package/src/graphs/index.js +0 -3
  38. package/src/index.js +0 -28
  39. package/src/instrumentation.js +0 -21
  40. package/src/llm/anthropic/index.js +0 -319
  41. package/src/llm/anthropic/types.js +0 -46
  42. package/src/llm/anthropic/utils/message_inputs.js +0 -627
  43. package/src/llm/anthropic/utils/message_outputs.js +0 -290
  44. package/src/llm/anthropic/utils/output_parsers.js +0 -89
  45. package/src/llm/anthropic/utils/tools.js +0 -25
  46. package/src/llm/bedrock/__tests__/bedrock-caching.test.js +0 -392
  47. package/src/llm/bedrock/index.js +0 -303
  48. package/src/llm/bedrock/types.js +0 -2
  49. package/src/llm/bedrock/utils/index.js +0 -6
  50. package/src/llm/bedrock/utils/message_inputs.js +0 -463
  51. package/src/llm/bedrock/utils/message_outputs.js +0 -269
  52. package/src/llm/fake.js +0 -92
  53. package/src/llm/google/index.js +0 -215
  54. package/src/llm/google/types.js +0 -12
  55. package/src/llm/google/utils/common.js +0 -670
  56. package/src/llm/google/utils/tools.js +0 -111
  57. package/src/llm/google/utils/zod_to_genai_parameters.js +0 -47
  58. package/src/llm/openai/index.js +0 -1033
  59. package/src/llm/openai/types.js +0 -2
  60. package/src/llm/openai/utils/index.js +0 -756
  61. package/src/llm/openai/utils/isReasoningModel.test.js +0 -79
  62. package/src/llm/openrouter/index.js +0 -261
  63. package/src/llm/openrouter/reasoning.test.js +0 -181
  64. package/src/llm/providers.js +0 -36
  65. package/src/llm/text.js +0 -65
  66. package/src/llm/vertexai/index.js +0 -402
  67. package/src/messages/__tests__/tools.test.js +0 -392
  68. package/src/messages/cache.js +0 -404
  69. package/src/messages/cache.test.js +0 -1167
  70. package/src/messages/content.js +0 -48
  71. package/src/messages/content.test.js +0 -314
  72. package/src/messages/core.js +0 -359
  73. package/src/messages/ensureThinkingBlock.test.js +0 -997
  74. package/src/messages/format.js +0 -973
  75. package/src/messages/formatAgentMessages.test.js +0 -2278
  76. package/src/messages/formatAgentMessages.tools.test.js +0 -362
  77. package/src/messages/formatMessage.test.js +0 -608
  78. package/src/messages/ids.js +0 -18
  79. package/src/messages/index.js +0 -9
  80. package/src/messages/labelContentByAgent.test.js +0 -725
  81. package/src/messages/prune.js +0 -438
  82. package/src/messages/reducer.js +0 -60
  83. package/src/messages/shiftIndexTokenCountMap.test.js +0 -63
  84. package/src/messages/summarize.js +0 -146
  85. package/src/messages/summarize.test.js +0 -332
  86. package/src/messages/tools.js +0 -90
  87. package/src/mockStream.js +0 -81
  88. package/src/prompts/collab.js +0 -7
  89. package/src/prompts/index.js +0 -3
  90. package/src/prompts/taskmanager.js +0 -58
  91. package/src/run.js +0 -427
  92. package/src/schemas/index.js +0 -3
  93. package/src/schemas/schema-preparation.test.js +0 -370
  94. package/src/schemas/validate.js +0 -314
  95. package/src/schemas/validate.test.js +0 -264
  96. package/src/scripts/abort.js +0 -127
  97. package/src/scripts/ant_web_search.js +0 -130
  98. package/src/scripts/ant_web_search_edge_case.js +0 -133
  99. package/src/scripts/ant_web_search_error_edge_case.js +0 -119
  100. package/src/scripts/args.js +0 -41
  101. package/src/scripts/bedrock-cache-debug.js +0 -186
  102. package/src/scripts/bedrock-content-aggregation-test.js +0 -195
  103. package/src/scripts/bedrock-merge-test.js +0 -80
  104. package/src/scripts/bedrock-parallel-tools-test.js +0 -150
  105. package/src/scripts/caching.js +0 -106
  106. package/src/scripts/cli.js +0 -152
  107. package/src/scripts/cli2.js +0 -119
  108. package/src/scripts/cli3.js +0 -163
  109. package/src/scripts/cli4.js +0 -165
  110. package/src/scripts/cli5.js +0 -165
  111. package/src/scripts/code_exec.js +0 -171
  112. package/src/scripts/code_exec_files.js +0 -180
  113. package/src/scripts/code_exec_multi_session.js +0 -185
  114. package/src/scripts/code_exec_ptc.js +0 -265
  115. package/src/scripts/code_exec_session.js +0 -217
  116. package/src/scripts/code_exec_simple.js +0 -120
  117. package/src/scripts/content.js +0 -111
  118. package/src/scripts/empty_input.js +0 -125
  119. package/src/scripts/handoff-test.js +0 -96
  120. package/src/scripts/image.js +0 -138
  121. package/src/scripts/memory.js +0 -83
  122. package/src/scripts/multi-agent-chain.js +0 -271
  123. package/src/scripts/multi-agent-conditional.js +0 -185
  124. package/src/scripts/multi-agent-document-review-chain.js +0 -171
  125. package/src/scripts/multi-agent-hybrid-flow.js +0 -264
  126. package/src/scripts/multi-agent-parallel-start.js +0 -214
  127. package/src/scripts/multi-agent-parallel.js +0 -346
  128. package/src/scripts/multi-agent-sequence.js +0 -184
  129. package/src/scripts/multi-agent-supervisor.js +0 -324
  130. package/src/scripts/multi-agent-test.js +0 -147
  131. package/src/scripts/parallel-asymmetric-tools-test.js +0 -202
  132. package/src/scripts/parallel-full-metadata-test.js +0 -176
  133. package/src/scripts/parallel-tools-test.js +0 -256
  134. package/src/scripts/programmatic_exec.js +0 -277
  135. package/src/scripts/programmatic_exec_agent.js +0 -168
  136. package/src/scripts/search.js +0 -118
  137. package/src/scripts/sequential-full-metadata-test.js +0 -143
  138. package/src/scripts/simple.js +0 -174
  139. package/src/scripts/single-agent-metadata-test.js +0 -152
  140. package/src/scripts/stream.js +0 -113
  141. package/src/scripts/test-custom-prompt-key.js +0 -132
  142. package/src/scripts/test-handoff-input.js +0 -143
  143. package/src/scripts/test-handoff-preamble.js +0 -227
  144. package/src/scripts/test-handoff-steering.js +0 -353
  145. package/src/scripts/test-multi-agent-list-handoff.js +0 -318
  146. package/src/scripts/test-parallel-agent-labeling.js +0 -253
  147. package/src/scripts/test-parallel-handoffs.js +0 -229
  148. package/src/scripts/test-thinking-handoff-bedrock.js +0 -132
  149. package/src/scripts/test-thinking-handoff.js +0 -132
  150. package/src/scripts/test-thinking-to-thinking-handoff-bedrock.js +0 -140
  151. package/src/scripts/test-tool-before-handoff-role-order.js +0 -223
  152. package/src/scripts/test-tools-before-handoff.js +0 -187
  153. package/src/scripts/test_code_api.js +0 -263
  154. package/src/scripts/thinking-bedrock.js +0 -128
  155. package/src/scripts/thinking-vertexai.js +0 -130
  156. package/src/scripts/thinking.js +0 -134
  157. package/src/scripts/tool_search.js +0 -114
  158. package/src/scripts/tools.js +0 -125
  159. package/src/specs/agent-handoffs-bedrock.integration.test.js +0 -280
  160. package/src/specs/agent-handoffs.test.js +0 -924
  161. package/src/specs/anthropic.simple.test.js +0 -287
  162. package/src/specs/azure.simple.test.js +0 -381
  163. package/src/specs/cache.simple.test.js +0 -282
  164. package/src/specs/custom-event-await.test.js +0 -148
  165. package/src/specs/deepseek.simple.test.js +0 -189
  166. package/src/specs/emergency-prune.test.js +0 -308
  167. package/src/specs/moonshot.simple.test.js +0 -237
  168. package/src/specs/observability.integration.test.js +0 -1337
  169. package/src/specs/openai.simple.test.js +0 -233
  170. package/src/specs/openrouter.simple.test.js +0 -202
  171. package/src/specs/prune.test.js +0 -733
  172. package/src/specs/reasoning.test.js +0 -144
  173. package/src/specs/spec.utils.js +0 -4
  174. package/src/specs/thinking-handoff.test.js +0 -486
  175. package/src/specs/thinking-prune.test.js +0 -600
  176. package/src/specs/token-distribution-edge-case.test.js +0 -246
  177. package/src/specs/token-memoization.test.js +0 -32
  178. package/src/specs/tokens.test.js +0 -49
  179. package/src/specs/tool-error.test.js +0 -139
  180. package/src/splitStream.js +0 -204
  181. package/src/splitStream.test.js +0 -504
  182. package/src/stream.js +0 -650
  183. package/src/stream.test.js +0 -225
  184. package/src/test/mockTools.js +0 -340
  185. package/src/tools/BrowserTools.js +0 -245
  186. package/src/tools/Calculator.js +0 -38
  187. package/src/tools/Calculator.test.js +0 -225
  188. package/src/tools/CodeExecutor.js +0 -233
  189. package/src/tools/ProgrammaticToolCalling.js +0 -602
  190. package/src/tools/StreamingToolCallBuffer.js +0 -179
  191. package/src/tools/ToolNode.js +0 -930
  192. package/src/tools/ToolSearch.js +0 -904
  193. package/src/tools/__tests__/BrowserTools.test.js +0 -306
  194. package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.js +0 -276
  195. package/src/tools/__tests__/ProgrammaticToolCalling.test.js +0 -807
  196. package/src/tools/__tests__/StreamingToolCallBuffer.test.js +0 -175
  197. package/src/tools/__tests__/ToolApproval.test.js +0 -675
  198. package/src/tools/__tests__/ToolNode.recovery.test.js +0 -200
  199. package/src/tools/__tests__/ToolNode.session.test.js +0 -319
  200. package/src/tools/__tests__/ToolSearch.integration.test.js +0 -125
  201. package/src/tools/__tests__/ToolSearch.test.js +0 -812
  202. package/src/tools/__tests__/handlers.test.js +0 -799
  203. package/src/tools/__tests__/truncation-recovery.integration.test.js +0 -362
  204. package/src/tools/handlers.js +0 -306
  205. package/src/tools/schema.js +0 -25
  206. package/src/tools/search/anthropic.js +0 -34
  207. package/src/tools/search/content.js +0 -116
  208. package/src/tools/search/content.test.js +0 -133
  209. package/src/tools/search/firecrawl.js +0 -173
  210. package/src/tools/search/format.js +0 -198
  211. package/src/tools/search/highlights.js +0 -241
  212. package/src/tools/search/index.js +0 -3
  213. package/src/tools/search/jina-reranker.test.js +0 -106
  214. package/src/tools/search/rerankers.js +0 -165
  215. package/src/tools/search/schema.js +0 -102
  216. package/src/tools/search/search.js +0 -561
  217. package/src/tools/search/serper-scraper.js +0 -126
  218. package/src/tools/search/test.js +0 -129
  219. package/src/tools/search/tool.js +0 -453
  220. package/src/tools/search/types.js +0 -2
  221. package/src/tools/search/utils.js +0 -59
  222. package/src/types/graph.js +0 -24
  223. package/src/types/graph.test.js +0 -192
  224. package/src/types/index.js +0 -7
  225. package/src/types/llm.js +0 -2
  226. package/src/types/messages.js +0 -2
  227. package/src/types/run.js +0 -2
  228. package/src/types/stream.js +0 -2
  229. package/src/types/tools.js +0 -2
  230. package/src/utils/contextAnalytics.js +0 -79
  231. package/src/utils/contextAnalytics.test.js +0 -166
  232. package/src/utils/events.js +0 -26
  233. package/src/utils/graph.js +0 -11
  234. package/src/utils/handlers.js +0 -65
  235. package/src/utils/index.js +0 -10
  236. package/src/utils/llm.js +0 -21
  237. package/src/utils/llmConfig.js +0 -205
  238. package/src/utils/logging.js +0 -37
  239. package/src/utils/misc.js +0 -51
  240. package/src/utils/run.js +0 -69
  241. package/src/utils/schema.js +0 -21
  242. package/src/utils/title.js +0 -119
  243. package/src/utils/tokens.js +0 -92
  244. package/src/utils/toonFormat.js +0 -379
@@ -1,379 +0,0 @@
1
- /**
2
- * TOON Format Utility
3
- *
4
- * Provides JSON to TOON conversion for token-efficient encoding.
5
- * TOON format can reduce token count by 30-60% for JSON data.
6
- *
7
- * Uses the official @toon-format/toon library when available.
8
- */
9
- // Dynamic import holder for the TOON library (ESM)
10
- let toonEncode = null;
11
- let toonLoadAttempted = false;
12
- let toonLoadPromise = null;
13
- /**
14
- * Lazily loads the TOON library
15
- * Tries both ESM dynamic import and CommonJS require for compatibility
16
- */
17
- async function loadToonLibrary() {
18
- if (toonLoadAttempted)
19
- return toonEncode !== null;
20
- toonLoadAttempted = true;
21
- // Try ESM dynamic import first
22
- try {
23
- const mod = await import('@toon-format/toon');
24
- toonEncode = mod.encode;
25
- return true;
26
- }
27
- catch {
28
- // ESM import failed, try CommonJS require
29
- try {
30
- // eslint-disable-next-line @typescript-eslint/no-require-imports
31
- const mod = require('@toon-format/toon');
32
- toonEncode = mod.encode;
33
- return true;
34
- }
35
- catch {
36
- // Library not available - that's OK, we'll return original content
37
- return false;
38
- }
39
- }
40
- }
41
- /**
42
- * Ensures the TOON library is loaded. Call this before using jsonToToon in tests.
43
- */
44
- export async function ensureToonLoaded() {
45
- if (!toonLoadPromise) {
46
- toonLoadPromise = loadToonLibrary();
47
- }
48
- return toonLoadPromise;
49
- }
50
- // Start loading immediately
51
- ensureToonLoaded();
52
- /**
53
- * Check if a string appears to be in TOON format.
54
- * TOON format characteristics:
55
- * - Uses key: value syntax (like YAML)
56
- * - Uses array notation like [3] or {fields}
57
- * - Does NOT start with { or [
58
- * - Often has patterns like "name[N]:" or "name{fields}:"
59
- *
60
- * @param str - String to check
61
- * @returns true if string appears to be TOON format
62
- */
63
- export function isToonFormat(str) {
64
- if (typeof str !== 'string' || str.length === 0)
65
- return false;
66
- const trimmed = str.trim();
67
- // TOON doesn't start with JSON brackets
68
- if (trimmed.startsWith('{') || trimmed.startsWith('['))
69
- return false;
70
- // Check for TOON-specific patterns:
71
- // 1. Key-value with colon (but not URL-like patterns)
72
- // 2. Array notation like "items[3]:" or "data[10]:"
73
- // 3. Object schema notation like "items{id,name}:"
74
- const toonPatterns = [
75
- /^\w+:$/m, // Simple key: at start of line
76
- /^\w+\[\d+\]:/m, // Array notation: items[3]:
77
- /^\w+\{[^}]+\}:/m, // Schema notation: items{id,name}:
78
- /^\w+\[\d+\]\{[^}]+\}:/m, // Combined: items[3]{id,name}:
79
- ];
80
- // Must match at least one TOON pattern
81
- const hasToonPattern = toonPatterns.some((pattern) => pattern.test(trimmed));
82
- // Additional check: TOON typically has multiple lines with consistent indentation
83
- const lines = trimmed.split('\n').filter((l) => l.trim());
84
- const hasMultipleKeyValueLines = lines.filter((l) => /^\s*\w+.*:/.test(l)).length >= 2;
85
- return hasToonPattern || hasMultipleKeyValueLines;
86
- }
87
- /**
88
- * Extract the first valid JSON object or array from a string.
89
- * Handles pure JSON or JSON embedded in text (e.g., tool responses).
90
- *
91
- * @param str - The string to extract JSON from
92
- * @returns Object with found status, parsed JSON, and indices
93
- */
94
- export function extractFirstJson(str) {
95
- if (typeof str !== 'string' || str.length === 0) {
96
- return { found: false, parsed: null, startIndex: -1, endIndex: -1 };
97
- }
98
- // Find the first { or [ character
99
- const objStart = str.indexOf('{');
100
- const arrStart = str.indexOf('[');
101
- if (objStart === -1 && arrStart === -1) {
102
- return { found: false, parsed: null, startIndex: -1, endIndex: -1 };
103
- }
104
- let startIndex;
105
- if (objStart === -1) {
106
- startIndex = arrStart;
107
- }
108
- else if (arrStart === -1) {
109
- startIndex = objStart;
110
- }
111
- else {
112
- startIndex = Math.min(objStart, arrStart);
113
- }
114
- // Find the matching closing bracket using a stack-based approach
115
- // Properly handle strings to avoid counting brackets inside strings
116
- let depth = 0;
117
- let inString = false;
118
- let escapeNext = false;
119
- for (let i = startIndex; i < str.length; i++) {
120
- const char = str[i];
121
- if (escapeNext) {
122
- escapeNext = false;
123
- continue;
124
- }
125
- if (char === '\\' && inString) {
126
- escapeNext = true;
127
- continue;
128
- }
129
- if (char === '"') {
130
- inString = !inString;
131
- continue;
132
- }
133
- if (inString)
134
- continue;
135
- if (char === '{' || char === '[')
136
- depth++;
137
- if (char === '}' || char === ']')
138
- depth--;
139
- if (depth === 0) {
140
- // Found matching bracket, try to parse
141
- const jsonStr = str.substring(startIndex, i + 1);
142
- try {
143
- const parsed = JSON.parse(jsonStr);
144
- return { found: true, parsed, startIndex, endIndex: i };
145
- }
146
- catch {
147
- // Not valid JSON at this bracket level, continue searching
148
- // Reset and look for the next JSON start after this position
149
- const nextResult = extractFirstJson(str.substring(i + 1));
150
- if (nextResult.found) {
151
- return {
152
- found: true,
153
- parsed: nextResult.parsed,
154
- startIndex: i + 1 + nextResult.startIndex,
155
- endIndex: i + 1 + nextResult.endIndex,
156
- };
157
- }
158
- return { found: false, parsed: null, startIndex: -1, endIndex: -1 };
159
- }
160
- }
161
- }
162
- return { found: false, parsed: null, startIndex: -1, endIndex: -1 };
163
- }
164
- /**
165
- * Convert JSON content to TOON format for token efficiency.
166
- * Extracts JSON from string if embedded, converts to TOON.
167
- * Returns original string if:
168
- * - Already in TOON format
169
- * - Not JSON
170
- * - TOON conversion fails or is larger
171
- *
172
- * @param str - The string containing JSON to convert
173
- * @returns Object with conversion status, result, and reduction percentage
174
- */
175
- export function jsonToToon(str) {
176
- if (!toonEncode || typeof str !== 'string') {
177
- return {
178
- converted: false,
179
- result: str,
180
- reduction: 0,
181
- error: !toonEncode ? 'TOON library not loaded' : undefined,
182
- };
183
- }
184
- // Check if already in TOON format - skip conversion
185
- if (isToonFormat(str)) {
186
- return { converted: false, result: str, reduction: 0, alreadyToon: true };
187
- }
188
- try {
189
- const { found, parsed, startIndex, endIndex } = extractFirstJson(str);
190
- if (!found || !parsed) {
191
- return {
192
- converted: false,
193
- result: str,
194
- reduction: 0,
195
- error: 'No JSON found in content',
196
- };
197
- }
198
- // Check if this JSON structure would benefit from TOON
199
- // Text-heavy content (emails, documents) won't compress well
200
- if (!isToonBeneficial(parsed)) {
201
- return {
202
- converted: false,
203
- result: str,
204
- reduction: 0,
205
- error: 'Content is text-heavy (>70% string values), TOON not beneficial',
206
- };
207
- }
208
- const toonResult = toonEncode(parsed);
209
- // Preserve text before and after the JSON block
210
- const textBefore = str.substring(0, startIndex);
211
- const textAfter = str.substring(endIndex + 1);
212
- // Build the full result: textBefore + TOON + textAfter
213
- const fullResult = textBefore + toonResult + textAfter;
214
- if (fullResult.length < str.length) {
215
- const reduction = Math.round(((str.length - fullResult.length) / str.length) * 100);
216
- return { converted: true, result: fullResult, reduction };
217
- }
218
- else {
219
- // TOON output was larger or same size - not beneficial
220
- return {
221
- converted: false,
222
- result: str,
223
- reduction: 0,
224
- error: `TOON output not smaller (${fullResult.length} >= ${str.length})`,
225
- };
226
- }
227
- }
228
- catch (err) {
229
- // TOON encoding or extraction failed - log error for debugging
230
- const errorMsg = err instanceof Error ? err.message : String(err);
231
- return {
232
- converted: false,
233
- result: str,
234
- reduction: 0,
235
- error: `TOON conversion error: ${errorMsg}`,
236
- };
237
- }
238
- }
239
- /**
240
- * Check if TOON library is loaded and available
241
- */
242
- export function isToonAvailable() {
243
- return toonEncode !== null;
244
- }
245
- /**
246
- * Analyze JSON structure to determine if TOON conversion would be beneficial.
247
- * Text-heavy content (emails, documents) doesn't compress well with TOON.
248
- * Structured data (API responses, metadata) compresses much better.
249
- *
250
- * @param parsed - Parsed JSON object
251
- * @returns true if TOON conversion is likely beneficial
252
- */
253
- function isToonBeneficial(parsed) {
254
- if (!parsed || typeof parsed !== 'object')
255
- return false;
256
- const jsonStr = JSON.stringify(parsed);
257
- const totalLength = jsonStr.length;
258
- // Count characters in string values (text content)
259
- let textContentLength = 0;
260
- function countTextContent(obj) {
261
- if (typeof obj === 'string') {
262
- // Count string length (this is text content that TOON can't compress)
263
- textContentLength += obj.length;
264
- }
265
- else if (Array.isArray(obj)) {
266
- obj.forEach(countTextContent);
267
- }
268
- else if (obj && typeof obj === 'object') {
269
- Object.values(obj).forEach(countTextContent);
270
- }
271
- }
272
- countTextContent(parsed);
273
- // Calculate ratio of text content to total JSON
274
- const textRatio = textContentLength / totalLength;
275
- // If more than 70% is text content, TOON won't help much
276
- // TOON compresses structure (field names, brackets), not text
277
- return textRatio < 0.7;
278
- }
279
- /**
280
- * Process tool output: apply TOON conversion if beneficial, then truncate if needed.
281
- * This is the main entry point for processing any tool output (regular or MCP).
282
- *
283
- * Flow:
284
- * 1. Check if already TOON format → skip conversion
285
- * 2. Try TOON conversion if content is JSON and large enough
286
- * 3. Truncate if still exceeds maxLength (with smart break points)
287
- *
288
- * @param content - The tool output content
289
- * @param options - Processing options
290
- * @returns Processed content and metadata
291
- */
292
- export function processToolOutput(content, options = {}) {
293
- const { maxLength = 100000, enableToon = true, minSizeForToon = 1000, minReductionPercent = 10, // Increased from 5% - only apply TOON when clearly beneficial
294
- } = options;
295
- const originalLength = content.length;
296
- const originalTokens = Math.ceil(originalLength / 4);
297
- let result = content;
298
- let toonConverted = false;
299
- let alreadyToon = false;
300
- let reduction = 0;
301
- let truncated = false;
302
- let toonError;
303
- // Step 1: Check if already TOON format
304
- if (isToonFormat(content)) {
305
- alreadyToon = true;
306
- }
307
- // Step 2: Apply TOON conversion if enabled and content is large enough
308
- else if (enableToon && content.length > minSizeForToon) {
309
- const toonResult = jsonToToon(content);
310
- if (toonResult.alreadyToon) {
311
- alreadyToon = true;
312
- }
313
- else if (toonResult.converted &&
314
- toonResult.reduction >= minReductionPercent) {
315
- result = toonResult.result;
316
- toonConverted = true;
317
- reduction = toonResult.reduction;
318
- }
319
- else if (toonResult.error) {
320
- // Track error for debugging
321
- toonError = toonResult.error;
322
- }
323
- else if (toonResult.converted &&
324
- toonResult.reduction < minReductionPercent) {
325
- // TOON converted but reduction was too small to be worth it
326
- toonError = `TOON reduction ${toonResult.reduction}% below threshold ${minReductionPercent}%`;
327
- }
328
- else if (!toonResult.converted) {
329
- // Conversion failed without explicit error - investigate
330
- toonError =
331
- toonResult.error || 'TOON conversion returned false with no error';
332
- }
333
- }
334
- // Step 3: Truncate if still too long (with smart break points)
335
- if (result.length > maxLength) {
336
- let truncatedStr = result.substring(0, maxLength);
337
- // Try to find a clean break point
338
- if (toonConverted || alreadyToon) {
339
- // For TOON format, break at newline for cleaner output
340
- const lastNewline = truncatedStr.lastIndexOf('\n');
341
- if (lastNewline > maxLength * 0.7) {
342
- truncatedStr = truncatedStr.substring(0, lastNewline);
343
- }
344
- }
345
- else {
346
- // For JSON, try to find a clean JSON break point
347
- const lastCompleteItem = truncatedStr.lastIndexOf('},');
348
- const lastArrayItem = truncatedStr.lastIndexOf('],');
349
- const breakPoint = Math.max(lastCompleteItem, lastArrayItem);
350
- if (breakPoint > maxLength * 0.5) {
351
- truncatedStr = truncatedStr.substring(0, breakPoint + 1);
352
- }
353
- }
354
- // Build truncation message
355
- const truncationInfo = toonConverted
356
- ? `Original ${originalLength.toLocaleString()} chars → TOON ${result.length.toLocaleString()} chars (${reduction}% saved). ` +
357
- `Still exceeds ${maxLength.toLocaleString()} char limit.`
358
- : `Original output was ${originalLength.toLocaleString()} characters (~${originalTokens.toLocaleString()} tokens).`;
359
- result =
360
- truncatedStr +
361
- `\n\n[OUTPUT_TRUNCATED: ${truncationInfo} Please use more specific queries or smaller date ranges.]`;
362
- truncated = true;
363
- }
364
- const finalLength = result.length;
365
- const finalTokens = Math.ceil(finalLength / 4);
366
- return {
367
- content: result,
368
- toonConverted,
369
- truncated,
370
- reduction,
371
- alreadyToon,
372
- originalLength,
373
- originalTokens,
374
- finalLength,
375
- finalTokens,
376
- toonError,
377
- };
378
- }
379
- //# sourceMappingURL=toonFormat.js.map