fix: cap context window resolution (#6187) (thanks @iamEvanYT)

This commit is contained in:
Ayaan Zaidi
2026-02-01 19:49:35 +05:30
committed by Ayaan Zaidi
parent 5d3c898a94
commit 0992c5a809
7 changed files with 50 additions and 58 deletions

View File

@@ -11,9 +11,7 @@ export type ContextWindowInfo = {
};
function normalizePositiveInt(value: unknown): number | null {
if (typeof value !== "number" || !Number.isFinite(value)) {
return null;
}
if (typeof value !== "number" || !Number.isFinite(value)) return null;
const int = Math.floor(value);
return int > 0 ? int : null;
}
@@ -25,11 +23,6 @@ export function resolveContextWindowInfo(params: {
modelContextWindow?: number;
defaultTokens: number;
}): ContextWindowInfo {
const fromModel = normalizePositiveInt(params.modelContextWindow);
if (fromModel) {
return { tokens: fromModel, source: "model" };
}
const fromModelsConfig = (() => {
const providers = params.cfg?.models?.providers as
| Record<string, { models?: Array<{ id?: string; contextWindow?: number }> }>
@@ -39,16 +32,19 @@ export function resolveContextWindowInfo(params: {
const match = models.find((m) => m?.id === params.modelId);
return normalizePositiveInt(match?.contextWindow);
})();
if (fromModelsConfig) {
return { tokens: fromModelsConfig, source: "modelsConfig" };
const fromModel = normalizePositiveInt(params.modelContextWindow);
const baseInfo = fromModelsConfig
? { tokens: fromModelsConfig, source: "modelsConfig" as const }
: fromModel
? { tokens: fromModel, source: "model" as const }
: { tokens: Math.floor(params.defaultTokens), source: "default" as const };
const capTokens = normalizePositiveInt(params.cfg?.agents?.defaults?.contextTokens);
if (capTokens && capTokens < baseInfo.tokens) {
return { tokens: capTokens, source: "agentContextTokens" };
}
const fromAgentConfig = normalizePositiveInt(params.cfg?.agents?.defaults?.contextTokens);
if (fromAgentConfig) {
return { tokens: fromAgentConfig, source: "agentContextTokens" };
}
return { tokens: Math.floor(params.defaultTokens), source: "default" };
return baseInfo;
}
export type ContextWindowGuardResult = ContextWindowInfo & {