From 9222e91835e892f750a7c750648c1e343880e2da Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Thu, 26 Nov 2026 19:59:19 -0500 Subject: [PATCH 1/2] feat(pi): track mid-stream stalls with agent stream stalled event --- .../harness/pi/__tests__/stream-stall.test.ts | 418 ++++++++++++++++++ .../pi/__tests__/structured-run.test.ts | 109 +++++ src/agent/runner/harness/pi/index.ts | 14 + src/agent/runner/harness/pi/stream-stall.ts | 330 ++++++++++++++ src/agent/runner/harness/pi/task.ts | 15 +- 5 files changed, 885 insertions(+), 1 deletion(-) create mode 100644 src/agent/runner/harness/pi/__tests__/stream-stall.test.ts create mode 100644 src/agent/runner/harness/pi/stream-stall.ts diff --git a/src/agent/runner/harness/pi/__tests__/stream-stall.test.ts b/src/agent/runner/harness/pi/__tests__/stream-stall.test.ts new file mode 100644 index 000000000..5a472fca2 --- /dev/null +++ b/src/agent/runner/harness/pi/__tests__/stream-stall.test.ts @@ -0,0 +1,418 @@ +import { Sequence } from '@shared/constants'; +import { analytics } from '@utils/analytics'; +import { + classifyStreamStallError, + createStreamStallWatcher, + DEFAULT_STREAM_SILENCE_MS, + getActivePiSessions, + STREAM_STALL_EVENT, + type StreamStallWatcherOptions, +} from '../stream-stall'; + +vi.mock('@utils/analytics', () => ({ + analytics: { wizardCapture: vi.fn() }, +})); +vi.mock('@utils/debug', () => ({ logToFile: vi.fn() })); + +describe('classifyStreamStallError', () => { + it.each([ + ['request deadline exceeded mid-stream', 'deadline_exceeded'], + ['context deadline exceeded', 'deadline_exceeded'], + ['UND_ERR_BODY_TIMEOUT', 'deadline_exceeded'], + ['upstream closed the stream', 'upstream_closed'], + ['stream ended unexpectedly', 'upstream_closed'], + ['terminated', 'upstream_closed'], + ['upstream connection lost', 'connection_reset'], + ['read ECONNRESET', 'connection_reset'], + ['socket hang up', 'connection_reset'], + ] as const)('classifies "%s" as %s', (message, expected) => { + expect(classifyStreamStallError(message)).toBe(expected); + }); + + it.each([ + undefined, + '', + '401 authentication_error', + '429 rate limit exceeded', + 'invalid_request_error: bad schema', + 'session terminated by policy', + ])('returns undefined for non-stall error %s', (message) => { + expect(classifyStreamStallError(message)).toBeUndefined(); + }); +}); + +describe('createStreamStallWatcher', () => { + const watchers: Array> = []; + + const createWatcher = ( + overrides: Partial = {}, + ) => { + const watcher = createStreamStallWatcher({ + sequence: Sequence.orchestrator, + model: 'openai/gpt-6.2-sol', + effort: 'low', + api: 'openai-responses', + tag: 'pi-task', + analyticsProperties: { task_type: 'logs', task_id: 'task-7' }, + ...overrides, + }); + watchers.push(watcher); + return watcher; + }; + + beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-11-26T22:00:00Z')); + vi.clearAllMocks(); + }); + + afterEach(() => { + while (watchers.length > 0) { + watchers.pop()?.dispose(); + } + vi.useRealTimers(); + }); + + it('does not fire on healthy turns or slow tool execution after message_end', () => { + const watcher = createWatcher(); + + watcher.onEvent({ type: 'turn_start' }); + watcher.onEvent({ type: 'message_start', message: { role: 'assistant' } }); + vi.advanceTimersByTime(60_000); + watcher.onEvent({ type: 'message_update' }); + vi.advanceTimersByTime(60_000); + watcher.onEvent({ + type: 'message_end', + message: { role: 'assistant', stopReason: 'toolUse' }, + }); + + // Long bash install between assistant turns must not trigger stream silence. + vi.advanceTimersByTime(300_000); + + expect(analytics.wizardCapture).not.toHaveBeenCalled(); + watcher.dispose(); + expect(getActivePiSessions()).toBe(0); + }); + + it('emits silent at 120s and failed at 600s deadline error with full diagnostics', () => { + const watcher = createWatcher(); + + watcher.onEvent({ type: 'turn_start' }); + // User/toolResult messages must not reset or end the model wait. + watcher.onEvent({ type: 'message_start', message: { role: 'user' } }); + watcher.onEvent({ type: 'message_end', message: { role: 'user' } }); + + watcher.onEvent({ type: 'message_start', message: { role: 'assistant' } }); + vi.advanceTimersByTime(5_000); + watcher.onEvent({ type: 'message_update' }); + watcher.onEvent({ type: 'message_update' }); + + vi.advanceTimersByTime(DEFAULT_STREAM_SILENCE_MS); + expect(analytics.wizardCapture).toHaveBeenCalledTimes(1); + expect(analytics.wizardCapture).toHaveBeenLastCalledWith( + STREAM_STALL_EVENT, + expect.objectContaining({ + stage: 'silent', + harness: 'pi', + sequence: Sequence.orchestrator, + model: 'openai/gpt-6.2-sol', + effort: 'low', + api: 'openai-responses', + task_type: 'logs', + task_id: 'task-7', + turn_number: 1, + stream_opened: true, + chunks_received: 2, + idle_ms: DEFAULT_STREAM_SILENCE_MS, + turn_elapsed_ms: DEFAULT_STREAM_SILENCE_MS + 5_000, + active_sessions: 1, + turn_start_active_sessions: 1, + }), + ); + + vi.advanceTimersByTime(480_000); + watcher.onEvent({ + type: 'message_end', + message: { + role: 'assistant', + stopReason: 'error', + errorMessage: 'request deadline exceeded mid-stream', + }, + }); + + expect(analytics.wizardCapture).toHaveBeenCalledTimes(2); + expect(analytics.wizardCapture).toHaveBeenLastCalledWith( + STREAM_STALL_EVENT, + expect.objectContaining({ + stage: 'failed', + error_kind: 'deadline_exceeded', + error_message: 'request deadline exceeded mid-stream', + stream_opened: true, + chunks_received: 2, + idle_ms: 600_000, + turn_elapsed_ms: 605_000, + }), + ); + }); + + it('emits silent with stream_opened=false when request hangs before first byte', () => { + const watcher = createWatcher(); + watcher.onEvent({ type: 'turn_start' }); + vi.advanceTimersByTime(DEFAULT_STREAM_SILENCE_MS); + + expect(analytics.wizardCapture).toHaveBeenCalledWith( + STREAM_STALL_EVENT, + expect.objectContaining({ + stage: 'silent', + stream_opened: false, + chunks_received: 0, + }), + ); + }); + + it('emits failed immediately on mid-stream drops even before 120s, and ignores non-stall errors', () => { + const watcher = createWatcher(); + + watcher.onEvent({ type: 'turn_start' }); + vi.advanceTimersByTime(2_000); + watcher.onEvent({ + type: 'message_end', + message: { + role: 'assistant', + stopReason: 'error', + errorMessage: '401 authentication_error', + }, + }); + expect(analytics.wizardCapture).not.toHaveBeenCalled(); + + watcher.onEvent({ type: 'turn_start' }); + watcher.onEvent({ type: 'message_start', message: { role: 'assistant' } }); + vi.advanceTimersByTime(8_000); + watcher.onEvent({ + type: 'message_end', + message: { + role: 'assistant', + stopReason: 'error', + errorMessage: 'upstream closed the stream', + }, + }); + expect(analytics.wizardCapture).toHaveBeenCalledTimes(1); + expect(analytics.wizardCapture).toHaveBeenCalledWith( + STREAM_STALL_EVENT, + expect.objectContaining({ + stage: 'failed', + turn_number: 2, + error_kind: 'upstream_closed', + error_message: 'upstream closed the stream', + }), + ); + }); + + it('emits recovered when a silent turn completes, and still captures a later pre-turn_start transport error', () => { + const watcher = createWatcher(); + watcher.onEvent({ type: 'turn_start' }); + vi.advanceTimersByTime(DEFAULT_STREAM_SILENCE_MS + 10_000); + watcher.onEvent({ + type: 'message_end', + message: { role: 'assistant', stopReason: 'stop' }, + }); + + // Follow-up continuation or remark prompt fails at the socket before turn_start. + watcher.noteTransportError('read ECONNRESET'); + + expect(analytics.wizardCapture).toHaveBeenCalledTimes(3); + expect(analytics.wizardCapture).toHaveBeenNthCalledWith( + 1, + STREAM_STALL_EVENT, + expect.objectContaining({ stage: 'silent' }), + ); + expect(analytics.wizardCapture).toHaveBeenNthCalledWith( + 2, + STREAM_STALL_EVENT, + expect.objectContaining({ stage: 'recovered' }), + ); + expect(analytics.wizardCapture).toHaveBeenNthCalledWith( + 3, + STREAM_STALL_EVENT, + expect.objectContaining({ + stage: 'failed', + error_kind: 'connection_reset', + error_message: 'read ECONNRESET', + idle_ms: 0, + chunks_received: 0, + }), + ); + }); + + it('emits aborted on stopReason aborted after silent without duplicating on cancelled dispose', () => { + const watcher = createWatcher(); + watcher.onEvent({ type: 'turn_start' }); + vi.advanceTimersByTime(DEFAULT_STREAM_SILENCE_MS); + watcher.onEvent({ + type: 'message_end', + message: { role: 'assistant', stopReason: 'aborted' }, + }); + watcher.dispose({ cancelled: true }); + + expect(analytics.wizardCapture).toHaveBeenCalledTimes(2); + expect(analytics.wizardCapture).toHaveBeenNthCalledWith( + 2, + STREAM_STALL_EVENT, + expect.objectContaining({ stage: 'aborted' }), + ); + }); + + it('emits aborted when cancelled during an active silent hang without double-emitting', () => { + const watcher = createWatcher(); + watcher.onEvent({ type: 'turn_start' }); + vi.advanceTimersByTime(DEFAULT_STREAM_SILENCE_MS); + watcher.dispose({ cancelled: true }); + watcher.dispose({ cancelled: true }); + + expect(analytics.wizardCapture).toHaveBeenCalledTimes(2); + expect(analytics.wizardCapture).toHaveBeenNthCalledWith( + 2, + STREAM_STALL_EVENT, + expect.objectContaining({ stage: 'aborted' }), + ); + expect(getActivePiSessions()).toBe(0); + }); + + it('clears state on agent_end so a later cancelled dispose does not emit a false aborted event', () => { + const watcher = createWatcher(); + watcher.onEvent({ type: 'turn_start' }); + vi.advanceTimersByTime(DEFAULT_STREAM_SILENCE_MS); + watcher.onEvent({ type: 'agent_end' }); + watcher.dispose({ cancelled: true }); + + expect(analytics.wizardCapture).toHaveBeenCalledTimes(1); + expect(analytics.wizardCapture).toHaveBeenCalledWith( + STREAM_STALL_EVENT, + expect.objectContaining({ stage: 'silent' }), + ); + }); + + it('pauses silence detection during compaction and re-arms on compaction_end', () => { + const watcher = createWatcher(); + watcher.onEvent({ type: 'turn_start' }); + vi.advanceTimersByTime(60_000); + watcher.onEvent({ type: 'compaction_start' }); + + // Compaction itself taking longer than threshold must not fire silent. + vi.advanceTimersByTime(DEFAULT_STREAM_SILENCE_MS * 2); + expect(analytics.wizardCapture).not.toHaveBeenCalled(); + + // Resuming after compaction re-arms the silence timer for a subsequent hang. + watcher.onEvent({ type: 'compaction_end', aborted: false }); + vi.advanceTimersByTime(DEFAULT_STREAM_SILENCE_MS); + expect(analytics.wizardCapture).toHaveBeenCalledTimes(1); + expect(analytics.wizardCapture).toHaveBeenCalledWith( + STREAM_STALL_EVENT, + expect.objectContaining({ + stage: 'silent', + idle_ms: DEFAULT_STREAM_SILENCE_MS, + }), + ); + }); + + it('clears paused state when compaction_end or auto_retry_end ends unsuccessfully', () => { + const watcher = createWatcher(); + watcher.onEvent({ type: 'turn_start' }); + watcher.onEvent({ type: 'compaction_start' }); + watcher.onEvent({ type: 'compaction_end', aborted: true }); + vi.advanceTimersByTime(DEFAULT_STREAM_SILENCE_MS * 2); + expect(analytics.wizardCapture).not.toHaveBeenCalled(); + + watcher.onEvent({ type: 'turn_start' }); + watcher.onEvent({ type: 'auto_retry_start' }); + watcher.onEvent({ type: 'auto_retry_end', success: false }); + vi.advanceTimersByTime(DEFAULT_STREAM_SILENCE_MS * 2); + expect(analytics.wizardCapture).not.toHaveBeenCalled(); + }); + + it('tracks concurrent in-flight Pi sessions accurately across parallel tasks', () => { + const sibling = createWatcher({ + analyticsProperties: { task_type: 'dashboard', task_id: 'task-6' }, + }); + const logs = createWatcher(); + + expect(getActivePiSessions()).toBe(2); + logs.onEvent({ type: 'turn_start' }); + sibling.dispose(); + expect(getActivePiSessions()).toBe(1); + + vi.advanceTimersByTime(DEFAULT_STREAM_SILENCE_MS); + expect(analytics.wizardCapture).toHaveBeenCalledWith( + STREAM_STALL_EVENT, + expect.objectContaining({ + stage: 'silent', + active_sessions: 1, + turn_start_active_sessions: 2, + }), + ); + + logs.dispose(); + expect(getActivePiSessions()).toBe(0); + }); + + it('redacts secrets in error_message before capturing', () => { + const watcher = createWatcher(); + watcher.onEvent({ type: 'turn_start' }); + watcher.onEvent({ + type: 'message_end', + message: { + role: 'assistant', + stopReason: 'error', + errorMessage: + 'upstream closed the stream for phx_secret1234567890abcdef and sk-proj-0123456789abcdefghij', + }, + }); + + expect(analytics.wizardCapture).toHaveBeenCalledWith( + STREAM_STALL_EVENT, + expect.objectContaining({ + stage: 'failed', + error_kind: 'upstream_closed', + error_message: expect.not.stringMatching( + /phx_secret1234567890abcdef|sk-proj-0123456789abcdefghij/, + ), + }), + ); + }); + + it('does not misclassify normal errors as stalls when silenceThresholdMs <= 0', () => { + const watcher = createWatcher({ silenceThresholdMs: 0 }); + watcher.onEvent({ type: 'turn_start' }); + vi.advanceTimersByTime(5_000); + watcher.onEvent({ + type: 'message_end', + message: { + role: 'assistant', + stopReason: 'error', + errorMessage: '401 authentication_error', + }, + }); + + expect(analytics.wizardCapture).not.toHaveBeenCalled(); + }); + + it('clears silence timer during retry backoff and handles thrown transport errors once', () => { + const watcher = createWatcher(); + watcher.onEvent({ type: 'turn_start' }); + watcher.onEvent({ type: 'auto_retry_start' }); + vi.advanceTimersByTime(DEFAULT_STREAM_SILENCE_MS * 2); + expect(analytics.wizardCapture).not.toHaveBeenCalled(); + + watcher.noteTransportError('read ECONNRESET'); + watcher.noteTransportError('read ECONNRESET'); + expect(analytics.wizardCapture).toHaveBeenCalledTimes(1); + expect(analytics.wizardCapture).toHaveBeenCalledWith( + STREAM_STALL_EVENT, + expect.objectContaining({ + stage: 'failed', + error_kind: 'connection_reset', + error_message: 'read ECONNRESET', + }), + ); + }); +}); diff --git a/src/agent/runner/harness/pi/__tests__/structured-run.test.ts b/src/agent/runner/harness/pi/__tests__/structured-run.test.ts index e02bfaeb9..c9045fdef 100644 --- a/src/agent/runner/harness/pi/__tests__/structured-run.test.ts +++ b/src/agent/runner/harness/pi/__tests__/structured-run.test.ts @@ -1,5 +1,6 @@ import { piBackend } from '..'; import { runPiTask } from '../task'; +import { getActivePiSessions, STREAM_STALL_EVENT } from '../stream-stall'; import { AgentSignals, REMARK_INSTRUCTION } from '@agent/signals'; import { analytics } from '@utils/analytics'; import { createSecurityExtension } from '../security'; @@ -47,6 +48,10 @@ const state = vi.hoisted(() => ({ toolResult: undefined as string | undefined, // A second turn in the same prompt: complete_task runs, then the agent replies. report: undefined as { settle: () => void; reply: string } | undefined, + // Assistant message_end error string (for stream-stall runner wiring tests). + messageError: undefined as string | undefined, + // Reject prompt() with a transport error before message_end. + promptError: undefined as string | undefined, })); vi.mock('@utils/analytics', () => ({ analytics: { wizardCapture: vi.fn(), capture: vi.fn() }, @@ -164,6 +169,22 @@ vi.mock('@earendil-works/pi-coding-agent', () => ({ prompt: (prompt: string) => { state.prompts.push(prompt); state.onPrompt?.(state.prompts); + if (state.promptError) { + return Promise.reject(new Error(state.promptError)); + } + if (state.messageError) { + state.listener?.({ type: 'turn_start' }); + state.listener?.({ + type: 'message_end', + message: { + role: 'assistant', + stopReason: 'error', + errorMessage: state.messageError, + content: [], + }, + }); + return Promise.resolve(); + } if (!state.noTools) state.listener?.({ type: 'tool_execution_start', @@ -329,6 +350,8 @@ beforeEach(() => { state.toolResult = undefined; state.remark = undefined; state.report = undefined; + state.messageError = undefined; + state.promptError = undefined; vi.mocked(analytics.wizardCapture).mockClear(); }); @@ -859,3 +882,89 @@ it('forwards config.run.detectPackageManager into createWizardPiTools on orchest expect.objectContaining({ detectPackageManager: customDetector }), ); }); + +describe('stream stall telemetry wiring', () => { + it('captures mid-stream stall events in piBackend.run and cleans up active sessions', async () => { + state.messageError = 'request deadline exceeded mid-stream'; + + await piBackend.run(runInputs(vi.fn(), null)); + + expect(analytics.wizardCapture).toHaveBeenCalledWith( + STREAM_STALL_EVENT, + expect.objectContaining({ + stage: 'failed', + harness: 'pi', + sequence: Sequence.linear, + model: GPT5_6_LUNA_MODEL, + effort: 'low', + api: 'openai-responses', + error_kind: 'deadline_exceeded', + error_message: 'request deadline exceeded mid-stream', + }), + ); + expect(getActivePiSessions()).toBe(0); + }); + + it('captures mid-stream stall events in runPiTask with task analyticsProperties', async () => { + state.messageError = 'upstream closed the stream'; + + await runPiTask({ + ...runInputs(vi.fn(), null), + orchestrator: { + currentTaskId: 'logs', + validTypes: ['logs'], + store: { get: () => ({ status: 'running' }) }, + } as never, + spinnerMessage: '', + successMessage: '', + requestRemark: false, + allowedTools: ['Read'], + analyticsProperties: { task_type: 'logs', task_id: 'task-7' }, + }); + + expect(analytics.wizardCapture).toHaveBeenCalledWith( + STREAM_STALL_EVENT, + expect.objectContaining({ + stage: 'failed', + harness: 'pi', + sequence: Sequence.orchestrator, + model: GPT5_6_LUNA_MODEL, + task_type: 'logs', + task_id: 'task-7', + error_kind: 'upstream_closed', + }), + ); + expect(getActivePiSessions()).toBe(0); + }); + + it('captures thrown transport errors in runPiTask via noteTransportError', async () => { + state.promptError = 'read ECONNRESET'; + + await runPiTask({ + ...runInputs(vi.fn(), null), + orchestrator: { + currentTaskId: 'logs', + validTypes: ['logs'], + store: { get: () => ({ status: 'running' }) }, + } as never, + spinnerMessage: '', + successMessage: '', + requestRemark: false, + allowedTools: ['Read'], + analyticsProperties: { task_type: 'logs', task_id: 'task-8' }, + }); + + expect(analytics.wizardCapture).toHaveBeenCalledWith( + STREAM_STALL_EVENT, + expect.objectContaining({ + stage: 'failed', + harness: 'pi', + sequence: Sequence.orchestrator, + task_type: 'logs', + task_id: 'task-8', + error_kind: 'connection_reset', + }), + ); + expect(getActivePiSessions()).toBe(0); + }); +}); diff --git a/src/agent/runner/harness/pi/index.ts b/src/agent/runner/harness/pi/index.ts index df8674ed5..4ca7c02a3 100644 --- a/src/agent/runner/harness/pi/index.ts +++ b/src/agent/runner/harness/pi/index.ts @@ -38,6 +38,7 @@ import { withGatewayRemint, createGatewayRuntime, } from './gateway'; +import { createStreamStallWatcher } from './stream-stall'; import { createAioCapture } from '../../../aio-capture'; import type { AgentResult, @@ -357,6 +358,7 @@ export const piBackend: AgentHarness = { let mcpCleanup: (() => void) | undefined; let aioFailed = true; let cancellation: ReturnType | undefined; + let streamStall: ReturnType | undefined; let timedOut = false; let timeoutAbort: Promise | undefined; let abortReason: string | undefined; @@ -679,6 +681,13 @@ export const piBackend: AgentHarness = { }, }); + streamStall = createStreamStallWatcher({ + sequence: Sequence.linear, + model: modelId, + effort: caps.thinkingLevel, + api, + tag: 'pi', + }); // Map pi events onto the run spinner + the log file, mirroring the // anthropic path's log shape (assistant turns + tool I/O) and driving the // single run spinner with one stable status at a time (no overlap). @@ -687,6 +696,7 @@ export const piBackend: AgentHarness = { // before the role guard so the module's own filter (assistant-only) // stays the single source of truth for what's captured. capture.captureFromPiMessageEndEvent(event); + streamStall?.onEvent(event); switch (event.type) { case 'message_end': { @@ -995,6 +1005,7 @@ export const piBackend: AgentHarness = { if (timedOut && structured) return timedOutResult(structured.timeoutMs); const message = err instanceof Error ? err.message : String(err); logToFile(`[pi] run error: ${message}`); + streamStall?.noteTransportError(message); spinner.stop(config.errorMessage ?? `${config.integrationLabel} failed`); log.error(`pi backend error: ${message}`); const coded = classifyRunFailure(err); @@ -1016,6 +1027,9 @@ export const piBackend: AgentHarness = { } finally { await cancellation?.settle(); await timeoutAbort; + streamStall?.dispose({ + cancelled: Boolean(inputs.signal?.aborted || timedOut), + }); try { mcpCleanup?.(); } catch { diff --git a/src/agent/runner/harness/pi/stream-stall.ts b/src/agent/runner/harness/pi/stream-stall.ts new file mode 100644 index 000000000..fd6d719e8 --- /dev/null +++ b/src/agent/runner/harness/pi/stream-stall.ts @@ -0,0 +1,330 @@ +/** + * Production telemetry for Pi model stream stalls and mid-stream drops. + * + * Emits `wizard: agent stream stalled` in two situations: + * 1. `stage: 'silent'` when a turn waits on the model for `silenceThresholdMs` + * (default 120s) without a chunk — catches hangs even when the user hits + * Ctrl+C before the gateway's 600s request deadline. + * 2. `stage: 'failed'` when a turn ends on a mid-stream deadline/drop error + * (or any error after crossing the silence threshold). + * + * If a turn that triggered `silent` later finishes or is cancelled, a follow-up + * `stage: 'recovered'` or `stage: 'aborted'` event closes the loop so dashboards + * can separate real hangs from slow reasoning turns. + */ + +import { analytics } from '@utils/analytics'; +import { logToFile } from '@utils/debug'; +import { redactSecrets } from '@shared/mcp-clients/results'; +import type { Sequence } from '@shared/constants'; +import type { GatewayApi } from './gateway'; + +export const STREAM_STALL_EVENT = 'agent stream stalled'; +export const DEFAULT_STREAM_SILENCE_MS = 120_000; + +export type StreamStallStage = 'silent' | 'failed' | 'recovered' | 'aborted'; + +export type StreamStallErrorKind = + | 'deadline_exceeded' + | 'upstream_closed' + | 'connection_reset' + | 'other'; + +type TurnState = 'idle' | 'waiting' | 'paused' | 'failed'; + +export interface StreamStallWatcherOptions { + sequence: Sequence; + model: string; + effort?: string; + api: GatewayApi; + tag: string; + analyticsProperties?: Record; + silenceThresholdMs?: number; + now?: () => number; +} + +export interface StreamStallEvent { + type: string; + message?: unknown; + success?: boolean; + aborted?: boolean; +} + +interface AssistantMessageShape { + role?: string; + stopReason?: string; + errorMessage?: string; +} + +let activePiSessions = 0; + +/** Current count of live Pi sessions in this process (for concurrency telemetry and tests). */ +export function getActivePiSessions(): number { + return activePiSessions; +} + +/** Classify known mid-stream deadline / dropped-stream error strings into a closed dashboard enum. */ +export function classifyStreamStallError( + message: string | undefined, +): Exclude | undefined { + if (!message) return undefined; + if ( + /deadline exceeded|(?:request|stream|headers?|body)\s+timed?\s*out|etimedout|und_err_body_timeout/i.test( + message, + ) + ) { + return 'deadline_exceeded'; + } + if ( + /upstream closed|stream closed|ended unexpectedly|stream terminated|^terminated$/i.test( + message, + ) + ) { + return 'upstream_closed'; + } + if ( + /upstream connection lost|econnreset|socket hang up|econnrefused|epipe/i.test( + message, + ) + ) { + return 'connection_reset'; + } + return undefined; +} + +export function createStreamStallWatcher(opts: StreamStallWatcherOptions) { + const thresholdMs = opts.silenceThresholdMs ?? DEFAULT_STREAM_SILENCE_MS; + const now = opts.now ?? Date.now; + + activePiSessions += 1; + let disposed = false; + let timer: ReturnType | undefined; + + let turnNumber = 0; + let turnState: TurnState = 'idle'; + let turnStartedAt = 0; + let lastActivityAt = 0; + let turnStartActiveSessions = activePiSessions; + let chunksReceived = 0; + let streamOpened = false; + let silentReported = false; + + const clearTimer = () => { + if (timer !== undefined) { + clearTimeout(timer); + timer = undefined; + } + }; + + const resetToIdle = () => { + clearTimer(); + turnState = 'idle'; + turnStartedAt = 0; + lastActivityAt = 0; + chunksReceived = 0; + streamOpened = false; + silentReported = false; + }; + + const report = ( + stage: StreamStallStage, + extra?: { errorKind?: StreamStallErrorKind; errorMessage?: string }, + ) => { + const ts = now(); + const idleMs = turnStartedAt > 0 ? Math.max(0, ts - lastActivityAt) : 0; + const turnElapsedMs = + turnStartedAt > 0 ? Math.max(0, ts - turnStartedAt) : 0; + const truncatedError = extra?.errorMessage + ? redactSecrets(extra.errorMessage).slice(0, 200) + : undefined; + + logToFile( + `[${opts.tag}] stream stalled (stage=${stage} model=${ + opts.model + } turn=${turnNumber} opened=${String( + streamOpened, + )} chunks=${chunksReceived} idle=${Math.round( + idleMs / 1000, + )}s active=${activePiSessions}${ + extra?.errorKind ? ` kind=${extra.errorKind}` : '' + })`, + ); + + analytics.wizardCapture(STREAM_STALL_EVENT, { + ...opts.analyticsProperties, + stage, + harness: 'pi', + sequence: opts.sequence, + model: opts.model, + ...(opts.effort ? { effort: opts.effort } : {}), + api: opts.api, + turn_number: turnNumber, + stream_opened: streamOpened, + chunks_received: chunksReceived, + idle_ms: idleMs, + turn_elapsed_ms: turnElapsedMs, + active_sessions: activePiSessions, + turn_start_active_sessions: turnStartActiveSessions, + ...(extra?.errorKind ? { error_kind: extra.errorKind } : {}), + ...(truncatedError ? { error_message: truncatedError } : {}), + }); + }; + + const armTimer = () => { + clearTimer(); + if ( + disposed || + turnState !== 'waiting' || + silentReported || + thresholdMs <= 0 + ) { + return; + } + timer = setTimeout(() => { + timer = undefined; + if (disposed || turnState !== 'waiting' || silentReported) return; + silentReported = true; + report('silent'); + }, thresholdMs); + timer.unref?.(); + }; + + return { + onEvent(event: StreamStallEvent): void { + if (disposed) return; + + switch (event.type) { + case 'turn_start': { + turnNumber += 1; + turnState = 'waiting'; + turnStartedAt = now(); + lastActivityAt = turnStartedAt; + turnStartActiveSessions = activePiSessions; + chunksReceived = 0; + streamOpened = false; + silentReported = false; + armTimer(); + break; + } + case 'message_start': { + const msg = event.message as AssistantMessageShape | undefined; + if (turnState !== 'waiting' || msg?.role !== 'assistant') break; + streamOpened = true; + lastActivityAt = now(); + armTimer(); + break; + } + case 'message_update': { + if (turnState !== 'waiting') break; + chunksReceived += 1; + lastActivityAt = now(); + armTimer(); + break; + } + case 'message_end': { + const msg = event.message as AssistantMessageShape | undefined; + if (msg?.role !== 'assistant') break; + clearTimer(); + const idleMs = + turnStartedAt > 0 ? Math.max(0, now() - lastActivityAt) : 0; + + if (msg.stopReason === 'error') { + const errorKind = classifyStreamStallError(msg.errorMessage); + if ( + errorKind !== undefined || + silentReported || + (thresholdMs > 0 && idleMs >= thresholdMs) + ) { + turnState = 'failed'; + report('failed', { + errorKind: errorKind ?? 'other', + errorMessage: msg.errorMessage, + }); + } else { + resetToIdle(); + } + } else if (msg.stopReason === 'aborted') { + if (silentReported) { + report('aborted'); + } + resetToIdle(); + } else { + if (silentReported) { + report('recovered'); + } + resetToIdle(); + } + break; + } + case 'auto_retry_start': + case 'compaction_start': { + if (turnState === 'waiting') { + clearTimer(); + turnState = 'paused'; + } + break; + } + case 'auto_retry_end': { + if (turnState !== 'paused') break; + if (event.success === false) { + resetToIdle(); + } else { + turnState = 'waiting'; + lastActivityAt = now(); + armTimer(); + } + break; + } + case 'compaction_end': { + if (turnState !== 'paused') break; + if (event.aborted) { + resetToIdle(); + } else { + turnState = 'waiting'; + lastActivityAt = now(); + armTimer(); + } + break; + } + case 'agent_end': { + if (turnState !== 'failed') { + resetToIdle(); + } else { + clearTimer(); + } + break; + } + default: + break; + } + }, + + noteTransportError(errorMessage: string): void { + if (disposed || turnState === 'failed') return; + clearTimer(); + const errorKind = classifyStreamStallError(errorMessage); + if (errorKind !== undefined || silentReported) { + turnState = 'failed'; + report('failed', { + errorKind: errorKind ?? 'other', + errorMessage, + }); + } + }, + + dispose(disposeOpts?: { cancelled?: boolean }): void { + if (disposed) return; + clearTimer(); + if ( + disposeOpts?.cancelled && + (turnState === 'waiting' || turnState === 'paused') && + silentReported + ) { + report('aborted'); + } + resetToIdle(); + disposed = true; + activePiSessions = Math.max(0, activePiSessions - 1); + }, + }; +} diff --git a/src/agent/runner/harness/pi/task.ts b/src/agent/runner/harness/pi/task.ts index 199d530d0..1519f2edb 100644 --- a/src/agent/runner/harness/pi/task.ts +++ b/src/agent/runner/harness/pi/task.ts @@ -45,6 +45,7 @@ import { withGatewayRemint, createGatewayRuntime, } from './gateway'; +import { createStreamStallWatcher } from './stream-stall'; import { runErrorType, setupSignalFailure } from './completion'; import { bindPiCancellation } from './cancellation'; import type { SecurityState } from './security'; @@ -244,6 +245,7 @@ export async function runPiTask(inputs: TaskRunInputs): Promise { let mcpCleanup: (() => void) | undefined; let aioFailed = true; let cancellation: ReturnType | undefined; + let streamStall: ReturnType | undefined; let securityState: SecurityState | undefined; let abortReason: string | undefined; let remarkTurn = false; @@ -290,7 +292,7 @@ export async function runPiTask(inputs: TaskRunInputs): Promise { // back to the model table. effort, }); - const { provider, caps } = buildGatewayProvider(providerInputs(auth)); + const { provider, caps, api } = buildGatewayProvider(providerInputs(auth)); const registry = await createGatewayRuntime(provider); const model = registry.getModel(GATEWAY_PROVIDER, modelId); if (!model) { @@ -481,10 +483,19 @@ export async function runPiTask(inputs: TaskRunInputs): Promise { logToFile(`[pi-task] tools passed to model: ${toolNames.join(', ')}`); const taskPrompt = `${prompt}\n\n${renderToolInventory(toolNames)}`; + streamStall = createStreamStallWatcher({ + sequence: Sequence.orchestrator, + model: modelId, + effort: caps.thinkingLevel, + api, + tag: 'pi-task', + analyticsProperties, + }); const unsubscribe = agentSession.subscribe((event) => { // Mirror the turn into AIO. No-op when --capture-aio is off. Runs // before the role guard so the module's own filter is authoritative. capture.captureFromPiMessageEndEvent(event); + streamStall?.onEvent(event); switch (event.type) { case 'message_end': { @@ -717,6 +728,7 @@ export async function runPiTask(inputs: TaskRunInputs): Promise { } const message = err instanceof Error ? err.message : String(err); logToFile(`[pi-task] run error: ${message}`); + streamStall?.noteTransportError(message); if (errorMessage || spinnerMessage) { spinner.stop(errorMessage ?? 'Task failed'); } @@ -738,6 +750,7 @@ export async function runPiTask(inputs: TaskRunInputs): Promise { }; } finally { await cancellation?.settle(); + streamStall?.dispose({ cancelled: Boolean(inputs.signal?.aborted) }); try { mcpCleanup?.(); } catch { From 32614a19307f445fd6da9d5af6d11c6df35f54d8 Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Fri, 27 Nov 2026 13:34:03 -0500 Subject: [PATCH 2/2] fix(pi): defer stream stall failure report until Pi retry decision --- .../harness/pi/__tests__/stream-stall.test.ts | 178 +++++++++++++++++- .../pi/__tests__/structured-run.test.ts | 1 + src/agent/runner/harness/pi/stream-stall.ts | 130 ++++++++++--- 3 files changed, 277 insertions(+), 32 deletions(-) diff --git a/src/agent/runner/harness/pi/__tests__/stream-stall.test.ts b/src/agent/runner/harness/pi/__tests__/stream-stall.test.ts index 5a472fca2..e50118055 100644 --- a/src/agent/runner/harness/pi/__tests__/stream-stall.test.ts +++ b/src/agent/runner/harness/pi/__tests__/stream-stall.test.ts @@ -139,6 +139,7 @@ describe('createStreamStallWatcher', () => { errorMessage: 'request deadline exceeded mid-stream', }, }); + watcher.onEvent({ type: 'agent_end', willRetry: false }); expect(analytics.wizardCapture).toHaveBeenCalledTimes(2); expect(analytics.wizardCapture).toHaveBeenLastCalledWith( @@ -170,7 +171,7 @@ describe('createStreamStallWatcher', () => { ); }); - it('emits failed immediately on mid-stream drops even before 120s, and ignores non-stall errors', () => { + it('emits failed on mid-stream drops once agent_end confirms no retry, and ignores non-stall errors', () => { const watcher = createWatcher(); watcher.onEvent({ type: 'turn_start' }); @@ -183,6 +184,7 @@ describe('createStreamStallWatcher', () => { errorMessage: '401 authentication_error', }, }); + watcher.onEvent({ type: 'agent_end', willRetry: false }); expect(analytics.wizardCapture).not.toHaveBeenCalled(); watcher.onEvent({ type: 'turn_start' }); @@ -196,6 +198,10 @@ describe('createStreamStallWatcher', () => { errorMessage: 'upstream closed the stream', }, }); + // Held until agent_end reports whether Pi will retry. + expect(analytics.wizardCapture).not.toHaveBeenCalled(); + + watcher.onEvent({ type: 'agent_end', willRetry: false }); expect(analytics.wizardCapture).toHaveBeenCalledTimes(1); expect(analytics.wizardCapture).toHaveBeenCalledWith( STREAM_STALL_EVENT, @@ -315,19 +321,174 @@ describe('createStreamStallWatcher', () => { ); }); - it('clears paused state when compaction_end or auto_retry_end ends unsuccessfully', () => { + it('clears paused state when compaction_end aborts', () => { const watcher = createWatcher(); watcher.onEvent({ type: 'turn_start' }); watcher.onEvent({ type: 'compaction_start' }); watcher.onEvent({ type: 'compaction_end', aborted: true }); vi.advanceTimersByTime(DEFAULT_STREAM_SILENCE_MS * 2); expect(analytics.wizardCapture).not.toHaveBeenCalled(); + }); + it('suppresses failed when Pi auto-retries a drop and recovers on the retry', () => { + const watcher = createWatcher(); watcher.onEvent({ type: 'turn_start' }); + watcher.onEvent({ type: 'message_start', message: { role: 'assistant' } }); + vi.advanceTimersByTime(8_000); + watcher.onEvent({ + type: 'message_end', + message: { + role: 'assistant', + stopReason: 'error', + errorMessage: 'upstream connection lost', + }, + }); + watcher.onEvent({ type: 'agent_end', willRetry: true }); watcher.onEvent({ type: 'auto_retry_start' }); - watcher.onEvent({ type: 'auto_retry_end', success: false }); + + // Backoff sleep must not trigger silence or emit a premature failed event. vi.advanceTimersByTime(DEFAULT_STREAM_SILENCE_MS * 2); expect(analytics.wizardCapture).not.toHaveBeenCalled(); + + // Retry attempt succeeds: Pi emits message_end then auto_retry_end(success: true). + watcher.onEvent({ type: 'turn_start' }); + watcher.onEvent({ type: 'message_start', message: { role: 'assistant' } }); + vi.advanceTimersByTime(5_000); + watcher.onEvent({ + type: 'message_end', + message: { role: 'assistant', stopReason: 'stop' }, + }); + watcher.onEvent({ type: 'auto_retry_end', success: true }); + watcher.onEvent({ type: 'agent_end', willRetry: false }); + + expect(analytics.wizardCapture).not.toHaveBeenCalled(); + }); + + it('emits recovered (not failed) when a silent turn drops and Pi recovers on retry', () => { + const watcher = createWatcher(); + watcher.onEvent({ type: 'turn_start' }); + vi.advanceTimersByTime(DEFAULT_STREAM_SILENCE_MS); + expect(analytics.wizardCapture).toHaveBeenCalledTimes(1); + expect(analytics.wizardCapture).toHaveBeenLastCalledWith( + STREAM_STALL_EVENT, + expect.objectContaining({ stage: 'silent' }), + ); + + vi.advanceTimersByTime(30_000); + watcher.onEvent({ + type: 'message_end', + message: { + role: 'assistant', + stopReason: 'error', + errorMessage: 'socket hang up', + }, + }); + watcher.onEvent({ type: 'agent_end', willRetry: true }); + watcher.onEvent({ type: 'auto_retry_start' }); + expect(analytics.wizardCapture).toHaveBeenCalledTimes(1); + + // Retry succeeds and closes the silent loop with recovered. + watcher.onEvent({ type: 'turn_start' }); + watcher.onEvent({ type: 'message_start', message: { role: 'assistant' } }); + vi.advanceTimersByTime(5_000); + watcher.onEvent({ + type: 'message_end', + message: { role: 'assistant', stopReason: 'stop' }, + }); + watcher.onEvent({ type: 'auto_retry_end', success: true }); + watcher.onEvent({ type: 'agent_end', willRetry: false }); + + expect(analytics.wizardCapture).toHaveBeenCalledTimes(2); + expect(analytics.wizardCapture).toHaveBeenNthCalledWith( + 2, + STREAM_STALL_EVENT, + expect.objectContaining({ stage: 'recovered' }), + ); + }); + + it('emits failed once when Pi exhausts retries on a mid-stream drop', () => { + const watcher = createWatcher(); + + // Attempt 1: retried by Pi. + watcher.onEvent({ type: 'turn_start' }); + vi.advanceTimersByTime(8_000); + watcher.onEvent({ + type: 'message_end', + message: { + role: 'assistant', + stopReason: 'error', + errorMessage: 'upstream connection lost', + }, + }); + watcher.onEvent({ type: 'agent_end', willRetry: true }); + watcher.onEvent({ type: 'auto_retry_start' }); + expect(analytics.wizardCapture).not.toHaveBeenCalled(); + + // Attempt 2: final failure, Pi emits agent_end(willRetry: false) then auto_retry_end(success: false). + watcher.onEvent({ type: 'turn_start' }); + vi.advanceTimersByTime(10_000); + watcher.onEvent({ + type: 'message_end', + message: { + role: 'assistant', + stopReason: 'error', + errorMessage: 'upstream connection lost', + }, + }); + expect(analytics.wizardCapture).not.toHaveBeenCalled(); + + watcher.onEvent({ type: 'agent_end', willRetry: false }); + watcher.onEvent({ + type: 'auto_retry_end', + success: false, + finalError: 'upstream connection lost', + }); + + expect(analytics.wizardCapture).toHaveBeenCalledTimes(1); + expect(analytics.wizardCapture).toHaveBeenCalledWith( + STREAM_STALL_EVENT, + expect.objectContaining({ + stage: 'failed', + turn_number: 2, + error_kind: 'connection_reset', + error_message: 'upstream connection lost', + idle_ms: 10_000, + }), + ); + }); + + it('emits failed on auto_retry_end(success: false) if retry backoff is cancelled before the next attempt', () => { + const watcher = createWatcher(); + watcher.onEvent({ type: 'turn_start' }); + vi.advanceTimersByTime(8_000); + watcher.onEvent({ + type: 'message_end', + message: { + role: 'assistant', + stopReason: 'error', + errorMessage: 'upstream connection lost', + }, + }); + watcher.onEvent({ type: 'agent_end', willRetry: true }); + watcher.onEvent({ type: 'auto_retry_start' }); + vi.advanceTimersByTime(20_000); + watcher.onEvent({ + type: 'auto_retry_end', + success: false, + finalError: 'Retry cancelled', + }); + watcher.dispose({ cancelled: true }); + + expect(analytics.wizardCapture).toHaveBeenCalledTimes(1); + expect(analytics.wizardCapture).toHaveBeenCalledWith( + STREAM_STALL_EVENT, + expect.objectContaining({ + stage: 'failed', + error_kind: 'connection_reset', + error_message: 'upstream connection lost', + idle_ms: 8_000, + }), + ); }); it('tracks concurrent in-flight Pi sessions accurately across parallel tasks', () => { @@ -367,6 +528,7 @@ describe('createStreamStallWatcher', () => { 'upstream closed the stream for phx_secret1234567890abcdef and sk-proj-0123456789abcdefghij', }, }); + watcher.onEvent({ type: 'agent_end', willRetry: false }); expect(analytics.wizardCapture).toHaveBeenCalledWith( STREAM_STALL_EVENT, @@ -392,6 +554,7 @@ describe('createStreamStallWatcher', () => { errorMessage: '401 authentication_error', }, }); + watcher.onEvent({ type: 'agent_end', willRetry: false }); expect(analytics.wizardCapture).not.toHaveBeenCalled(); }); @@ -399,6 +562,15 @@ describe('createStreamStallWatcher', () => { it('clears silence timer during retry backoff and handles thrown transport errors once', () => { const watcher = createWatcher(); watcher.onEvent({ type: 'turn_start' }); + watcher.onEvent({ + type: 'message_end', + message: { + role: 'assistant', + stopReason: 'error', + errorMessage: '429 rate limit exceeded', + }, + }); + watcher.onEvent({ type: 'agent_end', willRetry: true }); watcher.onEvent({ type: 'auto_retry_start' }); vi.advanceTimersByTime(DEFAULT_STREAM_SILENCE_MS * 2); expect(analytics.wizardCapture).not.toHaveBeenCalled(); diff --git a/src/agent/runner/harness/pi/__tests__/structured-run.test.ts b/src/agent/runner/harness/pi/__tests__/structured-run.test.ts index c9045fdef..7730903d1 100644 --- a/src/agent/runner/harness/pi/__tests__/structured-run.test.ts +++ b/src/agent/runner/harness/pi/__tests__/structured-run.test.ts @@ -183,6 +183,7 @@ vi.mock('@earendil-works/pi-coding-agent', () => ({ content: [], }, }); + state.listener?.({ type: 'agent_end', willRetry: false }); return Promise.resolve(); } if (!state.noTools) diff --git a/src/agent/runner/harness/pi/stream-stall.ts b/src/agent/runner/harness/pi/stream-stall.ts index fd6d719e8..fc86f2b68 100644 --- a/src/agent/runner/harness/pi/stream-stall.ts +++ b/src/agent/runner/harness/pi/stream-stall.ts @@ -6,11 +6,12 @@ * (default 120s) without a chunk — catches hangs even when the user hits * Ctrl+C before the gateway's 600s request deadline. * 2. `stage: 'failed'` when a turn ends on a mid-stream deadline/drop error - * (or any error after crossing the silence threshold). + * (or any error after crossing the silence threshold) and Pi is not going to + * auto-retry it (or retries end without recovering). * - * If a turn that triggered `silent` later finishes or is cancelled, a follow-up - * `stage: 'recovered'` or `stage: 'aborted'` event closes the loop so dashboards - * can separate real hangs from slow reasoning turns. + * If a turn that triggered `silent` later finishes (including on a retry) or is + * cancelled, a follow-up `stage: 'recovered'` or `stage: 'aborted'` event closes + * the loop so dashboards can separate real hangs from slow reasoning turns. */ import { analytics } from '@utils/analytics'; @@ -30,7 +31,20 @@ export type StreamStallErrorKind = | 'connection_reset' | 'other'; -type TurnState = 'idle' | 'waiting' | 'paused' | 'failed'; +type TurnState = + | 'idle' + | 'waiting' + | 'paused' + | 'pending_error' + | 'retrying' + | 'failed'; + +interface PendingFailure { + errorKind: StreamStallErrorKind; + errorMessage?: string; + idleMs: number; + turnElapsedMs: number; +} export interface StreamStallWatcherOptions { sequence: Sequence; @@ -48,6 +62,8 @@ export interface StreamStallEvent { message?: unknown; success?: boolean; aborted?: boolean; + willRetry?: boolean; + finalError?: string; } interface AssistantMessageShape { @@ -108,6 +124,7 @@ export function createStreamStallWatcher(opts: StreamStallWatcherOptions) { let chunksReceived = 0; let streamOpened = false; let silentReported = false; + let pendingFailure: PendingFailure | undefined; const clearTimer = () => { if (timer !== undefined) { @@ -124,16 +141,25 @@ export function createStreamStallWatcher(opts: StreamStallWatcherOptions) { chunksReceived = 0; streamOpened = false; silentReported = false; + pendingFailure = undefined; }; const report = ( stage: StreamStallStage, - extra?: { errorKind?: StreamStallErrorKind; errorMessage?: string }, + extra?: { + errorKind?: StreamStallErrorKind; + errorMessage?: string; + idleMs?: number; + turnElapsedMs?: number; + }, ) => { const ts = now(); - const idleMs = turnStartedAt > 0 ? Math.max(0, ts - lastActivityAt) : 0; + const idleMs = + extra?.idleMs ?? + (turnStartedAt > 0 ? Math.max(0, ts - lastActivityAt) : 0); const turnElapsedMs = - turnStartedAt > 0 ? Math.max(0, ts - turnStartedAt) : 0; + extra?.turnElapsedMs ?? + (turnStartedAt > 0 ? Math.max(0, ts - turnStartedAt) : 0); const truncatedError = extra?.errorMessage ? redactSecrets(extra.errorMessage).slice(0, 200) : undefined; @@ -170,6 +196,14 @@ export function createStreamStallWatcher(opts: StreamStallWatcherOptions) { }); }; + const flushPendingFailure = () => { + if (!pendingFailure) return; + const failure = pendingFailure; + pendingFailure = undefined; + turnState = 'failed'; + report('failed', failure); + }; + const armTimer = () => { clearTimer(); if ( @@ -195,6 +229,7 @@ export function createStreamStallWatcher(opts: StreamStallWatcherOptions) { switch (event.type) { case 'turn_start': { + const continuingRetry = turnState === 'retrying'; turnNumber += 1; turnState = 'waiting'; turnStartedAt = now(); @@ -202,7 +237,10 @@ export function createStreamStallWatcher(opts: StreamStallWatcherOptions) { turnStartActiveSessions = activePiSessions; chunksReceived = 0; streamOpened = false; - silentReported = false; + if (!continuingRetry) { + silentReported = false; + pendingFailure = undefined; + } armTimer(); break; } @@ -225,8 +263,11 @@ export function createStreamStallWatcher(opts: StreamStallWatcherOptions) { const msg = event.message as AssistantMessageShape | undefined; if (msg?.role !== 'assistant') break; clearTimer(); + const ts = now(); const idleMs = - turnStartedAt > 0 ? Math.max(0, now() - lastActivityAt) : 0; + turnStartedAt > 0 ? Math.max(0, ts - lastActivityAt) : 0; + const turnElapsedMs = + turnStartedAt > 0 ? Math.max(0, ts - turnStartedAt) : 0; if (msg.stopReason === 'error') { const errorKind = classifyStreamStallError(msg.errorMessage); @@ -235,11 +276,14 @@ export function createStreamStallWatcher(opts: StreamStallWatcherOptions) { silentReported || (thresholdMs > 0 && idleMs >= thresholdMs) ) { - turnState = 'failed'; - report('failed', { + // Hold the report until agent_end tells us whether Pi will auto-retry. + pendingFailure = { errorKind: errorKind ?? 'other', errorMessage: msg.errorMessage, - }); + idleMs, + turnElapsedMs, + }; + turnState = 'pending_error'; } else { resetToIdle(); } @@ -256,25 +300,39 @@ export function createStreamStallWatcher(opts: StreamStallWatcherOptions) { } break; } - case 'auto_retry_start': - case 'compaction_start': { - if (turnState === 'waiting') { + case 'auto_retry_start': { + if ( + turnState === 'waiting' || + turnState === 'pending_error' || + turnState === 'retrying' + ) { clearTimer(); - turnState = 'paused'; + turnState = 'retrying'; } break; } case 'auto_retry_end': { - if (turnState !== 'paused') break; if (event.success === false) { - resetToIdle(); - } else { + if (pendingFailure) { + flushPendingFailure(); + } else if (turnState !== 'failed') { + resetToIdle(); + } + } else if (turnState === 'retrying') { + pendingFailure = undefined; turnState = 'waiting'; lastActivityAt = now(); armTimer(); } break; } + case 'compaction_start': { + if (turnState === 'waiting') { + clearTimer(); + turnState = 'paused'; + } + break; + } case 'compaction_end': { if (turnState !== 'paused') break; if (event.aborted) { @@ -287,10 +345,17 @@ export function createStreamStallWatcher(opts: StreamStallWatcherOptions) { break; } case 'agent_end': { - if (turnState !== 'failed') { - resetToIdle(); - } else { + if (turnState === 'pending_error' && pendingFailure) { + if (event.willRetry) { + clearTimer(); + turnState = 'retrying'; + } else { + flushPendingFailure(); + } + } else if (turnState === 'failed') { clearTimer(); + } else { + resetToIdle(); } break; } @@ -304,6 +369,7 @@ export function createStreamStallWatcher(opts: StreamStallWatcherOptions) { clearTimer(); const errorKind = classifyStreamStallError(errorMessage); if (errorKind !== undefined || silentReported) { + pendingFailure = undefined; turnState = 'failed'; report('failed', { errorKind: errorKind ?? 'other', @@ -315,12 +381,18 @@ export function createStreamStallWatcher(opts: StreamStallWatcherOptions) { dispose(disposeOpts?: { cancelled?: boolean }): void { if (disposed) return; clearTimer(); - if ( - disposeOpts?.cancelled && - (turnState === 'waiting' || turnState === 'paused') && - silentReported - ) { - report('aborted'); + if (disposeOpts?.cancelled) { + if ( + (turnState === 'waiting' || + turnState === 'paused' || + turnState === 'retrying' || + turnState === 'pending_error') && + silentReported + ) { + report('aborted'); + } + } else if (turnState === 'pending_error' && pendingFailure) { + flushPendingFailure(); } resetToIdle(); disposed = true;