@ -45,7 +45,6 @@ import {
extractObservedOverflowTokenCount ,
type FailoverReason ,
formatAssistantErrorText ,
formatBillingErrorMessage ,
isAuthAssistantError ,
isBillingAssistantError ,
isCompactionFailureError ,
@ -53,13 +52,11 @@ import {
isFailoverErrorMessage ,
isLikelyContextOverflowError ,
isRateLimitAssistantError ,
isTimeoutErrorMessage ,
parseImageDimensionError ,
parseImageSizeError ,
pickFallbackThinkingLevel ,
} from "../pi-embedded-helpers.js" ;
import { ensureRuntimePluginsLoaded } from "../runtime-plugins.js" ;
import { isLikelyMutatingToolName } from "../tool-mutation.js" ;
import { derivePromptTokens , normalizeUsage , type UsageLike } from "../usage.js" ;
import { redactRunIdentifier , resolveRunWorkspaceDir } from "../workspace-run.js" ;
import { runPostCompactionSideEffects } from "./compact.js" ;
@ -68,9 +65,11 @@ import { runContextEngineMaintenance } from "./context-engine-maintenance.js";
import { resolveGlobalLane , resolveSessionLane } from "./lanes.js" ;
import { log } from "./logger.js" ;
import { resolveModelAsync } from "./model.js" ;
import { handleAssistantFailover } from "./run/assistant-failover.js" ;
import { runEmbeddedAttempt } from "./run/attempt.js" ;
import { createEmbeddedRunAuthController } from "./run/auth-controller.js" ;
import { createFailoverDecisionLogger } from "./run/failover-observation.js" ;
import { mergeRetryFailoverReason , resolveRunFailoverDecision } from "./run/failover-policy.js" ;
import {
buildErrorAgentMeta ,
buildUsageAgentMetaFields ,
@ -83,8 +82,10 @@ import {
type RuntimeAuthState ,
scrubAnthropicRefusalMagic ,
} from "./run/helpers.js" ;
import { resolveIncompleteTurnPayloadText } from "./run/incomplete-turn.js" ;
import type { RunEmbeddedPiAgentParams } from "./run/params.js" ;
import { buildEmbeddedRunPayloads } from "./run/payloads.js" ;
import { handleRetryLimitExhaustion } from "./run/retry-limit.js" ;
import { resolveEffectiveRuntimeModel , resolveHookModelSelection } from "./run/setup.js" ;
import {
sessionLikelyHasOversizedToolResults ,
@ -449,44 +450,27 @@ export async function runEmbeddedPiAgent(
` provider= ${ provider } / ${ modelId } attempts= ${ runLoopIterations } ` +
` maxAttempts= ${ MAX_RUN_LOOP_ITERATIONS } ` ,
) ;
if (
fallbackConfigured &&
lastRetryFailoverReason &&
lastRetryFailoverReason !== "timeout" &&
lastRetryFailoverReason !== "model_not_found" &&
lastRetryFailoverReason !== "format" &&
lastRetryFailoverReason !== "session_expired"
) {
throw new FailoverError ( message , {
reason : lastRetryFailoverReason ,
const retryLimitDecision = resolveRunFailoverDecision ( {
stage : "retry_limit" ,
fallbackConfigured ,
failoverReason : lastRetryFailoverReason ,
} ) ;
return handleRetryLimitExhaustion ( {
message ,
decision : retryLimitDecision ,
provider ,
model : modelId ,
profileId : lastProfileId ,
durationMs : Date.now ( ) - started ,
agentMeta : buildErrorAgentMeta ( {
sessionId : params.sessionId ,
provider ,
model : modelId ,
profileId : lastProfileId ,
status : resolveFailoverStatus ( lastRetryFailoverReason ) ,
} ) ;
}
return {
payloads : [
{
text :
"Request failed after repeated internal retries. " +
"Please try again, or use /new to start a fresh session." ,
isError : true ,
} ,
] ,
meta : {
durationMs : Date.now ( ) - started ,
agentMeta : buildErrorAgentMeta ( {
sessionId : params.sessionId ,
provider ,
model : model.id ,
usageAccumulator ,
lastRunPromptUsage ,
lastTurnTotal ,
} ) ,
error : { kind : "retry_limit" , message } ,
} ,
} ;
model : model.id ,
usageAccumulator ,
lastRunPromptUsage ,
lastTurnTotal ,
} ) ,
} ) ;
}
runLoopIterations += 1 ;
const runtimeAuthRetry = authRetryPending ;
@ -1083,16 +1067,36 @@ export async function runEmbeddedPiAgent(
logFallbackDecision : logPromptFailoverDecision ,
} ) ;
}
let promptFailoverDecision = resolveRunFailoverDecision ( {
stage : "prompt" ,
aborted ,
fallbackConfigured ,
failoverFailure : promptFailoverFailure ,
failoverReason : promptFailoverReason ,
profileRotated : false ,
} ) ;
if (
promptFailoverFailure &&
promptFailoverReason !== "timeout" &&
promptFailoverDecision . action === "rotate_profile" &&
( await advanceAuthProfile ( ) )
) {
lastRetryFailoverReason = promptFailoverReason ? ? lastRetryFailoverReason ;
lastRetryFailoverReason = mergeRetryFailoverReason ( {
previous : lastRetryFailoverReason ,
failoverReason : promptFailoverReason ,
} ) ;
logPromptFailoverDecision ( "rotate_profile" ) ;
await maybeBackoffBeforeOverloadFailover ( promptFailoverReason ) ;
continue ;
}
if ( promptFailoverDecision . action === "rotate_profile" ) {
promptFailoverDecision = resolveRunFailoverDecision ( {
stage : "prompt" ,
aborted ,
fallbackConfigured ,
failoverFailure : promptFailoverFailure ,
failoverReason : promptFailoverReason ,
profileRotated : true ,
} ) ;
}
const fallbackThinking = pickFallbackThinkingLevel ( {
message : errorText ,
attempted : attemptedThinking ,
@ -1107,22 +1111,23 @@ export async function runEmbeddedPiAgent(
// Throw FailoverError for prompt-side failover reasons when fallbacks
// are configured so outer model fallback can continue on overload,
// rate-limit, auth, or billing failures.
if ( fallbackConfigured && promptFailoverFailure ) {
const status = resolveFailoverStatus ( promptFailoverReason ? ? "unknown" ) ;
if ( promptFailoverDecision . action === "fallback_model" ) {
const fallbackReason = promptFailoverDecision . reason ? ? "unknown" ;
const status = resolveFailoverStatus ( fallbackReason ) ;
logPromptFailoverDecision ( "fallback_model" , { status } ) ;
await maybeBackoffBeforeOverloadFailover ( promptFailoverReason ) ;
throw (
normalizedPromptFailover ? ?
new FailoverError ( errorText , {
reason : promptFailoverReason ? ? "unknown" ,
reason : fallbackReason ,
provider ,
model : modelId ,
profileId : lastProfileId ,
status : resolveFailoverStatus ( promptFailoverReason ? ? "unknown" ) ,
status ,
} )
) ;
}
if ( promptFailover Failure || promptFailoverReason ) {
if ( promptFailover Decision. action === "surface_error" ) {
logPromptFailoverDecision ( "surface_error" ) ;
}
throw promptError ;
@ -1194,120 +1199,54 @@ export async function runEmbeddedPiAgent(
) ;
}
// Rotate on timeout to try another account/model path in this turn,
// but exclude post-prompt compaction timeouts (model succeeded; no profile issue).
const shouldRotate =
( ! aborted && ( failoverFailure || assistantFailoverReason !== null ) ) ||
( timedOut && ! timedOutDuringCompaction ) ;
if ( shouldRotate ) {
if ( lastProfileId ) {
const reason = timedOut ? "timeout" : assistantProfileFailureReason ;
// Skip cooldown for timeouts: a timeout is model/network-specific,
// not an auth issue. Marking the profile would poison fallback models
// on the same provider (e.g. gpt-5.3 timeout blocks gpt-5.2).
await maybeMarkAuthProfileFailure ( {
profileId : lastProfileId ,
reason ,
modelId ,
} ) ;
if ( timedOut && ! isProbeSession ) {
log . warn ( ` Profile ${ lastProfileId } timed out. Trying next account... ` ) ;
}
if ( cloudCodeAssistFormatError ) {
log . warn (
` Profile ${ lastProfileId } hit Cloud Code Assist format error. Tool calls will be sanitized on retry. ` ,
) ;
}
}
// For overloaded errors, check the configured rotation cap *before*
// calling advanceAuthProfile() to avoid a wasted auth-profile setup
// cycle. advanceAuthProfile() runs applyApiKeyInfo() which
// initializes the next profile — costly work that is pointless when
// we already know we will escalate to cross-provider fallback.
// See: https://github.com/openclaw/openclaw/issues/58348
if ( assistantFailoverReason === "overloaded" ) {
overloadProfileRotations += 1 ;
if ( overloadProfileRotations > overloadProfileRotationLimit && fallbackConfigured ) {
const status = resolveFailoverStatus ( "overloaded" ) ;
log . warn (
` overload profile rotation cap reached for ${ sanitizeForLog ( provider ) } / ${ sanitizeForLog ( modelId ) } after ${ overloadProfileRotations } rotations; escalating to model fallback ` ,
) ;
logAssistantFailoverDecision ( "fallback_model" , { status } ) ;
throw new FailoverError (
"The AI service is temporarily overloaded. Please try again in a moment." ,
{
reason : "overloaded" ,
provider : activeErrorContext.provider ,
model : activeErrorContext.model ,
profileId : lastProfileId ,
status ,
} ,
) ;
}
}
// For rate-limit errors, apply the same rotation cap so that
// per-model quota exhaustion (e.g. Anthropic Sonnet-only limits)
// escalates to cross-provider model fallback instead of spinning
// forever across profiles that share the same model quota.
// See: https://github.com/openclaw/openclaw/issues/58572
if ( assistantFailoverReason === "rate_limit" ) {
maybeEscalateRateLimitProfileFallback ( {
failoverProvider : activeErrorContext.provider ,
failoverModel : activeErrorContext.model ,
logFallbackDecision : logAssistantFailoverDecision ,
} ) ;
}
const rotated = await advanceAuthProfile ( ) ;
if ( rotated ) {
lastRetryFailoverReason =
assistantFailoverReason ? ? ( timedOut ? "timeout" : null ) ? ? lastRetryFailoverReason ;
logAssistantFailoverDecision ( "rotate_profile" ) ;
await maybeBackoffBeforeOverloadFailover ( assistantFailoverReason ) ;
continue ;
}
if ( fallbackConfigured ) {
await maybeBackoffBeforeOverloadFailover ( assistantFailoverReason ) ;
// Prefer formatted error message (user-friendly) over raw errorMessage
const message =
( lastAssistant
? formatAssistantErrorText ( lastAssistant , {
cfg : params.config ,
sessionKey : params.sessionKey ? ? params . sessionId ,
provider : activeErrorContext.provider ,
model : activeErrorContext.model ,
} )
: undefined ) ||
lastAssistant ? . errorMessage ? . trim ( ) ||
( timedOut
? "LLM request timed out."
: rateLimitFailure
? "LLM request rate limited."
: billingFailure
? formatBillingErrorMessage (
activeErrorContext . provider ,
activeErrorContext . model ,
)
: authFailure
? "LLM request unauthorized."
: "LLM request failed." ) ;
const status =
resolveFailoverStatus ( assistantFailoverReason ? ? "unknown" ) ? ?
( isTimeoutErrorMessage ( message ) ? 408 : undefined ) ;
logAssistantFailoverDecision ( "fallback_model" , { status } ) ;
throw new FailoverError ( message , {
reason : assistantFailoverReason ? ? "unknown" ,
provider : activeErrorContext.provider ,
model : activeErrorContext.model ,
profileId : lastProfileId ,
status ,
} ) ;
}
logAssistantFailoverDecision ( "surface_error" ) ;
const assistantFailoverDecision = resolveRunFailoverDecision ( {
stage : "assistant" ,
aborted ,
fallbackConfigured ,
failoverFailure ,
failoverReason : assistantFailoverReason ,
timedOut ,
timedOutDuringCompaction ,
profileRotated : false ,
} ) ;
const assistantFailoverOutcome = await handleAssistantFailover ( {
initialDecision : assistantFailoverDecision ,
aborted ,
fallbackConfigured ,
failoverFailure ,
failoverReason : assistantFailoverReason ,
timedOut ,
timedOutDuringCompaction ,
assistantProfileFailureReason ,
lastProfileId ,
modelId ,
provider ,
activeErrorContext ,
lastAssistant ,
config : params.config ,
sessionKey : params.sessionKey ? ? params . sessionId ,
authFailure ,
rateLimitFailure ,
billingFailure ,
cloudCodeAssistFormatError ,
isProbeSession ,
overloadProfileRotations ,
overloadProfileRotationLimit ,
previousRetryFailoverReason : lastRetryFailoverReason ,
logAssistantFailoverDecision ,
warn : ( message ) = > log . warn ( message ) ,
maybeMarkAuthProfileFailure ,
maybeEscalateRateLimitProfileFallback ,
maybeBackoffBeforeOverloadFailover ,
advanceAuthProfile ,
} ) ;
overloadProfileRotations = assistantFailoverOutcome . overloadProfileRotations ;
if ( assistantFailoverOutcome . action === "retry" ) {
lastRetryFailoverReason = assistantFailoverOutcome . lastRetryFailoverReason ;
continue ;
}
if ( assistantFailoverOutcome . action === "throw" ) {
throw assistantFailoverOutcome . error ;
}
const usageMeta = buildUsageAgentMetaFields ( {
@ -1373,83 +1312,50 @@ export async function runEmbeddedPiAgent(
} ;
}
// Detect incomplete turns where prompt() resolved prematurely due to
// pi-agent-core's auto-retry timing issue: when a mid-turn 429/overload
// triggers an internal retry, waitForRetry() resolves on the next
// assistant message *before* tool execution completes in the retried
// loop (see #8643). The captured lastAssistant has a non-terminal
// stopReason (e.g. "toolUse") with no text content, producing empty
// payloads. Surface an error instead of silently dropping the reply.
//
// Exclusions:
// - didSendDeterministicApprovalPrompt: approval-prompt turns
// intentionally produce empty payloads with stopReason=toolUse
// - lastToolError: suppressed/recoverable tool failures also produce
// empty payloads with stopReason=toolUse; those are handled by
// buildEmbeddedRunPayloads' own warning policy
if (
payloads . length === 0 &&
! aborted &&
! timedOut &&
! attempt . clientToolCall &&
! attempt . yieldDetected &&
! attempt . didSendDeterministicApprovalPrompt &&
! attempt . lastToolError
) {
const incompleteStopReason = lastAssistant ? . stopReason ;
// Only trigger for non-terminal stop reasons (toolUse, etc.) to
// avoid false positives when the model legitimately produces no text.
// StopReason union: "aborted" | "error" | "length" | "toolUse"
// "toolUse" is the key signal that prompt() resolved mid-turn.
if ( incompleteStopReason === "toolUse" || incompleteStopReason === "error" ) {
log . warn (
` incomplete turn detected: runId= ${ params . runId } sessionId= ${ params . sessionId } ` +
` stopReason= ${ incompleteStopReason } payloads=0 — surfacing error to user ` ,
) ;
// Mark the failing profile for cooldown so multi-profile setups
// rotate away from the exhausted credential on the next turn.
if ( lastProfileId ) {
await maybeMarkAuthProfileFailure ( {
profileId : lastProfileId ,
reason : resolveAuthProfileFailureReason ( assistantFailoverReason ) ,
} ) ;
}
// Detect incomplete turns where prompt() resolved prematurely and the
// runner would otherwise drop an empty reply.
const incompleteTurnText = resolveIncompleteTurnPayloadText ( {
payloadCount : payloads.length ,
aborted ,
timedOut ,
attempt ,
} ) ;
if ( incompleteTurnText ) {
const incompleteStopReason = attempt . lastAssistant ? . stopReason ;
log . warn (
` incomplete turn detected: runId= ${ params . runId } sessionId= ${ params . sessionId } ` +
` stopReason= ${ incompleteStopReason } payloads=0 — surfacing error to user ` ,
) ;
// Warn about potential side-effects when the interrupted turn may
// already have mutated state or sent outbound actions.
const hadMutatingTools = attempt . toolMetas . some ( ( t ) = >
isLikelyMutatingToolName ( t . toolName ) ,
) ;
const hadPotentialSideEffects =
hadMutatingTools ||
attempt . didSendViaMessagingTool ||
( attempt . successfulCronAdds ? ? 0 ) > 0 ;
const errorText = hadPotentialSideEffects
? "⚠️ Agent couldn't generate a response. Note: some tool actions may have already been executed — please verify before retrying."
: "⚠️ Agent couldn't generate a response. Please try again." ;
// Mark the failing profile for cooldown so multi-profile setups
// rotate away from the exhausted credential on the next turn.
if ( lastProfileId ) {
await maybeMarkAuthProfileFailure ( {
profileId : lastProfileId ,
reason : resolveAuthProfileFailureReason ( assistantFailoverReason ) ,
} ) ;
}
return {
payloads : [
{
text : errorText ,
isError : true ,
} ,
] ,
meta : {
durationMs : Date.now ( ) - started ,
agentMeta ,
aborted ,
systemPromptReport : attempt.systemPromptReport ,
return {
payloads : [
{
text : incompleteTurnText ,
isError : true ,
} ,
didSendViaMessagingTool : attempt.didSendViaMessagingTool ,
didSendDeterministicApprovalPrompt : attempt.didSendDeterministicApprovalPrompt ,
messagingToolSentTexts : attempt.messagingToolSentTexts ,
messagingToolSentMediaUrls : attempt.messagingToolSentMediaUrls ,
messagingToolSentTargets : attempt.messagingToolSentTargets ,
successfulCronAdds : attempt.successfulCronAdds ,
} ;
}
] ,
meta : {
durationMs : Date.now ( ) - started ,
agentMeta ,
aborted ,
systemPromptReport : attempt.systemPromptReport ,
} ,
didSendViaMessagingTool : attempt.didSendViaMessagingTool ,
didSendDeterministicApprovalPrompt : attempt.didSendDeterministicApprovalPrompt ,
messagingToolSentTexts : attempt.messagingToolSentTexts ,
messagingToolSentMediaUrls : attempt.messagingToolSentMediaUrls ,
messagingToolSentTargets : attempt.messagingToolSentTargets ,
successfulCronAdds : attempt.successfulCronAdds ,
} ;
}
log . debug (