illuma-agents 1.0.15 → 1.0.17

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 (63) hide show
  1. package/dist/cjs/common/enum.cjs +18 -0
  2. package/dist/cjs/common/enum.cjs.map +1 -1
  3. package/dist/cjs/graphs/Graph.cjs +88 -20
  4. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  5. package/dist/cjs/llm/openai/index.cjs +1 -0
  6. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  7. package/dist/cjs/main.cjs +13 -0
  8. package/dist/cjs/main.cjs.map +1 -1
  9. package/dist/cjs/messages/core.cjs +16 -8
  10. package/dist/cjs/messages/core.cjs.map +1 -1
  11. package/dist/cjs/messages/format.cjs +8 -2
  12. package/dist/cjs/messages/format.cjs.map +1 -1
  13. package/dist/cjs/messages/tools.cjs +17 -10
  14. package/dist/cjs/messages/tools.cjs.map +1 -1
  15. package/dist/cjs/stream.cjs +1 -0
  16. package/dist/cjs/stream.cjs.map +1 -1
  17. package/dist/cjs/tools/ToolNode.cjs +73 -3
  18. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  19. package/dist/cjs/tools/handlers.cjs +1 -0
  20. package/dist/cjs/tools/handlers.cjs.map +1 -1
  21. package/dist/cjs/utils/contextAnalytics.cjs +64 -0
  22. package/dist/cjs/utils/contextAnalytics.cjs.map +1 -0
  23. package/dist/cjs/utils/toonFormat.cjs +358 -0
  24. package/dist/cjs/utils/toonFormat.cjs.map +1 -0
  25. package/dist/esm/common/enum.mjs +19 -1
  26. package/dist/esm/common/enum.mjs.map +1 -1
  27. package/dist/esm/graphs/Graph.mjs +90 -22
  28. package/dist/esm/graphs/Graph.mjs.map +1 -1
  29. package/dist/esm/llm/openai/index.mjs +1 -0
  30. package/dist/esm/llm/openai/index.mjs.map +1 -1
  31. package/dist/esm/main.mjs +3 -1
  32. package/dist/esm/main.mjs.map +1 -1
  33. package/dist/esm/messages/core.mjs +18 -10
  34. package/dist/esm/messages/core.mjs.map +1 -1
  35. package/dist/esm/messages/format.mjs +9 -3
  36. package/dist/esm/messages/format.mjs.map +1 -1
  37. package/dist/esm/messages/tools.mjs +19 -12
  38. package/dist/esm/messages/tools.mjs.map +1 -1
  39. package/dist/esm/stream.mjs +1 -0
  40. package/dist/esm/stream.mjs.map +1 -1
  41. package/dist/esm/tools/ToolNode.mjs +73 -3
  42. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  43. package/dist/esm/tools/handlers.mjs +1 -0
  44. package/dist/esm/tools/handlers.mjs.map +1 -1
  45. package/dist/esm/utils/contextAnalytics.mjs +62 -0
  46. package/dist/esm/utils/contextAnalytics.mjs.map +1 -0
  47. package/dist/esm/utils/toonFormat.mjs +351 -0
  48. package/dist/esm/utils/toonFormat.mjs.map +1 -0
  49. package/dist/types/common/enum.d.ts +17 -0
  50. package/dist/types/graphs/Graph.d.ts +8 -0
  51. package/dist/types/utils/contextAnalytics.d.ts +37 -0
  52. package/dist/types/utils/index.d.ts +2 -0
  53. package/dist/types/utils/toonFormat.d.ts +111 -0
  54. package/package.json +2 -1
  55. package/src/common/enum.ts +18 -0
  56. package/src/graphs/Graph.ts +113 -27
  57. package/src/messages/core.ts +27 -19
  58. package/src/messages/format.ts +10 -3
  59. package/src/messages/tools.ts +20 -13
  60. package/src/tools/ToolNode.ts +78 -5
  61. package/src/utils/contextAnalytics.ts +95 -0
  62. package/src/utils/index.ts +2 -0
  63. package/src/utils/toonFormat.ts +437 -0
