@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
123 lines • 6.33 kB
JavaScript
import { PROVIDER_NOT_CONFIGURED_PREFIX, sanitizeProviderDiagnostic, stripTurnRetrySuppressionPrefix, } from "@earendil-works/pi-ai";
import { transportTrustFailure } from "../engine-trust/transport-failure.js";
import { parseFallbackSelector } from "./retry-fallback/chains.js";
const ACTIONS = {
auth: { reason: "the provider rejected the credentials", action: "re-authenticate the provider" },
request_refused: {
reason: "the provider refused this request, but the same key worked moments ago, so it may still be valid",
action: "send the message again or choose another model; if it keeps failing, re-authenticate",
},
model_unavailable: {
reason: "the model is not available for this account",
action: "choose another model, or check that your plan or key includes this model",
},
rate_limit: { reason: "the provider is rate limiting requests", action: "retry later or set a fallback model" },
quota: { reason: "the provider account is out of quota", action: "check the plan or credits" },
context_limit: {
reason: "the conversation is larger than the model's context",
action: "compact or shorten the conversation",
},
invalid_request: {
reason: "the provider could not accept this request",
action: "send the message again; if it repeats, choose another model or start a new session",
},
provider_unavailable: { reason: "the provider is unavailable", action: "retry or switch provider" },
network: { reason: "the connection to the provider failed", action: "check connectivity" },
};
/** An `auth` failure on a credential that served a response moments before: the request was refused, not the key. */
export function isRequestLevelRefusal(message) {
return (message.credentialServedRecently === true &&
sanitizeProviderDiagnostic(message.providerDiagnostic)?.category === "auth");
}
/**
* The model the user selected for this turn: the original of an active fallback chain, else the
* session model (which stays the virtual model when one routes the request).
*/
export function selectedModelOf(originalSelector, lookup, sessionModel) {
const original = originalSelector === undefined ? undefined : parseFallbackSelector(originalSelector, lookup);
if (original !== undefined)
return { provider: original.provider, model: original.id };
return sessionModel === undefined ? undefined : { provider: sessionModel.provider, model: sessionModel.id };
}
export function describeProviderFailure(diagnostic, provider, options = {}) {
const category = options.requestRefused
? "request_refused"
: diagnostic?.category === "unknown" && diagnostic.httpStatus === 404
? "model_unavailable"
: (diagnostic?.category ?? "unknown");
const detail = category === "unknown"
? {
reason: "the provider returned an unexpected error",
action: "send the message again; if it repeats, choose another model",
}
: ACTIONS[category];
const resetsAt = diagnostic?.resetsAt;
return {
category,
provider,
...(options.model === undefined ? {} : { model: options.model }),
...(diagnostic?.httpStatus === undefined ? {} : { httpStatus: diagnostic.httpStatus }),
...(diagnostic?.code === undefined ? {} : { code: diagnostic.code }),
...(resetsAt === undefined ? {} : { resetsAt }),
...detail,
...(category === "request_refused" ? { action: `${detail.action} ${provider}` } : {}),
...(resetsAt === undefined
? {}
: {
reason: `${detail.reason} until ${new Date(resetsAt).toLocaleString("en-US", {
year: "numeric",
month: "short",
day: "numeric",
hour: "numeric",
minute: "2-digit",
timeZoneName: "short",
})}`,
}),
};
}
/**
* The failure of a turn whose last assistant message ended with `stopReason: "error"`.
* Absent on success and on abort.
*/
export function providerFailureOf(messages, selected) {
const last = messages.findLast((message) => message.role === "assistant");
if (last === undefined || last.role !== "assistant" || last.stopReason !== "error")
return undefined;
const diagnostic = sanitizeProviderDiagnostic(last.providerDiagnostic);
const described = notConfiguredFailure(last) ??
describeProviderFailure(diagnostic, last.provider, {
model: last.model,
requestRefused: isRequestLevelRefusal(last),
});
const trust = transportTrustFailure(diagnostic);
const failure = trust === undefined ? described : { ...described, trust };
if (selected === undefined || (selected.provider === last.provider && selected.model === last.model)) {
return failure;
}
return { ...failure, selectedProvider: selected.provider, selectedModel: selected.model };
}
/**
* No request was sent: auth resolution found no API key or sign-in for the provider and threw its sentinel.
* Without this the turn read as an `unknown` provider error with a resend step that cannot work (senpi#4329).
*/
function notConfiguredFailure(message) {
const text = stripTurnRetrySuppressionPrefix(message.errorMessage ?? "");
if (!text.startsWith(PROVIDER_NOT_CONFIGURED_PREFIX))
return undefined;
const provider = text.slice(PROVIDER_NOT_CONFIGURED_PREFIX.length).trim() || message.provider;
return {
category: "auth",
provider: message.provider,
model: message.model,
reason: `no API key or sign-in is saved for ${provider}`,
action: `connect ${provider} (sign in or add an API key), or choose another model`,
};
}
export function formatProviderFailure(failure) {
const route = failure.model === undefined ? failure.provider : `${failure.model} on ${failure.provider}`;
const selected = failure.selectedProvider === undefined || failure.selectedModel === undefined
? ""
: ` (selected: ${failure.selectedModel} on ${failure.selectedProvider})`;
return `${route}${selected} failed: ${failure.reason}. Action: ${failure.action}.`;
}
//# sourceMappingURL=provider-failure.js.map