Skip to content
pi-c Documentation
Login

Documentation

/* What a provider's refusal means for the key that sent it, and how pic says
 * so. See keyhealth.h. */
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <time.h>

#include "keyhealth.h"

/* ---- the vendors' words (data) ----------------------------------------------
 * A row matches when its status is 0 or the reply's, and its text is "" or
 * appears in the error body or message (any case). The first match wins; a
 * reply no row matches falls to its status: 429 by how long it says to wait,
 * 5xx transient, anything else other. */
typedef struct {
    int status;
    const char *text;
    pic_key_state state;
} kh_row;

static const kh_row kh_rows[] = {
    /* OpenAI: the quota is spent, sent as a 429 that waiting will not cure. */
    {0, "insufficient_quota", PIC_KEY_CREDIT},
    /* OpenAI: prepaid credit spent ("You have no credits remaining"), a 429 too. */
    {0, "credit_balance_exhausted", PIC_KEY_CREDIT},
    /* Anthropic: the spend limit set on the account, a 400 that says when access
     * comes back ("You will regain access on 2026-12-01 at 00:00 UTC"). */
    {0, "specified API usage limits", PIC_KEY_LIMITED},
    /* Anthropic: a billing error, and "Your credit balance is too low", seen as 400 and as 402. */
    {0, "billing_error", PIC_KEY_CREDIT},
    {0, "credit balance is too low", PIC_KEY_CREDIT},
    /* OpenRouter: 402 for spent credit or a key's limit (metadata.limit_source names which). */
    {402, "", PIC_KEY_CREDIT},
    /* The key itself refused. */
    {0, "authentication_error", PIC_KEY_INVALID},
    {0, "invalid_api_key", PIC_KEY_INVALID},
    {401, "", PIC_KEY_INVALID},
    {403, "", PIC_KEY_INVALID},
    /* Anthropic's overload. */
    {529, "", PIC_KEY_TRANSIENT},
    {0, "overloaded_error", PIC_KEY_TRANSIENT},
};

static int kh_has(const char *hay, const char *needle) {
    size_t n = strlen(needle);
    for (; *hay; hay++) {
        if (strncasecmp(hay, needle, n) == 0) {
            return 1;
        }
    }
    return 0;
}

/* "2026-11-18T11:26:40Z" (a fraction allowed, UTC only) as ms, or 0. */
static long long kh_rfc3339(const char *v) {
    struct tm tm;
    int y, mo, d, h, mi, consumed = 0;
    double sec;
    time_t t;
    if (sscanf(v, "%4d-%2d-%2dT%2d:%2d:%lf%n", &y, &mo, &d, &h, &mi, &sec, &consumed) != 6 ||
        (v[consumed] != 'Z' && v[consumed] != 'z')) {
        return 0;
    }
    memset(&tm, 0, sizeof tm);
    tm.tm_year = y - 1900;
    tm.tm_mon = mo - 1;
    tm.tm_mday = d;
    tm.tm_hour = h;
    tm.tm_min = mi;
    tm.tm_sec = 0;
    t = timegm(&tm);
    return t == (time_t)-1 ? 0 : (long long)t * 1000 + (long long)(sec * 1000.0 + 0.5);
}

/* "regain access on 2026-12-01 at 00:00 UTC" anywhere in TEXT, as ms, or 0. */
static long long kh_regain(const char *text) {
    static const char lead[] = "regain access on ";
    char at[32];
    int y, mo, d, h, mi;
    for (const char *p = text; p && *p; p++) {
        if (strncasecmp(p, lead, sizeof lead - 1) == 0 &&
            sscanf(p + sizeof lead - 1, "%4d-%2d-%2d at %2d:%2d UTC", &y, &mo, &d, &h, &mi) == 5) {
            (void)snprintf(at, sizeof at, "%04d-%02d-%02dT%02d:%02d:00Z", y, mo, d, h, mi);
            return kh_rfc3339(at);
        }
    }
    return 0;
}

