File size: 2,461 Bytes
5c2a829
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { describe, expect, it } from "vitest";
import {
  type AuthProfileFailureReason,
  type AuthProfileStore,
  resolveProfilesUnavailableReason,
} from "./agent-runtime.js";

const cases = [
  {
    cooldownReason: "auth",
    cooldownClassification: "wham_token_expired",
    expected: "auth",
  },
  {
    cooldownReason: "auth_permanent",
    cooldownClassification: "wham_account_dead",
    expected: "auth_permanent",
  },
  {
    cooldownReason: "rate_limit",
    cooldownClassification: "wham_account_dead",
    expected: "rate_limit",
  },
] satisfies Array<{
  cooldownReason: AuthProfileFailureReason;
  cooldownClassification: NonNullable<
    NonNullable<AuthProfileStore["usageStats"]>[string]["cooldownClassification"]
  >;
  expected: AuthProfileFailureReason;
}>;

function preserveExhaustiveFailureReasonHandling(
  reason: AuthProfileFailureReason,
): AuthProfileFailureReason {
  switch (reason) {
    case "auth":
    case "auth_permanent":
    case "format":
    case "overloaded":
    case "rate_limit":
    case "billing":
    case "timeout":
    case "model_not_found":
    case "session_expired":
    case "empty_response":
    case "no_error_details":
    case "unclassified":
    case "unknown":
      return reason;
    default: {
      const exhaustive: never = reason;
      return exhaustive;
    }
  }
}

function consumeCanonicalReasonFromPublicStore(
  store: AuthProfileStore,
  profileId: string,
): AuthProfileFailureReason {
  const reason = store.usageStats?.[profileId]?.cooldownReason;
  if (!reason) {
    throw new Error("expected canonical cooldown reason");
  }
  return preserveExhaustiveFailureReasonHandling(reason);
}

describe("agent-runtime auth profile contract", () => {
  it.each(cases)(
    "keeps $cooldownReason canonical with $cooldownClassification diagnostics",
    ({ cooldownReason, cooldownClassification, expected }) => {
      const now = 1_700_000_000_000;
      const profileId = "openai:default";
      const store: AuthProfileStore = {
        version: 1,
        profiles: {},
        usageStats: {
          [profileId]: {
            cooldownUntil: now + 60_000,
            cooldownReason,
            cooldownClassification,
          },
        },
      };

      expect(consumeCanonicalReasonFromPublicStore(store, profileId)).toBe(expected);
      expect(resolveProfilesUnavailableReason({ store, profileIds: [profileId], now })).toBe(
        expected,
      );
    },
  );
});