From 2ce1b8d4f4ea110bfdf7763b3a76717c2667a62e Mon Sep 17 00:00:00 2001 From: sama Pyb Date: Tue, 1 Dec 2026 18:36:28 +0800 Subject: [PATCH 1/2] Cut back incomplete UTF-16 surrogate pairs in JSONCompleter --- .../Shared/JSONCompleter.swift | 38 +++++++++++++++++-- .../JSONCompleterTests.swift | 30 +++++++++++++++ 2 files changed, 65 insertions(+), 3 deletions(-) diff --git a/Sources/AnyLanguageModel/Shared/JSONCompleter.swift b/Sources/AnyLanguageModel/Shared/JSONCompleter.swift index f52ed0c6..0ae54dd5 100644 --- a/Sources/AnyLanguageModel/Shared/JSONCompleter.swift +++ b/Sources/AnyLanguageModel/Shared/JSONCompleter.swift @@ -119,8 +119,9 @@ struct JSONCompleter: Sendable { /// Completes a string that starts at the given index. /// - /// If the text ends inside an escape sequence, the completion keeps only the - /// text before the backslash so that the result is valid JSON. + /// If the text ends inside an escape sequence or an incomplete UTF-16 + /// surrogate pair, the completion cuts back to the start of the incomplete + /// sequence so that the result is valid JSON. private func completeString(_ json: String, from startIndex: String.Index) -> Completion? { guard startIndex < json.endIndex, json[startIndex] == "\"" else { return nil } @@ -134,8 +135,9 @@ struct JSONCompleter: Sendable { return (string: "\"", endIndex: escapeStart) } if json[current] == "u" { + let hexStart = json.index(after: current) + current = hexStart var remaining = 4 - current = json.index(after: current) while remaining > 0 && current < json.endIndex && json[current].isHexDigit { current = json.index(after: current) remaining -= 1 @@ -143,6 +145,36 @@ struct JSONCompleter: Sendable { if remaining > 0 { return (string: "\"", endIndex: escapeStart) } + if let codeUnit = UInt16(json[hexStart ..< current], radix: 16), + (0xD800 ... 0xDBFF).contains(codeUnit) + { + guard current < json.endIndex else { + return (string: "\"", endIndex: escapeStart) + } + if json[current] == "\\" { + let lowAfterSlash = json.index(after: current) + guard lowAfterSlash < json.endIndex else { + return (string: "\"", endIndex: escapeStart) + } + if json[lowAfterSlash] == "u" { + let lowHexStart = json.index(after: lowAfterSlash) + var lowCurrent = lowHexStart + var lowRemaining = 4 + while lowRemaining > 0 && lowCurrent < json.endIndex && json[lowCurrent].isHexDigit { + lowCurrent = json.index(after: lowCurrent) + lowRemaining -= 1 + } + if lowRemaining > 0 { + return (string: "\"", endIndex: escapeStart) + } + if let lowCodeUnit = UInt16(json[lowHexStart ..< lowCurrent], radix: 16), + (0xDC00 ... 0xDFFF).contains(lowCodeUnit) + { + current = lowCurrent + } + } + } + } continue } } else if char == "\"" { diff --git a/Tests/AnyLanguageModelTests/JSONCompleterTests.swift b/Tests/AnyLanguageModelTests/JSONCompleterTests.swift index 23689fef..6c247eae 100644 --- a/Tests/AnyLanguageModelTests/JSONCompleterTests.swift +++ b/Tests/AnyLanguageModelTests/JSONCompleterTests.swift @@ -93,6 +93,36 @@ struct JSONCompleterTests { #expect(isValidJSON(try completer.complete(#"{"a": "x\\"#))) } + @Test func handlesPartialSurrogatePairs() throws { + // Every prefix of a surrogate-pair escape (\uD83D\uDE00 = 😀) must complete to valid JSON. + #expect(try completer.complete(#""Hi \uD83D"#) == #""Hi ""#) + #expect(try completer.complete(#""Hi \uD83D\"#) == #""Hi ""#) + #expect(try completer.complete(#""Hi \uD83D\u"#) == #""Hi ""#) + #expect(try completer.complete(#""Hi \uD83D\uDE"#) == #""Hi ""#) + #expect(try completer.complete(#""Hi \uD83D\uDE0"#) == #""Hi ""#) + #expect(try completer.complete(#""Hi \uD83D\uDE00"#) == #""Hi \uD83D\uDE00""#) + + // Works with lowercase hex and inside object values and keys too. + #expect(try completer.complete(#"{"emoji": "Hi \ud83d"#) == #"{"emoji": "Hi "}"#) + #expect(try completer.complete(#"{"emoji": "Hi \ud83d\ude"#) == #"{"emoji": "Hi "}"#) + #expect(try completer.complete(#"{"\uD83D"#) == #"{"": null}"#) + + // Every character-by-character prefix of a JSON object with surrogate pairs decodes as JSON. + let full = #"{"emoji": "Hi \uD83D\uDE00 and \ud83c\udf89"}"# + var index = full.index(after: full.startIndex) + while index <= full.endIndex { + let prefix = String(full[.. \(completed)") + if index == full.endIndex { break } + index = full.index(after: index) + } + + // GeneratedContent(json:) keeps structured object kind across partial surrogate pairs. + let partial = try GeneratedContent(json: #"{"emoji": "Hi \uD83D\uDE"#) + #expect(try partial.value(String.self, forProperty: "emoji") == "Hi ") + } + @Test func handlesEmptyAndWhitespaceInput() throws { #expect(try completer.complete("") == "") #expect(try completer.complete(" ") == " ") From e3d3f5d5ecef3e7429720958191b2d593dfc0a61 Mon Sep 17 00:00:00 2001 From: sama Pyb Date: Tue, 1 Dec 2026 21:56:37 +0800 Subject: [PATCH 2/2] Only cut back short Unicode escapes at end of input --- Sources/AnyLanguageModel/Shared/JSONCompleter.swift | 10 ++++++++-- Tests/AnyLanguageModelTests/JSONCompleterTests.swift | 9 +++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/Sources/AnyLanguageModel/Shared/JSONCompleter.swift b/Sources/AnyLanguageModel/Shared/JSONCompleter.swift index 0ae54dd5..7b55d935 100644 --- a/Sources/AnyLanguageModel/Shared/JSONCompleter.swift +++ b/Sources/AnyLanguageModel/Shared/JSONCompleter.swift @@ -143,7 +143,10 @@ struct JSONCompleter: Sendable { remaining -= 1 } if remaining > 0 { - return (string: "\"", endIndex: escapeStart) + if current == json.endIndex { + return (string: "\"", endIndex: escapeStart) + } + continue } if let codeUnit = UInt16(json[hexStart ..< current], radix: 16), (0xD800 ... 0xDBFF).contains(codeUnit) @@ -165,7 +168,10 @@ struct JSONCompleter: Sendable { lowRemaining -= 1 } if lowRemaining > 0 { - return (string: "\"", endIndex: escapeStart) + if lowCurrent == json.endIndex { + return (string: "\"", endIndex: escapeStart) + } + continue } if let lowCodeUnit = UInt16(json[lowHexStart ..< lowCurrent], radix: 16), (0xDC00 ... 0xDFFF).contains(lowCodeUnit) diff --git a/Tests/AnyLanguageModelTests/JSONCompleterTests.swift b/Tests/AnyLanguageModelTests/JSONCompleterTests.swift index 6c247eae..779a3fc3 100644 --- a/Tests/AnyLanguageModelTests/JSONCompleterTests.swift +++ b/Tests/AnyLanguageModelTests/JSONCompleterTests.swift @@ -121,6 +121,15 @@ struct JSONCompleterTests { // GeneratedContent(json:) keeps structured object kind across partial surrogate pairs. let partial = try GeneratedContent(json: #"{"emoji": "Hi \uD83D\uDE"#) #expect(try partial.value(String.self, forProperty: "emoji") == "Hi ") + + // Malformed escapes before the end of input must not cut back and drop trailing properties. + let malformedSurrogate = #"{"a":"\uD83D\uDE","b":1}"# + #expect(try completer.complete(malformedSurrogate) == malformedSurrogate) + #expect(try GeneratedContent(json: malformedSurrogate).kind == .string(malformedSurrogate)) + + let malformedEscape = #"{"a":"\u12","b":1}"# + #expect(try completer.complete(malformedEscape) == malformedEscape) + #expect(try GeneratedContent(json: malformedEscape).kind == .string(malformedEscape)) } @Test func handlesEmptyAndWhitespaceInput() throws {