Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: gate AI fallbacks by request capability (#5099)

[._.]/ Adam Eivy48d0b01e3988
diff --git a/server/lib/aiToolkit/providerStatus.js b/server/lib/aiToolkit/providerStatus.js
index 18185e237c..249a94d60a 100644
--- a/server/lib/aiToolkit/providerStatus.js
+++ b/server/lib/aiToolkit/providerStatus.js
@@ -10,6 +10,7 @@ import { readFile } from 'fs/promises';
import { existsSync } from 'fs';
import { join, dirname } from 'path';
import { atomicWrite } from './internal/atomicWrite.js';
+import { isOllamaBackedProvider } from './internal/ollamaBacked.js';
/**
* Gate a *configured* fallback-model pin against the fallback provider's own
@@ -47,6 +48,82 @@ export function usableFallbackModel(provider, pinnedModel) {
return null;
}
+// Mirrored from the host's generation-model classifier because aiToolkit must
+// stay self-contained. Fallback admission must inspect the model the executor
+// will actually run, not an embedding-only configured pin/default.
+const EMBEDDING_MODEL_RE =
+ /(?:^|[-_/:])(?:embed|embedding|bge|nomic|mxbai|gte|e5|snowflake-arctic-embed)(?:[-_/:]|$)|text-embedding|embeddinggemma|minilm|paraphrase-multilingual/i;
+
+function isGenerationModelId(model) {
+ return typeof model === 'string' && model.length > 0 && !EMBEDDING_MODEL_RE.test(model);
+}
+
+function extractBakedModel(args) {
+ if (!Array.isArray(args)) return null;
+ for (let i = 0; i < args.length; i += 1) {
+ const arg = args[i];
+ if (typeof arg !== 'string') continue;
+ if (arg === '--model' || arg === '-m') {
+ const next = args[i + 1];
+ return typeof next === 'string' && next.length > 0 && !next.startsWith('-') ? next : null;
+ }
+ if (arg.startsWith('--model=')) return arg.slice('--model='.length) || null;
+ if (arg.startsWith('-m=')) return arg.slice('-m='.length) || null;
+ }
+ return null;
+}
+
+function resolvedFallbackModel(provider, correctedModel) {
+ const baked = provider?.type === 'cli' || provider?.type === 'tui'
+ ? extractBakedModel(provider?.args)
+ : null;
+ const candidates = baked
+ ? [baked, provider?.defaultModel]
+ : [correctedModel, provider?.defaultModel];
+ return candidates.find(isGenerationModelId)
+ || provider?.models?.find(isGenerationModelId)
+ || provider?.models?.[0]
+ || null;
+}
+
+function knownContextWindow(provider, model) {
+ const explicit = Number(provider?.contextWindow);
+ const catalog = Number(model && provider?.modelContextWindows?.[model]);
+ const runtime = Number(provider?.numCtx);
+ const planning = Number.isFinite(explicit) && explicit > 0
+ ? explicit
+ : (Number.isFinite(catalog) && catalog > 0 ? catalog : null);
+ // Only Ollama honors the runner's top-level num_ctx option. When configured,
+ // it is the real runtime ceiling and therefore constrains any wider planning
+ // or catalog window; other OpenAI-compatible endpoints ignore the field.
+ if (isOllamaBackedProvider(provider) && Number.isFinite(runtime) && runtime > 0) {
+ return planning ? Math.min(planning, runtime) : runtime;
+ }
+ return planning;
+}
+
+function capabilityRejection(provider, model, requestCapabilities) {
+ if (!requestCapabilities || typeof requestCapabilities !== 'object') return null;
+ if (requestCapabilities.hasImages === true && provider?.type !== 'api') {
+ return 'cannot transmit image input';
+ }
+
+ const required = Number(requestCapabilities.requiredContextTokens);
+ const available = knownContextWindow(provider, model);
+ if (Number.isFinite(required) && required > 0 && available && required > available) {
+ return `known ${available}-token context is below the ${required}-token request budget`;
+ }
+ return null;
+}
+
+function noEligibleFallbackError(rejections) {
+ const detail = rejections.map(({ provider, reason }) => `${provider}: ${reason}`).join('; ');
+ const error = new Error(`No eligible fallback can satisfy this request (${detail})`);
+ error.code = 'NO_ELIGIBLE_FALLBACK';
+ error.rejections = rejections;
+ return error;
+}
+
export function createProviderStatusService(config = {}) {
const {
dataDir = './data',
@@ -405,12 +482,26 @@ export function createProviderStatusService(config = {}) {
// and it hasn't failed lately — neither says its CLI is installed or its
// key is stored. Skipping an un-runnable candidate here is what turns a
// late `spawn <binary> ENOENT` into "try the next provider instead".
- getFallbackProvider(primaryProviderId, providers, taskFallbackId = null, taskFallbackModelId = null) {
+ getFallbackProvider(primaryProviderId, providers, taskFallbackId = null, taskFallbackModelId = null, requestCapabilities = null) {
+ const capabilityRejections = [];
+ const acceptCandidate = (provider, source, pinnedModel = null) => {
+ if (!provider?.enabled || !this.isAvailable(provider.id) || !meetsPrerequisites(provider, providers)) return null;
+ // Correct stale pins before checking the selected model's window. A pin
+ // that no longer exists falls back to the provider default, and THAT
+ // model must still fit the request before the retry is admitted.
+ const model = usableFallbackModel(provider, pinnedModel);
+ const reason = capabilityRejection(provider, resolvedFallbackModel(provider, model), requestCapabilities);
+ if (reason) {
+ capabilityRejections.push({ provider: provider.name || provider.id, reason });
+ return null;
+ }
+ return { provider, source, model };
+ };
+
if (taskFallbackId && taskFallbackId !== primaryProviderId) {
const taskFallback = providers[taskFallbackId];
- if (taskFallback?.enabled && this.isAvailable(taskFallback.id) && meetsPrerequisites(taskFallback, providers)) {
- return { provider: taskFallback, source: 'task', model: usableFallbackModel(taskFallback, taskFallbackModelId) };
- }
+ const accepted = acceptCandidate(taskFallback, 'task', taskFallbackModelId);
+ if (accepted) return accepted;
}
const primaryProvider = providers[primaryProviderId];
@@ -420,20 +511,19 @@ export function createProviderStatusService(config = {}) {
// primaryProviderId; the configured-fallback path needs its own check.
if (primaryProvider?.fallbackProvider && primaryProvider.fallbackProvider !== primaryProviderId) {
const configuredFallback = providers[primaryProvider.fallbackProvider];
- if (configuredFallback?.enabled && this.isAvailable(configuredFallback.id) && meetsPrerequisites(configuredFallback, providers)) {
- return { provider: configuredFallback, source: 'provider', model: usableFallbackModel(configuredFallback, primaryProvider.fallbackModel) };
- }
+ const accepted = acceptCandidate(configuredFallback, 'provider', primaryProvider.fallbackModel);
+ if (accepted) return accepted;
}
for (const providerId of defaultFallbackPriority) {
if (providerId === primaryProviderId) continue;
const provider = providers[providerId];
- if (provider?.enabled && this.isAvailable(providerId) && meetsPrerequisites(provider, providers)) {
- return { provider, source: 'system', model: null };
- }
+ const accepted = acceptCandidate(provider, 'system');
+ if (accepted) return accepted;
}
+ if (capabilityRejections.length > 0) throw noEligibleFallbackError(capabilityRejections);
return null;
},
diff --git a/server/lib/aiToolkit/providerStatus.test.js b/server/lib/aiToolkit/providerStatus.test.js
index 906be310bf..b4271c514c 100644
--- a/server/lib/aiToolkit/providerStatus.test.js
+++ b/server/lib/aiToolkit/providerStatus.test.js
@@ -551,6 +551,104 @@ describe('Provider Status Service', () => {
});
});
+ describe('getFallbackProvider — request capability gate', () => {
+ const providers = {
+ primary: { id: 'primary', enabled: true, fallbackProvider: 'fallback-provider-1' },
+ 'fallback-provider-1': {
+ id: 'fallback-provider-1', name: 'CLI fallback', type: 'cli', enabled: true,
+ defaultModel: 'small', contextWindow: 16_000,
+ },
+ 'fallback-provider-2': {
+ id: 'fallback-provider-2', name: 'API fallback', type: 'api', enabled: true,
+ defaultModel: 'large', modelContextWindows: { large: 128_000 },
+ },
+ };
+
+ it('preserves explicit order while skipping a fallback that cannot carry images', () => {
+ const result = statusService.getFallbackProvider(
+ 'primary', providers, null, null,
+ { hasImages: true, requiredContextTokens: 10_000 },
+ );
+
+ expect(result.provider.id).toBe('fallback-provider-2');
+ expect(result.source).toBe('system');
+ });
+
+ it('skips a known-too-small model window but retains unknown metadata', () => {
+ const result = statusService.getFallbackProvider(
+ 'primary', providers, null, null,
+ { hasImages: false, requiredContextTokens: 32_000 },
+ );
+ expect(result.provider.id).toBe('fallback-provider-2');
+
+ const unknown = {
+ primary: { id: 'primary', enabled: true, fallbackProvider: 'fallback-provider-1' },
+ 'fallback-provider-1': { id: 'fallback-provider-1', type: 'api', enabled: true },
+ };
+ expect(statusService.getFallbackProvider(
+ 'primary', unknown, null, null,
+ { hasImages: false, requiredContextTokens: 1_000_000 },
+ ).provider.id).toBe('fallback-provider-1');
+ });
+
+ it('re-checks the default model after dropping a stale fallback pin', () => {
+ const stalePin = {
+ primary: {
+ id: 'primary', enabled: true, fallbackProvider: 'fallback-provider-1', fallbackModel: 'retired',
+ },
+ 'fallback-provider-1': {
+ id: 'fallback-provider-1', type: 'api', enabled: true,
+ models: ['current'], defaultModel: 'current', modelContextWindows: { current: 4_096 },
+ },
+ };
+
+ expect(() => statusService.getFallbackProvider(
+ 'primary', stalePin, null, null,
+ { hasImages: false, requiredContextTokens: 8_000 },
+ )).toThrow(expect.objectContaining({ code: 'NO_ELIGIBLE_FALLBACK' }));
+ });
+
+ it('checks the generation model that the executor resolves', () => {
+ const executableModel = {
+ primary: { id: 'primary', enabled: true, fallbackProvider: 'fallback-provider-1' },
+ 'fallback-provider-1': {
+ id: 'fallback-provider-1', type: 'cli', enabled: true,
+ args: ['--model', 'baked-large'],
+ defaultModel: 'nomic-embed-text',
+ models: ['nomic-embed-text', 'baked-large'],
+ modelContextWindows: { 'nomic-embed-text': 2_048, 'baked-large': 64_000 },
+ },
+ };
+
+ expect(statusService.getFallbackProvider(
+ 'primary', executableModel, null, null,
+ { hasImages: false, requiredContextTokens: 32_000 },
+ ).provider.id).toBe('fallback-provider-1');
+ });
+
+ it('uses Ollama numCtx as the effective runtime ceiling', () => {
+ const local = {
+ primary: { id: 'primary', enabled: true, fallbackProvider: 'ollama' },
+ ollama: {
+ id: 'ollama', type: 'api', enabled: true, defaultModel: 'large',
+ contextWindow: 128_000, numCtx: 16_000,
+ },
+ };
+
+ expect(() => statusService.getFallbackProvider(
+ 'primary', local, null, null,
+ { hasImages: false, requiredContextTokens: 32_000 },
+ )).toThrow(expect.objectContaining({ code: 'NO_ELIGIBLE_FALLBACK' }));
+ });
+
+ it('surfaces why no candidate can satisfy the request', () => {
+ expect(() => statusService.getFallbackProvider(
+ 'primary', providers, null, null,
+ { hasImages: true, requiredContextTokens: 256_000 },
+ )).toThrow(/No eligible fallback.*image input.*128000-token context/is);
+ });
+ });
+
describe('getFallbackProvider — stale model pins', () => {
// A `fallbackModel` is set on the PRIMARY but resolved against the
// fallback, so a model bump on the fallback leaves the pin naming an id
diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.js
index 076a9558db..6f507851a7 100644
--- a/server/lib/aiToolkit/runner.js
+++ b/server/lib/aiToolkit/runner.js
@@ -27,6 +27,16 @@ const WIN_EXECUTABLE_EXTS = ['.exe', '.cmd', '.bat', '.com'];
// `provider.timeout || 300000` so a hung upstream can't hold `activeRuns`
// (and thus the run slot) open forever.
const DEFAULT_API_RUN_TIMEOUT_MS = 300000;
+const DEFAULT_OUTPUT_RESERVE_TOKENS = 8000;
+const CHARS_PER_TOKEN = 4;
+
+function deriveRequestCapabilities({ prompt, screenshots, requestCapabilities }) {
+ if (requestCapabilities && typeof requestCapabilities === 'object') return requestCapabilities;
+ return {
+ requiredContextTokens: Math.ceil(String(prompt ?? '').length / CHARS_PER_TOKEN) + DEFAULT_OUTPUT_RESERVE_TOKENS,
+ hasImages: Array.isArray(screenshots) && screenshots.length > 0,
+ };
+}
/**
* Resolve a bare command name to its full path WITH extension on Windows, so
@@ -299,6 +309,8 @@ export function createRunnerService(config = {}) {
source = 'devtools',
fallbackProviderId = null,
effort = null,
+ requestCapabilities = null,
+ screenshots = [],
} = options;
if (!providerService) {
@@ -311,6 +323,11 @@ export function createRunnerService(config = {}) {
// below. Stays null on the non-fallback path so the requested `model`
// wins as before.
let fallbackModelHint = null;
+ const effectiveRequestCapabilities = deriveRequestCapabilities({
+ prompt,
+ screenshots,
+ requestCapabilities,
+ });
if (providerStatusService && !providerStatusService.isAvailable(providerId)) {
const allProviders = await providerService.getAllProviders();
@@ -322,7 +339,9 @@ export function createRunnerService(config = {}) {
const fallback = providerStatusService.getFallbackProvider(
providerId,
providersMap,
- fallbackProviderId
+ fallbackProviderId,
+ null,
+ effectiveRequestCapabilities
);
if (fallback) {
diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.js
index 660441c1b4..177d3eda82 100644
--- a/server/lib/aiToolkit/runner.test.js
+++ b/server/lib/aiToolkit/runner.test.js
@@ -22,6 +22,68 @@ describe('AI Toolkit runner service', () => {
}
});
+ it('passes request capability requirements to proactive fallback selection', async () => {
+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));
+ tempDirs.push(dataDir);
+ const primary = { id: 'primary', name: 'Primary', type: 'api', enabled: true };
+ const fallback = { id: 'fallback', name: 'Fallback', type: 'api', enabled: true, defaultModel: 'vision' };
+ const providerService = {
+ getAllProviders: vi.fn().mockResolvedValue({ providers: [primary, fallback] }),
+ getProviderById: vi.fn(async (id) => (id === fallback.id ? fallback : primary)),
+ };
+ const providerStatusService = {
+ isAvailable: vi.fn().mockReturnValue(false),
+ getFallbackProvider: vi.fn().mockReturnValue({ provider: fallback, source: 'system', model: null }),
+ getStatus: vi.fn().mockReturnValue({ reason: 'rate-limit' }),
+ getTimeUntilRecovery: vi.fn().mockReturnValue('1m'),
+ };
+ const runner = createRunnerService({ dataDir, providerService, providerStatusService });
+ const requestCapabilities = { hasImages: true, requiredContextTokens: 12_000 };
+
+ const result = await runner.createRun({
+ providerId: primary.id,
+ prompt: 'describe',
+ requestCapabilities,
+ });
+
+ expect(result.provider.id).toBe(fallback.id);
+ expect(providerStatusService.getFallbackProvider).toHaveBeenCalledWith(
+ primary.id, expect.any(Object), null, null, requestCapabilities,
+ );
+ });
+
+ it('derives request capabilities for direct and pre-created runs', async () => {
+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));
+ tempDirs.push(dataDir);
+ const primary = { id: 'primary', name: 'Primary', type: 'api', enabled: true };
+ const fallback = { id: 'fallback', name: 'Fallback', type: 'api', enabled: true };
+ const providerService = {
+ getAllProviders: vi.fn().mockResolvedValue({ providers: [primary, fallback] }),
+ getProviderById: vi.fn(async (id) => (id === fallback.id ? fallback : primary)),
+ };
+ const providerStatusService = {
+ isAvailable: vi.fn().mockReturnValue(false),
+ getFallbackProvider: vi.fn().mockReturnValue({ provider: fallback, source: 'system', model: null }),
+ getStatus: vi.fn().mockReturnValue({ reason: 'rate-limit' }),
+ getTimeUntilRecovery: vi.fn().mockReturnValue('1m'),
+ };
+ const runner = createRunnerService({ dataDir, providerService, providerStatusService });
+
+ await runner.createRun({
+ providerId: primary.id,
+ prompt: '12345678',
+ screenshots: ['image.png'],
+ });
+
+ expect(providerStatusService.getFallbackProvider).toHaveBeenCalledWith(
+ primary.id,
+ expect.any(Object),
+ null,
+ null,
+ { hasImages: true, requiredContextTokens: 8002 },
+ );
+ });
+
it('checks provider readiness through the injected hook before API fetches', async () => {
const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));
tempDirs.push(dataDir);
diff --git a/server/services/promptRunner.js b/server/services/promptRunner.js
index a1db434178..56cb2a3e02 100644
--- a/server/services/promptRunner.js
+++ b/server/services/promptRunner.js
@@ -38,6 +38,7 @@ import { getAIToolkitInstance } from '../lib/aiToolkitState.js';
import { createSingleFlight } from '../lib/singleFlight.js';
import { extractJson } from '../lib/jsonExtract.js';
import { isCreativeRunSource, withCreativeLatitude } from '../lib/creativeLatitude.js';
+import { DEFAULT_OUTPUT_RESERVE_TOKENS, estimateTokens } from '../lib/contextBudget.js';
// The fallback-lifecycle notifiers live in services/autoFixer.js, which
// transitively pulls in services/cos.js (PM2 + fs + sockets). Importing it
@@ -56,6 +57,16 @@ export const DEFAULT_TIMEOUT_MS = 300000;
const API_TIMEOUT_BACKSTOP_GRACE_MS = 2000;
const APPEND_CHUNK = (acc, chunk) => acc + (typeof chunk === 'string' ? chunk : (chunk?.text || ''));
+export function buildRequestCapabilities({ prompt, screenshots, outputReserveTokens } = {}) {
+ const reserve = Number.isFinite(Number(outputReserveTokens))
+ ? Math.max(0, Number(outputReserveTokens))
+ : DEFAULT_OUTPUT_RESERVE_TOKENS;
+ return {
+ requiredContextTokens: estimateTokens(prompt) + reserve,
+ hasImages: Array.isArray(screenshots) && screenshots.length > 0,
+ };
+}
+
// ── Local-backend concurrency gate ─────────────────────────────────────────
// A local LLM server (Ollama / LM Studio on localhost) runs inference on one
// GPU. Firing N stage calls at it concurrently (e.g. the 3 parallel
@@ -513,6 +524,9 @@ export function assertVisionRunUsedImages(result, requestedProvider) {
* @param {number} [args.timeout] — per-call timeout in ms; falls back to
* `provider.timeout`, then DEFAULT_TIMEOUT_MS. Callers like the loop
* runner expose a user-configurable timeout that isn't a provider attr.
+ * @param {number} [args.outputReserveTokens=8000] — expected completion budget
+ * included in fallback context admission. Callers with a tighter known
+ * output budget may lower it.
* @param {string} [args.cwd] — working directory for the spawned process.
* Defaults to `process.cwd()`. Callers that run AI against external
* directories (loops with `loop.cwd`, pm2Standardizer with a repo path)
@@ -889,7 +903,7 @@ export async function runPromptThroughProvider(rawArgs) {
// (pickFallbackProvider) and re-writing provider-status.json
// (markUnavailable). The fallback *run* below is NOT coalesced — each failed
// call still executes its own fallback to get its own result.
- const picked = await coalesceFallbackMarkAndPick(failed, firstError);
+ const picked = await coalesceFallbackMarkAndPick(failed, firstError, buildRequestCapabilities(args));
if (!picked) {
// ── Tier 4 — escalate ──: no recovery path left. Every attempted key's
// incidental task was suppressed, so escalate exactly one investigation
@@ -1001,9 +1015,10 @@ const _fallbackMarkAndPick = createSingleFlight();
* @param {Error} firstError — the execution error (carries message + errorAnalysis)
* @returns {Promise<{ provider: object, model: string|null }|null>}
*/
-function coalesceFallbackMarkAndPick(failed, firstError) {
- return _fallbackMarkAndPick.run(failed.id, async () => {
- const picked = await pickFallbackProvider(failed);
+function coalesceFallbackMarkAndPick(failed, firstError, requestCapabilities) {
+ const capabilityKey = `${requestCapabilities?.hasImages === true ? 'images' : 'text'}:${requestCapabilities?.requiredContextTokens || 0}`;
+ return _fallbackMarkAndPick.run(`${failed.id}:${capabilityKey}`, async () => {
+ const picked = await pickFallbackProvider(failed, requestCapabilities);
if (!picked) return null;
await markProviderUnavailableFromError(failed, firstError.message, firstError.errorAnalysis).catch(err => {
console.error(`❌ markUnavailable failed for ${failed.id}: ${err.message}`);
@@ -1026,7 +1041,7 @@ function coalesceFallbackMarkAndPick(failed, firstError) {
* `getFallbackProvider`; the system priority loop already excludes
* `failed.id` by construction.
*/
-async function pickFallbackProvider(failed) {
+async function pickFallbackProvider(failed, requestCapabilities) {
const toolkit = getAIToolkitInstance();
const providerStatus = toolkit?.services?.providerStatus;
if (!providerStatus) return null;
@@ -1036,7 +1051,7 @@ async function pickFallbackProvider(failed) {
const providersMap = {};
for (const p of all.providers) providersMap[p.id] = p;
- const picked = providerStatus.getFallbackProvider(failed.id, providersMap);
+ const picked = providerStatus.getFallbackProvider(failed.id, providersMap, null, null, requestCapabilities);
if (!picked?.provider) return null;
return { provider: picked.provider, model: picked.model ?? null };
}
@@ -1117,6 +1132,7 @@ async function executeProviderRunOnce({
timeout: timeoutOverride,
cwd: cwdOverride,
screenshots = [],
+ outputReserveTokens,
}) {
// Resolve the model that'll actually run BEFORE creating the run record
// so the record reflects reality. resolveEffectiveModel handles both
@@ -1152,6 +1168,7 @@ async function executeProviderRunOnce({
source,
workspacePath: effectiveCwd,
effort,
+ requestCapabilities: buildRequestCapabilities({ prompt, screenshots, outputReserveTokens }),
});
runId = runResult.runId;
if (runResult.provider && runResult.provider.id !== provider.id) {
diff --git a/server/services/promptRunner.test.js b/server/services/promptRunner.test.js
index 5c9cccdc3e..e64b5c6d8a 100644
--- a/server/services/promptRunner.test.js
+++ b/server/services/promptRunner.test.js
@@ -64,7 +64,7 @@ const autoFixer = await import('./autoFixer.js');
const toolkitState = await import('../lib/aiToolkitState.js');
const { ERROR_CATEGORIES } = await import('../lib/aiToolkit/errorDetection.js');
const { CREATIVE_LATITUDE_HEADING, withCreativeLatitude } = await import('../lib/creativeLatitude.js');
-const { runPromptThroughProvider, resolveProviderAndModel, resolveEffectiveModel, pickConfigCorrectedModel, normalizeResponseSchema, coerceResponseToSchema, isSchemaTypeCategory } = await import('./promptRunner.js');
+const { runPromptThroughProvider, resolveProviderAndModel, resolveEffectiveModel, pickConfigCorrectedModel, normalizeResponseSchema, coerceResponseToSchema, isSchemaTypeCategory, buildRequestCapabilities } = await import('./promptRunner.js');
const apiProvider = (extra = {}) => ({
id: 'mock-api', type: 'api', defaultModel: 'm-default', ...extra,
@@ -163,6 +163,15 @@ describe('promptRunner — happy paths', () => {
expect(runner.executeApiRun).toHaveBeenCalledWith(
expect.objectContaining({ screenshots: ['a.png', 'b.png'] }),
);
+ expect(runner.createRun).toHaveBeenCalledWith(expect.objectContaining({
+ requestCapabilities: { hasImages: true, requiredContextTokens: 8_002 },
+ }));
+ });
+
+ it('builds a request budget from prompt input plus the caller output reserve', () => {
+ expect(buildRequestCapabilities({
+ prompt: '12345678', screenshots: [], outputReserveTokens: 1_000,
+ })).toEqual({ hasImages: false, requiredContextTokens: 1_002 });
});
it('defaults screenshots to [] when omitted', async () => {
@@ -830,7 +839,10 @@ describe('promptRunner — retry-with-fallback', () => {
expect(status.markUnavailable).toHaveBeenCalledWith('primary-cli', expect.objectContaining({
reason: expect.any(String),
}));
- expect(status.getFallbackProvider).toHaveBeenCalledWith('primary-cli', expect.any(Object));
+ expect(status.getFallbackProvider).toHaveBeenCalledWith(
+ 'primary-cli', expect.any(Object), null, null,
+ expect.objectContaining({ hasImages: false, requiredContextTokens: expect.any(Number) }),
+ );
// The fallback lifecycle is announced up front (so a slow fallback can't
// outrun the backstop timer) and resolved on success.
expect(autoFixer.noteFallbackStarted).toHaveBeenCalledWith({
@@ -844,6 +856,33 @@ describe('promptRunner — retry-with-fallback', () => {
expect(autoFixer.noteFallbackFailed).not.toHaveBeenCalled();
});
+ it('threads screenshot capability into retry selection and the fallback run', async () => {
+ const status = mockToolkitWithFallback();
+ runner.executeApiRun
+ .mockImplementationOnce(async ({ onComplete }) => {
+ onComplete({ success: false, error: 'vision primary failed' });
+ })
+ .mockImplementationOnce(async ({ screenshots, onData, onComplete }) => {
+ expect(screenshots).toEqual(['frame.png']);
+ onData('described');
+ onComplete({ success: true });
+ });
+
+ const out = await runPromptThroughProvider({
+ provider: primaryApi,
+ prompt: '12345678',
+ source: 'test',
+ screenshots: ['frame.png'],
+ outputReserveTokens: 1_000,
+ });
+
+ expect(out.text).toBe('described');
+ expect(status.getFallbackProvider).toHaveBeenCalledWith(
+ 'primary-api', expect.any(Object), null, null,
+ { hasImages: true, requiredContextTokens: 1_002 },
+ );
+ });
+
it('does NOT bench the provider on a model-not-found (request-specific bad model id), but still falls back for this call', async () => {
const status = mockToolkitWithFallback();
@@ -866,7 +905,10 @@ describe('promptRunner — retry-with-fallback', () => {
// The carve-out: the provider was NOT benched (mirrors CONTENT_REFUSAL).
expect(status.markUnavailable).not.toHaveBeenCalled();
// …but the failing call still recovered via the fallback.
- expect(status.getFallbackProvider).toHaveBeenCalledWith('primary-api', expect.any(Object));
+ expect(status.getFallbackProvider).toHaveBeenCalledWith(
+ 'primary-api', expect.any(Object), null, null,
+ expect.objectContaining({ hasImages: false, requiredContextTokens: expect.any(Number) }),
+ );
});
it('runs the configured fallbackModel on the fallback (never the primary model) when one is pinned', async () => {
@@ -1370,7 +1412,10 @@ describe('promptRunner — Tier 1 config/env correction (issue #2342)', () => {
expect(out.fixStrategy).toBe('constrained-agent-retry');
expect(out.fallbackProvider).toMatchObject({ id: 'fallback-api' });
// Tier 3 engaged: the fallback was looked up (MODEL_NOT_FOUND stays unbenched).
- expect(status.getFallbackProvider).toHaveBeenCalledWith('primary-api', expect.any(Object));
+ expect(status.getFallbackProvider).toHaveBeenCalledWith(
+ 'primary-api', expect.any(Object), null, null,
+ expect.objectContaining({ hasImages: false, requiredContextTokens: expect.any(Number) }),
+ );
expect(status.markUnavailable).not.toHaveBeenCalled();
});
@@ -1447,7 +1492,10 @@ describe('promptRunner — Tier 1 config/env correction (issue #2342)', () => {
// No same-provider corrected retry (primary ran once), straight to Tier 3.
expect(primaryCalls).toBe(1);
expect(out.fixTier).toBe(3);
- expect(status.getFallbackProvider).toHaveBeenCalledWith('primary-cli', expect.any(Object));
+ expect(status.getFallbackProvider).toHaveBeenCalledWith(
+ 'primary-cli', expect.any(Object), null, null,
+ expect.objectContaining({ hasImages: false, requiredContextTokens: expect.any(Number) }),
+ );
});
it('does NOT attempt a Tier-1 correction for non-model failure categories', async () => {
@@ -1473,7 +1521,10 @@ describe('promptRunner — Tier 1 config/env correction (issue #2342)', () => {
// going straight to the Tier-3 fallback.
expect(primaryCalls).toBe(1);
expect(out.fixTier).toBe(3);
- expect(status.getFallbackProvider).toHaveBeenCalledWith('primary-api', expect.any(Object));
+ expect(status.getFallbackProvider).toHaveBeenCalledWith(
+ 'primary-api', expect.any(Object), null, null,
+ expect.objectContaining({ hasImages: false, requiredContextTokens: expect.any(Number) }),
+ );
});
it('escalates explicitly when a Tier-1 pre-execution throw leaves no survivor and no fallback exists', async () => {
@@ -1596,7 +1647,10 @@ describe('promptRunner — Tier 1 config/env correction (issue #2342)', () => {
expect(primaryCalls).toBe(1);
expect(out.fixTier).toBe(3);
- expect(status.getFallbackProvider).toHaveBeenCalledWith('primary-api', expect.any(Object));
+ expect(status.getFallbackProvider).toHaveBeenCalledWith(
+ 'primary-api', expect.any(Object), null, null,
+ expect.objectContaining({ hasImages: false, requiredContextTokens: expect.any(Number) }),
+ );
});
});
@@ -1870,7 +1924,10 @@ describe('promptRunner — Tier 2 schema/type correction (issue #2350)', () => {
expect(out.text).toBe('{"ok":true}');
expect(out.fixTier).toBe(3);
expect(out.fallbackProvider).toMatchObject({ id: 'fallback-api' });
- expect(status.getFallbackProvider).toHaveBeenCalledWith('primary-api', expect.any(Object));
+ expect(status.getFallbackProvider).toHaveBeenCalledWith(
+ 'primary-api', expect.any(Object), null, null,
+ expect.objectContaining({ hasImages: false, requiredContextTokens: expect.any(Number) }),
+ );
// Schema/type failure never benches the primary (it's response-specific, not an outage).
expect(status.markUnavailable).not.toHaveBeenCalled();
expect(autoFixer.noteFallbackHandled).toHaveBeenCalledWith({ provider: 'Primary API', model: 'm1' });