File size: 12,262 Bytes
4440aec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import { sanitizeForLog } from "../../../packages/terminal-core/src/ansi.js";
import {
  classifyOAuthRefreshFailure,
  classifyOAuthRefreshFailureError,
} from "../../agents/auth-profiles/oauth-refresh-failure.js";
import {
  isCompactionFailureError,
  isLikelyContextOverflowError,
} from "../../agents/embedded-agent-helpers.js";
import { findCliTimeoutError, isFailoverError } from "../../agents/failover-error.js";
import {
  GENERIC_EXTERNAL_RUN_FAILURE_TEXT,
  HEARTBEAT_EXTERNAL_RUN_FAILURE_TEXT,
  renderControlUiAgentFailureCopy,
  renderFailoverCodeUserCopy,
} from "../../agents/failover/user-copy.js";
import { isAgentHarnessPreflightError } from "../../agents/harness/errors.js";
import { LiveSessionModelSwitchError } from "../../agents/live-model-switch-error.js";
import { formatErrorMessage } from "../../infra/errors.js";
import { CommandLaneClearedError, GatewayDrainingError } from "../../process/command-queue.js";
import { defaultRuntime } from "../../runtime.js";
import type { ReplyPayload } from "../types.js";
import { createAgentLifecycleTerminalBackstop } from "./agent-lifecycle-terminal.js";
import { buildContextOverflowRecoveryText } from "./agent-runner-context-recovery.js";
import type { AgentTurnInternalResult, AgentTurnParams } from "./agent-runner-execution.types.js";
import {
  buildAuthProfileFailoverFailureText,
  buildExternalRunFailureReply,
  isNonDirectConversationContext,
  isVerboseFailureDetailEnabled,
  markAgentRunFailureReplyPayload,
  resolveExternalRunFailureTextForConversation,
  resolveReplyFailureSummary,
  resolveReplyFailoverFacts,
} from "./agent-runner-failure-reply.js";
import type { AgentFallbackCycleState } from "./agent-runner-fallback-cycle.js";
import type { AgentTurnTimingTracker } from "./agent-runner-turn-timing.js";
import {
  buildRestartLifecycleReplyText,
  resolveReplyOperationAbortReason,
  resolveReplyOperationTerminationFields,
  resolveRestartLifecycleError,
} from "./reply-operation-abort.js";

const MAX_LIVE_SWITCH_RETRIES = 2;

type ErrorAction =
  | { kind: "retry"; liveModelSwitchError?: LiveSessionModelSwitchError }
  | Extract<AgentTurnInternalResult, { kind: "final" | "aborted" }>;

