/** * 代理对(surrogate pair)安全的字符串截断。 * * 半个 UTF-16 代理项(如 `\uD83C`)留在字符串里时,`JSON.stringify` 会写成 * `"\ud83c"` —— 语法合法但不是合法 Unicode。OpenAI(Responses/Chat)的请求体 * 校验会直接回 400 `invalid_json`("Invalid body: failed to parse JSON value…"), * 而坏内容一旦进了 history,此后每一轮请求都发不出去,界面上只剩「生成未完成」。 * * 真实事故:工具结果在 2000 字符处做预览,正好切在一个 emoji 中间。 * 所有会把内容写进消息正文、提示词或工具结果的定长截断都应走这里。 */ export function safeSlice(value: string, start: number, end?: number): string { const length = value.length; const from = clamp(start < 0 ? length + start : start, 0, length); const to = clamp(end === undefined ? length : end < 0 ? length + end : end, from, length); // 起点落在低位代理上:退一位,把它的高位代理一起保留 const startsInsidePair = from > 0 && isLowSurrogate(value.charCodeAt(from)) && isHighSurrogate(value.charCodeAt(from - 1)); // 终点落在高位代理上:退一位,别只留下半个字符 const endsInsidePair = to > from && isHighSurrogate(value.charCodeAt(to - 1)); return value.slice(startsInsidePair ? from - 1 : from, endsInsidePair ? Math.max(from, to - 1) : to); } function clamp(value: number, min: number, max: number): number { return Math.min(Math.max(value, min), max); } function isHighSurrogate(code: number): boolean { return code >= 0xd800 && code <= 0xdbff; } function isLowSurrogate(code: number): boolean { return code >= 0xdc00 && code <= 0xdfff; }