@@ -0,0 +1,351 @@
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
+ 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
+ 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
+ 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
+ function jsonToToon(str) {
176
+ if (!toonEncode || typeof str !== 'string') {
177
+ return { converted: false, result: str, reduction: 0, error: !toonEncode ? 'TOON library not loaded' : undefined };
178
+ }
179
+ // Check if already in TOON format - skip conversion
180
+ if (isToonFormat(str)) {
181
+ return { converted: false, result: str, reduction: 0, alreadyToon: true };
182
+ }
183
+ try {
184
+ const { found, parsed, startIndex, endIndex } = extractFirstJson(str);
185
+ if (!found || !parsed) {
186
+ return { converted: false, result: str, reduction: 0, error: 'No JSON found in content' };
187
+ }
188
+ // Check if this JSON structure would benefit from TOON
189
+ // Text-heavy content (emails, documents) won't compress well
190
+ if (!isToonBeneficial(parsed)) {
191
+ return { converted: false, result: str, reduction: 0, error: 'Content is text-heavy (>70% string values), TOON not beneficial' };
192
+ }
193
+ const toonResult = toonEncode(parsed);
194
+ // Preserve text before and after the JSON block
195
+ const textBefore = str.substring(0, startIndex);
196
+ const textAfter = str.substring(endIndex + 1);
197
+ // Build the full result: textBefore + TOON + textAfter
198
+ const fullResult = textBefore + toonResult + textAfter;
199
+ if (fullResult.length < str.length) {
200
+ const reduction = Math.round(((str.length - fullResult.length) / str.length) * 100);
201
+ return { converted: true, result: fullResult, reduction };
202
+ }
203
+ else {
204
+ // TOON output was larger or same size - not beneficial
205
+ return { converted: false, result: str, reduction: 0, error: `TOON output not smaller (${fullResult.length} >= ${str.length})` };
206
+ }
207
+ }
208
+ catch (err) {
209
+ // TOON encoding or extraction failed - log error for debugging
210
+ const errorMsg = err instanceof Error ? err.message : String(err);
211
+ return { converted: false, result: str, reduction: 0, error: `TOON conversion error: ${errorMsg}` };
212
+ }
213
+ }
214
+ /**
215
+ * Check if TOON library is loaded and available
216
+ */
217
+ function isToonAvailable() {
218
+ return toonEncode !== null;
219
+ }
220
+ /**
221
+ * Analyze JSON structure to determine if TOON conversion would be beneficial.
222
+ * Text-heavy content (emails, documents) doesn't compress well with TOON.
223
+ * Structured data (API responses, metadata) compresses much better.
224
+ *
225
+ * @param parsed - Parsed JSON object
226
+ * @returns true if TOON conversion is likely beneficial
227
+ */
228
+ function isToonBeneficial(parsed) {
229
+ if (!parsed || typeof parsed !== 'object')
230
+ return false;
231
+ const jsonStr = JSON.stringify(parsed);
232
+ const totalLength = jsonStr.length;
233
+ // Count characters in string values (text content)
234
+ let textContentLength = 0;
235
+ function countTextContent(obj) {
236
+ if (typeof obj === 'string') {
237
+ // Count string length (this is text content that TOON can't compress)
238
+ textContentLength += obj.length;
239
+ }
240
+ else if (Array.isArray(obj)) {
241
+ obj.forEach(countTextContent);
242
+ }
243
+ else if (obj && typeof obj === 'object') {
244
+ Object.values(obj).forEach(countTextContent);
245
+ }
246
+ }
247
+ countTextContent(parsed);
248
+ // Calculate ratio of text content to total JSON
249
+ const textRatio = textContentLength / totalLength;
250
+ // If more than 70% is text content, TOON won't help much
251
+ // TOON compresses structure (field names, brackets), not text
252
+ return textRatio < 0.7;
253
+ }
254
+ /**
255
+ * Process tool output: apply TOON conversion if beneficial, then truncate if needed.
256
+ * This is the main entry point for processing any tool output (regular or MCP).
257
+ *
258
+ * Flow:
259
+ * 1. Check if already TOON format → skip conversion
260
+ * 2. Try TOON conversion if content is JSON and large enough
261
+ * 3. Truncate if still exceeds maxLength (with smart break points)
262
+ *
263
+ * @param content - The tool output content
264
+ * @param options - Processing options
265
+ * @returns Processed content and metadata
266
+ */
267
+ function processToolOutput(content, options = {}) {
268
+ const { maxLength = 100000, enableToon = true, minSizeForToon = 1000, minReductionPercent = 10, // Increased from 5% - only apply TOON when clearly beneficial
269
+ } = options;
270
+ const originalLength = content.length;
271
+ const originalTokens = Math.ceil(originalLength / 4);
272
+ let result = content;
273
+ let toonConverted = false;
274
+ let alreadyToon = false;
275
+ let reduction = 0;
276
+ let truncated = false;
277
+ let toonError;
278
+ // Step 1: Check if already TOON format
279
+ if (isToonFormat(content)) {
280
+ alreadyToon = true;
281
+ }
282
+ // Step 2: Apply TOON conversion if enabled and content is large enough
283
+ else if (enableToon && content.length > minSizeForToon) {
284
+ const toonResult = jsonToToon(content);
285
+ if (toonResult.alreadyToon) {
286
+ alreadyToon = true;
287
+ }
288
+ else if (toonResult.converted && toonResult.reduction >= minReductionPercent) {
289
+ result = toonResult.result;
290
+ toonConverted = true;
291
+ reduction = toonResult.reduction;
292
+ }
293
+ else if (toonResult.error) {
294
+ // Track error for debugging
295
+ toonError = toonResult.error;
296
+ }
297
+ else if (toonResult.converted && toonResult.reduction < minReductionPercent) {
298
+ // TOON converted but reduction was too small to be worth it
299
+ toonError = `TOON reduction ${toonResult.reduction}% below threshold ${minReductionPercent}%`;
300
+ }
301
+ else if (!toonResult.converted) {
302
+ // Conversion failed without explicit error - investigate
303
+ toonError = toonResult.error || 'TOON conversion returned false with no error';
304
+ }
305
+ }
306
+ // Step 3: Truncate if still too long (with smart break points)
307
+ if (result.length > maxLength) {
308
+ let truncatedStr = result.substring(0, maxLength);
309
+ // Try to find a clean break point
310
+ if (toonConverted || alreadyToon) {
311
+ // For TOON format, break at newline for cleaner output
312
+ const lastNewline = truncatedStr.lastIndexOf('\n');
313
+ if (lastNewline > maxLength * 0.7) {
314
+ truncatedStr = truncatedStr.substring(0, lastNewline);
315
+ }
316
+ }
317
+ else {
318
+ // For JSON, try to find a clean JSON break point
319
+ const lastCompleteItem = truncatedStr.lastIndexOf('},');
320
+ const lastArrayItem = truncatedStr.lastIndexOf('],');
321
+ const breakPoint = Math.max(lastCompleteItem, lastArrayItem);
322
+ if (breakPoint > maxLength * 0.5) {
323
+ truncatedStr = truncatedStr.substring(0, breakPoint + 1);
324
+ }
325
+ }
326
+ // Build truncation message
327
+ const truncationInfo = toonConverted
328
+ ? `Original ${originalLength.toLocaleString()} chars → TOON ${result.length.toLocaleString()} chars (${reduction}% saved). ` +
329
+ `Still exceeds ${maxLength.toLocaleString()} char limit.`
330
+ : `Original output was ${originalLength.toLocaleString()} characters (~${originalTokens.toLocaleString()} tokens).`;
331
+ result = truncatedStr + `\n\n[OUTPUT_TRUNCATED: ${truncationInfo} Please use more specific queries or smaller date ranges.]`;
332
+ truncated = true;
333
+ }
334
+ const finalLength = result.length;
335
+ const finalTokens = Math.ceil(finalLength / 4);
336
+ return {
337
+ content: result,
338
+ toonConverted,
339
+ truncated,
340
+ reduction,
341
+ alreadyToon,
342
+ originalLength,
343
+ originalTokens,
344
+ finalLength,
345
+ finalTokens,
346
+ toonError,
347
+ };
348
+ }
349
+
350
+ export { ensureToonLoaded, extractFirstJson, isToonAvailable, isToonFormat, jsonToToon, processToolOutput };
351
+ //# sourceMappingURL=toonFormat.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toonFormat.mjs","sources":["../../../src/utils/toonFormat.ts"],"sourcesContent":["/**\r\n * TOON Format Utility\r\n * \r\n * Provides JSON to TOON conversion for token-efficient encoding.\r\n * TOON format can reduce token count by 30-60% for JSON data.\r\n * \r\n * Uses the official @toon-format/toon library when available.\r\n */\r\n\r\n// Dynamic import holder for the TOON library (ESM)\r\nlet toonEncode: ((data: unknown) => string) | null = null;\r\nlet toonLoadAttempted = false;\r\nlet toonLoadPromise: Promise<boolean> | null = null;\r\n\r\n/**\r\n * Lazily loads the TOON library\r\n * Tries both ESM dynamic import and CommonJS require for compatibility\r\n */\r\nasync function loadToonLibrary(): Promise<boolean> {\r\n if (toonLoadAttempted) return toonEncode !== null;\r\n toonLoadAttempted = true;\r\n\r\n // Try ESM dynamic import first\r\n try {\r\n const mod = await import('@toon-format/toon');\r\n toonEncode = mod.encode;\r\n return true;\r\n } catch {\r\n // ESM import failed, try CommonJS require\r\n try {\r\n // eslint-disable-next-line @typescript-eslint/no-require-imports\r\n const mod = require('@toon-format/toon');\r\n toonEncode = mod.encode;\r\n return true;\r\n } catch {\r\n // Library not available - that's OK, we'll return original content\r\n return false;\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Ensures the TOON library is loaded. Call this before using jsonToToon in tests.\r\n */\r\nexport async function ensureToonLoaded(): Promise<boolean> {\r\n if (!toonLoadPromise) {\r\n toonLoadPromise = loadToonLibrary();\r\n }\r\n return toonLoadPromise;\r\n}\r\n\r\n// Start loading immediately\r\nensureToonLoaded();\r\n\r\n/**\r\n * Check if a string appears to be in TOON format.\r\n * TOON format characteristics:\r\n * - Uses key: value syntax (like YAML)\r\n * - Uses array notation like [3] or {fields}\r\n * - Does NOT start with { or [\r\n * - Often has patterns like \"name[N]:\" or \"name{fields}:\"\r\n * \r\n * @param str - String to check\r\n * @returns true if string appears to be TOON format\r\n */\r\nexport function isToonFormat(str: string): boolean {\r\n if (typeof str !== 'string' || str.length === 0) return false;\r\n \r\n const trimmed = str.trim();\r\n \r\n // TOON doesn't start with JSON brackets\r\n if (trimmed.startsWith('{') || trimmed.startsWith('[')) return false;\r\n \r\n // Check for TOON-specific patterns:\r\n // 1. Key-value with colon (but not URL-like patterns)\r\n // 2. Array notation like \"items[3]:\" or \"data[10]:\"\r\n // 3. Object schema notation like \"items{id,name}:\"\r\n const toonPatterns = [\r\n /^\\w+:$/m, // Simple key: at start of line\r\n /^\\w+\\[\\d+\\]:/m, // Array notation: items[3]:\r\n /^\\w+\\{[^}]+\\}:/m, // Schema notation: items{id,name}:\r\n /^\\w+\\[\\d+\\]\\{[^}]+\\}:/m, // Combined: items[3]{id,name}:\r\n ];\r\n \r\n // Must match at least one TOON pattern\r\n const hasToonPattern = toonPatterns.some(pattern => pattern.test(trimmed));\r\n \r\n // Additional check: TOON typically has multiple lines with consistent indentation\r\n const lines = trimmed.split('\\n').filter(l => l.trim());\r\n const hasMultipleKeyValueLines = lines.filter(l => /^\\s*\\w+.*:/.test(l)).length >= 2;\r\n \r\n return hasToonPattern || hasMultipleKeyValueLines;\r\n}\r\n\r\n/**\r\n * Extract the first valid JSON object or array from a string.\r\n * Handles pure JSON or JSON embedded in text (e.g., tool responses).\r\n * \r\n * @param str - The string to extract JSON from\r\n * @returns Object with found status, parsed JSON, and indices\r\n */\r\nexport function extractFirstJson(str: string): {\r\n found: boolean;\r\n parsed: unknown;\r\n startIndex: number;\r\n endIndex: number;\r\n} {\r\n if (typeof str !== 'string' || str.length === 0) {\r\n return { found: false, parsed: null, startIndex: -1, endIndex: -1 };\r\n }\r\n\r\n // Find the first { or [ character\r\n const objStart = str.indexOf('{');\r\n const arrStart = str.indexOf('[');\r\n\r\n if (objStart === -1 && arrStart === -1) {\r\n return { found: false, parsed: null, startIndex: -1, endIndex: -1 };\r\n }\r\n\r\n let startIndex: number;\r\n if (objStart === -1) {\r\n startIndex = arrStart;\r\n } else if (arrStart === -1) {\r\n startIndex = objStart;\r\n } else {\r\n startIndex = Math.min(objStart, arrStart);\r\n }\r\n\r\n // Find the matching closing bracket using a stack-based approach\r\n // Properly handle strings to avoid counting brackets inside strings\r\n let depth = 0;\r\n let inString = false;\r\n let escapeNext = false;\r\n\r\n for (let i = startIndex; i < str.length; i++) {\r\n const char = str[i];\r\n\r\n if (escapeNext) {\r\n escapeNext = false;\r\n continue;\r\n }\r\n\r\n if (char === '\\\\' && inString) {\r\n escapeNext = true;\r\n continue;\r\n }\r\n\r\n if (char === '\"') {\r\n inString = !inString;\r\n continue;\r\n }\r\n\r\n if (inString) continue;\r\n\r\n if (char === '{' || char === '[') depth++;\r\n if (char === '}' || char === ']') depth--;\r\n\r\n if (depth === 0) {\r\n // Found matching bracket, try to parse\r\n const jsonStr = str.substring(startIndex, i + 1);\r\n try {\r\n const parsed = JSON.parse(jsonStr);\r\n return { found: true, parsed, startIndex, endIndex: i };\r\n } catch {\r\n // Not valid JSON at this bracket level, continue searching\r\n // Reset and look for the next JSON start after this position\r\n const nextResult = extractFirstJson(str.substring(i + 1));\r\n if (nextResult.found) {\r\n return {\r\n found: true,\r\n parsed: nextResult.parsed,\r\n startIndex: i + 1 + nextResult.startIndex,\r\n endIndex: i + 1 + nextResult.endIndex,\r\n };\r\n }\r\n return { found: false, parsed: null, startIndex: -1, endIndex: -1 };\r\n }\r\n }\r\n }\r\n\r\n return { found: false, parsed: null, startIndex: -1, endIndex: -1 };\r\n}\r\n\r\n/**\r\n * Convert JSON content to TOON format for token efficiency.\r\n * Extracts JSON from string if embedded, converts to TOON.\r\n * Returns original string if:\r\n * - Already in TOON format\r\n * - Not JSON\r\n * - TOON conversion fails or is larger\r\n * \r\n * @param str - The string containing JSON to convert\r\n * @returns Object with conversion status, result, and reduction percentage\r\n */\r\nexport function jsonToToon(str: string): {\r\n converted: boolean;\r\n result: string;\r\n reduction: number;\r\n alreadyToon?: boolean;\r\n error?: string;\r\n} {\r\n if (!toonEncode || typeof str !== 'string') {\r\n return { converted: false, result: str, reduction: 0, error: !toonEncode ? 'TOON library not loaded' : undefined };\r\n }\r\n\r\n // Check if already in TOON format - skip conversion\r\n if (isToonFormat(str)) {\r\n return { converted: false, result: str, reduction: 0, alreadyToon: true };\r\n }\r\n\r\n try {\r\n const { found, parsed, startIndex, endIndex } = extractFirstJson(str);\r\n\r\n if (!found || !parsed) {\r\n return { converted: false, result: str, reduction: 0, error: 'No JSON found in content' };\r\n }\r\n\r\n // Check if this JSON structure would benefit from TOON\r\n // Text-heavy content (emails, documents) won't compress well\r\n if (!isToonBeneficial(parsed)) {\r\n return { converted: false, result: str, reduction: 0, error: 'Content is text-heavy (>70% string values), TOON not beneficial' };\r\n }\r\n\r\n const toonResult = toonEncode(parsed);\r\n \r\n // Preserve text before and after the JSON block\r\n const textBefore = str.substring(0, startIndex);\r\n const textAfter = str.substring(endIndex + 1);\r\n \r\n // Build the full result: textBefore + TOON + textAfter\r\n const fullResult = textBefore + toonResult + textAfter;\r\n\r\n if (fullResult.length < str.length) {\r\n const reduction = Math.round(((str.length - fullResult.length) / str.length) * 100);\r\n return { converted: true, result: fullResult, reduction };\r\n } else {\r\n // TOON output was larger or same size - not beneficial\r\n return { converted: false, result: str, reduction: 0, error: `TOON output not smaller (${fullResult.length} >= ${str.length})` };\r\n }\r\n } catch (err) {\r\n // TOON encoding or extraction failed - log error for debugging\r\n const errorMsg = err instanceof Error ? err.message : String(err);\r\n return { converted: false, result: str, reduction: 0, error: `TOON conversion error: ${errorMsg}` };\r\n }\r\n}\r\n\r\n/**\r\n * Check if TOON library is loaded and available\r\n */\r\nexport function isToonAvailable(): boolean {\r\n return toonEncode !== null;\r\n}\r\n\r\n/**\r\n * Result of processing tool output\r\n */\r\nexport interface ProcessToolOutputResult {\r\n /** The processed content string */\r\n content: string;\r\n /** Whether TOON conversion was applied */\r\n toonConverted: boolean;\r\n /** Whether content was truncated */\r\n truncated: boolean;\r\n /** Percentage reduction from TOON (0 if not converted) */\r\n reduction: number;\r\n /** Whether input was already in TOON format */\r\n alreadyToon: boolean;\r\n /** Original content length */\r\n originalLength: number;\r\n /** Estimated original tokens (~4 chars per token) */\r\n originalTokens: number;\r\n /** Final content length */\r\n finalLength: number;\r\n /** Estimated final tokens */\r\n finalTokens: number;\r\n /** Error message if TOON conversion failed (for debugging) */\r\n toonError?: string;\r\n}\r\n\r\n/**\r\n * Options for processing tool output\r\n */\r\nexport interface ProcessToolOutputOptions {\r\n /** Maximum output length in characters (default: 100000) */\r\n maxLength?: number;\r\n /** Whether to apply TOON conversion (default: true) */\r\n enableToon?: boolean;\r\n /** Minimum content size to attempt TOON conversion (default: 1000) */\r\n minSizeForToon?: number;\r\n /** Minimum reduction % to accept TOON result (default: 10) */\r\n minReductionPercent?: number;\r\n}\r\n\r\n/**\r\n * Analyze JSON structure to determine if TOON conversion would be beneficial.\r\n * Text-heavy content (emails, documents) doesn't compress well with TOON.\r\n * Structured data (API responses, metadata) compresses much better.\r\n * \r\n * @param parsed - Parsed JSON object\r\n * @returns true if TOON conversion is likely beneficial\r\n */\r\nfunction isToonBeneficial(parsed: unknown): boolean {\r\n if (!parsed || typeof parsed !== 'object') return false;\r\n \r\n const jsonStr = JSON.stringify(parsed);\r\n const totalLength = jsonStr.length;\r\n \r\n // Count characters in string values (text content)\r\n let textContentLength = 0;\r\n \r\n function countTextContent(obj: unknown): void {\r\n if (typeof obj === 'string') {\r\n // Count string length (this is text content that TOON can't compress)\r\n textContentLength += obj.length;\r\n } else if (Array.isArray(obj)) {\r\n obj.forEach(countTextContent);\r\n } else if (obj && typeof obj === 'object') {\r\n Object.values(obj).forEach(countTextContent);\r\n }\r\n }\r\n \r\n countTextContent(parsed);\r\n \r\n // Calculate ratio of text content to total JSON\r\n const textRatio = textContentLength / totalLength;\r\n \r\n // If more than 70% is text content, TOON won't help much\r\n // TOON compresses structure (field names, brackets), not text\r\n return textRatio < 0.7;\r\n}\r\n\r\n/**\r\n * Process tool output: apply TOON conversion if beneficial, then truncate if needed.\r\n * This is the main entry point for processing any tool output (regular or MCP).\r\n * \r\n * Flow:\r\n * 1. Check if already TOON format → skip conversion\r\n * 2. Try TOON conversion if content is JSON and large enough\r\n * 3. Truncate if still exceeds maxLength (with smart break points)\r\n * \r\n * @param content - The tool output content\r\n * @param options - Processing options\r\n * @returns Processed content and metadata\r\n */\r\nexport function processToolOutput(\r\n content: string,\r\n options: ProcessToolOutputOptions = {}\r\n): ProcessToolOutputResult {\r\n const { \r\n maxLength = 100000, \r\n enableToon = true,\r\n minSizeForToon = 1000,\r\n minReductionPercent = 10, // Increased from 5% - only apply TOON when clearly beneficial\r\n } = options;\r\n\r\n const originalLength = content.length;\r\n const originalTokens = Math.ceil(originalLength / 4);\r\n \r\n let result = content;\r\n let toonConverted = false;\r\n let alreadyToon = false;\r\n let reduction = 0;\r\n let truncated = false;\r\n let toonError: string | undefined;\r\n\r\n // Step 1: Check if already TOON format\r\n if (isToonFormat(content)) {\r\n alreadyToon = true;\r\n }\r\n // Step 2: Apply TOON conversion if enabled and content is large enough\r\n else if (enableToon && content.length > minSizeForToon) {\r\n const toonResult = jsonToToon(content);\r\n if (toonResult.alreadyToon) {\r\n alreadyToon = true;\r\n } else if (toonResult.converted && toonResult.reduction >= minReductionPercent) {\r\n result = toonResult.result;\r\n toonConverted = true;\r\n reduction = toonResult.reduction;\r\n } else if (toonResult.error) {\r\n // Track error for debugging\r\n toonError = toonResult.error;\r\n } else if (toonResult.converted && toonResult.reduction < minReductionPercent) {\r\n // TOON converted but reduction was too small to be worth it\r\n toonError = `TOON reduction ${toonResult.reduction}% below threshold ${minReductionPercent}%`;\r\n } else if (!toonResult.converted) {\r\n // Conversion failed without explicit error - investigate\r\n toonError = toonResult.error || 'TOON conversion returned false with no error';\r\n }\r\n }\r\n\r\n // Step 3: Truncate if still too long (with smart break points)\r\n if (result.length > maxLength) {\r\n let truncatedStr = result.substring(0, maxLength);\r\n \r\n // Try to find a clean break point\r\n if (toonConverted || alreadyToon) {\r\n // For TOON format, break at newline for cleaner output\r\n const lastNewline = truncatedStr.lastIndexOf('\\n');\r\n if (lastNewline > maxLength * 0.7) {\r\n truncatedStr = truncatedStr.substring(0, lastNewline);\r\n }\r\n } else {\r\n // For JSON, try to find a clean JSON break point\r\n const lastCompleteItem = truncatedStr.lastIndexOf('},');\r\n const lastArrayItem = truncatedStr.lastIndexOf('],');\r\n const breakPoint = Math.max(lastCompleteItem, lastArrayItem);\r\n if (breakPoint > maxLength * 0.5) {\r\n truncatedStr = truncatedStr.substring(0, breakPoint + 1);\r\n }\r\n }\r\n \r\n // Build truncation message\r\n const truncationInfo = toonConverted\r\n ? `Original ${originalLength.toLocaleString()} chars → TOON ${result.length.toLocaleString()} chars (${reduction}% saved). ` +\r\n `Still exceeds ${maxLength.toLocaleString()} char limit.`\r\n : `Original output was ${originalLength.toLocaleString()} characters (~${originalTokens.toLocaleString()} tokens).`;\r\n \r\n result = truncatedStr + `\\n\\n[OUTPUT_TRUNCATED: ${truncationInfo} Please use more specific queries or smaller date ranges.]`;\r\n truncated = true;\r\n }\r\n\r\n const finalLength = result.length;\r\n const finalTokens = Math.ceil(finalLength / 4);\r\n\r\n return { \r\n content: result, \r\n toonConverted, \r\n truncated, \r\n reduction, \r\n alreadyToon,\r\n originalLength,\r\n originalTokens,\r\n finalLength,\r\n finalTokens,\r\n toonError,\r\n };\r\n}\r\n"],"names":[],"mappings":"AAAA;;;;;;;AAOG;AAEH;AACA,IAAI,UAAU,GAAuC,IAAI;AACzD,IAAI,iBAAiB,GAAG,KAAK;AAC7B,IAAI,eAAe,GAA4B,IAAI;AAEnD;;;AAGG;AACH,eAAe,eAAe,GAAA;AAC5B,IAAA,IAAI,iBAAiB;QAAE,OAAO,UAAU,KAAK,IAAI;IACjD,iBAAiB,GAAG,IAAI;;AAGxB,IAAA,IAAI;AACF,QAAA,MAAM,GAAG,GAAG,MAAM,OAAO,mBAAmB,CAAC;AAC7C,QAAA,UAAU,GAAG,GAAG,CAAC,MAAM;AACvB,QAAA,OAAO,IAAI;;AACX,IAAA,MAAM;;AAEN,QAAA,IAAI;;AAEF,YAAA,MAAM,GAAG,GAAG,OAAO,CAAC,mBAAmB,CAAC;AACxC,YAAA,UAAU,GAAG,GAAG,CAAC,MAAM;AACvB,YAAA,OAAO,IAAI;;AACX,QAAA,MAAM;;AAEN,YAAA,OAAO,KAAK;;;AAGlB;AAEA;;AAEG;AACI,eAAe,gBAAgB,GAAA;IACpC,IAAI,CAAC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AW;AAErH,QAAA,MAAM,GAAG,YAAY,GAAG,CAA0B,uBAAA,EAAA,cAAc,4DAA4D;QAC5H,SAAS,GAAG,IAAI;;AAGlB,IAAA,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM;IACjC,MAAM,WAAW,GAAG,IAAI,CAAC,IAAI,CAAC,WAAW,GAAG,CAAC,CAAC;IAE9C,OAAO;AACL,QAAA,OAAO,EAAE,MAAM;QACf,aAAa;QACb,SAAS;QACT,SAAS;QACT,WAAW;QACX,cAAc;QACd,cAAc;QACd,WAAW;QACX,WAAW;QACX,SAAS;KACV;AACH;;;;"}
@@ -17,6 +17,8 @@ export declare enum GraphEvents {
17
17
  ON_MESSAGE_DELTA = "on_message_delta",
18
18
  /** [Custom] Reasoning Delta events for messages */
19
19
  ON_REASONING_DELTA = "on_reasoning_delta",
20
+ /** [Custom] Context analytics event for traces */
21
+ ON_CONTEXT_ANALYTICS = "on_context_analytics",
20
22
  /** Custom event, emitted by system */
21
23
  ON_CUSTOM_EVENT = "on_custom_event",
22
24
  /** Emitted when a chat model starts processing. */
@@ -129,3 +131,18 @@ export declare enum EnvVar {
129
131
  CODE_API_KEY = "CODE_EXECUTOR_API_KEY",
130
132
  CODE_BASEURL = "CODE_EXECUTOR_BASEURL"
131
133
  }
134
+ /**
135
+ * Message type identifiers used by LangChain's BaseMessage.getType().
136
+ * Use these constants instead of instanceof checks to avoid module mismatch issues
137
+ * when different copies of @langchain/core/messages are loaded.
138
+ */
139
+ export declare enum MessageTypes {
140
+ HUMAN = "human",
141
+ AI = "ai",
142
+ SYSTEM = "system",
143
+ TOOL = "tool",
144
+ FUNCTION = "function",
145
+ GENERIC = "generic",
146
+ DEVELOPER = "developer",
147
+ REMOVE = "remove"
148
+ }
@@ -4,6 +4,7 @@ import type { UsageMetadata, BaseMessage } from '@langchain/core/messages';
4
4
  import type { ToolCall } from '@langchain/core/messages/tool';
5
5
  import type * as t from '@/types';
6
6
  import { Providers } from '@/common';
7
+ import { type ContextAnalytics } from '@/utils/contextAnalytics';
7
8
  import { ToolNode as CustomToolNode } from '@/tools/ToolNode';
8
9
  import { AgentContext } from '@/agents/AgentContext';
9
10
  import { HandlerRegistry } from '@/events';
@@ -113,6 +114,13 @@ export declare class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode>
113
114
  tokens: number;
114
115
  }>;
