illuma-agents 1.0.16 → 1.0.18

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 (114) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +3 -1
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/common/enum.cjs +18 -0
  4. package/dist/cjs/common/enum.cjs.map +1 -1
  5. package/dist/cjs/graphs/Graph.cjs +79 -32
  6. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  7. package/dist/cjs/llm/bedrock/index.cjs +5 -3
  8. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  9. package/dist/cjs/llm/openai/index.cjs +1 -0
  10. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  11. package/dist/cjs/llm/openrouter/index.cjs +10 -1
  12. package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
  13. package/dist/cjs/llm/vertexai/index.cjs +7 -8
  14. package/dist/cjs/llm/vertexai/index.cjs.map +1 -1
  15. package/dist/cjs/main.cjs +15 -0
  16. package/dist/cjs/main.cjs.map +1 -1
  17. package/dist/cjs/messages/cache.cjs +11 -6
  18. package/dist/cjs/messages/cache.cjs.map +1 -1
  19. package/dist/cjs/messages/core.cjs +16 -8
  20. package/dist/cjs/messages/core.cjs.map +1 -1
  21. package/dist/cjs/messages/format.cjs +9 -2
  22. package/dist/cjs/messages/format.cjs.map +1 -1
  23. package/dist/cjs/messages/tools.cjs +17 -10
  24. package/dist/cjs/messages/tools.cjs.map +1 -1
  25. package/dist/cjs/stream.cjs +30 -16
  26. package/dist/cjs/stream.cjs.map +1 -1
  27. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +209 -47
  28. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  29. package/dist/cjs/tools/ToolNode.cjs +73 -3
  30. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  31. package/dist/cjs/tools/handlers.cjs +1 -0
  32. package/dist/cjs/tools/handlers.cjs.map +1 -1
  33. package/dist/cjs/tools/search/search.cjs.map +1 -1
  34. package/dist/cjs/tools/search/tool.cjs +3 -1
  35. package/dist/cjs/tools/search/tool.cjs.map +1 -1
  36. package/dist/cjs/utils/contextAnalytics.cjs +66 -0
  37. package/dist/cjs/utils/contextAnalytics.cjs.map +1 -0
  38. package/dist/cjs/utils/run.cjs.map +1 -1
  39. package/dist/cjs/utils/toonFormat.cjs +388 -0
  40. package/dist/cjs/utils/toonFormat.cjs.map +1 -0
  41. package/dist/esm/agents/AgentContext.mjs +3 -1
  42. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  43. package/dist/esm/common/enum.mjs +19 -1
  44. package/dist/esm/common/enum.mjs.map +1 -1
  45. package/dist/esm/graphs/Graph.mjs +81 -34
  46. package/dist/esm/graphs/Graph.mjs.map +1 -1
  47. package/dist/esm/llm/bedrock/index.mjs +5 -3
  48. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  49. package/dist/esm/llm/openai/index.mjs +1 -0
  50. package/dist/esm/llm/openai/index.mjs.map +1 -1
  51. package/dist/esm/llm/openrouter/index.mjs +10 -1
  52. package/dist/esm/llm/openrouter/index.mjs.map +1 -1
  53. package/dist/esm/llm/vertexai/index.mjs +7 -8
  54. package/dist/esm/llm/vertexai/index.mjs.map +1 -1
  55. package/dist/esm/main.mjs +4 -2
  56. package/dist/esm/main.mjs.map +1 -1
  57. package/dist/esm/messages/cache.mjs +11 -6
  58. package/dist/esm/messages/cache.mjs.map +1 -1
  59. package/dist/esm/messages/core.mjs +18 -10
  60. package/dist/esm/messages/core.mjs.map +1 -1
  61. package/dist/esm/messages/format.mjs +10 -3
  62. package/dist/esm/messages/format.mjs.map +1 -1
  63. package/dist/esm/messages/tools.mjs +19 -12
  64. package/dist/esm/messages/tools.mjs.map +1 -1
  65. package/dist/esm/stream.mjs +30 -16
  66. package/dist/esm/stream.mjs.map +1 -1
  67. package/dist/esm/tools/ProgrammaticToolCalling.mjs +208 -48
  68. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  69. package/dist/esm/tools/ToolNode.mjs +73 -3
  70. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  71. package/dist/esm/tools/handlers.mjs +1 -0
  72. package/dist/esm/tools/handlers.mjs.map +1 -1
  73. package/dist/esm/tools/search/search.mjs.map +1 -1
  74. package/dist/esm/tools/search/tool.mjs +3 -1
  75. package/dist/esm/tools/search/tool.mjs.map +1 -1
  76. package/dist/esm/utils/contextAnalytics.mjs +64 -0
  77. package/dist/esm/utils/contextAnalytics.mjs.map +1 -0
  78. package/dist/esm/utils/run.mjs.map +1 -1
  79. package/dist/esm/utils/toonFormat.mjs +381 -0
  80. package/dist/esm/utils/toonFormat.mjs.map +1 -0
  81. package/dist/types/common/enum.d.ts +17 -0
  82. package/dist/types/graphs/Graph.d.ts +8 -0
  83. package/dist/types/tools/ProgrammaticToolCalling.d.ts +19 -0
  84. package/dist/types/types/tools.d.ts +3 -1
  85. package/dist/types/utils/contextAnalytics.d.ts +37 -0
  86. package/dist/types/utils/index.d.ts +2 -0
  87. package/dist/types/utils/toonFormat.d.ts +111 -0
  88. package/package.json +3 -2
  89. package/src/agents/AgentContext.ts +28 -20
  90. package/src/common/enum.ts +18 -0
  91. package/src/graphs/Graph.ts +152 -62
  92. package/src/llm/bedrock/__tests__/bedrock-caching.test.ts +495 -473
  93. package/src/llm/bedrock/index.ts +47 -35
  94. package/src/llm/openrouter/index.ts +11 -1
  95. package/src/llm/vertexai/index.ts +9 -10
  96. package/src/messages/cache.ts +104 -55
  97. package/src/messages/core.ts +29 -19
  98. package/src/messages/format.ts +14 -3
  99. package/src/messages/tools.ts +20 -13
  100. package/src/scripts/simple.ts +1 -1
  101. package/src/specs/emergency-prune.test.ts +407 -355
  102. package/src/stream.ts +28 -20
  103. package/src/tools/ProgrammaticToolCalling.ts +246 -52
  104. package/src/tools/ToolNode.ts +78 -5
  105. package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +155 -0
  106. package/src/tools/search/jina-reranker.test.ts +32 -28
  107. package/src/tools/search/search.ts +3 -1
  108. package/src/tools/search/tool.ts +16 -7
  109. package/src/types/tools.ts +3 -1
  110. package/src/utils/contextAnalytics.ts +103 -0
  111. package/src/utils/index.ts +2 -0
  112. package/src/utils/llmConfig.ts +8 -1
  113. package/src/utils/run.ts +5 -4
  114. package/src/utils/toonFormat.ts +475 -0
