From f358ac2e41efb0b84dd8f20d4a6fb12e2193245d Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:16:13 +0000 Subject: [PATCH 1/5] Initial plan From 45867083827c53df53ee86548bb54cdea5a5cdc9 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:34:05 +0000 Subject: [PATCH 2/5] feat: unify exact-model reasoning decisions --- containers/api-proxy/Dockerfile | 2 +- .../catalogue-contract/reasoning.d.ts | 44 ++++ .../api-proxy/catalogue-contract/reasoning.js | 130 +++++++++++ containers/api-proxy/model-reasoning.js | 134 +++++++++++ containers/api-proxy/model-reasoning.test.js | 178 +++++++++++++++ .../api-proxy/reasoning-effort-validation.js | 20 +- .../reasoning-effort-validation.test.js | 49 ++++ containers/api-proxy/routing-candidates.js | 24 +- containers/api-proxy/routing-catalogue.js | 38 +--- containers/api-proxy/routing-controller.js | 4 +- .../api-proxy/routing-provider-executor.js | 1 + containers/api-proxy/runtime-model-catalog.js | 5 +- containers/api-proxy/upstream-http.js | 2 +- docs/adr/0004-model-information-management.md | 64 ++++++ package.json | 2 +- scripts/model-information/compile.cjs | 21 ++ shared/model-information/reasoning.d.ts | 44 ++++ shared/model-information/reasoning.js | 130 +++++++++++ src/model-information-contract/reasoning.d.ts | 44 ++++ src/model-information-contract/reasoning.js | 130 +++++++++++ src/model-information-reasoning.test.ts | 209 ++++++++++++++++++ 21 files changed, 1213 insertions(+), 62 deletions(-) create mode 100644 containers/api-proxy/catalogue-contract/reasoning.d.ts create mode 100644 containers/api-proxy/catalogue-contract/reasoning.js create mode 100644 containers/api-proxy/model-reasoning.js create mode 100644 containers/api-proxy/model-reasoning.test.js create mode 100644 shared/model-information/reasoning.d.ts create mode 100644 shared/model-information/reasoning.js create mode 100644 src/model-information-contract/reasoning.d.ts create mode 100644 src/model-information-contract/reasoning.js create mode 100644 src/model-information-reasoning.test.ts diff --git a/containers/api-proxy/Dockerfile b/containers/api-proxy/Dockerfile index d1d55dd62..d355892d9 100644 --- a/containers/api-proxy/Dockerfile +++ b/containers/api-proxy/Dockerfile @@ -62,7 +62,7 @@ COPY server.js logging.js metrics.js rate-limiter.js rate-limiter-window.js \ token-tracker.js token-persistence.js token-parsers.js \ token-tracker-http.js token-tracker-ws.js token-tracker-shared.js \ model-resolver.js model-identity.js model-fallback.js model-fallback-chain.js model-utils.js model-body-rewriter.js proxy-utils.js oidc-adapter-utils.js adapter-factory.js anthropic-transforms.js claude-hosted-web.js codex-hosted-web.js hosted-web-policy.js \ - model-config.js model-recovery.js model-selector.js model-eligibility.js harness-observation.js scoped-auto-model.js key-validation.js server-factory.js startup.js \ + model-config.js model-recovery.js model-selector.js model-eligibility.js model-reasoning.js harness-observation.js scoped-auto-model.js key-validation.js server-factory.js startup.js \ proxy-request.js request-headers.js upstream-http.js proxy-guards.js proxy-error-handler.js http-client.js body-handler.js reasoning-effort-validation.js model-discovery.js management.js oidc-token-provider.js \ oidc-token-provider-base.js \ github-oidc.js aws-oidc-token-provider.js aws-sigv4.js gcp-oidc-token-provider.js \ diff --git a/containers/api-proxy/catalogue-contract/reasoning.d.ts b/containers/api-proxy/catalogue-contract/reasoning.d.ts new file mode 100644 index 000000000..51f6ecd8e --- /dev/null +++ b/containers/api-proxy/catalogue-contract/reasoning.d.ts @@ -0,0 +1,44 @@ +import { ModelIdentity } from './identity'; +import { ModelScope } from './resolution'; + +export type ReasoningSupport = 'absent' | 'unknown' | 'supported' | 'unsupported'; +export type ReasoningMode = 'optional' | 'required' | 'forbidden' | 'unknown'; +export interface ReasoningFact { + identity: ModelIdentity; + scope: ModelScope; + active: boolean; + authority: 'provider' | 'maintained'; + support: Exclude | 'conditional'; + rawEfforts?: readonly string[]; + mode?: ReasoningMode; + default?: string; + provenance?: Record; +} +export interface ReasoningInput { + identity: ModelIdentity | null; + scope: ModelScope; + facts?: readonly ReasoningFact[]; +} +export interface ReasoningReason { + readonly code: string; +} +export interface ReasoningDecision { + readonly identity: Readonly> | null; + readonly scope: Readonly; + readonly support: ReasoningSupport; + readonly mode: ReasoningMode; + readonly supportedEfforts: readonly string[]; + readonly selectableEfforts: readonly string[]; + readonly default?: string; + readonly observations: readonly Readonly<{ + authority: string; + rawEfforts: readonly string[]; + provenance: Readonly>; + selected: boolean; + }>[]; + readonly reasons: readonly ReasoningReason[]; +} +export function resolveReasoning(input: ReasoningInput): ReasoningDecision; +export function assessReasoningEffort( + decision: ReasoningDecision, effort: string | undefined, options?: { automatic?: boolean }, +): Readonly<{ admitted: boolean; reasons: readonly ReasoningReason[] }>; diff --git a/containers/api-proxy/catalogue-contract/reasoning.js b/containers/api-proxy/catalogue-contract/reasoning.js new file mode 100644 index 000000000..c0bdacce8 --- /dev/null +++ b/containers/api-proxy/catalogue-contract/reasoning.js @@ -0,0 +1,130 @@ +'use strict'; + +const { isDeepStrictEqual } = require('node:util'); + +const UNDERSTOOD_EFFORTS = new Set(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']); +const AUTHORITIES = { provider: 2, maintained: 1 }; + +function freeze(value) { + if (value && typeof value === 'object') { + for (const child of Object.values(value)) freeze(child); + Object.freeze(value); + } + return value; +} + +function provenance(value = {}) { + if (!value || typeof value !== 'object') return {}; + return Object.fromEntries(['authority', 'source', 'revision', 'at', 'apiVersion', 'field'] + .filter(key => typeof value[key] === 'string') + .map(key => [key, value[key].replace(/\p{Cc}/gu, '').slice(0, 512)])); +} + +function sameScope(left, right) { + return left?.provider === right.provider && left?.channel === right.channel && + left?.deployment === right.deployment; +} + +// Inputs are exact, captured facts, not names, family rules or live stores. +function resolveReasoning({ identity, scope, facts = [] }) { + const reasons = []; + const applicable = []; + for (const fact of facts) { + if (!fact || typeof fact !== 'object') { + reasons.push({ code: 'reasoning_malformed_fact' }); + continue; + } + let code; + if (!identity || identity.provider !== scope.provider || + fact.identity?.key !== identity.key || fact.identity?.provider !== identity.provider) { + code = 'reasoning_identity_mismatch'; + } else if (!sameScope(fact.scope, scope)) code = 'reasoning_scope_mismatch'; + else if (fact.active !== true) code = 'reasoning_inactive_fact'; + else if (!Object.hasOwn(AUTHORITIES, fact.authority)) code = 'reasoning_unreviewed_authority'; + if (code) reasons.push({ code }); + else applicable.push(fact); + } + const priority = Math.max(0, ...applicable.map(fact => AUTHORITIES[fact.authority])); + const selected = applicable.filter(fact => AUTHORITIES[fact.authority] === priority); + const observations = applicable.map(fact => ({ + authority: fact.authority, + rawEfforts: Array.isArray(fact.rawEfforts) ? fact.rawEfforts.filter(value => typeof value === 'string') : [], + provenance: provenance(fact.provenance), + selected: selected.includes(fact), + })); + let support = selected.length ? 'unknown' : 'absent'; + let mode = 'unknown'; + let supportedEfforts = []; + let defaultEffort; + if (selected.length) { + const fact = selected[0]; + const signature = value => ({ + support: value.support, rawEfforts: value.rawEfforts, mode: value.mode, default: value.default, + }); + const conflicting = selected.some(value => !isDeepStrictEqual(signature(value), signature(fact))); + const rawEfforts = Array.isArray(fact.rawEfforts) + ? fact.rawEfforts.filter(value => typeof value === 'string' && value.length > 0) : []; + const effortsValid = Array.isArray(fact.rawEfforts) && + (fact.rawEfforts.length === 0 || rawEfforts.length > 0); + if (effortsValid && rawEfforts.length !== fact.rawEfforts.length) { + reasons.push({ code: 'reasoning_malformed_effort_ignored' }); + } + const malformed = !['supported', 'unsupported', 'unknown', 'conditional'].includes(fact.support) || + (fact.rawEfforts !== undefined && !effortsValid) || + (fact.support === 'supported' && (!effortsValid || fact.rawEfforts.length === 0)) || + (fact.support === 'unsupported' && fact.rawEfforts?.length > 0) || + (fact.mode !== undefined && !['optional', 'required', 'forbidden', 'unknown'].includes(fact.mode)) || + (fact.mode === 'forbidden' && fact.support === 'supported') || + (fact.mode === 'required' && fact.support === 'unsupported'); + if (conflicting || malformed) { + reasons.push({ code: conflicting ? 'reasoning_conflicting_facts' : 'reasoning_malformed_fact' }); + } else { + support = fact.support === 'conditional' ? 'unknown' : fact.support; + mode = fact.mode || 'unknown'; + if (support === 'supported') supportedEfforts = [...new Set(rawEfforts)]; + if (fact.default !== undefined) { + if (typeof fact.default === 'string' && supportedEfforts.includes(fact.default) && mode !== 'forbidden') { + defaultEffort = fact.default; + } else reasons.push({ code: 'reasoning_invalid_default' }); + } + if (fact.support === 'conditional') reasons.push({ code: 'reasoning_condition_unverified' }); + } + } + reasons.push({ code: `reasoning_support_${support}` }); + if (supportedEfforts.some(effort => !UNDERSTOOD_EFFORTS.has(effort))) { + reasons.push({ code: 'reasoning_future_effort_not_selectable' }); + } + return freeze({ + identity: identity ? { key: identity.key, provider: identity.provider, rawId: identity.rawId } : null, + scope: { ...scope }, support, mode, supportedEfforts, + selectableEfforts: supportedEfforts.filter(effort => UNDERSTOOD_EFFORTS.has(effort)), + ...(defaultEffort === undefined ? {} : { default: defaultEffort }), + observations, reasons, + }); +} + +function assessReasoningEffort(decision, effort, { automatic = false } = {}) { + let code; + if (effort === undefined) { + if (decision.mode === 'required') code = 'reasoning_effort_required'; + else if (automatic && decision.support !== 'unsupported' && + !(decision.support === 'supported' && decision.mode === 'optional')) { + code = 'reasoning_automatic_requires_known_support'; + } + } else if (decision.mode === 'forbidden' || decision.support === 'unsupported') { + code = 'reasoning_effort_forbidden'; + } else if (decision.support === 'supported' && !decision.supportedEfforts.includes(effort)) { + code = 'reasoning_effort_unsupported'; + } else if (automatic && decision.support !== 'supported') { + code = 'reasoning_automatic_requires_known_support'; + } else if (automatic && !decision.selectableEfforts.includes(effort)) { + code = 'reasoning_future_effort_not_selectable'; + } + return freeze({ + admitted: !code, + reasons: [{ code: code || (['unknown', 'absent'].includes(decision.support) + ? 'reasoning_direct_unknown_passthrough' : 'reasoning_effort_accepted') }], + }); +} + +module.exports = { resolveReasoning, assessReasoningEffort }; diff --git a/containers/api-proxy/model-reasoning.js b/containers/api-proxy/model-reasoning.js new file mode 100644 index 000000000..7fa4f433b --- /dev/null +++ b/containers/api-proxy/model-reasoning.js @@ -0,0 +1,134 @@ +'use strict'; + +const { resolveReasoning, assessReasoningEffort } = require('./catalogue-contract/reasoning'); +const { resolveModelIdentity } = require('./model-identity'); +const { resolveIdentity } = require('./catalogue-contract/resolution'); +const { getModelEligibilityScope } = require('./model-eligibility'); +const { lookupModelRoutingMetadata, getModelApiMapping } = require('./model-api-mapping'); +const { getRuntimeModels } = require('./runtime-model-catalog'); +const { isGithubCopilotCatalogTarget } = require('./providers/copilot-auth'); + +const modelPins = new WeakMap(); +const requestPins = new WeakMap(); +const NATIVE_PROVIDER_HOSTS = Object.freeze({ + openai: 'api.openai.com', + anthropic: 'api.anthropic.com', +}); + +function runtimeFact(record, identity, scope) { + const supports = record.capabilities?.supports; + let rawEfforts; + let field; + let support = 'unknown'; + let mode; + if (Array.isArray(record.supportedReasoningEfforts)) { + rawEfforts = record.supportedReasoningEfforts; + field = 'supportedReasoningEfforts'; + } else if (Array.isArray(supports?.reasoning_effort)) { + rawEfforts = supports.reasoning_effort; + field = 'capabilities.supports.reasoning_effort'; + } else if (supports?.reasoningEffort === false) { + rawEfforts = []; + field = 'capabilities.supports.reasoningEffort'; + } else if (Object.hasOwn(record, 'supportedReasoningEfforts')) { + rawEfforts = record.supportedReasoningEfforts; + field = 'supportedReasoningEfforts'; + } else if (supports && Object.hasOwn(supports, 'reasoning_effort')) { + rawEfforts = supports.reasoning_effort; + field = 'capabilities.supports.reasoning_effort'; + } else if (supports && Object.hasOwn(supports, 'reasoningEffort')) { + field = 'capabilities.supports.reasoningEffort'; + } else if (scope.provider === 'copilot' && supports && + typeof supports === 'object' && !Array.isArray(supports)) { + rawEfforts = []; + field = 'capabilities.supports'; + } + if (!field) return null; + if (Array.isArray(rawEfforts)) { + support = rawEfforts.length ? 'supported' : 'unsupported'; + if (!rawEfforts.length) mode = 'forbidden'; + } + return { + identity, scope: record.scope || getModelEligibilityScope(identity.provider), active: true, authority: 'provider', + support, rawEfforts, mode, + provenance: { authority: 'provider', source: 'provider-model-list', field, + at: record.observedAt, apiVersion: record.apiVersion }, + }; +} + +function capturedIdentity(model, provider, scope, identities) { + const resolved = resolveModelIdentity(model, provider, { scope, policy: { providerPrefix: false } }); + return resolved.matchKind === 'unmatched' + ? resolveIdentity(model, scope, { models: identities.map(identity => ({ identity })) }, + { caseInsensitive: true, providerPrefix: false }) + : resolved; +} + +function resolveModelReasoning(model, provider, { records = getRuntimeModels(provider) || [], scope, maintained = true } = {}) { + scope = { ...getModelEligibilityScope(provider), ...scope, provider }; + const captured = records.filter(record => !record.provider || record.provider === provider).map(record => ({ + record, + identity: resolveModelIdentity(record.id, provider, { scope, policy: { providerPrefix: false } }).identity, + })); + const resolution = capturedIdentity(model, provider, scope, captured.map(entry => entry.identity).filter(Boolean)); + const facts = []; + for (const { record, identity: exact } of captured) { + if (!exact || !resolution.identity || exact.key !== resolution.identity.key) continue; + const fact = runtimeFact(record, exact, scope); + if (fact) facts.push(fact); + } + // Only active maintained native-API mappings apply. Staged canonical targets, + // imported metadata, accounting families and custom deployments are not evidence. + if (maintained && scope.channel === 'native-api' && scope.deployment === undefined) { + const mapped = lookupModelRoutingMetadata(resolution.wireId, provider); + if (mapped) facts.push({ + identity: resolution.identity, scope, active: true, authority: 'maintained', + support: mapped.reasoningEfforts.length ? 'supported' : 'unsupported', + rawEfforts: mapped.reasoningEfforts, + provenance: { authority: 'maintained', source: 'model-api-mapping', + at: getModelApiMapping()?.lastUpdated, field: 'routing.reasoningEfforts' }, + }); + } + return resolveReasoning({ identity: resolution.identity, scope, facts }); +} + +function pinModelReasoning(model, decision) { + modelPins.set(model, decision); + return model; +} + +function getModelReasoning(model, provider) { + return modelPins.get(model) || resolveModelReasoning(model.id, provider, { + records: [{ id: model.id, ...(model.efforts === undefined ? {} : { supportedReasoningEfforts: model.efforts }) }], + maintained: false, + }); +} + +function getRequestReasoning(model, provider, runtimeCatalog, req = {}, options = {}) { + const scope = getModelEligibilityScope(provider, req); + const nativeTarget = options.targetHost === undefined || ( + (provider === 'copilot' ? isGithubCopilotCatalogTarget(options.targetHost) + : options.targetHost.toLowerCase() === NATIVE_PROVIDER_HOSTS[provider]) && + (options.targetScheme === undefined || options.targetScheme === 'https')); + const key = JSON.stringify([provider, model, scope, nativeTarget]); + let pins = requestPins.get(req); + if (!pins) requestPins.set(req, pins = new Map()); + if (!pins.has(key)) { + const selected = req.awfReasoning; + const resolved = capturedIdentity(model, provider, scope, selected?.identity ? [selected.identity] : []); + const matches = nativeTarget && selected?.identity && resolved.identity && + selected.identity.key === resolved.identity.key && + selected.scope.provider === scope.provider && selected.scope.channel === scope.channel && + selected.scope.deployment === scope.deployment; + pins.set(key, matches ? selected : resolveModelReasoning(model, provider, { + scope, records: runtimeCatalog ? runtimeCatalog[provider] || [] : getRuntimeModels(provider) || [], + maintained: nativeTarget, + })); + } + return pins.get(key); +} + +module.exports = { + resolveModelReasoning, pinModelReasoning, getModelReasoning, getRequestReasoning, assessReasoningEffort, + NATIVE_PROVIDER_HOSTS, +}; diff --git a/containers/api-proxy/model-reasoning.test.js b/containers/api-proxy/model-reasoning.test.js new file mode 100644 index 000000000..537997536 --- /dev/null +++ b/containers/api-proxy/model-reasoning.test.js @@ -0,0 +1,178 @@ +'use strict'; + +const { + parseProviderModelMetadata, replaceRuntimeModels, clearRuntimeModels, captureRuntimePricing, +} = require('./runtime-model-catalog'); +const { resolveModelReasoning, getModelReasoning, getRequestReasoning } = require('./model-reasoning'); +const { normalizeModel } = require('./routing-catalogue'); +const { getModelRoutingChoices, buildRoutingCandidates } = require('./routing-candidates'); +const { validateReasoningEffort } = require('./reasoning-effort-validation'); + +const body = (model, effort = 'future') => Buffer.from(JSON.stringify({ model, reasoning_effort: effort })); +afterEach(() => clearRuntimeModels()); + +describe('shared direct and routing reasoning adapters', () => { + it.each([ + [{ supportedReasoningEfforts: ['max'], capabilities: { supports: { reasoning_effort: ['low'], reasoningEffort: false } } }, ['max']], + [{ capabilities: { supports: { reasoning_effort: ['none'], reasoningEffort: false } } }, ['none']], + [{ capabilities: { supports: { reasoningEffort: false } } }, []], + [{ capabilities: { supports: { streaming: true } } }, []], + [{ capabilities: { supports: { reasoning_effort: 'low' } } }, undefined], + [{}, undefined], + ])('characterizes runtime precedence without an independent routing table: %j', (metadata, efforts) => { + const record = { id: 'exact-test', ...metadata }; + const catalog = { copilot: [record] }; + const normalized = normalizeModel(record.id, record, 'copilot'); + const direct = getRequestReasoning(record.id, 'copilot', catalog); + expect(getModelReasoning(normalized, 'copilot')).toEqual(direct); + expect(normalized.efforts).toEqual(efforts); + if (efforts === undefined) { + expect(() => validateReasoningEffort(body(record.id), 'copilot', '/chat/completions', catalog)).not.toThrow(); + } else { + expect(() => validateReasoningEffort(body(record.id), 'copilot', '/chat/completions', catalog)) + .toThrow(expect.objectContaining({ code: 'unsupported_reasoning_effort' })); + } + }); + + it('keeps observed future values and their provenance but never automatically selects them', () => { + const records = parseProviderModelMetadata('copilot', { + data: [{ id: 'exact-test', supportedReasoningEfforts: ['none', 'max', 'future'], + supported_endpoints: ['/responses'] }], + }, { observedAt: '2026-11-01T00:00:00Z', apiVersion: 'fixture-version' }); + const normalized = normalizeModel('exact-test', records[0], 'copilot'); + expect(getModelRoutingChoices(normalized, 'copilot')).toEqual([ + { effort: 'none', protocol: 'responses' }, { effort: 'max', protocol: 'responses' }, + ]); + expect(getModelReasoning(normalized, 'copilot').observations[0]).toMatchObject({ + rawEfforts: ['none', 'max', 'future'], + provenance: { at: '2026-11-01T00:00:00Z', apiVersion: 'fixture-version' }, + }); + const catalog = { copilot: records }; + expect(() => validateReasoningEffort(Buffer.from(JSON.stringify({ + model: 'exact-test', reasoning: { effort: 'future' }, + })), 'copilot', '/responses', + catalog)).not.toThrow(); + expect(() => validateReasoningEffort(body('exact-test'), 'copilot', '/chat/completions', + catalog)).not.toThrow(); + }); + + it('uses reviewed scoped aliases, not same-slug backends or broad date normalization', () => { + const records = [{ id: 'claude-opus-4-8', supportedReasoningEfforts: ['max'] }]; + expect(resolveModelReasoning('claude-opus-4-8-20990101', 'copilot', { records }).support).toBe('absent'); + expect(resolveModelReasoning('claude-opus-4-8', 'openrouter', { + records: records.map(record => ({ ...record, provider: 'copilot' })), + }).support).toBe('absent'); + const scoped = records.map(record => ({ ...record, scope: { + provider: 'copilot', channel: 'copilot-api', deployment: 'enterprise-a', + } })); + expect(resolveModelReasoning('claude-opus-4-8', 'copilot', { records: scoped }).support).toBe('absent'); + expect(resolveModelReasoning('claude-opus-4-8', 'copilot', { + records: scoped, scope: scoped[0].scope, + }).support).toBe('supported'); + for (const scope of [{ deployment: 'other-enterprise' }, { channel: 'native-api' }]) { + expect(resolveModelReasoning('claude-opus-4-8', 'copilot', { records, scope }).support).toBe('absent'); + } + }); + + it('reuses scoped alias resolution and raw exact-ID precedence for captured facts', () => { + const { identity } = require('./catalogue-contract/identity'); + const scope = { provider: 'copilot', channel: 'copilot-api' }; + jest.isolateModules(() => { + jest.doMock('./model-information.naming.generated.json', () => ({ + models: [{ identity: { + ...identity('copilot', 'exact'), + aliases: [{ id: 'reviewed-alias', match: 'exact', scope }], + } }], + })); + const resolve = require('./model-reasoning').resolveModelReasoning; + const records = [{ id: 'exact', supportedReasoningEfforts: ['max'] }]; + expect(resolve('reviewed-alias', 'copilot', { records }).supportedEfforts).toEqual(['max']); + expect(resolve('reviewed-alias', 'copilot', { records, scope: { + ...scope, deployment: 'custom', + } }).support).toBe('absent'); + expect(resolve('reviewed-alias', 'openai', { records }).support).toBe('absent'); + }); + jest.dontMock('./model-information.naming.generated.json'); + jest.isolateModules(() => { + jest.doMock('./model-information.naming.generated.json', () => ({ + models: [ + { identity: { ...identity('copilot', 'exact'), + aliases: [{ id: 'literal', match: 'exact', scope }] } }, + { identity: identity('copilot', 'literal') }, + ], + })); + const resolve = require('./model-reasoning').resolveModelReasoning; + expect(resolve('literal', 'copilot', { records: [ + { id: 'exact', supportedReasoningEfforts: ['max'] }, + { id: 'literal', supportedReasoningEfforts: [] }, + ] }).support).toBe('unsupported'); + }); + jest.dontMock('./model-information.naming.generated.json'); + }); + + it.each([ + ['gpt-5.4', 'openai', 'supported'], + ['gpt-5.4-mini', 'openai', 'absent'], + ['gpt-5.5-pro', 'openai', 'absent'], + ['gpt-5.6-sol', 'openai', 'absent'], + ['claude-opus-4-6', 'anthropic', 'supported'], + ['claude-opus-4-7', 'anthropic', 'supported'], + ['claude-opus-4-8', 'anthropic', 'supported'], + ['claude-fable-5-1', 'anthropic', 'supported'], + ['claude-mythos-5-1', 'anthropic', 'supported'], + ['claude-mythos-preview', 'anthropic', 'supported'], + ['claude-haiku-5-5', 'anthropic', 'absent'], + ['gpt-5.4', 'copilot', 'absent'], + ])('uses only reviewed active evidence for specialized %s on %s', (model, provider, support) => { + const decision = resolveModelReasoning(model, provider, { records: [] }); + expect(decision.support).toBe(support); + expect(decision.mode).toBe('unknown'); + expect(decision).not.toHaveProperty('default'); + if (provider === 'anthropic') expect(decision.supportedEfforts).not.toContain('xhigh'); + }); + + it('does not apply native maintained evidence to custom deployments or targets', () => { + expect(resolveModelReasoning('gpt-5.4', 'openai', { + records: [], scope: { deployment: 'custom' }, + }).support).toBe('absent'); + const pin = resolveModelReasoning('gpt-5.4', 'openai', { records: [] }); + expect(getRequestReasoning('gpt-5.4', 'openai', {}, { awfReasoning: pin }, { + targetHost: 'custom.example', + }).support).toBe('absent'); + expect(getRequestReasoning('gpt-5.4', 'openai', {}, {}, { + targetHost: 'custom.example', + }).support).toBe('absent'); + expect(getRequestReasoning('gpt-5.4', 'openai', {}, {}, { + targetHost: 'api.openai.com', targetScheme: 'http', + }).support).toBe('absent'); + }); + + it('pins direct decisions and candidate pools while refresh affects subsequent requests', () => { + replaceRuntimeModels('copilot', [{ id: 'exact-test', supportedReasoningEfforts: ['low'] }]); + const capture = captureRuntimePricing(); + const req = {}; + const pinned = getRequestReasoning('exact-test', 'copilot', capture, req); + const normalized = normalizeModel('exact-test', capture.copilot[0], 'copilot'); + replaceRuntimeModels('copilot', [{ id: 'exact-test', supportedReasoningEfforts: ['max'] }]); + capture.copilot[0].supportedReasoningEfforts.push('none'); + expect(getRequestReasoning('exact-test', 'copilot', capture, req)).toBe(pinned); + expect(getModelReasoning(normalized, 'copilot')).toEqual(pinned); + expect(getRequestReasoning('exact-test', 'copilot').supportedEfforts).toEqual(['max']); + expect(() => validateReasoningEffort(body('exact-test', 'low'), 'copilot', '/chat/completions', + undefined, { awfReasoning: pinned })).not.toThrow(); + expect(() => validateReasoningEffort(body('other', 'low'), 'copilot', '/chat/completions', + { copilot: [{ id: 'other', supportedReasoningEfforts: [] }] }, { awfReasoning: pinned })).toThrow(); + }); + + it('does not bypass existing policy or eligibility when reasoning is supported', () => { + const model = normalizeModel('exact-test', { + supportedReasoningEfforts: ['max'], supportedEndpoints: ['/responses'], + }, 'copilot'); + const catalogue = { provider: 'copilot', configured: true, discovery: 'complete', models: [model] }; + expect(() => buildRoutingCandidates({ catalogue, policy: { disallowedModels: ['*'] } })) + .toThrow(expect.objectContaining({ code: 'model_policy_violation' })); + const eligibilityRequest = { awfEligibility: { evaluate: () => ({ admitted: false }) } }; + expect(() => buildRoutingCandidates({ catalogue, eligibilityRequest })) + .toThrow(expect.objectContaining({ code: 'no_route' })); + }); +}); diff --git a/containers/api-proxy/reasoning-effort-validation.js b/containers/api-proxy/reasoning-effort-validation.js index d2da84378..4c651e75f 100644 --- a/containers/api-proxy/reasoning-effort-validation.js +++ b/containers/api-proxy/reasoning-effort-validation.js @@ -1,6 +1,6 @@ 'use strict'; -const { findRuntimeModel } = require('./runtime-model-catalog'); +const { getRequestReasoning, assessReasoningEffort } = require('./model-reasoning'); function getReasoningEffort(parsed, url) { let pathname; @@ -22,15 +22,7 @@ function getReasoningEffort(parsed, url) { return null; } -function getSupportedEfforts(model) { - if (Array.isArray(model?.supportedReasoningEfforts)) return model.supportedReasoningEfforts; - const supports = model?.capabilities?.supports; - if (Array.isArray(supports?.reasoning_effort)) return supports.reasoning_effort; - if (supports?.reasoningEffort === false) return []; - return null; -} - -function validateReasoningEffort(body, provider, url, runtimeCatalog) { +function validateReasoningEffort(body, provider, url, runtimeCatalog, req, options) { let parsed; try { parsed = JSON.parse(body.toString('utf8')); @@ -40,10 +32,10 @@ function validateReasoningEffort(body, provider, url, runtimeCatalog) { if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed) || typeof parsed.model !== 'string') return; const requested = getReasoningEffort(parsed, url); - if (!requested || typeof requested.value !== 'string') return; - const model = findRuntimeModel(provider, parsed.model, runtimeCatalog); - const supported = getSupportedEfforts(model); - if (!supported || supported.includes(requested.value)) return; + if (!requested || (requested.value !== undefined && typeof requested.value !== 'string')) return; + const decision = getRequestReasoning(parsed.model, provider, runtimeCatalog, req, options); + if (assessReasoningEffort(decision, requested.value).admitted) return; + const supported = decision.supportedEfforts; const error = new Error( `${requested.field} ${JSON.stringify(requested.value)} is not supported by model ${parsed.model}; ` + diff --git a/containers/api-proxy/reasoning-effort-validation.test.js b/containers/api-proxy/reasoning-effort-validation.test.js index f13d282c9..a8ac34af1 100644 --- a/containers/api-proxy/reasoning-effort-validation.test.js +++ b/containers/api-proxy/reasoning-effort-validation.test.js @@ -53,4 +53,53 @@ describe('validateReasoningEffort', () => { '/v1/chat/completions', )).not.toThrow(); }); + + it.each([ + ['/v1/chat/completions/?trace=1', 'reasoning_effort'], + ['/v1/responses/', 'reasoning.effort'], + ['/v1/messages?trace=1', 'output_config.effort'], + ])('preserves omitted and non-string field semantics on %s', (url, field) => { + const catalog = { copilot: [{ id: 'exact-test', supportedReasoningEfforts: ['none', 'max'] }] }; + for (const value of [undefined, null, 3, {}, 'none', 'max']) { + const parsed = { model: 'exact-test' }; + if (field === 'reasoning_effort') parsed.reasoning_effort = value; + else { + const [parent, child] = field.split('.'); + parsed[parent] = { [child]: value }; + } + const body = Buffer.from(JSON.stringify(parsed)); + const original = Buffer.from(body); + expect(() => validateReasoningEffort(body, 'copilot', url, catalog)).not.toThrow(); + expect(body).toEqual(original); + } + }); + + it.each([ + ['/chat/completions', { reasoning_effort: 'future' }, 'reasoning_effort'], + ['/responses', { reasoning: { effort: 'future' } }, 'reasoning.effort'], + ['/messages', { output_config: { effort: 'future' } }, 'output_config.effort'], + ])('rejects unsupported future efforts with the unchanged error envelope on %s', (url, fields, field) => { + expect(() => validateReasoningEffort(Buffer.from(JSON.stringify({ model: 'exact-test', ...fields })), + 'copilot', url, { copilot: [{ id: 'exact-test', supportedReasoningEfforts: [] }] })) + .toThrow(expect.objectContaining({ + statusCode: 400, type: 'invalid_request_error', code: 'unsupported_reasoning_effort', + message: `${field} "future" is not supported by model exact-test; supported values: []`, + })); + }); + + it('uses active maintained native evidence but still passes genuinely unknown support through', () => { + expect(() => validateReasoningEffort(Buffer.from(JSON.stringify({ + model: 'gpt-5.4', reasoning_effort: 'max', + })), 'openai', '/chat/completions', {})) + .toThrow(expect.objectContaining({ code: 'unsupported_reasoning_effort' })); + expect(() => validateReasoningEffort(Buffer.from(JSON.stringify({ + model: 'gpt-5.4-mini', reasoning_effort: 'future', + })), 'openai', '/chat/completions', {})).not.toThrow(); + }); + + it.each(['', '?effort=high', '/opaque', '../opaque'])('preserves opaque model pass-through: %s', model => { + expect(() => validateReasoningEffort(Buffer.from(JSON.stringify({ + model, reasoning_effort: 'future', + })), 'openai', '/chat/completions', {})).not.toThrow(); + }); }); diff --git a/containers/api-proxy/routing-candidates.js b/containers/api-proxy/routing-candidates.js index 1c40eeae0..c9e7d0a69 100644 --- a/containers/api-proxy/routing-candidates.js +++ b/containers/api-proxy/routing-candidates.js @@ -5,13 +5,13 @@ const { getRetiredModelBlockState } = require('./guards/retired-model-guard'); const { stripRedundantProviderPrefix } = require('./model-utils'); const { createRoutingError } = require('./routing-errors'); const { isModelEligible } = require('./model-eligibility'); +const { getModelReasoning, pinModelReasoning, assessReasoningEffort } = require('./model-reasoning'); const PROVIDERS = Object.freeze({ copilot: Object.freeze({ canonical: 'github-copilot', alias: 'copilot' }), openai: Object.freeze({ canonical: 'openai', alias: 'openai' }), anthropic: Object.freeze({ canonical: 'anthropic', alias: 'anthropic' }), }); -const EFFORTS = new Set(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']); function normalizePolicyList(value, name) { if (value === undefined || value === null) return null; @@ -30,15 +30,6 @@ function normalizePolicyList(value, name) { }); } -// Unknown live efforts cannot be represented by this version of the contract. -function normalizeEfforts(value) { - const efforts = []; - for (const effort of value) { - if (EFFORTS.has(effort) && !efforts.includes(effort)) efforts.push(effort); - } - return efforts; -} - function protocolFor(provider, effort, protocols) { if (provider === 'anthropic') return 'messages'; if (effort === undefined) return protocols.includes('chat-completions') ? 'chat-completions' : null; @@ -50,10 +41,11 @@ function protocolFor(provider, effort, protocols) { function getModelRoutingChoices(providerModel, provider) { if (provider === 'copilot' && providerModel.modelPickerEnabled === false) return []; - if (!Array.isArray(providerModel.efforts) || !Array.isArray(providerModel.protocols)) return []; - const efforts = normalizeEfforts(providerModel.efforts); - if (providerModel.efforts.length > 0 && efforts.length === 0) return []; - return (efforts.length === 0 ? [undefined] : efforts).flatMap(effort => { + if (!Array.isArray(providerModel.protocols)) return []; + const decision = getModelReasoning(providerModel, provider); + const efforts = decision.support === 'unsupported' ? [undefined] : decision.selectableEfforts; + return efforts.flatMap(effort => { + if (!assessReasoningEffort(decision, effort, { automatic: true }).admitted) return []; const protocol = protocolFor(provider, effort, providerModel.protocols); return protocol && providerModel.protocols.includes(protocol) ? [{ effort, protocol }] : []; }); @@ -151,14 +143,14 @@ function buildRoutingCandidates({ catalogue, policy = {}, candidateModels, eligi const contextWindow = Number.isInteger(pair.providerModel.contextWindow) && pair.providerModel.contextWindow > 0 ? pair.providerModel.contextWindow : undefined; - byId[id] = Object.freeze({ + byId[id] = pinModelReasoning(Object.freeze({ choice, provider: pair.provider, wireModel: pair.providerModel.id, ...(pair.effort === undefined ? {} : { effort: pair.effort }), ...(contextWindow === undefined ? {} : { contextWindow }), protocol: pair.protocol, - }); + }), getModelReasoning(pair.providerModel, pair.provider)); return choice; }); diff --git a/containers/api-proxy/routing-catalogue.js b/containers/api-proxy/routing-catalogue.js index dc225eecc..76470a9fe 100644 --- a/containers/api-proxy/routing-catalogue.js +++ b/containers/api-proxy/routing-catalogue.js @@ -2,11 +2,7 @@ const { createRoutingError } = require('./routing-errors'); const { lookupModelEndpoints, lookupModelRoutingMetadata } = require('./model-api-mapping'); - -const NATIVE_PROVIDER_HOSTS = Object.freeze({ - openai: 'api.openai.com', - anthropic: 'api.anthropic.com', -}); +const { resolveModelReasoning, pinModelReasoning, NATIVE_PROVIDER_HOSTS } = require('./model-reasoning'); function isNativeAdapter(adapter, provider) { if ( @@ -33,23 +29,14 @@ function freezeModel(model) { return Object.freeze(model); } -// Copilot /models advertises efforts as capabilities.supports.reasoning_effort -// and omits that key for models without effort control. -function normalizeEfforts(metadata, mapped, provider) { - if (Array.isArray(metadata?.supportedReasoningEfforts)) return [...metadata.supportedReasoningEfforts]; - const supports = metadata?.capabilities?.supports; - if (!supports || typeof supports !== 'object' || Array.isArray(supports)) return mapped?.reasoningEfforts; - if (Array.isArray(supports.reasoning_effort)) return [...supports.reasoning_effort]; - if (supports.reasoningEffort === false) return []; - if (Object.hasOwn(supports, 'reasoning_effort') || Object.hasOwn(supports, 'reasoningEffort')) return undefined; - return provider === 'copilot' ? [] : mapped?.reasoningEfforts; -} - -function normalizeModel(id, metadata, provider) { +function normalizeModel(id, metadata, provider, scope, records) { const mapped = lookupModelRoutingMetadata(id, provider); const endpointMapping = lookupModelEndpoints(id, provider); const limits = metadata?.capabilities?.limits; - const efforts = normalizeEfforts(metadata, mapped, provider); + const reasoning = resolveModelReasoning(id, provider, { + records: records || (metadata ? [{ ...metadata, id: metadata.id || id }] : []), scope, + }); + const efforts = ['absent', 'unknown'].includes(reasoning.support) ? undefined : reasoning.supportedEfforts; const runtimeContextWindow = limits?.max_context_window_tokens; const contextWindow = Number.isInteger(runtimeContextWindow) && runtimeContextWindow > 0 ? runtimeContextWindow @@ -72,7 +59,7 @@ function normalizeModel(id, metadata, provider) { ? new Set(['responses', 'chat-completions', 'messages']) : new Set(['responses', 'chat-completions']); - return freezeModel({ + return pinModelReasoning(freezeModel({ id, ...(efforts === undefined ? {} : { efforts }), ...(Number.isInteger(contextWindow) && contextWindow > 0 ? { contextWindow } : {}), @@ -80,7 +67,7 @@ function normalizeModel(id, metadata, provider) { ...(typeof metadata?.modelPickerEnabled === 'boolean' ? { modelPickerEnabled: metadata.modelPickerEnabled } : {}), - }); + }), reasoning); } function createRoutingCatalogue({ getAdapter, getCopilotAdapter, getDiscoveredModels, getRuntimeModels }) { @@ -97,7 +84,7 @@ function createRoutingCatalogue({ getAdapter, getCopilotAdapter, getDiscoveredMo } return Object.freeze({ - async getSnapshot({ signal, provider = 'copilot' } = {}) { + async getSnapshot({ signal, provider = 'copilot', scope } = {}) { if (signal?.aborted) { throw createRoutingError('routing_cancelled', 'Model routing was cancelled'); } @@ -113,10 +100,9 @@ function createRoutingCatalogue({ getAdapter, getCopilotAdapter, getDiscoveredMo }); } - const metadataById = new Map( - (getRuntimeModels(provider) || []).map(model => [model.id.toLowerCase(), model]), - ); - const models = discovered.map(id => normalizeModel(id, metadataById.get(id.toLowerCase()), provider)); + const records = getRuntimeModels(provider) || []; + const metadataById = new Map(records.map(model => [model.id.toLowerCase(), model])); + const models = discovered.map(id => normalizeModel(id, metadataById.get(id.toLowerCase()), provider, scope, records)); return Object.freeze({ provider, configured: true, diff --git a/containers/api-proxy/routing-controller.js b/containers/api-proxy/routing-controller.js index b0b03a944..c2e246dd9 100644 --- a/containers/api-proxy/routing-controller.js +++ b/containers/api-proxy/routing-controller.js @@ -3,6 +3,7 @@ const { createHash } = require('crypto'); const { buildRoutingCandidates } = require('./routing-candidates'); const { pinRequestEligibility, proxyEligibilityStore } = require('./model-eligibility'); +const { getModelReasoning } = require('./model-reasoning'); const { extractClassifierOutput, preflightClassifierRequest } = require('./routing-classifier'); const { assertPlanningRequestSize, @@ -158,7 +159,7 @@ function createRoutingController(dependencies) { validateCapabilities(rawCapabilities, config.objective, routerIdentity); const snapshot = await runPhase(({ signal: phaseSignal }) => - catalogue.getSnapshot({ signal: phaseSignal, provider: config.provider || 'copilot' })); + catalogue.getSnapshot({ signal: phaseSignal, provider: config.provider || 'copilot', scope: eligibilityRequest.awfEligibilityScope })); const pool = buildRoutingCandidates({ catalogue: snapshot, policy, candidateModels: config.candidateModels, eligibilityRequest }); catalogueOverlap = countCatalogueOverlap(rawCapabilities, pool.choices); @@ -215,6 +216,7 @@ function createRoutingController(dependencies) { provider: mapping.provider, awfEligibility: eligibilityRequest.awfEligibility, awfEligibilityScope: eligibilityRequest.awfEligibilityScope, + awfReasoning: getModelReasoning(mapping, mapping.provider), }, { signal: phaseSignal, timeoutMs }), { signal, diff --git a/containers/api-proxy/routing-provider-executor.js b/containers/api-proxy/routing-provider-executor.js index 41e6bf06a..5006f9772 100644 --- a/containers/api-proxy/routing-provider-executor.js +++ b/containers/api-proxy/routing-provider-executor.js @@ -116,6 +116,7 @@ function createRoutingProviderExecutor({ req.awfRequestContext = Object.freeze({ purpose: 'routing_classification', signal }); req.awfEligibility = request.awfEligibility; req.awfEligibilityScope = request.awfEligibilityScope; + req.awfReasoning = request.awfReasoning; const res = new BufferedResponse(MAX_CLASSIFIER_RESPONSE_BYTES); return new Promise((resolve, reject) => { let settled = false; diff --git a/containers/api-proxy/runtime-model-catalog.js b/containers/api-proxy/runtime-model-catalog.js index cb5652d4a..9d6d5da4b 100644 --- a/containers/api-proxy/runtime-model-catalog.js +++ b/containers/api-proxy/runtime-model-catalog.js @@ -136,12 +136,13 @@ function parseProviderModelMetadata(provider, json, options = {}) { ...(typeof displayName === 'string' && displayName.length > 0 ? { displayName } : {}), source: 'provider', observedAt, + ...(options.scope ? { scope: { ...options.scope, provider } } : {}), ...(options.apiVersion ? { apiVersion: options.apiVersion } : {}), ...(entry.capabilities && typeof entry.capabilities === 'object' ? { capabilities: entry.capabilities } : {}), - ...(Array.isArray(entry.supportedReasoningEfforts) - ? { supportedReasoningEfforts: [...entry.supportedReasoningEfforts] } + ...(Object.hasOwn(entry, 'supportedReasoningEfforts') + ? { supportedReasoningEfforts: structuredClone(entry.supportedReasoningEfforts) } : {}), ...(Array.isArray(entry.supported_endpoints) ? { supportedEndpoints: [...entry.supported_endpoints] } diff --git a/containers/api-proxy/upstream-http.js b/containers/api-proxy/upstream-http.js index 1b8895803..1d0ad6c06 100644 --- a/containers/api-proxy/upstream-http.js +++ b/containers/api-proxy/upstream-http.js @@ -205,7 +205,7 @@ function createSendUpstreamRequest({ if (cancellation.cancelled) return; try { - validateReasoningEffort(body, provider, upstreamPath, req.awfRuntimePricing); + validateReasoningEffort(body, provider, upstreamPath, req.awfRuntimePricing, req, { targetHost, targetScheme }); } catch (err) { if (err.code !== 'unsupported_reasoning_effort') throw err; if (res.headersSent) return; diff --git a/docs/adr/0004-model-information-management.md b/docs/adr/0004-model-information-management.md index 13de9d0c0..29c9f44f3 100644 --- a/docs/adr/0004-model-information-management.md +++ b/docs/adr/0004-model-information-management.md @@ -1736,6 +1736,70 @@ Unify routing, validation, and reflection on resolved reasoning data. Add the feature compatibility model and connect translator rejection to declared requirements for each directed protocol pair and translator revision. +#### Bounded exact-model reasoning slice + +`shared/model-information/reasoning.{js,d.ts}` supplies an internal, read-only +decision for exact provider-qualified identities and captured scoped facts. +Direct effort validation and routing use the same proxy adapter and decision. +This does not complete Gate 6, activate staged targets, or add a public export +or reflection endpoint. Accounting-family membership is opaque to reasoning. + +The characterized precedence is the top-level runtime effort array, then the +runtime `capabilities.supports.reasoning_effort` array, then the explicit +`reasoningEffort: false` flag. Copilot's valid `supports` object with no effort +key is existing routing evidence that effort control is forbidden; a missing +supports object is unknown. Explicit malformed effort fields remain unknown +and do not activate lower-authority maintained evidence. Provider facts outrank +the existing maintained native-API routing mappings. Those mappings apply only +to their reviewed patterns on the matching provider/channel without a custom +deployment; they never establish support on another backend. Imported or +target-only records are not active evidence. Legacy unscoped runtime observations +are confined to their provider's default API channel and deployment, never +re-scoped to the requesting deployment. Native selection pins are not adopted +on custom targets. Same-authority contradictions +produce an unknown decision, with structured reason codes. Non-string elements +in an otherwise usable effort array are ignored with a reason, preserving the +router's existing mixed-array behavior. + +Intentional direct-validation corrections are regression-backed: it now rejects +efforts outside active maintained native evidence, and rejects explicit efforts +when Copilot advertises a valid supports object without effort control, as +routing already did. Exact/scoped identity resolution replaces the broad +runtime pricing normalizer for this decision; dated, dotted or same-slug IDs +do not borrow support without a reviewed alias. Provider-native IDs are not +prefix-stripped again after the request adapter resolves them. + +Genuinely absent, unknown, malformed or unverified conditional support retains +the direct unknown-support pass-through policy. Automatic routing requires +known model support and router-understood values. Supported future strings and +their provenance survive observations and decisions but cannot become automatic +choices. Explicit unsupported requests are still rejected, including `none`; +`none` is not omitted effort. Chat Completions, Responses and Messages retain +their existing fields, non-string handling and `unsupported_reasoning_effort` +400 error contract. No consumer strips, substitutes or inserts an effort. + +Required/optional modes and defaults are exposed only when evidenced. Current +active maintained mappings do not reliably supply them, so they remain unknown +and no default is inserted. In particular, the staged specialized GPT, Haiku, +and Opus/Fable/Mythos `xhigh` refinements above remain inactive; active Opus 4.6, +4.7 and 4.8 mappings still share their existing effort list. + +Decisions copy and deeply freeze their facts. Routing snapshots and classifier +requests retain their selected reasoning decision; direct requests cache +decisions against their accounting capture. Refresh affects later decisions, +not a selected in-flight request. Existing eligibility re-evaluation, model +policy and accounting captures remain independent gates. Sanitized reusable +reasons are internal handoff data for later additive Gate 7 consumers. + +The standard compiler projects the module and declarations into the proxy +`catalogue-contract` and host `model-information-contract` layouts. Use +`node scripts/model-information/compile.cjs --contracts-only` to copy just this +contract without regenerating family/source assets; add `--check` to verify it. +The build copies the reasoning declaration and its identity/scope type +dependencies after TypeScript emits JavaScript, preserving the typed contract +instead of inferred JavaScript declarations. Provider-free off-tree tests +exercise both built and proxy module layouts and type-check their declarations. + ### Gate 7: Exports Extend `/reflect` additively, add versioned persisted snapshots, CLI diff --git a/package.json b/package.json index c85f19df3..a46cb9cda 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "awf": "./dist/cli.js" }, "scripts": { - "build": "tsc", + "build": "tsc && node scripts/model-information/compile.cjs --reasoning-types-only", "dev": "tsc --watch", "type-check": "tsc --noEmit -p tsconfig.check.json", "test": "npm run build && jest", diff --git a/scripts/model-information/compile.cjs b/scripts/model-information/compile.cjs index 7e0fc3917..bd1624467 100644 --- a/scripts/model-information/compile.cjs +++ b/scripts/model-information/compile.cjs @@ -38,6 +38,25 @@ const latestTimestamp = provenances => provenances .map(item => new Date(item.at).toISOString()).sort().at(-1); function compile() { + if (process.argv.includes('--contracts-only') || process.argv.includes('--reasoning-types-only')) { + const typesOnly = process.argv.includes('--reasoning-types-only'); + const directories = typesOnly ? ['dist/model-information-contract'] + : ['containers/api-proxy/catalogue-contract', 'src/model-information-contract']; + const files = typesOnly ? ['identity.d.ts', 'resolution.d.ts', 'reasoning.d.ts'] + : ['reasoning.js', 'reasoning.d.ts']; + for (const directory of directories) { + for (const file of files) { + const content = fs.readFileSync(path.join(root, 'shared/model-information', file), 'utf8'); + const filename = path.join(root, directory, file); + if (process.argv.includes('--check')) { + if (!fs.existsSync(filename) || fs.readFileSync(filename, 'utf8') !== content) { + throw new Error(`${directory}/${file}: stale reasoning contract`); + } + } else fs.writeFileSync(filename, content); + } + } + return; + } const files = fs.readdirSync(sources).filter(file => file.endsWith('.json')).sort(); const importedFile = 'shared/model-information/imported/legacy-models-dev.snapshot.v1.json'; const expectedImport = importLegacySnapshot( @@ -502,6 +521,7 @@ function compile() { errors.push(...validate('resolvedExport', JSON.parse(output['shared/model-information/catalog.generated.json']))); errors.push(...validate('resolvedExport', JSON.parse(output['shared/model-information/target.generated.json']))); for (const file of ['contracts.js', 'contracts.d.ts', 'identity.js', 'identity.d.ts', 'resolution.js', 'resolution.d.ts', + 'reasoning.js', 'reasoning.d.ts', 'eligibility.js', 'eligibility.d.ts', 'harness-observation.js', 'harness-observation.d.ts', 'pricing-resolution.js', 'pricing-resolution.d.ts', 'exact-pricing.js', 'schema.v1.json', 'publication.v1.schema.json', 'publication-contract.cjs', 'publication.cjs']) { @@ -509,6 +529,7 @@ function compile() { fs.readFileSync(path.join(root, 'shared/model-information', file), 'utf8'); } for (const file of ['identity.js', 'identity.d.ts', 'resolution.js', 'resolution.d.ts', 'eligibility.js', 'eligibility.d.ts', + 'reasoning.js', 'reasoning.d.ts', 'harness-observation.js', 'harness-observation.d.ts', 'pricing-resolution.js', 'pricing-resolution.d.ts', 'exact-pricing.js']) { output[`src/model-information-contract/${file}`] = diff --git a/shared/model-information/reasoning.d.ts b/shared/model-information/reasoning.d.ts new file mode 100644 index 000000000..51f6ecd8e --- /dev/null +++ b/shared/model-information/reasoning.d.ts @@ -0,0 +1,44 @@ +import { ModelIdentity } from './identity'; +import { ModelScope } from './resolution'; + +export type ReasoningSupport = 'absent' | 'unknown' | 'supported' | 'unsupported'; +export type ReasoningMode = 'optional' | 'required' | 'forbidden' | 'unknown'; +export interface ReasoningFact { + identity: ModelIdentity; + scope: ModelScope; + active: boolean; + authority: 'provider' | 'maintained'; + support: Exclude | 'conditional'; + rawEfforts?: readonly string[]; + mode?: ReasoningMode; + default?: string; + provenance?: Record; +} +export interface ReasoningInput { + identity: ModelIdentity | null; + scope: ModelScope; + facts?: readonly ReasoningFact[]; +} +export interface ReasoningReason { + readonly code: string; +} +export interface ReasoningDecision { + readonly identity: Readonly> | null; + readonly scope: Readonly; + readonly support: ReasoningSupport; + readonly mode: ReasoningMode; + readonly supportedEfforts: readonly string[]; + readonly selectableEfforts: readonly string[]; + readonly default?: string; + readonly observations: readonly Readonly<{ + authority: string; + rawEfforts: readonly string[]; + provenance: Readonly>; + selected: boolean; + }>[]; + readonly reasons: readonly ReasoningReason[]; +} +export function resolveReasoning(input: ReasoningInput): ReasoningDecision; +export function assessReasoningEffort( + decision: ReasoningDecision, effort: string | undefined, options?: { automatic?: boolean }, +): Readonly<{ admitted: boolean; reasons: readonly ReasoningReason[] }>; diff --git a/shared/model-information/reasoning.js b/shared/model-information/reasoning.js new file mode 100644 index 000000000..c0bdacce8 --- /dev/null +++ b/shared/model-information/reasoning.js @@ -0,0 +1,130 @@ +'use strict'; + +const { isDeepStrictEqual } = require('node:util'); + +const UNDERSTOOD_EFFORTS = new Set(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']); +const AUTHORITIES = { provider: 2, maintained: 1 }; + +function freeze(value) { + if (value && typeof value === 'object') { + for (const child of Object.values(value)) freeze(child); + Object.freeze(value); + } + return value; +} + +function provenance(value = {}) { + if (!value || typeof value !== 'object') return {}; + return Object.fromEntries(['authority', 'source', 'revision', 'at', 'apiVersion', 'field'] + .filter(key => typeof value[key] === 'string') + .map(key => [key, value[key].replace(/\p{Cc}/gu, '').slice(0, 512)])); +} + +function sameScope(left, right) { + return left?.provider === right.provider && left?.channel === right.channel && + left?.deployment === right.deployment; +} + +// Inputs are exact, captured facts, not names, family rules or live stores. +function resolveReasoning({ identity, scope, facts = [] }) { + const reasons = []; + const applicable = []; + for (const fact of facts) { + if (!fact || typeof fact !== 'object') { + reasons.push({ code: 'reasoning_malformed_fact' }); + continue; + } + let code; + if (!identity || identity.provider !== scope.provider || + fact.identity?.key !== identity.key || fact.identity?.provider !== identity.provider) { + code = 'reasoning_identity_mismatch'; + } else if (!sameScope(fact.scope, scope)) code = 'reasoning_scope_mismatch'; + else if (fact.active !== true) code = 'reasoning_inactive_fact'; + else if (!Object.hasOwn(AUTHORITIES, fact.authority)) code = 'reasoning_unreviewed_authority'; + if (code) reasons.push({ code }); + else applicable.push(fact); + } + const priority = Math.max(0, ...applicable.map(fact => AUTHORITIES[fact.authority])); + const selected = applicable.filter(fact => AUTHORITIES[fact.authority] === priority); + const observations = applicable.map(fact => ({ + authority: fact.authority, + rawEfforts: Array.isArray(fact.rawEfforts) ? fact.rawEfforts.filter(value => typeof value === 'string') : [], + provenance: provenance(fact.provenance), + selected: selected.includes(fact), + })); + let support = selected.length ? 'unknown' : 'absent'; + let mode = 'unknown'; + let supportedEfforts = []; + let defaultEffort; + if (selected.length) { + const fact = selected[0]; + const signature = value => ({ + support: value.support, rawEfforts: value.rawEfforts, mode: value.mode, default: value.default, + }); + const conflicting = selected.some(value => !isDeepStrictEqual(signature(value), signature(fact))); + const rawEfforts = Array.isArray(fact.rawEfforts) + ? fact.rawEfforts.filter(value => typeof value === 'string' && value.length > 0) : []; + const effortsValid = Array.isArray(fact.rawEfforts) && + (fact.rawEfforts.length === 0 || rawEfforts.length > 0); + if (effortsValid && rawEfforts.length !== fact.rawEfforts.length) { + reasons.push({ code: 'reasoning_malformed_effort_ignored' }); + } + const malformed = !['supported', 'unsupported', 'unknown', 'conditional'].includes(fact.support) || + (fact.rawEfforts !== undefined && !effortsValid) || + (fact.support === 'supported' && (!effortsValid || fact.rawEfforts.length === 0)) || + (fact.support === 'unsupported' && fact.rawEfforts?.length > 0) || + (fact.mode !== undefined && !['optional', 'required', 'forbidden', 'unknown'].includes(fact.mode)) || + (fact.mode === 'forbidden' && fact.support === 'supported') || + (fact.mode === 'required' && fact.support === 'unsupported'); + if (conflicting || malformed) { + reasons.push({ code: conflicting ? 'reasoning_conflicting_facts' : 'reasoning_malformed_fact' }); + } else { + support = fact.support === 'conditional' ? 'unknown' : fact.support; + mode = fact.mode || 'unknown'; + if (support === 'supported') supportedEfforts = [...new Set(rawEfforts)]; + if (fact.default !== undefined) { + if (typeof fact.default === 'string' && supportedEfforts.includes(fact.default) && mode !== 'forbidden') { + defaultEffort = fact.default; + } else reasons.push({ code: 'reasoning_invalid_default' }); + } + if (fact.support === 'conditional') reasons.push({ code: 'reasoning_condition_unverified' }); + } + } + reasons.push({ code: `reasoning_support_${support}` }); + if (supportedEfforts.some(effort => !UNDERSTOOD_EFFORTS.has(effort))) { + reasons.push({ code: 'reasoning_future_effort_not_selectable' }); + } + return freeze({ + identity: identity ? { key: identity.key, provider: identity.provider, rawId: identity.rawId } : null, + scope: { ...scope }, support, mode, supportedEfforts, + selectableEfforts: supportedEfforts.filter(effort => UNDERSTOOD_EFFORTS.has(effort)), + ...(defaultEffort === undefined ? {} : { default: defaultEffort }), + observations, reasons, + }); +} + +function assessReasoningEffort(decision, effort, { automatic = false } = {}) { + let code; + if (effort === undefined) { + if (decision.mode === 'required') code = 'reasoning_effort_required'; + else if (automatic && decision.support !== 'unsupported' && + !(decision.support === 'supported' && decision.mode === 'optional')) { + code = 'reasoning_automatic_requires_known_support'; + } + } else if (decision.mode === 'forbidden' || decision.support === 'unsupported') { + code = 'reasoning_effort_forbidden'; + } else if (decision.support === 'supported' && !decision.supportedEfforts.includes(effort)) { + code = 'reasoning_effort_unsupported'; + } else if (automatic && decision.support !== 'supported') { + code = 'reasoning_automatic_requires_known_support'; + } else if (automatic && !decision.selectableEfforts.includes(effort)) { + code = 'reasoning_future_effort_not_selectable'; + } + return freeze({ + admitted: !code, + reasons: [{ code: code || (['unknown', 'absent'].includes(decision.support) + ? 'reasoning_direct_unknown_passthrough' : 'reasoning_effort_accepted') }], + }); +} + +module.exports = { resolveReasoning, assessReasoningEffort }; diff --git a/src/model-information-contract/reasoning.d.ts b/src/model-information-contract/reasoning.d.ts new file mode 100644 index 000000000..51f6ecd8e --- /dev/null +++ b/src/model-information-contract/reasoning.d.ts @@ -0,0 +1,44 @@ +import { ModelIdentity } from './identity'; +import { ModelScope } from './resolution'; + +export type ReasoningSupport = 'absent' | 'unknown' | 'supported' | 'unsupported'; +export type ReasoningMode = 'optional' | 'required' | 'forbidden' | 'unknown'; +export interface ReasoningFact { + identity: ModelIdentity; + scope: ModelScope; + active: boolean; + authority: 'provider' | 'maintained'; + support: Exclude | 'conditional'; + rawEfforts?: readonly string[]; + mode?: ReasoningMode; + default?: string; + provenance?: Record; +} +export interface ReasoningInput { + identity: ModelIdentity | null; + scope: ModelScope; + facts?: readonly ReasoningFact[]; +} +export interface ReasoningReason { + readonly code: string; +} +export interface ReasoningDecision { + readonly identity: Readonly> | null; + readonly scope: Readonly; + readonly support: ReasoningSupport; + readonly mode: ReasoningMode; + readonly supportedEfforts: readonly string[]; + readonly selectableEfforts: readonly string[]; + readonly default?: string; + readonly observations: readonly Readonly<{ + authority: string; + rawEfforts: readonly string[]; + provenance: Readonly>; + selected: boolean; + }>[]; + readonly reasons: readonly ReasoningReason[]; +} +export function resolveReasoning(input: ReasoningInput): ReasoningDecision; +export function assessReasoningEffort( + decision: ReasoningDecision, effort: string | undefined, options?: { automatic?: boolean }, +): Readonly<{ admitted: boolean; reasons: readonly ReasoningReason[] }>; diff --git a/src/model-information-contract/reasoning.js b/src/model-information-contract/reasoning.js new file mode 100644 index 000000000..c0bdacce8 --- /dev/null +++ b/src/model-information-contract/reasoning.js @@ -0,0 +1,130 @@ +'use strict'; + +const { isDeepStrictEqual } = require('node:util'); + +const UNDERSTOOD_EFFORTS = new Set(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']); +const AUTHORITIES = { provider: 2, maintained: 1 }; + +function freeze(value) { + if (value && typeof value === 'object') { + for (const child of Object.values(value)) freeze(child); + Object.freeze(value); + } + return value; +} + +function provenance(value = {}) { + if (!value || typeof value !== 'object') return {}; + return Object.fromEntries(['authority', 'source', 'revision', 'at', 'apiVersion', 'field'] + .filter(key => typeof value[key] === 'string') + .map(key => [key, value[key].replace(/\p{Cc}/gu, '').slice(0, 512)])); +} + +function sameScope(left, right) { + return left?.provider === right.provider && left?.channel === right.channel && + left?.deployment === right.deployment; +} + +// Inputs are exact, captured facts, not names, family rules or live stores. +function resolveReasoning({ identity, scope, facts = [] }) { + const reasons = []; + const applicable = []; + for (const fact of facts) { + if (!fact || typeof fact !== 'object') { + reasons.push({ code: 'reasoning_malformed_fact' }); + continue; + } + let code; + if (!identity || identity.provider !== scope.provider || + fact.identity?.key !== identity.key || fact.identity?.provider !== identity.provider) { + code = 'reasoning_identity_mismatch'; + } else if (!sameScope(fact.scope, scope)) code = 'reasoning_scope_mismatch'; + else if (fact.active !== true) code = 'reasoning_inactive_fact'; + else if (!Object.hasOwn(AUTHORITIES, fact.authority)) code = 'reasoning_unreviewed_authority'; + if (code) reasons.push({ code }); + else applicable.push(fact); + } + const priority = Math.max(0, ...applicable.map(fact => AUTHORITIES[fact.authority])); + const selected = applicable.filter(fact => AUTHORITIES[fact.authority] === priority); + const observations = applicable.map(fact => ({ + authority: fact.authority, + rawEfforts: Array.isArray(fact.rawEfforts) ? fact.rawEfforts.filter(value => typeof value === 'string') : [], + provenance: provenance(fact.provenance), + selected: selected.includes(fact), + })); + let support = selected.length ? 'unknown' : 'absent'; + let mode = 'unknown'; + let supportedEfforts = []; + let defaultEffort; + if (selected.length) { + const fact = selected[0]; + const signature = value => ({ + support: value.support, rawEfforts: value.rawEfforts, mode: value.mode, default: value.default, + }); + const conflicting = selected.some(value => !isDeepStrictEqual(signature(value), signature(fact))); + const rawEfforts = Array.isArray(fact.rawEfforts) + ? fact.rawEfforts.filter(value => typeof value === 'string' && value.length > 0) : []; + const effortsValid = Array.isArray(fact.rawEfforts) && + (fact.rawEfforts.length === 0 || rawEfforts.length > 0); + if (effortsValid && rawEfforts.length !== fact.rawEfforts.length) { + reasons.push({ code: 'reasoning_malformed_effort_ignored' }); + } + const malformed = !['supported', 'unsupported', 'unknown', 'conditional'].includes(fact.support) || + (fact.rawEfforts !== undefined && !effortsValid) || + (fact.support === 'supported' && (!effortsValid || fact.rawEfforts.length === 0)) || + (fact.support === 'unsupported' && fact.rawEfforts?.length > 0) || + (fact.mode !== undefined && !['optional', 'required', 'forbidden', 'unknown'].includes(fact.mode)) || + (fact.mode === 'forbidden' && fact.support === 'supported') || + (fact.mode === 'required' && fact.support === 'unsupported'); + if (conflicting || malformed) { + reasons.push({ code: conflicting ? 'reasoning_conflicting_facts' : 'reasoning_malformed_fact' }); + } else { + support = fact.support === 'conditional' ? 'unknown' : fact.support; + mode = fact.mode || 'unknown'; + if (support === 'supported') supportedEfforts = [...new Set(rawEfforts)]; + if (fact.default !== undefined) { + if (typeof fact.default === 'string' && supportedEfforts.includes(fact.default) && mode !== 'forbidden') { + defaultEffort = fact.default; + } else reasons.push({ code: 'reasoning_invalid_default' }); + } + if (fact.support === 'conditional') reasons.push({ code: 'reasoning_condition_unverified' }); + } + } + reasons.push({ code: `reasoning_support_${support}` }); + if (supportedEfforts.some(effort => !UNDERSTOOD_EFFORTS.has(effort))) { + reasons.push({ code: 'reasoning_future_effort_not_selectable' }); + } + return freeze({ + identity: identity ? { key: identity.key, provider: identity.provider, rawId: identity.rawId } : null, + scope: { ...scope }, support, mode, supportedEfforts, + selectableEfforts: supportedEfforts.filter(effort => UNDERSTOOD_EFFORTS.has(effort)), + ...(defaultEffort === undefined ? {} : { default: defaultEffort }), + observations, reasons, + }); +} + +function assessReasoningEffort(decision, effort, { automatic = false } = {}) { + let code; + if (effort === undefined) { + if (decision.mode === 'required') code = 'reasoning_effort_required'; + else if (automatic && decision.support !== 'unsupported' && + !(decision.support === 'supported' && decision.mode === 'optional')) { + code = 'reasoning_automatic_requires_known_support'; + } + } else if (decision.mode === 'forbidden' || decision.support === 'unsupported') { + code = 'reasoning_effort_forbidden'; + } else if (decision.support === 'supported' && !decision.supportedEfforts.includes(effort)) { + code = 'reasoning_effort_unsupported'; + } else if (automatic && decision.support !== 'supported') { + code = 'reasoning_automatic_requires_known_support'; + } else if (automatic && !decision.selectableEfforts.includes(effort)) { + code = 'reasoning_future_effort_not_selectable'; + } + return freeze({ + admitted: !code, + reasons: [{ code: code || (['unknown', 'absent'].includes(decision.support) + ? 'reasoning_direct_unknown_passthrough' : 'reasoning_effort_accepted') }], + }); +} + +module.exports = { resolveReasoning, assessReasoningEffort }; diff --git a/src/model-information-reasoning.test.ts b/src/model-information-reasoning.test.ts new file mode 100644 index 000000000..d6b13a18b --- /dev/null +++ b/src/model-information-reasoning.test.ts @@ -0,0 +1,209 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { execFileSync } from 'node:child_process'; +import { identity } from '../shared/model-information/identity'; +import { + resolveReasoning, assessReasoningEffort, ReasoningFact, +} from '../shared/model-information/reasoning'; + +const scope = { provider: 'copilot', channel: 'copilot-api' }; +const exact = identity('copilot', 'exact'); +const fact = (extra: Partial = {}): ReasoningFact => ({ + identity: exact, scope, active: true, authority: 'provider', + support: 'supported', rawEfforts: ['none', 'low', 'max', 'future-effort'], + provenance: { authority: 'provider', source: 'fixture', at: '2026-11-01T00:00:00Z' }, + ...extra, +}); +const resolve = (...facts: ReasoningFact[]) => resolveReasoning({ identity: exact, scope, facts }); + +describe('exact-model reasoning decisions', () => { + it('distinguishes absence, explicit unknown, unsupported and supported evidence', () => { + expect(resolve().support).toBe('absent'); + expect(resolve(fact({ support: 'unknown', rawEfforts: undefined })).support).toBe('unknown'); + expect(resolve(fact({ support: 'unsupported', rawEfforts: [] })).support).toBe('unsupported'); + const decision = resolve(fact()); + expect(decision.support).toBe('supported'); + expect(decision.mode).toBe('unknown'); + expect(decision.supportedEfforts).toEqual(['none', 'low', 'max', 'future-effort']); + expect(decision.selectableEfforts).toEqual(['none', 'low', 'max']); + expect(decision.observations[0]).toMatchObject({ + rawEfforts: ['none', 'low', 'max', 'future-effort'], + provenance: { source: 'fixture' }, selected: true, + }); + expect(decision.reasons).toContainEqual({ code: 'reasoning_future_effort_not_selectable' }); + }); + + it.each(['none', 'max', 'future-effort'])('accepts exact supported direct value %s without substitution', effort => { + const decision = resolve(fact()); + expect(assessReasoningEffort(decision, effort).admitted).toBe(true); + expect(assessReasoningEffort(decision, effort, { automatic: true }).admitted) + .toBe(effort !== 'future-effort'); + expect(assessReasoningEffort(decision, 'unsupported').admitted).toBe(false); + }); + + it.each(['absent', 'unknown'] as const)('names direct unknown pass-through versus automatic known-support policy: %s', support => { + const decision = support === 'absent' ? resolve() : resolve(fact({ support, rawEfforts: undefined })); + for (const effort of [undefined, 'none', 'max', 'future-effort']) { + expect(assessReasoningEffort(decision, effort)).toEqual({ + admitted: true, reasons: [{ code: 'reasoning_direct_unknown_passthrough' }], + }); + expect(assessReasoningEffort(decision, effort, { automatic: true }).admitted).toBe(false); + } + }); + + it('uses evidenced required, optional, forbidden and default facts without inventing them', () => { + const required = resolve(fact({ mode: 'required', default: 'low' })); + expect(required.default).toBe('low'); + expect(assessReasoningEffort(required, undefined).admitted).toBe(false); + expect(assessReasoningEffort(required, 'low').admitted).toBe(true); + const optional = resolve(fact({ mode: 'optional' })); + expect(assessReasoningEffort(optional, undefined).admitted).toBe(true); + expect(optional).not.toHaveProperty('default'); + const forbidden = resolve(fact({ mode: 'forbidden', support: 'unsupported', rawEfforts: [] })); + expect(assessReasoningEffort(forbidden, undefined, { automatic: true }).admitted).toBe(true); + expect(assessReasoningEffort(forbidden, 'none').admitted).toBe(false); + const invalid = resolve(fact({ default: 'high' })); + expect(invalid).not.toHaveProperty('default'); + expect(invalid.reasons).toContainEqual({ code: 'reasoning_invalid_default' }); + }); + + it('ignores other providers, channels, deployments, staged targets and unreviewed sources', () => { + const ignored = [ + fact({ identity: identity('openai', 'exact') }), + fact({ scope: { ...scope, channel: 'native-api' } }), + fact({ scope: { ...scope, deployment: 'other' } }), + fact({ active: false }), + fact({ authority: 'models.dev' as ReasoningFact['authority'] }), + fact({ identity: identity('copilot', 'exact-mini') }), + ]; + const decision = resolve(...ignored); + expect(decision.support).toBe('absent'); + expect(decision.reasons.map(reason => reason.code)).toEqual(expect.arrayContaining([ + 'reasoning_identity_mismatch', 'reasoning_scope_mismatch', + 'reasoning_inactive_fact', 'reasoning_unreviewed_authority', + ])); + expect(resolve(fact({ identity: { ...exact, family: 'accounting-only' } }))) + .toEqual(resolve(fact())); + }); + + it('prefers provider facts, including unknowns, without lower-authority fallback', () => { + const maintained = fact({ authority: 'maintained', rawEfforts: ['high'] }); + const decision = resolve(maintained, fact({ support: 'unknown', rawEfforts: undefined })); + expect(decision.support).toBe('unknown'); + expect(decision.observations.map(observation => observation.selected)).toEqual([false, true]); + }); + + it('makes same-authority contradictions explicitly unknown regardless of order', () => { + const first = fact(); + const second = fact({ rawEfforts: ['high'] }); + for (const facts of [[first, second], [second, first]]) { + const decision = resolve(...facts); + expect(decision).toMatchObject({ support: 'unknown', mode: 'unknown', supportedEfforts: [] }); + expect(decision.reasons).toContainEqual({ code: 'reasoning_conflicting_facts' }); + } + }); + + it.each([ + { rawEfforts: 'low' }, + { support: 'supported', rawEfforts: [] }, + { support: 'unsupported', rawEfforts: ['low'] }, + { mode: 'required', support: 'unsupported', rawEfforts: [] }, + { mode: 'forbidden' }, + { mode: 'marketing-default' }, + ])('reports malformed or contradictory facts as unknown: %j', malformed => { + const decision = resolve(fact(malformed as Partial)); + expect(decision.support).toBe('unknown'); + expect(decision.reasons).toContainEqual({ code: 'reasoning_malformed_fact' }); + }); + + it('preserves the router mixed-array policy but records ignored malformed elements', () => { + const decision = resolve(fact({ rawEfforts: ['low', null, 'future'] as unknown as string[] })); + expect(decision.selectableEfforts).toEqual(['low']); + expect(decision.reasons).toContainEqual({ code: 'reasoning_malformed_effort_ignored' }); + }); + + it('does not turn unverified conditions into support', () => { + const decision = resolve(fact({ support: 'conditional' })); + expect(decision.support).toBe('unknown'); + expect(decision.reasons).toContainEqual({ code: 'reasoning_condition_unverified' }); + }); + + it('copies and deeply freezes facts, including future values and sanitized provenance', () => { + const source = fact({ provenance: { source: 'fixture\n', secret: 'must-not-leak', nested: {} } }); + const pinned = resolve(source); + (source.rawEfforts as string[]).push('high'); + source.provenance!.source = 'replacement'; + expect(pinned.supportedEfforts).not.toContain('high'); + expect(pinned.observations[0].provenance).toEqual({ source: 'fixture' }); + expect(Object.isFrozen(pinned.observations[0].rawEfforts)).toBe(true); + expect(Object.isFrozen(pinned.reasons[0])).toBe(true); + expect(resolve(source).supportedEfforts).toContain('high'); + }); +}); + +describe('shipped reasoning contract', () => { + const root = path.resolve(__dirname, '..'); + it('projects identical modules and declarations without regenerating catalogue data', () => { + execFileSync(process.execPath, [ + path.join(root, 'scripts/model-information/compile.cjs'), '--contracts-only', '--check', + ]); + for (const directory of ['src/model-information-contract', 'containers/api-proxy/catalogue-contract']) { + for (const file of ['reasoning.js', 'reasoning.d.ts']) { + expect(fs.readFileSync(path.join(root, directory, file))) + .toEqual(fs.readFileSync(path.join(root, 'shared/model-information', file))); + } + } + }); + + it('executes provider-free from off-tree built and proxy package layouts', () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'awf-reasoning-package-')); + try { + for (const [name, source] of [ + ['built', 'dist/model-information-contract'], + ['proxy', 'containers/api-proxy/catalogue-contract'], + ]) { + fs.mkdirSync(path.join(directory, name)); + for (const file of ['reasoning.js', 'reasoning.d.ts', 'identity.d.ts', 'resolution.d.ts']) { + fs.copyFileSync(path.join(root, source, file), path.join(directory, name, file)); + } + expect(fs.readFileSync(path.join(directory, name, 'reasoning.d.ts'))) + .toEqual(fs.readFileSync(path.join(root, 'shared/model-information/reasoning.d.ts'))); + } + execFileSync(process.execPath, ['-e', ` + const assert = require('node:assert/strict'); + for (const name of ['built', 'proxy']) { + const {resolveReasoning, assessReasoningEffort} = require('./' + name + '/reasoning'); + const identity = {key:'copilot/exact', provider:'copilot', rawId:'exact'}; + const scope = {provider:'copilot', channel:'copilot-api'}; + const decision = resolveReasoning({identity, scope, facts:[{ + identity, scope, active:true, authority:'provider', support:'supported', rawEfforts:['none','max','future'] + }]}); + assert.deepEqual(decision.selectableEfforts, ['none','max']); + assert.equal(assessReasoningEffort(decision, 'future', {automatic:true}).admitted, false); + assert.equal(Object.isFrozen(decision), true); + } + `], { cwd: directory, env: { ...process.env, NODE_PATH: '' } }); + const fixture = path.join(directory, 'consumer.ts'); + fs.writeFileSync(fixture, ` + import { resolveReasoning, ReasoningDecision } from './built/reasoning'; + import { assessReasoningEffort } from './proxy/reasoning'; + const decision: ReasoningDecision = resolveReasoning({ + identity: {key:'copilot/exact', provider:'copilot', rawId:'exact', lookupId:'exact'}, + scope: {provider:'copilot', channel:'copilot-api'}, facts:[] + }); + assessReasoningEffort(decision, 'future'); + // @ts-expect-error A non-string effort is not part of the internal contract. + assessReasoningEffort(decision, {}); + // @ts-expect-error A decision is immutable. + decision.supportedEfforts.push('max'); + `); + execFileSync(process.execPath, [ + path.join(root, 'node_modules/typescript/bin/tsc'), '--strict', '--noEmit', + '--skipLibCheck', '--target', 'ES2020', '--moduleResolution', 'node', fixture, + ], { cwd: directory }); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }); +}); From a53925ae7ac9a5e055c337c5646afd009f41b52d Mon Sep 17 00:00:00 2001 From: Landon Cox Date: Sun, 8 Nov 2026 09:39:58 -0800 Subject: [PATCH 3/5] Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> --- containers/api-proxy/reasoning-effort-validation.js | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/containers/api-proxy/reasoning-effort-validation.js b/containers/api-proxy/reasoning-effort-validation.js index 4c651e75f..6c58006b2 100644 --- a/containers/api-proxy/reasoning-effort-validation.js +++ b/containers/api-proxy/reasoning-effort-validation.js @@ -35,11 +35,19 @@ function validateReasoningEffort(body, provider, url, runtimeCatalog, req, optio if (!requested || (requested.value !== undefined && typeof requested.value !== 'string')) return; const decision = getRequestReasoning(parsed.model, provider, runtimeCatalog, req, options); if (assessReasoningEffort(decision, requested.value).admitted) return; - const supported = decision.supportedEfforts; + const supported = Array.isArray(decision.supportedEfforts) ? decision.supportedEfforts : []; + const safeSupported = supported + .slice(0, 20) + .map((value) => + String(value) + .replace(/[\u0000-\u001F\u007F]/g, ' ') + .trim() + .slice(0, 64), + ); const error = new Error( `${requested.field} ${JSON.stringify(requested.value)} is not supported by model ${parsed.model}; ` + - `supported values: [${supported.join(' ')}]`, + `supported values: ${JSON.stringify(safeSupported)}`, ); error.statusCode = 400; error.type = 'invalid_request_error'; From 331d2a56fc74bbdf58626f6e31776926a231a107 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 8 Nov 2026 18:07:08 +0000 Subject: [PATCH 4/5] test: align reasoning and packaging assertions --- containers/api-proxy/reasoning-effort-validation.test.js | 2 +- containers/api-proxy/server.token-steering.test.js | 2 +- containers/api-proxy/upstream-http.test.js | 4 ++-- scripts/model-information/compile.test.ts | 3 ++- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/containers/api-proxy/reasoning-effort-validation.test.js b/containers/api-proxy/reasoning-effort-validation.test.js index a8ac34af1..73adf747b 100644 --- a/containers/api-proxy/reasoning-effort-validation.test.js +++ b/containers/api-proxy/reasoning-effort-validation.test.js @@ -23,7 +23,7 @@ describe('validateReasoningEffort', () => { )).toThrow(expect.objectContaining({ statusCode: 400, code: 'unsupported_reasoning_effort', - message: `${field} "short" is not supported by model gpt-5-mini; supported values: [low medium high]`, + message: `${field} "short" is not supported by model gpt-5-mini; supported values: ["low","medium","high"]`, })); }); diff --git a/containers/api-proxy/server.token-steering.test.js b/containers/api-proxy/server.token-steering.test.js index 112904bcc..f54ceecb3 100644 --- a/containers/api-proxy/server.token-steering.test.js +++ b/containers/api-proxy/server.token-steering.test.js @@ -360,7 +360,7 @@ describe('budget steering and injectSteeringMessage', () => { error: { type: 'invalid_request_error', code: 'unsupported_reasoning_effort', - message: 'reasoning_effort "short" is not supported by model gpt-5-mini; supported values: [low medium high]', + message: 'reasoning_effort "short" is not supported by model gpt-5-mini; supported values: ["low","medium","high"]', }, }); expect(getAiCreditsReflectState().thresholds_pending).toEqual([]); diff --git a/containers/api-proxy/upstream-http.test.js b/containers/api-proxy/upstream-http.test.js index 2cf7e2954..6e7924c02 100644 --- a/containers/api-proxy/upstream-http.test.js +++ b/containers/api-proxy/upstream-http.test.js @@ -727,7 +727,7 @@ describe('upstream-http', () => { expect(res.writeHead).toHaveBeenCalledWith(400, { 'Content-Type': 'application/json', 'X-Request-ID': 'req-1' }); expect(written).toEqual([JSON.stringify({ error: { - message: 'reasoning_effort "high" is not supported by model low-only-model; supported values: [low]', + message: 'reasoning_effort "high" is not supported by model low-only-model; supported values: ["low"]', type: 'invalid_request_error', code: 'unsupported_reasoning_effort', }, @@ -863,7 +863,7 @@ describe('upstream-http', () => { expect(JSON.parse(res.end.mock.calls[0][0])).toMatchObject({ error: { code: 'unsupported_reasoning_effort', - message: 'reasoning_effort "high" is not supported by model fallback-model; supported values: [low]', + message: 'reasoning_effort "high" is not supported by model fallback-model; supported values: ["low"]', }, }); }, diff --git a/scripts/model-information/compile.test.ts b/scripts/model-information/compile.test.ts index be3263849..59e6a7c34 100644 --- a/scripts/model-information/compile.test.ts +++ b/scripts/model-information/compile.test.ts @@ -579,7 +579,8 @@ describe('maintained model compilation', () => { it('resolves generated proxy assets independently of repository shared modules', () => { const dockerfile = fs.readFileSync(path.join(root, 'containers/api-proxy/Dockerfile'), 'utf8'); expect(dockerfile).toMatch(/model-information\.pricing\.generated\.json model-information\.fallback-pricing\.generated\.json model-information\.retired\.generated\.json/); - expect(dockerfile).toMatch(/model-eligibility\.js harness-observation\.js/); + expect(dockerfile).toMatch(/model-eligibility\.js/); + expect(dockerfile).toMatch(/harness-observation\.js/); const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'awf-model-assets-')); try { const fixturePath = fs.realpathSync(temp); From eea819b9e8269b4d825bb6ea7c49ebdab6855dea Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 8 Nov 2026 18:38:44 +0000 Subject: [PATCH 5/5] fix: address reasoning review feedback Co-authored-by: lpcox <15877973+lpcox@users.noreply.github.com> --- .../catalogue-contract/reasoning.d.ts | 3 +- .../api-proxy/catalogue-contract/reasoning.js | 11 ++- containers/api-proxy/key-validation.js | 12 +++ containers/api-proxy/key-validation.test.js | 22 +++++ containers/api-proxy/model-reasoning.js | 88 +++++++++++++++---- containers/api-proxy/model-reasoning.test.js | 53 ++++++++++- .../api-proxy/reasoning-effort-validation.js | 37 +++++--- .../reasoning-effort-validation.test.js | 19 +++- .../api-proxy/server.token-steering.test.js | 2 +- containers/api-proxy/upstream-http.test.js | 6 +- docs/adr/0004-model-information-management.md | 42 +++++---- shared/model-information/reasoning.d.ts | 3 +- shared/model-information/reasoning.js | 11 ++- src/model-information-contract/reasoning.d.ts | 3 +- src/model-information-contract/reasoning.js | 11 ++- 15 files changed, 262 insertions(+), 61 deletions(-) diff --git a/containers/api-proxy/catalogue-contract/reasoning.d.ts b/containers/api-proxy/catalogue-contract/reasoning.d.ts index 51f6ecd8e..25a94d588 100644 --- a/containers/api-proxy/catalogue-contract/reasoning.d.ts +++ b/containers/api-proxy/catalogue-contract/reasoning.d.ts @@ -40,5 +40,6 @@ export interface ReasoningDecision { } export function resolveReasoning(input: ReasoningInput): ReasoningDecision; export function assessReasoningEffort( - decision: ReasoningDecision, effort: string | undefined, options?: { automatic?: boolean }, + decision: ReasoningDecision, effort: string | undefined, + options?: { automatic?: boolean; directMaintainedEfforts?: readonly string[] }, ): Readonly<{ admitted: boolean; reasons: readonly ReasoningReason[] }>; diff --git a/containers/api-proxy/catalogue-contract/reasoning.js b/containers/api-proxy/catalogue-contract/reasoning.js index c0bdacce8..7b9f4d790 100644 --- a/containers/api-proxy/catalogue-contract/reasoning.js +++ b/containers/api-proxy/catalogue-contract/reasoning.js @@ -103,8 +103,14 @@ function resolveReasoning({ identity, scope, facts = [] }) { }); } -function assessReasoningEffort(decision, effort, { automatic = false } = {}) { +function assessReasoningEffort(decision, effort, { + automatic = false, + directMaintainedEfforts = [], +} = {}) { let code; + const maintainedEvidence = decision.observations?.some(observation => + observation.selected && observation.authority === 'maintained'); + const directMaintainedEffort = maintainedEvidence && directMaintainedEfforts.includes(effort); if (effort === undefined) { if (decision.mode === 'required') code = 'reasoning_effort_required'; else if (automatic && decision.support !== 'unsupported' && @@ -113,7 +119,8 @@ function assessReasoningEffort(decision, effort, { automatic = false } = {}) { } } else if (decision.mode === 'forbidden' || decision.support === 'unsupported') { code = 'reasoning_effort_forbidden'; - } else if (decision.support === 'supported' && !decision.supportedEfforts.includes(effort)) { + } else if (decision.support === 'supported' && !decision.supportedEfforts.includes(effort) && + !directMaintainedEffort) { code = 'reasoning_effort_unsupported'; } else if (automatic && decision.support !== 'supported') { code = 'reasoning_automatic_requires_known_support'; diff --git a/containers/api-proxy/key-validation.js b/containers/api-proxy/key-validation.js index c00f71f21..151372d8d 100644 --- a/containers/api-proxy/key-validation.js +++ b/containers/api-proxy/key-validation.js @@ -9,6 +9,7 @@ const { } = require('./runtime-model-catalog'); const { logRequest } = require('./logging'); const { resolveModel } = require('./model-resolver'); +const { getReasoningScope } = require('./model-reasoning'); /** @type {Record} */ const cachedModels = {}; @@ -21,6 +22,15 @@ let keyValidationComplete = false; let getRegisteredAdapters = () => []; let getModelAliases = () => null; +function getModelMetadataScope(provider, url) { + try { + const target = new URL(url); + return getReasoningScope(provider, target.host, target.protocol.slice(0, -1)); + } catch { + return undefined; + } +} + const brokerFailures = Object.freeze({ ERR_TOKEN_BROKER_CONFIGURATION: ['inconclusive', 'Token broker configuration is invalid. Check the broker configuration.'], ERR_TOKEN_BROKER_OIDC: ['inconclusive', 'Token broker identity acquisition failed. Check Actions OIDC permissions and availability.'], @@ -88,6 +98,7 @@ async function refreshProviderModelsForResolution(provider) { const metadata = extractModelMetadata(provider, json, { format: config.modelMetadataFormat, apiVersion: config.apiVersion, + scope: getModelMetadataScope(provider, config.url), }); if (Array.isArray(extracted) && extracted.length > 0) { cachedModels[config.cacheKey] = extracted; @@ -229,6 +240,7 @@ async function fetchStartupModels(adapters = []) { const metadata = extractModelMetadata(adapter.name, json, { format: config.modelMetadataFormat, apiVersion: config.apiVersion, + scope: getModelMetadataScope(adapter.name, config.url), }); if (Array.isArray(extracted) && extracted.length > 0) { cachedModels[config.cacheKey] = extracted; diff --git a/containers/api-proxy/key-validation.test.js b/containers/api-proxy/key-validation.test.js index 1dafb2224..ddcd2d786 100644 --- a/containers/api-proxy/key-validation.test.js +++ b/containers/api-proxy/key-validation.test.js @@ -11,6 +11,8 @@ const discovery = require('./model-discovery'); const { logRequest } = require('./logging'); const validation = require('./key-validation'); const { createCopilotTokenBrokerAdapter } = require('./providers/copilot-token-broker'); +const { getRuntimeModels } = require('./runtime-model-catalog'); +const { getRequestReasoning } = require('./model-reasoning'); function deferred() { let resolve, reject; @@ -150,6 +152,26 @@ describe('renewable startup key validation', () => { adapter.shutdown(); }); + test('scopes BYOK model metadata to the fetched target', async () => { + discovery.fetchJson.mockResolvedValue({ + data: [{ id: 'byok-model', capabilities: { supports: { streaming: true } } }], + }); + await validation.fetchStartupModels([{ + name: 'copilot', + getModelsFetchConfig: () => ({ + url: 'https://byok.example/v1/models', cacheKey: 'copilot', modelMetadataFormat: 'openai', + }), + }]); + + const records = getRuntimeModels('copilot'); + expect(records[0].scope).toEqual({ + provider: 'copilot', channel: 'copilot-api', deployment: 'https://byok.example', + }); + expect(getRequestReasoning('byok-model', 'copilot', { copilot: records }, {}, { + targetHost: 'byok.example', targetScheme: 'https', + }).support).toBe('unknown'); + }); + test.each([401, 403])('late HTTP %s rejection revokes concurrently accepted renewable auth', async status => { const adapter = renewableAdapter(); const probe = deferred(); diff --git a/containers/api-proxy/model-reasoning.js b/containers/api-proxy/model-reasoning.js index 7fa4f433b..14c08c8bb 100644 --- a/containers/api-proxy/model-reasoning.js +++ b/containers/api-proxy/model-reasoning.js @@ -1,12 +1,13 @@ 'use strict'; const { resolveReasoning, assessReasoningEffort } = require('./catalogue-contract/reasoning'); -const { resolveModelIdentity } = require('./model-identity'); +const { identity: createIdentity } = require('./catalogue-contract/identity'); const { resolveIdentity } = require('./catalogue-contract/resolution'); const { getModelEligibilityScope } = require('./model-eligibility'); const { lookupModelRoutingMetadata, getModelApiMapping } = require('./model-api-mapping'); const { getRuntimeModels } = require('./runtime-model-catalog'); const { isGithubCopilotCatalogTarget } = require('./providers/copilot-auth'); +const naming = require('./model-information.naming.generated.json'); const modelPins = new WeakMap(); const requestPins = new WeakMap(); @@ -14,6 +15,15 @@ const NATIVE_PROVIDER_HOSTS = Object.freeze({ openai: 'api.openai.com', anthropic: 'api.anthropic.com', }); +const REASONING_NATIVE_PROVIDER_HOSTS = Object.freeze({ + ...NATIVE_PROVIDER_HOSTS, + gemini: 'generativelanguage.googleapis.com', + vertex: 'aiplatform.googleapis.com', +}); +const DIRECT_MAINTAINED_EFFORTS = Object.freeze({ + 'anthropic/claude-opus-4-7': Object.freeze(['xhigh']), + 'anthropic/claude-opus-4-8': Object.freeze(['xhigh']), +}); function runtimeFact(record, identity, scope) { const supports = record.capabilities?.supports; @@ -40,8 +50,8 @@ function runtimeFact(record, identity, scope) { field = 'capabilities.supports.reasoningEffort'; } else if (scope.provider === 'copilot' && supports && typeof supports === 'object' && !Array.isArray(supports)) { - rawEfforts = []; field = 'capabilities.supports'; + if (scope.channel === 'copilot-api' && scope.deployment === undefined) rawEfforts = []; } if (!field) return null; if (Array.isArray(rawEfforts)) { @@ -56,21 +66,60 @@ function runtimeFact(record, identity, scope) { }; } -function capturedIdentity(model, provider, scope, identities) { - const resolved = resolveModelIdentity(model, provider, { scope, policy: { providerPrefix: false } }); - return resolved.matchKind === 'unmatched' - ? resolveIdentity(model, scope, { models: identities.map(identity => ({ identity })) }, - { caseInsensitive: true, providerPrefix: false }) - : resolved; +function capturedIdentity(model, scope, identities = []) { + return resolveIdentity(model, scope, { + models: [...naming.models, ...identities.map(identity => ({ identity }))], + }, { caseInsensitive: true, providerPrefix: false }); +} + +function isNativeTarget(provider, targetHost, targetScheme) { + if (targetHost === undefined) return true; + if (targetScheme !== undefined && targetScheme !== 'https') return false; + let target; + try { + target = new URL(`${targetScheme || 'https'}://${targetHost}`); + } catch { + return false; + } + if (provider === 'copilot') { + return isGithubCopilotCatalogTarget(`${target.protocol}//${target.host}`); + } + const nativeHost = REASONING_NATIVE_PROVIDER_HOSTS[provider]; + return nativeHost + ? target.hostname.toLowerCase() === nativeHost && (!target.port || target.port === '443') + : true; +} + +function getReasoningScope(provider, targetHost, targetScheme, req = {}) { + const scope = getModelEligibilityScope(provider, req); + if (targetHost === undefined || isNativeTarget(provider, targetHost, targetScheme)) return scope; + let deploymentHost = targetHost.toLowerCase(); + try { + deploymentHost = new URL(`${targetScheme || 'https'}://${targetHost}`).host.toLowerCase(); + } catch { + return { ...scope, deployment: `${targetScheme || 'https'}://${deploymentHost}` }; + } + return { + ...scope, + deployment: `${targetScheme || 'https'}://${deploymentHost}`, + }; } function resolveModelReasoning(model, provider, { records = getRuntimeModels(provider) || [], scope, maintained = true } = {}) { scope = { ...getModelEligibilityScope(provider), ...scope, provider }; - const captured = records.filter(record => !record.provider || record.provider === provider).map(record => ({ + const providerRecords = records.filter(record => !record.provider || record.provider === provider); + const capturedIdentities = providerRecords.map(record => { + try { + return createIdentity(provider, record.id); + } catch { + return null; + } + }).filter(Boolean); + const captured = providerRecords.map(record => ({ record, - identity: resolveModelIdentity(record.id, provider, { scope, policy: { providerPrefix: false } }).identity, + identity: capturedIdentity(record.id, scope, capturedIdentities).identity, })); - const resolution = capturedIdentity(model, provider, scope, captured.map(entry => entry.identity).filter(Boolean)); + const resolution = capturedIdentity(model, scope, capturedIdentities); const facts = []; for (const { record, identity: exact } of captured) { if (!exact || !resolution.identity || exact.key !== resolution.identity.key) continue; @@ -104,18 +153,21 @@ function getModelReasoning(model, provider) { }); } +function getDirectMaintainedEfforts(decision) { + if (!decision.observations.some(observation => + observation.selected && observation.authority === 'maintained')) return []; + return DIRECT_MAINTAINED_EFFORTS[decision.identity?.key] || []; +} + function getRequestReasoning(model, provider, runtimeCatalog, req = {}, options = {}) { - const scope = getModelEligibilityScope(provider, req); - const nativeTarget = options.targetHost === undefined || ( - (provider === 'copilot' ? isGithubCopilotCatalogTarget(options.targetHost) - : options.targetHost.toLowerCase() === NATIVE_PROVIDER_HOSTS[provider]) && - (options.targetScheme === undefined || options.targetScheme === 'https')); + const nativeTarget = isNativeTarget(provider, options.targetHost, options.targetScheme); + const scope = getReasoningScope(provider, options.targetHost, options.targetScheme, req); const key = JSON.stringify([provider, model, scope, nativeTarget]); let pins = requestPins.get(req); if (!pins) requestPins.set(req, pins = new Map()); if (!pins.has(key)) { const selected = req.awfReasoning; - const resolved = capturedIdentity(model, provider, scope, selected?.identity ? [selected.identity] : []); + const resolved = capturedIdentity(model, scope, selected?.identity ? [selected.identity] : []); const matches = nativeTarget && selected?.identity && resolved.identity && selected.identity.key === resolved.identity.key && selected.scope.provider === scope.provider && selected.scope.channel === scope.channel && @@ -130,5 +182,5 @@ function getRequestReasoning(model, provider, runtimeCatalog, req = {}, options module.exports = { resolveModelReasoning, pinModelReasoning, getModelReasoning, getRequestReasoning, assessReasoningEffort, - NATIVE_PROVIDER_HOSTS, + getReasoningScope, getDirectMaintainedEfforts, NATIVE_PROVIDER_HOSTS, }; diff --git a/containers/api-proxy/model-reasoning.test.js b/containers/api-proxy/model-reasoning.test.js index 537997536..ab16e5771 100644 --- a/containers/api-proxy/model-reasoning.test.js +++ b/containers/api-proxy/model-reasoning.test.js @@ -3,7 +3,10 @@ const { parseProviderModelMetadata, replaceRuntimeModels, clearRuntimeModels, captureRuntimePricing, } = require('./runtime-model-catalog'); -const { resolveModelReasoning, getModelReasoning, getRequestReasoning } = require('./model-reasoning'); +const { + resolveModelReasoning, getModelReasoning, getRequestReasoning, assessReasoningEffort, + getReasoningScope, +} = require('./model-reasoning'); const { normalizeModel } = require('./routing-catalogue'); const { getModelRoutingChoices, buildRoutingCandidates } = require('./routing-candidates'); const { validateReasoningEffort } = require('./reasoning-effort-validation'); @@ -98,7 +101,6 @@ describe('shared direct and routing reasoning adapters', () => { models: [ { identity: { ...identity('copilot', 'exact'), aliases: [{ id: 'literal', match: 'exact', scope }] } }, - { identity: identity('copilot', 'literal') }, ], })); const resolve = require('./model-reasoning').resolveModelReasoning; @@ -147,6 +149,53 @@ describe('shared direct and routing reasoning adapters', () => { }).support).toBe('absent'); }); + it('does not reject direct efforts omitted from maintained native routing lists', () => { + for (const model of ['claude-opus-4-7', 'claude-opus-4-8']) { + const decision = getRequestReasoning(model, 'anthropic', { anthropic: [] }, {}, { + targetHost: 'api.anthropic.com', + }); + expect(decision.support).toBe('supported'); + expect(decision.supportedEfforts).not.toContain('xhigh'); + expect(assessReasoningEffort(decision, 'xhigh', { automatic: true }).admitted).toBe(false); + expect(assessReasoningEffort(decision, 'xhigh', { + directMaintainedEfforts: ['xhigh'], + }).admitted).toBe(true); + expect(() => validateReasoningEffort(Buffer.from(JSON.stringify({ + model, output_config: { effort: 'xhigh' }, + })), 'anthropic', '/messages', { anthropic: [] }, {}, { + targetHost: 'api.anthropic.com', + })).not.toThrow(); + } + expect(() => validateReasoningEffort(Buffer.from(JSON.stringify({ + model: 'claude-opus-4-6', output_config: { effort: 'xhigh' }, + })), 'anthropic', '/messages', { anthropic: [] }, {}, { + targetHost: 'api.anthropic.com', + })).toThrow(expect.objectContaining({ code: 'unsupported_reasoning_effort' })); + }); + + it('scopes custom runtime evidence to its backend and limits Copilot omission to native catalogs', () => { + expect(getReasoningScope('gemini', 'generativelanguage.googleapis.com', 'https')) + .toEqual({ provider: 'gemini', channel: 'native-api' }); + expect(getReasoningScope('openai', 'api.openai.com:443', 'https')) + .toEqual({ provider: 'openai', channel: 'native-api' }); + expect(getReasoningScope('gemini', 'custom.example', 'https')).toEqual({ + provider: 'gemini', channel: 'native-api', deployment: 'https://custom.example', + }); + const scope = getReasoningScope('copilot', 'byok.example', 'https'); + expect(scope).toEqual({ + provider: 'copilot', channel: 'copilot-api', deployment: 'https://byok.example', + }); + const decision = getRequestReasoning('byok-model', 'copilot', { copilot: [{ + id: 'byok-model', scope, capabilities: { supports: { streaming: true } }, + }] }, {}, { targetHost: 'byok.example', targetScheme: 'https' }); + expect(decision.support).toBe('unknown'); + + const native = getRequestReasoning('native-model', 'copilot', { copilot: [{ + id: 'native-model', capabilities: { supports: { streaming: true } }, + }] }, {}, { targetHost: 'api.githubcopilot.com', targetScheme: 'https' }); + expect(native.support).toBe('unsupported'); + }); + it('pins direct decisions and candidate pools while refresh affects subsequent requests', () => { replaceRuntimeModels('copilot', [{ id: 'exact-test', supportedReasoningEfforts: ['low'] }]); const capture = captureRuntimePricing(); diff --git a/containers/api-proxy/reasoning-effort-validation.js b/containers/api-proxy/reasoning-effort-validation.js index 6c58006b2..497c208c9 100644 --- a/containers/api-proxy/reasoning-effort-validation.js +++ b/containers/api-proxy/reasoning-effort-validation.js @@ -1,6 +1,8 @@ 'use strict'; -const { getRequestReasoning, assessReasoningEffort } = require('./model-reasoning'); +const { + getRequestReasoning, assessReasoningEffort, getDirectMaintainedEfforts, +} = require('./model-reasoning'); function getReasoningEffort(parsed, url) { let pathname; @@ -34,20 +36,33 @@ function validateReasoningEffort(body, provider, url, runtimeCatalog, req, optio const requested = getReasoningEffort(parsed, url); if (!requested || (requested.value !== undefined && typeof requested.value !== 'string')) return; const decision = getRequestReasoning(parsed.model, provider, runtimeCatalog, req, options); - if (assessReasoningEffort(decision, requested.value).admitted) return; + if (assessReasoningEffort(decision, requested.value, { + directMaintainedEfforts: getDirectMaintainedEfforts(decision), + }).admitted) return; const supported = Array.isArray(decision.supportedEfforts) ? decision.supportedEfforts : []; - const safeSupported = supported - .slice(0, 20) - .map((value) => - String(value) - .replace(/[\u0000-\u001F\u007F]/g, ' ') - .trim() - .slice(0, 64), - ); + const safeSupported = []; + let remaining = 256; + for (const value of supported.slice(0, 20)) { + if (remaining <= 0) break; + let item; + try { + item = String(value); + } catch { + continue; + } + item = item.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, '').slice(0, 64); + const separatorLength = safeSupported.length ? 1 : 0; + if (item.length + separatorLength > remaining) { + item = item.slice(0, remaining - separatorLength); + } + if (!item) continue; + safeSupported.push(item); + remaining -= item.length + separatorLength; + } const error = new Error( `${requested.field} ${JSON.stringify(requested.value)} is not supported by model ${parsed.model}; ` + - `supported values: ${JSON.stringify(safeSupported)}`, + `supported values: [${safeSupported.join(' ')}]`, ); error.statusCode = 400; error.type = 'invalid_request_error'; diff --git a/containers/api-proxy/reasoning-effort-validation.test.js b/containers/api-proxy/reasoning-effort-validation.test.js index 73adf747b..bfdc74f3a 100644 --- a/containers/api-proxy/reasoning-effort-validation.test.js +++ b/containers/api-proxy/reasoning-effort-validation.test.js @@ -23,7 +23,7 @@ describe('validateReasoningEffort', () => { )).toThrow(expect.objectContaining({ statusCode: 400, code: 'unsupported_reasoning_effort', - message: `${field} "short" is not supported by model gpt-5-mini; supported values: ["low","medium","high"]`, + message: `${field} "short" is not supported by model gpt-5-mini; supported values: [low medium high]`, })); }); @@ -87,6 +87,23 @@ describe('validateReasoningEffort', () => { })); }); + it('sanitizes and bounds provider values while preserving the error format', () => { + const longEfforts = Array.from({ length: 24 }, (_, index) => `${index}-${'v'.repeat(62)}`); + replaceRuntimeModels('copilot', [{ + id: 'gpt-5-mini', + supportedReasoningEfforts: ['low\ninjected\u202e', 'x'.repeat(80), ...longEfforts], + }]); + + expect(() => validateReasoningEffort( + Buffer.from(JSON.stringify({ model: 'gpt-5-mini', reasoning_effort: 'short' })), + 'copilot', + '/v1/chat/completions', + )).toThrow(expect.objectContaining({ + message: `reasoning_effort "short" is not supported by model gpt-5-mini; supported values: [` + + ['lowinjected', 'x'.repeat(64), longEfforts[0], longEfforts[1], longEfforts[2].slice(0, 49)].join(' ') + ']', + })); + }); + it('uses active maintained native evidence but still passes genuinely unknown support through', () => { expect(() => validateReasoningEffort(Buffer.from(JSON.stringify({ model: 'gpt-5.4', reasoning_effort: 'max', diff --git a/containers/api-proxy/server.token-steering.test.js b/containers/api-proxy/server.token-steering.test.js index f54ceecb3..112904bcc 100644 --- a/containers/api-proxy/server.token-steering.test.js +++ b/containers/api-proxy/server.token-steering.test.js @@ -360,7 +360,7 @@ describe('budget steering and injectSteeringMessage', () => { error: { type: 'invalid_request_error', code: 'unsupported_reasoning_effort', - message: 'reasoning_effort "short" is not supported by model gpt-5-mini; supported values: ["low","medium","high"]', + message: 'reasoning_effort "short" is not supported by model gpt-5-mini; supported values: [low medium high]', }, }); expect(getAiCreditsReflectState().thresholds_pending).toEqual([]); diff --git a/containers/api-proxy/upstream-http.test.js b/containers/api-proxy/upstream-http.test.js index 6e7924c02..bb46e7c98 100644 --- a/containers/api-proxy/upstream-http.test.js +++ b/containers/api-proxy/upstream-http.test.js @@ -716,6 +716,7 @@ describe('upstream-http', () => { requestBytes: body.length, req, res, + targetHost: 'api.githubcopilot.com', })); expect(httpsRequest).not.toHaveBeenCalled(); @@ -727,7 +728,7 @@ describe('upstream-http', () => { expect(res.writeHead).toHaveBeenCalledWith(400, { 'Content-Type': 'application/json', 'X-Request-ID': 'req-1' }); expect(written).toEqual([JSON.stringify({ error: { - message: 'reasoning_effort "high" is not supported by model low-only-model; supported values: ["low"]', + message: 'reasoning_effort "high" is not supported by model low-only-model; supported values: [low]', type: 'invalid_request_error', code: 'unsupported_reasoning_effort', }, @@ -848,6 +849,7 @@ describe('upstream-http', () => { requestBytes: body.length, req, res, + targetHost: 'api.githubcopilot.com', })); if (fallbackType === 'ordered fallback') { @@ -863,7 +865,7 @@ describe('upstream-http', () => { expect(JSON.parse(res.end.mock.calls[0][0])).toMatchObject({ error: { code: 'unsupported_reasoning_effort', - message: 'reasoning_effort "high" is not supported by model fallback-model; supported values: ["low"]', + message: 'reasoning_effort "high" is not supported by model fallback-model; supported values: [low]', }, }); }, diff --git a/docs/adr/0004-model-information-management.md b/docs/adr/0004-model-information-management.md index 29c9f44f3..ef18765e5 100644 --- a/docs/adr/0004-model-information-management.md +++ b/docs/adr/0004-model-information-management.md @@ -1753,21 +1753,25 @@ and do not activate lower-authority maintained evidence. Provider facts outrank the existing maintained native-API routing mappings. Those mappings apply only to their reviewed patterns on the matching provider/channel without a custom deployment; they never establish support on another backend. Imported or -target-only records are not active evidence. Legacy unscoped runtime observations -are confined to their provider's default API channel and deployment, never -re-scoped to the requesting deployment. Native selection pins are not adopted -on custom targets. Same-authority contradictions -produce an unknown decision, with structured reason codes. Non-string elements -in an otherwise usable effort array are ignored with a reason, preserving the -router's existing mixed-array behavior. - -Intentional direct-validation corrections are regression-backed: it now rejects -efforts outside active maintained native evidence, and rejects explicit efforts -when Copilot advertises a valid supports object without effort control, as -routing already did. Exact/scoped identity resolution replaces the broad -runtime pricing normalizer for this decision; dated, dotted or same-slug IDs -do not borrow support without a reviewed alias. Provider-native IDs are not -prefix-stripped again after the request adapter resolves them. +target-only records are not active evidence. Model-list observations carry the +backend/deployment scope derived from their fetch target; legacy unscoped runtime +observations remain confined to their provider's default API channel and +deployment. Native selection pins are not adopted on custom targets. +Same-authority contradictions produce an unknown decision, with structured +reason codes. Non-string elements in an otherwise usable effort array are +ignored with a reason, preserving the router's existing mixed-array behavior. + +Intentional direct-validation corrections are regression-backed: it rejects +explicit efforts when native Copilot advertises a valid supports object without +effort control. Maintained native routing lists are not exhaustive direct +rejection lists: exact, reviewed direct-support exceptions can admit an effort +without making it selectable for automatic routing. This keeps Opus 4.7/4.8 +`xhigh` support from being rejected while it remains unavailable for automatic +selection; other efforts outside active evidence continue to be rejected. +Exact/scoped identity resolution replaces the broad runtime pricing normalizer +for this decision; dated, dotted or same-slug IDs do not borrow support without +a reviewed alias. Provider-native IDs are not prefix-stripped again after the +request adapter resolves them. Genuinely absent, unknown, malformed or unverified conditional support retains the direct unknown-support pass-through policy. Automatic routing requires @@ -1776,13 +1780,17 @@ their provenance survive observations and decisions but cannot become automatic choices. Explicit unsupported requests are still rejected, including `none`; `none` is not omitted effort. Chat Completions, Responses and Messages retain their existing fields, non-string handling and `unsupported_reasoning_effort` -400 error contract. No consumer strips, substitutes or inserts an effort. +400 error contract, including the original space-separated supported-values +format. Reflected supported values have controls stripped and bounded before +rendering. No consumer strips, substitutes or inserts an effort. Required/optional modes and defaults are exposed only when evidenced. Current active maintained mappings do not reliably supply them, so they remain unknown and no default is inserted. In particular, the staged specialized GPT, Haiku, and Opus/Fable/Mythos `xhigh` refinements above remain inactive; active Opus 4.6, -4.7 and 4.8 mappings still share their existing effort list. +4.7 and 4.8 mappings still share their existing effort list. Direct validation +admits the reviewed `xhigh` exception but does not interpret other omissions +from that routing list as direct support. Decisions copy and deeply freeze their facts. Routing snapshots and classifier requests retain their selected reasoning decision; direct requests cache diff --git a/shared/model-information/reasoning.d.ts b/shared/model-information/reasoning.d.ts index 51f6ecd8e..25a94d588 100644 --- a/shared/model-information/reasoning.d.ts +++ b/shared/model-information/reasoning.d.ts @@ -40,5 +40,6 @@ export interface ReasoningDecision { } export function resolveReasoning(input: ReasoningInput): ReasoningDecision; export function assessReasoningEffort( - decision: ReasoningDecision, effort: string | undefined, options?: { automatic?: boolean }, + decision: ReasoningDecision, effort: string | undefined, + options?: { automatic?: boolean; directMaintainedEfforts?: readonly string[] }, ): Readonly<{ admitted: boolean; reasons: readonly ReasoningReason[] }>; diff --git a/shared/model-information/reasoning.js b/shared/model-information/reasoning.js index c0bdacce8..7b9f4d790 100644 --- a/shared/model-information/reasoning.js +++ b/shared/model-information/reasoning.js @@ -103,8 +103,14 @@ function resolveReasoning({ identity, scope, facts = [] }) { }); } -function assessReasoningEffort(decision, effort, { automatic = false } = {}) { +function assessReasoningEffort(decision, effort, { + automatic = false, + directMaintainedEfforts = [], +} = {}) { let code; + const maintainedEvidence = decision.observations?.some(observation => + observation.selected && observation.authority === 'maintained'); + const directMaintainedEffort = maintainedEvidence && directMaintainedEfforts.includes(effort); if (effort === undefined) { if (decision.mode === 'required') code = 'reasoning_effort_required'; else if (automatic && decision.support !== 'unsupported' && @@ -113,7 +119,8 @@ function assessReasoningEffort(decision, effort, { automatic = false } = {}) { } } else if (decision.mode === 'forbidden' || decision.support === 'unsupported') { code = 'reasoning_effort_forbidden'; - } else if (decision.support === 'supported' && !decision.supportedEfforts.includes(effort)) { + } else if (decision.support === 'supported' && !decision.supportedEfforts.includes(effort) && + !directMaintainedEffort) { code = 'reasoning_effort_unsupported'; } else if (automatic && decision.support !== 'supported') { code = 'reasoning_automatic_requires_known_support'; diff --git a/src/model-information-contract/reasoning.d.ts b/src/model-information-contract/reasoning.d.ts index 51f6ecd8e..25a94d588 100644 --- a/src/model-information-contract/reasoning.d.ts +++ b/src/model-information-contract/reasoning.d.ts @@ -40,5 +40,6 @@ export interface ReasoningDecision { } export function resolveReasoning(input: ReasoningInput): ReasoningDecision; export function assessReasoningEffort( - decision: ReasoningDecision, effort: string | undefined, options?: { automatic?: boolean }, + decision: ReasoningDecision, effort: string | undefined, + options?: { automatic?: boolean; directMaintainedEfforts?: readonly string[] }, ): Readonly<{ admitted: boolean; reasons: readonly ReasoningReason[] }>; diff --git a/src/model-information-contract/reasoning.js b/src/model-information-contract/reasoning.js index c0bdacce8..7b9f4d790 100644 --- a/src/model-information-contract/reasoning.js +++ b/src/model-information-contract/reasoning.js @@ -103,8 +103,14 @@ function resolveReasoning({ identity, scope, facts = [] }) { }); } -function assessReasoningEffort(decision, effort, { automatic = false } = {}) { +function assessReasoningEffort(decision, effort, { + automatic = false, + directMaintainedEfforts = [], +} = {}) { let code; + const maintainedEvidence = decision.observations?.some(observation => + observation.selected && observation.authority === 'maintained'); + const directMaintainedEffort = maintainedEvidence && directMaintainedEfforts.includes(effort); if (effort === undefined) { if (decision.mode === 'required') code = 'reasoning_effort_required'; else if (automatic && decision.support !== 'unsupported' && @@ -113,7 +119,8 @@ function assessReasoningEffort(decision, effort, { automatic = false } = {}) { } } else if (decision.mode === 'forbidden' || decision.support === 'unsupported') { code = 'reasoning_effort_forbidden'; - } else if (decision.support === 'supported' && !decision.supportedEfforts.includes(effort)) { + } else if (decision.support === 'supported' && !decision.supportedEfforts.includes(effort) && + !directMaintainedEffort) { code = 'reasoning_effort_unsupported'; } else if (automatic && decision.support !== 'supported') { code = 'reasoning_automatic_requires_known_support';