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(maker-core): stop degenerate Pi output loops

ZJPex25eb3777e946
diff --git a/packages/maker-core/src/agents/pi/__tests__/output-degeneration-protection.test.ts b/packages/maker-core/src/agents/pi/__tests__/output-degeneration-protection.test.ts
new file mode 100644
index 0000000000..85aa03a1fe
--- /dev/null
+++ b/packages/maker-core/src/agents/pi/__tests__/output-degeneration-protection.test.ts
@@ -0,0 +1,181 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { Logger } from '../../../interfaces/logger.js';
+import type { PiRpcEvent } from '../rpc-client.js';
+import {
+ consumePiOutputDegenerationDirective,
+ PiOutputDegenerationProtection,
+ shouldProtectPiOutput,
+} from '../output-degeneration-protection.js';
+
+const ev = (event: Record<string, unknown>): PiRpcEvent => event as unknown as PiRpcEvent;
+
+function loggerWithSpies(): Logger {
+ const logger = {
+ trace: vi.fn(),
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ fatal: vi.fn(),
+ child: () => logger,
+ } satisfies Logger;
+ return logger;
+}
+
+function textDelta(text: string): PiRpcEvent {
+ return ev({
+ type: 'message_update',
+ assistantMessageEvent: { type: 'text_delta', contentIndex: 0, delta: text },
+ });
+}
+
+describe('PiOutputDegenerationProtection', () => {
+ it('consumes only the explicit leading per-turn bypass directive', () => {
+ expect(consumePiOutputDegenerationDirective(
+ ' /allow-repetitive-output\nRepeat this fixture 10,000 times.',
+ )).toEqual({
+ prompt: 'Repeat this fixture 10,000 times.',
+ allowRepetitiveOutput: true,
+ });
+ expect(consumePiOutputDegenerationDirective(
+ '/allow-repetitive-output-now keep the normal guard',
+ )).toEqual({
+ prompt: '/allow-repetitive-output-now keep the normal guard',
+ allowRepetitiveOutput: false,
+ });
+ });
+
+ it('requests exactly one native abort and reports only non-content diagnostics', async () => {
+ const abort = vi.fn().mockResolvedValue({ success: true });
+ const onDetected = vi.fn();
+ const logger = loggerWithSpies();
+ const protection = new PiOutputDegenerationProtection({
+ logger,
+ isEnabled: () => true,
+ abort,
+ onDetected,
+ guardOptions: {
+ minimumCharacters: 4_096,
+ analysisWindowCharacters: 4_096,
+ checkIntervalCharacters: 1_024,
+ requiredConfirmations: 2,
+ },
+ });
+
+ protection.onEvent(ev({ type: 'message_start' }));
+ const repeated = 'let me write the file now; 现在执行;落地。'.repeat(300);
+ for (let offset = 0; offset < repeated.length; offset += 257) {
+ protection.onEvent(textDelta(repeated.slice(offset, offset + 257)));
+ }
+
+ await vi.waitFor(() => expect(abort).toHaveBeenCalledOnce());
+ expect(onDetected).toHaveBeenCalledOnce();
+ expect(logger.warn).toHaveBeenCalledWith(
+ 'pi output degeneration guard triggered',
+ expect.objectContaining({
+ reason: 'low-entropy-repetition',
+ observedCharacters: expect.any(Number),
+ structuredToolCall: false,
+ }),
+ );
+ expect(JSON.stringify((logger.warn as ReturnType<typeof vi.fn>).mock.calls)).not.toContain(
+ 'let me write the file now',
+ );
+ });
+
+ it('does not inspect a message after Pi reports a structured tool call', () => {
+ const abort = vi.fn().mockResolvedValue({ success: true });
+ const protection = new PiOutputDegenerationProtection({
+ logger: loggerWithSpies(),
+ isEnabled: () => true,
+ abort,
+ onDetected: vi.fn(),
+ guardOptions: {
+ minimumCharacters: 1_024,
+ analysisWindowCharacters: 1_024,
+ checkIntervalCharacters: 256,
+ requiredConfirmations: 1,
+ },
+ });
+
+ protection.onEvent(ev({ type: 'message_start' }));
+ protection.onEvent(ev({
+ type: 'message_update',
+ assistantMessageEvent: { type: 'toolcall_start', contentIndex: 0 },
+ }));
+ protection.onEvent(textDelta('repeat this forever; '.repeat(500)));
+
+ expect(abort).not.toHaveBeenCalled();
+ });
+
+ it('keeps one abort per turn and re-arms at the next agent boundary', async () => {
+ const abort = vi.fn().mockResolvedValue({ success: true });
+ const protection = new PiOutputDegenerationProtection({
+ logger: loggerWithSpies(),
+ isEnabled: () => true,
+ abort,
+ onDetected: vi.fn(),
+ guardOptions: {
+ minimumCharacters: 1_024,
+ analysisWindowCharacters: 1_024,
+ checkIntervalCharacters: 256,
+ requiredConfirmations: 1,
+ },
+ });
+
+ protection.onEvent(ev({ type: 'agent_start' }));
+ protection.onEvent(ev({ type: 'message_start' }));
+ protection.onEvent(textDelta('repeat this forever; '.repeat(500)));
+ await vi.waitFor(() => expect(abort).toHaveBeenCalledOnce());
+
+ // 同一 turn 即使 Pi 又开了一条 assistant message,也不能重复请求 abort。
+ protection.onEvent(ev({ type: 'message_start' }));
+ protection.onEvent(textDelta('repeat this forever; '.repeat(500)));
+ expect(abort).toHaveBeenCalledOnce();
+
+ protection.onEvent(ev({ type: 'agent_settled' }));
+ protection.onEvent(ev({ type: 'agent_start' }));
+ protection.onEvent(ev({ type: 'message_start' }));
+ protection.onEvent(textDelta('repeat this forever; '.repeat(500)));
+ await vi.waitFor(() => expect(abort).toHaveBeenCalledTimes(2));
+ });
+
+ it('keeps the terminal diagnosis latched when the abort RPC fails', async () => {
+ const abort = vi.fn().mockRejectedValue(new Error('transport unavailable'));
+ const onDetected = vi.fn();
+ const logger = loggerWithSpies();
+ const protection = new PiOutputDegenerationProtection({
+ logger,
+ isEnabled: () => true,
+ abort,
+ onDetected,
+ guardOptions: {
+ minimumCharacters: 1_024,
+ analysisWindowCharacters: 1_024,
+ checkIntervalCharacters: 256,
+ requiredConfirmations: 1,
+ },
+ });
+
+ protection.onEvent(ev({ type: 'agent_start' }));
+ protection.onEvent(ev({ type: 'message_start' }));
+ protection.onEvent(textDelta('repeat this forever; '.repeat(500)));
+ await vi.waitFor(() => expect(logger.warn).toHaveBeenCalledWith(
+ 'pi output degeneration abort failed',
+ expect.objectContaining({ message: 'transport unavailable' }),
+ ));
+
+ protection.onEvent(ev({ type: 'message_start' }));
+ protection.onEvent(textDelta('repeat this forever; '.repeat(500)));
+ expect(abort).toHaveBeenCalledOnce();
+ expect(onDetected).toHaveBeenCalledOnce();
+ });
+
+ it('keeps the first-stage rollout scoped to the DeepSeek model family', () => {
+ expect(shouldProtectPiOutput('DeepSeek-V4-Flash-0731')).toBe(true);
+ expect(shouldProtectPiOutput('deepseek/deepseek-v4-pro')).toBe(true);
+ expect(shouldProtectPiOutput('xai/grok-4.5')).toBe(false);
+ expect(shouldProtectPiOutput('claude-sonnet-4-6')).toBe(false);
+ });
+});
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
index cfac7aa87d..7faf8b376f 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
@@ -382,6 +382,138 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
await handle.close();
});
+ it('aborts one DeepSeek response after the bounded low-entropy guard confirms degeneration', async () => {
+ const deepSeekModel = 'DeepSeek-V4-Flash-0731';
+ const handle = await new PiAgent(buildDeps({
+ capabilityAdditions: {
+ availableModels: [{
+ id: deepSeekModel,
+ displayName: deepSeekModel,
+ contextWindow: 200_000,
+ efforts: [],
+ defaultEffort: null,
+ }],
+ },
+ })).startSession({ ...opts(), model: deepSeekModel });
+ const iterator = handle.events()[Symbol.asyncIterator]();
+ knobs.requests = [];
+
+ knobs.onEvent?.({ type: 'agent_start' });
+ knobs.onEvent?.({ type: 'message_start' });
+ const repeated = 'let me write the file now; 现在执行;落地。'.repeat(1_100);
+ knobs.onEvent?.({
+ type: 'message_update',
+ assistantMessageEvent: {
+ type: 'text_delta',
+ contentIndex: 0,
+ delta: repeated.slice(0, 16_384),
+ },
+ });
+ knobs.onEvent?.({
+ type: 'message_update',
+ assistantMessageEvent: {
+ type: 'text_delta',
+ contentIndex: 0,
+ delta: repeated.slice(16_384, 20_480),
+ },
+ });
+ knobs.onEvent?.({
+ type: 'message_update',
+ assistantMessageEvent: {
+ type: 'text_delta',
+ contentIndex: 0,
+ delta: repeated.slice(20_480),
+ },
+ });
+
+ await vi.waitFor(() => expect(knobs.requests.filter((type) => type === 'abort')).toHaveLength(1));
+ knobs.onEvent?.({
+ type: 'message_end',
+ message: {
+ role: 'assistant',
+ content: [{ type: 'text', text: repeated.slice(0, 20_480) }],
+ model: deepSeekModel,
+ stopReason: 'aborted',
+ usage: { output: 8_000 },
+ },
+ });
+ knobs.onEvent?.({ type: 'agent_settled' });
+
+ const events = [];
+ for (let index = 0; index < 10; index += 1) {
+ const next = await iterator.next();
+ if (next.done) break;
+ events.push(next.value);
+ if (
+ next.value.type === 'status'
+ && (next.value.data as { isRunning?: unknown }).isRunning === false
+ ) {
+ break;
+ }
+ }
+ expect(events).toContainEqual(expect.objectContaining({
+ type: 'error',
+ source: 'pi',
+ data: expect.objectContaining({
+ reason: 'output-degeneration',
+ isTerminal: true,
+ }),
+ }));
+ expect(events).toContainEqual(expect.objectContaining({ type: 'done', source: 'pi' }));
+
+ await handle.close();
+ });
+
+ it('allows an explicitly requested repetitive Pi turn without weakening the next turn', async () => {
+ const deepSeekModel = 'DeepSeek-V4-Flash-0731';
+ const handle = await new PiAgent(buildDeps({
+ capabilityAdditions: {
+ availableModels: [{
+ id: deepSeekModel,
+ displayName: deepSeekModel,
+ contextWindow: 200_000,
+ efforts: [],
+ defaultEffort: null,
+ }],
+ },
+ })).startSession({ ...opts(), model: deepSeekModel });
+ const repeated = 'intentional repeated fixture; '.repeat(1_100);
+
+ await handle.send({
+ type: 'user',
+ content: '/allow-repetitive-output\nRepeat the fixture exactly as requested.',
+ });
+ knobs.requests = [];
+ knobs.onEvent?.({ type: 'agent_start' });
+ knobs.onEvent?.({ type: 'message_start' });
+ knobs.onEvent?.({
+ type: 'message_update',
+ assistantMessageEvent: { type: 'text_delta', contentIndex: 0, delta: repeated },
+ });
+ expect(knobs.requests).not.toContain('abort');
+ knobs.onEvent?.({ type: 'agent_settled' });
+
+ await handle.send({ type: 'user', content: 'Normal protected turn.' });
+ knobs.requests = [];
+ knobs.onEvent?.({ type: 'agent_start' });
+ knobs.onEvent?.({ type: 'message_start' });
+ knobs.onEvent?.({
+ type: 'message_update',
+ assistantMessageEvent: { type: 'text_delta', contentIndex: 0, delta: repeated },
+ });
+ knobs.onEvent?.({
+ type: 'message_update',
+ assistantMessageEvent: {
+ type: 'text_delta',
+ contentIndex: 0,
+ delta: 'intentional repeated fixture; '.repeat(100),
+ },
+ });
+ await vi.waitFor(() => expect(knobs.requests.filter((type) => type === 'abort')).toHaveLength(1));
+
+ await handle.close();
+ });
+
it('keeps local runtime files until a close retry confirms process exit', async () => {
knobs.closeFailuresRemaining = 1;
const handle = await new PiAgent(buildDeps()).startSession(opts());
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.ts
index 5cae18805e..f342c8462c 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
@@ -296,6 +296,53 @@ describe('pi translator', () => {
}));
});
+ it('preserves length-limited text but reports that the Pi response is incomplete', () => {
+ const ctx = createPiTranslateContext(noopLogger);
+ const { queue, events } = makeQueue();
+
+ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);
+ translatePiEvent(
+ ev({
+ type: 'message_end',
+ message: {
+ role: 'assistant',
+ content: [{ type: 'text', text: 'a long but incomplete answer' }],
+ model: 'DeepSeek-V4-Flash-0731',
+ stopReason: 'length',
+ usage: { input: 100, output: 16_000 },
+ },
+ }),
+ queue,
+ ctx,
+ );
+ translatePiEvent(ev({ type: 'agent_settled' }), queue, ctx);
+
+ expect(events.filter((event) => event.type === 'text')).toContainEqual(
+ expect.objectContaining({
+ data: expect.objectContaining({
+ text: 'a long but incomplete answer',
+ isFinal: true,
+ }),
+ }),
+ );
+ expect(events.filter((event) => event.type === 'error')).toEqual([
+ expect.objectContaining({
+ source: 'pi',
+ data: expect.objectContaining({
+ reason: 'output-limit',
+ isTerminal: true,
+ }),
+ }),
+ ]);
+ expect((events.find((event) => event.type === 'done')?.data as {
+ result?: unknown;
+ usage?: { outputTokens?: unknown };
+ })).toMatchObject({
+ result: 'a long but incomplete answer',
+ usage: { outputTokens: 16_000 },
+ });
+ });
+
it('drops a pending provider error when Pi auto-retry succeeds', () => {
const ctx = createPiTranslateContext(noopLogger);
const { queue, events } = makeQueue();
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index db4e852c83..972113a091 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -139,10 +139,16 @@ import {
createPiTranslateContext,
disposePiTranslateContext,
isFailedOrAbortedPiCompaction,
+ markPiOutputDegeneration,
translatePiEvent,
usageSnapshotOf,
type PiTranslateContext,
} from './translator.js';
+import {
+ consumePiOutputDegenerationDirective,
+ PiOutputDegenerationProtection,
+ shouldProtectPiOutput,
+} from './output-degeneration-protection.js';
import {
activePiHistoryFromTree,
findPiTreeEntry,
@@ -2164,6 +2170,10 @@ export class PiAgent extends BaseAgent {
// follow-up send)同口径。清空只认 turn 终态,由 send 预检覆盖为最新值。
let activeTurnPermissionPolicy: TurnPermissionPolicy | null = null;
let mutableModel = opts.model;
+ // 用户显式放行只对下一条 Pi agent turn 生效。pending 与 active 分开,避免 streaming
+ // 中排队 followUp 时提前改变当前 turn 的保护状态。
+ let pendingOutputDegenerationBypass: boolean | null = null;
+ let activeOutputDegenerationBypass = false;
let mutableWireModel = initialWireModel;
// Pi RPC 实际选中的 provider。与用于宿主鉴权/审阅元数据的 mutableProviderId 分开:
// null/订阅来源会归一到 cindy,setModel 未显式传来源时也必须跟随本次解析结果。
@@ -2265,6 +2275,14 @@ export class PiAgent extends BaseAgent {
// preparePiExtraSpawnConfig 注册、但 handle 尚未交出,close() 不会跑 → 单独
// 兜底注销 ctx 再抛(构造失败没有 proc 可关)。catch 必抛,故其后 proc 恒已赋值。
let proc: PiRpcProcess;
+ const outputDegenerationProtection = new PiOutputDegenerationProtection({
+ logger: this.deps.logger.child('output-degeneration'),
+ // 读取 mutableModel 而不是启动快照:会话内 setModel 后下一条消息立即按新模型生效。
+ isEnabled: () =>
+ shouldProtectPiOutput(mutableModel) && !activeOutputDegenerationBypass,
+ abort: () => proc.request({ type: 'abort' }),
+ onDetected: () => markPiOutputDegeneration(ctx),
+ });
const getAutoCompactThresholdPct = (): number | undefined =>
this.deps.runtimeConfig.autoCompactThresholdPct;
const autoCompactController =
@@ -2517,6 +2535,11 @@ export class PiAgent extends BaseAgent {
transport,
logger: this.deps.logger,
onEvent: (event: PiRpcEvent) => {
+ if (event.type === 'agent_start') {
+ activeOutputDegenerationBypass = pendingOutputDegenerationBypass ?? false;
+ pendingOutputDegenerationBypass = null;
+ }
+ outputDegenerationProtection.onEvent(event);
if (event.type === 'agent_start' || event.type === 'agent_settled') {
piAgentLifecycleSequence += 1;
}
@@ -3560,6 +3583,8 @@ export class PiAgent extends BaseAgent {
await assertReviewMessageContentPaths(message.content, opts.workingDir, reviewReadGrants);
}
let { text, images } = await buildPiPrompt(message, { remote });
+ const outputDegenerationDirective = consumePiOutputDegenerationDirective(text);
+ text = outputDegenerationDirective.prompt;
rejectIfCancelled(sendOpts, 'send');
assertImageInputSupported(images);
setAutoReviewIntent(message.content);
@@ -3596,6 +3621,8 @@ export class PiAgent extends BaseAgent {
? await readPiUserEntryIds()
: null;
if (!managedPackageRoute.accepted) rejectIfCancelled(sendOpts, 'send');
+ const previousPendingOutputDegenerationBypass = pendingOutputDegenerationBypass;
+ pendingOutputDegenerationBypass = outputDegenerationDirective.allowRepetitiveOutput;
promptRequestStarted = true;
try {
const resp = await runExclusivePiRpc(() => proc.request(command, {
@@ -3732,6 +3759,9 @@ export class PiAgent extends BaseAgent {
if (activeExtensionCommandNotifications === capturedExtensionNotifications) {
activeExtensionCommandNotifications = null;
}
+ if (!providerAccepted) {
+ pendingOutputDegenerationBypass = previousPendingOutputDegenerationBypass;
+ }
}
} catch (err) {
// 只在 Provider 尚未接受本轮时回滚。接受后的 transcript 回调失败不代表
diff --git a/packages/maker-core/src/agents/pi/output-degeneration-protection.ts b/packages/maker-core/src/agents/pi/output-degeneration-protection.ts
new file mode 100644
index 0000000000..ab3a11ba79
--- /dev/null
+++ b/packages/maker-core/src/agents/pi/output-degeneration-protection.ts
@@ -0,0 +1,157 @@
+import type { Logger } from '../../interfaces/logger.js';
+import {
+ OutputDegenerationGuard,
+ type OutputDegenerationGuardOptions,
+ type OutputDegenerationVerdict,
+} from '../shared/output-degeneration-guard.js';
+import type { PiRpcEvent } from './rpc-client.js';
+
+export const PI_ALLOW_REPETITIVE_OUTPUT_DIRECTIVE = '/allow-repetitive-output';
+
+interface PiAbortResponse {
+ success: boolean;
+ error?: unknown;
+}
+
+export interface PiOutputDegenerationProtectionOptions {
+ logger: Logger;
+ /** 动态读取当前模型,模型切换后不能沿用启动时快照。 */
+ isEnabled: () => boolean;
+ abort: () => Promise<PiAbortResponse>;
+ /** 同步登记终态原因,避免 abort ACK 与 agent_settled 竞态丢失诊断。 */
+ onDetected: (verdict: Extract<OutputDegenerationVerdict, { kind: 'hard' }>) => void;
+ guardOptions?: OutputDegenerationGuardOptions;
+}
+
+export interface PiOutputDegenerationDirective {
+ prompt: string;
+ allowRepetitiveOutput: boolean;
+}
+
+/**
+ * 显式、按 turn 放行的用户入口。只认开头的完整指令 token,不猜测自然语言意图;
+ * 指令本身不会发送给模型,避免它污染正文或被 Pi 当作扩展命令执行。
+ */
+export function consumePiOutputDegenerationDirective(
+ prompt: string,
+): PiOutputDegenerationDirective {
+ const trimmed = prompt.trimStart();
+ if (
+ !trimmed.startsWith(PI_ALLOW_REPETITIVE_OUTPUT_DIRECTIVE)
+ || !isDirectiveBoundary(trimmed[PI_ALLOW_REPETITIVE_OUTPUT_DIRECTIVE.length])
+ ) {
+ return { prompt, allowRepetitiveOutput: false };
+ }
+
+ return {
+ prompt: trimmed.slice(PI_ALLOW_REPETITIVE_OUTPUT_DIRECTIVE.length).trimStart(),
+ allowRepetitiveOutput: true,
+ };
+}
+
+/**
+ * Pi 事件层的低熵输出保险丝。
+ *
+ * 只消费当前 assistant message 的可见 text_delta。发现结构化 tool call 后禁用本消息的
+ * 文本判定;命中时只发一次 Pi 原生 abort,不自动重放用户请求。正文与指标判定由纯 guard
+ * 负责,这里只拥有 Pi RPC 生命周期和幂等中断。
+ */
+export class PiOutputDegenerationProtection {
+ private readonly guard: OutputDegenerationGuard;
+ private readonly logger: Logger;
+ private readonly isEnabled: () => boolean;
+ private readonly abort: () => Promise<PiAbortResponse>;
+ private readonly onDetected: PiOutputDegenerationProtectionOptions['onDetected'];
+ private messageHasStructuredToolCall = false;
+ private turnAbortRequested = false;
+
+ constructor(options: PiOutputDegenerationProtectionOptions) {
+ this.guard = new OutputDegenerationGuard(options.guardOptions);
+ this.logger = options.logger;
+ this.isEnabled = options.isEnabled;
+ this.abort = options.abort;
+ this.onDetected = options.onDetected;
+ }
+
+ onEvent(event: PiRpcEvent): void {
+ if (event.type === 'agent_start' || event.type === 'agent_settled') {
+ this.turnAbortRequested = false;
+ this.resetMessage();
+ return;
+ }
+ if (event.type === 'message_start') {
+ this.resetMessage();
+ return;
+ }
+ if (event.type === 'tool_execution_start') {
+ this.messageHasStructuredToolCall = true;
+ return;
+ }
+ if (event.type !== 'message_update') return;
+
+ const delta = event.assistantMessageEvent as Record<string, unknown> | undefined;
+ if (!delta || typeof delta.type !== 'string') return;
+ if (delta.type.startsWith('toolcall_')) {
+ this.messageHasStructuredToolCall = true;
+ return;
+ }
+ if (
+ delta.type !== 'text_delta'
+ || typeof delta.delta !== 'string'
+ || this.messageHasStructuredToolCall
+ || this.turnAbortRequested
+ || !this.isEnabled()
+ ) {
+ return;
+ }
+
+ const verdict = this.guard.onTextDelta(delta.delta);
+ if (verdict.kind !== 'hard') return;
+ this.turnAbortRequested = true;
+ this.onDetected(verdict);
+ this.logger.warn('pi output degeneration guard triggered', {
+ reason: verdict.reason,
+ observedCharacters: verdict.observedCharacters,
+ analysisWindowCharacters: verdict.analysisWindowCharacters,
+ uniqueNgramRatio: verdict.uniqueNgramRatio,
+ halfSimilarity: verdict.halfSimilarity,
+ confirmations: verdict.confirmations,
+ structuredToolCall: false,
+ });
+ void this.abort().then(
+ (response) => {
+ if (response.success) {
+ this.logger.info('pi output degeneration abort accepted', {
+ reason: verdict.reason,
+ observedCharacters: verdict.observedCharacters,
+ });
+ return;
+ }
+ this.logger.warn('pi output degeneration abort rejected', {
+ reason: verdict.reason,
+ message: typeof response.error === 'string' ? response.error : 'unknown',
+ });
+ },
+ (error: unknown) => {
+ this.logger.warn('pi output degeneration abort failed', {
+ reason: verdict.reason,
+ message: error instanceof Error ? error.message : String(error),
+ });
+ },
+ );
+ }
+
+ private resetMessage(): void {
+ this.guard.resetMessage();
+ this.messageHasStructuredToolCall = false;
+ }
+}
+
+/** 首阶段只覆盖 Issue 证实的 Pi + DeepSeek 模型族,不按自定义 provider 名称写死。 */
+export function shouldProtectPiOutput(model: string): boolean {
+ return model.toLowerCase().includes('deepseek');
+}
+
+function isDirectiveBoundary(character: string | undefined): boolean {
+ return character === undefined || /\s/u.test(character);
+}
diff --git a/packages/maker-core/src/agents/pi/translator.ts b/packages/maker-core/src/agents/pi/translator.ts
index 492da18cbf..cd443c68be 100644
--- a/packages/maker-core/src/agents/pi/translator.ts
+++ b/packages/maker-core/src/agents/pi/translator.ts
@@ -60,6 +60,7 @@ interface PiAssistantMessage {
interface PiPendingAssistantError {
message: string;
sdkError: string;
+ reason?: string;
errorStatus?: 401 | 429 | 529;
usageLimit?: true;
}
@@ -108,6 +109,11 @@ export interface PiTranslateContext {
* 暂存到 agent_settled 再终态上报,避免一次可恢复错误提前收口整个 turn。
*/
pendingAssistantError: PiPendingAssistantError | null;
+ /**
+ * Cindy 自己确认的 turn 级安全收口。与 provider retry 错误分开保存:后续普通
+ * message_end 可以证明 provider retry 已恢复,却不能抹掉已经触发的本地止损。
+ */
+ pendingSafetyError: PiPendingAssistantError | null;
/** 整轮 wall-clock 起点;只用于诊断,不参与 TPS。 */
turnWallClockStartedAt: number;
generationDurationMs: number;
@@ -158,6 +164,7 @@ export function createPiTranslateContext(logger: Logger): PiTranslateContext {
delegatedUsage: new Map(),
subagentToolCalls: new Map(),
pendingAssistantError: null,
+ pendingSafetyError: null,
hostAutoCompactInFlight: false,
};
}
@@ -176,6 +183,7 @@ export function disposePiTranslateContext(ctx: PiTranslateContext): void {
stopPiGenerationHeartbeat(ctx);
ctx.isStreaming = false;
ctx.pendingAssistantError = null;
+ ctx.pendingSafetyError = null;
ctx.subagentToolCalls.clear();
}
@@ -208,6 +216,15 @@ export function usageSnapshotOf(ctx: PiTranslateContext): UsageSnapshot {
};
}
+/** 由 Pi 事件层在高置信低熵保护命中时登记,终态统一等 agent_settled 发出。 */
+export function markPiOutputDegeneration(ctx: PiTranslateContext): void {
+ ctx.pendingSafetyError ??= {
+ message: 'Pi stopped this response after detecting highly repetitive output with almost no new information. If the repetition is intentional, resend the request starting with /allow-repetitive-output.',
+ sdkError: 'Pi output degeneration guard stopped the current response',
+ reason: 'output-degeneration',
+ };
+}
+
function pushStatus(
queue: AsyncQueue<AgentEvent>,
ctx: PiTranslateContext,
@@ -378,6 +395,7 @@ export function translatePiEvent(
ctx.turnCacheWrite = 0;
ctx.finalAssistantText = '';
ctx.pendingAssistantError = null;
+ ctx.pendingSafetyError = null;
ctx.turnWallClockStartedAt = Date.now();
ctx.generationDurationMs = 0;
ctx.generationTimingReliable = true;
@@ -442,6 +460,13 @@ export function translatePiEvent(
// A normal assistant message proves an earlier provider failure recovered.
ctx.pendingAssistantError = null;
}
+ if (message.stopReason === 'length' && ctx.pendingSafetyError === null) {
+ ctx.pendingSafetyError = {
+ message: 'Pi reached the model output limit. The response may be incomplete.',
+ sdkError: 'Pi response stopped at the model output limit',
+ reason: 'output-limit',
+ };
+ }
if (message.stopReason !== 'error' && fullText.length > 0) {
// 覆盖为本 turn 最新一条有文本的 assistant 回复,agent_settled 作 done.result 上报。
ctx.finalAssistantText = fullText;
@@ -578,11 +603,14 @@ export function translatePiEvent(
stopPiGenerationHeartbeat(ctx);
const pendingAssistantError = ctx.pendingAssistantError;
ctx.pendingAssistantError = null;
- if (pendingAssistantError) {
+ const pendingSafetyError = ctx.pendingSafetyError;
+ ctx.pendingSafetyError = null;
+ const terminalError = pendingSafetyError ?? pendingAssistantError;
+ if (terminalError) {
queue.push({
type: 'error',
data: {
- ...pendingAssistantError,
+ ...terminalError,
isTerminal: true,
},
source: 'pi',
diff --git a/packages/maker-core/src/agents/shared/output-degeneration-guard.test.ts b/packages/maker-core/src/agents/shared/output-degeneration-guard.test.ts
new file mode 100644
index 0000000000..09de93f543
--- /dev/null
+++ b/packages/maker-core/src/agents/shared/output-degeneration-guard.test.ts
@@ -0,0 +1,115 @@
+import { describe, expect, it } from 'vitest';
+
+import { OutputDegenerationGuard } from './output-degeneration-guard.js';
+
+function feedInUnevenDeltas(guard: OutputDegenerationGuard, text: string): ReturnType<OutputDegenerationGuard['onTextDelta']> {
+ const sizes = [1, 7, 31, 3, 127, 19, 509];
+ let offset = 0;
+ let verdict: ReturnType<OutputDegenerationGuard['onTextDelta']> = { kind: 'ok' };
+ for (let index = 0; offset < text.length; index += 1) {
+ const next = Math.min(text.length, offset + sizes[index % sizes.length]!);
+ verdict = guard.onTextDelta(text.slice(offset, next));
+ offset = next;
+ if (verdict.kind === 'hard') return verdict;
+ }
+ return verdict;
+}
+
+describe('OutputDegenerationGuard', () => {
+ it('detects the Issue #2866 low-entropy loop across arbitrary delta boundaries', () => {
+ const guard = new OutputDegenerationGuard();
+ guard.resetMessage();
+
+ const verdict = feedInUnevenDeltas(
+ guard,
+ 'let me write the file now; 现在执行;落地。'.repeat(1_100),
+ );
+
+ expect(verdict).toMatchObject({
+ kind: 'hard',
+ reason: 'low-entropy-repetition',
+ });
+ if (verdict.kind === 'hard') {
+ expect(verdict.observedCharacters).toBeGreaterThanOrEqual(16_384);
+ expect(verdict.uniqueNgramRatio).toBeLessThanOrEqual(0.08);
+ expect(verdict.halfSimilarity).toBeGreaterThanOrEqual(0.92);
+ }
+ });
+
+ it.each([
+ [
+ 'long prose',
+ Array.from(
+ { length: 700 },
+ (_, index) =>
+ `Section ${index}: component-${index} accepts request-${index * 17}, validates invariant-${index % 29}, and returns result-${index * 31}.`,
+ ).join('\n'),
+ ],
+ [
+ 'source code',
+ Array.from(
+ { length: 650 },
+ (_, index) =>
+ `export function transform${index}(value: number): number { return value * ${index + 3} + ${index * 11}; }`,
+ ).join('\n'),
+ ],
+ [
+ 'structured logs',
+ Array.from(
+ { length: 900 },
+ (_, index) =>
+ `2026-08-20T10:${String(index % 60).padStart(2, '0')}:${String((index * 7) % 60).padStart(2, '0')}Z request=req-${index.toString(36)} latency=${17 + index}ms checksum=${(index * 2654435761 >>> 0).toString(16)}`,
+ ).join('\n'),
+ ],
+ [
+ 'json data',
+ JSON.stringify(
+ Array.from({ length: 1_000 }, (_, index) => ({
+ id: `record-${index}`,
+ score: index * 13,
+ label: `category-${index % 47}`,
+ digest: (index * 2246822519 >>> 0).toString(36),
+ })),
+ ),
+ ],
+ [
+ 'repeated-format list',
+ Array.from(
+ { length: 1_000 },
+ (_, index) =>
+ `- Item ${index}: source-${index.toString(36)} -> target-${(index * 97).toString(36)}; checksum=${(index * 3266489917 >>> 0).toString(16)}`,
+ ).join('\n'),
+ ],
+ [
+ 'multilingual prose',
+ Array.from(
+ { length: 700 },
+ (_, index) =>
+ `第 ${index} 节记录组件 ${index % 53} 的结果 ${index * 19};English sample ${index.toString(36)} explains branch ${index * 23}; 日本語項目 ${index * 29};한국어 값 ${index * 31}.`,
+ ).join('\n'),
+ ],
+ ])('does not treat %s as degeneration merely because it is long', (_name, text) => {
+ expect(text.length).toBeGreaterThan(16_384);
+ const guard = new OutputDegenerationGuard();
+ guard.resetMessage();
+
+ expect(feedInUnevenDeltas(guard, text)).toEqual({ kind: 'ok' });
+ });
+
+ it('requires repeated confirmations and resets evidence for each assistant message', () => {
+ const guard = new OutputDegenerationGuard({
+ minimumCharacters: 4_096,
+ analysisWindowCharacters: 4_096,
+ checkIntervalCharacters: 1_024,
+ requiredConfirmations: 2,
+ });
+ const repeated = 'prepare then execute; '.repeat(400);
+
+ guard.resetMessage();
+ expect(guard.onTextDelta(repeated.slice(0, 4_096))).toEqual({ kind: 'ok' });
+
+ guard.resetMessage();
+ expect(guard.onTextDelta(repeated.slice(0, 4_096))).toEqual({ kind: 'ok' });
+ expect(guard.onTextDelta(repeated.slice(4_096))).toMatchObject({ kind: 'hard' });
+ });
+});
diff --git a/packages/maker-core/src/agents/shared/output-degeneration-guard.ts b/packages/maker-core/src/agents/shared/output-degeneration-guard.ts
new file mode 100644
index 0000000000..48260547c4
--- /dev/null
+++ b/packages/maker-core/src/agents/shared/output-degeneration-guard.ts
@@ -0,0 +1,197 @@
+/**
+ * 流式正文退化检测器。
+ *
+ * 长度本身不是异常。只有一个足够长的滑动窗口同时满足“字符 n-gram 多样性很低”与
+ * “前后半窗高度相似”,并在相隔的检查点重复确认,才判定为低熵重复。检测器只保存
+ * 有界正文窗口,不做 IO、不匹配语言或意图关键词;调用方负责决定启用范围与中断方式。
+ */
+
+const DEFAULT_MINIMUM_CHARACTERS = 16_384;
+const DEFAULT_ANALYSIS_WINDOW_CHARACTERS = 8_192;
+const DEFAULT_CHECK_INTERVAL_CHARACTERS = 2_048;
+const DEFAULT_NGRAM_SIZE = 5;
+const DEFAULT_MAX_UNIQUE_NGRAM_RATIO = 0.08;
+const DEFAULT_MIN_HALF_SIMILARITY = 0.92;
+const DEFAULT_REQUIRED_CONFIRMATIONS = 2;
+
+export interface OutputDegenerationGuardOptions {
+ /** 开始检查前,当前 assistant message 至少需要输出多少个归一化字符。 */
+ minimumCharacters?: number;
+ /** 每次判定只观察末尾多少个归一化字符。 */
+ analysisWindowCharacters?: number;
+ /** 两次高置信确认之间至少相隔多少个归一化字符。 */
+ checkIntervalCharacters?: number;
+ /** 字符 n-gram 大小;字符级统计同时覆盖中文、英文和代码。 */
+ ngramSize?: number;
+ /** 窗口内 unique n-gram / 总 n-gram 的最大比例。 */
+ maxUniqueNgramRatio?: number;
+ /** 前后半窗 n-gram 集合的最小 Jaccard 相似度。 */
+ minHalfSimilarity?: number;
+ /** 连续多少个检查点命中后才返回 hard。 */
+ requiredConfirmations?: number;
+}
+
+export type OutputDegenerationVerdict =
+ | { kind: 'ok' }
+ | {
+ kind: 'hard';
+ reason: 'low-entropy-repetition';
+ observedCharacters: number;
+ analysisWindowCharacters: number;
+ uniqueNgramRatio: number;
+ halfSimilarity: number;
+ confirmations: number;
+ };
+
+interface OutputDegenerationMetrics {
+ uniqueNgramRatio: number;
+ halfSimilarity: number;
+}
+
+export class OutputDegenerationGuard {
+ readonly minimumCharacters: number;
+ readonly analysisWindowCharacters: number;
+ readonly checkIntervalCharacters: number;
+ readonly ngramSize: number;
+ readonly maxUniqueNgramRatio: number;
+ readonly minHalfSimilarity: number;
+ readonly requiredConfirmations: number;
+
+ private chunks: string[] = [];
+ private observedCharacters = 0;
+ private nextCheckAt: number;
+ private consecutiveConfirmations = 0;
+ private lastNormalizedCharacterWasWhitespace = false;
+ private triggered = false;
+
+ constructor(options: OutputDegenerationGuardOptions = {}) {
+ this.minimumCharacters = positiveInteger(
+ options.minimumCharacters,
+ DEFAULT_MINIMUM_CHARACTERS,
+ );
+ this.analysisWindowCharacters = positiveInteger(
+ options.analysisWindowCharacters,
+ DEFAULT_ANALYSIS_WINDOW_CHARACTERS,
+ );
+ this.checkIntervalCharacters = positiveInteger(
+ options.checkIntervalCharacters,
+ DEFAULT_CHECK_INTERVAL_CHARACTERS,
+ );
+ this.ngramSize = positiveInteger(options.ngramSize, DEFAULT_NGRAM_SIZE);
+ this.maxUniqueNgramRatio = boundedRatio(
+ options.maxUniqueNgramRatio,
+ DEFAULT_MAX_UNIQUE_NGRAM_RATIO,
+ );
+ this.minHalfSimilarity = boundedRatio(
+ options.minHalfSimilarity,
+ DEFAULT_MIN_HALF_SIMILARITY,
+ );
+ this.requiredConfirmations = positiveInteger(
+ options.requiredConfirmations,
+ DEFAULT_REQUIRED_CONFIRMATIONS,
+ );
+ this.nextCheckAt = this.minimumCharacters;
+ }
+
+ /** 每条 assistant message 的 start 边界调用,禁止跨消息累计。 */
+ resetMessage(): void {
+ this.chunks = [];
+ this.observedCharacters = 0;
+ this.nextCheckAt = this.minimumCharacters;
+ this.consecutiveConfirmations = 0;
+ this.lastNormalizedCharacterWasWhitespace = false;
+ this.triggered = false;
+ }
+
+ onTextDelta(delta: string): OutputDegenerationVerdict {
+ if (this.triggered || delta.length === 0) return { kind: 'ok' };
+
+ const normalized = this.normalizeDelta(delta);
+ if (normalized.length === 0) return { kind: 'ok' };
+ this.chunks.push(normalized);
+ this.observedCharacters += normalized.length;
+
+ if (this.observedCharacters < this.nextCheckAt) return { kind: 'ok' };
+ this.nextCheckAt = this.observedCharacters + this.checkIntervalCharacters;
+
+ const window = this.compactWindow();
+ if (window.length < this.analysisWindowCharacters) return { kind: 'ok' };
+ const metrics = outputDegenerationMetrics(window, this.ngramSize);
+ const suspicious =
+ metrics.uniqueNgramRatio <= this.maxUniqueNgramRatio
+ && metrics.halfSimilarity >= this.minHalfSimilarity;
+ if (!suspicious) {
+ this.consecutiveConfirmations = 0;
+ return { kind: 'ok' };
+ }
+
+ this.consecutiveConfirmations += 1;
+ if (this.consecutiveConfirmations < this.requiredConfirmations) return { kind: 'ok' };
+
+ this.triggered = true;
+ return {
+ kind: 'hard',
+ reason: 'low-entropy-repetition',
+ observedCharacters: this.observedCharacters,
+ analysisWindowCharacters: window.length,
+ uniqueNgramRatio: metrics.uniqueNgramRatio,
+ halfSimilarity: metrics.halfSimilarity,
+ confirmations: this.consecutiveConfirmations,
+ };
+ }
+
+ private normalizeDelta(delta: string): string {
+ let normalized = delta.toLowerCase().replace(/\s+/gu, ' ');
+ if (this.lastNormalizedCharacterWasWhitespace && normalized.startsWith(' ')) {
+ normalized = normalized.slice(1);
+ }
+ this.lastNormalizedCharacterWasWhitespace = /\s$/u.test(delta);
+ return normalized;
+ }
+
+ /** 仅在间隔检查点合并 chunk,避免每个 token delta 都复制整个滑动窗口。 */
+ private compactWindow(): string {
+ const joined = this.chunks.join('');
+ const window = joined.slice(-this.analysisWindowCharacters);
+ this.chunks = [window];
+ return window;
+ }
+}
+
+function outputDegenerationMetrics(text: string, ngramSize: number): OutputDegenerationMetrics {
+ const all = ngramsOf(text, ngramSize);
+ const totalNgrams = Math.max(1, text.length - ngramSize + 1);
+ const midpoint = Math.floor(text.length / 2);
+ const firstHalf = ngramsOf(text.slice(0, midpoint), ngramSize);
+ const secondHalf = ngramsOf(text.slice(midpoint), ngramSize);
+
+ let intersection = 0;
+ for (const gram of firstHalf) {
+ if (secondHalf.has(gram)) intersection += 1;
+ }
+ const union = firstHalf.size + secondHalf.size - intersection;
+ return {
+ uniqueNgramRatio: all.size / totalNgrams,
+ halfSimilarity: union === 0 ? 0 : intersection / union,
+ };
+}
+
+function ngramsOf(text: string, size: number): Set<string> {
+ const grams = new Set<string>();
+ for (let index = 0; index <= text.length - size; index += 1) {
+ grams.add(text.slice(index, index + size));
+ }
+ return grams;
+}
+
+function positiveInteger(value: number | undefined, fallback: number): number {
+ return typeof value === 'number' && Number.isSafeInteger(value) && value > 0
+ ? value
+ : fallback;
+}
+
+function boundedRatio(value: number | undefined, fallback: number): number {
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1
+ ? value
+ : fallback;
+}