Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

fix(bots): never send a lone surrogate — DeepSeek rejects the whole body

JC60965c5bb44a
diff --git a/src/bots/bot-turn.test.ts b/src/bots/bot-turn.test.ts
index 9a2b92d7..e80af598 100644
--- a/src/bots/bot-turn.test.ts
+++ b/src/bots/bot-turn.test.ts
@@ -311,6 +311,26 @@ describe('compactMessages', () => {
const msgs = [{ role: 'user', content: 'hi' }];
expect(compactMessages(msgs as never, DEFAULT_TURN_LIMITS)).toBe(msgs);
});
+ // Measured on api.deepseek.com: a body containing `\ud83c` — what JSON.stringify writes for half a
+ // surrogate pair — is refused with 400 "unexpected end of hex escape", and the whole turn dies as
+ // unknown_error. The cut used to land inside an emoji, so a half is never sent again.
+ it('never truncates inside a surrogate pair', () => {
+ const emoji = '\u{1F3A7}';
+ const big = `${'x'.repeat(999)}${emoji}${'y'.repeat(500)}`;
+ const msgs = [toolMsg('a', big), toolMsg('b', 'ok')];
+ const out = compactMessages(msgs as never, { keepRecentToolResults: 2, maxToolResultChars: 1000 }) as unknown as Array<{ content: Array<{ output: { value: string } }> }>;
+ const value = out[0].content[0].output.value;
+ expect(value).toContain('[…truncated');
+ expect(value).not.toMatch(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/);
+ expect(JSON.stringify({ content: value })).not.toMatch(/\\u[dD][89abAB]/);
+ });
+ it('strips a lone surrogate that came from somewhere else, even under the cap', () => {
+ const half = '\u{1F3A7}'.slice(0, 1);
+ const msgs = [toolMsg('a', `output${half}`), toolMsg('b', 'ok')];
+ const out = compactMessages(msgs as never, { keepRecentToolResults: 2, maxToolResultChars: 1000 }) as unknown as Array<{ content: Array<{ output: { value: string } }> }>;
+ expect(out[0].content[0].output.value).toBe('output');
+ expect(JSON.stringify({ content: out[0].content[0].output.value })).not.toMatch(/\\u[dD][89abAB]/);
+ });
});
describe('turn governor', () => {
diff --git a/src/bots/bot-turn.ts b/src/bots/bot-turn.ts
index 5fdd848d..ee969b3d 100644
--- a/src/bots/bot-turn.ts
+++ b/src/bots/bot-turn.ts
@@ -11,6 +11,7 @@ import { isFailedToolResult } from '../core/execute-guard.js';
import { MAX_AUTOMATIC_CONTINUATIONS } from '../core/execution-limits.js';
import { formatToolStep } from '../utils/tool-label.js';
import { logger } from '../utils/logger.js';
+import { stripLoneSurrogates, truncateText } from '../utils/text-safe.js';
import type { BotManifest, BotTrigger } from './types.js';
/** Mailbox messages injected mid-turn (bot-to-bot or queued user input). */
@@ -674,6 +675,53 @@ function noOutcomePrompt(input: BotTurnInput): string {
*/
type ToolResultPart = { type: 'tool-result'; toolName?: string; output?: ToolOutput };
+/**
+ * No lone UTF-16 surrogate may reach the JSON body: `JSON.stringify` writes it as `\ud83c`, and
+ * DeepSeek then rejects the whole request — "400 Failed to parse the request body as JSON:
+ * messages[6].content: unexpected end of hex escape". An index-based cut through an emoji is enough
+ * to produce one, and it can come from anywhere (tool result, prompt, deliverable), so everything
+ * leaving for the model is cleaned, not just what this function truncates.
+ */
+function sanitizeString(value: string): string {
+ return /[\uD800-\uDFFF]/.test(value) ? stripLoneSurrogates(value) : value;
+}
+
+function sanitizeModelMessages(messages: ModelMessage[]): ModelMessage[] {
+ let changed = false;
+ const out = messages.map((m) => {
+ if (typeof m.content === 'string') {
+ const clean = sanitizeString(m.content);
+ if (clean === m.content) return m;
+ changed = true;
+ return { ...m, content: clean } as ModelMessage;
+ }
+ if (!Array.isArray(m.content)) return m;
+ let partChanged = false;
+ const parts = (m.content as unknown as Array<Record<string, any>>).map((p) => {
+ if (p?.type === 'text' && typeof p.text === 'string') {
+ const clean = sanitizeString(p.text);
+ if (clean !== p.text) {
+ partChanged = true;
+ return { ...p, text: clean };
+ }
+ return p;
+ }
+ if (p?.type === 'tool-result' && typeof p.output?.value === 'string') {
+ const clean = sanitizeString(p.output.value);
+ if (clean !== p.output.value) {
+ partChanged = true;
+ return { ...p, output: { ...p.output, value: clean } };
+ }
+ }
+ return p;
+ });
+ if (!partChanged) return m;
+ changed = true;
+ return { ...m, content: parts } as unknown as ModelMessage;
+ });
+ return changed ? out : messages;
+}
+
export function compactMessages(messages: ModelMessage[], limits: Pick<BotTurnLimits, 'keepRecentToolResults' | 'maxToolResultChars'>): ModelMessage[] {
const resultRefs: Array<{ mi: number; pi: number }> = [];
messages.forEach((m, mi) => {
@@ -682,7 +730,7 @@ export function compactMessages(messages: ModelMessage[], limits: Pick<BotTurnLi
if (p?.type === 'tool-result') resultRefs.push({ mi, pi });
});
});
- if (resultRefs.length === 0) return messages;
+ if (resultRefs.length === 0) return sanitizeModelMessages(messages);
const stubBefore = Math.max(0, resultRefs.length - limits.keepRecentToolResults);
const out = messages.slice();
resultRefs.forEach(({ mi, pi }, idx) => {
@@ -694,16 +742,16 @@ export function compactMessages(messages: ModelMessage[], limits: Pick<BotTurnLi
let next: string | null = null;
if (idx < stubBefore) {
if (text.length > 400) {
- next = `${text.slice(0, 400)}\n[…${text.length - 400} more chars trimmed from an earlier step — re-run ${part.toolName ?? 'the tool'} if you need it]`;
+ next = `${truncateText(text, 400)}\n[…${text.length - 400} more chars trimmed from an earlier step — re-run ${part.toolName ?? 'the tool'} if you need it]`;
}
} else if (text.length > limits.maxToolResultChars) {
- next = `${text.slice(0, limits.maxToolResultChars)}\n[…truncated ${text.length - limits.maxToolResultChars} chars]`;
+ next = `${truncateText(text, limits.maxToolResultChars)}\n[…truncated ${text.length - limits.maxToolResultChars} chars]`;
}
if (next === null) return;
if (out[mi] === messages[mi]) out[mi] = { ...messages[mi], content: (messages[mi].content as unknown as ToolResultPart[]).slice() } as ModelMessage;
(out[mi].content as unknown as ToolResultPart[])[pi] = { ...part, output: { type: 'text', value: next } };
});
- return out;
+ return sanitizeModelMessages(out);
}
// ---- tool wrapping: delivery capture + shared-folder write budget ----------
diff --git a/src/utils/text-safe.test.ts b/src/utils/text-safe.test.ts
new file mode 100644
index 00000000..ba780994
--- /dev/null
+++ b/src/utils/text-safe.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from 'vitest';
+import { stripLoneSurrogates, truncateText } from './text-safe.js';
+
+const HEADPHONES = '\u{1F3A7}'; // 🎧 — une paire de surrogates
+
+describe('stripLoneSurrogates', () => {
+ it('laisse une paire valide intacte', () => {
+ expect(stripLoneSurrogates(`casque ${HEADPHONES}`)).toBe(`casque ${HEADPHONES}`);
+ });
+
+ it('jette une moitié haute orpheline, celle qui fait échouer le fournisseur', () => {
+ const half = HEADPHONES.slice(0, 1);
+ expect(stripLoneSurrogates(`abc${half}`)).toBe('abc');
+ });
+
+ it('jette une moitié basse orpheline', () => {
+ const half = HEADPHONES.slice(1);
+ expect(stripLoneSurrogates(`abc${half}`)).toBe('abc');
+ });
+
+ it('conserve le texte autour et recolle les paires suivantes', () => {
+ const half = HEADPHONES.slice(0, 1);
+ expect(stripLoneSurrogates(`a${half}b${HEADPHONES}c`)).toBe(`ab${HEADPHONES}c`);
+ });
+});
+
+describe('truncateText', () => {
+ it('ne coupe pas une paire de surrogates au milieu', () => {
+ // La coupe tombe exactement entre le high et le low : c'est le cas qui partait en 400.
+ const text = `${'x'.repeat(10)}${HEADPHONES}fin`;
+ const cut = truncateText(text, 11);
+ expect(cut).toBe('x'.repeat(10));
+ expect(cut.charCodeAt(cut.length - 1)).toBeLessThan(0xd800);
+ });
+
+ it('produit un corps JSON que plus aucun parseur strict ne refuse', () => {
+ const text = `${'x'.repeat(10)}${HEADPHONES}fin`;
+ const body = JSON.stringify({ content: truncateText(text, 11) });
+ expect(body).not.toMatch(/\\u[dD][89abAB]/); // aucun \udXXX isolé
+ });
+
+ it('garde le texte entier quand il tient, sans surrogates isolés', () => {
+ const half = HEADPHONES.slice(0, 1);
+ expect(truncateText(`court${half}`, 100)).toBe('court');
+ expect(truncateText('court', 100)).toBe('court');
+ });
+
+ it('rend une chaîne vide pour une limite nulle ou négative', () => {
+ expect(truncateText('abc', 0)).toBe('');
+ expect(truncateText('abc', -5)).toBe('');
+ });
+});
diff --git a/src/utils/text-safe.ts b/src/utils/text-safe.ts
new file mode 100644
index 00000000..5893dacd
--- /dev/null
+++ b/src/utils/text-safe.ts
@@ -0,0 +1,59 @@
+/**
+ * Texte sûr pour un corps JSON destiné à un fournisseur.
+ *
+ * Un surrogate UTF-16 isolé — ce que produit n'importe quelle coupe par index sur une chaîne qui
+ * contient un emoji — traverse `JSON.stringify` sous la forme `\ud83c`, et certains serveurs
+ * refusent le corps entier : DeepSeek répond « 400 Failed to parse the request body as JSON:
+ * messages[6].content: unexpected end of hex escape ». Mesuré sur api.deepseek.com : la même
+ * chaîne avec le surrogate *brut* en UTF-8 passe (200), la même en séquence d'échappement est
+ * rejetée (400). La coupe doit donc tomber entre deux points de code, et le texte envoyé ne doit
+ * plus contenir de moitié de paire.
+ */
+
+const HIGH_SURROGATE_START = 0xd800;
+const HIGH_SURROGATE_END = 0xdbff;
+const LOW_SURROGATE_START = 0xdc00;
+const LOW_SURROGATE_END = 0xdfff;
+
+function isHigh(code: number): boolean {
+ return code >= HIGH_SURROGATE_START && code <= HIGH_SURROGATE_END;
+}
+
+function isLow(code: number): boolean {
+ return code >= LOW_SURROGATE_START && code <= LOW_SURROGATE_END;
+}
+
+/**
+ * Retire les surrogates isolés. Une paire valide (emoji) est conservée telle quelle : seules les
+ * moitiés orphelines — celles qui font échouer le serveur — disparaissent.
+ */
+export function stripLoneSurrogates(text: string): string {
+ let out = '';
+ for (let i = 0; i < text.length; i += 1) {
+ const code = text.charCodeAt(i);
+ if (isHigh(code)) {
+ const next = i + 1 < text.length ? text.charCodeAt(i + 1) : 0;
+ if (isLow(next)) {
+ out += text[i] + text[i + 1];
+ i += 1;
+ continue;
+ }
+ continue; // high sans low : on jette la moitié
+ }
+ if (isLow(code)) continue; // low sans high : on jette la moitié
+ out += text[i];
+ }
+ return out;
+}
+
+/**
+ * Coupe à `max` caractères sans jamais séparer une paire de surrogates, puis retire ce qui
+ * resterait d'isolé. `max` compte des unités UTF-16, comme `String.prototype.length`.
+ */
+export function truncateText(text: string, max: number): string {
+ if (max <= 0) return '';
+ if (text.length <= max) return stripLoneSurrogates(text);
+ let end = max;
+ if (end > 0 && isHigh(text.charCodeAt(end - 1))) end -= 1; // la paire commençait juste avant la coupe
+ return stripLoneSurrogates(text.slice(0, end));
+}