Skip to content

The open alternative to Salesforce, designed for AI.

Add benchmarks, data residency and zero data retention to the AI model catalog (#25675)

Félix Malfaitf1d00f033d0e
diff --git a/.github/workflows/ci-ai-catalog-sync.yaml b/.github/workflows/ci-ai-catalog-sync.yaml
index 59346166897..4b60d2bc09b 100644
--- a/.github/workflows/ci-ai-catalog-sync.yaml
+++ b/.github/workflows/ci-ai-catalog-sync.yaml
@@ -28,32 +28,50 @@ jobs:
run: npx nx build twenty-shared
- name: Run catalog sync
- run: npx nx run twenty-server:ts-node-no-deps-transpile-only -- ./scripts/ai-sync-models-dev.ts
+ env:
+ ARTIFICIAL_ANALYSIS_API_KEY: ${{ secrets.ARTIFICIAL_ANALYSIS_API_KEY }}
+ run: |
+ npx nx run twenty-server:ts-node-no-deps-transpile-only -- \
+ ./scripts/ai-catalog-sync/index.ts --report "${RUNNER_TEMP}/coverage.md"
- name: Check for changes
id: changes
run: |
- if git diff --quiet packages/twenty-server/src/engine/metadata-modules/ai/ai-models/ai-providers.json; then
+ catalog_dir=packages/twenty-server/src/engine/metadata-modules/ai/ai-models
+ if git diff --quiet "$catalog_dir/ai-providers.json" "$catalog_dir/ai-model-benchmarks.json"; then
echo "changed=false" >> "$GITHUB_OUTPUT"
else
echo "changed=true" >> "$GITHUB_OUTPUT"
fi
+ - name: Compose pull request body
+ if: steps.changes.outputs.changed == 'true'
+ run: |
+ cat > "${RUNNER_TEMP}/pr-body.md" <<'PREAMBLE'
+ Automated daily sync of the AI model catalog.
+
+ - Model identity, pricing, context windows and availability come from [models.dev](https://models.dev).
+ - Intelligence, speed and cost per task come from [Artificial Analysis](https://artificialanalysis.ai/),
+ which requires `ARTIFICIAL_ANALYSIS_API_KEY`.
+
+ New models meeting inclusion criteria (tool calling, pricing data, context limits) are added
+ automatically. Benchmark data is best-effort: a model Artificial Analysis has not rated keeps
+ every other field and simply carries no `benchmark` entry.
+
+ **Please review before merging** and check the coverage summary below for models that silently
+ stopped matching.
+
+ PREAMBLE
+ cat "${RUNNER_TEMP}/coverage.md" >> "${RUNNER_TEMP}/pr-body.md"
+
- name: Create pull request
if: steps.changes.outputs.changed == 'true'
uses: peter-evans/create-pull-request@22a9089034f40e5a961c8808d113e2c98fb63676 # v7.0.6
with:
token: ${{ secrets.GITHUB_TOKEN }}
- commit-message: 'chore: sync AI model catalog from models.dev'
- title: 'chore: sync AI model catalog from models.dev'
- body: |
- Automated daily sync of `ai-providers.json` from [models.dev](https://models.dev).
-
- This PR updates pricing, context windows, and model availability based on the latest data.
- New models meeting inclusion criteria (tool calling, pricing data, context limits) are added automatically.
- Deprecated models are detected based on cost-efficiency within the same model family.
-
- **Please review before merging** — verify no critical models were incorrectly deprecated.
+ commit-message: 'chore: sync AI model catalog'
+ title: 'chore: sync AI model catalog'
+ body-path: ${{ runner.temp }}/pr-body.md
branch: chore/ai-catalog-sync
base: main
labels: ai, automated
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/__tests__/build-catalog.spec.ts b/packages/twenty-server/scripts/ai-catalog-sync/__tests__/build-catalog.spec.ts
new file mode 100644
index 00000000000..8896847e5e3
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/__tests__/build-catalog.spec.ts
@@ -0,0 +1,57 @@
+import { type ModelsDevData } from 'src/engine/metadata-modules/ai/ai-models/types/models-dev-data.type';
+
+import { assertPayloadIsUsable } from '../utils/assert-payload-is-usable.util';
+import { buildCatalog } from '../utils/build-catalog.util';
+
+const languageModel = {
+ id: 'model',
+ name: 'Model',
+ tool_call: true,
+ cost: { input: 2, output: 6 },
+ limit: { context: 128000, output: 8192 },
+};
+
+const payload = (): ModelsDevData => ({
+ openai: { id: 'openai', models: { 'gpt-x': languageModel } },
+ anthropic: { id: 'anthropic', models: { 'claude-x': languageModel } },
+ google: { id: 'google', models: { 'gemini-x': languageModel } },
+ xai: { id: 'xai', models: { 'grok-x': languageModel } },
+ mistral: { id: 'mistral', models: { 'mistral-x': languageModel } },
+});
+
+describe('assertPayloadIsUsable', () => {
+ it('accepts a payload carrying models for every native provider', () => {
+ expect(() => assertPayloadIsUsable(payload())).not.toThrow();
+ });
+
+ it('refuses an empty payload rather than generating an empty catalog', () => {
+ expect(() => assertPayloadIsUsable({} as ModelsDevData)).toThrow(
+ /refusing to overwrite the catalog/,
+ );
+ });
+
+ it('names the providers that came back empty', () => {
+ const data = payload();
+
+ data.anthropic.models = {};
+
+ expect(() => assertPayloadIsUsable(data)).toThrow(/anthropic/);
+ });
+});
+
+describe('buildCatalog', () => {
+ it('prices long context from the standard output rate when none is quoted', () => {
+ const data = payload();
+
+ data.openai.models['gpt-x'].cost = {
+ input: 2,
+ output: 6,
+ context_over_200k: { input: 4 },
+ };
+
+ const model = buildCatalog(data).openai.models[0];
+
+ // A missing long-context rate is unknown, not free.
+ expect(model.longContextCost?.outputCostPerMillionTokens).toBe(6);
+ });
+});
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/__tests__/enrich-catalog.spec.ts b/packages/twenty-server/scripts/ai-catalog-sync/__tests__/enrich-catalog.spec.ts
new file mode 100644
index 00000000000..9a36bf485d1
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/__tests__/enrich-catalog.spec.ts
@@ -0,0 +1,80 @@
+import { type ModelsDevData } from 'src/engine/metadata-modules/ai/ai-models/types/models-dev-data.type';
+
+import { enrichCatalog } from '../utils/enrich-catalog.util';
+import { type BenchmarkIndex } from '../types/benchmark-index.type';
+import { type GeneratedCatalog } from '../types/generated-catalog.type';
+
+const MEASURED_AT = '2026-09-09';
+
+const catalogOf = (...modelNames: string[]): GeneratedCatalog =>
+ ({
+ openai: {
+ npm: '@ai-sdk/openai',
+ label: 'OpenAI',
+ apiKey: '',
+ models: modelNames.map((name) => ({ name, label: name })),
+ },
+ }) as GeneratedCatalog;
+
+const enrich = (catalog: GeneratedCatalog, benchmarkIndex: BenchmarkIndex) =>
+ enrichCatalog({
+ catalog,
+ modelsDevData: {} as ModelsDevData,
+ benchmarkIndex,
+ measuredAt: MEASURED_AT,
+ });
+
+describe('enrichCatalog', () => {
+ it('attaches a measurement to the model and mirrors it into the overlay', () => {
+ const catalog = catalogOf('gpt-x');
+ const overlay = enrich(
+ catalog,
+ new Map([['gptx', { intelligenceIndex: 41, aliases: ['gpt-x'] }]]),
+ );
+
+ expect(catalog.openai.models[0].benchmark).toEqual({
+ intelligenceIndex: 41,
+ outputTokensPerSecond: undefined,
+ costPerTask: undefined,
+ measuredAt: MEASURED_AT,
+ });
+ expect(overlay['gpt-x'].measuredAt).toBe(MEASURED_AT);
+ });
+
+ it('leaves a row the publisher measured nothing about out of both artifacts', () => {
+ const catalog = catalogOf('gpt-x');
+ const overlay = enrich(
+ catalog,
+ new Map([['gptx', { aliases: ['gpt-x'] }]]),
+ );
+
+ expect(overlay).toEqual({});
+ expect(catalog.openai.models[0].benchmark).toBeUndefined();
+ });
+
+ it('leaves a model no publisher covers untouched and out of the overlay', () => {
+ const catalog = catalogOf('gpt-x');
+ const overlay = enrich(catalog, new Map());
+
+ expect(catalog.openai.models[0].benchmark).toBeUndefined();
+ expect(overlay).toEqual({});
+ });
+
+ it('keeps isDeprecated last so the generated catalog stays stable', () => {
+ const catalog = catalogOf('gpt-x');
+
+ catalog.openai.models[0].isDeprecated = true;
+
+ enrich(
+ catalog,
+ new Map([['gptx', { intelligenceIndex: 41, aliases: ['gpt-x'] }]]),
+ );
+
+ expect(Object.keys(catalog.openai.models[0])).toEqual([
+ 'name',
+ 'label',
+ 'benchmark',
+ 'isDeprecated',
+ ]);
+ });
+});
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/__tests__/fetch-artificial-analysis.spec.ts b/packages/twenty-server/scripts/ai-catalog-sync/__tests__/fetch-artificial-analysis.spec.ts
new file mode 100644
index 00000000000..ebf57c3c457
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/__tests__/fetch-artificial-analysis.spec.ts
@@ -0,0 +1,108 @@
+import { fetchArtificialAnalysisBenchmarks } from '../utils/fetch-artificial-analysis-benchmarks.util';
+
+const respondWith = (models: unknown[]): void => {
+ global.fetch = jest.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({ data: models }),
+ }) as unknown as typeof fetch;
+};
+
+const measuredModel = {
+ slug: 'claude-sonnet-5',
+ evaluations: { artificial_analysis_intelligence_index: 38.4 },
+ median_output_tokens_per_second: 92.1,
+ cost_per_task: { total_cost: 0.42 },
+};
+
+describe('fetchArtificialAnalysisBenchmarks', () => {
+ it('reads the index, speed and cost per task for a measured model', async () => {
+ respondWith([measuredModel]);
+
+ const record = (await fetchArtificialAnalysisBenchmarks('key')).get(
+ 'claudesonnet5',
+ );
+
+ expect(record?.intelligenceIndex).toBe(38.4);
+ expect(record?.outputTokensPerSecond).toBe(92.1);
+ expect(record?.costPerTask).toBe(0.42);
+ });
+
+ it('treats zero as not measured rather than as a measurement', async () => {
+ respondWith([
+ {
+ slug: 'grok-4-6',
+ evaluations: { artificial_analysis_intelligence_index: 44.1 },
+ median_output_tokens_per_second: 0,
+ },
+ ]);
+
+ const record = (await fetchArtificialAnalysisBenchmarks('key')).get(
+ 'grok46',
+ );
+
+ expect(record?.intelligenceIndex).toBe(44.1);
+ expect(record?.outputTokensPerSecond).toBeUndefined();
+ });
+
+ it.each([
+ ['unmeasured row first', true],
+ ['measured row first', false],
+ ])(
+ 'keeps the measured row when an unmeasured duplicate shares its name (%s)',
+ async (_label, unmeasuredFirst) => {
+ const unmeasured = {
+ slug: 'claude-sonnet-5',
+ median_output_tokens_per_second: 0,
+ };
+
+ respondWith(
+ unmeasuredFirst
+ ? [unmeasured, measuredModel]
+ : [measuredModel, unmeasured],
+ );
+
+ const record = (await fetchArtificialAnalysisBenchmarks('key')).get(
+ 'claudesonnet5',
+ );
+
+ expect(record?.intelligenceIndex).toBe(38.4);
+ },
+ );
+
+ it('survives a null row rather than discarding the whole response', async () => {
+ respondWith([null, measuredModel]);
+
+ const record = (await fetchArtificialAnalysisBenchmarks('key')).get(
+ 'claudesonnet5',
+ );
+
+ expect(record?.intelligenceIndex).toBe(38.4);
+ });
+
+ it('fails loudly when every row came back unmeasured', async () => {
+ respondWith([
+ { slug: 'claude-sonnet-5', median_output_tokens_per_second: 0 },
+ ]);
+
+ await expect(fetchArtificialAnalysisBenchmarks('key')).rejects.toThrow(
+ /none carried a measurement/,
+ );
+ });
+
+ it('ignores figures published at the top level instead of their container', async () => {
+ respondWith([
+ {
+ slug: 'claude-sonnet-5',
+ artificial_analysis_intelligence_index: 38.4,
+ median_output_tokens_per_second: 92.1,
+ },
+ ]);
+
+ const record = (await fetchArtificialAnalysisBenchmarks('key')).get(
+ 'claudesonnet5',
+ );
+
+ expect(record?.intelligenceIndex).toBeUndefined();
+ expect(record?.outputTokensPerSecond).toBe(92.1);
+ });
+});
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/__tests__/match-benchmarks.spec.ts b/packages/twenty-server/scripts/ai-catalog-sync/__tests__/match-benchmarks.spec.ts
new file mode 100644
index 00000000000..2ce8ec2acdd
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/__tests__/match-benchmarks.spec.ts
@@ -0,0 +1,176 @@
+import { type ModelsDevModel } from 'src/engine/metadata-modules/ai/ai-models/types/models-dev-model.type';
+
+import { type BenchmarkIndex } from '../types/benchmark-index.type';
+import { type BenchmarkRecord } from '../types/benchmark-record.type';
+import { buildLookupCandidates } from '../utils/build-lookup-candidates.util';
+import { matchBenchmarks } from '../utils/match-benchmarks.util';
+
+const MEASURED_AT = '2026-09-09';
+
+const modelsDevModel = (
+ overrides: Partial<ModelsDevModel> = {},
+): ModelsDevModel => ({
+ id: 'model',
+ name: 'Model',
+ cost: { input: 2, output: 6 },
+ limit: { context: 128000, output: 8192 },
+ ...overrides,
+});
+
+const MISTRAL_MODELS: Record<string, ModelsDevModel> = {
+ 'mistral-large-latest': modelsDevModel({ id: 'mistral-large-latest' }),
+ 'mistral-large-2512': modelsDevModel({
+ id: 'mistral-large-2512',
+ release_date: '2025-12-01',
+ }),
+ 'mistral-large-2411': modelsDevModel({
+ id: 'mistral-large-2411',
+ release_date: '2024-11-01',
+ cost: { input: 3, output: 9 },
+ }),
+};
+
+const indexOf = (entries: Record<string, BenchmarkRecord>): BenchmarkIndex =>
+ new Map(Object.entries(entries));
+
+const match = (modelName: string, benchmarkIndex: BenchmarkIndex) =>
+ matchBenchmarks({
+ modelName,
+ siblingModels: MISTRAL_MODELS,
+ benchmarkIndex,
+ measuredAt: MEASURED_AT,
+ });
+
+describe('buildLookupCandidates', () => {
+ it('resolves a rolling alias to the priced-identical release it points at', () => {
+ expect(
+ buildLookupCandidates({
+ modelName: 'mistral-large-latest',
+ siblingModels: MISTRAL_MODELS,
+ }),
+ ).toContain('mistral-large-2512');
+ });
+
+ it('prefers the newest release when several share the same price and limits', () => {
+ const candidates = buildLookupCandidates({
+ modelName: 'mistral-large-latest',
+ siblingModels: {
+ ...MISTRAL_MODELS,
+ 'mistral-large-2506': modelsDevModel({ release_date: '2025-06-01' }),
+ },
+ });
+
+ expect(candidates).toContain('mistral-large-2512');
+ expect(candidates).not.toContain('mistral-large-2506');
+ });
+
+ it('resolves the same way whatever order an undated provider lists twins in', () => {
+ // Nothing in models.dev hits this today, but the resolution must not depend
+ // on the order a third party happens to serialize its models in.
+ const undated = {
+ 'mistral-large-latest': modelsDevModel({ id: 'mistral-large-latest' }),
+ 'mistral-large-2506': modelsDevModel({ id: 'mistral-large-2506' }),
+ 'mistral-large-2512': modelsDevModel({ id: 'mistral-large-2512' }),
+ };
+
+ const resolve = (siblingModels: Record<string, ModelsDevModel>) =>
+ buildLookupCandidates({
+ modelName: 'mistral-large-latest',
+ siblingModels,
+ });
+
+ const reordered = {
+ 'mistral-large-latest': undated['mistral-large-latest'],
+ 'mistral-large-2512': undated['mistral-large-2512'],
+ 'mistral-large-2506': undated['mistral-large-2506'],
+ };
+
+ [undated, reordered].forEach((siblingModels) => {
+ const candidates = resolve(siblingModels);
+
+ expect(candidates).toContain('mistral-large-2512');
+ expect(candidates).not.toContain('mistral-large-2506');
+ });
+ });
+
+ it('offers the undated name for a dated snapshot', () => {
+ expect(
+ buildLookupCandidates({
+ modelName: 'claude-sonnet-4-5-20250929',
+ siblingModels: {},
+ }),
+ ).toContain('claude-sonnet-4-5');
+ });
+});
+
+describe('matchBenchmarks', () => {
+ it('scores a rolling alias from the release it resolves to', () => {
+ const result = match(
+ 'mistral-large-latest',
+ indexOf({ mistrallarge2512: { intelligenceIndex: 41, aliases: [] } }),
+ );
+
+ expect(result?.benchmark.intelligenceIndex).toBe(41);
+ expect(result?.benchmark.measuredAt).toBe(MEASURED_AT);
+ });
+
+ it('carries speed and cost per task through to the catalog', () => {
+ const result = match(
+ 'mistral-large-2512',
+ indexOf({
+ mistrallarge2512: {
+ outputTokensPerSecond: 92,
+ costPerTask: 0.42,
+ aliases: [],
+ },
+ }),
+ );
+
+ expect(result?.benchmark.outputTokensPerSecond).toBe(92);
+ expect(result?.benchmark.costPerTask).toBe(0.42);
+ });
+
+ it('returns nothing for a model absent from the index', () => {
+ expect(match('mistral-large-2512', new Map())).toBeUndefined();
+ });
+
+ it('returns nothing for a matched row carrying no measurement at all', () => {
+ // The publisher lists models it has measured nothing about; matching one
+ // must not produce an entry holding only a timestamp.
+ expect(
+ match(
+ 'mistral-large-2512',
+ indexOf({ mistrallarge2512: { aliases: ['mistral-large-2512'] } }),
+ ),
+ ).toBeUndefined();
+ });
+
+ it('prefers the release a rolling alias resolves to over an undated row', () => {
+ const result = match(
+ 'mistral-large-latest',
+ indexOf({
+ mistrallarge: { intelligenceIndex: 20, aliases: [] },
+ mistrallarge2512: { intelligenceIndex: 41, aliases: [] },
+ }),
+ );
+
+ expect(result?.benchmark.intelligenceIndex).toBe(41);
+ });
+
+ it('collects the aliases the publisher gives so consumers can join on them', () => {
+ const result = match(
+ 'mistral-large-2512',
+ indexOf({
+ mistrallarge2512: {
+ intelligenceIndex: 41,
+ aliases: ['mistral-large-2512', 'mistralai/mistral-large-2512'],
+ },
+ }),
+ );
+
+ expect(result?.aliases).toEqual([
+ 'mistral-large-2512',
+ 'mistralai/mistral-large-2512',
+ ]);
+ });
+});
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/__tests__/read-committed-benchmarks.spec.ts b/packages/twenty-server/scripts/ai-catalog-sync/__tests__/read-committed-benchmarks.spec.ts
new file mode 100644
index 00000000000..c13c6d60a31
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/__tests__/read-committed-benchmarks.spec.ts
@@ -0,0 +1,68 @@
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+
+import { matchBenchmarks } from '../utils/match-benchmarks.util';
+import { readCommittedBenchmarks } from '../utils/read-committed-benchmarks.util';
+
+const writeOverlay = (value: unknown): string => {
+ const filePath = path.join(
+ fs.mkdtempSync(path.join(os.tmpdir(), 'overlay-')),
+ 'ai-model-benchmarks.json',
+ );
+
+ fs.writeFileSync(filePath, JSON.stringify(value), 'utf-8');
+
+ return filePath;
+};
+
+const PUBLISHED = {
+ source: 'artificialanalysis.ai',
+ measuredAt: '2026-09-01',
+ models: {
+ 'claude-sonnet-5': {
+ intelligenceIndex: 38.4,
+ outputTokensPerSecond: 92.1,
+ measuredAt: '2026-09-01',
+ aliases: ['claude-sonnet-5', 'claude-sonnet-5-20260630'],
+ },
+ },
+};
+
+describe('readCommittedBenchmarks', () => {
+ it('returns nothing when no overlay has been published yet', () => {
+ expect(
+ readCommittedBenchmarks(path.join(os.tmpdir(), 'does-not-exist.json'))
+ .size,
+ ).toBe(0);
+ });
+
+ it('recovers every measurement', () => {
+ const index = readCommittedBenchmarks(writeOverlay(PUBLISHED));
+ const record = index.get('claudesonnet5');
+
+ expect(record?.intelligenceIndex).toBe(38.4);
+ expect(record?.outputTokensPerSecond).toBe(92.1);
+ });
+
+ it('indexes the published aliases so matching still resolves them', () => {
+ const index = readCommittedBenchmarks(writeOverlay(PUBLISHED));
+
+ expect(index.get('claudesonnet520260630')?.intelligenceIndex).toBe(38.4);
+ });
+
+ it('keeps a preserved measurement dated when it was taken, not today', () => {
+ // Restamping recovered data as measured today would present a stale
+ // benchmark as fresh on every failed run.
+ const index = readCommittedBenchmarks(writeOverlay(PUBLISHED));
+
+ const result = matchBenchmarks({
+ modelName: 'claude-sonnet-5',
+ siblingModels: {},
+ benchmarkIndex: index,
+ measuredAt: '2026-09-09',
+ });
+
+ expect(result?.benchmark.measuredAt).toBe('2026-09-01');
+ });
+});
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/index.ts b/packages/twenty-server/scripts/ai-catalog-sync/index.ts
new file mode 100644
index 00000000000..aedd793ff5d
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/index.ts
@@ -0,0 +1,158 @@
+import * as fs from 'fs';
+import * as path from 'path';
+import * as prettier from 'prettier';
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { MODELS_DEV_API_URL } from 'src/engine/metadata-modules/ai/ai-models/constants/models-dev.const';
+import { type ModelsDevData } from 'src/engine/metadata-modules/ai/ai-models/types/models-dev-data.type';
+
+import { assertPayloadIsUsable } from './utils/assert-payload-is-usable.util';
+import { buildCatalog } from './utils/build-catalog.util';
+import { enrichCatalog } from './utils/enrich-catalog.util';
+import { fetchArtificialAnalysisBenchmarks } from './utils/fetch-artificial-analysis-benchmarks.util';
+import { readCommittedBenchmarks } from './utils/read-committed-benchmarks.util';
+import { buildCoverageReport } from './utils/build-coverage-report.util';
+import { renderCoverageReport } from './utils/render-coverage-report.util';
+import { type BenchmarkIndex } from './types/benchmark-index.type';
+
+const AI_MODELS_DIR = path.resolve(
+ __dirname,
+ '..',
+ '..',
+ 'src',
+ 'engine',
+ 'metadata-modules',
+ 'ai',
+ 'ai-models',
+);
+
+const CATALOG_PATH = path.join(AI_MODELS_DIR, 'ai-providers.json');
+const BENCHMARKS_PATH = path.join(AI_MODELS_DIR, 'ai-model-benchmarks.json');
+
+// oxlint-disable no-console
+const log = console.log;
+const warn = console.warn;
+// oxlint-enable no-console
+
+const readArgument = (flag: string): string | undefined => {
+ const index = process.argv.indexOf(flag);
+
+ return index === -1 ? undefined : process.argv[index + 1];
+};
+
+const fetchModelsDev = async (): Promise<ModelsDevData> => {
+ const response = await fetch(MODELS_DEV_API_URL, {
+ signal: AbortSignal.timeout(120000),
+ });
+
+ if (!response.ok) {
+ throw new Error(`${response.status} ${response.statusText}`);
+ }
+
+ const data: ModelsDevData = await response.json();
+
+ assertPayloadIsUsable(data);
+
+ return data;
+};
+
+// A leaderboard outage must never break the model catalog, so a failed fetch
+// degrades to an empty index and the catalog is written without benchmarks.
+const fetchBenchmarks = async (): Promise<BenchmarkIndex> => {
+ const apiKey = process.env.ARTIFICIAL_ANALYSIS_API_KEY;
+
+ if (!isDefined(apiKey) || apiKey.length === 0) {
+ warn('Skipping benchmarks: ARTIFICIAL_ANALYSIS_API_KEY is not set');
+
+ return new Map();
+ }
+
+ try {
+ const index = await fetchArtificialAnalysisBenchmarks(apiKey);
+
+ log(`Fetched ${index.size} model aliases from Artificial Analysis`);
+
+ return index;
+ } catch (error) {
+ warn(
+ `Skipping benchmarks: ${error instanceof Error ? error.message : String(error)}`,
+ );
+
+ return new Map();
+ }
+};
+
+const writeJson = async (filePath: string, value: unknown): Promise<void> => {
+ const prettierConfig = await prettier.resolveConfig(filePath);
+
+ const formatted = await prettier.format(
+ JSON.stringify(value, null, 2) + '\n',
+ { ...prettierConfig, filepath: filePath },
+ );
+
+ fs.writeFileSync(filePath, formatted, 'utf-8');
+ log(`Wrote ${filePath}`);
+};
+
+const main = async (): Promise<void> => {
+ const dryRun = process.argv.includes('--dry-run');
+ const reportPath = readArgument('--report');
+ const measuredAt = new Date().toISOString().slice(0, 10);
+
+ log('Fetching models.dev API...');
+
+ const modelsDevData = await fetchModelsDev();
+
+ log(`Fetched ${Object.keys(modelsDevData).length} providers from models.dev`);
+
+ const fetched = await fetchBenchmarks();
+
+ // A failed fetch must not delete measurements we already published: the
+ // catalog PR is automerged, so an empty index would silently strip every
+ // benchmark until the next healthy run.
+ const benchmarkIndex =
+ fetched.size > 0 ? fetched : readCommittedBenchmarks(BENCHMARKS_PATH);
+
+ if (fetched.size === 0 && benchmarkIndex.size > 0) {
+ warn(
+ `Reusing ${benchmarkIndex.size} committed benchmark aliases from a previous run`,
+ );
+ }
+
+ const catalog = buildCatalog(modelsDevData);
+
+ const overlay = enrichCatalog({
+ catalog,
+ modelsDevData,
+ benchmarkIndex,
+ measuredAt,
+ });
+
+ const renderedReport = renderCoverageReport(buildCoverageReport(catalog));
+
+ log(`\n${renderedReport}\n`);
+
+ if (isDefined(reportPath)) {
+ fs.writeFileSync(reportPath, `${renderedReport}\n`, 'utf-8');
+ }
+
+ if (dryRun) {
+ log('[DRY RUN] Skipping writes');
+
+ return;
+ }
+
+ await writeJson(CATALOG_PATH, catalog);
+ await writeJson(BENCHMARKS_PATH, {
+ source: 'artificialanalysis.ai',
+ measuredAt,
+ models: overlay,
+ });
+};
+
+main().catch((error) => {
+ // oxlint-disable-next-line no-console
+ console.error('AI catalog sync failed:', error);
+ process.exit(1);
+});
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/types/benchmark-index.type.ts b/packages/twenty-server/scripts/ai-catalog-sync/types/benchmark-index.type.ts
new file mode 100644
index 00000000000..2b256e62279
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/types/benchmark-index.type.ts
@@ -0,0 +1,5 @@
+import { type BenchmarkRecord } from './benchmark-record.type';
+
+// Keyed by normalized model name, so a single lookup resolves every alias a
+// source publishes for the same underlying model.
+export type BenchmarkIndex = Map<string, BenchmarkRecord>;
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/types/benchmark-match.type.ts b/packages/twenty-server/scripts/ai-catalog-sync/types/benchmark-match.type.ts
new file mode 100644
index 00000000000..4df7e326474
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/types/benchmark-match.type.ts
@@ -0,0 +1,6 @@
+import { type AiModelBenchmark } from 'src/engine/metadata-modules/ai/ai-models/types/ai-model-benchmark.type';
+
+export type BenchmarkMatch = {
+ benchmark: AiModelBenchmark;
+ aliases: string[];
+};
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/types/benchmark-overlay-entry.type.ts b/packages/twenty-server/scripts/ai-catalog-sync/types/benchmark-overlay-entry.type.ts
new file mode 100644
index 00000000000..baa901b487b
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/types/benchmark-overlay-entry.type.ts
@@ -0,0 +1,8 @@
+import { type AiModelBenchmark } from 'src/engine/metadata-modules/ai/ai-models/types/ai-model-benchmark.type';
+
+// The overlay is the cross-repo artifact: it carries what the catalog embeds
+// plus the alias set a joining consumer needs to find the model under the
+// publisher's own spelling.
+export type BenchmarkOverlayEntry = AiModelBenchmark & {
+ aliases: string[];
+};
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/types/benchmark-record.type.ts b/packages/twenty-server/scripts/ai-catalog-sync/types/benchmark-record.type.ts
new file mode 100644
index 00000000000..2b98fa78508
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/types/benchmark-record.type.ts
@@ -0,0 +1,9 @@
+export type BenchmarkRecord = {
+ intelligenceIndex?: number;
+ outputTokensPerSecond?: number;
+ costPerTask?: number;
+ // Set only on a record recovered from the committed overlay, so preserved
+ // measurements keep the date they were actually taken.
+ measuredAt?: string;
+ aliases: string[];
+};
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/types/coverage-report.type.ts b/packages/twenty-server/scripts/ai-catalog-sync/types/coverage-report.type.ts
new file mode 100644
index 00000000000..ef61d140241
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/types/coverage-report.type.ts
@@ -0,0 +1,6 @@
+export type CoverageReport = {
+ generalPurposeModelCount: number;
+ scoredGeneralPurposeModelCount: number;
+ unscoredGeneralPurposeModelIds: string[];
+ specializedModelCount: number;
+};
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/types/enrich-catalog-args.type.ts b/packages/twenty-server/scripts/ai-catalog-sync/types/enrich-catalog-args.type.ts
new file mode 100644
index 00000000000..c3ac7d0e0b5
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/types/enrich-catalog-args.type.ts
@@ -0,0 +1,11 @@
+import { type ModelsDevData } from 'src/engine/metadata-modules/ai/ai-models/types/models-dev-data.type';
+
+import { type BenchmarkIndex } from './benchmark-index.type';
+import { type GeneratedCatalog } from './generated-catalog.type';
+
+export type EnrichCatalogArgs = {
+ catalog: GeneratedCatalog;
+ modelsDevData: ModelsDevData;
+ benchmarkIndex: BenchmarkIndex;
+ measuredAt: string;
+};
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/types/generated-catalog.type.ts b/packages/twenty-server/scripts/ai-catalog-sync/types/generated-catalog.type.ts
new file mode 100644
index 00000000000..b887237c61f
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/types/generated-catalog.type.ts
@@ -0,0 +1,3 @@
+import { type GeneratedProvider } from './generated-provider.type';
+
+export type GeneratedCatalog = Record<string, GeneratedProvider>;
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/types/generated-model.type.ts b/packages/twenty-server/scripts/ai-catalog-sync/types/generated-model.type.ts
new file mode 100644
index 00000000000..4a216aeb2e4
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/types/generated-model.type.ts
@@ -0,0 +1,21 @@
+import { type AiModelBenchmark } from 'src/engine/metadata-modules/ai/ai-models/types/ai-model-benchmark.type';
+import { type LongContextCost } from 'src/engine/metadata-modules/ai/ai-models/types/long-context-cost.type';
+import { type ModelFamily } from 'src/engine/metadata-modules/ai/ai-models/types/model-family.enum';
+
+export type GeneratedModel = {
+ name: string;
+ label: string;
+ description?: string;
+ modelFamily?: ModelFamily;
+ inputCostPerMillionTokens?: number;
+ outputCostPerMillionTokens?: number;
+ cachedInputCostPerMillionTokens?: number;
+ cacheCreationCostPerMillionTokens?: number;
+ longContextCost?: LongContextCost;
+ contextWindowTokens?: number;
+ maxOutputTokens?: number;
+ modalities?: string[];
+ supportsReasoning?: boolean;
+ benchmark?: AiModelBenchmark;
+ isDeprecated?: boolean;
+};
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/types/generated-provider.type.ts b/packages/twenty-server/scripts/ai-catalog-sync/types/generated-provider.type.ts
new file mode 100644
index 00000000000..ebc6826d505
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/types/generated-provider.type.ts
@@ -0,0 +1,10 @@
+import { type AiSdkPackage } from 'twenty-shared/ai';
+
+import { type GeneratedModel } from './generated-model.type';
+
+export type GeneratedProvider = {
+ npm: AiSdkPackage;
+ label: string;
+ apiKey: string;
+ models: GeneratedModel[];
+};
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/types/match-benchmarks-args.type.ts b/packages/twenty-server/scripts/ai-catalog-sync/types/match-benchmarks-args.type.ts
new file mode 100644
index 00000000000..8d6d3bcbd38
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/types/match-benchmarks-args.type.ts
@@ -0,0 +1,10 @@
+import { type ModelsDevModel } from 'src/engine/metadata-modules/ai/ai-models/types/models-dev-model.type';
+
+import { type BenchmarkIndex } from './benchmark-index.type';
+
+export type MatchBenchmarksArgs = {
+ modelName: string;
+ siblingModels: Record<string, ModelsDevModel>;
+ benchmarkIndex: BenchmarkIndex;
+ measuredAt: string;
+};
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/utils/assert-payload-is-usable.util.ts b/packages/twenty-server/scripts/ai-catalog-sync/utils/assert-payload-is-usable.util.ts
new file mode 100644
index 00000000000..af30cde8182
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/utils/assert-payload-is-usable.util.ts
@@ -0,0 +1,18 @@
+import { NATIVE_AI_SDK_PROVIDER_IDS } from 'twenty-shared/ai';
+
+import { type ModelsDevData } from 'src/engine/metadata-modules/ai/ai-models/types/models-dev-data.type';
+
+// A 200 carrying an empty or reshaped payload would otherwise generate an
+// empty catalog, and the sync PR automerges over the real one.
+export const assertPayloadIsUsable = (data: ModelsDevData): void => {
+ const missing = NATIVE_AI_SDK_PROVIDER_IDS.filter(
+ (providerName) =>
+ Object.keys(data[providerName]?.models ?? {}).length === 0,
+ );
+
+ if (missing.length > 0) {
+ throw new Error(
+ `models.dev payload is missing models for ${missing.join(', ')}; refusing to overwrite the catalog`,
+ );
+ }
+};
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/utils/build-catalog.util.ts b/packages/twenty-server/scripts/ai-catalog-sync/utils/build-catalog.util.ts
new file mode 100644
index 00000000000..b5ccdf8ac6e
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/utils/build-catalog.util.ts
@@ -0,0 +1,181 @@
+import {
+ type AiSdkPackage,
+ NATIVE_AI_SDK_PROVIDER_IDS,
+} from 'twenty-shared/ai';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type ModelsDevData } from 'src/engine/metadata-modules/ai/ai-models/types/models-dev-data.type';
+import { type ModelsDevModel } from 'src/engine/metadata-modules/ai/ai-models/types/models-dev-model.type';
+import { inferModelFamily } from 'src/engine/metadata-modules/ai/ai-models/utils/infer-model-family.util';
+
+import { type GeneratedCatalog } from '../types/generated-catalog.type';
+import { type GeneratedModel } from '../types/generated-model.type';
+
+const EXCLUDED_MODEL_PREFIXES = [
+ 'text-embedding',
+ 'embedding',
+ 'dall-e',
+ 'tts-',
+ 'whisper',
+ 'moderation',
+ 'davinci',
+ 'babbage',
+ 'ada',
+ 'curie',
+ 'text-search',
+ 'text-similarity',
+ 'code-search',
+ 'text-davinci',
+ 'text-curie',
+ 'text-babbage',
+ 'text-ada',
+ 'ft:',
+ 'canary',
+];
+
+const EXCLUDED_MODEL_SUFFIXES = ['-audio-preview', '-realtime-preview'];
+
+const LONG_CONTEXT_THRESHOLD_TOKENS = 200000;
+
+const PROVIDER_LABELS: Record<string, string> = {
+ openai: 'OpenAI',
+ anthropic: 'Anthropic',
+ google: 'Google',
+ mistral: 'Mistral',
+ xai: 'xAI',
+};
+
+const API_KEY_TEMPLATES: Record<string, string> = {
+ openai: '{{OPENAI_API_KEY}}',
+ anthropic: '{{ANTHROPIC_API_KEY}}',
+ google: '{{GOOGLE_API_KEY}}',
+ mistral: '{{MISTRAL_API_KEY}}',
+ xai: '{{XAI_API_KEY}}',
+};
+
+const isLanguageModel = (modelId: string): boolean => {
+ const lowerId = modelId.toLowerCase();
+
+ if (EXCLUDED_MODEL_PREFIXES.some((prefix) => lowerId.startsWith(prefix))) {
+ return false;
+ }
+
+ return !EXCLUDED_MODEL_SUFFIXES.some((suffix) => lowerId.endsWith(suffix));
+};
+
+const meetsInclusionCriteria = (modelData: ModelsDevModel): boolean =>
+ modelData.status !== 'beta' &&
+ (modelData.tool_call ?? false) &&
+ isDefined(modelData.cost?.input) &&
+ isDefined(modelData.limit?.context);
+
+const extractCost = ({
+ modelData,
+ model,
+}: {
+ modelData: ModelsDevModel;
+ model: GeneratedModel;
+}): void => {
+ const cost = modelData.cost;
+
+ if (!isDefined(cost)) {
+ return;
+ }
+
+ model.inputCostPerMillionTokens = cost.input;
+ model.outputCostPerMillionTokens = cost.output;
+ model.cachedInputCostPerMillionTokens = cost.cache_read;
+ model.cacheCreationCostPerMillionTokens = cost.cache_write;
+
+ const longContextCost = cost.context_over_200k;
+
+ if (!isDefined(longContextCost?.input)) {
+ return;
+ }
+
+ model.longContextCost = {
+ inputCostPerMillionTokens: longContextCost.input,
+ outputCostPerMillionTokens:
+ longContextCost.output ?? model.outputCostPerMillionTokens ?? 0,
+ thresholdTokens: LONG_CONTEXT_THRESHOLD_TOKENS,
+ cachedInputCostPerMillionTokens: longContextCost.cache_read,
+ cacheCreationCostPerMillionTokens: longContextCost.cache_write,
+ };
+};
+
+const buildModel = ({
+ providerName,
+ modelId,
+ modelData,
+}: {
+ providerName: string;
+ modelId: string;
+ modelData: ModelsDevModel;
+}): GeneratedModel => {
+ const model: GeneratedModel = {
+ name: modelId,
+ label: modelData.name ?? modelId,
+ modelFamily: inferModelFamily(providerName, modelId),
+ };
+
+ extractCost({ modelData, model });
+
+ model.contextWindowTokens = modelData.limit?.context;
+ model.maxOutputTokens = modelData.limit?.output;
+
+ const modalities = (modelData.modalities?.input ?? []).filter(
+ (modality) => modality !== 'text',
+ );
+
+ if (modalities.length > 0) {
+ model.modalities = modalities;
+ }
+
+ if (modelData.reasoning) {
+ model.supportsReasoning = true;
+ }
+
+ if (modelData.status === 'deprecated') {
+ model.isDeprecated = true;
+ }
+
+ return model;
+};
+
+export const buildCatalog = (data: ModelsDevData): GeneratedCatalog => {
+ const catalog: GeneratedCatalog = {};
+
+ for (const providerName of NATIVE_AI_SDK_PROVIDER_IDS) {
+ const providerData = data[providerName];
+
+ if (!isDefined(providerData)) {
+ // oxlint-disable-next-line no-console
+ console.warn(`Provider "${providerName}" not found in models.dev`);
+ continue;
+ }
+
+ const models = Object.entries(providerData.models)
+ .filter(
+ ([modelId, modelData]) =>
+ isLanguageModel(modelId) && meetsInclusionCriteria(modelData),
+ )
+ .map(([modelId, modelData]) =>
+ buildModel({ providerName, modelId, modelData }),
+ );
+
+ if (models.length === 0) {
+ // oxlint-disable-next-line no-console
+ console.warn(`No qualifying models for "${providerName}", skipping`);
+ continue;
+ }
+
+ catalog[providerName] = {
+ npm: `@ai-sdk/${providerName}` as AiSdkPackage,
+ label: PROVIDER_LABELS[providerName] ?? providerName,
+ apiKey: API_KEY_TEMPLATES[providerName] ?? '',
+ models,
+ };
+ }
+
+ return catalog;
+};
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/utils/build-coverage-report.util.ts b/packages/twenty-server/scripts/ai-catalog-sync/utils/build-coverage-report.util.ts
new file mode 100644
index 00000000000..91843c9bfb3
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/utils/build-coverage-report.util.ts
@@ -0,0 +1,47 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type CoverageReport } from '../types/coverage-report.type';
+import { type GeneratedCatalog } from '../types/generated-catalog.type';
+
+// Models whose job is not general reasoning (speech, image, embeddings,
+// computer use, deep research). A capability index for them would be
+// meaningless, so they are excluded from the coverage denominator rather than
+// counted as gaps.
+const SPECIALIZED_MODEL_PATTERN =
+ /realtime|voxtral|tts|audio|-live|computer-use|deep-research|-image|pixtral|codestral|embed/;
+
+export const buildCoverageReport = (
+ catalog: GeneratedCatalog,
+): CoverageReport => {
+ const report: CoverageReport = {
+ generalPurposeModelCount: 0,
+ scoredGeneralPurposeModelCount: 0,
+ unscoredGeneralPurposeModelIds: [],
+ specializedModelCount: 0,
+ };
+
+ for (const [providerName, provider] of Object.entries(catalog)) {
+ for (const model of provider.models) {
+ if (model.isDeprecated) {
+ continue;
+ }
+
+ if (SPECIALIZED_MODEL_PATTERN.test(model.name)) {
+ report.specializedModelCount += 1;
+ continue;
+ }
+
+ report.generalPurposeModelCount += 1;
+
+ if (isDefined(model.benchmark?.intelligenceIndex)) {
+ report.scoredGeneralPurposeModelCount += 1;
+ } else {
+ report.unscoredGeneralPurposeModelIds.push(
+ `${providerName}/${model.name}`,
+ );
+ }
+ }
+ }
+
+ return report;
+};
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/utils/build-lookup-candidates.util.ts b/packages/twenty-server/scripts/ai-catalog-sync/utils/build-lookup-candidates.util.ts
new file mode 100644
index 00000000000..f357af829e1
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/utils/build-lookup-candidates.util.ts
@@ -0,0 +1,67 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type ModelsDevModel } from 'src/engine/metadata-modules/ai/ai-models/types/models-dev-model.type';
+
+const DATE_SUFFIX = /-\d{4}-?\d{2}-?\d{2}$/;
+const ROLLING_SUFFIX = /-(latest|preview|exp)$/;
+
+const fingerprint = (model: ModelsDevModel): string =>
+ JSON.stringify([model.cost ?? {}, model.limit ?? {}]);
+
+// `mistral-large-latest` is never benchmarked under that name, so it is
+// resolved to the dated release it currently points at by matching price and
+// limits against its non-rolling siblings. Re-resolves on its own when the
+// provider repoints the alias.
+const resolveRollingAlias = (
+ modelName: string,
+ siblingModels: Record<string, ModelsDevModel>,
+): string | undefined => {
+ const model = siblingModels[modelName];
+
+ if (!isDefined(model) || !ROLLING_SUFFIX.test(modelName)) {
+ return undefined;
+ }
+
+ const target = fingerprint(model);
+
+ const twins = Object.entries(siblingModels)
+ .filter(
+ ([siblingName, sibling]) =>
+ siblingName !== modelName &&
+ !ROLLING_SUFFIX.test(siblingName) &&
+ fingerprint(sibling) === target,
+ )
+ // Falling back to the name keeps this deterministic when a provider dates
+ // neither twin, and for the date-stamped ids providers actually use it
+ // still lands on the newer one.
+ .sort(
+ ([nameA, a], [nameB, b]) =>
+ (b.release_date ?? '').localeCompare(a.release_date ?? '') ||
+ nameB.localeCompare(nameA),
+ );
+
+ return twins[0]?.[0];
+};
+
+export const buildLookupCandidates = ({
+ modelName,
+ siblingModels,
+}: {
+ modelName: string;
+ siblingModels: Record<string, ModelsDevModel>;
+}): string[] => {
+ const candidates = [modelName, modelName.replace(DATE_SUFFIX, '')];
+
+ const resolved = resolveRollingAlias(modelName, siblingModels);
+
+ if (isDefined(resolved)) {
+ candidates.push(resolved, resolved.replace(DATE_SUFFIX, ''));
+ }
+
+ // Last: an undated `mistral-large` row in the index is whichever release the
+ // publisher last measured, so it must not win over the release the alias
+ // currently resolves to.
+ candidates.push(modelName.replace(ROLLING_SUFFIX, ''));
+
+ return [...new Set(candidates)];
+};
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/utils/enrich-catalog.util.ts b/packages/twenty-server/scripts/ai-catalog-sync/utils/enrich-catalog.util.ts
new file mode 100644
index 00000000000..c172c4011d3
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/utils/enrich-catalog.util.ts
@@ -0,0 +1,44 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type BenchmarkOverlayEntry } from '../types/benchmark-overlay-entry.type';
+import { type EnrichCatalogArgs } from '../types/enrich-catalog-args.type';
+
+import { matchBenchmarks } from './match-benchmarks.util';
+
+export const enrichCatalog = ({
+ catalog,
+ modelsDevData,
+ benchmarkIndex,
+ measuredAt,
+}: EnrichCatalogArgs): Record<string, BenchmarkOverlayEntry> => {
+ const overlay: Record<string, BenchmarkOverlayEntry> = {};
+
+ for (const [providerName, provider] of Object.entries(catalog)) {
+ const siblingModels = modelsDevData[providerName]?.models ?? {};
+
+ provider.models = provider.models.map((model) => {
+ const match = matchBenchmarks({
+ modelName: model.name,
+ siblingModels,
+ benchmarkIndex,
+ measuredAt,
+ });
+
+ if (!isDefined(match)) {
+ return model;
+ }
+
+ overlay[model.name] = { ...match.benchmark, aliases: match.aliases };
+
+ const { isDeprecated, ...rest } = model;
+
+ return {
+ ...rest,
+ benchmark: match.benchmark,
+ ...(isDefined(isDeprecated) ? { isDeprecated } : {}),
+ };
+ });
+ }
+
+ return overlay;
+};
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/utils/fetch-artificial-analysis-benchmarks.util.ts b/packages/twenty-server/scripts/ai-catalog-sync/utils/fetch-artificial-analysis-benchmarks.util.ts
new file mode 100644
index 00000000000..fe241b99b12
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/utils/fetch-artificial-analysis-benchmarks.util.ts
@@ -0,0 +1,138 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { normalizeModelName } from './normalize-model-name.util';
+import { type BenchmarkIndex } from '../types/benchmark-index.type';
+import { type BenchmarkRecord } from '../types/benchmark-record.type';
+
+const DEFAULT_ARTIFICIAL_ANALYSIS_API_URL =
+ 'https://artificialanalysis.ai/api/v2/data/llms/models';
+
+type ArtificialAnalysisModel = Record<string, unknown> & {
+ id?: string;
+ slug?: string;
+ name?: string;
+};
+
+// This endpoint returns 0 for "not measured", and a zero tokens-per-second is a
+// lie rather than a datum.
+const readPositiveNumber = (value: unknown): number | undefined =>
+ typeof value === 'number' && Number.isFinite(value) && value > 0
+ ? value
+ : undefined;
+
+const readNested = ({
+ model,
+ containerKey,
+ leafKey,
+}: {
+ model: ArtificialAnalysisModel;
+ containerKey: string;
+ leafKey: string;
+}): number | undefined => {
+ const container = model[containerKey];
+
+ if (typeof container !== 'object' || container === null) {
+ return undefined;
+ }
+
+ return readPositiveNumber((container as Record<string, unknown>)[leafKey]);
+};
+
+const readModels = (payload: unknown): ArtificialAnalysisModel[] => {
+ if (Array.isArray(payload)) {
+ return payload as ArtificialAnalysisModel[];
+ }
+
+ const data = (payload as { data?: unknown } | null)?.data;
+
+ return Array.isArray(data) ? (data as ArtificialAnalysisModel[]) : [];
+};
+
+// How much a row actually says. The endpoint carries several rows per model and
+// some hosts publish no measurements at all, so an unmeasured row must never
+// displace a measured one under the same key.
+const informationScore = (record: BenchmarkRecord): number =>
+ [
+ record.intelligenceIndex,
+ record.outputTokensPerSecond,
+ record.costPerTask,
+ ].filter(isDefined).length;
+
+export const fetchArtificialAnalysisBenchmarks = async (
+ apiKey: string,
+): Promise<BenchmarkIndex> => {
+ const url =
+ process.env.ARTIFICIAL_ANALYSIS_API_URL ??
+ DEFAULT_ARTIFICIAL_ANALYSIS_API_URL;
+
+ const response = await fetch(url, {
+ headers: { 'x-api-key': apiKey },
+ signal: AbortSignal.timeout(60000),
+ });
+
+ if (!response.ok) {
+ throw new Error(`${response.status} ${response.statusText}`);
+ }
+
+ const models = readModels(await response.json());
+
+ if (models.length === 0) {
+ throw new Error(`No models in response from ${url}`);
+ }
+
+ const index: BenchmarkIndex = new Map();
+
+ for (const model of models) {
+ // One malformed row must not cost us every measurement in the response.
+ if (typeof model !== 'object' || model === null) {
+ continue;
+ }
+
+ const aliases = [model.slug, model.id, model.name].filter(isDefined);
+
+ // The intelligence index sits under `evaluations` and cost per task under
+ // `cost_per_task`; only the speed figure is top level. Reading them all
+ // from the top level yields matched models carrying no usable number.
+ const record: BenchmarkRecord = {
+ intelligenceIndex: readNested({
+ model,
+ containerKey: 'evaluations',
+ leafKey: 'artificial_analysis_intelligence_index',
+ }),
+ outputTokensPerSecond: readPositiveNumber(
+ model.median_output_tokens_per_second,
+ ),
+ costPerTask: readNested({
+ model,
+ containerKey: 'cost_per_task',
+ leafKey: 'total_cost',
+ }),
+ aliases,
+ };
+
+ if (informationScore(record) === 0) {
+ continue;
+ }
+
+ for (const alias of aliases) {
+ const key = normalizeModelName(alias);
+ const existing = index.get(key);
+
+ if (
+ key.length > 0 &&
+ (!isDefined(existing) ||
+ informationScore(record) > informationScore(existing))
+ ) {
+ index.set(key, record);
+ }
+ }
+ }
+
+ if (index.size === 0) {
+ throw new Error(
+ `${models.length} models returned from ${url} but none carried a measurement`,
+ );
+ }
+
+ return index;
+};
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/utils/match-benchmarks.util.ts b/packages/twenty-server/scripts/ai-catalog-sync/utils/match-benchmarks.util.ts
new file mode 100644
index 00000000000..983a5a0457b
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/utils/match-benchmarks.util.ts
@@ -0,0 +1,60 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type BenchmarkIndex } from '../types/benchmark-index.type';
+import { type BenchmarkMatch } from '../types/benchmark-match.type';
+import { type BenchmarkRecord } from '../types/benchmark-record.type';
+import { type MatchBenchmarksArgs } from '../types/match-benchmarks-args.type';
+
+import { buildLookupCandidates } from './build-lookup-candidates.util';
+import { normalizeModelName } from './normalize-model-name.util';
+
+const lookup = (
+ index: BenchmarkIndex,
+ candidates: string[],
+): BenchmarkRecord | undefined => {
+ for (const candidate of candidates) {
+ const record = index.get(normalizeModelName(candidate));
+
+ if (isDefined(record)) {
+ return record;
+ }
+ }
+
+ return undefined;
+};
+
+export const matchBenchmarks = ({
+ modelName,
+ siblingModels,
+ benchmarkIndex,
+ measuredAt,
+}: MatchBenchmarksArgs): BenchmarkMatch | undefined => {
+ const record = lookup(
+ benchmarkIndex,
+ buildLookupCandidates({ modelName, siblingModels }),
+ );
+
+ if (!isDefined(record)) {
+ return undefined;
+ }
+
+ const { intelligenceIndex, outputTokensPerSecond, costPerTask } = record;
+
+ // The publisher lists plenty of models it has measured nothing about, and a
+ // row of pure aliases says nothing worth carrying into either artifact.
+ if (
+ ![intelligenceIndex, outputTokensPerSecond, costPerTask].some(isDefined)
+ ) {
+ return undefined;
+ }
+
+ return {
+ benchmark: {
+ intelligenceIndex,
+ outputTokensPerSecond,
+ costPerTask,
+ measuredAt: record.measuredAt ?? measuredAt,
+ },
+ aliases: [...new Set([modelName, ...record.aliases])],
+ };
+};
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/utils/normalize-model-name.util.ts b/packages/twenty-server/scripts/ai-catalog-sync/utils/normalize-model-name.util.ts
new file mode 100644
index 00000000000..f2492879a95
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/utils/normalize-model-name.util.ts
@@ -0,0 +1,12 @@
+// Benchmark publishers, providers and the AI SDK all spell the same model
+// differently (`claude-sonnet-4-6`, `claude-sonnet-4.6`, `Claude Sonnet 4.6`),
+// so every lookup key goes through this before it is compared. The trailing
+// `-v1:0` strip lets a Bedrock deployment id join the same row as the model it
+// serves.
+export const normalizeModelName = (modelName: string): string =>
+ modelName
+ .toLowerCase()
+ .replace(/:batch$/, '')
+ .replace(/\(.*\)/g, '')
+ .replace(/-v\d+(:\d+)?$/, '')
+ .replace(/[\s.\-_/]/g, '');
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/utils/read-committed-benchmarks.util.ts b/packages/twenty-server/scripts/ai-catalog-sync/utils/read-committed-benchmarks.util.ts
new file mode 100644
index 00000000000..e3e40245ed6
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/utils/read-committed-benchmarks.util.ts
@@ -0,0 +1,52 @@
+import * as fs from 'fs';
+
+import { normalizeModelName } from './normalize-model-name.util';
+import { type BenchmarkIndex } from '../types/benchmark-index.type';
+import { type BenchmarkRecord } from '../types/benchmark-record.type';
+
+type CommittedEntry = Partial<BenchmarkRecord> & {
+ measuredAt?: string;
+ aliases?: string[];
+};
+
+// The last published measurements, read back so a failed fetch degrades to
+// stale data rather than deleting the catalog's benchmarks. Each record keeps
+// its own measuredAt, so a stale entry stays visibly stale.
+export const readCommittedBenchmarks = (filePath: string): BenchmarkIndex => {
+ if (!fs.existsSync(filePath)) {
+ return new Map();
+ }
+
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf-8')) as {
+ models?: Record<string, CommittedEntry>;
+ };
+
+ const index: BenchmarkIndex = new Map();
+
+ for (const [modelName, entry] of Object.entries(parsed.models ?? {})) {
+ const record: BenchmarkRecord = {
+ intelligenceIndex: entry.intelligenceIndex,
+ outputTokensPerSecond: entry.outputTokensPerSecond,
+ costPerTask: entry.costPerTask,
+ measuredAt: entry.measuredAt,
+ aliases: entry.aliases ?? [modelName],
+ };
+
+ for (const alias of record.aliases) {
+ const key = normalizeModelName(alias);
+
+ if (key.length > 0 && !index.has(key)) {
+ index.set(key, record);
+ }
+ }
+
+ // An entry always claims its own name, whatever a sibling's alias list says.
+ const ownKey = normalizeModelName(modelName);
+
+ if (ownKey.length > 0) {
+ index.set(ownKey, record);
+ }
+ }
+
+ return index;
+};
diff --git a/packages/twenty-server/scripts/ai-catalog-sync/utils/render-coverage-report.util.ts b/packages/twenty-server/scripts/ai-catalog-sync/utils/render-coverage-report.util.ts
new file mode 100644
index 00000000000..2388caa7c10
--- /dev/null
+++ b/packages/twenty-server/scripts/ai-catalog-sync/utils/render-coverage-report.util.ts
@@ -0,0 +1,37 @@
+import { type CoverageReport } from '../types/coverage-report.type';
+
+const asPercentage = ({
+ numerator,
+ denominator,
+}: {
+ numerator: number;
+ denominator: number;
+}): string =>
+ denominator === 0 ? 'n/a' : `${Math.round((numerator / denominator) * 100)}%`;
+
+export const renderCoverageReport = (report: CoverageReport): string => {
+ const {
+ generalPurposeModelCount: total,
+ scoredGeneralPurposeModelCount: scored,
+ } = report;
+
+ const lines = [
+ '### Benchmark coverage',
+ '',
+ `- General-purpose models with an intelligence index: **${scored}/${total}** (${asPercentage({ numerator: scored, denominator: total })})`,
+ `- Specialized models excluded from the denominator: ${report.specializedModelCount}`,
+ ];
+
+ if (report.unscoredGeneralPurposeModelIds.length > 0) {
+ lines.push(
+ '',
+ '<details><summary>General-purpose models with no matched intelligence index</summary>',
+ '',
+ ...report.unscoredGeneralPurposeModelIds.map((modelId) => `- ${modelId}`),
+ '',
+ '</details>',
+ );
+ }
+
+ return lines.join('\n');
+};
diff --git a/packages/twenty-server/scripts/ai-sync-models-dev.ts b/packages/twenty-server/scripts/ai-sync-models-dev.ts
deleted file mode 100644
index 8de0df0d2b8..00000000000
--- a/packages/twenty-server/scripts/ai-sync-models-dev.ts
+++ /dev/null
@@ -1,349 +0,0 @@
-import * as fs from 'fs';
-import * as path from 'path';
-import * as prettier from 'prettier';
-
-import {
- type AiSdkPackage,
- NATIVE_AI_SDK_PROVIDER_IDS,
-} from 'twenty-shared/ai';
-
-import { MODELS_DEV_API_URL } from 'src/engine/metadata-modules/ai/ai-models/constants/models-dev.const';
-import { type ModelFamily } from 'src/engine/metadata-modules/ai/ai-models/types/model-family.enum';
-import { type ModelsDevData } from 'src/engine/metadata-modules/ai/ai-models/types/models-dev-data.type';
-import { inferModelFamily } from 'src/engine/metadata-modules/ai/ai-models/utils/infer-model-family.util';
-
-const EXCLUDED_MODEL_PREFIXES = [
- 'text-embedding',
- 'embedding',
- 'dall-e',
- 'tts-',
- 'whisper',
- 'moderation',
- 'davinci',
- 'babbage',
- 'ada',
- 'curie',
- 'text-search',
- 'text-similarity',
- 'code-search',
- 'text-davinci',
- 'text-curie',
- 'text-babbage',
- 'text-ada',
- 'ft:',
- 'canary',
-];
-
-const EXCLUDED_MODEL_SUFFIXES = ['-audio-preview', '-realtime-preview'];
-
-const LONG_CONTEXT_THRESHOLD_TOKENS = 200000;
-
-const PROVIDER_LABELS: Record<string, string> = {
- openai: 'OpenAI',
- anthropic: 'Anthropic',
- google: 'Google',
- mistral: 'Mistral',
- xai: 'xAI',
-};
-
-const API_KEY_TEMPLATES: Record<string, string> = {
- openai: '{{OPENAI_API_KEY}}',
- anthropic: '{{ANTHROPIC_API_KEY}}',
- google: '{{GOOGLE_API_KEY}}',
- mistral: '{{MISTRAL_API_KEY}}',
- xai: '{{XAI_API_KEY}}',
-};
-
-type LongContextCostEntry = {
- inputCostPerMillionTokens: number;
- outputCostPerMillionTokens: number;
- cachedInputCostPerMillionTokens?: number;
- cacheCreationCostPerMillionTokens?: number;
- thresholdTokens: number;
-};
-
-type GeneratedModel = {
- name: string;
- label: string;
- description?: string;
- modelFamily?: ModelFamily;
- inputCostPerMillionTokens?: number;
- outputCostPerMillionTokens?: number;
- cachedInputCostPerMillionTokens?: number;
- cacheCreationCostPerMillionTokens?: number;
- longContextCost?: LongContextCostEntry;
- contextWindowTokens?: number;
- maxOutputTokens?: number;
- modalities?: string[];
- supportsReasoning?: boolean;
- isDeprecated?: boolean;
-};
-
-type GeneratedProvider = {
- npm: AiSdkPackage;
- label: string;
- apiKey: string;
- models: GeneratedModel[];
-};
-
-const isLanguageModel = (modelId: string): boolean => {
- const lowerId = modelId.toLowerCase();
-
- for (const prefix of EXCLUDED_MODEL_PREFIXES) {
- if (lowerId.startsWith(prefix)) return false;
- }
-
- for (const suffix of EXCLUDED_MODEL_SUFFIXES) {
- if (lowerId.endsWith(suffix)) return false;
- }
-
- return true;
-};
-
-const meetsInclusionCriteria = (
- modelData: Record<string, unknown>,
-): boolean => {
- if (modelData.status === 'beta') return false;
- if (modelData.tool_call !== true) return false;
-
- const cost = modelData.cost as
- | { input?: number; output?: number }
- | undefined;
-
- if (cost?.input === undefined) return false;
-
- const limit = modelData.limit as
- | { context?: number; output?: number }
- | undefined;
-
- if (limit?.context === undefined) return false;
-
- return true;
-};
-
-const extractCost = (
- modelData: Record<string, unknown>,
- model: GeneratedModel,
-): void => {
- const cost = modelData.cost as Record<string, unknown> | undefined;
-
- if (!cost) return;
-
- if (typeof cost.input === 'number') {
- model.inputCostPerMillionTokens = cost.input;
- }
- if (typeof cost.output === 'number') {
- model.outputCostPerMillionTokens = cost.output;
- }
- if (typeof cost.cache_read === 'number') {
- model.cachedInputCostPerMillionTokens = cost.cache_read;
- }
- if (typeof cost.cache_write === 'number') {
- model.cacheCreationCostPerMillionTokens = cost.cache_write;
- }
-
- const longCtx = cost.context_over_200k as Record<string, unknown> | undefined;
-
- if (longCtx && typeof longCtx.input === 'number') {
- model.longContextCost = {
- inputCostPerMillionTokens: longCtx.input as number,
- outputCostPerMillionTokens: (longCtx.output as number) ?? 0,
- thresholdTokens: LONG_CONTEXT_THRESHOLD_TOKENS,
- };
- if (typeof longCtx.cache_read === 'number') {
- model.longContextCost.cachedInputCostPerMillionTokens =
- longCtx.cache_read;
- }
- if (typeof longCtx.cache_write === 'number') {
- model.longContextCost.cacheCreationCostPerMillionTokens =
- longCtx.cache_write;
- }
- }
-};
-
-const extractLimits = (
- modelData: Record<string, unknown>,
- model: GeneratedModel,
-): void => {
- const limit = modelData.limit as Record<string, unknown> | undefined;
-
- if (!limit) return;
-
- if (typeof limit.context === 'number') {
- model.contextWindowTokens = limit.context;
- }
- if (typeof limit.output === 'number') {
- model.maxOutputTokens = limit.output;
- }
-};
-
-const extractModalities = (
- modelData: Record<string, unknown>,
- model: GeneratedModel,
-): void => {
- const modalities = modelData.modalities as { input?: string[] } | undefined;
-
- if (!modalities?.input) return;
-
- const relevant = modalities.input.filter((modality) => modality !== 'text');
-
- if (relevant.length > 0) {
- model.modalities = relevant;
- }
-};
-
-const buildModelsForProvider = (
- providerName: string,
- modelsDevModels: Record<string, { name: string } & Record<string, unknown>>,
-): GeneratedModel[] => {
- const qualifying: GeneratedModel[] = [];
-
- for (const [modelId, modelData] of Object.entries(modelsDevModels)) {
- if (!isLanguageModel(modelId)) continue;
- if (!meetsInclusionCriteria(modelData)) continue;
-
- const family = inferModelFamily(providerName, modelId);
-
- const model: GeneratedModel = {
- name: modelId,
- label: modelData.name ?? modelId,
- modelFamily: family,
- };
-
- extractCost(modelData, model);
- extractLimits(modelData, model);
- extractModalities(modelData, model);
-
- if (modelData.reasoning === true) {
- model.supportsReasoning = true;
- }
-
- if (modelData.status === 'deprecated') {
- model.isDeprecated = true;
- }
-
- qualifying.push(model);
- }
-
- return qualifying;
-};
-
-const generateCatalog = (
- data: ModelsDevData,
-): Record<string, GeneratedProvider> => {
- const result: Record<string, GeneratedProvider> = {};
-
- for (const providerName of NATIVE_AI_SDK_PROVIDER_IDS) {
- const providerData = data[providerName];
-
- if (!providerData) {
- // oxlint-disable-next-line no-console
- console.warn(`Provider "${providerName}" not found in models.dev`);
- continue;
- }
-
- const models = buildModelsForProvider(providerName, providerData.models);
-
- if (models.length === 0) {
- // oxlint-disable-next-line no-console
- console.warn(`No qualifying models for "${providerName}", skipping`);
- continue;
- }
-
- result[providerName] = {
- npm: `@ai-sdk/${providerName}`,
- label: PROVIDER_LABELS[providerName] ?? providerName,
- apiKey: API_KEY_TEMPLATES[providerName] ?? '',
- models,
- };
- }
-
- return result;
-};
-
-const printSummary = (catalog: Record<string, GeneratedProvider>): void => {
- // oxlint-disable-next-line no-console
- console.log('=== Generation Summary ===');
-
- let totalModels = 0;
- let deprecatedCount = 0;
-
- for (const [providerName, provider] of Object.entries(catalog)) {
- const deprecatedModelCount = provider.models.filter(
- (model) => model.isDeprecated,
- ).length;
- const active = provider.models.length - deprecatedModelCount;
-
- // oxlint-disable-next-line no-console
- console.log(
- ` ${providerName}: ${provider.models.length} models (${active} active, ${deprecatedModelCount} deprecated)`,
- );
- totalModels += provider.models.length;
- deprecatedCount += deprecatedModelCount;
- }
-
- // oxlint-disable-next-line no-console
- console.log(
- `Total: ${totalModels} models (${totalModels - deprecatedCount} active, ${deprecatedCount} deprecated)`,
- );
-};
-
-const main = async (): Promise<void> => {
- const dryRun = process.argv.includes('--dry-run');
-
- // oxlint-disable-next-line no-console
- console.log('Fetching models.dev API...');
-
- const response = await fetch(MODELS_DEV_API_URL);
-
- if (!response.ok) {
- throw new Error(
- `Failed to fetch: ${response.status} ${response.statusText}`,
- );
- }
-
- const data: ModelsDevData = await response.json();
-
- // oxlint-disable-next-line no-console
- console.log(`Fetched ${Object.keys(data).length} providers from models.dev`);
-
- const generated = generateCatalog(data);
- const json = JSON.stringify(generated, null, 2) + '\n';
-
- printSummary(generated);
-
- if (dryRun) {
- // oxlint-disable-next-line no-console
- console.log('[DRY RUN] Would write ai-providers.json');
-
- return;
- }
-
- const outputPath = path.resolve(
- __dirname,
- '..',
- 'src',
- 'engine',
- 'metadata-modules',
- 'ai',
- 'ai-models',
- 'ai-providers.json',
- );
-
- const prettierConfig = await prettier.resolveConfig(outputPath);
-
- const formatted = await prettier.format(json, {
- ...prettierConfig,
- filepath: outputPath,
- });
-
- fs.writeFileSync(outputPath, formatted, 'utf-8');
- // oxlint-disable-next-line no-console
- console.log(`Wrote ${outputPath}`);
-};
-
-main().catch((error) => {
- // oxlint-disable-next-line no-console
- console.error('AI catalog sync failed:', error);
- process.exit(1);
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/__tests__/ai-model-benchmarks-json.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/__tests__/ai-model-benchmarks-json.spec.ts
new file mode 100644
index 00000000000..95539a9c63b
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/__tests__/ai-model-benchmarks-json.spec.ts
@@ -0,0 +1,52 @@
+import benchmarkOverlay from 'src/engine/metadata-modules/ai/ai-models/ai-model-benchmarks.json';
+import defaultAiProviders from 'src/engine/metadata-modules/ai/ai-models/ai-providers.json';
+import { aiModelBenchmarkSchema } from 'src/engine/metadata-modules/ai/ai-models/types/ai-model-benchmark.schema';
+import { type AiProvidersConfig } from 'src/engine/metadata-modules/ai/ai-models/types/ai-providers-config.type';
+
+const OVERLAY_MODELS = benchmarkOverlay.models as Record<
+ string,
+ { aliases: string[] } & Record<string, unknown>
+>;
+
+const CATALOG_MODELS = Object.values(
+ defaultAiProviders as AiProvidersConfig,
+).flatMap((provider) => provider.models ?? []);
+
+describe('ai-model-benchmarks.json integrity', () => {
+ it('should name the publisher every figure came from', () => {
+ expect(benchmarkOverlay.source).toBe('artificialanalysis.ai');
+ });
+
+ it('should pass Zod schema validation for every entry', () => {
+ Object.values(OVERLAY_MODELS).forEach(({ aliases: _aliases, ...entry }) => {
+ expect(() => aiModelBenchmarkSchema.parse(entry)).not.toThrow();
+ });
+ });
+
+ it('should agree with the benchmark merged into the catalog', () => {
+ // The overlay is empty until the sync runs with an API key configured, so
+ // this checks the two artifacts cannot drift rather than pinning a count.
+ const scored = CATALOG_MODELS.filter(
+ (model) => model.benchmark !== undefined,
+ );
+
+ scored.forEach((model) => {
+ const { aliases, ...overlayEntry } = OVERLAY_MODELS[model.name];
+
+ expect(overlayEntry).toEqual(model.benchmark);
+ expect(aliases).toContain(model.name);
+ });
+ });
+
+ it('should hold no entry for a model the catalog does not score', () => {
+ const scoredNames = new Set(
+ CATALOG_MODELS.filter((model) => model.benchmark !== undefined).map(
+ (model) => model.name,
+ ),
+ );
+
+ Object.keys(OVERLAY_MODELS).forEach((name) => {
+ expect(scoredNames.has(name)).toBe(true);
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/__tests__/ai-providers-json.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/__tests__/ai-providers-json.spec.ts
index 40ab1cc471e..c542a3e7440 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/__tests__/ai-providers-json.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/__tests__/ai-providers-json.spec.ts
@@ -74,6 +74,19 @@ describe('ai-providers.json integrity', () => {
});
});
+ // Where a self-hosted instance processes and retains data depends on its own
+ // provider accounts, so the shipped catalog states neither on its behalf.
+ it('should not assert data residency or zero data retention', () => {
+ Object.values(PROVIDERS).forEach((config) => {
+ expect(config.dataResidency).toBeUndefined();
+
+ (config.models ?? []).forEach((model) => {
+ expect(model.dataResidency).toBeUndefined();
+ expect(model.zeroDataRetention).toBeUndefined();
+ });
+ });
+ });
+
it('should have npm field set for all providers', () => {
Object.values(PROVIDERS).forEach((config) => {
expect(config.npm).toBeDefined();
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/ai-model-benchmarks.json b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/ai-model-benchmarks.json
new file mode 100644
index 00000000000..ac335c77ee3
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/ai-model-benchmarks.json
@@ -0,0 +1,5 @@
+{
+ "source": "artificialanalysis.ai",
+ "measuredAt": "2026-09-09",
+ "models": {}
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service.ts
index 8cc514ce32c..227d2dc1cf7 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service.ts
@@ -211,7 +211,8 @@ export class AiModelRegistryService {
sdkPackage: config.npm,
label: modelDef.label,
description: modelDef.description ?? compositeId,
- dataResidency: config.dataResidency,
+ dataResidency: modelDef.dataResidency ?? config.dataResidency,
+ zeroDataRetention: modelDef.zeroDataRetention,
costPerMinute: modelDef.costPerMinute,
isDeprecated: modelDef.isDeprecated,
});
@@ -289,7 +290,10 @@ export class AiModelRegistryService {
modelFamily:
modelDef.modelFamily ??
inferModelFamily(providerConfig.name ?? '', modelDef.name),
- dataResidency: providerConfig.dataResidency,
+ // The provider value is only a fallback: one Bedrock provider serves both
+ // eu.* and global.* models, which do not route to the same place.
+ dataResidency: modelDef.dataResidency ?? providerConfig.dataResidency,
+ zeroDataRetention: modelDef.zeroDataRetention,
inputCostPerMillionTokens: modelDef.inputCostPerMillionTokens ?? 0,
outputCostPerMillionTokens: modelDef.outputCostPerMillionTokens ?? 0,
cachedInputCostPerMillionTokens: modelDef.cachedInputCostPerMillionTokens,
@@ -306,6 +310,7 @@ export class AiModelRegistryService {
),
modalities: modelDef.modalities,
supportsReasoning: modelDef.supportsReasoning,
+ benchmark: modelDef.benchmark,
isDeprecated: modelDef.isDeprecated,
};
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-benchmark.schema.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-benchmark.schema.ts
new file mode 100644
index 00000000000..eea17794c84
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-benchmark.schema.ts
@@ -0,0 +1,12 @@
+import { z } from 'zod';
+
+// One publisher's reading of a model, taken on one date. An index is only
+// meaningful against models scored the same way, so whoever fills this must use
+// the same publisher throughout rather than filling gaps from a second. The
+// generated catalog uses Artificial Analysis.
+export const aiModelBenchmarkSchema = z.object({
+ intelligenceIndex: z.number().optional(),
+ outputTokensPerSecond: z.number().positive().optional(),
+ costPerTask: z.number().positive().optional(),
+ measuredAt: z.string().date(),
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-benchmark.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-benchmark.type.ts
new file mode 100644
index 00000000000..a1d00e1242f
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-benchmark.type.ts
@@ -0,0 +1,5 @@
+import { z } from 'zod';
+
+import { aiModelBenchmarkSchema } from 'src/engine/metadata-modules/ai/ai-models/types/ai-model-benchmark.schema';
+
+export type AiModelBenchmark = z.infer<typeof aiModelBenchmarkSchema>;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-config.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-config.type.ts
index b195119fbbf..5be2607663b 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-config.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-model-config.type.ts
@@ -1,4 +1,5 @@
import { type AiSdkPackage, type DataResidency } from 'twenty-shared/ai';
+import { type AiModelBenchmark } from 'src/engine/metadata-modules/ai/ai-models/types/ai-model-benchmark.type';
import { type LongContextCost } from 'src/engine/metadata-modules/ai/ai-models/types/long-context-cost.type';
import { type ModelFamily } from 'src/engine/metadata-modules/ai/ai-models/types/model-family.enum';
@@ -10,6 +11,7 @@ export type AiModelConfig = {
description: string;
modelFamily?: ModelFamily;
dataResidency?: DataResidency;
+ zeroDataRetention?: boolean;
inputCostPerMillionTokens: number;
outputCostPerMillionTokens: number;
contextWindowTokens: number;
@@ -19,5 +21,6 @@ export type AiModelConfig = {
longContextCost?: LongContextCost;
modalities?: string[];
supportsReasoning?: boolean;
+ benchmark?: AiModelBenchmark;
isDeprecated?: boolean;
};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-provider-model-config.schema.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-provider-model-config.schema.ts
index d220d46e6b4..b28df867527 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-provider-model-config.schema.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-provider-model-config.schema.ts
@@ -1,6 +1,9 @@
import { z } from 'zod';
+import { DATA_RESIDENCY_KEYS } from 'twenty-shared/ai';
+
import { AI_MODEL_KINDS } from 'src/engine/metadata-modules/ai/ai-models/constants/ai-model-kinds.const';
+import { aiModelBenchmarkSchema } from 'src/engine/metadata-modules/ai/ai-models/types/ai-model-benchmark.schema';
import { ModelFamily } from 'src/engine/metadata-modules/ai/ai-models/types/model-family.enum';
import { longContextCostSchema } from 'src/engine/metadata-modules/ai/ai-models/types/long-context-cost.schema';
@@ -21,6 +24,12 @@ export const aiProviderModelConfigSchema = z
maxOutputTokens: z.number().int().positive().optional(),
modalities: z.array(z.string()).optional(),
supportsReasoning: z.boolean().optional(),
+ // Contractual per route rather than published anywhere, so an operator
+ // declares them and undefined means unasserted, not false. One Bedrock
+ // provider serves both eu.* and global.* models, hence per model.
+ dataResidency: z.enum(DATA_RESIDENCY_KEYS).optional(),
+ zeroDataRetention: z.boolean().optional(),
+ benchmark: aiModelBenchmarkSchema.optional(),
isDeprecated: z.boolean().optional(),
})
.refine(
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-transcription-model-config.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-transcription-model-config.type.ts
index 14b82b79c4e..745e40de43d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-transcription-model-config.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/ai-transcription-model-config.type.ts
@@ -8,6 +8,7 @@ export type AiTranscriptionModelConfig = {
label: string;
description: string;
dataResidency?: DataResidency;
+ zeroDataRetention?: boolean;
costPerMinute: number;
isDeprecated?: boolean;
};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/models-dev-cost.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/models-dev-cost.type.ts
new file mode 100644
index 00000000000..abb330b6247
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/models-dev-cost.type.ts
@@ -0,0 +1,6 @@
+export type ModelsDevCost = {
+ input?: number;
+ output?: number;
+ cache_read?: number;
+ cache_write?: number;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/models-dev-model.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/models-dev-model.type.ts
index d708fda4b54..d8e921d72d2 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/models-dev-model.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-models/types/models-dev-model.type.ts
@@ -1,3 +1,5 @@
+import { type ModelsDevCost } from './models-dev-cost.type';
+
export type ModelsDevModel = {
// Model id as returned by models.dev (may match the record key in `ModelsDevProvider.models`).
id: string;
@@ -6,15 +8,12 @@ export type ModelsDevModel = {
status?: 'deprecated' | 'beta';
reasoning?: boolean;
tool_call?: boolean;
- cost?: {
- input?: number;
- output?: number;
- cache_read?: number;
- cache_write?: number;
- };
+ // Providers that price long context separately nest a second set of rates
+ // under `context_over_200k`, in the same shape.
+ cost?: ModelsDevCost & { context_over_200k?: ModelsDevCost };
limit?: { context?: number; output?: number };
modalities?: { input?: string[]; output?: string[] };
knowledge?: string;
- release?: string;
- updated?: string;
+ release_date?: string;
+ last_updated?: string;
};