export async function handleAgentExecutionError(params: {
  turn: AgentTurnParams;
  error: unknown;
  runtimeConfig: AgentTurnParams["followupRun"]["run"]["config"];
  runId: string;
  state: AgentFallbackCycleState;
  liveModelSwitchRetries: number;
  shouldSurfaceToControlUi: boolean;
  timing: AgentTurnTimingTracker;
  modelPatch: { fail: (error: unknown) => Promise<void> };
}): Promise<ErrorAction> {
  const turn = params.turn;
  const err = params.error;
  // A failed candidate leaves its backstop pending; settlement takes it before later work.
  // This keeps session-override failures from being mislabeled as model failures.
  const postCompactionModelFailure =
    params.state.postCompactionModelAttempted && params.state.pendingLifecycleTerminal
      ? true
      : undefined;
  const takePendingLifecycleTerminal = () => {
    const terminal =
      params.state.pendingLifecycleTerminal?.backstop ??
      createAgentLifecycleTerminalBackstop({
        runId: params.runId,
        sessionKey: turn.sessionKey,
        startedAt: params.state.turnStartedAtMs,
        getLifecycleGeneration: () => params.state.lifecycleGeneration,
        resolveTerminationFields: (error) =>
          resolveReplyOperationTerminationFields(
            error,
            turn.replyOperation?.abortSignal ?? turn.opts?.abortSignal,
            turn.replyOperation,
          ),
      });
    params.state.pendingLifecycleTerminal = undefined;
    return terminal;
  };
  const settleFailure = async (
    payload: ReplyPayload,
  ): Promise<Extract<AgentTurnInternalResult, { kind: "final" }>> => {
    takePendingLifecycleTerminal().emit("error", err);
    turn.replyOperation?.fail("run_failed", err);
    await params.modelPatch.fail(err);
    return {
      kind: "final",
      payload: markAgentRunFailureReplyPayload(payload),
      postCompactionModelFailure,
    };
  };
  const resolveReplyOperationAbortAction = (abortError: unknown): ErrorAction | undefined => {
    const reason = resolveReplyOperationAbortReason(turn.replyOperation, abortError);
    if (!reason) {
      return undefined;
    }
    // Preserve signal-owned timeout attribution; only normalized restart/supersession need metadata.
    const terminalMetadata = reason === "user" ? undefined : { aborted: true, stopReason: reason };
    takePendingLifecycleTerminal().emit(
      reason === "restart" ? "end" : "error",
      abortError,
      terminalMetadata,
    );
    return { kind: "aborted", reason };
  };
  const replyOperationAbortAction = resolveReplyOperationAbortAction(err);
  if (replyOperationAbortAction) {
    return replyOperationAbortAction;
  }
  if (err instanceof LiveSessionModelSwitchError) {
    if (params.liveModelSwitchRetries <= MAX_LIVE_SWITCH_RETRIES) {
      params.state.pendingLifecycleTerminal = undefined;
      return { kind: "retry", liveModelSwitchError: err };
    }
    const visibleReplyDelivered = await turn.resolveVisibleReplyDelivery?.();
    defaultRuntime.error(
      `Live model switch failed after ${MAX_LIVE_SWITCH_RETRIES} retries ` +
        `(${sanitizeForLog(err.provider)}/${sanitizeForLog(err.model)}). The requested model may be unavailable.`,
    );
    takePendingLifecycleTerminal().emit("error", err);
    const switchErrorText = params.shouldSurfaceToControlUi
      ? renderControlUiAgentFailureCopy(
          "model switch could not be completed. The requested model may be temporarily unavailable.",
        )
      : isVerboseFailureDetailEnabled(turn.resolvedVerboseLevel)
        ? "⚠️ Agent failed before reply: model switch could not be completed. " +
          "The requested model may be temporarily unavailable. Please try again shortly."
        : "⚠️ Model switch could not be completed. The requested model may be temporarily unavailable. Please try again shortly.";
    turn.replyOperation?.fail("run_failed", err);
    await params.modelPatch.fail(err);
    return {
      kind: "final",
      payload: markAgentRunFailureReplyPayload({
        text: resolveExternalRunFailureTextForConversation({
          text: switchErrorText,
          visibleReplyDelivered,
          sessionCtx: turn.sessionCtx,
          isGenericRunnerFailure: !params.shouldSurfaceToControlUi,
          cfg: turn.followupRun.run.config,
        }),
      }),
    };
  }
  const message = formatErrorMessage(err);
  params.timing.logIfSlow({
    runId: params.runId,
    sessionId: turn.followupRun.run.sessionId,
    sessionKey: turn.sessionKey,
    outcome: "error",
    error: message,
  });
  // The exhausted preflight is deliberate, even if its diagnostic cause looks
  // like HTTP/overload. Settle delivery and normal diagnostic policy without replay.
  if (isAgentHarnessPreflightError(err)) {
    const externalReply = buildExternalRunFailureReply(
      { message, error: err },
      {
        includeDetails: isVerboseFailureDetailEnabled(turn.resolvedVerboseLevel),
        isHeartbeat: turn.isHeartbeat,
      },
    );
    const text = resolveExternalRunFailureTextForConversation({
      text: params.shouldSurfaceToControlUi
        ? renderControlUiAgentFailureCopy(message)
        : externalReply.text,
      visibleReplyDelivered: await turn.resolveVisibleReplyDelivery?.(),
      sessionCtx: turn.sessionCtx,
      isGenericRunnerFailure: externalReply.isGenericRunnerFailure,
      cfg: turn.followupRun.run.config,
    });
    return await settleFailure({ text });
  }
  const failoverFacts = resolveReplyFailoverFacts(err, message);
  const failureSummary = resolveReplyFailureSummary({
    error: err,
    message,
    reason: failoverFacts.reason,
    attempts: isFailoverError(err) ? err.attempts : undefined,
  });
  const failoverReason = failoverFacts.reason;
  const isBilling = failureSummary?.kind === "billing";
  const isContextOverflow =
    !isBilling && (failoverReason === "context_overflow" || isLikelyContextOverflowError(message));
  const isCompactionFailure = !isBilling && isCompactionFailureError(message);
  const oauthRefreshFailure =
    classifyOAuthRefreshFailureError(err) ?? classifyOAuthRefreshFailure(message);
  const hasAuthProfileFailoverFailure = buildAuthProfileFailoverFailureText(err) !== null;
  const providerRequestError =
    !isBilling &&
    !oauthRefreshFailure &&
    !hasAuthProfileFailoverFailure &&
    !params.shouldSurfaceToControlUi
      ? failoverFacts.providerRequestError
      : undefined;
  const restartLifecycleError = resolveRestartLifecycleError(err);
  if (
    restartLifecycleError instanceof GatewayDrainingError ||
    restartLifecycleError instanceof CommandLaneClearedError
  ) {
    takePendingLifecycleTerminal().emit("error", restartLifecycleError);
    turn.replyOperation?.fail(
      restartLifecycleError instanceof GatewayDrainingError
        ? "gateway_draining"
        : "command_lane_cleared",
      restartLifecycleError,
    );
    return {
      kind: "final",
      payload: markAgentRunFailureReplyPayload({ text: buildRestartLifecycleReplyText() }),
    };
  }
  if (isCompactionFailure) {
    takePendingLifecycleTerminal().emit("error", err);
    defaultRuntime.error(
      `Auto-compaction failed (${message}). Preserving existing session mapping for ${turn.sessionKey ?? turn.followupRun.run.sessionId}.`,
    );
    turn.replyOperation?.fail("run_failed", err);
    return {
      kind: "final",
      payload: markAgentRunFailureReplyPayload({
        text: buildContextOverflowRecoveryText({
          duringCompaction: true,
          preserveSessionMapping: true,
          cfg: params.runtimeConfig,
          agentId: turn.followupRun.run.agentId,
          primaryProvider: turn.followupRun.run.provider,
          primaryModel: turn.followupRun.run.model,
          runtimeProvider: params.state.attemptedRuntimeProvider,
          runtimeModel: params.state.attemptedRuntimeModel,
          activeSessionEntry: turn.getActiveSessionEntry(),
        }),
      }),
    };
  }
  const replayPrevented = findCliTimeoutError(err)?.cliTimeout.observedActivity === true;
  if (providerRequestError) {
    return await settleFailure({
      // Curated facet copy beats the generic classified summary; see
      // buildExternalRunFailureReply for the same priority.
      text: providerRequestError.userMessage,
    });
  }
  defaultRuntime.error(`Embedded agent failed before reply: ${message}`);
  const externalRunFailureCandidate =
    !failureSummary && !isContextOverflow
      ? buildExternalRunFailureReply(
          { message, error: err },
          {
            includeAuthProfileId: !isNonDirectConversationContext(turn.sessionCtx),
            includeDetails: isVerboseFailureDetailEnabled(turn.resolvedVerboseLevel),
            isHeartbeat: turn.isHeartbeat,
            replayPrevented,
            failoverFacts,
          },
        )
      : undefined;
  const externalRunFailureReply =
    !params.shouldSurfaceToControlUi ||
    externalRunFailureCandidate?.presentation ||
    renderFailoverCodeUserCopy(failoverFacts.code)
      ? externalRunFailureCandidate
      : undefined;
  const fallbackText =
    failureSummary?.text ??
    (isContextOverflow
      ? "⚠️ Context overflow — prompt too large for this model. Try a shorter message or a larger-context model."
      : (externalRunFailureReply?.text ??
        (params.shouldSurfaceToControlUi
          ? renderControlUiAgentFailureCopy(message)
          : turn.isHeartbeat
            ? HEARTBEAT_EXTERNAL_RUN_FAILURE_TEXT
            : GENERIC_EXTERNAL_RUN_FAILURE_TEXT)));
  const userVisibleFallbackText = resolveExternalRunFailureTextForConversation({
    text: fallbackText,
    visibleReplyDelivered: await turn.resolveVisibleReplyDelivery?.(),
    sessionCtx: turn.sessionCtx,
    isGenericRunnerFailure: externalRunFailureReply?.isGenericRunnerFailure ?? false,
    cfg: turn.followupRun.run.config,
  });
  return await settleFailure({
    text: userVisibleFallbackText,
    ...(externalRunFailureReply?.presentation
      ? { presentation: externalRunFailureReply.presentation }
      : {}),
  });
}