Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix: only strip a whole-message leaked stop token
Dashf34254326ba8
diff --git a/apps/desktop/src/main/localDb/__tests__/mapperCitation.test.ts b/apps/desktop/src/main/localDb/__tests__/mapperCitation.test.tsindex 2ef5b6302d..5585c42302 100644--- a/apps/desktop/src/main/localDb/__tests__/mapperCitation.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/mapperCitation.test.ts@@ -45,6 +45,9 @@ describe('message mapper internal citation compatibility', () => {expect(messageToCamel(row).content).toBe('');expect(extractMessagePreview(JSON.stringify('<|eos|>'), 'assistant')).toBeNull();+ expect(extractMessagePreview(JSON.stringify('The token is <|eos|>'), 'assistant')).toBe(+ 'The token is <|eos|>',+ );expect(extractMessagePreview(JSON.stringify('用户说 <|eos|>'), 'user')).toBe('用户说 <|eos|>');});});diff --git a/packages/maker-core/src/agents/claude-code/__tests__/translator-context-overflow.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/translator-context-overflow.test.tsindex c7e83c79f7..7968ed2ab2 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/translator-context-overflow.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/translator-context-overflow.test.ts@@ -30,6 +30,7 @@ function createTurnState(): TurnState {sawCompactBoundary: false,hasEmittedText: false,uiEmittedText: '',+ rawAssistantText: '',pendingApiError: null,interruptRequested: false,generation: 0,diff --git a/packages/maker-core/src/agents/claude-code/__tests__/translator-context-window.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/translator-context-window.test.tsindex 09399fa1b9..bd7977642e 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/translator-context-window.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/translator-context-window.test.ts@@ -17,6 +17,7 @@ function createTurnState(): TurnState {sawCompactBoundary: false,hasEmittedText: false,uiEmittedText: '',+ rawAssistantText: '',pendingApiError: null,interruptRequested: false,generation: 0,diff --git a/packages/maker-core/src/agents/claude-code/__tests__/translator-empty-response.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/translator-empty-response.test.tsindex a887c5a761..9ce8c8631b 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/translator-empty-response.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/translator-empty-response.test.ts@@ -17,6 +17,7 @@ function createTurnState(): TurnState {sawCompactBoundary: false,hasEmittedText: false,uiEmittedText: '',+ rawAssistantText: '',pendingApiError: null,interruptRequested: false,generation: 0,diff --git a/packages/maker-core/src/agents/claude-code/__tests__/translator-error-result.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/translator-error-result.test.tsindex cfa202642a..6ddc9059a4 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/translator-error-result.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/translator-error-result.test.ts@@ -17,6 +17,7 @@ function createTurnState(): TurnState {sawCompactBoundary: false,hasEmittedText: false,uiEmittedText: '',+ rawAssistantText: '',pendingApiError: null,interruptRequested: false,generation: 0,diff --git a/packages/maker-core/src/agents/claude-code/__tests__/translator-silent-stop.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/translator-silent-stop.test.tsindex d86883078c..3a1efc5840 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/translator-silent-stop.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/translator-silent-stop.test.ts@@ -25,6 +25,7 @@ function createTurnState(): TurnState {sawCompactBoundary: false,hasEmittedText: false,uiEmittedText: '',+ rawAssistantText: '',pendingApiError: null,interruptRequested: false,generation: 0,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 49aceaefa2..234db6b087 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@@ -17,6 +17,7 @@ function createTurnState(): TurnState {sawCompactBoundary: false,hasEmittedText: false,uiEmittedText: '',+ rawAssistantText: '',pendingApiError: null,interruptRequested: false,generation: 0,@@ -168,6 +169,62 @@ describe('Claude Code assistant text streaming contract', () => {expect(ctx.turn.lastAssistantMsgHadSubstance).toBe(false);});+ it('does not emit a stop token split across streaming deltas', async () => {+ const queue = createAsyncQueue<AgentEvent>();+ const ctx = createCtx();++ for (const [uuid, text] of [+ ['stream-eos-1', '<|eo'],+ ['stream-eos-2', 's|>'],+ ] as const) {+ translateSdkMessage(+ {+ type: 'stream_event',+ uuid,+ session_id: 'sdk-session',+ parent_tool_use_id: null,+ event: { type: 'content_block_delta', delta: { type: 'text_delta', text } },+ },+ 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('');+ });++ it('keeps an embedded stop token in streamed assistant prose', async () => {+ const queue = createAsyncQueue<AgentEvent>();+ const ctx = createCtx();++ for (const [uuid, text] of [+ ['stream-embed-1', 'The token is '],+ ['stream-embed-2', '<|eos|>'],+ ] as const) {+ translateSdkMessage(+ {+ type: 'stream_event',+ uuid,+ session_id: 'sdk-session',+ parent_tool_use_id: null,+ event: { type: 'content_block_delta', delta: { type: 'text_delta', text } },+ },+ queue,+ ctx,+ );+ }++ const textEvents = (await collect(queue)).filter((event) => event.type === 'text');+ expect(textEvents.map((event) => event.data)).toEqual([+ { text: 'The token is ', isFinal: false },+ { text: '<|eos|>', isFinal: false },+ ]);+ expect(ctx.turn.uiEmittedText).toBe('The token is <|eos|>');+ });+it('keeps a result fallback tail unmarked so it cannot replace accumulated streaming text', async () => {const queue = createAsyncQueue<AgentEvent>();const ctx = createCtx();diff --git a/packages/maker-core/src/agents/claude-code/__tests__/translator-tool-output.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/translator-tool-output.test.tsindex 78b2555ec2..7850697b75 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/translator-tool-output.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/translator-tool-output.test.ts@@ -18,6 +18,7 @@ function createTurnState(): TurnState {sawCompactBoundary: false,hasEmittedText: false,uiEmittedText: '',+ rawAssistantText: '',pendingApiError: null,interruptRequested: false,generation: 0,diff --git a/packages/maker-core/src/agents/claude-code/__tests__/translator-workflow.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/translator-workflow.test.tsindex e27056dca1..5acf4fdfa0 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/translator-workflow.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/translator-workflow.test.ts@@ -17,6 +17,7 @@ function createTurnState(): TurnState {sawCompactBoundary: false,hasEmittedText: false,uiEmittedText: '',+ rawAssistantText: '',pendingApiError: null,interruptRequested: false,generation: 0,diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex e49ac23f0c..cd03f158cf 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -2290,6 +2290,7 @@ export class ClaudeCodeAgent extends BaseAgent {sawCompactBoundary: false,hasEmittedText: false,uiEmittedText: '',+ rawAssistantText: '',pendingApiError: null,interruptRequested: false,generation: 0,diff --git a/packages/maker-core/src/agents/claude-code/translator.ts b/packages/maker-core/src/agents/claude-code/translator.tsindex 619fab30ee..66e8f30ebc 100644--- a/packages/maker-core/src/agents/claude-code/translator.ts+++ b/packages/maker-core/src/agents/claude-code/translator.ts@@ -21,7 +21,10 @@ import {extractNonSecretErrorSignals,redactSensitiveText,} from '@cindy/maker-shared/error-redaction';-import { stripInternalWebCitations } from '@cindy/maker-shared/internal-citation';+import {+ stableStandaloneModelStopTokenBoundary,+ stripInternalWebCitations,+} from '@cindy/maker-shared/internal-citation';import type { createAsyncQueue } from '../shared/async-queue.js';import { stripTerminalControlSequences } from '../shared/terminal-output.js';import { formatOverloadRetryMessage, parseOverloadError } from '../shared/overload-error.js';@@ -57,6 +60,11 @@ export interface TurnState {* "整轮全空"和"前面推过、最后一段被截断";uiEmittedText 让兜底能精确算出缺哪一段。*/uiEmittedText: string;+ /**+ * 当前 assistant text block 尚未归一化的累计原文。text_delta 可能把+ * `<|eos|>` 拆开;必须先拼回快照再清洗,才能按住半截前缀、丢掉整条泄漏。+ */+ rawAssistantText: string;/*** SDK API retry / assistant error envelope 的暂存详情。两者都不是可靠的 turn* 终态: Claude Code 可能随后自动重试并返回成功 result。只有最终@@ -171,6 +179,7 @@ function resetTurnState(turn: TurnState): void {turn.sawCompactBoundary = false;turn.hasEmittedText = false;turn.uiEmittedText = '';+ turn.rawAssistantText = '';turn.pendingApiError = null;turn.interruptRequested = false;turn.lastAssistantMsgHadSubstance = true;@@ -1155,6 +1164,7 @@ function handleAssistant(for (const blockRaw of content) {const block = blockRaw as { type?: string; text?: string; name?: string; id?: string; input?: unknown; thinking?: string; signature?: string };if (block.type === 'text' && typeof block.text === 'string') {+ ctx.turn.rawAssistantText = '';const visibleText = stripInternalWebCitations(block.text);ctx.turn.text += visibleText;if (visibleText.length > 0) {@@ -1276,10 +1286,17 @@ function handleStreamEvent(const delta = event.delta as { type?: string; text?: string; thinking?: string } | undefined;if (!delta) return;if (delta.type === 'text_delta' && typeof delta.text === 'string') {- const visibleDelta = stripInternalWebCitations(delta.text);+ ctx.turn.rawAssistantText += delta.text;+ const visible = stripInternalWebCitations(+ ctx.turn.rawAssistantText.slice(+ 0,+ stableStandaloneModelStopTokenBoundary(ctx.turn.rawAssistantText),+ ),+ );+ const visibleDelta = visible.slice(ctx.turn.uiEmittedText.length);if (visibleDelta.length > 0) {ctx.turn.hasEmittedText = true;- ctx.turn.uiEmittedText += visibleDelta;+ ctx.turn.uiEmittedText = visible;queue.push({type: 'text',data: { text: visibleDelta, isFinal: false },diff --git a/packages/maker-shared/src/internalCitation.test.ts b/packages/maker-shared/src/internalCitation.test.tsindex e14ab49b80..dd162cbfe5 100644--- a/packages/maker-shared/src/internalCitation.test.ts+++ b/packages/maker-shared/src/internalCitation.test.ts@@ -2,8 +2,9 @@ import { describe, expect, it } from 'vitest';import {stableInternalWebCitationBoundary,+ stableStandaloneModelStopTokenBoundary,stripInternalWebCitations,- stripLeakedModelStopTokens,+ stripStandaloneModelStopToken,} from './internalCitation.js';const source1 = '\uE200cite\uE202turn17search1\uE201';@@ -37,21 +38,27 @@ describe('internal Web citation normalization', () => {describe('leaked model stop tokens', () => {it('strips a whole-message Grok stop token to empty text', () => {- expect(stripLeakedModelStopTokens('<|eos|>')).toBe('');- expect(stripInternalWebCitations('<|eos|>')).toBe('');+ expect(stripStandaloneModelStopToken('<|eos|>')).toBe('');+ expect(stripInternalWebCitations(' <|eos|>\n')).toBe('');});- it('strips a trailing stop token after real prose', () => {- expect(stripInternalWebCitations('\u73B0\u6709 reviewer \u7A7A\u95F2\u3002<|eos|>')).toBe('\u73B0\u6709 reviewer \u7A7A\u95F2\u3002');+ 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|>');+ expect(stripInternalWebCitations('use <|placeholder|> here')).toBe('use <|placeholder|> here');});- it('leaves ordinary angle-bracket text and code fences untouched', () => {- expect(stripInternalWebCitations('use <|placeholder|> here')).toBe('use <|placeholder|> here');- expect(stripInternalWebCitations('See <eos> in the docs')).toBe('See <eos> in the docs');+ it('holds an incomplete standalone prefix until the closer arrives', () => {+ expect(stableStandaloneModelStopTokenBoundary('hello')).toBe(5);+ expect(stableStandaloneModelStopTokenBoundary('<|eo')).toBe(0);+ expect(stableStandaloneModelStopTokenBoundary('<|eos|>')).toBe(0);+ expect(stableStandaloneModelStopTokenBoundary('The token is <|eo')).toBe('The token is <|eo'.length);});it('is idempotent', () => {expect(stripInternalWebCitations(stripInternalWebCitations('<|eos|>'))).toBe('');- expect(stripInternalWebCitations(stripInternalWebCitations('done<|eot_id|>'))).toBe('done');+ expect(stripInternalWebCitations(stripInternalWebCitations('The token is <|eos|>'))).toBe(+ 'The token is <|eos|>',+ );});});diff --git a/packages/maker-shared/src/internalCitation.ts b/packages/maker-shared/src/internalCitation.tsindex 6ab273ea96..7c9dd17dd8 100644--- a/packages/maker-shared/src/internalCitation.ts+++ b/packages/maker-shared/src/internalCitation.ts@@ -9,7 +9,8 @@* text, typically as a whole message after a tool-only wrap-up. That marker* is not user-facing prose either.*/-const MODEL_STOP_TOKEN_RE = /<\|(?:endoftext|eot_id|im_end|eos)\|>/g;+const MODEL_STOP_TOKENS = new Set(['<|endoftext|>', '<|eot_id|>', '<|im_end|>', '<|eos|>']);+const MODEL_STOP_TOKEN_NAMES = ['endoftext', 'eot_id', 'im_end', 'eos'] as const;const WEB_CITATION_OPEN = '\uE200cite\uE202';const WEB_CITATION_CLOSE = '\uE201';@@ -49,7 +50,7 @@ export function stableInternalWebCitationBoundary(text: string): number {* left untouched. The transform is idempotent.*/export function stripInternalWebCitations(text: string): string {- return stripLeakedModelStopTokens(stripInternalWebCitationMarkers(text));+ return stripStandaloneModelStopToken(stripInternalWebCitationMarkers(text));}function stripInternalWebCitationMarkers(text: string): string {@@ -72,12 +73,37 @@ function stripInternalWebCitationMarkers(text: string): string {}/**- * Drop leaked model stop tokens. Whole-message leftovers become empty so- * persist / render callers can treat them as no user-facing text. Trailing- * tokens after real prose are removed without collapsing surrounding spaces- * that the caller already owns.+ * 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.*/-export function stripLeakedModelStopTokens(text: string): string {- if (!text.includes('<|')) return text;- return text.replace(MODEL_STOP_TOKEN_RE, '');+export function stripStandaloneModelStopToken(text: string): string {+ return MODEL_STOP_TOKENS.has(text.trim()) ? '' : text;+}++/**+ * Return the append-only prefix of a streaming snapshot. A trailing+ * incomplete `<|eos` / `<|im_end` prefix is withheld until the closer+ * arrives, because a completed standalone token will disappear.+ */+export function stableStandaloneModelStopTokenBoundary(text: string): number {+ if (stripStandaloneModelStopToken(text) === '') return 0;++ const trimmedStart = text.trimStart();+ const leading = text.length - trimmedStart.length;+ const candidate = trimmedStart.trimEnd();+ if (!candidate.startsWith('<|')) return text.length;++ let longest = 0;+ for (const name of MODEL_STOP_TOKEN_NAMES) {+ const token = `<|${name}|>`;+ const maxProbe = Math.min(candidate.length, token.length - 1);+ for (let length = maxProbe; length > 0; length -= 1) {+ if (candidate === token.slice(0, length)) {+ longest = Math.max(longest, length);+ break;+ }+ }+ }+ return longest > 0 ? leading : text.length;}