@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
170 lines • 7.26 kB
JavaScript
import { isRetryableErrorMessage } from "@earendil-works/pi-ai";
import { Text } from "@earendil-works/pi-tui";
import { z } from "zod";
import { keyText } from "./components/keybinding-hints.js";
import { sanitizeTuiErrorMessage } from "./extension-error-format.js";
import { isExcludedFromTurnRetry, isTurnRetryableFailure } from "../../core/turn-retry-eligibility.js";
import { describedProviderError } from "./provider-error-description.js";
import { providerErrorReason } from "./provider-error-reason.js";
import { theme } from "./theme/theme.js";
const envelope = z.object({
type: z.literal("error").optional(),
error: z.object({ type: z.string(), message: z.string() }),
});
const networkFailure = /network error|service unavailable|connection (?:error|lost|reset)|fetch failed|ECONNRESET|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|socket hang up|overloaded/i;
const otherFailure = /auth|api.?key|permission|quota|credit|billing|rate.?limit|too many requests|429/i;
/** Presentation classification only. Retry eligibility remains owned by AgentSession. */
export function isNetworkProviderError(raw, envelopeOnly = false) {
if (!raw || otherFailure.test(raw))
return false;
if (!envelopeOnly)
return networkFailure.test(raw);
try {
const parsed = envelope.safeParse(JSON.parse(raw));
return parsed.success && networkFailure.test(parsed.data.error.message);
}
catch (error) {
if (error instanceof SyntaxError)
return false;
throw error;
}
}
/**
* True when a provider failure should take the quiet presentation path (one banner, a
* status-line countdown while retrying, raw JSON only on expand): any transient failure,
* which is a network drop, a 429 rate-limit, or a 5xx. Hard quota/auth/billing failures
* classify non-retryable here and stay verbose, because they need a credential or plan
* change, not a wait. Delegates to the shared classifier so the transcript decision and
* the retry engine never disagree about what is transient.
*/
export function isRetryableProviderError(raw) {
if (!raw)
return false;
if (isNetworkProviderError(raw))
return true;
return isRetryableErrorMessage(raw);
}
/**
* True when a failed attempt's row belongs to the quiet retry episode instead of painting its raw error. It requires
* the retry engine's own decision (`isTurnRetryableFailure`, which excludes a suppressed replay, a local failure, a
* model-config failure and a context overflow) AND transient wording, so a row is folded only for a failure the
* engine retries (senpi#6012). A failure a classifier already describes in plain language keeps its row.
*/
export function isRetryableProviderMessage(message, session) {
if (message.stopReason !== "error" && message.stopReason !== "aborted")
return false;
const contextWindow = session?.model?.contextWindow ?? 0;
if (isExcludedFromTurnRetry(message, contextWindow))
return false;
if (isNetworkProviderError(message.errorMessage))
return true;
return (isTurnRetryableFailure(message, contextWindow) &&
isRetryableProviderError(message.errorMessage) &&
describedProviderError(message) === undefined);
}
/** True when the turn's last failed attempt belongs to an active quiet episode, which owes its one final notice. */
export function episodeOwnsFailure(messages, presentation, session) {
if (presentation?.hasActiveRetry !== true)
return false;
const last = messages.findLast((message) => message.role === "assistant");
return last?.role === "assistant" && isRetryableProviderMessage(last, session);
}
class ProviderFailureNotice {
constructor() {
this.details = new Set();
this.expanded = false;
this.summary = "The model provider may be having trouble.";
}
add(raw) {
this.details.add(raw);
}
setExpanded(expanded) {
this.expanded = expanded;
}
setSummary(summary) {
this.summary = summary;
}
render(width) {
const lines = [];
if (this.summary) {
lines.push(...new Text(theme.fg("warning", `${this.summary} (${keyText("app.tools.expand")} for details)`), 1, 0).render(width));
}
if (this.expanded) {
for (const raw of this.details) {
lines.push(...new Text(theme.fg("dim", sanitizeTuiErrorMessage(raw)), 1, 0).render(width));
}
}
return lines;
}
invalidate() { }
}
/** Owns one display episode, not session messages or retry/fallback policy. */
export class ProviderErrorPresentation {
constructor(chat) {
this.pending = false;
this.retryAwaitingFinish = false;
this.chat = chat;
}
record(raw, expanded = false) {
this.pending = true;
this.retryAwaitingFinish = true;
if (!this.notice) {
this.notice = new ProviderFailureNotice();
this.notice.setExpanded(expanded);
this.chat.addChild(this.notice);
}
this.notice.add(raw);
this.lastReason = providerErrorReason(raw) ?? this.lastReason;
}
retrying(raw, expanded) {
this.record(raw, expanded);
// RetryStatusIndicator owns the single visible transient row.
this.notice?.setSummary(undefined);
}
/** A success or cleanup ends the episode: no finish is owed afterward. */
clear() {
this.pending = false;
this.retryAwaitingFinish = false;
this.lastReason = undefined;
// Keep diagnostics reachable through the existing expansion affordance.
this.notice?.setSummary(undefined);
}
/**
* The retry engine finishing (summarization_retry_finished): clears the transient row but keeps
* the episode marker, because the terminal compaction_end that follows still closes the
* exhausted episode out via finish().
*/
clearTransient() {
this.pending = false;
this.notice?.setSummary(undefined);
}
/** True while a retry episode is active (a retry was recorded and not yet finished/cleared). */
get hasActiveRetry() {
return this.pending;
}
/**
* True only while a retry has been recorded in the CURRENT episode and not yet closed out by
* finish(). A fresh terminal failure after an episode that already finished returns false, so
* it surfaces as a plain error instead of reopening the stale banner.
*/
get awaitingRetryFinish() {
return this.retryAwaitingFinish;
}
finish(raw, attempts) {
if (raw)
this.record(raw);
if (!this.pending)
return;
this.pending = false;
this.retryAwaitingFinish = false;
const count = attempts === undefined ? "" : ` after ${attempts} retries`;
const reason = this.lastReason === undefined ? "" : ` (${this.lastReason})`;
this.notice?.setSummary(`The model provider could not complete the request${count}${reason}. Try again or choose another model with /model.`);
}
newTurn() {
this.finish();
this.notice = undefined;
this.lastReason = undefined;
}
}
//# sourceMappingURL=provider-error-presentation.js.map