Compare commits

...
9 changed files with 1038 additions and 425 deletions

No files matched your search

+2
View File
@@ -88,6 +88,8 @@ jobs:
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
GOOGLE_GENERATIVE_AI_API_KEY: ${{ secrets.GOOGLE_GENERATIVE_AI_API_KEY }}
XAI_API_KEY: ${{ secrets.XAI_API_KEY }}
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
CLOUDFLARE_WORKERS_AI_SYNC_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_WORKERS_AI_SYNC_ACCOUNT_ID }}
CLOUDFLARE_WORKERS_AI_SYNC_API_TOKEN: ${{ secrets.CLOUDFLARE_WORKERS_AI_SYNC_API_TOKEN }}
@@ -1,417 +1,14 @@
#!/usr/bin/env bun
//
// Regenerate the cloudflare-ai-gateway provider model TOMLs from Cloudflare's own sources,
// with human curation reduced to providers/cloudflare-ai-gateway/curation.toml.
//
// Scope: proxied third-party models only (anthropic, openai, google, xai, alibaba, deepseek,
// moonshotai, …). Cloudflare's own Workers AI (@cf/...) models are a different pathway — hosted
// on Cloudflare, CF-token auth, model agreements — and live in their own provider,
// providers/cloudflare-workers-ai, so they are deliberately not mirrored here.
//
// Source of truth (live):
// - GET /accounts/{id}/ai/catalog/models — canonical dotted model_id, name, description,
// context_length, max_output_tokens, and pricing (flat or context-tiered).
//
// curation.toml holds only what that source cannot express: structured_output (a quality
// judgement — Cloudflare advertises response_format broadly but several models do not honour
// it), reasoning_options (the catalog has no reasoning schema), limit divergences, and a skip
// list for catalog ids with no lab file (or not reachable via unified billing).
//
// Env: CLOUDFLARE_API_TOKEN, CLOUDFLARE_ACCOUNT_ID
// CF_AIG_FIXTURE_DIR (optional) — read cached catalog* JSON instead of the network.
//
// Usage:
// CLOUDFLARE_API_TOKEN=… CLOUDFLARE_ACCOUNT_ID=… bun run cloudflare-ai-gateway:generate
// bun run cloudflare-ai-gateway:generate --check # fail if the tree would change
import path from "node:path";
import { readdirSync, readFileSync, statSync, existsSync, rmSync } from "node:fs";
import { z } from "zod";
import { formatToml } from "../src/sync/index.ts";
import { syncProviderByID } from "../src/sync/index.js";
const PROVIDER_DIR = path.join(
import.meta.dirname, "..", "..", "..", "providers", "cloudflare-ai-gateway",
);
const MODELS_DIR = path.join(PROVIDER_DIR, "models");
const MODELS_ROOT = path.join(import.meta.dirname, "..", "..", "..", "models");
const CURATION_PATH = path.join(PROVIDER_DIR, "curation.toml");
const check = process.argv.includes("--check");
const result = await syncProviderByID("cloudflare-ai-gateway", { dryRun: check });
const TEXT_GENERATION = "Text Generation";
// Proxied providers that Cloudflare fronts with a *native* passthrough route rather than the
// gateway's generic OpenAI-compatible transform: Anthropic keeps the Messages API, OpenAI keeps
// the Responses API. Advertise each model's native SDK so consumers route to the endpoint that
// serves it best instead of falling back to the provider default (ai-gateway-provider). Other
// third-party providers Cloudflare only exposes over the compat route inherit that default.
// https://developers.cloudflare.com/ai-gateway/usage/providers/anthropic/
// https://developers.cloudflare.com/ai-gateway/usage/providers/openai/
const NATIVE_NPM: Record<string, string> = {
anthropic: "@ai-sdk/anthropic",
openai: "@ai-sdk/openai",
};
function nativeNpm(id: string): string | undefined {
return NATIVE_NPM[id.split("/")[0]!];
}
// ---------------------------------------------------------------------------
// curation.toml schema
// ---------------------------------------------------------------------------
const ReasoningOption = z.record(z.any());
const CuratedModel = z
.object({
base_model: z.string().min(1).optional(),
structured_output: z.boolean().optional(),
reasoning_options: z.array(ReasoningOption).optional(),
limit: z.record(z.number()).optional(),
interleaved: z
.union([z.literal(true), z.object({ field: z.enum(["reasoning_content", "reasoning_details"]) }).strict()])
.optional(),
// Leading `#` comment lines, e.g. a toggle/effort wire-path note (AGENTS.md requires one
// for every `toggle` reasoning option) or a source citation. Rendered verbatim above the
// generated fields so hand-verified host behavior survives every regeneration.
note: z.array(z.string()).optional(),
})
.strict();
const Curation = z
.object({
skip: z.array(z.string()).default([]),
models: z.record(CuratedModel).default({}),
})
.strict();
// ---------------------------------------------------------------------------
// Fetch (with fixture fallback)
// ---------------------------------------------------------------------------
async function fetchAllPages(url: string, token: string, perPage: number) {
const out: any[] = [];
for (let page = 1; page < 50; page++) {
const res = await fetch(`${url}?page=${page}&per_page=${perPage}`, {
headers: { Authorization: `Bearer ${token}` },
});
if (!res.ok) throw new Error(`Fetch failed ${res.status} ${res.statusText} for ${url}`);
const json: any = await res.json();
out.push(...(json.result ?? []));
const total = json.result_info?.total_count ?? out.length;
if (out.length >= total || (json.result ?? []).length === 0) break;
}
return out;
}
// Fetch with retry on 429/5xx. raw.githubusercontent.com rate-limits bursts, so honour
// Retry-After when present and otherwise back off exponentially. Returns the Response;
// callers decide how to treat a final !ok (throw vs. tolerate).
async function fetchWithRetry(url: string, init?: RequestInit, tries = 5): Promise<Response> {
let delay = 500;
for (let attempt = 1; ; attempt++) {
const res = await fetch(url, init);
if (res.ok || (res.status !== 429 && res.status < 500) || attempt >= tries) return res;
const retryAfter = Number(res.headers.get("retry-after"));
const wait = Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter * 1000 : delay;
await new Promise((r) => setTimeout(r, wait));
delay = Math.min(delay * 2, 8000);
}
}
// Run async tasks with bounded concurrency to avoid tripping rate limits.
async function mapLimit<T, R>(items: T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {
const results = new Array<R>(items.length);
let next = 0;
const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
while (true) {
const i = next++;
if (i >= items.length) break;
results[i] = await fn(items[i]!);
}
});
await Promise.all(workers);
return results;
}
// Load rows from every fixture file whose name starts with prefix, de-duplicated by their
// catalog model_id. Dedup guards against overlapping snapshot files inflating the model set.
function loadFixtureRows(dir: string, prefix: string): any[] {
const byId = new Map<string, any>();
for (const f of readdirSync(dir).filter((f) => f.startsWith(prefix) && f.endsWith(".json"))) {
for (const row of JSON.parse(readFileSync(path.join(dir, f), "utf8")).result ?? []) {
const key = row.model_id ?? row.name ?? JSON.stringify(row);
byId.set(key, row);
}
}
return [...byId.values()];
}
async function loadProxied() {
const fixtureDir = process.env.CF_AIG_FIXTURE_DIR;
if (fixtureDir) return loadFixtureRows(fixtureDir, "catalog");
const token = process.env.CLOUDFLARE_API_TOKEN;
const account = process.env.CLOUDFLARE_ACCOUNT_ID;
if (!token || !account) {
throw new Error(
"Set CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID (or CF_AIG_FIXTURE_DIR for offline runs).",
);
}
const base = `https://api.cloudflare.com/client/v4/accounts/${account}/ai`;
return fetchAllPages(`${base}/catalog/models`, token, 50);
}
// Load the per-model catalog schema for a proxied model. The list endpoint omits `schema`;
// the single-model schema endpoint returns schema.input, from which reasoning_options are
// derivable for OpenAI-compatible providers (xai, alibaba, openai). Providers whose schema
// is their native shape (google, anthropic, deepseek, moonshotai) return no reasoning
// property — those fall back to curation.toml. Returns schema.input or undefined.
async function loadCatalogSchemaInput(id: string): Promise<unknown> {
const fixtureDir = process.env.CF_AIG_FIXTURE_DIR;
if (fixtureDir) {
const p = path.join(fixtureDir, "schema", `${id.replace(/\//g, "_")}.json`);
if (!existsSync(p)) return undefined; // schema is optional per-model
return JSON.parse(readFileSync(p, "utf8")).result?.schema?.input;
}
const token = process.env.CLOUDFLARE_API_TOKEN!;
const account = process.env.CLOUDFLARE_ACCOUNT_ID!;
const res = await fetchWithRetry(
`https://api.cloudflare.com/client/v4/accounts/${account}/ai/catalog/models/${id}/schema`,
{ headers: { Authorization: `Bearer ${token}` } },
);
if (!res.ok) return undefined; // treat missing schema as "not derivable"
return ((await res.json()) as any).result?.schema?.input;
}
// Read the `reasoning` flag from a base lab file (models/<base>.toml). A base model that
// declares reasoning=true MUST carry reasoning_options in the provider file (schema validates
// this), so we hard-fail when neither the catalog schema nor curation can supply them.
function baseReasoning(base: string): boolean {
const p = path.join(MODELS_ROOT, `${base}.toml`);
if (!existsSync(p)) return false;
return (Bun.TOML.parse(readFileSync(p, "utf8")) as any).reasoning === true;
}
// ---------------------------------------------------------------------------
// Pricing → cost
// ---------------------------------------------------------------------------
const FLAT_KEYS: Record<string, string> = {
"Input tokens (per 1M)": "input",
"Output tokens (per 1M)": "output",
"Cached input tokens (per 1M)": "cache_read",
"Cache creation tokens (per 1M)": "cache_write",
};
const TIER_RE = /^(Input|Output|Cached input)\s*(<=?|>=?)\s*(\d+)k\s*\(per 1M\)$/;
const TIER_FIELD: Record<string, string> = {
Input: "input",
Output: "output",
"Cached input": "cache_read",
};
function proxiedCost(pricing: Record<string, number>, id: string, warnings: string[]) {
const base: Record<string, number> = {};
for (const [key, value] of Object.entries(pricing)) {
if (FLAT_KEYS[key]) {
base[FLAT_KEYS[key]] = value;
continue;
}
const m = key.match(TIER_RE);
if (m) {
const [, label, op] = m;
const field = TIER_FIELD[label!]!;
// Cloudflare AI Gateway entries don't carry tiered pricing (unsupported here). Fold the
// lower/default-context band (op "<") into the flat rate and drop the higher-context bands.
if (op!.startsWith("<")) base[field] = value;
continue;
}
warnings.push(`${id}: unmapped pricing key "${key}"`);
}
return { ...base };
}
// Derive reasoning_options from a docs schema.input by walking every named property.
function deriveReasoningOptions(schemaInput: unknown): Array<Record<string, unknown>> {
let hasToggle = false;
let effortValues: string[] | undefined;
const visit = (node: unknown) => {
if (Array.isArray(node)) {
node.forEach(visit);
return;
}
if (!node || typeof node !== "object") return;
for (const [key, value] of Object.entries(node as Record<string, unknown>)) {
if (key === "properties" && value && typeof value === "object") {
for (const [propName, propSchema] of Object.entries(value as Record<string, any>)) {
if (propName === "enable_thinking" || propName === "thinking") hasToggle = true;
if (propName === "effort" || propName === "reasoning_effort") {
let enumVals: string[] | undefined = propSchema?.enum;
if (!enumVals) {
for (const branch of [...(propSchema?.anyOf ?? []), ...(propSchema?.oneOf ?? [])]) {
if (Array.isArray(branch?.enum)) enumVals = branch.enum;
}
}
if (enumVals) effortValues = enumVals;
}
visit(propSchema);
}
} else {
visit(value);
}
}
};
visit(schemaInput);
const opts: Array<Record<string, unknown>> = [];
if (hasToggle) opts.push({ type: "toggle" });
if (effortValues) opts.push({ type: "effort", values: effortValues });
return opts;
}
// Prepend curated leading `#` comment lines (a toggle/effort wire-path note, a source
// citation, etc.) above the generated content. AGENTS.md requires one for every `toggle`
// reasoning option since sync strips mid-file comments on every regeneration.
function withNote(note: string[] | undefined, content: string): string {
if (!note || note.length === 0) return content;
return `${note.map((line) => `# ${line}`).join("\n")}\n\n${content}`;
}
// ---------------------------------------------------------------------------
// base_model resolution
// ---------------------------------------------------------------------------
function labFileExists(id: string): boolean {
return existsSync(path.join(MODELS_ROOT, `${id}.toml`));
}
function autoResolveBase(catalogId: string): string | null {
if (labFileExists(catalogId)) return catalogId;
const dashed = catalogId.replace(/\./g, "-");
if (labFileExists(dashed)) return dashed;
return null;
}
// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------
function walkToml(dir: string): string[] {
if (!existsSync(dir)) return [];
return readdirSync(dir).flatMap((e) => {
const p = path.join(dir, e);
return statSync(p).isDirectory() ? walkToml(p) : p.endsWith(".toml") ? [p] : [];
});
}
async function main() {
const check = process.argv.includes("--check");
const parsed = Curation.safeParse(Bun.TOML.parse(readFileSync(CURATION_PATH, "utf8")));
if (!parsed.success) {
console.error("Invalid curation.toml:", parsed.error.issues);
if (check) {
if (result.files.length > 0) {
console.error(`--check: ${result.files.length} file(s) out of date`);
process.exit(1);
}
const curation = parsed.data;
const skip = new Set(curation.skip);
const errors: string[] = [];
const warnings: string[] = [];
const proxied = await loadProxied();
const proxiedTextGen = proxied.filter((m) => m.task === TEXT_GENERATION);
const wanted = new Map<string, string>(); // absolute path -> content
// Fetch per-model schemas up front for the proxied models we'll actually emit, with bounded
// concurrency so the catalog/docs endpoints don't rate-limit us.
const proxiedEmit = proxiedTextGen.filter((m) => !skip.has(m.model_id));
const schemaInputs = new Map<string, unknown>();
await mapLimit(proxiedEmit, 6, async (m) => {
schemaInputs.set(m.model_id, await loadCatalogSchemaInput(m.model_id));
});
// --- proxied models ---
for (const m of proxiedTextGen) {
const id: string = m.model_id;
if (skip.has(id)) continue;
const cur = curation.models[id] ?? {};
const base = cur.base_model ?? autoResolveBase(id);
if (!base) {
errors.push(`proxied ${id}: no lab file and no curation base_model (add to skip or map it)`);
continue;
}
// name/description are inherited from base_model (models.dev's canonical copy);
// the catalog only carries Cloudflare's own casing/marketing variants.
const model: Record<string, unknown> = { base_model: base };
if (cur.structured_output !== undefined) model.structured_output = cur.structured_output;
if (cur.interleaved !== undefined) model.interleaved = cur.interleaved;
// reasoning_options: only meaningful when the base actually reasons. The catalog schema
// advertises reasoning_effort for some non-reasoning models (gpt-4.1, gpt-4o) — schema
// acceptance is not capability, so gate on the base's reasoning flag. When the base does
// reason, prefer the per-model catalog schema, then curation, and fail loudly if neither
// supplies a shape (the schema requires reasoning_options whenever reasoning=true).
if (baseReasoning(base)) {
const derivedRo = deriveReasoningOptions(schemaInputs.get(id));
if (cur.reasoning_options !== undefined) model.reasoning_options = cur.reasoning_options;
else if (derivedRo.length > 0) model.reasoning_options = derivedRo;
else {
errors.push(
`proxied ${id}: base ${base} has reasoning=true but no reasoning_options ` +
`(catalog schema exposes none; add reasoning_options to curation.toml)`,
);
continue;
}
}
const cost = proxiedCost(m.pricing ?? {}, id, warnings);
if (Object.keys(cost).length === 0) errors.push(`proxied ${id}: catalog pricing empty`);
model.cost = cost;
// limit.output: the catalog's max_output_tokens is not a reliable ceiling — verified wrong
// against lab/first-party for gpt-5, gpt-5.5, and claude-haiku-4.5 (all understated by
// 4-8x). Only context_length has checked out, so that's all we auto-derive; output is
// either curated explicitly or left to inherit from base_model.
const limit: Record<string, number> = {};
if (m.context_length != null) limit.context = m.context_length;
if (cur.limit) Object.assign(limit, cur.limit); // curation overrides/adds (e.g. served output)
if (Object.keys(limit).length) model.limit = limit;
const npm = nativeNpm(id);
if (npm) model.provider = { npm };
wanted.set(path.join(MODELS_DIR, `${id}.toml`), withNote(cur.note, formatToml(model as any)));
}
// Guards: a curation model id that no longer appears in the live feed (warn only).
const liveIds = new Set<string>(proxiedTextGen.map((m) => m.model_id));
for (const id of Object.keys(curation.models)) {
if (!liveIds.has(id)) warnings.push(`curation id not in live feed: ${id}`);
}
if (errors.length > 0) {
console.error("Errors:\n" + errors.map((e) => ` - ${e}`).join("\n"));
process.exit(1);
}
for (const w of warnings) console.warn(`warning: ${w}`);
const existing = new Set(walkToml(MODELS_DIR));
const wantedPaths = new Set(wanted.keys());
const toRemove = [...existing].filter((p) => !wantedPaths.has(p));
if (check) {
let changed = 0;
for (const [p, content] of wanted) {
const cur = existing.has(p) ? readFileSync(p, "utf8") : undefined;
if (cur !== content) { console.error(`would change: ${path.relative(MODELS_DIR, p)}`); changed++; }
}
for (const p of toRemove) { console.error(`would remove: ${path.relative(MODELS_DIR, p)}`); changed++; }
if (changed > 0) { console.error(`--check: ${changed} file(s) out of date`); process.exit(1); }
console.log("--check: up to date");
return;
}
let changed = 0;
for (const [p, content] of wanted) {
const cur = existing.has(p) ? readFileSync(p, "utf8") : undefined;
if (cur !== content) { await Bun.write(p, content); changed++; }
}
for (const p of toRemove) { rmSync(p); changed++; }
console.log(
`cloudflare-ai-gateway: ${wanted.size} proxied model(s) ` +
`(${changed} written/removed, ${skip.size} skipped, ${warnings.length} warning(s)).`,
);
console.log("--check: up to date");
}
await main();
+8
View File
@@ -55,6 +55,14 @@ export async function classifyAutoMerge(
if (created + deleted > MAX_MODEL_CHURN) {
reasons.push(`${created + deleted} models created or deleted (limit ${MAX_MODEL_CHURN})`);
}
if (
models.some((change) =>
change.status === "deleted"
&& change.path.startsWith("providers/cloudflare-ai-gateway/models/")
)
) {
reasons.push("Cloudflare AI Gateway model deletions require manual review");
}
const reasoningMetadata = async (path: string, loader: typeof load) => {
const model = Bun.TOML.parse(await loader(path)) as Record<string, unknown>;
+58 -12
View File
@@ -9,6 +9,7 @@ import { ambient } from "./providers/ambient.js";
import { anthropic } from "./providers/anthropic.js";
import { baseten } from "./providers/baseten.js";
import { chutes } from "./providers/chutes.js";
import { cloudflareAiGateway } from "./providers/cloudflare-ai-gateway.js";
import { cloudflareWorkersAi } from "./providers/cloudflare-workers-ai.js";
import { cortecs } from "./providers/cortecs.js";
import { crossmodel } from "./providers/crossmodel.js";
@@ -83,6 +84,8 @@ export interface SyncProvider<SourceModel> {
preserveSymlinks?: boolean;
preserveBaseModels?: boolean;
preserveDescriptions?: boolean;
/** Replace existing leading comments with translateModel.header. */
authoritativeHeaders?: boolean;
sameModel?(current: ExistingModel, desired: SyncedModel): boolean;
missingNotice?(paths: string[]): string[];
/**
@@ -104,9 +107,9 @@ export interface SyncProvider<SourceModel> {
model: SyncedModel;
metadata?: { id: string; model: SyncedMetadata };
/**
* Leading comment block for the written file when it has none of its own
* (e.g. the wire-path header every toggle reasoning control requires). A
* header already present on the existing file always wins.
* Leading comment block for the written file (e.g. the wire-path header
* every toggle reasoning control requires). Existing headers win unless
* authoritativeHeaders is enabled.
*/
header?: string;
} | undefined;
@@ -129,6 +132,7 @@ export const providers: {
anthropic: SyncProvider<any>;
baseten: SyncProvider<any>;
chutes: SyncProvider<any>;
"cloudflare-ai-gateway": SyncProvider<any>;
"cloudflare-workers-ai": SyncProvider<any>;
cortecs: SyncProvider<any>;
crossmodel: SyncProvider<any>;
@@ -162,6 +166,7 @@ export const providers: {
anthropic,
baseten,
chutes,
"cloudflare-ai-gateway": cloudflareAiGateway,
"cloudflare-workers-ai": cloudflareWorkersAi,
cortecs,
crossmodel,
@@ -209,7 +214,7 @@ export const groups = {
"openrouter",
"vercel",
],
cloudflare: ["cloudflare-workers-ai"],
cloudflare: ["cloudflare-ai-gateway", "cloudflare-workers-ai"],
direct: ["ambient", "anthropic", "baseten", "chutes", "cortecs", "deepinfra", "digitalocean", "github-copilot", "google", "hyper", "openai", "ovhcloud", "pioneer", "tinfoil", "venice", "wandb", "xai"],
} as const;
@@ -235,7 +240,11 @@ export async function syncProvider<SourceModel>(
const { models: existing, brokenSymlinks } = existingState;
let { modelMetadata } = existingState;
const sourceModels = provider.parseModels(await provider.fetchModels());
const desired = new Map<string, { model: z.infer<typeof SyncedAuthoredModel>; content: string }>();
const desired = new Map<string, {
model: z.infer<typeof SyncedAuthoredModel>;
content: string;
header: string;
}>();
const caseNormalizedDesiredPaths = new Map<string, string>();
const desiredMetadata = new Map<string, { model: z.infer<typeof ModelMetadata>; content: string }>();
const skippedRemote: string[] = [];
@@ -325,9 +334,16 @@ export async function syncProvider<SourceModel>(
throw parsed.error;
}
const translatedHeader = translated.header === undefined
? undefined
: leadingComments(translated.header);
const header = provider.authoritativeHeaders
? translatedHeader ?? ""
: (existing.get(relativePath)?.header || translatedHeader) ?? "";
desired.set(relativePath, {
model: parsed.data,
content: ((existing.get(relativePath)?.header || translated.header) ?? "") + formatToml(parsed.data),
content: header + formatToml(parsed.data),
header,
});
}
@@ -336,7 +352,7 @@ export async function syncProvider<SourceModel>(
const metadataDir = modelMetadataDir(provider.modelsDir);
for (const [relativePath, file] of desiredMetadata) {
const filePath = path.join(metadataDir, relativePath);
const filePath = await safeWritePath(metadataDir, relativePath);
const currentFile = Bun.file(filePath);
const currentText = await currentFile.exists() ? await currentFile.text() : undefined;
const current = currentText !== undefined
@@ -367,7 +383,7 @@ export async function syncProvider<SourceModel>(
console.log(`Skipping metadata removal in new-only mode: ${relativePath}`);
continue;
}
const filePath = path.join(metadataDir, relativePath);
const filePath = await safeWritePath(metadataDir, relativePath);
files.push({ status: "deleted", path: filePath });
if (options.dryRun) {
console.log(`Would remove metadata ${relativePath}`);
@@ -378,7 +394,7 @@ export async function syncProvider<SourceModel>(
}
for (const [relativePath, file] of desired) {
const filePath = path.join(provider.modelsDir, relativePath);
const filePath = await safeWritePath(provider.modelsDir, relativePath, true);
const current = existing.get(relativePath);
if (current === undefined) {
@@ -398,7 +414,12 @@ export async function syncProvider<SourceModel>(
continue;
}
if (!(provider.sameModel?.(current.authored, file.model) ?? sameModel(relativePath, current.authored, file.model))) {
const headerChanged = provider.authoritativeHeaders && current.header !== file.header;
if (
headerChanged
|| !(provider.sameModel?.(current.authored, file.model)
?? sameModel(relativePath, current.authored, file.model))
) {
if (options.newOnly) {
unchanged++;
continue;
@@ -431,7 +452,7 @@ export async function syncProvider<SourceModel>(
continue;
}
const filePath = path.join(provider.modelsDir, relativePath);
const filePath = await safeWritePath(provider.modelsDir, relativePath, true);
files.push({ status: "deleted", path: filePath });
if (options.dryRun) {
console.log(`Would remove ${relativePath}`);
@@ -602,6 +623,31 @@ async function isSymlink(filePath: string) {
}
}
async function safeWritePath(root: string, relativePath: string, allowLeafSymlink = false) {
const resolvedRoot = path.resolve(root);
const target = path.resolve(resolvedRoot, relativePath);
const relative = path.relative(resolvedRoot, target);
if (relative === "" || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
throw new Error(`Refusing to sync path outside ${root}: ${relativePath}`);
}
if (await isSymlink(resolvedRoot)) {
throw new Error(`Refusing to sync through symlink: ${resolvedRoot}`);
}
let current = resolvedRoot;
for (const segment of path.relative(resolvedRoot, path.dirname(target)).split(path.sep)) {
if (segment === "") continue;
current = path.join(current, segment);
if (await isSymlink(current)) {
throw new Error(`Refusing to sync through symlink: ${current}`);
}
}
if (!allowLeafSymlink && await isSymlink(target)) {
throw new Error(`Refusing to sync through symlink: ${target}`);
}
return target;
}
async function readModelMetadata(modelsDir: string) {
const metadataDir = modelMetadataDir(modelsDir);
const result: Record<string, Record<string, unknown>> = {};
@@ -829,7 +875,7 @@ async function writeReport(target: string, results: SyncResult[]) {
}
}
lines.push("", "This PR was created automatically by the daily model sync workflow.");
lines.push("", "This PR was created automatically by the model sync workflow.");
await Bun.write(".sync/model-sync-report.md", `${lines.join("\n")}\n`);
}
@@ -0,0 +1,502 @@
import { existsSync, readFileSync, readdirSync } from "node:fs";
import path from "node:path";
import { z } from "zod";
import { ReasoningOption } from "../../schema.js";
import type { ExistingModel, SyncProvider, SyncedBaseModel } from "../index.js";
const API_BASE = "https://api.cloudflare.com/client/v4/accounts";
const PROVIDER_DIR = path.join(
import.meta.dirname,
"..",
"..",
"..",
"..",
"..",
"providers",
"cloudflare-ai-gateway",
);
const MODELS_ROOT = path.join(import.meta.dirname, "..", "..", "..", "..", "..", "models");
const CURATION_PATH = path.join(PROVIDER_DIR, "curation.toml");
const TEXT_GENERATION = "Text Generation";
const REQUEST_TIMEOUT_MS = 30_000;
const MAX_CATALOG_PAGES = 1_000;
const MAX_BACKOFF_DELAY_MS = 8_000;
const MAX_RETRY_DELAY_MS = 60_000;
const NATIVE_NPM: Record<string, string> = {
anthropic: "@ai-sdk/anthropic",
openai: "@ai-sdk/openai",
};
const CatalogEntry = z.object({
model_id: z.string().refine(isSafeModelID, "model_id must be a safe relative provider/model path"),
task: z.string(),
context_length: z.number().int().positive().nullish(),
pricing: z.record(z.number().nonnegative()).nullish(),
}).passthrough();
const CatalogModel = CatalogEntry.extend({
task: z.literal(TEXT_GENERATION),
context_length: z.number().int().positive().nullish(),
pricing: z.record(z.number().nonnegative()),
});
const CloudflareResponse = z.object({
success: z.literal(true),
result: z.array(CatalogEntry),
result_info: z.object({
page: z.number().int().positive(),
per_page: z.number().int().positive(),
total_count: z.number().int().nonnegative(),
total_pages: z.number().int().positive().optional(),
count: z.number().int().nonnegative().optional(),
}).passthrough(),
}).passthrough();
const SourceModel = z.object({
catalog: CatalogModel,
schemaInput: z.unknown().optional(),
});
const CuratedModel = z.object({
base_model: z.string().refine(isSafeModelID, "base_model must be a safe relative provider/model path").optional(),
structured_output: z.boolean().optional(),
reasoning_options: z.array(ReasoningOption).optional(),
limit: z.object({
context: z.number().optional(),
input: z.number().optional(),
output: z.number().optional(),
}).strict().optional(),
interleaved: z.union([
z.literal(true),
z.object({ field: z.enum(["reasoning_content", "reasoning_details"]) }).strict(),
]).optional(),
note: z.array(z.string().refine((value) => !/[\r\n]/.test(value))).optional(),
}).strict();
const Curation = z.object({
skip: z.array(z.string()).default([]),
models: z.record(CuratedModel).default({}),
}).strict();
type CatalogModel = z.infer<typeof CatalogModel>;
type CatalogEntry = z.infer<typeof CatalogEntry>;
type SourceModel = z.infer<typeof SourceModel>;
type CuratedModel = z.infer<typeof CuratedModel>;
const curation = Curation.parse(Bun.TOML.parse(readFileSync(CURATION_PATH, "utf8")));
const skippedModels = new Set(curation.skip);
export const cloudflareAiGateway = {
id: "cloudflare-ai-gateway",
name: "Cloudflare AI Gateway",
modelsDir: "providers/cloudflare-ai-gateway/models",
preserveDescriptions: false,
authoritativeHeaders: true,
async fetchModels() {
const catalog = CatalogEntry.array().parse(await loadCatalog());
const catalogIDs = new Set(catalog.map((model) => model.model_id));
if (catalogIDs.size !== catalog.length) {
throw new Error("Cloudflare AI Gateway catalog returned duplicate model IDs");
}
const textModels = catalog.filter((model) => model.task === TEXT_GENERATION);
if (textModels.length === 0) {
throw new Error("Cloudflare AI Gateway catalog returned no Text Generation models");
}
const emittedModels = textModels.filter(
(model) => !model.model_id.startsWith("@cf/") && !skippedModels.has(model.model_id),
).map((model) => CatalogModel.parse(model));
if (emittedModels.length === 0) {
throw new Error("Cloudflare AI Gateway catalog returned no eligible proxied models");
}
const sources = await mapLimit(emittedModels, 6, async (model) => ({
catalog: model,
schemaInput: await loadCatalogSchemaInput(model.model_id),
}));
const liveIDs = new Set(textModels.map((model) => model.model_id));
for (const id of Object.keys(curation.models)) {
if (!liveIDs.has(id)) console.warn(`warning: curation id not in live feed: ${id}`);
}
return sources;
},
parseModels(raw) {
return SourceModel.array().parse(raw);
},
translateModel(source, context) {
const id = source.catalog.model_id;
const curated = curation.models[id] ?? {};
return {
id,
model: buildCloudflareAiGatewayModel(
source.catalog,
source.schemaInput,
curated,
context.authored(id),
),
header: noteHeader(curated.note),
};
},
} satisfies SyncProvider<SourceModel>;
export function buildCloudflareAiGatewayModel(
catalog: CatalogModel,
schemaInput: unknown,
curated: CuratedModel = {},
existing?: ExistingModel,
): SyncedBaseModel {
const id = catalog.model_id;
const baseModel = curated.base_model ?? resolveBaseModel(id);
if (baseModel === undefined) {
throw new Error(`${id}: no lab file and no curated base_model; add it to skip or map it`);
}
const model: SyncedBaseModel = { base_model: baseModel };
if (curated.structured_output !== undefined) {
model.structured_output = curated.structured_output;
}
if (curated.interleaved !== undefined) model.interleaved = curated.interleaved;
if (baseReasoning(baseModel)) {
const derived = deriveReasoningOptions(schemaInput);
const reasoningOptions = curated.reasoning_options ?? (derived.length > 0 ? derived : undefined);
if (reasoningOptions === undefined) {
throw new Error(
`${id}: base ${baseModel} reasons but the catalog schema and curation provide no reasoning_options`,
);
}
model.reasoning_options = reasoningOptions;
}
model.cost = proxiedCost(catalog.pricing, id);
const limit = {
...(catalog.context_length == null && existing?.limit?.context === undefined
? {}
: { context: catalog.context_length ?? existing?.limit?.context }),
...curated.limit,
};
if (Object.keys(limit).length > 0) model.limit = limit;
const npm = NATIVE_NPM[id.split("/")[0]!];
if (npm !== undefined) model.provider = { npm };
return model;
}
export function deriveReasoningOptions(
schemaInput: unknown,
): NonNullable<SyncedBaseModel["reasoning_options"]> {
let hasToggle = false;
let effortValues: Array<"none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max" | "default">
| undefined;
const EffortValues = z.array(z.enum([
"none",
"minimal",
"low",
"medium",
"high",
"xhigh",
"max",
"default",
]));
const visit = (node: unknown) => {
if (Array.isArray(node)) {
node.forEach(visit);
return;
}
if (node === null || typeof node !== "object") return;
for (const [key, value] of Object.entries(node)) {
if (key !== "properties" || value === null || typeof value !== "object") {
visit(value);
continue;
}
for (const [property, rawSchema] of Object.entries(value)) {
const propertySchema = rawSchema as Record<string, unknown>;
if (property === "enable_thinking" || property === "thinking") hasToggle = true;
if (property === "effort" || property === "reasoning_effort") {
const candidates = [propertySchema, ...arrayValue(propertySchema.anyOf), ...arrayValue(propertySchema.oneOf)];
for (const candidate of candidates) {
const parsed = EffortValues.safeParse(candidate.enum);
if (parsed.success) effortValues = parsed.data;
}
}
visit(rawSchema);
}
}
};
visit(schemaInput);
const options: NonNullable<SyncedBaseModel["reasoning_options"]> = [];
if (hasToggle) options.push({ type: "toggle" });
if (effortValues !== undefined) options.push({ type: "effort", values: effortValues });
return options;
}
function arrayValue(value: unknown): Array<Record<string, unknown>> {
return Array.isArray(value)
? value.filter((item): item is Record<string, unknown> => item !== null && typeof item === "object")
: [];
}
async function loadCatalog() {
const fixtureDir = process.env.CF_AIG_FIXTURE_DIR;
if (fixtureDir !== undefined) return loadFixtureRows(fixtureDir, "catalog");
const { accountID, token } = credentials();
const pages: Array<z.infer<typeof CloudflareResponse>> = [];
for (let page = 1; page <= MAX_CATALOG_PAGES; page++) {
const url = new URL(`${API_BASE}/${accountID}/ai/catalog/models`);
url.searchParams.set("page", String(page));
url.searchParams.set("per_page", "50");
const { response, json } = await fetchJsonWithRetry(url, { headers: { Authorization: `Bearer ${token}` } });
if (!response.ok) {
throw new Error(`Cloudflare AI Gateway catalog request failed: ${response.status} ${response.statusText}`);
}
const body = CloudflareResponse.parse(json);
pages.push(body);
const expectedPages = catalogPageCount(pages[0]!);
if (expectedPages > MAX_CATALOG_PAGES) throw new Error(`Invalid Cloudflare AI Gateway catalog page count: ${expectedPages}`);
if (page === expectedPages) return validateCatalogPages(pages, "Cloudflare AI Gateway catalog");
}
throw new Error("Cloudflare AI Gateway catalog exceeded the pagination safety limit");
}
async function loadCatalogSchemaInput(id: string): Promise<unknown> {
const fixtureDir = process.env.CF_AIG_FIXTURE_DIR;
if (fixtureDir !== undefined) {
const file = path.join(fixtureDir, "schema", `${id.replaceAll("/", "_")}.json`);
if (!existsSync(file)) return undefined;
return z.object({
success: z.literal(true),
result: z.object({ schema: z.object({ input: z.unknown().optional() }).passthrough() }).passthrough(),
}).passthrough().parse(JSON.parse(readFileSync(file, "utf8"))).result.schema.input;
}
const { accountID, token } = credentials();
const { response, json } = await fetchJsonWithRetry(
`${API_BASE}/${accountID}/ai/catalog/models/${id.split("/").map(encodeURIComponent).join("/")}/schema`,
{ headers: { Authorization: `Bearer ${token}` } },
);
if (response.status === 404) return undefined;
if (!response.ok) {
throw new Error(`Cloudflare AI Gateway schema request failed for ${id}: ${response.status} ${response.statusText}`);
}
return z.object({
success: z.literal(true),
result: z.object({ schema: z.object({ input: z.unknown().optional() }).passthrough() }).passthrough(),
}).passthrough().parse(json).result.schema.input;
}
function credentials() {
const token = process.env.CLOUDFLARE_API_TOKEN
?? process.env.CLOUDFLARE_PRODUCTION_API_TOKEN;
const accountID = process.env.CLOUDFLARE_ACCOUNT_ID
?? process.env.CLOUDFLARE_PRODUCTION_ACCOUNT_ID_AI_GATEWAY_SANDBOX;
if (!token || !accountID) {
throw new Error(
"Cloudflare AI Gateway sync requires Cloudflare API token and account ID credentials",
);
}
return { accountID, token };
}
function loadFixtureRows(directory: string, prefix: string): unknown[] {
const pages = readdirSync(directory)
.filter((name) => name.startsWith(prefix) && name.endsWith(".json"))
.sort()
.map((file) => CloudflareResponse.parse(JSON.parse(readFileSync(path.join(directory, file), "utf8"))))
.sort((a, b) => a.result_info.page - b.result_info.page);
return validateCatalogPages(pages, `Cloudflare AI Gateway fixtures in ${directory}`);
}
function catalogPageCount(page: z.infer<typeof CloudflareResponse>) {
const calculated = Math.max(1, Math.ceil(page.result_info.total_count / page.result_info.per_page));
if (page.result_info.total_pages !== undefined && page.result_info.total_pages !== calculated) {
throw new Error("Invalid Cloudflare AI Gateway catalog pagination: total_pages does not match total_count");
}
return page.result_info.total_pages ?? calculated;
}
function validateCatalogPages(pages: Array<z.infer<typeof CloudflareResponse>>, source: string) {
const first = pages[0];
if (first === undefined) throw new Error(`${source} contained no pages`);
const expectedPages = catalogPageCount(first);
if (pages.length !== expectedPages) {
throw new Error(`${source} contains ${pages.length}/${expectedPages} pages`);
}
const models: CatalogEntry[] = [];
const ids = new Set<string>();
for (const [index, page] of pages.entries()) {
if (page.result_info.page !== index + 1) {
throw new Error(`${source} expected page ${index + 1}, got ${page.result_info.page}`);
}
if (
page.result_info.total_count !== first.result_info.total_count
|| page.result_info.per_page !== first.result_info.per_page
|| catalogPageCount(page) !== expectedPages
) {
throw new Error(`${source} pagination changed while reading pages`);
}
if (page.result_info.count !== undefined && page.result_info.count !== page.result.length) {
throw new Error(`${source} result count mismatch on page ${page.result_info.page}`);
}
if (page.result.length > page.result_info.per_page) {
throw new Error(`${source} page ${page.result_info.page} exceeds per_page`);
}
for (const model of page.result) {
if (ids.has(model.model_id)) throw new Error(`${source} returned duplicate model ID ${model.model_id}`);
ids.add(model.model_id);
models.push(model);
}
}
if (models.length !== first.result_info.total_count) {
throw new Error(`${source} pagination ended at ${models.length}/${first.result_info.total_count}`);
}
return models;
}
async function fetchJsonWithRetry(
url: string | URL,
init: RequestInit,
attempts = 5,
): Promise<{ response: Response; json?: unknown }> {
let delay = 500;
for (let attempt = 1; attempt <= attempts; attempt++) {
try {
const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
const response = await fetch(url, {
...init,
signal: init.signal ? AbortSignal.any([init.signal, timeout]) : timeout,
});
if (!response.ok) {
if ((response.status === 429 || response.status >= 500) && attempt < attempts) {
await response.body?.cancel();
await waitForRetry(retryDelay(response, delay), init.signal);
delay = Math.min(delay * 2, MAX_BACKOFF_DELAY_MS);
continue;
}
await response.body?.cancel();
return { response };
}
try {
return { response, json: await response.json() };
} catch (error) {
if (attempt === attempts) throw error;
}
} catch (error) {
if (init.signal?.aborted || attempt === attempts) throw error;
}
await waitForRetry(delay, init.signal);
delay = Math.min(delay * 2, MAX_BACKOFF_DELAY_MS);
}
throw new Error("Cloudflare AI Gateway request exhausted retries");
}
function retryDelay(response: Response, fallback: number) {
const value = response.headers.get("retry-after");
if (value === null) return fallback;
const seconds = Number(value);
if (Number.isFinite(seconds) && seconds >= 0) return Math.min(seconds * 1_000, MAX_RETRY_DELAY_MS);
const timestamp = Date.parse(value);
return Number.isFinite(timestamp)
? Math.min(Math.max(timestamp - Date.now(), 0), MAX_RETRY_DELAY_MS)
: fallback;
}
function waitForRetry(delay: number, signal: AbortSignal | null | undefined) {
return new Promise<void>((resolve, reject) => {
if (signal?.aborted) return reject(signal.reason);
const onAbort = () => {
clearTimeout(timer);
reject(signal.reason);
};
const timer = setTimeout(() => {
signal?.removeEventListener("abort", onAbort);
resolve();
}, delay);
signal?.addEventListener("abort", onAbort, { once: true });
});
}
async function mapLimit<T, R>(items: T[], limit: number, transform: (item: T) => Promise<R>) {
const results = new Array<R>(items.length);
let next = 0;
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
while (next < items.length) {
const index = next++;
results[index] = await transform(items[index]!);
}
}));
return results;
}
const FLAT_PRICING_KEYS: Record<string, "input" | "output" | "cache_read" | "cache_write"> = {
"Input tokens (per 1M)": "input",
"Output tokens (per 1M)": "output",
"Cached input tokens (per 1M)": "cache_read",
"Cache creation tokens (per 1M)": "cache_write",
};
const TIERED_PRICING_KEY = /^(Input|Output|Cached input)\s*(<=?|>=?)\s*(\d+)k\s*\(per 1M\)$/;
const TIERED_PRICING_FIELDS = {
Input: "input",
Output: "output",
"Cached input": "cache_read",
} as const;
function proxiedCost(pricing: Record<string, number>, id: string): NonNullable<SyncedBaseModel["cost"]> {
const cost: NonNullable<SyncedBaseModel["cost"]> = {};
for (const [key, value] of Object.entries(pricing)) {
const flatField = FLAT_PRICING_KEYS[key];
if (flatField !== undefined) {
cost[flatField] = value;
continue;
}
const tier = TIERED_PRICING_KEY.exec(key);
if (tier !== null) {
const field = TIERED_PRICING_FIELDS[tier[1] as keyof typeof TIERED_PRICING_FIELDS];
if (tier[2]!.startsWith("<")) cost[field] = value;
continue;
}
throw new Error(`${id}: unmapped pricing key "${key}"`);
}
if (cost.input === undefined || cost.output === undefined) {
throw new Error(`${id}: catalog pricing must include input and output rates`);
}
return cost;
}
function isSafeModelID(id: string) {
if (path.isAbsolute(id) || id.includes("\\")) return false;
const segments = id.split("/");
return segments.length >= 2
&& segments.every((segment) => /^[A-Za-z0-9@._-]+$/.test(segment) && segment !== "." && segment !== "..");
}
function resolveBaseModel(id: string) {
if (labFileExists(id)) return id;
const dashed = id.replaceAll(".", "-");
return labFileExists(dashed) ? dashed : undefined;
}
function labFileExists(id: string) {
return existsSync(path.join(MODELS_ROOT, `${id}.toml`));
}
function baseReasoning(id: string) {
const file = path.join(MODELS_ROOT, `${id}.toml`);
return existsSync(file) && z.object({ reasoning: z.boolean().optional() }).passthrough()
.parse(Bun.TOML.parse(readFileSync(file, "utf8"))).reasoning === true;
}
function noteHeader(note: string[] | undefined) {
return note === undefined || note.length === 0
? undefined
: `${note.map((line) => `# ${line}`).join("\n")}\n`;
}
+12
View File
@@ -31,6 +31,18 @@ test("requires manual review for bulk additions", async () => {
expect(decision.reasons).toContain("11 models created (limit 10)");
});
test("requires manual review for Cloudflare AI Gateway deletions", async () => {
const decision = await classifyAutoMerge([
{
status: "deleted",
path: "providers/cloudflare-ai-gateway/models/openai/gpt-4.1.toml",
},
]);
expect(decision.safe).toBe(false);
expect(decision.reasons).toContain("Cloudflare AI Gateway model deletions require manual review");
});
test("requires manual review for added reasoning provider models", async () => {
const withoutOptions = await classifyAutoMerge(
[{ status: "created", path: "providers/test/models/reasoner.toml" }],
@@ -0,0 +1,433 @@
import { expect, test } from "bun:test";
import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises";
import path from "node:path";
import { syncProvider } from "../src/sync/index.js";
import {
buildCloudflareAiGatewayModel,
cloudflareAiGateway,
deriveReasoningOptions,
} from "../src/sync/providers/cloudflare-ai-gateway.js";
test("builds Cloudflare AI Gateway overrides from catalog metadata", () => {
const model = buildCloudflareAiGatewayModel(
{
model_id: "openai/gpt-5.4",
task: "Text Generation",
context_length: 1_050_000,
pricing: {
"Input <= 200k (per 1M)": 2.5,
"Input > 200k (per 1M)": 5,
"Output tokens (per 1M)": 15,
"Cached input tokens (per 1M)": 0.25,
},
},
undefined,
{
reasoning_options: [{ type: "effort", values: ["none", "low", "medium", "high", "xhigh"] }],
},
);
expect(model).toEqual({
base_model: "openai/gpt-5.4",
reasoning_options: [{ type: "effort", values: ["none", "low", "medium", "high", "xhigh"] }],
cost: { input: 2.5, output: 15, cache_read: 0.25 },
limit: { context: 1_050_000 },
provider: { npm: "@ai-sdk/openai" },
});
});
test("derives nested Cloudflare reasoning controls", () => {
expect(deriveReasoningOptions({
properties: {
thinking: { type: "boolean" },
reasoning: {
properties: {
effort: {
anyOf: [{ enum: ["low", "medium", "high"] }],
},
},
},
},
})).toEqual([
{ type: "toggle" },
{ type: "effort", values: ["low", "medium", "high"] },
]);
});
test("ignores advertised reasoning controls for non-reasoning base models", () => {
const model = buildCloudflareAiGatewayModel(
{
model_id: "openai/gpt-4.1",
task: "Text Generation",
context_length: 1_047_576,
pricing: {
"Input tokens (per 1M)": 2,
"Output tokens (per 1M)": 8,
},
},
{
properties: {
reasoning_effort: { enum: ["low", "medium", "high"] },
},
},
);
expect(model.reasoning_options).toBeUndefined();
});
test("fails closed on unknown pricing fields", () => {
expect(() => buildCloudflareAiGatewayModel({
model_id: "openai/gpt-4.1",
task: "Text Generation",
context_length: 1_047_576,
pricing: {
"Input tokens (per 1M)": 2,
"Output tokens (per 1M)": 8,
"New billing unit": 1,
},
}, undefined)).toThrow('unmapped pricing key "New billing unit"');
});
test("fails closed when Cloudflare pagination is incomplete", async () => {
const originalFetch = globalThis.fetch;
const originalToken = process.env.CLOUDFLARE_API_TOKEN;
const originalAccount = process.env.CLOUDFLARE_ACCOUNT_ID;
process.env.CLOUDFLARE_API_TOKEN = "test";
process.env.CLOUDFLARE_ACCOUNT_ID = "test";
let page = 0;
globalThis.fetch = async () => new Response(JSON.stringify(catalogPage(
page++ === 0
? [{
model_id: "openai/gpt-4.1",
task: "Text Generation",
context_length: 1_047_576,
pricing: {
"Input tokens (per 1M)": 2,
"Output tokens (per 1M)": 8,
},
}]
: [],
{ page, total_count: 2 },
)));
try {
await expect(cloudflareAiGateway.fetchModels()).rejects.toThrow("pagination ended at 1/2");
} finally {
globalThis.fetch = originalFetch;
restoreEnv("CLOUDFLARE_API_TOKEN", originalToken);
restoreEnv("CLOUDFLARE_ACCOUNT_ID", originalAccount);
}
});
test("rejects unsafe catalog model paths", async () => {
const originalFetch = globalThis.fetch;
const originalToken = process.env.CLOUDFLARE_API_TOKEN;
const originalAccount = process.env.CLOUDFLARE_ACCOUNT_ID;
process.env.CLOUDFLARE_API_TOKEN = "test";
process.env.CLOUDFLARE_ACCOUNT_ID = "test";
globalThis.fetch = async () => new Response(JSON.stringify(catalogPage([{
model_id: "../providers/openai/models/gpt-4.1",
task: "Text Generation",
context_length: 1_047_576,
pricing: {
"Input tokens (per 1M)": 2,
"Output tokens (per 1M)": 8,
},
}])));
try {
await expect(cloudflareAiGateway.fetchModels()).rejects.toThrow("safe relative provider/model path");
} finally {
globalThis.fetch = originalFetch;
restoreEnv("CLOUDFLARE_API_TOKEN", originalToken);
restoreEnv("CLOUDFLARE_ACCOUNT_ID", originalAccount);
}
});
test("rejects a catalog with no eligible proxied models", async () => {
const originalFetch = globalThis.fetch;
const originalToken = process.env.CLOUDFLARE_API_TOKEN;
const originalAccount = process.env.CLOUDFLARE_ACCOUNT_ID;
process.env.CLOUDFLARE_API_TOKEN = "test";
process.env.CLOUDFLARE_ACCOUNT_ID = "test";
globalThis.fetch = async () => new Response(JSON.stringify(catalogPage([{
model_id: "@cf/meta/llama-3.1-8b-instruct",
task: "Text Generation",
}])));
try {
await expect(cloudflareAiGateway.fetchModels()).rejects.toThrow("no eligible proxied models");
} finally {
globalThis.fetch = originalFetch;
restoreEnv("CLOUDFLARE_API_TOKEN", originalToken);
restoreEnv("CLOUDFLARE_ACCOUNT_ID", originalAccount);
}
});
test("validates Cloudflare page metadata", async () => {
const originalFetch = globalThis.fetch;
const originalToken = process.env.CLOUDFLARE_API_TOKEN;
const originalAccount = process.env.CLOUDFLARE_ACCOUNT_ID;
process.env.CLOUDFLARE_API_TOKEN = "test";
process.env.CLOUDFLARE_ACCOUNT_ID = "test";
globalThis.fetch = async () => new Response(JSON.stringify(catalogPage([], { page: 2, total_count: 0 })));
try {
await expect(cloudflareAiGateway.fetchModels()).rejects.toThrow("expected page 1, got 2");
} finally {
globalThis.fetch = originalFetch;
restoreEnv("CLOUDFLARE_API_TOKEN", originalToken);
restoreEnv("CLOUDFLARE_ACCOUNT_ID", originalAccount);
}
});
test("retries transient Cloudflare responses", async () => {
const originalFetch = globalThis.fetch;
const originalToken = process.env.CLOUDFLARE_API_TOKEN;
const originalAccount = process.env.CLOUDFLARE_ACCOUNT_ID;
process.env.CLOUDFLARE_API_TOKEN = "test";
process.env.CLOUDFLARE_ACCOUNT_ID = "test";
let catalogRequests = 0;
globalThis.fetch = async (input) => {
if (String(input).endsWith("/schema")) return new Response(null, { status: 404 });
catalogRequests++;
if (catalogRequests === 1) return new Response(null, { status: 503, headers: { "retry-after": "0" } });
return new Response(JSON.stringify(catalogPage([{
model_id: "openai/gpt-4.1",
task: "Text Generation",
context_length: 1_047_576,
pricing: {
"Input tokens (per 1M)": 2,
"Output tokens (per 1M)": 8,
},
}])));
};
try {
expect(await cloudflareAiGateway.fetchModels()).toHaveLength(1);
expect(catalogRequests).toBe(2);
} finally {
globalThis.fetch = originalFetch;
restoreEnv("CLOUDFLARE_API_TOKEN", originalToken);
restoreEnv("CLOUDFLARE_ACCOUNT_ID", originalAccount);
}
});
test("replaces a stale generated base-model mapping", async () => {
const providersDir = path.join(import.meta.dirname, "..", "..", "..", "providers");
const providerDir = await mkdtemp(path.join(providersDir, ".base-model-sync-"));
const modelsDir = path.join(providerDir, "models");
await mkdir(modelsDir);
const file = path.join(modelsDir, "model.toml");
await writeFile(file, 'base_model = "anthropic/claude-opus-4-6"\n');
try {
const provider = {
id: "base-model-test",
name: "Base-model test",
modelsDir,
async fetchModels() {
return [{ id: "model" }];
},
parseModels(raw: unknown) {
return raw as Array<{ id: string }>;
},
translateModel(model: { id: string }) {
return { id: model.id, model: { base_model: "openai/gpt-4.1" } };
},
};
await syncProvider(provider);
expect(await readFile(file, "utf8")).toContain('base_model = "openai/gpt-4.1"');
} finally {
await rm(providerDir, { recursive: true, force: true });
}
});
test("reconciles authoritative generated headers", async () => {
const providersDir = path.join(import.meta.dirname, "..", "..", "..", "providers");
const providerDir = await mkdtemp(path.join(providersDir, ".cloudflare-ai-gateway-sync-"));
const modelsDir = path.join(providerDir, "models");
await mkdir(modelsDir);
const file = path.join(modelsDir, "gpt-4.1.toml");
await writeFile(file, "# Old note\n\nbase_model = \"openai/gpt-4.1\"\n");
try {
const provider = {
id: "cloudflare-ai-gateway-test",
name: "Cloudflare AI Gateway test",
modelsDir,
authoritativeHeaders: true,
async fetchModels() {
return [{ id: "gpt-4.1" }];
},
parseModels() {
return [{ id: "gpt-4.1" }];
},
translateModel(model) {
return {
id: model.id,
model: { base_model: "openai/gpt-4.1" },
header: "# New note\n\n",
};
},
};
const result = await syncProvider(provider);
expect(result.updated).toBe(1);
expect(await readFile(file, "utf8")).toStartWith("# New note\nbase_model");
expect((await syncProvider(provider)).updated).toBe(0);
} finally {
await rm(providerDir, { recursive: true, force: true });
}
});
test("refuses to write through a symlinked model directory", async () => {
const providersDir = path.join(import.meta.dirname, "..", "..", "..", "providers");
const providerDir = await mkdtemp(path.join(providersDir, ".sync-symlink-"));
const outsideDir = await mkdtemp(path.join(providersDir, ".sync-outside-"));
const modelsDir = path.join(providerDir, "models");
await mkdir(modelsDir);
await symlink(outsideDir, path.join(modelsDir, "linked"));
try {
const provider = {
id: "symlink-test",
name: "Symlink test",
modelsDir,
async fetchModels() {
return [{ id: "linked/model" }];
},
parseModels(raw: unknown) {
return raw as Array<{ id: string }>;
},
translateModel(model: { id: string }) {
return { id: model.id, model: { base_model: "openai/gpt-4.1" } };
},
};
await expect(syncProvider(provider)).rejects.toThrow("Refusing to sync through symlink");
expect(await Bun.file(path.join(outsideDir, "model.toml")).exists()).toBe(false);
} finally {
await rm(providerDir, { recursive: true, force: true });
await rm(outsideDir, { recursive: true, force: true });
}
});
test("refuses a symlinked models root", async () => {
const providersDir = path.join(import.meta.dirname, "..", "..", "..", "providers");
const providerDir = await mkdtemp(path.join(providersDir, ".sync-root-"));
const outsideDir = await mkdtemp(path.join(providersDir, ".sync-root-outside-"));
const modelsDir = path.join(providerDir, "models");
await symlink(outsideDir, modelsDir);
try {
const provider = testSyncProvider(modelsDir, "model");
await expect(syncProvider(provider)).rejects.toThrow("Refusing to sync through symlink");
expect(await Bun.file(path.join(outsideDir, "model.toml")).exists()).toBe(false);
} finally {
await rm(providerDir, { recursive: true, force: true });
await rm(outsideDir, { recursive: true, force: true });
}
});
test("refuses a symlinked metadata file", async () => {
const providersDir = path.join(import.meta.dirname, "..", "..", "..", "providers");
const providerDir = await mkdtemp(path.join(providersDir, ".sync-metadata-"));
const outsideDir = await mkdtemp(path.join(providersDir, ".sync-metadata-outside-"));
const modelsDir = path.join(providerDir, "models");
const namespace = `sync-symlink-${path.basename(providerDir).replaceAll(/[^a-z0-9-]/g, "")}`;
const metadataDir = path.join(providersDir, "..", "models", namespace);
const outsideFile = path.join(outsideDir, "model.toml");
await mkdir(modelsDir);
await mkdir(metadataDir);
await writeFile(outsideFile, "sentinel\n");
await symlink(outsideFile, path.join(metadataDir, "model.toml"));
try {
const provider = {
...testSyncProvider(modelsDir, "provider-model"),
metadataNamespace: namespace,
translateModel(model: { id: string }) {
return {
id: model.id,
model: {
name: "Provider symlink test",
description: "Provider model used to test safe sync paths",
release_date: "2026-01-01",
last_updated: "2026-01-01",
attachment: false,
reasoning: false,
tool_call: false,
open_weights: false,
modalities: { input: ["text"], output: ["text"] },
limit: { context: 1_000, output: 100 },
cost: { input: 1, output: 2 },
},
metadata: {
id: `${namespace}/model`,
model: {
name: "Symlink test",
description: "Metadata used to test safe sync paths",
release_date: "2026-01-01",
last_updated: "2026-01-01",
attachment: false,
reasoning: false,
tool_call: false,
open_weights: false,
modalities: { input: ["text"], output: ["text"] },
limit: { context: 1_000, output: 100 },
},
},
};
},
};
await expect(syncProvider(provider)).rejects.toThrow("Refusing to sync through symlink");
expect(await readFile(outsideFile, "utf8")).toBe("sentinel\n");
} finally {
await rm(providerDir, { recursive: true, force: true });
await rm(outsideDir, { recursive: true, force: true });
await rm(metadataDir, { recursive: true, force: true });
}
});
function testSyncProvider(modelsDir: string, id: string) {
return {
id: "symlink-test",
name: "Symlink test",
modelsDir,
async fetchModels() {
return [{ id }];
},
parseModels(raw: unknown) {
return raw as Array<{ id: string }>;
},
translateModel(model: { id: string }) {
return { id: model.id, model: { base_model: "openai/gpt-4.1" } };
},
};
}
function catalogPage(
result: Array<Record<string, unknown>>,
resultInfo: Partial<{ page: number; per_page: number; total_count: number; total_pages: number }> = {},
) {
const page = resultInfo.page ?? 1;
const perPage = resultInfo.per_page ?? 50;
const totalCount = resultInfo.total_count ?? result.length;
return {
success: true,
result,
result_info: {
page,
per_page: perPage,
count: result.length,
total_count: totalCount,
total_pages: resultInfo.total_pages ?? Math.max(1, Math.ceil(totalCount / perPage)),
},
};
}
function restoreEnv(name: string, value: string | undefined) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
+5 -2
View File
@@ -18,10 +18,13 @@ One command regenerates every model TOML:
CLOUDFLARE_API_TOKEN=xxx CLOUDFLARE_ACCOUNT_ID=xxx bun run cloudflare-ai-gateway:generate
```
The sync also accepts `CLOUDFLARE_PRODUCTION_API_TOKEN` and
`CLOUDFLARE_PRODUCTION_ACCOUNT_ID_AI_GATEWAY_SANDBOX` directly.
It reads two live Cloudflare sources plus one local curation file:
- **Proxied catalog** — `GET /accounts/{id}/ai/catalog/models`. The source of truth: one
canonical (dotted) `model_id` per model, description, context/output limits, and pricing.
canonical (dotted) `model_id` per model, description, context limits, and pricing.
This is why ids look like `anthropic/claude-haiku-4.5`, not `claude-haiku-4-5`.
- **Per-model catalog schema** — `GET /accounts/{id}/ai/catalog/models/{id}/schema`. Used to
derive `reasoning_options` for providers whose schema is OpenAI-compatible (xAI, Alibaba,
@@ -44,7 +47,7 @@ bun run cloudflare-ai-gateway:generate --check
```
Exits non-zero if the committed TOMLs are out of date with the live catalog + curation.
Used in CI.
The same shared provider runs hourly; use `--check` for local drift checks.
### Offline / fixtures
+11 -1
View File
@@ -11,6 +11,7 @@ The grouped sync targets are available for local convenience, but CI syncs each
- `bun models:sync aggregators` syncs every provider in the `aggregators` group.
- `bun models:sync openrouter` syncs only OpenRouter.
- `bun models:sync cloudflare-workers-ai` syncs only Cloudflare Workers AI.
- `bun models:sync cloudflare-ai-gateway` syncs only Cloudflare AI Gateway's proxied catalog.
- `bun models:sync cloudflare` syncs the Cloudflare sync group.
- `bun models:sync direct` syncs every provider in the `direct` group.
- `bun models:sync google` syncs only Google.
@@ -202,7 +203,16 @@ Cloudflare Workers AI is implemented in `packages/core/src/sync/providers/cloudf
- Use a dedicated token scoped to Workers AI read access so sync automation does not share deploy credentials.
- The endpoint is parsed as Cloudflare's OpenRouter-like Workers AI metadata.
- Model IDs map directly to TOML paths under `providers/cloudflare-workers-ai/models`.
- This sync target does not manage `providers/cloudflare-ai-gateway`, because the AI Gateway `/compat/models` endpoint does not support `format=openrouter` and does not provide enough model metadata for authoritative catalog sync.
- This target only manages Workers AI; the separate Cloudflare AI Gateway target handles proxied third-party models.
## Cloudflare AI Gateway Notes
- Cloudflare AI Gateway is implemented in `packages/core/src/sync/providers/cloudflare-ai-gateway.ts`.
- Source endpoints: `GET /accounts/{id}/ai/catalog/models` for model availability, context limits, and pricing, plus `GET /accounts/{id}/ai/catalog/models/{model}/schema` for reasoning controls exposed by compatible schemas.
- Required auth: `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN`, or the production-token aliases documented in the provider README for local runs. The hourly workflow uses the canonical secret names.
- The sync manages proxied third-party text-generation models only. Workers AI `@cf/...` models remain under `providers/cloudflare-workers-ai`.
- `providers/cloudflare-ai-gateway/curation.toml` supplies base-model mappings, live-tested reasoning controls, structured-output support, limit overrides, and intentional skips that the catalog cannot express authoritatively.
- New catalog entries without canonical lab metadata or required reasoning controls fail closed instead of generating incomplete TOMLs.
## Google Notes