@@ -0,0 +1,475 @@
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
+ // Dynamic import holder for the TOON library (ESM)
11
+ let toonEncode: ((data: unknown) => string) | null = null;
12
+ let toonLoadAttempted = false;
13
+ let toonLoadPromise: Promise<boolean> | null = null;
14
+
15
+ /**
16
+ * Lazily loads the TOON library
17
+ * Tries both ESM dynamic import and CommonJS require for compatibility
18
+ */
19
+ async function loadToonLibrary(): Promise<boolean> {
20
+ if (toonLoadAttempted) return toonEncode !== null;
21
+ toonLoadAttempted = true;
22
+
23
+ // Try ESM dynamic import first
24
+ try {
25
+ const mod = await import('@toon-format/toon');
26
+ toonEncode = mod.encode;
27
+ return true;
28
+ } catch {
29
+ // ESM import failed, try CommonJS require
30
+ try {
31
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
32
+ const mod = require('@toon-format/toon');
33
+ toonEncode = mod.encode;
34
+ return true;
35
+ } catch {
36
+ // Library not available - that's OK, we'll return original content
37
+ return false;
38
+ }
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Ensures the TOON library is loaded. Call this before using jsonToToon in tests.
44
+ */
45
+ export async function ensureToonLoaded(): Promise<boolean> {
46
+ if (!toonLoadPromise) {
47
+ toonLoadPromise = loadToonLibrary();
48
+ }
49
+ return toonLoadPromise;
50
+ }
51
+
52
+ // Start loading immediately
53
+ ensureToonLoaded();
54
+
55
+ /**
56
+ * Check if a string appears to be in TOON format.
57
+ * TOON format characteristics:
58
+ * - Uses key: value syntax (like YAML)
59
+ * - Uses array notation like [3] or {fields}
60
+ * - Does NOT start with { or [
61
+ * - Often has patterns like "name[N]:" or "name{fields}:"
62
+ *
63
+ * @param str - String to check
64
+ * @returns true if string appears to be TOON format
65
+ */
66
+ export function isToonFormat(str: string): boolean {
67
+ if (typeof str !== 'string' || str.length === 0) return false;
68
+
69
+ const trimmed = str.trim();
70
+
71
+ // TOON doesn't start with JSON brackets
72
+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) return false;
73
+
74
+ // Check for TOON-specific patterns:
75
+ // 1. Key-value with colon (but not URL-like patterns)
76
+ // 2. Array notation like "items[3]:" or "data[10]:"
77
+ // 3. Object schema notation like "items{id,name}:"
78
+ const toonPatterns = [
79
+ /^\w+:$/m, // Simple key: at start of line
80
+ /^\w+\[\d+\]:/m, // Array notation: items[3]:
81
+ /^\w+\{[^}]+\}:/m, // Schema notation: items{id,name}:
82
+ /^\w+\[\d+\]\{[^}]+\}:/m, // Combined: items[3]{id,name}:
83
+ ];
84
+
85
+ // Must match at least one TOON pattern
86
+ const hasToonPattern = toonPatterns.some((pattern) => pattern.test(trimmed));
87
+
88
+ // Additional check: TOON typically has multiple lines with consistent indentation
89
+ const lines = trimmed.split('\n').filter((l) => l.trim());
90
+ const hasMultipleKeyValueLines =
91
+ lines.filter((l) => /^\s*\w+.*:/.test(l)).length >= 2;
92
+
93
+ return hasToonPattern || hasMultipleKeyValueLines;
94
+ }
95
+
96
+ /**
97
+ * Extract the first valid JSON object or array from a string.
98
+ * Handles pure JSON or JSON embedded in text (e.g., tool responses).
99
+ *
100
+ * @param str - The string to extract JSON from
101
+ * @returns Object with found status, parsed JSON, and indices
102
+ */
103
+ export function extractFirstJson(str: string): {
104
+ found: boolean;
105
+ parsed: unknown;
106
+ startIndex: number;
107
+ endIndex: number;
108
+ } {
109
+ if (typeof str !== 'string' || str.length === 0) {
110
+ return { found: false, parsed: null, startIndex: -1, endIndex: -1 };
111
+ }
112
+
113
+ // Find the first { or [ character
114
+ const objStart = str.indexOf('{');
115
+ const arrStart = str.indexOf('[');
116
+
117
+ if (objStart === -1 && arrStart === -1) {
118
+ return { found: false, parsed: null, startIndex: -1, endIndex: -1 };
119
+ }
120
+
121
+ let startIndex: number;
122
+ if (objStart === -1) {
123
+ startIndex = arrStart;
124
+ } else if (arrStart === -1) {
125
+ startIndex = objStart;
126
+ } else {
127
+ startIndex = Math.min(objStart, arrStart);
128
+ }
129
+
130
+ // Find the matching closing bracket using a stack-based approach
131
+ // Properly handle strings to avoid counting brackets inside strings
132
+ let depth = 0;
133
+ let inString = false;
134
+ let escapeNext = false;
135
+
136
+ for (let i = startIndex; i < str.length; i++) {
137
+ const char = str[i];
138
+
139
+ if (escapeNext) {
140
+ escapeNext = false;
141
+ continue;
142
+ }
143
+
144
+ if (char === '\\' && inString) {
145
+ escapeNext = true;
146
+ continue;
147
+ }
148
+
149
+ if (char === '"') {
150
+ inString = !inString;
151
+ continue;
152
+ }
153
+
154
+ if (inString) continue;
155
+
156
+ if (char === '{' || char === '[') depth++;
157
+ if (char === '}' || char === ']') depth--;
158
+
159
+ if (depth === 0) {
160
+ // Found matching bracket, try to parse
161
+ const jsonStr = str.substring(startIndex, i + 1);
162
+ try {
163
+ const parsed = JSON.parse(jsonStr);
164
+ return { found: true, parsed, startIndex, endIndex: i };
165
+ } catch {
166
+ // Not valid JSON at this bracket level, continue searching
167
+ // Reset and look for the next JSON start after this position
168
+ const nextResult = extractFirstJson(str.substring(i + 1));
169
+ if (nextResult.found) {
170
+ return {
171
+ found: true,
172
+ parsed: nextResult.parsed,
173
+ startIndex: i + 1 + nextResult.startIndex,
174
+ endIndex: i + 1 + nextResult.endIndex,
175
+ };
176
+ }
177
+ return { found: false, parsed: null, startIndex: -1, endIndex: -1 };
178
+ }
179
+ }
180
+ }
181
+
182
+ return { found: false, parsed: null, startIndex: -1, endIndex: -1 };
183
+ }
184
+
185
+ /**
186
+ * Convert JSON content to TOON format for token efficiency.
187
+ * Extracts JSON from string if embedded, converts to TOON.
188
+ * Returns original string if:
189
+ * - Already in TOON format
190
+ * - Not JSON
191
+ * - TOON conversion fails or is larger
192
+ *
193
+ * @param str - The string containing JSON to convert
194
+ * @returns Object with conversion status, result, and reduction percentage
195
+ */
196
+ export function jsonToToon(str: string): {
197
+ converted: boolean;
198
+ result: string;
199
+ reduction: number;
200
+ alreadyToon?: boolean;
201
+ error?: string;
202
+ } {
203
+ if (!toonEncode || typeof str !== 'string') {
204
+ return {
205
+ converted: false,
206
+ result: str,
207
+ reduction: 0,
208
+ error: !toonEncode ? 'TOON library not loaded' : undefined,
209
+ };
210
+ }
211
+
212
+ // Check if already in TOON format - skip conversion
213
+ if (isToonFormat(str)) {
214
+ return { converted: false, result: str, reduction: 0, alreadyToon: true };
215
+ }
216
+
217
+ try {
218
+ const { found, parsed, startIndex, endIndex } = extractFirstJson(str);
219
+
220
+ if (!found || !parsed) {
221
+ return {
222
+ converted: false,
223
+ result: str,
224
+ reduction: 0,
225
+ error: 'No JSON found in content',
226
+ };
227
+ }
228
+
229
+ // Check if this JSON structure would benefit from TOON
230
+ // Text-heavy content (emails, documents) won't compress well
231
+ if (!isToonBeneficial(parsed)) {
232
+ return {
233
+ converted: false,
234
+ result: str,
235
+ reduction: 0,
236
+ error:
237
+ 'Content is text-heavy (>70% string values), TOON not beneficial',
238
+ };
239
+ }
240
+
241
+ const toonResult = toonEncode(parsed);
242
+
243
+ // Preserve text before and after the JSON block
244
+ const textBefore = str.substring(0, startIndex);
245
+ const textAfter = str.substring(endIndex + 1);
246
+
247
+ // Build the full result: textBefore + TOON + textAfter
248
+ const fullResult = textBefore + toonResult + textAfter;
249
+
250
+ if (fullResult.length < str.length) {
251
+ const reduction = Math.round(
252
+ ((str.length - fullResult.length) / str.length) * 100
253
+ );
254
+ return { converted: true, result: fullResult, reduction };
255
+ } else {
256
+ // TOON output was larger or same size - not beneficial
257
+ return {
258
+ converted: false,
259
+ result: str,
260
+ reduction: 0,
261
+ error: `TOON output not smaller (${fullResult.length} >= ${str.length})`,
262
+ };
263
+ }
264
+ } catch (err) {
265
+ // TOON encoding or extraction failed - log error for debugging
266
+ const errorMsg = err instanceof Error ? err.message : String(err);
267
+ return {
268
+ converted: false,
269
+ result: str,
270
+ reduction: 0,
271
+ error: `TOON conversion error: ${errorMsg}`,
272
+ };
273
+ }
274
+ }
275
+
276
+ /**
277
+ * Check if TOON library is loaded and available
278
+ */
279
+ export function isToonAvailable(): boolean {
280
+ return toonEncode !== null;
281
+ }
282
+
283
+ /**
284
+ * Result of processing tool output
285
+ */
286
+ export interface ProcessToolOutputResult {
287
+ /** The processed content string */
288
+ content: string;
289
+ /** Whether TOON conversion was applied */
290
+ toonConverted: boolean;
291
+ /** Whether content was truncated */
292
+ truncated: boolean;
293
+ /** Percentage reduction from TOON (0 if not converted) */
294
+ reduction: number;
295
+ /** Whether input was already in TOON format */
296
+ alreadyToon: boolean;
297
+ /** Original content length */
298
+ originalLength: number;
299
+ /** Estimated original tokens (~4 chars per token) */
300
+ originalTokens: number;
301
+ /** Final content length */
302
+ finalLength: number;
303
+ /** Estimated final tokens */
304
+ finalTokens: number;
305
+ /** Error message if TOON conversion failed (for debugging) */
306
+ toonError?: string;
307
+ }
308
+
309
+ /**
310
+ * Options for processing tool output
311
+ */
312
+ export interface ProcessToolOutputOptions {
313
+ /** Maximum output length in characters (default: 100000) */
314
+ maxLength?: number;
315
+ /** Whether to apply TOON conversion (default: true) */
316
+ enableToon?: boolean;
317
+ /** Minimum content size to attempt TOON conversion (default: 1000) */
318
+ minSizeForToon?: number;
319
+ /** Minimum reduction % to accept TOON result (default: 10) */
320
+ minReductionPercent?: number;
321
+ }
322
+
323
+ /**
324
+ * Analyze JSON structure to determine if TOON conversion would be beneficial.
325
+ * Text-heavy content (emails, documents) doesn't compress well with TOON.
326
+ * Structured data (API responses, metadata) compresses much better.
327
+ *
328
+ * @param parsed - Parsed JSON object
329
+ * @returns true if TOON conversion is likely beneficial
330
+ */
331
+ function isToonBeneficial(parsed: unknown): boolean {
332
+ if (!parsed || typeof parsed !== 'object') return false;
333
+
334
+ const jsonStr = JSON.stringify(parsed);
335
+ const totalLength = jsonStr.length;
336
+
337
+ // Count characters in string values (text content)
338
+ let textContentLength = 0;
339
+
340
+ function countTextContent(obj: unknown): void {
341
+ if (typeof obj === 'string') {
342
+ // Count string length (this is text content that TOON can't compress)
343
+ textContentLength += obj.length;
344
+ } else if (Array.isArray(obj)) {
345
+ obj.forEach(countTextContent);
346
+ } else if (obj && typeof obj === 'object') {
347
+ Object.values(obj).forEach(countTextContent);
348
+ }
349
+ }
350
+
351
+ countTextContent(parsed);
352
+
353
+ // Calculate ratio of text content to total JSON
354
+ const textRatio = textContentLength / totalLength;
355
+
356
+ // If more than 70% is text content, TOON won't help much
357
+ // TOON compresses structure (field names, brackets), not text
358
+ return textRatio < 0.7;
359
+ }
360
+
361
+ /**
362
+ * Process tool output: apply TOON conversion if beneficial, then truncate if needed.
363
+ * This is the main entry point for processing any tool output (regular or MCP).
364
+ *
365
+ * Flow:
366
+ * 1. Check if already TOON format → skip conversion
367
+ * 2. Try TOON conversion if content is JSON and large enough
368
+ * 3. Truncate if still exceeds maxLength (with smart break points)
369
+ *
370
+ * @param content - The tool output content
371
+ * @param options - Processing options
372
+ * @returns Processed content and metadata
373
+ */
374
+ export function processToolOutput(
375
+ content: string,
376
+ options: ProcessToolOutputOptions = {}
377
+ ): ProcessToolOutputResult {
378
+ const {
379
+ maxLength = 100000,
380
+ enableToon = true,
381
+ minSizeForToon = 1000,
382
+ minReductionPercent = 10, // Increased from 5% - only apply TOON when clearly beneficial
383
+ } = options;
384
+
385
+ const originalLength = content.length;
386
+ const originalTokens = Math.ceil(originalLength / 4);
387
+
388
+ let result = content;
389
+ let toonConverted = false;
390
+ let alreadyToon = false;
391
+ let reduction = 0;
392
+ let truncated = false;
393
+ let toonError: string | undefined;
394
+
395
+ // Step 1: Check if already TOON format
396
+ if (isToonFormat(content)) {
397
+ alreadyToon = true;
398
+ }
399
+ // Step 2: Apply TOON conversion if enabled and content is large enough
400
+ else if (enableToon && content.length > minSizeForToon) {
401
+ const toonResult = jsonToToon(content);
402
+ if (toonResult.alreadyToon) {
403
+ alreadyToon = true;
404
+ } else if (
405
+ toonResult.converted &&
406
+ toonResult.reduction >= minReductionPercent
407
+ ) {
408
+ result = toonResult.result;
409
+ toonConverted = true;
410
+ reduction = toonResult.reduction;
411
+ } else if (toonResult.error) {
412
+ // Track error for debugging
413
+ toonError = toonResult.error;
414
+ } else if (
415
+ toonResult.converted &&
416
+ toonResult.reduction < minReductionPercent
417
+ ) {
418
+ // TOON converted but reduction was too small to be worth it
419
+ toonError = `TOON reduction ${toonResult.reduction}% below threshold ${minReductionPercent}%`;
420
+ } else if (!toonResult.converted) {
421
+ // Conversion failed without explicit error - investigate
422
+ toonError =
423
+ toonResult.error || 'TOON conversion returned false with no error';
424
+ }
425
+ }
426
+
427
+ // Step 3: Truncate if still too long (with smart break points)
428
+ if (result.length > maxLength) {
429
+ let truncatedStr = result.substring(0, maxLength);
430
+
431
+ // Try to find a clean break point
432
+ if (toonConverted || alreadyToon) {
433
+ // For TOON format, break at newline for cleaner output
434
+ const lastNewline = truncatedStr.lastIndexOf('\n');
435
+ if (lastNewline > maxLength * 0.7) {
436
+ truncatedStr = truncatedStr.substring(0, lastNewline);
437
+ }
438
+ } else {
439
+ // For JSON, try to find a clean JSON break point
440
+ const lastCompleteItem = truncatedStr.lastIndexOf('},');
441
+ const lastArrayItem = truncatedStr.lastIndexOf('],');
442
+ const breakPoint = Math.max(lastCompleteItem, lastArrayItem);
443
+ if (breakPoint > maxLength * 0.5) {
444
+ truncatedStr = truncatedStr.substring(0, breakPoint + 1);
445
+ }
446
+ }
447
+
448
+ // Build truncation message
449
+ const truncationInfo = toonConverted
450
+ ? `Original ${originalLength.toLocaleString()} chars → TOON ${result.length.toLocaleString()} chars (${reduction}% saved). ` +
451
+ `Still exceeds ${maxLength.toLocaleString()} char limit.`
452
+ : `Original output was ${originalLength.toLocaleString()} characters (~${originalTokens.toLocaleString()} tokens).`;
453
+
454
+ result =
455
+ truncatedStr +
456
+ `\n\n[OUTPUT_TRUNCATED: ${truncationInfo} Please use more specific queries or smaller date ranges.]`;
457
+ truncated = true;
458
+ }
459
+
460
+ const finalLength = result.length;
461
+ const finalTokens = Math.ceil(finalLength / 4);
462
+
463
+ return {
464
+ content: result,
465
+ toonConverted,
466
+ truncated,
467
+ reduction,
468
+ alreadyToon,
469
+ originalLength,
470
+ originalTokens,
471
+ finalLength,
472
+ finalTokens,
473
+ toonError,
474
+ };
475
+ }