truncateSessionMemoryForCompact function
Truncate session memory sections that exceed the per-section token limit. Used when inserting session memory into compact messages.
Implementation
TruncationResult truncateSessionMemoryForCompact(String content) {
final lines = content.split('\n');
final maxCharsPerSection = _maxSectionLength * 4;
final outputLines = <String>[];
final currentSectionLines = <String>[];
var currentSectionHeader = '';
var wasTruncated = false;
for (final line in lines) {
if (line.startsWith('# ')) {
final result = _flushSessionSection(
currentSectionHeader,
currentSectionLines,
maxCharsPerSection,
);
outputLines.addAll(result.lines);
wasTruncated = wasTruncated || result.wasTruncated;
currentSectionHeader = line;
currentSectionLines.clear();
} else {
currentSectionLines.add(line);
}
}
// Flush the last section.
final result = _flushSessionSection(
currentSectionHeader,
currentSectionLines,
maxCharsPerSection,
);
outputLines.addAll(result.lines);
wasTruncated = wasTruncated || result.wasTruncated;
return TruncationResult(
truncatedContent: outputLines.join('\n'),
wasTruncated: wasTruncated,
);
}