Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion containers/api-proxy/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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 model-decision-diagnostics.js model-decision-diagnostics.schema.json model-decision-observation.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 \
Expand Down
45 changes: 45 additions & 0 deletions containers/api-proxy/catalogue-contract/reasoning.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
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<ReasoningSupport, 'absent'> | 'conditional';
rawEfforts?: readonly string[];
mode?: ReasoningMode;
default?: string;
provenance?: Record<string, unknown>;
}
export interface ReasoningInput {
identity: ModelIdentity | null;
scope: ModelScope;
facts?: readonly ReasoningFact[];
}
export interface ReasoningReason {
readonly code: string;
}
export interface ReasoningDecision {
readonly identity: Readonly<Pick<ModelIdentity, 'key' | 'provider' | 'rawId'>> | null;
readonly scope: Readonly<ModelScope>;
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<Record<string, string>>;
selected: boolean;
}>[];
readonly reasons: readonly ReasoningReason[];
}
export function resolveReasoning(input: ReasoningInput): ReasoningDecision;
export function assessReasoningEffort(
decision: ReasoningDecision, effort: string | undefined,
options?: { automatic?: boolean; directMaintainedEfforts?: readonly string[] },
): Readonly<{ admitted: boolean; reasons: readonly ReasoningReason[] }>;
137 changes: 137 additions & 0 deletions containers/api-proxy/catalogue-contract/reasoning.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
'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,
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' &&
!(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) &&
!directMaintainedEffort) {
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 };
12 changes: 12 additions & 0 deletions containers/api-proxy/key-validation.js
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string[]|null>} */
const cachedModels = {};
Expand All @@ -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.'],
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
22 changes: 22 additions & 0 deletions containers/api-proxy/key-validation.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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();
Expand Down
Loading
Loading