/* OpenAI's "6m0s", "1s", "20ms", "1h2m3.5s" as ms, or -1. */
static long long kh_duration(const char *v) {
    double total = 0;
    int any = 0;
    while (*v && *v != '\n') {
        char *end;
        double n = strtod(v, &end);
        if (end == v) {
            return -1;
        }
        v = end;
        if (strncmp(v, "ms", 2) == 0) {
            total += n, v += 2;
        } else if (*v == 'h') {
            total += n * 3600000.0, v++;
        } else if (*v == 'm') {
            total += n * 60000.0, v++;
        } else if (*v == 's') {
            total += n * 1000.0, v++;
        } else {
            return -1;
        }
        any = 1;
    }
    return any ? (long long)(total + 0.5) : -1;
}

/* When the limit lifts, from Retry-After or the rate-limit header lines
 * (the latest reset named), as ms; 0 when nothing says. */
static long long kh_until(const char *ratelimit, const char *retry_after, long long now_ms) {
    long long until = 0;
    if (retry_after && *retry_after) {
        char *end;
        long secs = strtol(retry_after, &end, 10);
        if (*end == '\0' && secs >= 0) {
            return now_ms + secs * 1000LL;
        }
    }
    for (const char *line = ratelimit; line && *line;) {
        const char *nl = strchr(line, '\n');
        size_t n = nl ? (size_t)(nl - line) : strlen(line);
        char one[200], *colon;
        long long at = 0;
        (void)snprintf(one, sizeof one, "%.*s", (int)(n < sizeof one ? n : sizeof one - 1), line);
        if ((colon = strstr(one, ": "))) {
            const char *value = colon + 2;
            *colon = '\0';
            if (strncmp(one, "anthropic-ratelimit-", 20) == 0 && strlen(one) > 6 && strcmp(one + strlen(one) - 6, "-reset") == 0) {
                at = kh_rfc3339(value);
            } else if (strncmp(one, "x-ratelimit-reset-", 18) == 0) {
                long long ms = kh_duration(value);
                at = ms >= 0 ? now_ms + ms : 0;
            } else if (strcmp(one, "x-ratelimit-reset") == 0) { /* OpenRouter: ms since the epoch */
                at = strtoll(value, NULL, 10);
            }
        }
        if (at > until) {
            until = at;
        }
        line = nl ? nl + 1 : NULL;
    }
    return until;
}

void pic_keyhealth_classify(const char *provider, int status, const char *body, const char *message,
                            const char *ratelimit, const char *retry_after, long long now_ms, pic_key_health *h) {
    (void)provider;
    h->status = status;
    h->checked_ms = now_ms;
    h->until_ms = 0;
    (void)snprintf(h->reason, sizeof h->reason, "%.160s", message ? message : "");
    for (size_t i = 0; i < sizeof kh_rows / sizeof kh_rows[0]; i++) {
        const kh_row *r = &kh_rows[i];
        if ((r->status == 0 || r->status == status) &&
            (!*r->text || kh_has(body ? body : "", r->text) || kh_has(message ? message : "", r->text))) {
            h->state = r->state;
            if (h->state == PIC_KEY_LIMITED) { /* until the time the words name; none named, waiting will not help */
                long long until = kh_regain(message ? message : "");
                h->until_ms = until ? until : kh_regain(body ? body : "");
                h->state = h->until_ms > now_ms ? PIC_KEY_LIMITED : PIC_KEY_CREDIT;
                h->until_ms = h->state == PIC_KEY_LIMITED ? h->until_ms : 0;
            }
            return;
        }
    }
    if (status == 429) {
        long long until = kh_until(ratelimit, retry_after, now_ms);
        h->state = until - now_ms >= PIC_KEYHEALTH_LONG_MS ? PIC_KEY_LIMITED : PIC_KEY_TRANSIENT;
        h->until_ms = h->state == PIC_KEY_LIMITED ? until : 0;
    } else if (status >= 500) {
        h->state = PIC_KEY_TRANSIENT;
    } else {
        h->state = PIC_KEY_OTHER;
    }
}

/* ---- the words ------------------------------------------------------------- */

