Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
Merge remote-tracking branch 'upstream/main' into fix/issue-2866-pi-output-degeneration
ZJPex6661acf7fc4b
diff --cc apps/desktop/src/renderer/components/chat/errorReasonI18n.tsindex 94e081879e,8243276a40..608dba9bdf--- a/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts+++ b/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts@@@ -15,8 -17,7 +17,9 @@@ export const ERROR_REASON_I18N_KEYS: Re'empty-response': 'logic.errors.emptyResponse','turn-failed': 'logic.errors.turnFailed','silent-stop-exhausted': 'logic.errors.silentStopExhausted',+ 'output-degeneration': 'logic.errors.outputDegeneration',+ 'output-limit': 'logic.errors.outputLimit',+ tool_use_loop_detected: 'logic.errors.toolUseLoopDetected','permission-tighten-interrupt-failed': 'logic.errors.permissionTightenInterruptFailed','codex-auto-review-unavailable': 'logic.errors.codexAutoReviewUnavailable','host-shell-command-blocked': 'logic.errors.hostShellCommandBlocked',diff --cc packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.tsindex b2709fe5b1,fbd8cd16e0..3ef8d007fe--- 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@@@ -21,7 -21,8 +21,9 @@@ import { afterEach, beforeEach, describconst knobs = vi.hoisted(() => ({ctorThrows: false,getStateRejects: false,+ abortRejects: false,getStateGate: null as Promise<void> | null,++ promptGate: null as Promise<void> | null,closeRejects: false,closeFailuresRemaining: 0,closeGate: null as Promise<void> | null,@@@ -79,6 -82,9 +83,13 @@@ vi.mock('../rpc-client.js', () => (if (knobs.getStateRejects) throw new Error('get_state rejected (mock)');return { success: true, data: { sessionFile: '/mock/session.jsonl', model: { contextWindow: 200000 } } };}++ if (cmd.type === 'prompt') {++ const gate = knobs.promptGate;++ if (gate) await gate;++ }+ if (cmd.type === 'abort' && knobs.abortRejects) {+ return { success: false, error: 'abort rejected (mock)' };+ }// switch_session / set_thinking_level / set_auto_compaction / get_entries 等一律成功。return { success: true, data: { entries: [] } };}@@@ -119,7 -131,8 +136,9 @@@ describe('PiAgent.startSession failurebeforeEach(() => {knobs.ctorThrows = false;knobs.getStateRejects = false;+ knobs.abortRejects = false;knobs.getStateGate = null;++ knobs.promptGate = null;knobs.closeRejects = false;knobs.closeFailuresRemaining = 0;knobs.closeGate = null;@@@ -248,40 -280,50 +286,84 @@@model: 'm',});+ function emitConfirmedDegenerateOutput(): void {+ knobs.onEvent?.({ type: 'agent_start' });+ emitConfirmedDegenerateMessage();+ }++ function emitConfirmedDegenerateMessage(): void {+ 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),+ },+ });+ }++ /**+ * Owner ids are `<host pid>:<session-instance scope>`; the pid half is what+ * lets an agent-home-wide sweep tell this process's runs from a concurrent+ * instance's. Fixtures owned by "this handle" must use the same shape.+ */+ const ownerId = (scope = 'pi-instance-1') =>+ piSubagentRuns.piSubagentRuntimeOwnerId(process.pid, scope);++ function pendingSubagentRun(+ input: Record<string, unknown>,+ overrides: Partial<PiSubagentRunStatus> = {},+ method: 'confirm' | 'input' = 'confirm',+ ): PiSubagentRunStatus {+ const runId = '123e4567-e89b-42d3-a456-426614174096';+ return {+ version: 1,+ runId,+ taskId: 'tool-subagent-approval',+ parentSessionId: 's1',+ runtimeOwnerId: ownerId(),+ interactiveOwner: 'host',+ runnerInstanceId: 'runner-subagent-approval',+ state: 'running',+ startedAt: 1,+ updatedAt: 2,+ tasks: [{+ childId: `${runId}-1`,+ sessionId: `${runId}-1`,+ agent: 'worker',+ title: 'approval-fixture',+ status: 'running',+ pendingApproval: {+ id: 'approval-1',+ method,+ title: 'cindy:permission',+ ...(method === 'input'+ ? { placeholder: JSON.stringify(input) }+ : { message: JSON.stringify(input) }),+ },+ }],+ ...overrides,+ };+ }+it('disposes ctx (and does not close a nonexistent proc) when the process constructor throws synchronously', async () => {knobs.ctorThrows = true;const agent = new PiAgent(buildDeps());@@@ -416,276 -1889,67 +1929,389 @@@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),- },- });-++ emitConfirmedDegenerateOutput();+ 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' }));++ expect(events).toContainEqual(expect.objectContaining({++ type: 'done',++ source: 'pi',++ data: expect.objectContaining({ status: 'failed' }),++ }));++++ await handle.close();++ });++++ it('does not let a queued degeneration abort cross into the next Pi 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 });++ knobs.onEvent?.({ type: 'agent_start' });++++ let releasePrompt!: () => void;++ knobs.promptGate = new Promise<void>((resolve) => { releasePrompt = resolve; });++ const sending = handle.send({ type: 'user', content: 'Queue the next turn.' });++ await vi.waitFor(() => expect(knobs.requests.filter((type) => type === 'prompt')).toHaveLength(1));++++ knobs.requests = [];++ emitConfirmedDegenerateMessage();++ await Promise.resolve();++ expect(knobs.requests).not.toContain('abort');++++ // Pi may publish the next boundary while the previous RPC acknowledgement is late.++ // The queued session-global abort must then become a no-op rather than kill this turn.++ knobs.onEvent?.({ type: 'agent_settled' });++ knobs.onEvent?.({ type: 'agent_start' });++ releasePrompt();++ await sending;++ await Promise.resolve();++ expect(knobs.requests).not.toContain('abort');++++ await handle.close();++ });++++ it.each(['abort', 'graceful-stop'] as const)(++ 'clears queued output-degeneration bypasses on %s',++ async (stopMethod) => {++ 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 });++++ knobs.onEvent?.({ type: 'agent_start' });++ await handle.send({++ type: 'user',++ content: '/allow-repetitive-output\nQueue a bypassed follow-up.',++ });++ if (stopMethod === 'abort') {++ await handle.abort();++ } else {++ await handle.requestGracefulStop?.();++ }++ knobs.onEvent?.({ type: 'agent_settled' });++++ knobs.requests = [];++ knobs.onEvent?.({ type: 'agent_start' });++ emitConfirmedDegenerateMessage();++ await vi.waitFor(() => expect(knobs.requests.filter((type) => type === 'abort')).toHaveLength(1));++++ await handle.close();++ },++ );+++ it('does not surface an aborted gateway error when Host stop beats agent_start', async () => {+ const handle = await new PiAgent(buildDeps()).startSession(opts());+ const events: Array<{ type: string; data?: unknown }> = [];+ void (async () => {+ for await (const event of handle.events()) events.push(event);+ })();+ const rawError = 'OpenAI Responses stream ended before a terminal response event';++ await handle.send({ type: 'user', content: 'start a Pi turn' });+ await handle.abort();+ knobs.onEvent?.({ type: 'agent_start' });+ knobs.onEvent?.({+ type: 'message_end',+ message: {+ role: 'assistant',+ content: [],+ stopReason: 'aborted',+ errorMessage: rawError,+ },+ });+ knobs.onEvent?.({ type: 'agent_settled' });++ await vi.waitFor(() => expect(events.some((event) => event.type === 'done')).toBe(true));+ expect(events.filter((event) => event.type === 'error')).toHaveLength(0);await handle.close();});+ it('enables DeepSeek output protection from the resolved wire model', async () => {+ const publicModel = 'legacy-model';+ const providerId = 'native-alias';+ const handle = await new PiAgent(buildDeps({+ capabilityAdditions: {+ availableModels: [{+ id: publicModel,+ displayName: publicModel,+ contextWindow: 200_000,+ efforts: [],+ defaultEffort: null,+ }],+ },+ resolvePiNativeProviders: async () => ({+ providers: [{+ id: providerId,+ name: 'Native Alias',+ baseUrl: 'https://native.example.test/v1',+ api: 'openai-responses',+ modelIdAliases: { [publicModel]: 'deepseek-native' },+ models: [{ id: 'deepseek-native', wireId: 'deepseek/deepseek-v4-pro' }],+ }],+ env: {},+ }),+ })).startSession({ ...opts(), model: publicModel, providerId });+ knobs.requests = [];++ emitConfirmedDegenerateOutput();++ await vi.waitFor(() => expect(knobs.requests.filter((type) => type === 'abort')).toHaveLength(1));+ await handle.close();+ });++ it('does not enable DeepSeek output protection when the wire model is not DeepSeek', async () => {+ const publicModel = 'deepseek-public';+ const providerId = 'native-alias';+ const handle = await new PiAgent(buildDeps({+ capabilityAdditions: {+ availableModels: [{+ id: publicModel,+ displayName: publicModel,+ contextWindow: 200_000,+ efforts: [],+ defaultEffort: null,+ }],+ },+ resolvePiNativeProviders: async () => ({+ providers: [{+ id: providerId,+ name: 'Native Alias',+ baseUrl: 'https://native.example.test/v1',+ api: 'openai-responses',+ modelIdAliases: { [publicModel]: 'deepseek-native' },+ models: [{ id: 'deepseek-native', wireId: 'neutral/model-v1' }],+ }],+ env: {},+ }),+ })).startSession({ ...opts(), model: publicModel, providerId });+ knobs.requests = [];++ emitConfirmedDegenerateOutput();++ expect(knobs.requests.filter((type) => type === 'abort')).toHaveLength(0);+ 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 a bypassed follow-up ahead of a queued protected 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 });++ knobs.onEvent?.({ type: 'agent_start' });+ await handle.send({+ type: 'user',+ content: '/allow-repetitive-output\nRepeat the fixture exactly as requested.',+ });+ await handle.send({ type: 'user', content: 'Normal protected follow-up.' });+ knobs.onEvent?.({ type: 'agent_settled' });++ knobs.requests = [];+ knobs.onEvent?.({ type: 'agent_start' });+ emitConfirmedDegenerateMessage();+ expect(knobs.requests.filter((type) => type === 'abort')).toHaveLength(0);+ knobs.onEvent?.({ type: 'agent_settled' });++ knobs.requests = [];+ knobs.onEvent?.({ type: 'agent_start' });+ emitConfirmedDegenerateMessage();+ await vi.waitFor(() => expect(knobs.requests.filter((type) => type === 'abort')).toHaveLength(1));++ await handle.close();+ });++ it('keeps a protected follow-up ahead of a queued bypassed 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 });++ knobs.onEvent?.({ type: 'agent_start' });+ await handle.send({ type: 'user', content: 'Normal protected follow-up.' });+ await handle.send({+ type: 'user',+ content: '/allow-repetitive-output\nRepeat the fixture exactly as requested.',+ });+ knobs.onEvent?.({ type: 'agent_settled' });++ knobs.requests = [];+ knobs.onEvent?.({ type: 'agent_start' });+ emitConfirmedDegenerateMessage();+ await vi.waitFor(() => expect(knobs.requests.filter((type) => type === 'abort')).toHaveLength(1));+ knobs.onEvent?.({ type: 'agent_settled' });++ knobs.requests = [];+ knobs.onEvent?.({ type: 'agent_start' });+ emitConfirmedDegenerateMessage();+ expect(knobs.requests.filter((type) => type === 'abort')).toHaveLength(0);++ await handle.close();+ });++ it('keeps a real gateway disconnect resumable when the Pi abort RPC is rejected', async () => {+ knobs.abortRejects = true;+ const handle = await new PiAgent(buildDeps()).startSession(opts());+ const events: Array<{ type: string; data?: unknown }> = [];+ void (async () => {+ for await (const event of handle.events()) events.push(event);+ })();+ const rawError = 'OpenAI Responses stream ended before a terminal response event';++ await handle.send({ type: 'user', content: 'start a Pi turn' });+ await handle.abort();+ knobs.onEvent?.({ type: 'agent_start' });+ knobs.onEvent?.({+ type: 'message_end',+ message: {+ role: 'assistant',+ content: [],+ stopReason: 'aborted',+ errorMessage: rawError,+ },+ });+ knobs.onEvent?.({ type: 'agent_settled' });++ await vi.waitFor(() => expect(events.some((event) => event.type === 'error')).toBe(true));+ expect(events.filter((event) => event.type === 'error')).toEqual([+ expect.objectContaining({+ data: expect.objectContaining({ message: rawError, isTerminal: true }),+ }),+ ]);++ 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 --cc packages/maker-core/src/agents/pi/index.tsindex b73fd25abb,1a953dc91e..6597b9d688--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@@ -139,7 -179,10 +179,11 @@@ importcreatePiTranslateContext,disposePiTranslateContext,isFailedOrAbortedPiCompaction,+ markPiHostAbortRequested,+ markPiHostTurnStartPending,+ markPiOutputDegeneration,+ rollbackPiHostAbortRequest,+ rollbackPiHostTurnStart,translatePiEvent,usageSnapshotOf,type PiTranslateContext,@@@ -2170,17 -2797,6 +2803,20 @@@ export class PiAgent extends BaseAgent// follow-up send)同口径。清空只认 turn 终态,由 send 预检覆盖为最新值。let activeTurnPermissionPolicy: TurnPermissionPolicy | null = null;let mutableModel = opts.model;+ // 用户显式放行只对对应的 Pi agent turn 生效。每个已发起的 prompt 独立排队,避免+ // streaming 中连续 followUp 互相覆盖;对象身份让明确拒绝的 prompt 只撤销自己。+ type OutputDegenerationBypassReservation = { allowRepetitiveOutput: boolean };+ const pendingOutputDegenerationBypasses: OutputDegenerationBypassReservation[] = [];+ const discardOutputDegenerationBypass = (+ reservation: OutputDegenerationBypassReservation,+ ): void => {+ const index = pendingOutputDegenerationBypasses.indexOf(reservation);+ if (index >= 0) pendingOutputDegenerationBypasses.splice(index, 1);+ };++ const clearPendingOutputDegenerationBypasses = (): void => {++ pendingOutputDegenerationBypasses.length = 0;++ };+ let activeOutputDegenerationBypass = false;let mutableWireModel = initialWireModel;// Pi RPC 实际选中的 provider。与用于宿主鉴权/审阅元数据的 mutableProviderId 分开:// null/订阅来源会归一到 cindy,setModel 未显式传来源时也必须跟随本次解析结果。@@@ -2334,32 -3695,6 +3715,45 @@@};const runPiCompact = (instructions?: string): Promise<ManualCompactResult> =>runExclusivePiRpc(() => requestPiCompact(instructions));- const maybeHostAutoCompact = (): void => {- if (closed || ctx.isStreaming) return;- if (!autoCompactController?.shouldCompactNow()) return;- const snapshot = autoCompactController.getLatestSnapshot();- this.deps.logger.info('pi host auto-compact triggered', {- threshold: autoCompactController.getCurrentThresholdPct(),- ratio: snapshot ? Number(snapshot.ratio.toFixed(3)) : undefined,- contextTokens: snapshot?.contextTokens,- contextWindow: snapshot?.contextWindow,- });- ctx.hostAutoCompactInFlight = true;- void runPiCompact()- .then((result) => {- if (result.noop) {- ctx.hostAutoCompactInFlight = false;- autoCompactController.onCompactCanceled('host_auto_compact_noop');++ const outputDegenerationProtection = new PiOutputDegenerationProtection({++ logger: this.deps.logger.child('output-degeneration'),++ // 读取实际下发给 Pi 的 mutableWireModel:既遵守 provider alias / wireId,++ // 也让会话内 setModel 后的下一条消息立即按新模型生效。++ isEnabled: () =>++ shouldProtectPiOutput(mutableWireModel) && !activeOutputDegenerationBypass,++ abort: () => {++ // abort 是 session-global RPC。检测时先钉住 turn generation,再进入与++ // prompt/compact/model 控制共用的串行链;排队期间 turn 已推进就直接忽略,++ // 防止迟到的止损误杀下一轮合法输出。++ const detectedTurnGeneration = ctx.turnGeneration;++ clearPendingOutputDegenerationBypasses();++ return runExclusivePiRpc(async () => {++ if (++ proc.isClosed++ || !ctx.isStreaming++ || ctx.turnGeneration !== detectedTurnGeneration++ ) {++ return { success: true, ignored: true };+ }- })- .catch((err) => {- ctx.hostAutoCompactInFlight = false;- autoCompactController.onCompactCanceled('host_auto_compact_failed');- this.deps.logger.warn('pi host auto-compact failed', {- message: err instanceof Error ? err.message : String(err),- });++ const hostAbortToken = markPiHostAbortRequested(ctx);++ let response: Awaited<ReturnType<typeof proc.request>>;++ try {++ response = await proc.request({ type: 'abort' });++ } catch (error) {++ if (ctx.turnGeneration === detectedTurnGeneration) {++ rollbackPiHostAbortRequest(ctx, hostAbortToken);++ }++ throw error;++ }++ if (ctx.turnGeneration !== detectedTurnGeneration) {++ return { success: true, ignored: true };++ }++ if (!response.success) rollbackPiHostAbortRequest(ctx, hostAbortToken);++ return response;+ });- };++ },++ onDetected: () => markPiOutputDegeneration(ctx),++ });let sessionTransport: PiTransport | undefined;let runtimeCapabilityManifest: PiRuntimeCapabilityManifest | undefined;let runtimeCapabilityGeneration = 0;@@@ -3590,9 -5307,7 +5371,11 @@@if (reviewMode) {await assertReviewMessageContentPaths(message.content, opts.workingDir, reviewReadGrants);}-- let { text, images } = await buildPiPrompt(message, { remote });++ const builtPrompt = await buildPiPrompt(message, { remote });++ let text = builtPrompt.text;++ const { images } = builtPrompt;+ const outputDegenerationDirective = consumePiOutputDegenerationDirective(text);+ text = outputDegenerationDirective.prompt;rejectIfCancelled(sendOpts, 'send');assertImageInputSupported(images);setAutoReviewIntent(message.content);@@@ -3629,12 -5353,10 +5421,14 @@@? await readPiUserEntryIds(): null;if (!managedPackageRoute.accepted) rejectIfCancelled(sendOpts, 'send');+ const outputDegenerationBypassReservation = {+ allowRepetitiveOutput: outputDegenerationDirective.allowRepetitiveOutput,+ };+ pendingOutputDegenerationBypasses.push(outputDegenerationBypassReservation);+ const pendingTurnStartToken = markPiHostTurnStartPending(ctx);promptRequestStarted = true;try {+ doctorCommandActivity.enter(isDoctorCommand);const resp = await runExclusivePiRpc(() => proc.request(command, {timeoutMs: PI_PROMPT_ACCEPTANCE_TIMEOUT_MS,// Prompt acceptance may legitimately span multiple compaction@@@ -3644,8 -5366,8 +5438,9 @@@PI_PROMPT_ACCEPTANCE_PROGRESS_EVENTS.has(event.type),}));if (!resp.success) {+ rollbackPiHostTurnStart(ctx, pendingTurnStartToken);if (managedPackageRoute.accepted) {+ discardOutputDegenerationBypass(outputDegenerationBypassReservation);// The host-owned package mutation and its deterministic visible// receipt already crossed the dispatch boundary. The follow-up// prompt only lets Pi/model restate that receipt; rejecting it@@@ -3714,7 -5436,7 +5509,8 @@@data.isCompacting !== true &&(typeof data.pendingMessageCount !== 'number' || data.pendingMessageCount === 0);if (runtimeIdle && piAgentLifecycleSequence === lifecycleSequenceBeforePrompt) {+ discardOutputDegenerationBypass(outputDegenerationBypassReservation);+ rollbackPiHostTurnStart(ctx, pendingTurnStartToken);const result = capturedExtensionNotifications?.join('\n\n') ?? '';// prompt success is only the RPC acceptance boundary. Let// handle.send() resolve before publishing a synthetic terminal;@@@ -3771,9 -5493,7 +5567,10 @@@if (activeExtensionCommandNotifications === capturedExtensionNotifications) {activeExtensionCommandNotifications = null;}+ if (!providerAccepted) {+ discardOutputDegenerationBypass(outputDegenerationBypassReservation);+ }+ doctorCommandActivity.leave(isDoctorCommand);}} catch (err) {// 只在 Provider 尚未接受本轮时回滚。接受后的 transcript 回调失败不代表@@@ -3845,11 -5580,77 +5657,78 @@@}},+ async stopBackgroundTask(taskId: string): Promise<void> {+ if (closed) return;+ if (!localSubagentSupported) throw new Error('PI Subagent is available only in local PI sessions.');+ await controlPiSubagentRuns(subagentRunRoot, taskId, 'stop', {+ runtimeOwnerId: subagentRuntimeOwnerId,+ });+ await refreshPiSubagentRuns();+ },++ async resumeBackgroundTask(taskId: string, message: string, childId?: string): Promise<void> {+ if (closed) throw new Error('PI session is closed');+ if (!localSubagentSupported) throw new Error('PI Subagent is available only in local PI sessions.');+ const operation = (async () => {+ await permissionWriteChain;+ if (closed) throw new Error('PI session is closed');+ const [modelsJson, bridgeSource, runnerSource] = await Promise.all([+ fs.readFile(path.join(configHome, 'models.json')),+ fs.readFile(bridgeExtensionPath),+ fs.readFile(subagentRunnerPath),+ ]);+ const runId = await resumePiSubagentRun(subagentRunRoot, taskId, message, {+ launchRunner: launchSubagentRunner,+ env: durableSpawnEnv,+ runtimeOwnerId: subagentRuntimeOwnerId,+ permissionSnapshot: {+ ...requestedPermissionSnapshot,+ mode: permissionMode,+ readOnlyRoots: [...requestedPermissionSnapshot.readOnlyRoots],+ writableRoots: [...requestedPermissionSnapshot.writableRoots],+ ...reviewPathSnapshot,+ },+ runnerFallbackFile: subagentRunnerPath,+ runtimeSnapshot: { modelsJson, bridgeSource, runnerSource },+ }, childId);+ if (!runId) throw new Error('No terminal PI Subagent run is available to resume.');+ await refreshPiSubagentRuns();+ })();+ // close() waits for every resume that entered while this handle was+ // live before inspecting durable runs and transferring the proxy-token+ // lease. Otherwise a concurrent close can observe no new directory,+ // revoke the token, and then let this resume launch a doomed child.+ piSubagentResumeTail = operation.then(() => undefined, () => undefined);+ await operation;+ },++ listBackgroundTasks() {+ if (closed) return [];+ return Array.from(piSubagentStatuses.values())+ .filter((status) => !isPiSubagentTerminal(status.state))+ .map((status) => ({+ taskId: status.taskId,+ taskType: 'pi_subagent',+ toolUseId: status.taskId,+ title: status.title ?? status.description,+ provider: 'pi' as const,+ }));+ },+async requestGracefulStop(): Promise<void> {if (proc.isClosed) throw new Error('No active Pi turn to stop');++ clearPendingOutputDegenerationBypasses();+ const hostAbortToken = markPiHostAbortRequested(ctx);dismissAllPendingPrompts('turn_aborted', 'deny');- const resp = await proc.request({ type: 'abort' });+ let resp: Awaited<ReturnType<typeof proc.request>>;+ try {+ resp = await proc.request({ type: 'abort' });+ } catch (error) {+ rollbackPiHostAbortRequest(ctx, hostAbortToken);+ throw error;+ }if (!resp.success) {+ rollbackPiHostAbortRequest(ctx, hostAbortToken);throw new Error(`Pi graceful stop rejected: ${resp.error ?? 'unknown'}`);}clearActiveTurnPermissionPolicy('turn_aborted');@@@ -3857,6 -5658,7 +5736,8 @@@async abort(): Promise<void> {if (proc.isClosed) return;++ clearPendingOutputDegenerationBypasses();+ const hostAbortToken = markPiHostAbortRequested(ctx);// 先把等待中的调用 fail-closed 唤醒;即使 abort RPC 失败,也不能让用户刚拒绝/// 停止的那次工具继续等一张已失效的卡。policy 仅在 Pi 确认接受 abort 后清空,// RPC 失败时继续保留,防止仍在运行的 turn 失去渠道安全边界。@@@ -3877,8 -5681,13 +5760,14 @@@}},- async close(): Promise<void> {+ async close(closeOpts?: AgentSessionTeardownOptions): Promise<void> {closed = true;++ clearPendingOutputDegenerationBypasses();+ // No reason means the caller could not identify its boundary; fail+ // closed to the account boundary rather than leaving a detached child+ // running against credentials that may already belong to someone else.+ const accountBoundary = (closeOpts?.reason ?? 'account-boundary') === 'account-boundary';+ clearPiSubagentRefreshTimer();disposePiTranslateContext(ctx);runtimeCapabilityGeneration++;publishRuntimeCapabilities(undefined);diff --cc packages/maker-core/src/agents/pi/output-degeneration-protection.tsindex ab3a11ba79,0000000000..f3e249a180mode 100644,000000..100644--- a/packages/maker-core/src/agents/pi/output-degeneration-protection.ts+++ b/packages/maker-core/src/agents/pi/output-degeneration-protection.ts@@@ -1,157 -1,0 +1,166 @@@+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;++ /** 检测所属 turn 已结束或切换时,不再发送/消费 session-global abort。 */++ ignored?: boolean;+}++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.ignored) {++ this.logger.info('pi output degeneration abort ignored after turn advanced', {++ reason: verdict.reason,++ observedCharacters: verdict.observedCharacters,++ });++ return;++ }+ 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 --cc packages/maker-core/src/agents/pi/translator.tsindex cd443c68be,1edea217ec..e9662ae07c--- a/packages/maker-core/src/agents/pi/translator.ts+++ b/packages/maker-core/src/agents/pi/translator.ts@@@ -60,11 -78,11 +78,17 @@@ interface PiAssistantMessageinterface PiPendingAssistantError {message: string;sdkError: string;- reason?: string;errorStatus?: 401 | 429 | 529;usageLimit?: true;+ reason?: typeof CONTEXT_OVERFLOW_REASON | typeof UPSTREAM_STREAM_INTERRUPTED_REASON | typeof PI_GATEWAY_DROP_REASON;+ }+++interface PiPendingSafetyError {++ message: string;++ sdkError: string;++ reason: 'output-degeneration' | 'output-limit';+}+interface PiThinkingBlock {blockId: string;startedAt: number;@@@ -109,11 -144,6 +150,11 @@@ export interface PiTranslateContext* 暂存到 agent_settled 再终态上报,避免一次可恢复错误提前收口整个 turn。*/pendingAssistantError: PiPendingAssistantError | null;+ /**+ * Cindy 自己确认的 turn 级安全收口。与 provider retry 错误分开保存:后续普通+ * message_end 可以证明 provider retry 已恢复,却不能抹掉已经触发的本地止损。+ */- pendingSafetyError: PiPendingAssistantError | null;++ pendingSafetyError: PiPendingSafetyError | null;/** 整轮 wall-clock 起点;只用于诊断,不参与 TPS。 */turnWallClockStartedAt: number;generationDurationMs: number;@@@ -162,10 -216,12 +227,13 @@@ export function createPiTranslateContexgenerationHeartbeatTimer: null,generationHeartbeatReliable: true,delegatedUsage: new Map(),+ delegatedUsageSegmentIds: new Set(),+ delegatedUsageIncompleteTaskIds: new Set(),subagentToolCalls: new Map(),+ toolNamesByCallId: new Map(),pendingAssistantError: null,+ pendingSafetyError: null,- hostAutoCompactInFlight: false,+ compactTurnScope: null,};}@@@ -182,9 -300,12 +312,13 @@@ function stopPiGenerationHeartbeat(ctxexport function disposePiTranslateContext(ctx: PiTranslateContext): void {stopPiGenerationHeartbeat(ctx);ctx.isStreaming = false;+ ctx.pendingHostTurnStartToken = null;+ clearPiHostAbortRequests(ctx);ctx.pendingAssistantError = null;+ ctx.pendingSafetyError = null;+ ctx.compactTurnScope = null;ctx.subagentToolCalls.clear();+ ctx.toolNamesByCallId.clear();}function samplePiGenerationHeartbeat(ctx: PiTranslateContext, now = Date.now()): void {@@@ -208,23 -330,22 +343,31 @@@ function startPiGenerationHeartbeat(ctx}export function usageSnapshotOf(ctx: PiTranslateContext): UsageSnapshot {- return {- tokenUsage: ctx.turnTokens,- contextTokens: ctx.contextTokens,- contextWindow: ctx.contextWindow,- costUsd: ctx.costUsd,- };+ return attachLiveGeneration(+ {+ tokenUsage: ctx.turnTokens,+ contextTokens: ctx.contextTokens,+ contextWindow: ctx.contextWindow,+ costUsd: ctx.costUsd,+ },+ {+ outputTokens: ctx.turnOutput,+ closedDurationMs: ctx.generationDurationMs,+ openStartedAt: ctx.generationOpenAt > 0 ? ctx.generationOpenAt : null,+ reliable: ctx.generationTimingReliable && ctx.generationHeartbeatReliable,+ },+ );}+/** 由 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,@@@ -393,9 -641,14 +663,15 @@@ export function translatePiEventctx.turnOutput = 0;ctx.turnCacheRead = 0;ctx.turnCacheWrite = 0;+ ctx.turnUsageSegments = [];+ ctx.turnUsageSegmentsComplete = true;+ ctx.turnUsageSegmentSeq = 0;+ ctx.pendingPriceVariants = [];+ ctx.turnSettled = false;ctx.finalAssistantText = '';+ ctx.finalAssistantStopReason = null;ctx.pendingAssistantError = null;+ ctx.pendingSafetyError = null;ctx.turnWallClockStartedAt = Date.now();ctx.generationDurationMs = 0;ctx.generationTimingReliable = true;@@@ -460,14 -733,7 +756,14 @@@// 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) {+ if (!transientAssistantFailure && fullText.length > 0) {// 覆盖为本 turn 最新一条有文本的 assistant 回复,agent_settled 作 done.result 上报。ctx.finalAssistantText = fullText;queue.push({@@@ -599,14 -900,21 +930,24 @@@return;case 'agent_settled': {+ if (ctx.turnSettled) return;+ ctx.turnSettled = true;ctx.isStreaming = false;+ ctx.pendingPriceVariants = [];stopPiGenerationHeartbeat(ctx);- const pendingAssistantError = ctx.pendingAssistantError;+ const hostAbortRequested = isCurrentTurnHostAbortRequested(ctx);+ const pendingAssistantError = hostAbortRequested ? null : ctx.pendingAssistantError;- const outcome = pendingAssistantError+ ctx.pendingAssistantError = null;+ const pendingSafetyError = ctx.pendingSafetyError;+ ctx.pendingSafetyError = null;+ const terminalError = pendingSafetyError ?? pendingAssistantError;++ const outcome = terminalError+ ? 'failed'+ : hostAbortRequested || ctx.finalAssistantStopReason === 'aborted'+ ? 'cancelled'+ : 'completed';- ctx.pendingAssistantError = null;+ clearPiHostAbortRequests(ctx);- if (pendingAssistantError) {+ if (terminalError) {queue.push({type: 'error',data: {@@@ -623,7 -931,8 +964,10 @@@// 本 turn 最终 assistant 回复文本。与 CC/Codex 的 done.data.result 对齐:// register.ts 的 will-assistant-message 出口钩子与 Orca worker 终态 finalText// 都读 done.data.result,不带上就会对 Pi 静默跳过这些钩子(codex review P1)。- result: ctx.finalAssistantText,- result: outcome === 'completed' ? ctx.finalAssistantText : '',++ // 本地安全止损也必须保留已经产生的正文,便于用户确认中断点;普通++ // provider 失败/用户取消仍保持空 result,避免把半截失败响应当成功答案。++ result: pendingSafetyError || outcome === 'completed' ? ctx.finalAssistantText : '',+ status: outcome,// ghost 订阅 did-turn-end 的 usage 上报(subscriptionGateway.normalizeTurnUsage// 认 camelCase);与 CC/Codex 的 done.usage 对齐,让插件能显示 pi turn 的用量。usage: {