src/anthropic.js
Commit 01f96e7. All files · Download the tarball.
// Read-only calls to Anthropic's Admin API. Endpoints, params and response fields checked on 2026-11-16 against:
// https://docs.anthropic.com/en/api/usage-cost-api
// https://docs.anthropic.com/en/api/admin-api/usage-cost/get-messages-usage-report
// https://docs.anthropic.com/en/api/admin-api/apikeys/list-api-keys
// The base URL is fixed on purpose: the Admin key is only ever sent to api.anthropic.com.
export const API_BASE = "https://api.anthropic.com";
export const USER_AGENT = "LLMSpendTripwire/0.1.0";
const MAX_PAGES = 20;
export class ApiError extends Error {
constructor(status, message) { super(message); this.status = status; }
}
const iso = (minute) => new Date(minute * 60000).toISOString().replace(".000Z", "Z");
function headers(key, version) {
return { "x-api-key": key, "anthropic-version": version, "user-agent": USER_AGENT, accept: "application/json" };
}
async function getJson(fetchImpl, url, key, version) {
// redirect: "manual" so the Admin key is never re-sent to another host, even if a redirect is returned.
const res = await fetchImpl(url, { method: "GET", headers: headers(key, version), redirect: "manual" });
if (!res.ok) {
let detail = "";
try { const j = await res.json(); detail = (j && j.error && (j.error.type || "")) || ""; } catch { /* ignore body */ }
throw new ApiError(res.status, `Anthropic Admin API returned HTTP ${res.status}${detail ? ` (${detail})` : ""}`);
}
return res.json();
}
// Query string with literal [] in array params, as in Anthropic's examples.
function qs(params) {
const parts = [];
for (const [k, v] of params) parts.push(`${k}=${encodeURIComponent(v)}`);
return parts.join("&");
}
// Flatten one usage result into token counts by type.
export function tokensOf(r) {
const cc = r.cache_creation || {};
return {
uncached_input: Number(r.uncached_input_tokens) || 0,
cache_write_5m: Number(cc.ephemeral_5m_input_tokens) || 0,
cache_write_1h: Number(cc.ephemeral_1h_input_tokens) || 0,
cache_read: Number(r.cache_read_input_tokens) || 0,
output: Number(r.output_tokens) || 0,
};
}
// GET /v1/organizations/usage_report/messages, grouped by api_key_id and model.
// Returns rows: { minute, width, key, model, t: {token counts} }. `minute` is the bucket start (minutes since epoch).
export async function fetchUsage({ fetchImpl, key, version, startMin, endMin, width }) {
const per = width === "1h" ? 60 : 1;
const buckets = Math.ceil((endMin - startMin) / per);
const limit = Math.max(1, Math.min(width === "1h" ? 168 : 1440, buckets));
const rows = [];
let page = null;
for (let i = 0; i < MAX_PAGES; i++) {
const params = [
["starting_at", iso(startMin)], ["ending_at", iso(endMin)], ["bucket_width", width],
["group_by[]", "api_key_id"], ["group_by[]", "model"], ["limit", String(limit)],
];
if (page) params.push(["page", page]);
const body = await getJson(fetchImpl, `${API_BASE}/v1/organizations/usage_report/messages?${qs(params)}`, key, version);
for (const b of body.data || []) {
const minute = Math.floor(Date.parse(b.starting_at) / 60000);
if (!Number.isFinite(minute)) continue;
for (const r of b.results || []) {
rows.push({ minute, width: per, key: r.api_key_id || "none", model: r.model || "unknown", t: tokensOf(r) });
}
}
if (!body.has_more || !body.next_page) break;
page = body.next_page;
if (i === MAX_PAGES - 1) console.warn("tripwire: stopped after 20 pages");
}
return rows;
}
// GET /v1/organizations/api_keys?status=active. Returns [{ id, name, hint, created_at, created_by }].
export async function fetchActiveKeys({ fetchImpl, key, version }) {
const out = [];
let after = null;
for (let i = 0; i < MAX_PAGES; i++) {
const params = [["status", "active"], ["limit", "1000"]];
if (after) params.push(["after_id", after]);
const body = await getJson(fetchImpl, `${API_BASE}/v1/organizations/api_keys?${qs(params)}`, key, version);
for (const k of body.data || []) {
if (!k || !k.id) continue;
out.push({
id: k.id,
name: typeof k.name === "string" ? k.name : "",
hint: typeof k.partial_key_hint === "string" ? k.partial_key_hint : "",
created_at: k.created_at || "",
created_by: k.created_by && k.created_by.type ? `${k.created_by.type} ${k.created_by.id || ""}`.trim() : "",
});
}
if (!body.has_more || !body.last_id) break;
after = body.last_id;
if (i === MAX_PAGES - 1) console.warn("tripwire: stopped after 20 pages");
}
return out;
}