static void kh_clock(long long ms, long long now_ms, char *out, size_t cap) {
    time_t t = (time_t)(ms / 1000), now = (time_t)(now_ms / 1000);
    struct tm tm, today;
    (void)localtime_r(&t, &tm);
    (void)localtime_r(&now, &today);
    (void)strftime(out, cap, tm.tm_year == today.tm_year && tm.tm_yday == today.tm_yday ? "%H:%M" : "%Y-%m-%d %H:%M", &tm);
}

void pic_keyhealth_until(long long until_ms, long long now_ms, char *out, size_t cap) {
    char at[32];
    long long mins = (until_ms - now_ms + 59999) / 60000;
    kh_clock(until_ms, now_ms, at, sizeof at);
    if (mins >= 120) {
        (void)snprintf(out, cap, "%s (%lld h)", at, (mins + 30) / 60);
    } else {
        (void)snprintf(out, cap, "%s (%lld min)", at, mins < 1 ? 1 : mins);
    }
}

void pic_keyhealth_message(const char *provider, const char *label, const pic_key_health *h, long long now_ms, char *out,
                           size_t cap) {
    char why[200], until[48];
    (void)snprintf(why, sizeof why, "HTTP %d%s%.160s", h->status, h->reason[0] ? ": " : "", h->reason);
    switch (h->state) {
    case PIC_KEY_CREDIT:
        (void)snprintf(out, cap, "The key \"%s\" for %s is out of credit (%s).", label, provider, why);
        break;
    case PIC_KEY_INVALID:
        (void)snprintf(out, cap, "%s refused the key \"%s\" (%s).", provider, label, why);
        break;
    case PIC_KEY_LIMITED:
        pic_keyhealth_until(h->until_ms, now_ms, until, sizeof until);
        (void)snprintf(out, cap, "The key \"%s\" for %s is limited until %s (%s).", label, provider, until, why);
        break;
    default:
        (void)snprintf(out, cap, "%s", why);
    }
}

void pic_keyhealth_headline(const char *provider, const char *label, const pic_key_health *h, long long now_ms, char *out,
                            size_t cap) {
    char until[48];
    switch (h->state) {
    case PIC_KEY_CREDIT:
        (void)snprintf(out, cap, "The key \"%s\" is out of credit. Nothing was lost.", label);
        break;
    case PIC_KEY_INVALID:
        (void)snprintf(out, cap, "%s refused the key \"%s\" (HTTP %d).", provider, label, h->status);
        break;
    case PIC_KEY_LIMITED:
        pic_keyhealth_until(h->until_ms, now_ms, until, sizeof until);
        (void)snprintf(out, cap, "Limited until %s.", until);
        break;
    default:
        (void)snprintf(out, cap, "The key \"%s\" failed (HTTP %d). Nothing was lost.", label, h->status);
    }
}

const char *pic_keyhealth_offers(pic_key_state state, int have_other) {
    switch (state) {
    case PIC_KEY_INVALID:
        return have_other ? "sl" : "l";
    case PIC_KEY_LIMITED:
        return have_other ? "wsm" : "wm";
    default:
        return have_other ? "sm" : "m";
    }
}

int pic_keyhealth_bad(const pic_key_health *h, long long now_ms) {
    return h->state == PIC_KEY_INVALID || h->state == PIC_KEY_CREDIT || (h->state == PIC_KEY_LIMITED && h->until_ms > now_ms);
}

/* A failure a free check has said valid since: both facts, "valid ยท last request failed 03:20
 * (usage limit until Dec 1)". A limit a day or more away is named by its day. */
