diff --git a/.config/config.json b/.config/config.json index 397a80f..16e25a4 100644 --- a/.config/config.json +++ b/.config/config.json @@ -1,30 +1,16 @@ { "defaultModel": "gpt-6-luna", - "modelAliases": { - "gpt-5": "gpt-6.2-sol", - "gpt-5.1": "gpt-6.2-sol", - "gpt-5.2": "gpt-6.2-sol", - "gpt-5-mini": "gpt-6.1-terra", - "gpt-5-nano": "gpt-6-luna" - }, "providers": [ { "id": "openai", "name": "OpenAI", "type": "openai", - "enabled": true, "apiKeyEnv": "OPENAI_API_KEY", "models": [ { - "id": "gpt-6.2-astra", - "name": "GPT-6.2 Astra", - "reasoningEfforts": ["low", "medium", "high", "xhigh", "max"], - "defaultReasoningEffort": "low" - }, - { - "id": "gpt-6.2-sol", - "name": "GPT-6.2 Sol", - "reasoningEfforts": ["low", "medium", "high", "xhigh", "max"], + "id": "gpt-6-luna", + "name": "GPT-6 Luna", + "reasoningEfforts": ["none", "low", "medium", "high", "xhigh", "max"], "defaultReasoningEffort": "low" }, { @@ -32,12 +18,6 @@ "name": "GPT-6.1 Terra", "reasoningEfforts": ["none", "low", "medium", "high", "xhigh", "max"], "defaultReasoningEffort": "low" - }, - { - "id": "gpt-6-luna", - "name": "GPT-6 Luna", - "reasoningEfforts": ["none", "low", "medium", "high", "xhigh", "max"], - "defaultReasoningEffort": "low" } ] }, @@ -45,15 +25,13 @@ "id": "anthropic", "name": "Anthropic", "type": "anthropic", - "enabled": true, "apiKeyEnv": "ANTHROPIC_API_KEY", "models": [ { - "id": "claude-opus-5-5", - "name": "Claude Opus 5.5", + "id": "claude-haiku-5-5", + "name": "Claude Haiku 5.5", "reasoningEfforts": ["low", "medium", "high", "xhigh", "max"], - "defaultReasoningEffort": "medium", - "refusalFallback": true + "defaultReasoningEffort": "medium" }, { "id": "claude-sonnet-5-5", @@ -61,12 +39,6 @@ "reasoningEfforts": ["low", "medium", "high", "xhigh", "max"], "defaultReasoningEffort": "medium", "refusalFallback": true - }, - { - "id": "claude-haiku-5-5", - "name": "Claude Haiku 5.5", - "reasoningEfforts": ["low", "medium", "high", "xhigh", "max"], - "defaultReasoningEffort": "medium" } ] } diff --git a/AGENTS.md b/AGENTS.md index 9f33351..ab02969 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -68,7 +68,7 @@ Server routes: - Set the API key of each provider you use (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`) before running agent workflows. - Providers and models live in `.config/config.json`; keys stay in the environment, named by each provider's `apiKeyEnv`. -- Do not hard-code model ids in source: add them to `.config/config.json` (and `modelAliases` for retired ids). +- Do not hard-code model ids in source: `.config/config.json` is the only model list. A node whose model is no longer listed runs on the default model. - Never commit secrets, `.env` files, or generated data from `data/runs/`. ## Design System Policy diff --git a/CLAUDE.md b/CLAUDE.md index 4d443a1..75d2373 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -101,7 +101,7 @@ git submodule update --init --recursive - `OPENAI_API_KEY` / `ANTHROPIC_API_KEY`: key for each provider whose models are used. - `PORT`: server port (default `3000`). - `PROJECT_ROOT`: optional root override. -- `.config/config.json`: providers, models, default model and aliases; routes each Agent node to a provider (`apps/server/src/llm`). Schema in `docs/configuration.md`. +- `.config/config.json`: the only model list (providers, models in order of strength, default model); routes each Agent node to a provider (`apps/server/src/llm`). Schema in `docs/configuration.md`. - `.config/default-workflow.json`: optional startup workflow (gitignored). ## References diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts index 98499c5..b00bd3e 100644 --- a/apps/server/src/index.ts +++ b/apps/server/src/index.ts @@ -26,7 +26,6 @@ function readConfig(store: ConfigStore): ConfigSnapshot | undefined { function logProviders(snapshot: ConfigSnapshot): void { for (const provider of snapshot.config.providers) { - if (!provider.enabled) continue; if (snapshot.isAvailable(provider)) { logger.info('%s enabled with %d models (%s detected)', provider.name, provider.models.length, provider.apiKeyEnv); } else { @@ -55,7 +54,8 @@ async function bootstrap() { const current = readConfig(configStore); return current ? resolveAgentModels(current, graph) : {}; }, - getPublicConfig: () => readConfig(configStore)?.toPublic(), + // Throws on a missing or invalid file, so the editor can show why. + getPublicConfig: () => configStore.get().toPublic(), getDefaultModel: () => readConfig(configStore)?.defaultModel }); diff --git a/apps/server/src/llm/app-config.test.ts b/apps/server/src/llm/app-config.test.ts index 904c592..744f72f 100644 --- a/apps/server/src/llm/app-config.test.ts +++ b/apps/server/src/llm/app-config.test.ts @@ -6,7 +6,6 @@ import { ConfigError, ConfigSnapshot, ConfigStore, parseAppConfig } from './app- const twoProviders = { defaultModel: 'claude-a', - modelAliases: { 'old-model': 'gpt-a' }, providers: [ { id: 'openai', @@ -23,17 +22,12 @@ const twoProviders = { }; describe('parseAppConfig', () => { - it('fills in defaults so files written before provider types existed still load', () => { + it('fills in the type, key variable and API when the provider id names them', () => { const config = parseAppConfig({ - providers: [{ id: 'openai', name: 'OpenAI', enabled: true, models: [{ id: 'gpt-5', name: 'GPT-5', reasoningEfforts: ['low'] }] }] + providers: [{ id: 'openai', name: 'OpenAI', models: [{ id: 'gpt-5', name: 'GPT-5', reasoningEfforts: ['low'] }] }] }); - expect(config.providers[0]).toMatchObject({ - type: 'openai', - apiKeyEnv: 'OPENAI_API_KEY', - api: 'responses', - enabled: true - }); - expect(config.modelAliases).toEqual({}); + expect(config.providers[0]).toMatchObject({ type: 'openai', apiKeyEnv: 'OPENAI_API_KEY', api: 'responses' }); + expect(config.defaultModel).toBeUndefined(); }); it('reads provider and model options', () => { @@ -56,21 +50,16 @@ describe('parseAppConfig', () => { [{ providers: [{ id: 'openai', models: [{ id: 'm' }] }, { id: 'openai', models: [] }] }, /Provider id "openai" is duplicated/], [{ providers: [{ id: 'a', type: 'openai', models: [{ id: 'm' }] }, { id: 'b', type: 'openai', models: [{ id: 'm' }] }] }, /listed by both "a" and "b"/], [{ defaultModel: 'nope', providers: [{ id: 'openai', models: [{ id: 'm' }] }] }, /defaultModel "nope"/], - [{ modelAliases: { old: 'nope' }, providers: [{ id: 'openai', models: [{ id: 'm' }] }] }, /modelAliases\["old"\]/] + [{ providers: [{ id: 'openai', models: [] }] }, /lists no models/], + [{ modelAliases: { old: 'm' }, providers: [{ id: 'openai', models: [{ id: 'm' }] }] }, /modelAliases is no longer supported/], + [{ providers: [{ id: 'openai', enabled: false, models: [{ id: 'm' }] }] }, /providers\[0\]\.enabled is no longer supported/], + [{ defaultModle: 'm', providers: [{ id: 'openai', models: [{ id: 'm' }] }] }, /defaultModle is not a known field/], + [{ providers: [{ id: 'openai', models: [{ id: 'm', reasoningEffort: 'low' }] }] }, /models\[0\]\.reasoningEffort is not a known field/], + [{ providers: [{ id: 'anthropic', models: [{ id: 'm', refusalFallback: 'yes' }] }] }, /refusalFallback must be true or false/] ])('rejects invalid configuration %#', (raw, message) => { expect(() => parseAppConfig(raw)).toThrow(ConfigError); expect(() => parseAppConfig(raw)).toThrow(message); }); - - it('allows the same model id in a disabled provider', () => { - const config = parseAppConfig({ - providers: [ - { id: 'a', type: 'openai', models: [{ id: 'm' }] }, - { id: 'b', type: 'openai', enabled: false, models: [{ id: 'm' }] } - ] - }); - expect(config.providers).toHaveLength(2); - }); }); describe('ConfigSnapshot', () => { @@ -81,21 +70,21 @@ describe('ConfigSnapshot', () => { expect(lookup).toMatchObject({ ok: true, resolved: { provider: { id: 'openai' }, model: { id: 'gpt-a' }, apiKey: 'sk-test' } }); }); - it('follows aliases and falls back to the default model', () => { + it('runs a missing or unlisted model on the default model', () => { const both = snapshot({ OPENAI_API_KEY: 'a', ANTHROPIC_API_KEY: 'b' }); - expect(both.lookup('old-model')).toMatchObject({ ok: true, resolved: { model: { id: 'gpt-a' } } }); + expect(both.lookup('gpt-retired')).toMatchObject({ ok: true, resolved: { model: { id: 'claude-a' } } }); expect(both.lookup(undefined)).toMatchObject({ ok: true, resolved: { model: { id: 'claude-a' } } }); expect(both.lookup(' ')).toMatchObject({ ok: true, resolved: { model: { id: 'claude-a' } } }); }); - it('explains a missing key and an unknown model', () => { + it('explains a missing key', () => { const noKeys = snapshot({}); expect(noKeys.lookup('claude-a')).toEqual({ ok: false, reason: 'missing_key', message: 'ANTHROPIC_API_KEY is required to run Agent nodes that use Anthropic models.' }); - expect(noKeys.lookup('gpt-99')).toMatchObject({ ok: false, reason: 'unknown_model' }); + expect(noKeys.lookup('gpt-retired')).toMatchObject({ ok: false, reason: 'missing_key' }); }); it('prefers a provider with a key when no default model is configured', () => { @@ -141,6 +130,7 @@ describe('ConfigStore', () => { it('accepts the configuration shipped with the project', () => { const shipped = ConfigStore.forProject(path.resolve(import.meta.dirname, '../../../..'), {}).get(); expect(shipped.config.providers.map((p) => p.type)).toEqual(['openai', 'anthropic']); + expect(shipped.defaultModel).toBe(shipped.config.providers[0].models[0].id); expect(shipped.lookup(undefined)).toMatchObject({ ok: false, reason: 'missing_key' }); }); }); diff --git a/apps/server/src/llm/app-config.ts b/apps/server/src/llm/app-config.ts index 0898b0c..dfb272c 100644 --- a/apps/server/src/llm/app-config.ts +++ b/apps/server/src/llm/app-config.ts @@ -22,7 +22,6 @@ export interface ProviderConfig { id: string; name: string; type: ProviderType; - enabled: boolean; /** Name of the environment variable that holds the API key. Keys never live in the file. */ apiKeyEnv: string; /** Optional API base URL, for a proxy or an OpenAI-compatible service. */ @@ -32,11 +31,13 @@ export interface ProviderConfig { models: ModelConfig[]; } +/** + * `.config/config.json`: the one place that lists the models the app offers. + * There is no built-in model list: without this file, agents cannot run. + */ export interface AppConfig { - /** Model used by agent nodes that do not name one. Defaults to the first available model. */ + /** Model for agent nodes that name none or name one the file does not list. Defaults to the first available model. */ defaultModel?: string; - /** Maps model ids found in older saved workflows to current ones. */ - modelAliases: Record; providers: ProviderConfig[]; } @@ -52,10 +53,30 @@ const DEFAULT_API_KEY_ENV: Record = { anthropic: 'ANTHROPIC_API_KEY' }; +const CONFIG_FIELDS = ['defaultModel', 'providers']; +const PROVIDER_FIELDS = ['id', 'name', 'type', 'apiKeyEnv', 'baseUrl', 'api', 'models']; +const MODEL_FIELDS = ['id', 'name', 'reasoningEfforts', 'defaultReasoningEffort', 'maxOutputTokens', 'refusalFallback']; + +/** Fields older files used, with what to do instead. */ +const REMOVED_FIELDS: Record = { + modelAliases: 'remove it: a workflow that names a model the file does not list runs on the default model', + enabled: 'remove it, and remove the provider to stop offering its models' +}; + function isObject(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); } +/** Unknown fields are errors, so a misspelt field cannot be silently ignored. */ +function rejectUnknownFields(raw: Record, allowed: string[], where: string): void { + for (const key of Object.keys(raw)) { + if (allowed.includes(key)) continue; + const label = where ? `${where}.${key}` : key; + const removed = REMOVED_FIELDS[key]; + throw new ConfigError(removed ? `${label} is no longer supported; ${removed}.` : `${label} is not a known field.`); + } +} + function requireString(value: unknown, where: string): string { if (typeof value !== 'string' || !value.trim()) { throw new ConfigError(`${where} must be a non-empty string.`); @@ -70,6 +91,7 @@ function optionalString(value: unknown, where: string): string | undefined { function parseModel(raw: unknown, where: string): ModelConfig { if (!isObject(raw)) throw new ConfigError(`${where} must be an object.`); + rejectUnknownFields(raw, MODEL_FIELDS, where); const id = requireString(raw.id, `${where}.id`); const efforts = raw.reasoningEfforts ?? []; if (!Array.isArray(efforts) || efforts.some((effort) => typeof effort !== 'string' || !effort)) { @@ -86,6 +108,9 @@ function parseModel(raw: unknown, where: string): ModelConfig { ) { throw new ConfigError(`${where}.maxOutputTokens must be a positive integer.`); } + if (raw.refusalFallback !== undefined && typeof raw.refusalFallback !== 'boolean') { + throw new ConfigError(`${where}.refusalFallback must be true or false.`); + } return { id, name: optionalString(raw.name, `${where}.name`) ?? id, @@ -98,9 +123,9 @@ function parseModel(raw: unknown, where: string): ModelConfig { function parseProvider(raw: unknown, where: string): ProviderConfig { if (!isObject(raw)) throw new ConfigError(`${where} must be an object.`); + rejectUnknownFields(raw, PROVIDER_FIELDS, where); const id = requireString(raw.id, `${where}.id`); - // `type` may be omitted when the id already names a supported provider, - // which is how configuration files written before `type` existed look. + // `type` may be omitted when the id already names a supported provider. const type = optionalString(raw.type, `${where}.type`) ?? id; if (type !== 'openai' && type !== 'anthropic') { throw new ConfigError(`${where}.type must be "openai" or "anthropic" (got "${type}").`); @@ -114,7 +139,6 @@ function parseProvider(raw: unknown, where: string): ProviderConfig { id, name: optionalString(raw.name, `${where}.name`) ?? id, type, - enabled: raw.enabled !== false, apiKeyEnv: optionalString(raw.apiKeyEnv, `${where}.apiKeyEnv`) ?? DEFAULT_API_KEY_ENV[type], baseUrl: optionalString(raw.baseUrl, `${where}.baseUrl`), api, @@ -127,6 +151,7 @@ export function parseAppConfig(raw: unknown): AppConfig { if (!isObject(raw) || !Array.isArray(raw.providers)) { throw new ConfigError('config.json must be an object with a "providers" array.'); } + rejectUnknownFields(raw, CONFIG_FIELDS, ''); const providers = raw.providers.map((provider, index) => parseProvider(provider, `providers[${index}]`)); const providerIds = new Set(); @@ -134,7 +159,6 @@ export function parseAppConfig(raw: unknown): AppConfig { for (const provider of providers) { if (providerIds.has(provider.id)) throw new ConfigError(`Provider id "${provider.id}" is duplicated.`); providerIds.add(provider.id); - if (!provider.enabled) continue; for (const model of provider.models) { const owner = modelOwners.get(model.id); if (owner) { @@ -143,25 +167,14 @@ export function parseAppConfig(raw: unknown): AppConfig { modelOwners.set(model.id, provider.id); } } - - const modelAliases: Record = {}; - if (raw.modelAliases !== undefined) { - if (!isObject(raw.modelAliases)) throw new ConfigError('modelAliases must be an object.'); - for (const [alias, target] of Object.entries(raw.modelAliases)) { - const targetId = requireString(target, `modelAliases["${alias}"]`); - if (!modelOwners.has(targetId)) { - throw new ConfigError(`modelAliases["${alias}"] points to "${targetId}", which no enabled provider lists.`); - } - modelAliases[alias] = targetId; - } - } + if (modelOwners.size === 0) throw new ConfigError('config.json lists no models.'); const defaultModel = optionalString(raw.defaultModel, 'defaultModel'); if (defaultModel && !modelOwners.has(defaultModel)) { - throw new ConfigError(`defaultModel "${defaultModel}" is not listed by any enabled provider.`); + throw new ConfigError(`defaultModel "${defaultModel}" is not one of the listed models.`); } - return { defaultModel, modelAliases, providers }; + return { defaultModel, providers }; } export interface ResolvedModel { @@ -187,53 +200,56 @@ export class ConfigSnapshot { } isAvailable(provider: ProviderConfig): boolean { - return provider.enabled && this.apiKey(provider) !== ''; + return this.apiKey(provider) !== ''; } - /** The configured default, or the first model of a provider that has a key. */ + /** The configured default, or the first model of a provider that has a key, or the first model. */ get defaultModel(): string | undefined { if (this.config.defaultModel) return this.config.defaultModel; - const enabled = this.config.providers.filter((provider) => provider.enabled); - const preferred = enabled.find((provider) => this.isAvailable(provider) && provider.models.length > 0); - return (preferred ?? enabled.find((provider) => provider.models.length > 0))?.models[0]?.id; + const providers = this.config.providers.filter((provider) => provider.models.length > 0); + return (providers.find((provider) => this.isAvailable(provider)) ?? providers[0])?.models[0]?.id; + } + + private find(modelId: string): { provider: ProviderConfig; model: ModelConfig } | undefined { + for (const provider of this.config.providers) { + const model = provider.models.find((candidate) => candidate.id === modelId); + if (model) return { provider, model }; + } + return undefined; } + /** + * The model an agent runs with: the one it names if the file lists it, + * otherwise the default model. A workflow saved before a model was removed + * from the file therefore keeps running. + */ lookup(requestedModel: string | undefined): ModelLookup { - const requested = requestedModel?.trim() || this.defaultModel; - if (!requested) { + const requested = requestedModel?.trim(); + const listed = requested ? this.find(requested) : undefined; + const defaultModel = this.defaultModel; + const found = listed ?? (defaultModel ? this.find(defaultModel) : undefined); + if (!found) { return { ok: false, reason: 'unknown_model', message: 'No models are configured in .config/config.json.' }; } - const modelId = this.config.modelAliases[requested] ?? requested; - for (const provider of this.config.providers) { - if (!provider.enabled) continue; - const model = provider.models.find((candidate) => candidate.id === modelId); - if (!model) continue; - const apiKey = this.apiKey(provider); - if (!apiKey) { - return { - ok: false, - reason: 'missing_key', - message: `${provider.apiKeyEnv} is required to run Agent nodes that use ${provider.name} models.` - }; - } - return { ok: true, resolved: { provider, model, apiKey } }; + const { provider, model } = found; + const apiKey = this.apiKey(provider); + if (!apiKey) { + return { + ok: false, + reason: 'missing_key', + message: `${provider.apiKeyEnv} is required to run Agent nodes that use ${provider.name} models.` + }; } - return { - ok: false, - reason: 'unknown_model', - message: `Model "${requested}" is not listed by any enabled provider in .config/config.json.` - }; + return { ok: true, resolved: { provider, model, apiKey } }; } /** What the browser receives: no key names, no base URLs. */ toPublic(): PublicAppConfig { return { defaultModel: this.defaultModel, - modelAliases: this.config.modelAliases, providers: this.config.providers.map((provider) => ({ id: provider.id, name: provider.name, - enabled: provider.enabled, available: this.isAvailable(provider), models: provider.models.map((model) => ({ id: model.id, @@ -248,11 +264,9 @@ export class ConfigSnapshot { export interface PublicAppConfig { defaultModel?: string; - modelAliases: Record; providers: Array<{ id: string; name: string; - enabled: boolean; available: boolean; models: Array>; }>; @@ -297,8 +311,8 @@ export class ConfigStore { } /** - * The model id each agent node of `graph` runs with, after aliases and the - * default model. Nodes whose model cannot be resolved are left out. + * The model id each agent node of `graph` runs with: its own if listed, + * otherwise the default model. Nodes whose model cannot be resolved are left out. */ export function resolveAgentModels(snapshot: ConfigSnapshot, graph: WorkflowGraph): Record { const models: Record = {}; diff --git a/apps/server/src/llm/router.test.ts b/apps/server/src/llm/router.test.ts index 64aad22..87386ad 100644 --- a/apps/server/src/llm/router.test.ts +++ b/apps/server/src/llm/router.test.ts @@ -6,7 +6,6 @@ import { ProviderRouterLLM, toToolName } from './router.js'; const config = parseAppConfig({ defaultModel: 'gpt-a', - modelAliases: { 'gpt-old': 'gpt-a' }, providers: [ { id: 'openai', @@ -59,7 +58,7 @@ describe('ProviderRouterLLM', () => { expect(await router.respond(invocation('gpt-a'))).toBe('openai answer'); expect(await router.respond(invocation('claude-a'))).toBe('anthropic answer'); - expect(await router.respond(invocation('gpt-old'))).toBe('openai answer'); + expect(await router.respond(invocation('gpt-retired'))).toBe('openai answer'); expect(requests.map((entry) => [entry.providerId, entry.request.model])).toEqual([ ['openai', 'gpt-a'], @@ -86,9 +85,8 @@ describe('ProviderRouterLLM', () => { expect(requests[0].request.signal).toBe(controller.signal); }); - it('fails with a clear message for an unknown model or a missing key', async () => { + it('fails with a clear message for a missing key', async () => { const { router } = setup({ OPENAI_API_KEY: 'k' }); - await expect(router.respond(invocation('gpt-99'))).rejects.toThrow(/"gpt-99" is not listed/); await expect(router.respond(invocation('claude-a'))).rejects.toThrow(/ANTHROPIC_API_KEY is required/); }); @@ -192,17 +190,18 @@ describe('ProviderRouterLLM', () => { }); it('accepts graphs whose models all have keys, and graphs without agents', () => { - expect(setup(allKeys).router.preflight(graph('gpt-a', 'claude-a', undefined, 'gpt-old'))).toBeNull(); + expect(setup(allKeys).router.preflight(graph('gpt-a', 'claude-a', undefined, 'gpt-retired'))).toBeNull(); expect(setup({}).router.preflight(graph())).toBeNull(); }); - it('returns 503 for a missing key and 400 for an unknown model', () => { + it('returns 503 for a missing key, including the default model an unlisted one runs on', () => { const { router } = setup({ OPENAI_API_KEY: 'k' }); expect(router.preflight(graph('gpt-a', 'claude-a'))).toEqual({ status: 503, error: 'ANTHROPIC_API_KEY is required to run Agent nodes that use Anthropic models.' }); - expect(router.preflight(graph('gpt-99'))).toMatchObject({ status: 400 }); + expect(router.preflight(graph('gpt-retired'))).toBeNull(); + expect(setup({ ANTHROPIC_API_KEY: 'k' }).router.preflight(graph('gpt-retired'))).toMatchObject({ status: 503 }); }); }); }); diff --git a/apps/server/src/report/build.test.ts b/apps/server/src/report/build.test.ts index 49268d9..8a42e4d 100644 --- a/apps/server/src/report/build.test.ts +++ b/apps/server/src/report/build.test.ts @@ -13,7 +13,6 @@ import { loadReportInput, type ReportInput, type ReportModelInfo } from './load. const MODELS: ReportModelInfo = { defaultModel: 'gpt-6-luna', - aliases: { 'gpt-old': 'gpt-6-luna' }, models: { 'gpt-6-luna': { name: 'GPT-6 Luna', reasoningEfforts: ['low', 'medium', 'high'], defaultReasoningEffort: 'low' }, 'claude-haiku-5-5': { name: 'Claude Haiku 5.5', reasoningEfforts: [] } @@ -61,7 +60,7 @@ function researchWorkflow(): WorkflowGraph { y: 0, data: { agentName: 'Writer', systemPrompt: '', userPrompt: '', tools: {} } }, - { id: 'stray', type: 'agent', x: 0, y: 400, data: { agentName: 'Draft Bot', tools: {} } } + { id: 'stray', type: 'agent', x: 0, y: 400, data: { agentName: 'Draft Bot', model: 'gpt-6.2-sol', tools: {} } } ], connections: [ { source: 'start', target: 'researcher', sourceHandle: 'output', targetHandle: 'input' }, @@ -222,6 +221,9 @@ describe('buildReport', () => { expect(report).toContain('## Unconnected nodes'); expect(report.indexOf('### Draft Bot')).toBeGreaterThan(report.indexOf('## Unconnected nodes')); + expect(section(report, '### Draft Bot (Agent)')).toContain( + '- Model: GPT-6 Luna (gpt-6-luna), the default model, because the node is set to "gpt-6.2-sol", which the app no longer offers' + ); }); it('reports why the editor would not run the workflow', () => { @@ -346,10 +348,9 @@ describe('loadReportInput', () => { await fs.writeFile( path.join(root, '.config', 'config.json'), JSON.stringify({ - modelAliases: { 'gpt-old': 'gpt-6-luna' }, providers: [ - { id: 'off', enabled: false, models: [{ id: 'claude-haiku-5-5', name: 'Claude Haiku 5.5' }] }, - { id: 'openai', models: [{ id: 'gpt-6-luna', name: 'GPT-6 Luna', reasoningEfforts: ['low'] }] } + { id: 'openai', models: [{ id: 'gpt-6-luna', name: 'GPT-6 Luna', reasoningEfforts: ['low'] }] }, + { id: 'anthropic', models: [{ id: 'claude-haiku-5-5', name: 'Claude Haiku 5.5' }] } ] }) ); @@ -377,6 +378,6 @@ describe('loadReportInput', () => { it('returns empty input for a root with no data or config', async () => { root = await fs.mkdtemp(path.join(os.tmpdir(), 'agentflow-report-')); const loaded = await loadReportInput(root); - expect(loaded).toEqual({ saved: null, startingWorkflow: null, runs: [], models: { models: {}, aliases: {} }, problems: [] }); + expect(loaded).toEqual({ saved: null, startingWorkflow: null, runs: [], models: { models: {} }, problems: [] }); }); }); diff --git a/apps/server/src/report/build.ts b/apps/server/src/report/build.ts index bb34816..8d1f3b1 100644 --- a/apps/server/src/report/build.ts +++ b/apps/server/src/report/build.ts @@ -17,7 +17,6 @@ import { getRunDisableReason, upgradeLegacyGraph } from '@agentflow/workflow-graph'; -import { DEFAULT_MODEL } from '@agentflow/workflow-engine'; import { stableStringify, workflowFingerprint } from '../services/fingerprint.js'; import type { ReportInput, ReportModelInfo, ReportRun } from './load.js'; @@ -236,20 +235,25 @@ interface ModelChoice { text: string; } -/** The model an agent node runs with, the way the server resolves it. */ +/** + * The model an agent node runs with, the way the server resolves it: its own + * if the configuration lists it, otherwise the default model. + */ function modelFor(node: TypedWorkflowNode, info: ReportModelInfo): ModelChoice { const requested = typeof node.data?.model === 'string' ? node.data.model.trim() : ''; - const fallback = info.defaultModel ?? DEFAULT_MODEL; - const chosen = requested || fallback; - const id = info.aliases[chosen] ?? chosen; - const known = info.models[id]; - const name = known ? `${known.name} (${id})` : id; - const aliasNote = id !== chosen ? `, set as ${quote(chosen)}, an older id` : ''; - if (!requested) return { id, text: `${name}, the default model${aliasNote}` }; - if (Object.keys(info.models).length > 0 && !known) { - return { id, text: `${name}${aliasNote}, which the app configuration does not list, so the agent cannot run` }; - } - return { id, text: `${name}${aliasNote}` }; + const configured = Object.keys(info.models).length > 0; + const describe = (id: string) => { + const known = info.models[id]; + return known ? `${known.name} (${id})` : id; + }; + if (requested && (!configured || info.models[requested])) return { id: requested, text: describe(requested) }; + const fallback = info.defaultModel; + if (!fallback) return { id: undefined, text: 'the default model (unknown, because .config/config.json could not be read)' }; + if (!requested) return { id: fallback, text: `${describe(fallback)}, the default model` }; + return { + id: fallback, + text: `${describe(fallback)}, the default model, because the node is set to ${quote(requested)}, which the app no longer offers` + }; } function modelName(id: string, info: ReportModelInfo): string { diff --git a/apps/server/src/report/load.ts b/apps/server/src/report/load.ts index 8eeb41a..91a1adc 100644 --- a/apps/server/src/report/load.ts +++ b/apps/server/src/report/load.ts @@ -12,10 +12,9 @@ export interface ReportModel { defaultReasoningEffort?: string; } -/** What the report needs from `.config/config.json`: models, aliases and the default model. */ +/** What the report needs from `.config/config.json`: the models and the default model. */ export interface ReportModelInfo { models: Record; - aliases: Record; defaultModel?: string; } @@ -55,21 +54,15 @@ function strings(value: unknown): string[] { /** * Reads the models loosely: a config the server would reject still names its - * models. The default model follows the server: the configured one, else the - * first model of an enabled provider. + * models. The default model is the configured one, else the first listed. */ function readModelInfo(raw: unknown): ReportModelInfo { - const info: ReportModelInfo = { models: {}, aliases: {} }; + const info: ReportModelInfo = { models: {} }; if (!raw || typeof raw !== 'object') return info; - const config = raw as { defaultModel?: unknown; modelAliases?: unknown; providers?: unknown }; - if (config.modelAliases && typeof config.modelAliases === 'object') { - for (const [alias, target] of Object.entries(config.modelAliases as Record)) { - if (typeof target === 'string') info.aliases[alias] = target; - } - } - let firstEnabledModel: string | undefined; + const config = raw as { defaultModel?: unknown; providers?: unknown }; + let firstModel: string | undefined; for (const provider of Array.isArray(config.providers) ? config.providers : []) { - const { models, enabled } = provider as { models?: unknown; enabled?: unknown }; + const { models } = provider as { models?: unknown }; for (const model of Array.isArray(models) ? models : []) { const { id, name, reasoningEfforts, defaultReasoningEffort } = model as Record; if (typeof id !== 'string' || !id) continue; @@ -78,11 +71,11 @@ function readModelInfo(raw: unknown): ReportModelInfo { reasoningEfforts: strings(reasoningEfforts), defaultReasoningEffort: typeof defaultReasoningEffort === 'string' ? defaultReasoningEffort : undefined }; - if (enabled !== false && !firstEnabledModel) firstEnabledModel = id; + firstModel ??= id; } } info.defaultModel = - typeof config.defaultModel === 'string' && config.defaultModel ? config.defaultModel : firstEnabledModel; + typeof config.defaultModel === 'string' && config.defaultModel ? config.defaultModel : firstModel; return info; } @@ -118,7 +111,7 @@ export async function loadReportInput(projectRoot: string): Promise problems.push(`.config/default-workflow.json could not be read (${describeError(error)}).`); } - let models: ReportModelInfo = { models: {}, aliases: {} }; + let models: ReportModelInfo = { models: {} }; try { models = readModelInfo(await readJson(path.join(projectRoot, '.config', 'config.json'))); } catch (error) { diff --git a/apps/server/src/store/run-store.ts b/apps/server/src/store/run-store.ts index e01774a..1bb3392 100644 --- a/apps/server/src/store/run-store.ts +++ b/apps/server/src/store/run-store.ts @@ -4,7 +4,7 @@ import type { WorkflowEngine } from '@agentflow/workflow-engine'; export interface RunMeta { startedAt: string; workflowFingerprint: string; - /** Model id each agent node runs with, after aliases and the default model. */ + /** Model id each agent node runs with: its own if listed, otherwise the default model. */ models: Record; } diff --git a/apps/web/src/app/constants.ts b/apps/web/src/app/constants.ts index 901e7f6..e0d157f 100644 --- a/apps/web/src/app/constants.ts +++ b/apps/web/src/app/constants.ts @@ -12,21 +12,9 @@ export const TOOLS_CONFIG: ToolConfig[] = [ { key: 'subagents', label: 'Subagents', iconClass: 'icon-engineering-manager' } ]; -// Fallbacks for when `/api/config` cannot be loaded. The real model list -// comes from `.config/config.json` on the server. -export const DEFAULT_MODEL = 'gpt-6-luna'; +// Effort for new agent nodes until a model's own default is applied. The +// models themselves come only from `.config/config.json` on the server. export const DEFAULT_REASONING_EFFORT = 'low'; -export const DEFAULT_MODEL_OPTIONS = ['gpt-6.2-sol', 'gpt-6.1-terra', 'gpt-6-luna']; -export const DEFAULT_MODEL_EFFORTS: Record = { - 'gpt-6.2-sol': ['low', 'medium', 'high', 'xhigh', 'max'], - 'gpt-6.1-terra': ['none', 'low', 'medium', 'high', 'xhigh', 'max'], - 'gpt-6-luna': ['none', 'low', 'medium', 'high', 'xhigh', 'max'] -}; -export const DEFAULT_MODEL_LABELS: Record = { - 'gpt-6.2-sol': 'GPT-6.2 Sol', - 'gpt-6.1-terra': 'GPT-6.1 Terra', - 'gpt-6-luna': 'GPT-6 Luna' -}; export { APPROVE_HANDLE, diff --git a/apps/web/src/app/model-catalog.test.ts b/apps/web/src/app/model-catalog.test.ts index 4eecc83..122d30b 100644 --- a/apps/web/src/app/model-catalog.test.ts +++ b/apps/web/src/app/model-catalog.test.ts @@ -1,40 +1,36 @@ import { describe, expect, it } from 'vitest'; import type { AppConfig } from '../services/api'; -import { applyModelAliases, buildModelCatalog, buildModelPickerItems } from './model-catalog'; +import { buildModelCatalog, buildModelPickerItems, replaceUnlistedModels } from './model-catalog'; import type { EditorNode } from './types'; const config: AppConfig = { defaultModel: 'claude-a', - modelAliases: { 'gpt-old': 'gpt-a' }, providers: [ { id: 'openai', name: 'OpenAI', - enabled: true, available: true, models: [{ id: 'gpt-a', name: 'GPT A', reasoningEfforts: ['low', 'high'], defaultReasoningEffort: 'low' }] }, { id: 'anthropic', name: 'Anthropic', - enabled: true, available: true, models: [{ id: 'claude-a', name: 'Claude A', reasoningEfforts: ['medium'] }] - }, - { id: 'off', name: 'Off', enabled: false, models: [{ id: 'hidden', name: 'Hidden', reasoningEfforts: [] }] } + } ] }; describe('buildModelCatalog', () => { - it('lists models from every enabled provider with labels, efforts and the default', () => { + it('lists models from every provider with labels, efforts and the default', () => { expect(buildModelCatalog(config)).toEqual({ options: ['gpt-a', 'claude-a'], + listed: ['gpt-a', 'claude-a'], efforts: { 'gpt-a': ['low', 'high'], 'claude-a': ['medium'] }, labels: { 'gpt-a': 'GPT A', 'claude-a': 'Claude A' }, providers: { 'gpt-a': 'OpenAI', 'claude-a': 'Anthropic' }, defaultEfforts: { 'gpt-a': 'low' }, - defaultModel: 'claude-a', - aliases: { 'gpt-old': 'gpt-a' } + defaultModel: 'claude-a' }); }); @@ -44,6 +40,7 @@ describe('buildModelCatalog', () => { providers: config.providers!.map((p) => (p.id === 'anthropic' ? { ...p, available: false } : p)) }); expect(catalog?.options).toEqual(['gpt-a']); + expect(catalog?.listed).toEqual(['gpt-a', 'claude-a']); expect(catalog?.defaultModel).toBe('gpt-a'); }); @@ -55,16 +52,16 @@ describe('buildModelCatalog', () => { expect(catalog?.options).toEqual(['gpt-a', 'claude-a']); }); - it('accepts the older configuration shape without availability, aliases or a default', () => { + it('uses the first model when no default is given', () => { const catalog = buildModelCatalog({ - providers: [{ id: 'openai', name: 'OpenAI', enabled: true, models: [{ id: 'gpt-5', name: 'GPT-5', reasoningEfforts: ['low'] }] }] + providers: [{ id: 'openai', name: 'OpenAI', models: [{ id: 'gpt-5', name: 'GPT-5', reasoningEfforts: ['low'] }] }] }); - expect(catalog).toMatchObject({ options: ['gpt-5'], defaultModel: 'gpt-5', aliases: {} }); + expect(catalog).toMatchObject({ options: ['gpt-5'], defaultModel: 'gpt-5' }); }); it('returns null when nothing is configured', () => { expect(buildModelCatalog({})).toBeNull(); - expect(buildModelCatalog({ providers: [{ id: 'x', name: 'X', enabled: true, models: [] }] })).toBeNull(); + expect(buildModelCatalog({ providers: [{ id: 'x', name: 'X', models: [] }] })).toBeNull(); }); }); @@ -96,23 +93,24 @@ describe('buildModelPickerItems', () => { }); }); -describe('applyModelAliases', () => { +describe('replaceUnlistedModels', () => { const agent = (id: string, model?: string): EditorNode => ({ id, type: 'agent', x: 0, y: 0, data: { model } }); - it('replaces retired model ids on agent nodes only', () => { + it('moves agent nodes whose model is no longer listed to the default model', () => { const nodes: EditorNode[] = [ - agent('a', 'gpt-old'), + agent('a', 'gpt-retired'), agent('b', 'claude-a'), agent('c'), { id: 'd', type: 'start', x: 0, y: 0, data: {} } ]; - expect(applyModelAliases(nodes, { 'gpt-old': 'gpt-a' }, ['gpt-a', 'claude-a'])).toBe(true); + expect(replaceUnlistedModels(nodes, ['gpt-a', 'claude-a'], 'gpt-a')).toBe(true); expect(nodes.map((node) => node.data?.model)).toEqual(['gpt-a', 'claude-a', undefined, undefined]); }); - it('leaves a node alone when the replacement is not offered', () => { - const nodes = [agent('a', 'gpt-old')]; - expect(applyModelAliases(nodes, { 'gpt-old': 'gpt-a' }, ['claude-a'])).toBe(false); - expect(nodes[0].data?.model).toBe('gpt-old'); + it('keeps a listed model even when its provider has no key, and does nothing without a default', () => { + const nodes = [agent('a', 'claude-a'), agent('b', 'gpt-retired')]; + expect(replaceUnlistedModels(nodes.slice(0, 1), ['gpt-a', 'claude-a'], 'gpt-a')).toBe(false); + expect(replaceUnlistedModels(nodes, [], '')).toBe(false); + expect(nodes.map((node) => node.data?.model)).toEqual(['claude-a', 'gpt-retired']); }); }); diff --git a/apps/web/src/app/model-catalog.ts b/apps/web/src/app/model-catalog.ts index 114c5e4..c42b3a0 100644 --- a/apps/web/src/app/model-catalog.ts +++ b/apps/web/src/app/model-catalog.ts @@ -4,35 +4,35 @@ import type { EditorNode } from './types'; export interface ModelCatalog { /** Model ids offered in the picker. */ options: string[]; + /** Every model id the configuration lists, including ones hidden for a missing key. */ + listed: string[]; efforts: Record; labels: Record; /** Provider display name by model id. */ providers: Record; defaultEfforts: Record; defaultModel: string; - aliases: Record; } /** * Turns the server's provider configuration into what the model picker needs. - * Returns null when the configuration lists no models, so callers keep their - * built-in fallback. + * Returns null when the configuration lists no models. */ export function buildModelCatalog(config: AppConfig): ModelCatalog | null { - const enabledProviders = (config.providers ?? []).filter((provider) => provider.enabled); + const allProviders = config.providers ?? []; // Offer only models that can run. If no provider has a key yet, list them // all so workflows can still be designed; Run reports the missing key. - const usableProviders = enabledProviders.filter((provider) => provider.available !== false); - const providers = usableProviders.length > 0 ? usableProviders : enabledProviders; + const usableProviders = allProviders.filter((provider) => provider.available !== false); + const providers = usableProviders.length > 0 ? usableProviders : allProviders; const catalog: ModelCatalog = { options: [], + listed: allProviders.flatMap((provider) => provider.models.map((model) => model.id)), efforts: {}, labels: {}, providers: {}, defaultEfforts: {}, - defaultModel: '', - aliases: config.modelAliases ?? {} + defaultModel: '' }; for (const provider of providers) { for (const model of provider.models) { @@ -98,23 +98,18 @@ export function buildModelPickerItems( } /** - * Moves agent nodes saved with a retired model id to its configured - * replacement, so older workflows keep running. Returns true if any node changed. + * Moves agent nodes whose model the configuration no longer lists to the + * default model, which is also what the server would run them with. + * Returns true if any node changed. */ -export function applyModelAliases( - nodes: EditorNode[], - aliases: Record, - options: string[] -): boolean { +export function replaceUnlistedModels(nodes: EditorNode[], listed: string[], defaultModel: string): boolean { + if (!defaultModel) return false; let changed = false; for (const node of nodes) { const model = node.data?.model; - if (node.type !== 'agent' || !node.data || !model) continue; - const replacement = aliases[model]; - if (replacement && options.includes(replacement)) { - node.data.model = replacement; - changed = true; - } + if (node.type !== 'agent' || !node.data || !model || listed.includes(model)) continue; + node.data.model = defaultModel; + changed = true; } return changed; } diff --git a/apps/web/src/app/nodes/node-view.ts b/apps/web/src/app/nodes/node-view.ts index 8fdc141..8c31352 100644 --- a/apps/web/src/app/nodes/node-view.ts +++ b/apps/web/src/app/nodes/node-view.ts @@ -1,7 +1,6 @@ import { DEFAULT_APPROVAL_PROMPT, DEFAULT_CONDITION, - DEFAULT_MODEL, DEFAULT_REASONING_EFFORT, KEYBOARD_NODE_NUDGE_PX, PREVIOUS_OUTPUT_TEMPLATE, @@ -18,7 +17,7 @@ import type { EditorNode, WorkflowNodeData } from '../types'; import type { NodeForms } from './node-forms'; import { createPortElement, renderPorts } from './ports'; -export function getDefaultNodeData(type: string, defaultModel: string = DEFAULT_MODEL): WorkflowNodeData { +export function getDefaultNodeData(type: string, defaultModel: string): WorkflowNodeData { switch (type) { case 'agent': return { @@ -75,8 +74,8 @@ export function getNodePreviewHTML(node: EditorNode, modelLabels: Record new Response(JSON.stringify(value), { status }); +/** What `GET /api/config` returns for a project whose config.json lists one model. */ +const MODEL_CONFIG = { + defaultModel: 'gpt-5', + providers: [ + { id: 'openai', name: 'OpenAI', available: true, models: [{ id: 'gpt-5', name: 'GPT-5', reasoningEfforts: ['low'] }] } + ] +}; + const agentData = (overrides: EditorNode['data'] = {}): EditorNode['data'] => ({ agentName: 'Agent', systemPrompt: 'You are a helpful assistant.', @@ -89,7 +97,7 @@ beforeEach(() => { destroyedDropdowns.length = 0; document.body.innerHTML = bodyHtml; fetchRoute = (url) => { - if (url === '/api/config') return json({}); + if (url === '/api/config') return json(MODEL_CONFIG); if (url === '/api/default-workflow') return json({ error: 'No default workflow found' }, 404); if (url === '/api/workflow') return json({ error: 'No saved workflow' }, 404); return json({ error: `unexpected request to ${url}` }, 500); @@ -116,11 +124,39 @@ describe('WorkflowEditor start-up', () => { expect((document.getElementById('btn-cancel-run') as HTMLElement).style.display).toBe('none'); }); + it('keeps Run disabled and says why when the model configuration cannot be loaded', async () => { + fetchRoute = (url) => { + if (url === '/api/config') { + return json({ error: 'Failed to read config', details: 'Configuration file not found: .config/config.json' }, 500); + } + if (url === '/api/workflow') return json({ formatVersion: 1, savedAt: 'x', fingerprint: 'y', workflow: savedGraph() }); + return json({}, 404); + }; + await createEditor(); + const runButton = document.getElementById('btn-run') as HTMLButtonElement; + expect(runButton.disabled).toBe(true); + expect(runButton.getAttribute('data-disabled-hint')).toBe( + 'Models are not configured: Configuration file not found: .config/config.json' + ); + }); + + it('moves agents whose model the configuration no longer lists to the default model', async () => { + const graph = savedGraph(); + graph.nodes[1].data = agentData({ model: 'gpt-retired' }); + fetchRoute = (url) => { + if (url === '/api/config') return json(MODEL_CONFIG); + if (url === '/api/workflow') return json({ formatVersion: 1, savedAt: 'x', fingerprint: 'y', workflow: graph }); + return json({}, 404); + }; + const editor = await createEditor(); + expect(editor.store.nodes[1].data?.model).toBe('gpt-5'); + }); + it('prefers the workflow the server saved over the one in browser storage', async () => { const serverGraph = savedGraph(); serverGraph.nodes[1].data = agentData({ agentName: 'From server' }); fetchRoute = (url) => { - if (url === '/api/config') return json({}); + if (url === '/api/config') return json(MODEL_CONFIG); if (url === '/api/workflow') return json({ formatVersion: 1, savedAt: 'x', fingerprint: 'y', workflow: serverGraph }); return json({}, 404); }; @@ -134,7 +170,7 @@ describe('WorkflowEditor start-up', () => { it('saves the canvas to the server, once per change', async () => { const saves: unknown[] = []; fetchRoute = (url, init) => { - if (url === '/api/config') return json({}); + if (url === '/api/config') return json(MODEL_CONFIG); if (url === '/api/workflow' && init?.method === 'PUT') { saves.push(JSON.parse(String(init.body))); return json({ savedAt: 'x', fingerprint: 'y' }); @@ -563,6 +599,7 @@ describe('WorkflowEditor run controls', () => { requests.push(url); if (url === '/api/run-stream') return sse([{ type: 'start', runId: 'run-1' }, { type: 'done', result: pausedRun }]); if (url === '/api/cancel') return json({ ...pausedRun, status: 'cancelled', waitingForInput: false }); + if (url === '/api/config') return json(MODEL_CONFIG); if (url === '/api/default-workflow') return json({}, 404); return json({}); }; diff --git a/apps/web/src/app/workflow-editor.ts b/apps/web/src/app/workflow-editor.ts index 8fbaf98..dbd6e25 100644 --- a/apps/web/src/app/workflow-editor.ts +++ b/apps/web/src/app/workflow-editor.ts @@ -6,17 +6,13 @@ import type { WorkflowConnection } from '@agentflow/types'; import { fetchConfig } from '../services/api'; -import { applyModelAliases, buildModelCatalog } from './model-catalog'; +import { buildModelCatalog, replaceUnlistedModels } from './model-catalog'; import { ConnectionsController } from './canvas/connections'; import { ViewportController } from './canvas/viewport'; import { ChatView } from './chat/chat-view'; import { CANVAS_MESSAGE_TIMEOUT_MS, COLLAPSED_NODE_FALLBACK_HEIGHT, - DEFAULT_MODEL, - DEFAULT_MODEL_EFFORTS, - DEFAULT_MODEL_LABELS, - DEFAULT_MODEL_OPTIONS, DEFAULT_RIGHT_PANEL_WIDTH, DUPLICATE_NODE_MIN_WORLD_Y, DUPLICATE_NODE_SPACING, @@ -63,7 +59,11 @@ function getErrorMessage(error: unknown): string { export class WorkflowEditor implements EditorHost { readonly store: EditorStore; - private modelAliases: Record = {}; + /** Every model id the configuration lists. */ + private listedModels: string[] = []; + + /** Why the model configuration could not be loaded; agents cannot run until it is fixed. */ + private configError: string | null = null; readonly viewport: ViewportController; @@ -133,12 +133,12 @@ export class WorkflowEditor implements EditorHost { nextNodeId: 1, selectedNodeId: null, selectedConnection: null, - modelOptions: [...DEFAULT_MODEL_OPTIONS], - modelEfforts: { ...DEFAULT_MODEL_EFFORTS }, - modelLabels: { ...DEFAULT_MODEL_LABELS }, + modelOptions: [], + modelEfforts: {}, + modelLabels: {}, modelProviders: {}, modelDefaultEfforts: {}, - defaultModel: DEFAULT_MODEL + defaultModel: '' }; // DOM Elements @@ -185,7 +185,7 @@ export class WorkflowEditor implements EditorHost { this.addDefaultStartNode(); this.loadConfig().then(async () => { await this.loadInitialWorkflow(); - this.applyModelAliases(); + this.replaceUnlistedModels(); this.stateReady = true; this.history.reset(this.getGraph()); this.saveWorkflowState(); @@ -344,7 +344,8 @@ export class WorkflowEditor implements EditorHost { 'Workflow is paused waiting for approval. Approve, reject, or cancel the run.' ); } else { - const disabledReason = getRunDisableReason(this.store.nodes, this.store.connections); + const disabledReason = + this.configError ?? getRunDisableReason(this.store.nodes, this.store.connections); this.runButton.innerHTML = 'Run Workflow '; this.runButton.disabled = Boolean(disabledReason); this.setButtonHint(this.runButton, 'data-disabled-hint', disabledReason); @@ -641,21 +642,25 @@ export class WorkflowEditor implements EditorHost { private async loadConfig(): Promise { try { const catalog = buildModelCatalog(await fetchConfig()); - if (!catalog) return; + if (!catalog) throw new Error('.config/config.json lists no models.'); this.store.modelOptions = catalog.options; this.store.modelEfforts = catalog.efforts; this.store.modelLabels = catalog.labels; this.store.modelProviders = catalog.providers; this.store.modelDefaultEfforts = catalog.defaultEfforts; this.store.defaultModel = catalog.defaultModel; - this.modelAliases = catalog.aliases; - } catch { - // keep hardcoded defaults + this.listedModels = catalog.listed; + this.configError = null; + } catch (error) { + // No built-in model list to fall back on: say why and keep Run disabled. + this.configError = `Models are not configured: ${getErrorMessage(error)}`; + console.error(this.configError); } + this.updateRunButton(); } - private applyModelAliases(): void { - if (applyModelAliases(this.store.nodes, this.modelAliases, this.store.modelOptions)) { + private replaceUnlistedModels(): void { + if (replaceUnlistedModels(this.store.nodes, this.listedModels, this.store.defaultModel)) { this.render(); } } diff --git a/apps/web/src/services/api.ts b/apps/web/src/services/api.ts index e091ff2..d7cad03 100644 --- a/apps/web/src/services/api.ts +++ b/apps/web/src/services/api.ts @@ -155,22 +155,23 @@ export type ProviderModel = { export type Provider = { id: string; name: string; - enabled: boolean; - /** False when the server has no API key for this provider. Absent on older servers. */ + /** False when the server has no API key for this provider. */ available?: boolean; models: ProviderModel[]; }; export type AppConfig = { defaultModel?: string; - /** Maps model ids from older saved workflows to current ones. */ - modelAliases?: Record; providers?: Provider[]; }; +/** Throws with the server's explanation when `.config/config.json` is missing or invalid. */ export async function fetchConfig(): Promise { const res = await fetch('/api/config'); - if (!res.ok) return {}; + if (!res.ok) { + const body = (await res.json().catch(() => ({}))) as { error?: string; details?: string }; + throw new Error(body.details || body.error || `HTTP ${res.status}`); + } return res.json() as Promise; } diff --git a/docs/api.md b/docs/api.md index 51667e5..75f2c85 100644 --- a/docs/api.md +++ b/docs/api.md @@ -49,8 +49,7 @@ Responses: - `200`: `WorkflowRunResult` (+ `workflow`) - `400`: invalid graph payload; `details` lists each problem (shape, duplicate ids, unknown connection endpoints, size limits) -- `400`: an Agent node names a model that no enabled provider lists -- `503`: an Agent node uses a provider whose API key is not set +- `503`: an Agent node uses a provider whose API key is not set (a node whose model is not listed runs on the default model), or `.config/config.json` is missing or invalid - `500`: execution failure ## `POST /api/run-stream` @@ -189,13 +188,12 @@ Responses: ## `GET /api/config` -Returns the browser-safe view of `.config/config.json`: `defaultModel`, `modelAliases`, and for each provider its `id`, `name`, `enabled`, `available` (whether its API key is set) and `models` (`id`, `name`, `reasoningEfforts`, `defaultReasoningEffort`). Key variable names and base URLs are not included. +Returns the browser-safe view of `.config/config.json`: `defaultModel`, and for each provider its `id`, `name`, `available` (whether its API key is set) and `models` (`id`, `name`, `reasoningEfforts`, `defaultReasoningEffort`). Key variable names and base URLs are not included. Responses: - `200`: app config JSON -- `404`: config missing or invalid (the reason is logged by the server) -- `500`: read/parse failure +- `500`: the file is missing or invalid; `details` says why, and the editor shows it on the disabled Run button ## Persistence and Lifecycle Notes diff --git a/docs/architecture.md b/docs/architecture.md index 0890590..4469e4d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -70,7 +70,7 @@ The workflow engine supports: Subagents are function tools owned by the router. When a parent model calls one, the router runs the subagent as its own agent run on whatever provider its model belongs to, and logs the `subagent_call_*` events. Web Search maps to each provider's hosted search tool. -Before a run starts, the server checks that every Agent node names a configured model whose provider has an API key. +An Agent node whose model the file does not list runs on the default model. Before a run starts, the server checks that the provider of every model the run will use has an API key. There is no model list in code: without a valid file, agents cannot run. ## Subagent Model diff --git a/docs/configuration.md b/docs/configuration.md index 9fc5d42..c84017e 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -45,18 +45,20 @@ ## `.config/config.json` (committed) -Defines which providers and models the app offers. The server validates it, uses it to route each Agent node to a provider, and serves a browser-safe view through `GET /api/config`. The file is re-read when it changes, so no restart is needed. +The only list of the models the app offers. There is no model list in code: if the file is missing or invalid, the editor disables Run and shows why, and agents cannot run. The server validates it, uses it to route each Agent node to a provider, and serves a browser-safe view through `GET /api/config`. The file is re-read when it changes, so no restart is needed. + +To change what learners can use, edit the list: remove a model's entry to stop offering it, add one to offer it. A CodeSignal task or base task changes the models by shipping its own copy of this file. Keep models in order of strength, weakest first, within each provider. + +An Agent node whose model the file no longer lists runs on the default model, and the editor switches the node to the default model when it loads the workflow. A workflow saved before a model was removed therefore keeps running, and the report notes the substitution. ```json { "defaultModel": "gpt-6-luna", - "modelAliases": { "gpt-5": "gpt-6.2-sol" }, "providers": [ { "id": "openai", "name": "OpenAI", "type": "openai", - "enabled": true, "apiKeyEnv": "OPENAI_API_KEY", "models": [ { @@ -71,12 +73,11 @@ Defines which providers and models the app offers. The server validates it, uses "id": "anthropic", "name": "Anthropic", "type": "anthropic", - "enabled": true, "apiKeyEnv": "ANTHROPIC_API_KEY", "models": [ { - "id": "claude-opus-5-5", - "name": "Claude Opus 5.5", + "id": "claude-sonnet-5-5", + "name": "Claude Sonnet 5.5", "reasoningEfforts": ["low", "medium", "high", "xhigh", "max"], "defaultReasoningEffort": "medium", "refusalFallback": true @@ -87,42 +88,44 @@ Defines which providers and models the app offers. The server validates it, uses } ``` +Fields not listed below are rejected, so a misspelt field fails loudly instead of being ignored. `modelAliases` and a provider's `enabled` were removed: delete entries instead. + Top-level fields: -| Field | Meaning | -| --- | --- | -| `defaultModel` | Model for new Agent nodes and for nodes that name none. Defaults to the first model of a provider that has a key. | -| `modelAliases` | Maps model ids found in older saved workflows to current ids. Applied by the editor on load and by the server at run time. | -| `providers` | Provider list, in the order models appear in the editor. | +| Field | Required | Meaning | +| --- | --- | --- | +| `defaultModel` | no | Model for new Agent nodes, for nodes that name none, and for nodes whose model is not listed. Must be one of the listed models. Defaults to the first model of a provider that has a key, else the first model. | +| `providers` | yes | Provider list, in the order models appear in the editor. Must list at least one model. | Provider fields: -| Field | Meaning | -| --- | --- | -| `id` | Unique id. | -| `name` | Display name. Defaults to `id`. | -| `type` | `openai` (OpenAI Agents SDK) or `anthropic` (Anthropic SDK). May be omitted when `id` is one of those. | -| `enabled` | `false` hides the provider. Defaults to `true`. | -| `apiKeyEnv` | Environment variable holding the key. Defaults to `OPENAI_API_KEY` or `ANTHROPIC_API_KEY`. | -| `baseUrl` | Optional API base URL, for a proxy or an OpenAI-compatible service. | -| `api` | `openai` type only: `responses` (default) or `chat_completions` for OpenAI-compatible services. Web Search needs `responses`. | -| `models` | Models offered by this provider. A model id may appear in only one enabled provider. | +| Field | Required | Meaning | +| --- | --- | --- | +| `id` | yes | Unique id. | +| `name` | no | Heading in the model picker. Defaults to `id`. | +| `type` | no | `openai` (OpenAI Agents SDK) or `anthropic` (Anthropic SDK). May be omitted when `id` is one of those. | +| `apiKeyEnv` | no | Environment variable holding the key. Defaults to `OPENAI_API_KEY` or `ANTHROPIC_API_KEY`. | +| `baseUrl` | no | API base URL, for a proxy or an OpenAI-compatible service. | +| `api` | no | `openai` type only: `responses` (default) or `chat_completions` for OpenAI-compatible services. Web Search needs `responses`. | +| `models` | yes | Models offered by this provider. A model id may appear in only one provider. | Model fields: -| Field | Meaning | -| --- | --- | -| `id` | Model id sent to the provider. | -| `name` | Label in the editor. Defaults to `id`. | -| `reasoningEfforts` | Effort values offered in the editor. | -| `defaultReasoningEffort` | Used when a node has no effort, or one this model does not list. | -| `maxOutputTokens` | `anthropic` type only: output cap per model call. Defaults to 16000. | -| `refusalFallback` | `anthropic` type only: lets the API re-run a declined request on a fallback model (`fallbacks: "default"`). Not supported on Claude Haiku 5.5. | +| Field | Required | Meaning | +| --- | --- | --- | +| `id` | yes | Model id sent to the provider. | +| `name` | no | Label in the editor. Defaults to `id`. | +| `reasoningEfforts` | no | Effort values offered in the editor. Empty when the model has no effort setting. | +| `defaultReasoningEffort` | no | Used when a node has no effort, or one this model does not list. Must be one of `reasoningEfforts`. | +| `maxOutputTokens` | no | `anthropic` type only: output cap per model call. Defaults to 16000. | +| `refusalFallback` | no | `anthropic` type only: `true` lets the API re-run a declined request on a fallback model (`fallbacks: "default"`). Not supported on Claude Haiku 5.5. | Several providers of the same type can be configured side by side, for example OpenAI plus an OpenAI-compatible service with its own `baseUrl`, `apiKeyEnv` and `"api": "chat_completions"`. An Agent node and its subagents may use models from different providers. +The models offered must also be allowed by whatever sits in front of the providers. In a CodeSignal session that is the LLM proxy's model allow-list on the base task; a model this file lists but the proxy refuses fails at run time. + ## `.config/default-workflow.json` (gitignored) Optional startup graph served by `GET /api/default-workflow`. diff --git a/docs/report.md b/docs/report.md index a67db95..223c152 100644 --- a/docs/report.md +++ b/docs/report.md @@ -18,12 +18,12 @@ From the project root: - `data/workflow.json`: the learner's saved canvas. - `data/runs/*.json`: run records, both the current and the legacy file names. - `.config/default-workflow.json`: the task's starting workflow, to list what the learner changed. -- `.config/config.json`: model names, aliases, effort settings and the default model. +- `.config/config.json`: model names, effort settings and the default model. ## Sections 1. **Summary**: where the workflow came from (saved canvas, else the latest run's workflow, else the starting workflow), whether the editor would run it (the same check as the Run button, `getRunDisableReason` from `@agentflow/workflow-graph`), node counts, changes from the starting workflow, run counts by status, and whether the latest run used the current workflow (fingerprint comparison). -2. **Workflow**: nodes in the order a run reaches them from Start, then agents used only as subagents, then **Unconnected nodes**. Agents show model (display name and id, noting the default model or an alias), effective reasoning effort, tools, subagent links, next steps, system prompt and input. Conditions show their rules and branch targets; approvals show their message and both branches. +2. **Workflow**: nodes in the order a run reaches them from Start, then agents used only as subagents, then **Unconnected nodes**. Agents show model (display name and id, noting the default model, and when the node names a model the configuration no longer lists), effective reasoning effort, tools, subagent links, next steps, system prompt and input. Conditions show their rules and branch targets; approvals show their message and both branches. 3. **Runs (newest first)**: one line per run: number (oldest saved run is 1), start time in UTC, status, duration, current or earlier workflow, and the path of steps. Loops repeated three or more times are written once with a count, such as `(Researcher → Condition 1) × 12`. 4. **Latest 3 runs step by step**: each step with its input, web searches, subagent calls (task and answer), condition checks and the branch taken, approval decisions and feedback, output and errors, then the result. A run made with an earlier workflow lists what changed since. diff --git a/docs/run-persistence.md b/docs/run-persistence.md index 5e53beb..0249f29 100644 --- a/docs/run-persistence.md +++ b/docs/run-persistence.md @@ -56,7 +56,7 @@ Fields: - `finishedAt`: when it completed, failed or was cancelled; `null` while running or paused (since 2). - `workflowFingerprint`: fingerprint of `workflow`, to compare a run with the saved workflow (since 2). - `workflow`: graph that actually ran. -- `models`: model id each agent node ran with, after aliases and the default model (since 2). +- `models`: model id each agent node ran with: its own if `.config/config.json` lists it, otherwise the default model (since 2). - `logs`: ordered runtime log entries (see [Workflow Semantics](./workflow-semantics.md)). - `status`: current/terminal status. - `state`: engine internal state snapshot. `state.previous_output` holds the final output of a completed run. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index b6f80e8..01fc454 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -9,15 +9,21 @@ Fix: 1. Export the named variable (for example `OPENAI_API_KEY` or `ANTHROPIC_API_KEY`) in the shell. 2. Restart `npm run dev`. -## `Model "..." is not listed by any enabled provider` +## An agent ran on a different model than the one it was set to -Cause: an Agent node uses a model id that is not in `.config/config.json`, usually from an older saved workflow. +Cause: its model is no longer listed in `.config/config.json`, so it ran on the default model. The editor also switches such nodes to the default model when it loads the workflow. -Fix: pick a current model on the node, or add the old id to `modelAliases` in `.config/config.json`. +Fix: add the model back to `.config/config.json` if it should still be offered. + +## Run disabled with "Models are not configured: ..." + +Cause: `.config/config.json` is missing or invalid; the message says what is wrong (for example a field that is not part of the schema). There is no built-in model list to fall back on. + +Fix: correct the file (see [Configuration](./configuration.md)) and reload the page. ## A provider's models are missing from the editor -Cause: the provider is disabled or its API key is not set. Models of providers without a key are hidden while at least one other provider has a key. +Cause: the provider is not in `.config/config.json`, or its API key is not set. Models of providers without a key are hidden while at least one other provider has a key. Fix: set the key named by the provider's `apiKeyEnv` and reload the page. diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts index 0abfa1f..dc423da 100644 --- a/packages/types/src/index.ts +++ b/packages/types/src/index.ts @@ -100,7 +100,7 @@ export interface WorkflowRunRecord { /** `workflowFingerprint()` of `workflow`, to match the run to a saved workflow. Since 2. */ workflowFingerprint?: string; workflow: WorkflowGraph; - /** Model id each agent node ran with, after aliases and the default model. Since 2. */ + /** Model id each agent node ran with: its own if listed, otherwise the default model. Since 2. */ models?: Record; logs: WorkflowLogEntry[]; status: WorkflowStatus; diff --git a/packages/workflow-engine/src/index.ts b/packages/workflow-engine/src/index.ts index 97b4b47..3c9601b 100644 --- a/packages/workflow-engine/src/index.ts +++ b/packages/workflow-engine/src/index.ts @@ -27,7 +27,8 @@ export interface AgentSubagentInvocation { nodeId: string; agentName: string; systemPrompt: string; - model: string; + /** Absent when the node names no model; the LLM then uses its default. */ + model?: string; reasoningEffort?: string; tools?: AgentToolsConfig; subagents?: AgentSubagentInvocation[]; @@ -36,7 +37,8 @@ export interface AgentSubagentInvocation { export interface AgentInvocation { systemPrompt: string; userContent: string; - model: string; + /** Absent when the node names no model; the LLM then uses its default. */ + model?: string; reasoningEffort?: string; tools?: AgentToolsConfig; subagents?: AgentSubagentInvocation[]; @@ -104,7 +106,10 @@ export interface WorkflowEngineInitOptions { * matches. Defaults to {@link DEFAULT_MAX_STEPS}. */ maxSteps?: number; - /** Model for agent nodes that do not name one. Defaults to {@link DEFAULT_MODEL}. */ + /** + * Model for agent nodes that do not name one. Without it, such nodes are + * sent with no model and the LLM picks its own default. + */ defaultModel?: string; /** * Restore a previously paused engine to its exact saved state. @@ -121,7 +126,6 @@ export interface WorkflowEngineInitOptions { } export const DEFAULT_MAX_STEPS = 100; -export const DEFAULT_MODEL = 'gpt-6-luna'; const DEFAULT_SYSTEM_PROMPT = 'You are a helpful assistant.'; const DEFAULT_REASONING = 'low'; const PREVIOUS_OUTPUT_PLACEHOLDER = /\{\{PREVIOUS_OUTPUT\}\}/g; @@ -187,7 +191,7 @@ export class WorkflowEngine { private readonly maxSteps: number; - private readonly defaultModel: string; + private readonly defaultModel: string | undefined; private stepCount = 0; @@ -196,7 +200,7 @@ export class WorkflowEngine { constructor(graph: WorkflowGraph, options: WorkflowEngineInitOptions = {}) { this.graph = this.normalizeGraph(graph); this.runId = options.runId ?? globalThis.crypto.randomUUID(); - this.defaultModel = options.defaultModel?.trim() || DEFAULT_MODEL; + this.defaultModel = options.defaultModel?.trim() || undefined; this.maxSteps = typeof options.maxSteps === 'number' && Number.isFinite(options.maxSteps) && options.maxSteps > 0 ? Math.floor(options.maxSteps)