44 */
55import type { AgentMessage } from "openclaw/plugin-sdk/agent-harness-runtime" ;
66import { redactSensitiveFieldValue , redactToolPayloadText } from "openclaw/plugin-sdk/logging-core" ;
7+ import { sliceUtf16Safe , truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime" ;
78
89type CodexContextProjection = {
910 developerInstructionAddition ?: string ;
@@ -485,9 +486,11 @@ function resolveTextPartMaxChars(maxRenderedContextChars: number): number {
485486}
486487
487488function truncateText ( text : string , maxChars : number ) : string {
488- return text . length > maxChars
489- ? `${ text . slice ( 0 , maxChars ) } \n[truncated ${ text . length - maxChars } chars]`
490- : text ;
489+ if ( text . length <= maxChars ) {
490+ return text ;
491+ }
492+ const truncated = truncateUtf16Safe ( text , maxChars ) ;
493+ return `${ truncated } \n[truncated ${ text . length - truncated . length } chars]` ;
491494}
492495
493496function truncateOlderContext ( text : string , maxChars : number ) : string {
@@ -507,20 +510,5 @@ function truncateOlderContext(text: string, maxChars: number): string {
507510 return marker . slice ( 0 , maxChars ) ;
508511 }
509512 tailChars = maxChars - marker . length ;
510- return `${ marker } ${ sliceTailFromCodePointBoundary ( text , tailChars ) . trimStart ( ) } ` ;
511- }
512-
513- // Keep the kept tail at a code-point boundary so a UTF-16 surrogate pair is
514- // never split at the cut: a tail start that lands on a low surrogate would
515- // orphan it into U+FFFD, corrupting the first character. Dropping that unit
516- // stays within maxChars (it only removes a char), so the bound still holds.
517- function sliceTailFromCodePointBoundary ( text : string , tailChars : number ) : string {
518- let start = text . length - tailChars ;
519- if ( start > 0 && start < text . length ) {
520- const code = text . charCodeAt ( start ) ;
521- if ( code >= 0xdc00 && code <= 0xdfff ) {
522- start += 1 ;
523- }
524- }
525- return text . slice ( start ) ;
513+ return `${ marker } ${ sliceUtf16Safe ( text , - tailChars ) . trimStart ( ) } ` ;
526514}
0 commit comments