Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(maker-shared): 丢掉整段泄漏的模型停止符 (#3489)
Dashd1171fc58cc3
diff --git a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.tsindex 27d1ba8686..e8f4d29b64 100644--- a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts+++ b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts@@ -2238,8 +2238,10 @@ describe('consumeLastAssistantPersistId(per-turn 费用挂载的目标消息追it('does not persist a leaked Grok stop token as the last assistant', async () => {const first = onAssistantTextEvent(SESSION, { text: '现有 reviewer 空闲。', isFinal: true }, null);const leaked = onAssistantTextEvent(SESSION, { text: '<|eos|>', isFinal: true }, null);+ const repeated = onAssistantTextEvent(SESSION, { text: '<|eos|><|eos|>', isFinal: true }, null);await flushWrites();expect(leaked).toBeUndefined();+ expect(repeated).toBeUndefined();expect(createMessage).toHaveBeenCalledTimes(1);expect(consumeLastAssistantPersistId(SESSION)).toBe(first);});diff --git a/apps/desktop/src/main/localDb/__tests__/mapperCitation.test.ts b/apps/desktop/src/main/localDb/__tests__/mapperCitation.test.tsindex 75a6e371d5..7af2d8357a 100644--- a/apps/desktop/src/main/localDb/__tests__/mapperCitation.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/mapperCitation.test.ts@@ -44,7 +44,15 @@ describe('message mapper internal citation compatibility', () => {} as Parameters<typeof messageToCamel>[0];expect(messageToCamel(row).content).toBe('');+ expect(+ messageToCamel({+ ...row,+ id: 'message-eos-repeat',+ content: JSON.stringify('<|eos|><|eos|>'),+ }).content,+ ).toBe('');expect(extractMessagePreview(JSON.stringify('<|eos|>'), 'assistant')).toBeNull();+ expect(extractMessagePreview(JSON.stringify('<|eos|><|eos|>'), 'assistant')).toBeNull();expect(extractMessagePreview(JSON.stringify('The token is <|eos|>'), 'assistant')).toBe('The token is <|eos|>',);diff --git a/packages/maker-core/src/agents/claude-code/__tests__/translator-subagent-model.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/translator-subagent-model.test.tsindex 01fc1aea4d..0b1ed937da 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/translator-subagent-model.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/translator-subagent-model.test.ts@@ -222,6 +222,32 @@ describe('Claude Code assistant text streaming contract', () => {expect(ctx.turn.lastAssistantMsgHadSubstance).toBe(true);});+ it('does not emit a repeated Grok stop token as assistant text', async () => {+ const queue = createAsyncQueue<AgentEvent>();+ const ctx = createCtx();++ translateSdkMessage(+ {+ type: 'assistant',+ uuid: 'assistant-eos-repeat',+ session_id: 'sdk-session',+ parent_tool_use_id: null,+ message: {+ model: 'grok-4.6',+ content: [{ type: 'text', text: '<|eos|><|eos|>' }],+ },+ },+ queue,+ ctx,+ );++ const textEvents = (await collect(queue)).filter((event) => event.type === 'text');+ expect(textEvents).toEqual([]);+ expect(ctx.turn.hasEmittedText).toBe(false);+ expect(ctx.turn.uiEmittedText).toBe('');+ expect(ctx.turn.lastAssistantMsgHadSubstance).toBe(true);+ });+it('does not emit a stop token split across streaming deltas', async () => {const queue = createAsyncQueue<AgentEvent>();const ctx = createCtx();diff --git a/packages/maker-core/src/agents/codex/translator.test.ts b/packages/maker-core/src/agents/codex/translator.test.tsindex 9aacc5b8d1..5ad92c76a2 100644--- a/packages/maker-core/src/agents/codex/translator.test.ts+++ b/packages/maker-core/src/agents/codex/translator.test.ts@@ -2048,6 +2048,7 @@ describe('codex internal citation 归一化 (#785)', () => {expect(stableCitationBoundary('<|eo')).toBe(0);expect(stableCitationBoundary('<')).toBe(0);expect(stableCitationBoundary(' <|eos|>')).toBe(0);+ expect(stableCitationBoundary('<|eos|><|eos|>')).toBe(0);expect(stableCitationBoundary('The token is <|eos|>')).toBe('The token is <|eos|>'.length);});@@ -2088,6 +2089,7 @@ describe('codex internal citation 归一化 (#785)', () => {expect(finalizeCodexCitationText('<')).toBe('<');expect(finalizeCodexCitationText('<|eo')).toBe('<|eo');expect(finalizeCodexCitationText('<|eos|>')).toBe('');+ expect(finalizeCodexCitationText('<|eos|><|eos|>')).toBe('');});it('Web Search 引用标记被剥离,普通 cite 文本与相邻标点不变', async () => {diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.tsindex 7276872cb3..1af0f43453 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts@@ -355,6 +355,44 @@ describe('pi translator', () => {expect(events.filter((event) => event.type === 'text')).toEqual([]);});+ it('does not emit a repeated Grok stop token as assistant text', () => {+ const ctx = createPiTranslateContext(noopLogger);+ const { queue, events } = makeQueue();++ translatePiEvent(ev({ type: 'message_start' }), queue, ctx);+ translatePiEvent(+ ev({+ type: 'message_update',+ assistantMessageEvent: { type: 'text_delta', contentIndex: 0, delta: '<|eos|>' },+ }),+ queue,+ ctx,+ );+ translatePiEvent(+ ev({+ type: 'message_update',+ assistantMessageEvent: { type: 'text_delta', contentIndex: 0, delta: '<|eos|>' },+ }),+ queue,+ ctx,+ );+ translatePiEvent(+ ev({+ type: 'message_end',+ message: {+ role: 'assistant',+ content: [{ type: 'text', text: '<|eos|><|eos|>' }],+ model: 'xai/grok-4.6',+ stopReason: 'stop',+ },+ }),+ queue,+ ctx,+ );++ expect(events.filter((event) => event.type === 'text')).toEqual([]);+ });+it('surfaces a terminal provider error after Pi settles instead of staying in Working', () => {const ctx = createPiTranslateContext(noopLogger);const { queue, events } = makeQueue();diff --git a/packages/maker-core/src/agents/pi/translator.ts b/packages/maker-core/src/agents/pi/translator.tsindex 3625a8704a..669da3e168 100644--- a/packages/maker-core/src/agents/pi/translator.ts+++ b/packages/maker-core/src/agents/pi/translator.ts@@ -119,7 +119,7 @@ export interface PiTranslateContext {/** contentIndex → 当前消息内的 thinking block 状态。 */thinkingBlocks: Map<number, PiThinkingBlock>;/**- * contentIndex → 独立停止符暂存。text_delta 可能把 `<|eos|>` 拆开,+ * contentIndex → 停止符控制暂存。text_delta 可能把 `<|eos|>` 拆开或连写,* 必须按本块判定,不能和别的 text block 共用。*/streamStopTokenByIndex: Map<number, StandaloneStopTokenHold>;diff --git a/packages/maker-shared/src/internalCitation.test.ts b/packages/maker-shared/src/internalCitation.test.tsindex 011cfc45e6..040a5e452c 100644--- a/packages/maker-shared/src/internalCitation.test.ts+++ b/packages/maker-shared/src/internalCitation.test.ts@@ -44,6 +44,20 @@ describe('leaked model stop tokens', () => {expect(stripInternalWebCitations(' <|eos|>\n')).toBe('');});+ it('strips a whole-message run of stop tokens, including mixed tokens and blank lines', () => {+ expect(stripStandaloneModelStopToken('<|eos|><|eos|>')).toBe('');+ expect(stripInternalWebCitations('<|eos|>\n\n<|eos|>')).toBe('');+ expect(stripInternalWebCitations(' <|eos|> <|eot_id|>\n')).toBe('');+ expect(stripInternalWebCitations('<|eos|>answer')).toBe('<|eos|>answer');+ });++ it('leaves completed messages that start with a stop token but continue as prose', () => {+ expect(stripStandaloneModelStopToken('<|eos|>answer')).toBe('<|eos|>answer');+ expect(stripInternalWebCitations('<|endoftext|> The token is still here')).toBe(+ '<|endoftext|> The token is still here',+ );+ });+it('leaves embedded stop-token prose intact', () => {expect(stripInternalWebCitations('The token is <|eos|>')).toBe('The token is <|eos|>');expect(stripInternalWebCitations('done<|eot_id|>')).toBe('done<|eot_id|>');@@ -55,16 +69,20 @@ describe('leaked model stop tokens', () => {expect(stableStandaloneModelStopTokenBoundary('<|eo')).toBe(0);expect(stableStandaloneModelStopTokenBoundary(' <|eo')).toBe(0);expect(stableStandaloneModelStopTokenBoundary('<|eos|>')).toBe(0);+ expect(stableStandaloneModelStopTokenBoundary('<|eos|><|eos|>')).toBe(0);+ expect(stableStandaloneModelStopTokenBoundary('<|eos|><|eo')).toBe(0);expect(stableStandaloneModelStopTokenBoundary('The token is <|eo')).toBe('The token is <|eo'.length);expect(isPossibleStandaloneStopPrefix(' <|eo')).toBe(true);expect(isPossibleStandaloneStopPrefix('<')).toBe(true);expect(isPossibleStandaloneStopPrefix('<|')).toBe(true);expect(isPossibleStandaloneStopPrefix(`${' '.repeat(23)}<|eos|>`)).toBe(true);+ expect(isPossibleStandaloneStopPrefix('<|eos|><|eos|>')).toBe(true);expect(isPossibleStandaloneStopPrefix('The token is <|eo')).toBe(false);});it('is idempotent', () => {expect(stripInternalWebCitations(stripInternalWebCitations('<|eos|>'))).toBe('');+ expect(stripInternalWebCitations(stripInternalWebCitations('<|eos|><|eos|>'))).toBe('');expect(stripInternalWebCitations(stripInternalWebCitations('The token is <|eos|>'))).toBe('The token is <|eos|>',);@@ -91,11 +109,18 @@ describe('leaked model stop tokens', () => {it('holds whitespace-only deltas without releasing a later leftover token', () => {const buffer = { pending: '', emitted: false };expect(holdStandaloneStopTokenDelta(buffer, ' '.repeat(23))).toBeNull();+ expect(buffer.pending).toBe(' '.repeat(23));expect(holdStandaloneStopTokenDelta(buffer, '<|eos|>')).toBeNull();expect(buffer.emitted).toBe(false);expect(buffer.pending.trim()).toBe('<|eos|>');});+ it('keeps ordinary leading whitespace when later prose arrives', () => {+ const buffer = { pending: '', emitted: false };+ expect(holdStandaloneStopTokenDelta(buffer, ' ')).toBeNull();+ expect(holdStandaloneStopTokenDelta(buffer, 'code')).toBe(' code');+ });+it('holds a one-character leftover prefix until the closer arrives', () => {const buffer = { pending: '', emitted: false };expect(holdStandaloneStopTokenDelta(buffer, '<')).toBeNull();@@ -103,6 +128,21 @@ describe('leaked model stop tokens', () => {expect(buffer).toEqual({ pending: '<|eos|>', emitted: false });});+ it('keeps a split leftover so later prose reconstructs the original text', () => {+ const buffer = { pending: '', emitted: false };+ expect(holdStandaloneStopTokenDelta(buffer, '<|eos|>')).toBeNull();+ expect(holdStandaloneStopTokenDelta(buffer, 'answer')).toBe('<|eos|>answer');+ });++ it('drops a completed leftover so a second copy cannot flush it as prose', () => {+ const buffer = { pending: '', emitted: false };+ expect(holdStandaloneStopTokenDelta(buffer, '<|eos|>')).toBeNull();+ expect(holdStandaloneStopTokenDelta(buffer, '<|eos|>')).toBeNull();+ expect(buffer.emitted).toBe(false);+ expect(buffer.pending.trim()).toBe('<|eos|><|eos|>');+ expect(holdStandaloneStopTokenDelta(buffer, 'answer')).toBe('<|eos|><|eos|>answer');+ });+it('still strips a split web citation after ordinary prose has been emitted', () => {const buffer = { pending: '', emitted: false };expect(holdStandaloneStopTokenDelta(buffer, '结论。')).toBe('结论。');diff --git a/packages/maker-shared/src/internalCitation.ts b/packages/maker-shared/src/internalCitation.tsindex b3fa2c963b..16be636722 100644--- a/packages/maker-shared/src/internalCitation.ts+++ b/packages/maker-shared/src/internalCitation.ts@@ -5,16 +5,16 @@* expose only the flattened text and omit the structured URL annotations, so* client boundaries must remove the opaque marker deterministically.*- * Grok / xAI may also leak the stop token `<|eos|>` as visible assistant- * text, typically as a whole message after a tool-only wrap-up. That marker- * is not user-facing prose either.+ * Grok / xAI may also leak stop tokens such as `<|eos|>` as visible+ * assistant text, typically as a wrap-up after a tool-only turn. One token,+ * several in a row, or the same tokens split across stream deltas are still+ * transport control, not user-facing prose. Mentions that follow real+ * prose, such as `The token is <|eos|>`, stay intact.*/-const MODEL_STOP_TOKENS = new Set(['<|endoftext|>', '<|eot_id|>', '<|im_end|>', '<|eos|>']);+const MODEL_STOP_TOKEN_LIST = ['<|endoftext|>', '<|eot_id|>', '<|im_end|>', '<|eos|>'];const LONGEST_MODEL_STOP_TOKEN = Math.max(- ...[...MODEL_STOP_TOKENS].map((token) => token.length),+ ...MODEL_STOP_TOKEN_LIST.map((token) => token.length),);-/** Leading whitespace plus the longest token. Anything longer cannot be standalone. */-const MAX_STANDALONE_STOP_PREFIX = LONGEST_MODEL_STOP_TOKEN + 16;const WEB_CITATION_OPEN = '\uE200cite\uE202';const WEB_CITATION_CLOSE = '\uE201';@@ -76,34 +76,67 @@ function stripInternalWebCitationMarkers(text: string): string {}}+function matchStopTokenAt(text: string, index: number): string | null {+ for (const token of MODEL_STOP_TOKEN_LIST) {+ if (text.startsWith(token, index)) return token;+ }+ return null;+}++function isIncompleteStopTokenPrefix(text: string): boolean {+ return text.length > 0+ && text.length <= LONGEST_MODEL_STOP_TOKEN+ && MODEL_STOP_TOKEN_LIST.some((token) => token.startsWith(text));+}++/**+ * Eat a leading run of known stop tokens and the whitespace around them.+ * Completed messages only disappear when nothing remains. The streaming+ * hold keeps a recognized run pending until later prose proves the block+ * is not stop-control-only, then emits that original text.+ */+function consumeLeadingStopControl(text: string): { remainder: string; consumedToken: boolean } {+ let index = 0;+ let consumedToken = false;+ while (index < text.length) {+ if ((text[index] ?? '').trim() === '') {+ index += 1;+ continue;+ }+ const token = matchStopTokenAt(text, index);+ if (!token) break;+ consumedToken = true;+ index += token.length;+ }+ return { remainder: text.slice(index), consumedToken };+}+/**- * Drop a leaked model stop token only when it is the whole assistant- * message (optional surrounding whitespace). Embedded mentions such as- * `The token is <|eos|>` stay intact.+ * Drop a leaked stop-token run only when it is the whole assistant+ * message (optional surrounding whitespace). Repeated or mixed tokens+ * still count. Mentions such as `The token is <|eos|>`, or a token+ * glued to later prose (`<|eos|>answer`), stay intact.*/export function stripStandaloneModelStopToken(text: string): string {- return MODEL_STOP_TOKENS.has(text.trim()) ? '' : text;+ const { remainder, consumedToken } = consumeLeadingStopControl(text);+ return consumedToken && remainder.length === 0 ? '' : text;}/**- * True while `text` is still only a possible whole-message stop token:- * surrounding whitespace, a known token, or any incomplete prefix of one- * (`<`, `<|`, `<|eo`, …). Used to hold streaming deltas until the leftover- * can be dropped or flushed.+ * True while `text` is still only stop-token control: whitespace, one or+ * more known tokens, and at most one incomplete prefix (`<`, `<|eo`, …).+ * Used to hold streaming deltas until the leftover can be dropped or flushed.*/export function isPossibleStandaloneStopPrefix(text: string): boolean {- const candidate = text.trim();- if (candidate.length === 0) return true;- if (MODEL_STOP_TOKENS.has(candidate)) return true;- if (candidate.length > MAX_STANDALONE_STOP_PREFIX) return false;- return [...MODEL_STOP_TOKENS].some((token) => token.startsWith(candidate));+ const { remainder } = consumeLeadingStopControl(text);+ return remainder.length === 0 || isIncompleteStopTokenPrefix(remainder);}/*** Return the append-only prefix of a streaming snapshot. A standalone- * leftover — including its surrounding whitespace and an incomplete- * `<|eos` prefix — is withheld until the closer arrives, because the- * completed token will disappear.+ * leftover — including repeated tokens and an incomplete `<|eos` prefix —+ * is withheld until the closer arrives, because the completed control+ * will disappear.*/export function stableStandaloneModelStopTokenBoundary(text: string): number {return isPossibleStandaloneStopPrefix(text) ? 0 : text.length;@@ -115,26 +148,25 @@ export interface StandaloneStopTokenHold {}/**- * Hold a leftover stop token until this stream has either completed it or- * proven it is ordinary prose. After visible prose starts, still hold an- * unfinished Web-citation tail so split markers are not emitted raw.- * The buffer is per stream; callers must not share it across concurrent- * text streams.+ * Hold leftover stop-token control until this stream has either completed+ * it or proven it is ordinary prose. A recognized run stays pending so a+ * later `answer` can still reconstruct `<|eos|>answer`; only a later copy+ * of the same control run is dropped. After visible prose starts, still+ * hold an unfinished Web-citation tail so split markers are not emitted+ * raw. The buffer is per stream; callers must not share it across+ * concurrent text streams.*/export function holdStandaloneStopTokenDelta(buffer: StandaloneStopTokenHold,delta: string,): string | null {const combined = buffer.pending + delta;- if (!buffer.emitted && isPossibleStandaloneStopPrefix(combined)) {- const candidate = combined.trim();- if (candidate.length === 0) {- buffer.pending = combined.slice(-MAX_STANDALONE_STOP_PREFIX);- } else {- const tokenStart = combined.lastIndexOf(candidate);- buffer.pending = `${combined.slice(0, tokenStart).slice(-MAX_STANDALONE_STOP_PREFIX)}${candidate}`;+ if (!buffer.emitted) {+ const { remainder } = consumeLeadingStopControl(combined);+ if (remainder.length === 0 || isIncompleteStopTokenPrefix(remainder)) {+ buffer.pending = combined;+ return null;}- return null;}const citationEnd = stableInternalWebCitationBoundary(combined);buffer.pending = combined.slice(citationEnd);