Repository navigation
Description
Description
truncateToolResult cuts by UTF-16 index and can land in the middle of a surrogate pair (an emoji or other character outside the BMP). The result then contains a lone surrogate, which is invalid text.
Environment
- OS: macOS 27.2
- Node version: v22.23.4
- Nanocoder version: 1.32.0 (main at daa0ad9)
- Provider: not provider specific
- Model: not model specific
Steps to Reproduce
source/utils/truncate-tool-result.ts picks headEnd and tailStart and slices the string with content.slice(...). The "snap" helpers only move the cut to whitespace when there is some within 256 characters; otherwise the raw index is used. So any long run without whitespace, with emoji in it, can be cut inside a pair.
I copied the module out and ran it:
const lone = (s: string) =>
/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(s);
for (let len = 3000; len < 3040; len++) {
const s = '\u{1F600}'.repeat(len);
for (const max of [1000, 1001, 2000, 2001, 2500]) {
// count results where lone(truncateToolResult(s, max)) is true
}
}Expected Behavior
The truncated text is always valid Unicode: the cut moves one code unit to keep a pair together.
Actual Behavior
120 of the 200 cases above came back with a lone surrogate. Plain text and BMP-only CJK are fine; it needs astral characters near the cut with nothing to snap to. Realistic inputs are minified JSON or bundle lines, i18n files and logs with emoji and no spaces.
Logs/Screenshots
lone surrogate results 120 of 200
emoji only lone: true
Additional Context
- I have searched existing issues to ensure this is not a duplicate
- I can reproduce this issue consistently
- This issue occurs with the latest version of nanocoder
I could not check how every provider reacts to a lone surrogate in a request. Some JSON consumers refuse it, and a bad message that stays in history would then break each later turn, so it seems worth closing. The fix is small: after computing headEnd, step back one if content.charCodeAt(headEnd - 1) is a high surrogate, and step tailStart forward one if content.charCodeAt(tailStart) is a low surrogate. The fetch_url cut (content.substring(0, MAX_URL_CONTENT_BYTES)) has the same shape and could use the same helper.
Activity
dhruvil-codes commentedon Nov 8, 2026
Hi @akramcodez @addyCooks,
I'd like to take this issue!
Plan
truncateToolResult(source/utils/truncate-tool-result.ts), stepheadEndback by 1 if it ends on a high surrogate, and steptailStartforward by 1 if it starts on a low surrogate into the elided range.fetch_url.truncate-tool-result.spec.tstesting astral/emoji strings across cut boundaries to verify zero lone surrogates.Could you please assign this issue to me? Thanks!
fix(tools): snap truncation boundaries outside UTF-16 surrogate pairs (…