115
116
  } | null;
117
+ /**
118
+ * Get the latest context analytics from the graph.
119
+ * Returns metrics like utilization %, TOON stats, message breakdown.
120
+ */
121
+ getContextAnalytics(): ContextAnalytics | null;
122
+ /** Store the latest context analytics for retrieval after run */
123
+ private lastContextAnalytics;
116
124
  createSystemRunnable({ provider, clientOptions, instructions, additional_instructions, }: {
117
125
  provider?: Providers;
118
126
  clientOptions?: t.ClientOptions;
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Context Analytics Utility
3
+ *
4
+ * Provides context analytics data for observability/traces.
5
+ * No console logging - just data structures for event emission.
6
+ */
7
+ import type { BaseMessage } from '@langchain/core/messages';
8
+ import type { TokenCounter } from '@/types/run';
9
+ /**
10
+ * Context analytics data for traces
11
+ */
12
+ export interface ContextAnalytics {
13
+ /** Total messages in context */
14
+ messageCount: number;
15
+ /** Total tokens in context */
16
+ totalTokens: number;
17
+ /** Maximum allowed context tokens */
18
+ maxContextTokens?: number;
19
+ /** Instruction/system tokens */
20
+ instructionTokens?: number;
21
+ /** Context utilization percentage (0-100) */
22
+ utilizationPercent?: number;
23
+ /** Breakdown by message type */
24
+ breakdown?: Record<string, {
25
+ tokens: number;
26
+ percent: number;
27
+ }>;
28
+ }
29
+ /**
30
+ * Build context analytics for traces (no logging)
31
+ */
32
+ export declare function buildContextAnalytics(messages: BaseMessage[], options: {
33
+ tokenCounter?: TokenCounter;
34
+ maxContextTokens?: number;
35
+ instructionTokens?: number;
36
+ indexTokenCountMap?: Record<string, number | undefined>;
37
+ }): ContextAnalytics;
@@ -4,3 +4,5 @@ export * from './misc';
4
4
  export * from './handlers';
5
5
  export * from './run';
6
6
  export * from './tokens';
7
+ export * from './toonFormat';
8
+ export * from './contextAnalytics';
@@ -0,0 +1,111 @@
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
+ /**
10
+ * Ensures the TOON library is loaded. Call this before using jsonToToon in tests.
11
+ */
12
+ export declare function ensureToonLoaded(): Promise<boolean>;
13
+ /**
14
+ * Check if a string appears to be in TOON format.
15
+ * TOON format characteristics:
16
+ * - Uses key: value syntax (like YAML)
17
+ * - Uses array notation like [3] or {fields}
18
+ * - Does NOT start with { or [
19
+ * - Often has patterns like "name[N]:" or "name{fields}:"
20
+ *
21
+ * @param str - String to check
22
+ * @returns true if string appears to be TOON format
23
+ */
24
+ export declare function isToonFormat(str: string): boolean;
25
+ /**
26
+ * Extract the first valid JSON object or array from a string.
27
+ * Handles pure JSON or JSON embedded in text (e.g., tool responses).
28
+ *
29
+ * @param str - The string to extract JSON from
30
+ * @returns Object with found status, parsed JSON, and indices
31
+ */
32
+ export declare function extractFirstJson(str: string): {
33
+ found: boolean;
34
+ parsed: unknown;
35
+ startIndex: number;
36
+ endIndex: number;
37
+ };
38
+ /**
39
+ * Convert JSON content to TOON format for token efficiency.
40
+ * Extracts JSON from string if embedded, converts to TOON.
41
+ * Returns original string if:
42
+ * - Already in TOON format
43
+ * - Not JSON
44
+ * - TOON conversion fails or is larger
45
+ *
46
+ * @param str - The string containing JSON to convert
47
+ * @returns Object with conversion status, result, and reduction percentage
48
+ */
49
+ export declare function jsonToToon(str: string): {
50
+ converted: boolean;
51
+ result: string;
52
+ reduction: number;
53
+ alreadyToon?: boolean;
54
+ error?: string;
55
+ };
56
+ /**
57
+ * Check if TOON library is loaded and available
58
+ */
59
+ export declare function isToonAvailable(): boolean;
60
+ /**
61
+ * Result of processing tool output
62
+ */
63
+ export interface ProcessToolOutputResult {
64
+ /** The processed content string */
65
+ content: string;
66
+ /** Whether TOON conversion was applied */
67
+ toonConverted: boolean;
68
+ /** Whether content was truncated */
69
+ truncated: boolean;
70
+ /** Percentage reduction from TOON (0 if not converted) */
71
+ reduction: number;
72
+ /** Whether input was already in TOON format */
73
+ alreadyToon: boolean;
74
+ /** Original content length */
75
+ originalLength: number;
76
+ /** Estimated original tokens (~4 chars per token) */
77
+ originalTokens: number;
78
+ /** Final content length */
79
+ finalLength: number;
80
+ /** Estimated final tokens */
81
+ finalTokens: number;
82
+ /** Error message if TOON conversion failed (for debugging) */
83
+ toonError?: string;
84
+ }
85
+ /**
86
+ * Options for processing tool output
87
+ */
88
+ export interface ProcessToolOutputOptions {
89
+ /** Maximum output length in characters (default: 100000) */
90
+ maxLength?: number;
91
+ /** Whether to apply TOON conversion (default: true) */
92
+ enableToon?: boolean;
93
+ /** Minimum content size to attempt TOON conversion (default: 1000) */
94
+ minSizeForToon?: number;
95
+ /** Minimum reduction % to accept TOON result (default: 10) */
96
+ minReductionPercent?: number;
97
+ }
98
+ /**
99
+ * Process tool output: apply TOON conversion if beneficial, then truncate if needed.
100
+ * This is the main entry point for processing any tool output (regular or MCP).
101
+ *
102
+ * Flow:
103
+ * 1. Check if already TOON format → skip conversion
104
+ * 2. Try TOON conversion if content is JSON and large enough
105
+ * 3. Truncate if still exceeds maxLength (with smart break points)
106
+ *
107
+ * @param content - The tool output content
108
+ * @param options - Processing options
109
+ * @returns Processed content and metadata
110
+ */
111
+ export declare function processToolOutput(content: string, options?: ProcessToolOutputOptions): ProcessToolOutputResult;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "illuma-agents",
3
- "version": "1.0.15",
3
+ "version": "1.0.17",
4
4
  "main": "./dist/cjs/main.cjs",
5
5
  "module": "./dist/esm/main.mjs",
6
6
  "types": "./dist/types/index.d.ts",
@@ -111,6 +111,7 @@
111
111
  "@langfuse/otel": "^4.3.0",
112
112
  "@langfuse/tracing": "^4.3.0",
113
113
  "@opentelemetry/sdk-node": "^0.207.0",
114
+ "@toon-format/toon": "^2.1.0",
114
115
  "axios": "^1.12.1",
115
116
  "cheerio": "^1.0.0",
116
117
  "dotenv": "^16.4.7",
@@ -19,6 +19,8 @@ export enum GraphEvents {
19
19
  ON_MESSAGE_DELTA = 'on_message_delta',
20
20
  /** [Custom] Reasoning Delta events for messages */
21
21
  ON_REASONING_DELTA = 'on_reasoning_delta',
22
+ /** [Custom] Context analytics event for traces */
23
+ ON_CONTEXT_ANALYTICS = 'on_context_analytics',
22
24
 
23
25
  /* Official Events */
24
26
 
@@ -176,3 +178,19 @@ export enum EnvVar {
176
178
  CODE_API_KEY = 'CODE_EXECUTOR_API_KEY',
177
179
  CODE_BASEURL = 'CODE_EXECUTOR_BASEURL',
178
180
  }
181
+
182
+ /**
183
+ * Message type identifiers used by LangChain's BaseMessage.getType().
184
+ * Use these constants instead of instanceof checks to avoid module mismatch issues
185
+ * when different copies of @langchain/core/messages are loaded.
186
+ */
187
+ export enum MessageTypes {
188
+ HUMAN = 'human',
189
+ AI = 'ai',
190
+ SYSTEM = 'system',
191
+ TOOL = 'tool',
192
+ FUNCTION = 'function',
193
+ GENERIC = 'generic',
194
+ DEVELOPER = 'developer',
195
+ REMOVE = 'remove',
196
+ }