static void kh_failed_since(const pic_key_health *h, long long now_ms, char *out, size_t cap) {
    static const char *const months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
                                         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
    char at[32], what[64];
    kh_clock(h->checked_ms, now_ms, at, sizeof at);
    if (h->state == PIC_KEY_LIMITED && h->until_ms > now_ms) {
        if (h->until_ms - now_ms >= 24 * 3600000LL) {
            time_t t = (time_t)(h->until_ms / 1000);
            struct tm tm;
            (void)localtime_r(&t, &tm);
            (void)snprintf(what, sizeof what, "usage limit until %s %d", months[tm.tm_mon], tm.tm_mday);
        } else {
            char until[32];
            kh_clock(h->until_ms, now_ms, until, sizeof until);
            (void)snprintf(what, sizeof what, "limited until %s", until);
        }
    } else {
        (void)snprintf(what, sizeof what, "%s", h->state == PIC_KEY_CREDIT    ? "out of credit"
                                                : h->state == PIC_KEY_INVALID ? "refused"
                                                                              : "limited");
    }
    (void)snprintf(out, cap, "valid \xc2\xb7 last request failed %s (%s)", at, what);
}

void pic_keyhealth_phrase(const pic_key_health *h, long long now_ms, char *out, size_t cap) {
    char at[32];
    long long ago = (now_ms - h->checked_ms) / 60000;
    kh_clock(h->checked_ms, now_ms, at, sizeof at);
    if ((h->state == PIC_KEY_CREDIT || h->state == PIC_KEY_INVALID || h->state == PIC_KEY_LIMITED) &&
        h->valid_ms > h->checked_ms) {
        kh_failed_since(h, now_ms, out, cap);
        return;
    }
    switch (h->state) {
    case PIC_KEY_OK:
        if (h->has_remaining) {
            const char *unit = h->currency[0] ? h->currency : "$";
            (void)snprintf(out, cap, "%s%s%.2f left", unit, isalpha((unsigned char)unit[strlen(unit) - 1]) ? " " : "",
                           h->remaining);
        } else if (ago < 1) {
            (void)snprintf(out, cap, "valid, checked just now");
        } else if (ago < 120) {
            (void)snprintf(out, cap, "valid, checked %lld min ago", ago);
        } else {
            (void)snprintf(out, cap, "valid, checked %s", at);
        }
        break;
    case PIC_KEY_CREDIT: /* a free check's 200 that reports nothing left has no status to show */
    case PIC_KEY_INVALID: {
        char http[24] = "";
        if (h->status && h->status != 200) {
            (void)snprintf(http, sizeof http, " (HTTP %d)", h->status);
        }
        (void)snprintf(out, cap, "%s since %s%s", h->state == PIC_KEY_CREDIT ? "out of credit" : "refused", at, http);
        break;
    }
    case PIC_KEY_LIMITED:
        if (h->until_ms > now_ms) {
            char until[48];
            pic_keyhealth_until(h->until_ms, now_ms, until, sizeof until);
            (void)snprintf(out, cap, "limited until %s", until);
        } else {
            kh_clock(h->until_ms, now_ms, at, sizeof at);
            (void)snprintf(out, cap, "was limited until %s", at);
        }
        break;
    case PIC_KEY_OTHER: /* a free check that learnt nothing */
        if (h->status) {
            (void)snprintf(out, cap, "check failed (HTTP %d)", h->status);
        } else if (h->reason[0]) {
            (void)snprintf(out, cap, "check failed: %.120s", h->reason);
        } else {
            (void)snprintf(out, cap, "not checked yet");
        }
        break;
    default:
        (void)snprintf(out, cap, "not checked yet");
    }
}

void pic_keyhealth_alert(const pic_key_health *h, long long now_ms, char *out, size_t cap) {
    char at[32];
    out[0] = '\0';
    if (h->state == PIC_KEY_CREDIT) {
        (void)snprintf(out, cap, "! out of credit");
    } else if (h->state == PIC_KEY_INVALID) {
        (void)snprintf(out, cap, "! refused");
    } else if (h->state == PIC_KEY_LIMITED && h->until_ms > now_ms) {
        kh_clock(h->until_ms, now_ms, at, sizeof at);
        (void)snprintf(out, cap, "! limited until %s", at);
    }
}

const pic_cred_health_ops pic_keyhealth_ops = {pic_keyhealth_classify, pic_keyhealth_message, pic_keyhealth_headline,
                                               pic_keyhealth_offers,   pic_keyhealth_phrase,  pic_keyhealth_alert,
                                               pic_keyhealth_bad,      pic_keyhealth_until};