Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix: hold only an unresolved standalone stop-token prefix

Dash911f5f78c615
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.ts
index 97cf3c8dba..6e3cec1b23 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
@@ -195,6 +195,33 @@ describe('Claude Code assistant text streaming contract', () => {
expect(ctx.turn.uiEmittedText).toBe('');
});
+ it('does not emit leading whitespace from a split standalone stop token', async () => {
+ const queue = createAsyncQueue<AgentEvent>();
+ const ctx = createCtx();
+
+ for (const [uuid, text] of [
+ ['stream-ws-1', ' <|eo'],
+ ['stream-ws-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();
@@ -297,7 +324,7 @@ describe('Claude Code assistant text streaming contract', () => {
}),
]);
expect(ctx.turn.uiEmittedText).toBe('answer');
- expect(ctx.rt.streamStopTokenByKey.get('toolu-a')).toEqual({ raw: '<|eo', emitted: 0 });
+ expect(ctx.rt.streamStopTokenByKey.get('toolu-a')).toEqual({ pending: '<|eo' });
});
it('keeps a result fallback tail unmarked so it cannot replace accumulated streaming text', async () => {
diff --git a/packages/maker-core/src/agents/claude-code/translator.ts b/packages/maker-core/src/agents/claude-code/translator.ts
index a33bf401a3..b0a76cd82a 100644
--- a/packages/maker-core/src/agents/claude-code/translator.ts
+++ b/packages/maker-core/src/agents/claude-code/translator.ts
@@ -22,7 +22,7 @@ import {
redactSensitiveText,
} from '@cindy/maker-shared/error-redaction';
import {
- stableStandaloneModelStopTokenBoundary,
+ isPossibleStandaloneStopPrefix,
stripInternalWebCitations,
} from '@cindy/maker-shared/internal-citation';
import type { createAsyncQueue } from '../shared/async-queue.js';
@@ -151,7 +151,7 @@ export interface RuntimeState {
* 按 streamKey 隔离的停止符清洗缓冲。text_delta 可能把 `<|eos|>` 拆开,
* 必须先拼回该 stream 的快照再清洗;并发 subagent 不能共用一份原文。
*/
- streamStopTokenByKey: Map<string, { raw: string; emitted: number }>;
+ streamStopTokenByKey: Map<string, { pending: string }>;
}
export function newRuntimeState(): RuntimeState {
@@ -1287,17 +1287,22 @@ 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 buffer = ctx.rt.streamStopTokenByKey.get(streamKey) ?? { raw: '', emitted: 0 };
- buffer.raw += delta.text;
- const visible = stripInternalWebCitations(
- buffer.raw.slice(0, stableStandaloneModelStopTokenBoundary(buffer.raw)),
- );
- const visibleDelta = visible.slice(buffer.emitted);
+ const buffer = ctx.rt.streamStopTokenByKey.get(streamKey) ?? { pending: '' };
+ const holdStandalonePrefix = ctx.turn.uiEmittedText.length === 0;
+ const combined = buffer.pending + delta.text;
+ if (holdStandalonePrefix && isPossibleStandaloneStopPrefix(combined)) {
+ buffer.pending = combined;
+ ctx.rt.streamStopTokenByKey.set(streamKey, buffer);
+ return;
+ }
+ buffer.pending = '';
ctx.rt.streamStopTokenByKey.set(streamKey, buffer);
+ const visibleDelta = holdStandalonePrefix
+ ? stripInternalWebCitations(combined)
+ : combined;
if (visibleDelta.length > 0) {
ctx.turn.hasEmittedText = true;
ctx.turn.uiEmittedText += visibleDelta;
- buffer.emitted = visible.length;
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.ts
index dd162cbfe5..07162299c3 100644
--- a/packages/maker-shared/src/internalCitation.test.ts
+++ b/packages/maker-shared/src/internalCitation.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import {
+ isPossibleStandaloneStopPrefix,
stableInternalWebCitationBoundary,
stableStandaloneModelStopTokenBoundary,
stripInternalWebCitations,
@@ -51,8 +52,11 @@ describe('leaked model stop tokens', () => {
it('holds an incomplete standalone prefix until the closer arrives', () => {
expect(stableStandaloneModelStopTokenBoundary('hello')).toBe(5);
expect(stableStandaloneModelStopTokenBoundary('<|eo')).toBe(0);
+ expect(stableStandaloneModelStopTokenBoundary(' <|eo')).toBe(0);
expect(stableStandaloneModelStopTokenBoundary('<|eos|>')).toBe(0);
expect(stableStandaloneModelStopTokenBoundary('The token is <|eo')).toBe('The token is <|eo'.length);
+ expect(isPossibleStandaloneStopPrefix(' <|eo')).toBe(true);
+ expect(isPossibleStandaloneStopPrefix('The token is <|eo')).toBe(false);
});
it('is idempotent', () => {
diff --git a/packages/maker-shared/src/internalCitation.ts b/packages/maker-shared/src/internalCitation.ts
index 7c9dd17dd8..777980661a 100644
--- a/packages/maker-shared/src/internalCitation.ts
+++ b/packages/maker-shared/src/internalCitation.ts
@@ -11,6 +11,11 @@
*/
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 LONGEST_MODEL_STOP_TOKEN = Math.max(
+ ...[...MODEL_STOP_TOKENS].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';
@@ -82,28 +87,25 @@ export function stripStandaloneModelStopToken(text: string): string {
}
/**
- * 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.
+ * True while `text` is still only a possible whole-message stop token:
+ * surrounding whitespace, a known token, or an incomplete `<|eos` prefix.
+ * Used to hold streaming deltas until the leftover can be dropped or flushed.
*/
-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;
+export function isPossibleStandaloneStopPrefix(text: string): boolean {
+ if (MODEL_STOP_TOKENS.has(text.trim())) return true;
+ if (text.length > MAX_STANDALONE_STOP_PREFIX) return false;
+ const candidate = text.trim();
+ if (candidate.length === 0) return true;
+ if (!candidate.startsWith('<|')) return false;
+ return MODEL_STOP_TOKEN_NAMES.some((name) => `<|${name}|>`.startsWith(candidate));
+}
- 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;
+/**
+ * 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.
+ */
+export function stableStandaloneModelStopTokenBoundary(text: string): number {
+ return isPossibleStandaloneStopPrefix(text) ? 0 : text.length;
}