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.
- package/dist/cjs/common/enum.cjs +18 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +88 -20
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/llm/openai/index.cjs +1 -0
- package/dist/cjs/llm/openai/index.cjs.map +1 -1
- package/dist/cjs/main.cjs +13 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/core.cjs +16 -8
- package/dist/cjs/messages/core.cjs.map +1 -1
- package/dist/cjs/messages/format.cjs +8 -2
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/messages/tools.cjs +17 -10
- package/dist/cjs/messages/tools.cjs.map +1 -1
- package/dist/cjs/stream.cjs +1 -0
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +73 -3
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/handlers.cjs +1 -0
- package/dist/cjs/tools/handlers.cjs.map +1 -1
- package/dist/cjs/utils/contextAnalytics.cjs +64 -0
- package/dist/cjs/utils/contextAnalytics.cjs.map +1 -0
- package/dist/cjs/utils/toonFormat.cjs +358 -0
- package/dist/cjs/utils/toonFormat.cjs.map +1 -0
- package/dist/esm/common/enum.mjs +19 -1
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +90 -22
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/llm/openai/index.mjs +1 -0
- package/dist/esm/llm/openai/index.mjs.map +1 -1
- package/dist/esm/main.mjs +3 -1
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/core.mjs +18 -10
- package/dist/esm/messages/core.mjs.map +1 -1
- package/dist/esm/messages/format.mjs +9 -3
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/messages/tools.mjs +19 -12
- package/dist/esm/messages/tools.mjs.map +1 -1
- package/dist/esm/stream.mjs +1 -0
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +73 -3
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/handlers.mjs +1 -0
- package/dist/esm/tools/handlers.mjs.map +1 -1
- package/dist/esm/utils/contextAnalytics.mjs +62 -0
- package/dist/esm/utils/contextAnalytics.mjs.map +1 -0
- package/dist/esm/utils/toonFormat.mjs +351 -0
- package/dist/esm/utils/toonFormat.mjs.map +1 -0
- package/dist/types/common/enum.d.ts +17 -0
- package/dist/types/graphs/Graph.d.ts +8 -0
- package/dist/types/utils/contextAnalytics.d.ts +37 -0
- package/dist/types/utils/index.d.ts +2 -0
- package/dist/types/utils/toonFormat.d.ts +111 -0
- package/package.json +2 -1
- package/src/common/enum.ts +18 -0
- package/src/graphs/Graph.ts +113 -27
- package/src/messages/core.ts +27 -19
- package/src/messages/format.ts +10 -3
- package/src/messages/tools.ts +20 -13
- package/src/tools/ToolNode.ts +78 -5
- package/src/utils/contextAnalytics.ts +95 -0
- package/src/utils/index.ts +2 -0
- package/src/utils/toonFormat.ts +437 -0
package/src/utils/index.ts
CHANGED
|
@@ -0,0 +1,437 @@
|
|
|
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 = lines.filter(l => /^\s*\w+.*:/.test(l)).length >= 2;
|
|
91
|
+
|
|
92
|
+
return hasToonPattern || hasMultipleKeyValueLines;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Extract the first valid JSON object or array from a string.
|
|
97
|
+
* Handles pure JSON or JSON embedded in text (e.g., tool responses).
|
|
98
|
+
*
|
|
99
|
+
* @param str - The string to extract JSON from
|
|
100
|
+
* @returns Object with found status, parsed JSON, and indices
|
|
101
|
+
*/
|
|
102
|
+
export function extractFirstJson(str: string): {
|
|
103
|
+
found: boolean;
|
|
104
|
+
parsed: unknown;
|
|
105
|
+
startIndex: number;
|
|
106
|
+
endIndex: number;
|
|
107
|
+
} {
|
|
108
|
+
if (typeof str !== 'string' || str.length === 0) {
|
|
109
|
+
return { found: false, parsed: null, startIndex: -1, endIndex: -1 };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Find the first { or [ character
|
|
113
|
+
const objStart = str.indexOf('{');
|
|
114
|
+
const arrStart = str.indexOf('[');
|
|
115
|
+
|
|
116
|
+
if (objStart === -1 && arrStart === -1) {
|
|
117
|
+
return { found: false, parsed: null, startIndex: -1, endIndex: -1 };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
let startIndex: number;
|
|
121
|
+
if (objStart === -1) {
|
|
122
|
+
startIndex = arrStart;
|
|
123
|
+
} else if (arrStart === -1) {
|
|
124
|
+
startIndex = objStart;
|
|
125
|
+
} else {
|
|
126
|
+
startIndex = Math.min(objStart, arrStart);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Find the matching closing bracket using a stack-based approach
|
|
130
|
+
// Properly handle strings to avoid counting brackets inside strings
|
|
131
|
+
let depth = 0;
|
|
132
|
+
let inString = false;
|
|
133
|
+
let escapeNext = false;
|
|
134
|
+
|
|
135
|
+
for (let i = startIndex; i < str.length; i++) {
|
|
136
|
+
const char = str[i];
|
|
137
|
+
|
|
138
|
+
if (escapeNext) {
|
|
139
|
+
escapeNext = false;
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
if (char === '\\' && inString) {
|
|
144
|
+
escapeNext = true;
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (char === '"') {
|
|
149
|
+
inString = !inString;
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (inString) continue;
|
|
154
|
+
|
|
155
|
+
if (char === '{' || char === '[') depth++;
|
|
156
|
+
if (char === '}' || char === ']') depth--;
|
|
157
|
+
|
|
158
|
+
if (depth === 0) {
|
|
159
|
+
// Found matching bracket, try to parse
|
|
160
|
+
const jsonStr = str.substring(startIndex, i + 1);
|
|
161
|
+
try {
|
|
162
|
+
const parsed = JSON.parse(jsonStr);
|
|
163
|
+
return { found: true, parsed, startIndex, endIndex: i };
|
|
164
|
+
} catch {
|
|
165
|
+
// Not valid JSON at this bracket level, continue searching
|
|
166
|
+
// Reset and look for the next JSON start after this position
|
|
167
|
+
const nextResult = extractFirstJson(str.substring(i + 1));
|
|
168
|
+
if (nextResult.found) {
|
|
169
|
+
return {
|
|
170
|
+
found: true,
|
|
171
|
+
parsed: nextResult.parsed,
|
|
172
|
+
startIndex: i + 1 + nextResult.startIndex,
|
|
173
|
+
endIndex: i + 1 + nextResult.endIndex,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
return { found: false, parsed: null, startIndex: -1, endIndex: -1 };
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
return { found: false, parsed: null, startIndex: -1, endIndex: -1 };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Convert JSON content to TOON format for token efficiency.
|
|
186
|
+
* Extracts JSON from string if embedded, converts to TOON.
|
|
187
|
+
* Returns original string if:
|
|
188
|
+
* - Already in TOON format
|
|
189
|
+
* - Not JSON
|
|
190
|
+
* - TOON conversion fails or is larger
|
|
191
|
+
*
|
|
192
|
+
* @param str - The string containing JSON to convert
|
|
193
|
+
* @returns Object with conversion status, result, and reduction percentage
|
|
194
|
+
*/
|
|
195
|
+
export function jsonToToon(str: string): {
|
|
196
|
+
converted: boolean;
|
|
197
|
+
result: string;
|
|
198
|
+
reduction: number;
|
|
199
|
+
alreadyToon?: boolean;
|
|
200
|
+
error?: string;
|
|
201
|
+
} {
|
|
202
|
+
if (!toonEncode || typeof str !== 'string') {
|
|
203
|
+
return { converted: false, result: str, reduction: 0, error: !toonEncode ? 'TOON library not loaded' : undefined };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// Check if already in TOON format - skip conversion
|
|
207
|
+
if (isToonFormat(str)) {
|
|
208
|
+
return { converted: false, result: str, reduction: 0, alreadyToon: true };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
try {
|
|
212
|
+
const { found, parsed, startIndex, endIndex } = extractFirstJson(str);
|
|
213
|
+
|
|
214
|
+
if (!found || !parsed) {
|
|
215
|
+
return { converted: false, result: str, reduction: 0, error: 'No JSON found in content' };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// Check if this JSON structure would benefit from TOON
|
|
219
|
+
// Text-heavy content (emails, documents) won't compress well
|
|
220
|
+
if (!isToonBeneficial(parsed)) {
|
|
221
|
+
return { converted: false, result: str, reduction: 0, error: 'Content is text-heavy (>70% string values), TOON not beneficial' };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const toonResult = toonEncode(parsed);
|
|
225
|
+
|
|
226
|
+
// Preserve text before and after the JSON block
|
|
227
|
+
const textBefore = str.substring(0, startIndex);
|
|
228
|
+
const textAfter = str.substring(endIndex + 1);
|
|
229
|
+
|
|
230
|
+
// Build the full result: textBefore + TOON + textAfter
|
|
231
|
+
const fullResult = textBefore + toonResult + textAfter;
|
|
232
|
+
|
|
233
|
+
if (fullResult.length < str.length) {
|
|
234
|
+
const reduction = Math.round(((str.length - fullResult.length) / str.length) * 100);
|
|
235
|
+
return { converted: true, result: fullResult, reduction };
|
|
236
|
+
} else {
|
|
237
|
+
// TOON output was larger or same size - not beneficial
|
|
238
|
+
return { converted: false, result: str, reduction: 0, error: `TOON output not smaller (${fullResult.length} >= ${str.length})` };
|
|
239
|
+
}
|
|
240
|
+
} catch (err) {
|
|
241
|
+
// TOON encoding or extraction failed - log error for debugging
|
|
242
|
+
const errorMsg = err instanceof Error ? err.message : String(err);
|
|
243
|
+
return { converted: false, result: str, reduction: 0, error: `TOON conversion error: ${errorMsg}` };
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Check if TOON library is loaded and available
|
|
249
|
+
*/
|
|
250
|
+
export function isToonAvailable(): boolean {
|
|
251
|
+
return toonEncode !== null;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Result of processing tool output
|
|
256
|
+
*/
|
|
257
|
+
export interface ProcessToolOutputResult {
|
|
258
|
+
/** The processed content string */
|
|
259
|
+
content: string;
|
|
260
|
+
/** Whether TOON conversion was applied */
|
|
261
|
+
toonConverted: boolean;
|
|
262
|
+
/** Whether content was truncated */
|
|
263
|
+
truncated: boolean;
|
|
264
|
+
/** Percentage reduction from TOON (0 if not converted) */
|
|
265
|
+
reduction: number;
|
|
266
|
+
/** Whether input was already in TOON format */
|
|
267
|
+
alreadyToon: boolean;
|
|
268
|
+
/** Original content length */
|
|
269
|
+
originalLength: number;
|
|
270
|
+
/** Estimated original tokens (~4 chars per token) */
|
|
271
|
+
originalTokens: number;
|
|
272
|
+
/** Final content length */
|
|
273
|
+
finalLength: number;
|
|
274
|
+
/** Estimated final tokens */
|
|
275
|
+
finalTokens: number;
|
|
276
|
+
/** Error message if TOON conversion failed (for debugging) */
|
|
277
|
+
toonError?: string;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Options for processing tool output
|
|
282
|
+
*/
|
|
283
|
+
export interface ProcessToolOutputOptions {
|
|
284
|
+
/** Maximum output length in characters (default: 100000) */
|
|
285
|
+
maxLength?: number;
|
|
286
|
+
/** Whether to apply TOON conversion (default: true) */
|
|
287
|
+
enableToon?: boolean;
|
|
288
|
+
/** Minimum content size to attempt TOON conversion (default: 1000) */
|
|
289
|
+
minSizeForToon?: number;
|
|
290
|
+
/** Minimum reduction % to accept TOON result (default: 10) */
|
|
291
|
+
minReductionPercent?: number;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Analyze JSON structure to determine if TOON conversion would be beneficial.
|
|
296
|
+
* Text-heavy content (emails, documents) doesn't compress well with TOON.
|
|
297
|
+
* Structured data (API responses, metadata) compresses much better.
|
|
298
|
+
*
|
|
299
|
+
* @param parsed - Parsed JSON object
|
|
300
|
+
* @returns true if TOON conversion is likely beneficial
|
|
301
|
+
*/
|
|
302
|
+
function isToonBeneficial(parsed: unknown): boolean {
|
|
303
|
+
if (!parsed || typeof parsed !== 'object') return false;
|
|
304
|
+
|
|
305
|
+
const jsonStr = JSON.stringify(parsed);
|
|
306
|
+
const totalLength = jsonStr.length;
|
|
307
|
+
|
|
308
|
+
// Count characters in string values (text content)
|
|
309
|
+
let textContentLength = 0;
|
|
310
|
+
|
|
311
|
+
function countTextContent(obj: unknown): void {
|
|
312
|
+
if (typeof obj === 'string') {
|
|
313
|
+
// Count string length (this is text content that TOON can't compress)
|
|
314
|
+
textContentLength += obj.length;
|
|
315
|
+
} else if (Array.isArray(obj)) {
|
|
316
|
+
obj.forEach(countTextContent);
|
|
317
|
+
} else if (obj && typeof obj === 'object') {
|
|
318
|
+
Object.values(obj).forEach(countTextContent);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
countTextContent(parsed);
|
|
323
|
+
|
|
324
|
+
// Calculate ratio of text content to total JSON
|
|
325
|
+
const textRatio = textContentLength / totalLength;
|
|
326
|
+
|
|
327
|
+
// If more than 70% is text content, TOON won't help much
|
|
328
|
+
// TOON compresses structure (field names, brackets), not text
|
|
329
|
+
return textRatio < 0.7;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Process tool output: apply TOON conversion if beneficial, then truncate if needed.
|
|
334
|
+
* This is the main entry point for processing any tool output (regular or MCP).
|
|
335
|
+
*
|
|
336
|
+
* Flow:
|
|
337
|
+
* 1. Check if already TOON format → skip conversion
|
|
338
|
+
* 2. Try TOON conversion if content is JSON and large enough
|
|
339
|
+
* 3. Truncate if still exceeds maxLength (with smart break points)
|
|
340
|
+
*
|
|
341
|
+
* @param content - The tool output content
|
|
342
|
+
* @param options - Processing options
|
|
343
|
+
* @returns Processed content and metadata
|
|
344
|
+
*/
|
|
345
|
+
export function processToolOutput(
|
|
346
|
+
content: string,
|
|
347
|
+
options: ProcessToolOutputOptions = {}
|
|
348
|
+
): ProcessToolOutputResult {
|
|
349
|
+
const {
|
|
350
|
+
maxLength = 100000,
|
|
351
|
+
enableToon = true,
|
|
352
|
+
minSizeForToon = 1000,
|
|
353
|
+
minReductionPercent = 10, // Increased from 5% - only apply TOON when clearly beneficial
|
|
354
|
+
} = options;
|
|
355
|
+
|
|
356
|
+
const originalLength = content.length;
|
|
357
|
+
const originalTokens = Math.ceil(originalLength / 4);
|
|
358
|
+
|
|
359
|
+
let result = content;
|
|
360
|
+
let toonConverted = false;
|
|
361
|
+
let alreadyToon = false;
|
|
362
|
+
let reduction = 0;
|
|
363
|
+
let truncated = false;
|
|
364
|
+
let toonError: string | undefined;
|
|
365
|
+
|
|
366
|
+
// Step 1: Check if already TOON format
|
|
367
|
+
if (isToonFormat(content)) {
|
|
368
|
+
alreadyToon = true;
|
|
369
|
+
}
|
|
370
|
+
// Step 2: Apply TOON conversion if enabled and content is large enough
|
|
371
|
+
else if (enableToon && content.length > minSizeForToon) {
|
|
372
|
+
const toonResult = jsonToToon(content);
|
|
373
|
+
if (toonResult.alreadyToon) {
|
|
374
|
+
alreadyToon = true;
|
|
375
|
+
} else if (toonResult.converted && toonResult.reduction >= minReductionPercent) {
|
|
376
|
+
result = toonResult.result;
|
|
377
|
+
toonConverted = true;
|
|
378
|
+
reduction = toonResult.reduction;
|
|
379
|
+
} else if (toonResult.error) {
|
|
380
|
+
// Track error for debugging
|
|
381
|
+
toonError = toonResult.error;
|
|
382
|
+
} else if (toonResult.converted && toonResult.reduction < minReductionPercent) {
|
|
383
|
+
// TOON converted but reduction was too small to be worth it
|
|
384
|
+
toonError = `TOON reduction ${toonResult.reduction}% below threshold ${minReductionPercent}%`;
|
|
385
|
+
} else if (!toonResult.converted) {
|
|
386
|
+
// Conversion failed without explicit error - investigate
|
|
387
|
+
toonError = toonResult.error || 'TOON conversion returned false with no error';
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// Step 3: Truncate if still too long (with smart break points)
|
|
392
|
+
if (result.length > maxLength) {
|
|
393
|
+
let truncatedStr = result.substring(0, maxLength);
|
|
394
|
+
|
|
395
|
+
// Try to find a clean break point
|
|
396
|
+
if (toonConverted || alreadyToon) {
|
|
397
|
+
// For TOON format, break at newline for cleaner output
|
|
398
|
+
const lastNewline = truncatedStr.lastIndexOf('\n');
|
|
399
|
+
if (lastNewline > maxLength * 0.7) {
|
|
400
|
+
truncatedStr = truncatedStr.substring(0, lastNewline);
|
|
401
|
+
}
|
|
402
|
+
} else {
|
|
403
|
+
// For JSON, try to find a clean JSON break point
|
|
404
|
+
const lastCompleteItem = truncatedStr.lastIndexOf('},');
|
|
405
|
+
const lastArrayItem = truncatedStr.lastIndexOf('],');
|
|
406
|
+
const breakPoint = Math.max(lastCompleteItem, lastArrayItem);
|
|
407
|
+
if (breakPoint > maxLength * 0.5) {
|
|
408
|
+
truncatedStr = truncatedStr.substring(0, breakPoint + 1);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
// Build truncation message
|
|
413
|
+
const truncationInfo = toonConverted
|
|
414
|
+
? `Original ${originalLength.toLocaleString()} chars → TOON ${result.length.toLocaleString()} chars (${reduction}% saved). ` +
|
|
415
|
+
`Still exceeds ${maxLength.toLocaleString()} char limit.`
|
|
416
|
+
: `Original output was ${originalLength.toLocaleString()} characters (~${originalTokens.toLocaleString()} tokens).`;
|
|
417
|
+
|
|
418
|
+
result = truncatedStr + `\n\n[OUTPUT_TRUNCATED: ${truncationInfo} Please use more specific queries or smaller date ranges.]`;
|
|
419
|
+
truncated = true;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
const finalLength = result.length;
|
|
423
|
+
const finalTokens = Math.ceil(finalLength / 4);
|
|
424
|
+
|
|
425
|
+
return {
|
|
426
|
+
content: result,
|
|
427
|
+
toonConverted,
|
|
428
|
+
truncated,
|
|
429
|
+
reduction,
|
|
430
|
+
alreadyToon,
|
|
431
|
+
originalLength,
|
|
432
|
+
originalTokens,
|
|
433
|
+
finalLength,
|
|
434
|
+
finalTokens,
|
|
435
|
+
toonError,
|
|
436
|
+
};
|
|
437
|
+
}
|