示例工程 58-agent-app-architecture
58-agent-app-architecture/demo-02-failure-policy/failures.ts
type Failure = {
id: string;
retryable: boolean;
maxAttempts: number;
action: "retry" | "wait" | "surface" | "abort" | "recover";
};
const FAILURES: Failure[] = [
{ id: "timeout", retryable: true, maxAttempts: 2, action: "retry" },
{ id: "rate-limit", retryable: true, maxAttempts: 3, action: "wait" },
{ id: "tool-error", retryable: false, maxAttempts: 1, action: "surface" },
{ id: "invalid-args", retryable: false, maxAttempts: 1, action: "surface" },
{ id: "cancel", retryable: false, maxAttempts: 0, action: "abort" },
{ id: "crash", retryable: true, maxAttempts: 1, action: "recover" },
];
function policy(id: string): Failure {
const row = FAILURES.find((failure) => failure.id === id);
if (!row) throw new Error(`UNKNOWN_FAILURE:${id}`);
return row;
}
function shouldRetry(id: string, attempt: number): boolean {
const row = policy(id);
return row.retryable && attempt < row.maxAttempts;
}
const timeout = policy("timeout");
const cancel = policy("cancel");
const crash = policy("crash");
const ok =
FAILURES.length === 6 &&
timeout.action === "retry" &&
shouldRetry("timeout", 0) &&
shouldRetry("timeout", 1) &&
!shouldRetry("timeout", 2) &&
shouldRetry("rate-limit", 2) &&
!shouldRetry("rate-limit", 3) &&
cancel.action === "abort" &&
!shouldRetry("cancel", 0) &&
crash.action === "recover" &&
shouldRetry("crash", 0) &&
!shouldRetry("tool-error", 0) &&
!shouldRetry("invalid-args", 0);
let unknown = "";
try {
policy("disk-full");
} catch (error) {
unknown = error instanceof Error ? error.message : String(error);
}
console.log(
JSON.stringify({
evt: "smoke",
ok: ok && unknown === "UNKNOWN_FAILURE:disk-full",
policies: FAILURES,
unknown,
}),
);