Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

feat(models): complete public protocol and credential handling

wytd79f4aa16c54
diff --git a/src/main/features/auth.ts b/src/main/features/auth.ts
index 6644cf37..55079d90 100644
--- a/src/main/features/auth.ts
+++ b/src/main/features/auth.ts
@@ -35,15 +35,12 @@
*
* Pick algorithm (pickChatEntry / pickChatEntryGroup)
* 1. Walk entries top-to-bottom.
- * 2. Group consecutive entries by (provider, model): the first group hit
- * is the "primary" model; entries in that group round-robin by
- * lastUsed (oldest picked first).
- * 3. For each candidate, check credential is usable:
- * - api_key: key is present, profile not in cooldown
- * - oauth: access token not expired, OR refresh succeeds
- * If unusable, try the next candidate in the group, then the next
- * group.
- * 4. Bump lastUsed on the chosen entry.
+ * 2. Preserve that priority even when adjacent entries share a model.
+ * 3. For each candidate, check that its credential is usable:
+ * - api_key: key is present, profile not in cooldown
+ * - oauth: access token not expired, OR one refresh succeeds
+ * If unusable, try the next candidate in user order.
+ * 4. Picking is read-only; request completion owns usage updates.
*
* Cooldown (`model/core-agent/profile-cooldown.ts`)
* A profile that fails with a key-specific error (401 / 403 / 429 / 402;
@@ -65,6 +62,7 @@ import { shell } from 'electron';
import { userAuthProfilesFile, userLocalConfigDir } from '../paths';
import * as localSecrets from '../util/local-secret-store';
+import { MIN_NATIVE_MODEL_CONTEXT_WINDOW, modelContextWindowBelowMinimum } from '../util/model-context-window';
import { isBearerTokenHeaderSafe } from '../util/http-authorization';
import { safeExternalUserActionUrl } from '../util/window-security';
import { getActiveUserId, hasActiveUser } from './users';
@@ -74,6 +72,9 @@ import {
OAUTH_ALIAS_FOR,
VISIBLE_PROVIDERS,
EXTERNAL_API_PROVIDERS,
+ isExternalApiProvider,
+ configuredOpenAICompatibleProviders,
+ getConfiguredOpenAICompatibleProvider,
isVisibleProvider,
curatedModelsFor,
isSelectableModel,
@@ -191,7 +192,7 @@ interface ApiKeyProfile {
key: string;
/** Present only for the custom provider. */
baseUrl?: string;
- protocol?: 'openai' | 'anthropic';
+ protocol?: 'openai' | 'responses' | 'anthropic';
contextWindow?: number;
maxTokens?: number;
supportsReasoning?: boolean;
@@ -921,14 +922,15 @@ function isEntryAllowed(store: ProfilesFile, entry: Entry): boolean {
return !!prof
&& isModelProviderAllowed(entry.provider, entry.model)
&& !isStoredProfileBlocked(prof)
- && (!providerUsesCustomOpenAIConfig(entry.provider) || !!customRuntimeConfigFromProfile(prof))
+ && (!providerUsesCustomOpenAIConfig(entry.provider) || (!!customRuntimeConfigFromProfile(prof) && !entryHasSmallCustomWindow(store, entry)))
&& isSelectableModel(entry.provider, entry.model);
}
-function modelNotAvailableError(): Error & { code: string } {
- return Object.assign(new Error(t('errors.model_not_available')), {
- code: 'MODEL_NOT_AVAILABLE',
- });
+function modelNotAvailableError(contextTooSmall = false): Error & { code: string } {
+ const err = new Error(t(contextTooSmall ? 'errors.model_context_too_small' : 'errors.model_not_available',
+ { minimum: MIN_NATIVE_MODEL_CONTEXT_WINDOW })) as Error & { code: string };
+ err.code = 'MODEL_NOT_AVAILABLE';
+ return err;
}
/** A configured SDK-backed model is usable only when pi-ai knows the exact id
@@ -936,37 +938,49 @@ function modelNotAvailableError(): Error & { code: string } {
* Direct adapters build their own Model objects and remain independently
* resolvable. */
function isRuntimeModelResolvable(
- catalog: CoreAgentModule,
+ catalog: CoreAgentModule | null,
providerId: string,
modelId: string,
+ ignoreContextMinimum = false,
): boolean {
if (!isSelectableModel(providerId, modelId)) return false;
- if (EXTERNAL_API_PROVIDERS.includes(providerId)) return true;
- return resolveConfiguredPiModel(catalog, providerId, modelId) !== null;
+ const external = isExternalApiProvider(providerId);
+ const resolved = !external && catalog ? resolveConfiguredPiModel(catalog, providerId, modelId) : null;
+ if (!external && !resolved) return false;
+ const window = external
+ ? curatedModelsFor(providerId).find(model => model.id === modelId)?.contextWindow
+ : resolved?.model.contextWindow;
+ return ignoreContextMinimum || !modelContextWindowBelowMinimum(window);
}
async function assertRuntimeSelectableModel(providerId: string, modelId: string): Promise<void> {
if (!isSelectableModel(providerId, modelId)) throw modelNotAvailableError();
- if (EXTERNAL_API_PROVIDERS.includes(providerId)) return;
- if (isRuntimeModelResolvable(await ca(), providerId, modelId)) return;
- throw modelNotAvailableError();
+ const catalog = isExternalApiProvider(providerId) ? null : await ca();
+ if (isRuntimeModelResolvable(catalog, providerId, modelId)) return;
+ throw modelNotAvailableError(isRuntimeModelResolvable(catalog, providerId, modelId, true));
}
-type RuntimeModelResolver = (providerId: string, modelId: string) => boolean;
+type RuntimeModelResolver = (providerId: string, modelId: string, ignoreContextMinimum?: boolean) => boolean;
async function buildRuntimeModelResolver(
entries: readonly Pick<Entry, 'provider' | 'model'>[],
): Promise<RuntimeModelResolver> {
const needsPiCatalog = entries.some((entry) => (
isSelectableModel(entry.provider, entry.model)
- && !EXTERNAL_API_PROVIDERS.includes(entry.provider)
+ && !isExternalApiProvider(entry.provider)
));
const catalog = needsPiCatalog ? await ca() : null;
- return (providerId, modelId) => (
- isSelectableModel(providerId, modelId)
- && (EXTERNAL_API_PROVIDERS.includes(providerId)
- || (!!catalog && isRuntimeModelResolvable(catalog, providerId, modelId)))
- );
+ const resolutions = new Map<string, { allowed: boolean; exists: boolean }>();
+ return (providerId, modelId, ignoreContextMinimum) => {
+ const key = JSON.stringify([providerId, modelId]);
+ let facts = resolutions.get(key);
+ if (!facts) {
+ const allowed = isRuntimeModelResolvable(catalog, providerId, modelId);
+ facts = { allowed, exists: allowed || isRuntimeModelResolvable(catalog, providerId, modelId, true) };
+ resolutions.set(key, facts);
+ }
+ return ignoreContextMinimum ? facts.exists : facts.allowed;
+ };
}
function makeProfileId(provider: string, label: string): string {
@@ -1006,7 +1020,7 @@ function customConfigError(code: string, message: string): Error & { code: strin
export function normalizeCustomModelBaseUrl(
raw: string,
- protocol: 'openai' | 'anthropic' = 'openai',
+ protocol: 'openai' | 'responses' | 'anthropic' = 'openai',
normalizeEndpoint = true,
): string {
const value = String(raw || '').trim();
@@ -1032,6 +1046,10 @@ export function normalizeCustomModelBaseUrl(
// can consume a gateway prefix that itself ends in /v1.
return normalizeEndpoint ? normalizeAnthropicBaseUrl(url.toString()) : url.toString().replace(/\/+$/, '');
}
+ if (protocol === 'responses') {
+ if (normalizeEndpoint) url.pathname = url.pathname.replace(/\/+$/, '').replace(/\/responses$/i, '') || '/';
+ return url.toString().replace(/\/+$/, '');
+ }
const chatPathIndex = url.pathname.search(/\/chat(?:\/|$)/i);
if (chatPathIndex >= 0) {
url.pathname = url.pathname.slice(0, chatPathIndex).replace(/\/+$/, '') || '/';
@@ -1043,10 +1061,11 @@ function normalizeCustomTokenLimit(
raw: number | string | null | undefined,
fallback: number,
field: 'contextWindow' | 'maxTokens',
+ contextMinimum = MIN_NATIVE_MODEL_CONTEXT_WINDOW,
): number {
if (raw === undefined || raw === null || raw === '') return fallback;
const value = typeof raw === 'number' || typeof raw === 'string' ? Number(raw) : NaN;
- const minimum = field === 'contextWindow' ? 1_024 : 1;
+ const minimum = field === 'contextWindow' ? contextMinimum : 1;
if (!Number.isInteger(value) || value < minimum || value > MAX_CUSTOM_TOKEN_LIMIT) {
throw customConfigError(
'CUSTOM_TOKEN_LIMIT_INVALID',
@@ -1061,12 +1080,13 @@ function customRuntimeConfigFromProfile(
): CustomOpenAICompatibleRuntimeConfig | null {
if (!profile || profile.type !== 'api_key' || profile.provider !== CUSTOM_MODEL_PROVIDER) return null;
try {
- const protocol = profile.protocol === 'anthropic' ? 'anthropic' : 'openai';
+ const protocol = profile.protocol === 'anthropic' ? 'anthropic' : profile.protocol === 'responses' ? 'responses' : 'openai';
const baseUrl = normalizeCustomModelBaseUrl(profile.baseUrl || '', protocol, false);
const contextWindow = normalizeCustomTokenLimit(
profile.contextWindow,
DEFAULT_CUSTOM_CONTEXT_WINDOW,
'contextWindow',
+ 1_024,
);
const maxTokens = normalizeCustomTokenLimit(
profile.maxTokens,
@@ -1291,7 +1311,7 @@ export async function listProviders(): Promise<{ providers: ProviderEntry[] }> {
}
// Visible set: whitelist + providers with saved profiles.
- const visible = new Set<string>(VISIBLE_PROVIDERS);
+ const visible = new Set<string>([...VISIBLE_PROVIDERS, ...configuredOpenAICompatibleProviders().map(p => p.id)]);
for (const pid of byProvider.keys()) {
if (isModelProviderAllowed(pid)) visible.add(pid);
}
@@ -1323,7 +1343,7 @@ export async function listProviders(): Promise<{ providers: ProviderEntry[] }> {
const directOAuth = oauthIds.has(id);
const aliasOAuth = OAUTH_ALIAS_FOR[id];
const supportsOAuth = directOAuth || (!!aliasOAuth && oauthIds.has(aliasOAuth));
- const supportsApiKey = apiCapable.has(id) && !oauthOnlyIds.has(id);
+ const supportsApiKey = (apiCapable.has(id) || isExternalApiProvider(id)) && !oauthOnlyIds.has(id);
return {
id,
label: providerLabel(id),
@@ -1357,8 +1377,9 @@ export async function listModels(providerId: string): Promise<{ models: { id: st
const allowed = (models: { id: string; name: string }[]) =>
models.filter((m) => isModelProviderAllowed(id, m.id));
const curated = curatedModelsFor(id);
- const policyAllowed = allowed(curated.filter(model => model.hiddenFromPicker !== true));
- if (EXTERNAL_API_PROVIDERS.includes(id) || policyAllowed.length === 0) {
+ const policyAllowed = allowed(curated.filter(model => model.hiddenFromPicker !== true && !modelContextWindowBelowMinimum(model.contextWindow)));
+
+ if (isExternalApiProvider(id) || policyAllowed.length === 0) {
return { models: policyAllowed };
}
const catalog = await ca();
@@ -1379,6 +1400,9 @@ export async function addApiKey(
if (!id) throw new Error('provider required');
if (!key) throw new Error('api key required');
assertModelProviderAllowed(id);
+ if (getConfiguredOpenAICompatibleProvider(id) && !isBearerTokenHeaderSafe(key)) {
+ throw customConfigError('API_KEY_INVALID', 'Invalid API key for HTTP Authorization headers');
+ }
if (providerUsesCustomOpenAIConfig(id)) {
throw customConfigError('CUSTOM_CONFIG_REQUIRED', 'Use the custom model configuration flow');
}
@@ -1419,6 +1443,9 @@ export async function addApiKeyEntry(
if (!model) throw new Error('model required');
if (!key) throw new Error('api key required');
assertModelProviderAllowed(id, model);
+ if (getConfiguredOpenAICompatibleProvider(id) && !isBearerTokenHeaderSafe(key)) {
+ throw customConfigError('API_KEY_INVALID', 'Invalid API key for HTTP Authorization headers');
+ }
if (providerUsesCustomOpenAIConfig(id)) {
throw customConfigError('CUSTOM_CONFIG_REQUIRED', 'Use the custom model configuration flow');
}
@@ -1461,7 +1488,7 @@ export async function addApiKeyEntry(
export interface AddCustomModelEntryInput {
label?: string;
- protocol?: 'openai' | 'anthropic' | string;
+ protocol?: 'openai' | 'responses' | 'anthropic' | string;
baseUrl: string;
model: string;
apiKey: string;
@@ -1478,7 +1505,7 @@ export async function addCustomModelEntry(
): Promise<{ profileId: string; entryId: string }> {
const rawLabel = String(input?.label || '').trim();
const model = String(input?.model || '').trim();
- const protocol = input?.protocol === 'anthropic' ? 'anthropic' : 'openai';
+ const protocol = input?.protocol === 'anthropic' ? 'anthropic' : input?.protocol === 'responses' ? 'responses' : 'openai';
const key = String(input?.apiKey || '').trim();
if (!model) throw customConfigError('CUSTOM_MODEL_REQUIRED', 'Model ID required');
if (!key) throw customConfigError('CUSTOM_API_KEY_REQUIRED', 'API key required');
@@ -1513,7 +1540,7 @@ export async function addCustomModelEntry(
'reasoningEffort must be low, medium, or high',
);
}
- if (maxTokens !== undefined && maxTokens > contextWindow) {
+ if ((maxTokens ?? DEFAULT_CUSTOM_MAX_TOKENS) > contextWindow) {
throw customConfigError(
'CUSTOM_TOKEN_LIMIT_INVALID',
'Maximum output tokens cannot exceed the context window',
@@ -1615,6 +1642,9 @@ export interface EntryView {
modelEditable: boolean;
modelAvailable: boolean;
includedModels: string[];
+ selectable?: boolean;
+ availability?: 'available' | 'catalog_removed' | 'credential_missing' | 'context_too_small' | 'service_disabled';
+ availabilityReason?: string;
official?: boolean;
recommended?: boolean;
profileId: string;
@@ -1632,10 +1662,18 @@ function entryToView(
store: ProfilesFile,
modelNameLookup: (p: string, m: string) => string,
runtimeResolvable = true,
+ contextTooSmall = false,
): EntryView {
const prof = store.profiles[e.profileId];
const catalogModel = curatedModelsFor(e.provider).find((model) => model.id === e.model);
+ const availability = contextTooSmall || entryHasSmallCustomWindow(store, e) ? 'context_too_small'
+ : !isSelectableModel(e.provider, e.model) || !runtimeResolvable ? 'catalog_removed'
+ : !isModelProviderAllowed(e.provider, e.model) ? 'service_disabled'
+ : !prof || (providerUsesCustomOpenAIConfig(e.provider) && !customRuntimeConfigFromProfile(prof)) ? 'credential_missing' : 'available';
const base = {
+ selectable: availability === 'available',
+ availability: availability as NonNullable<EntryView['availability']>,
+ ...(availability === 'context_too_small' ? { availabilityReason: t('errors.model_context_too_small', { minimum: MIN_NATIVE_MODEL_CONTEXT_WINDOW }) } : {}),
entryId: e.entryId,
provider: e.provider,
providerLabel: providerLabel(e.provider),
@@ -1696,18 +1734,21 @@ export async function getChatPreloadApi(): Promise<string | null> {
if (!isActiveAuthOwner(uid)) return null;
const entry = allowed.find(entry => resolvable(entry.provider, entry.model));
if (!entry) return null;
- if (EXTERNAL_API_PROVIDERS.includes(entry.provider)) {
+ if (isExternalApiProvider(entry.provider)) {
const models = await import('../model/core-agent/external-providers');
if (!isActiveAuthOwner(uid)) return null;
if (entry.provider === ORKAS_API_PROVIDER) return models.buildOrkasApiModel(entry.model).api;
if (entry.provider === 'moonshot') return models.buildMoonshotModel(entry.model).api;
if (entry.provider === 'deepseek') return models.buildDeepSeekModel(entry.model).api;
if (entry.provider === 'doubao') return models.buildDoubaoModel(entry.model).api;
+ const configured = models.buildConfiguredOpenAICompatibleModel(entry.provider, entry.model);
+ if (configured) return configured.api;
const config = customRuntimeConfigFromProfile(store.profiles[entry.profileId]);
if (!config) return null;
return (config.protocol === 'anthropic'
? models.buildCustomAnthropicModel(entry.model, config)
- : models.buildCustomOpenAICompatibleModel(entry.model, config)).api;
+ : config.protocol === 'responses' ? models.buildCustomResponsesModel(entry.model, config)
+ : models.buildCustomOpenAICompatibleModel(entry.model, config)).api;
}
const catalog = await ca();
if (!isActiveAuthOwner(uid)) return null;
@@ -1731,6 +1772,7 @@ export async function listEntries(
store,
lookup,
runtimeResolvable(entry.provider, entry.model),
+ entryContextWindowTooSmall(store, entry, runtimeResolvable),
)),
};
}
@@ -1886,7 +1928,7 @@ export async function selectEntry(
if (
!isEntryAllowed(store, selected)
|| !runtimeResolvable(selected.provider, selected.model)
- ) throw modelNotAvailableError();
+ ) throw modelNotAvailableError(entryContextWindowTooSmall(store, selected, runtimeResolvable));
const runnable = store.entries.filter((entry) => (
isEntryAllowed(store, entry) && runtimeResolvable(entry.provider, entry.model)
@@ -2229,32 +2271,7 @@ export interface ChatEntryChoice {
model: string;
apiKey: string;
customConfig?: CustomOpenAICompatibleRuntimeConfig;
-}
-
-/**
- * Group consecutive entries by `(provider, model)`. Dropped into a helper
- * so `pickChatEntry` (single winner) and `pickChatEntryGroup` (whole
- * group of candidates for rotation) share exactly the same grouping
- * semantics — including the "first group wins" priority rule.
- */
-function groupEntries(entries: Entry[]): Entry[][] {
- const groups: Entry[][] = [];
- let current: Entry[] = [];
- let currentKey = '';
- for (const e of entries) {
- const key = providerUsesCustomOpenAIConfig(e.provider)
- ? `${e.provider}::${e.model}::${e.profileId}`
- : `${e.provider}::${e.model}`;
- if (key !== currentKey) {
- if (current.length) groups.push(current);
- current = [e];
- currentKey = key;
- } else {
- current.push(e);
- }
- }
- if (current.length) groups.push(current);
- return groups;
+ refreshApiKey?: (rejectedApiKey: string) => Promise<string | undefined>;
}
/**
@@ -2353,11 +2370,7 @@ export function bumpEntryLastUsed(entryId: string): void {
* can fall back to a completely different provider+model if that's how
* the user arranged their list.
*
- * Within a run of consecutive entries sharing the same `(provider, model)`
- * (often: multiple API keys for the same model), we still pre-order by
- * oldest `lastUsed` first so load spreads fairly — but we flatten the
- * ordered sub-lists back into a single stream so the rotating provider
- * sees one simple sequence.
+ * Credentials retain user order even when they share provider and model.
*
* Skips:
* - entries whose profile was deleted
@@ -2376,16 +2389,11 @@ export async function pickChatEntryGroup(): Promise<ChatEntryChoice[]> {
const runtimeResolvable = await buildRuntimeModelResolver(store.entries);
if (!isActiveAuthOwner(userId)) return [];
- // Flatten: preserve entries[] order across groups, but within a
- // consecutive same-(provider, model) run, sort oldest lastUsed first.
- const groups = groupEntries(store.entries);
- const ordered: Entry[] = [];
- for (const group of groups) {
- const sorted = [...group].sort((a, b) => (a.lastUsed || 0) - (b.lastUsed || 0));
- for (const e of sorted) ordered.push(e);
- }
+ // User priority applies to each credential, including identical models.
+ const ordered: Entry[] = [...store.entries];
const choices: ChatEntryChoice[] = [];
+ const resolvedApiKeys = new Map<string, Promise<string | undefined>>();
for (const entry of ordered) {
if (!isEntryAllowed(store, entry)) {
log.info(`skipping disabled provider/model ${entry.provider}/${entry.model}`);
@@ -2399,7 +2407,12 @@ export async function pickChatEntryGroup(): Promise<ChatEntryChoice[]> {
log.info(`skipping cooled-down profile ${entry.profileId}`);
continue;
}
- const apiKey = await resolveEntryApiKey(store, entry, userId);
+ let pendingKey = resolvedApiKeys.get(entry.profileId);
+ if (!pendingKey) {
+ pendingKey = resolveEntryApiKey(store, entry, userId);
+ resolvedApiKeys.set(entry.profileId, pendingKey);
+ }
+ const apiKey = await pendingKey;
// Even an immediately available key crosses an await boundary here.
if (!isActiveAuthOwner(userId)) return [];
if (!apiKey) continue;
@@ -2410,6 +2423,9 @@ export async function pickChatEntryGroup(): Promise<ChatEntryChoice[]> {
provider: entry.provider,
model: entry.model,
apiKey,
+ ...(store.profiles[entry.profileId]?.type === 'oauth' ? {
+ refreshApiKey: (rejectedApiKey: string) => refreshOAuthProfileAfterAuthFailure(entry.profileId, rejectedApiKey, userId),
+ } : {}),
...(customConfig ? { customConfig } : {}),
});
}
@@ -2419,7 +2435,7 @@ export async function pickChatEntryGroup(): Promise<ChatEntryChoice[]> {
/**
* Pick the next chat entry respecting user priority. Thin wrapper over
* `pickChatEntryGroup` that returns the top candidate (first group,
- * oldest-lastUsed first) and bumps `lastUsed` immediately. Callers that
+ * user order). Selection is read-only; completed requests own usage updates. Callers that
* want rotation (runner.ts's chat path) use `pickChatEntryGroup` directly;
* callers that only need one key (testConnection with provider-only mode)
* keep using this.
@@ -2429,9 +2445,7 @@ export async function pickChatEntryGroup(): Promise<ChatEntryChoice[]> {
export async function pickChatEntry(): Promise<ChatEntryChoice | null> {
const group = await pickChatEntryGroup();
if (group.length === 0) return null;
- const chosen = group[0];
- bumpEntryLastUsed(chosen.entryId);
- return chosen;
+ return group[0];
}
/** Retained for one legacy caller (testConnection with a specific provider). */
@@ -2540,7 +2554,7 @@ async function performOAuthProfileRefresh(
if (!isSameOAuthCredential(loadProfiles({ userId }).profiles[profileId], prof)) return undefined;
let newCreds: any;
try {
- newCreds = await provider.refreshToken(creds as any);
+ newCreds = await oauth.refreshOAuthProviderWithTimeout(provider, creds as any);
} catch (err) {
if (isActiveAuthOwner(userId)) rememberOAuthRefreshFailure(profileId, prof, userId);
throw err;
@@ -2605,10 +2619,10 @@ export async function testConnection(
const userId = getActiveUserId();
const mod = await ca();
if (!isActiveAuthOwner(userId)) return { ok: false, error: t('errors.model_not_available') };
- const resolvedModel = EXTERNAL_API_PROVIDERS.includes(pid)
+ const resolvedModel = isExternalApiProvider(pid)
? null
: resolveConfiguredPiModel(mod, pid, selectedModel);
- if (!EXTERNAL_API_PROVIDERS.includes(pid) && !resolvedModel) {
+ if (!isExternalApiProvider(pid) && !resolvedModel) {
return { ok: false, error: t('errors.model_not_available') };
}
@@ -2642,7 +2656,7 @@ export async function testConnection(
// Orkas-side external providers bypass pi-ai's catalog — route directly
// to their factory so we don't hit the "provider has no models registered"
// guard below (which relies on pi-ai's listPiModels).
- if (EXTERNAL_API_PROVIDERS.includes(pid)) {
+ if (isExternalApiProvider(pid)) {
const modelForTest = selectedModel;
const t0 = Date.now();
try {
@@ -2665,7 +2679,7 @@ export async function testConnection(
...customConfig,
});
} else {
- throw new Error(`external provider "${pid}" has no test-connection factory yet`);
+ provider = await ext.createConfiguredOpenAICompatibleProvider({ providerId: pid, apiKey, modelId: probeModel });
}
if (!isActiveAuthOwner(userId)) return { ok: false, error: t('errors.model_not_available') };
const msg = await provider.complete({
@@ -2752,3 +2766,71 @@ function rememberOAuthRefreshFailure(profileId: string, prof: OAuthProfile, user
function clearOAuthRefreshFailure(profileId: string, userId = getActiveUserId()): void {
if (profileId) oauthRefreshFailures.delete(oauthProfileKey(userId, profileId));
}
+
+/** Saved entries remain visible for credential/catalog remediation. */
+export async function listSettingsEntries(): Promise<{ entries: EntryView[] }> {
+ return listEntries({ includeUnavailable: true });
+}
+
+function entryHasSmallCustomWindow(store: ProfilesFile, entry: Entry): boolean {
+ if (!providerUsesCustomOpenAIConfig(entry.provider)) return false;
+ const profile = store.profiles[entry.profileId];
+ if (!profile || profile.type !== 'api_key') return false;
+ try {
+ const window = normalizeCustomTokenLimit(profile.contextWindow, DEFAULT_CUSTOM_CONTEXT_WINDOW, 'contextWindow', 1_024);
+ return modelContextWindowBelowMinimum(window);
+ } catch { return false; }
+}
+
+function entryContextWindowTooSmall(store: ProfilesFile, entry: Entry, resolver: RuntimeModelResolver): boolean {
+ return entryHasSmallCustomWindow(store, entry)
+ || (resolver(entry.provider, entry.model, true) && !resolver(entry.provider, entry.model));
+}
+
+export function getConfiguredModelContextWindowMessage(): string | null {
+ const store = loadProfiles();
+ const visible = store.entries.filter(entry => isModelProviderAllowed(entry.provider, entry.model) && !isStoredProfileBlocked(store.profiles[entry.profileId]));
+ return visible.length > 0 && visible.every(entry => entryHasSmallCustomWindow(store, entry))
+ ? t('errors.model_context_too_small', { minimum: MIN_NATIVE_MODEL_CONTEXT_WINDOW }) : null;
+}
+
+/** Only currently executable configured credentials are rotation candidates. */
+export async function listRotationEntries(): Promise<{ entries: EntryView[] }> { return listEntries(); }
+
+function oauthCredentialsFromProfile(prof: OAuthProfile): Record<string, unknown> {
+ return {
+ access: prof.access,
+ refresh: prof.refresh,
+ expires: prof.expires,
+ ...Object.fromEntries(
+ Object.entries(prof).filter(([k]) =>
+ !['type', 'provider', 'label', 'createdAt', 'lastUsed', 'email', 'access', 'refresh', 'expires'].includes(k),
+ ),
+ ),
+ };
+}
+
+async function refreshOAuthProfileAfterAuthFailure(
+ profileId: string,
+ rejectedApiKey: string,
+ userId: string,
+): Promise<string | undefined> {
+ if (!isActiveAuthOwner(userId)) return undefined;
+ const store = loadProfiles({ userId });
+ const prof = store.profiles[profileId];
+ if (!prof || prof.type !== 'oauth') return undefined;
+ try {
+ const oauth = await piOauth();
+ const provider = await oauth.getOAuthProvider(prof.provider);
+ if (!isActiveAuthOwner(userId)) return undefined;
+ if (!isSameOAuthCredential(loadProfiles({ userId }).profiles[profileId], prof)) return undefined;
+ const currentApiKey = provider?.getApiKey(oauthCredentialsFromProfile(prof) as any);
+ if (currentApiKey && currentApiKey !== rejectedApiKey) {
+ clearOAuthRefreshFailure(profileId, userId);
+ return currentApiKey;
+ }
+ } catch {
+ // The real refresh call below owns failure recording and propagation.
+ }
+ return refreshOAuthProfile(profileId, userId);
+}
diff --git a/src/main/features/client_config.ts b/src/main/features/client_config.ts
index f3488029..d65c154f 100644
--- a/src/main/features/client_config.ts
+++ b/src/main/features/client_config.ts
@@ -636,6 +636,7 @@ export interface QuickStartConfigState {
interface ModelCatalogConfig {
providers: Record<string, ProviderModelEntry[]>;
+ openAICompatibleProviders: Record<string, OpenAICompatibleProviderConfig>;
imageGeneration: Record<string, ImageGenCapability>;
}
@@ -654,7 +655,7 @@ export const DEFAULT_PROVIDER_MODELS = PUBLIC_PROVIDER_MODELS;
export const DEFAULT_IMAGE_GEN_BY_PROVIDER: Readonly<Record<string, ImageGenCapability>> = {
openai: { model: 'gpt-image-2', api: 'openai', supportsEdit: true },
google: { model: 'gemini-nano-banana-2.1', api: 'gemini', supportsEdit: true },
- doubao: { model: 'doubao-seedream-5-0-lite-260128', api: 'doubao', supportsEdit: true },
+ doubao: { model: 'doubao-seedream-5-0-flash-260915', api: 'doubao', supportsEdit: true },
};
/**
@@ -704,7 +705,7 @@ function mergeQuickStartConfig(baseRaw: unknown, overrideRaw: unknown): QuickSta
}
function emptyModelCatalog(): ModelCatalogConfig {
- return { providers: {}, imageGeneration: {} };
+ return { providers: {}, openAICompatibleProviders: {}, imageGeneration: {} };
}
function normalizeProviderModels(value: unknown, providerId: string): ProviderModelEntry[] | null {
@@ -816,6 +817,7 @@ function normalizeModelCatalogConfig(raw: unknown): ModelCatalogConfig {
if (!raw || typeof raw !== 'object') return out;
const r = raw as Record<string, unknown>;
mergeProviderSection(out.providers, r.providers ?? r.curated_models);
+ mergeOpenAICompatibleProviderSection(out.openAICompatibleProviders, r.openai_compatible_providers ?? r.openAICompatibleProviders);
mergeImageGenerationSection(out.imageGeneration, r.image_generation ?? r.imageGeneration);
return out;
}
@@ -1047,6 +1049,10 @@ function mergeModelCatalogConfig(baseRaw: unknown, overrideRaw: unknown): ModelC
...base.providers,
...override.providers,
},
+ openAICompatibleProviders: {
+ ...base.openAICompatibleProviders,
+ ...override.openAICompatibleProviders,
+ },
imageGeneration: {
...base.imageGeneration,
...override.imageGeneration,
@@ -1193,3 +1199,93 @@ export function getRetryErrorPolicyConfig(): RetryErrorPolicyConfig {
clientConfig.get('model.retry_error_policy', fallback),
);
}
+
+export interface OpenAICompatibleProviderConfig {
+ id: string;
+ label: string;
+ baseUrl: string;
+ docsUrl?: string;
+}
+
+const CONFIGURED_PROVIDER_ID_RE = /^[a-z0-9](?:[a-z0-9._-]{0,63})$/;
+
+function normalizePublicHttpsUrl(
+ raw: unknown,
+ options: { baseUrl: boolean },
+): string | null {
+ const value = typeof raw === 'string' ? raw.trim() : '';
+ if (!value || value.length > 2048) return null;
+ let url: URL;
+ try {
+ url = new URL(value);
+ } catch {
+ return null;
+ }
+ const hostname = url.hostname.replace(/^\[|\]$/g, '').replace(/\.$/, '').toLowerCase();
+ if (
+ url.protocol !== 'https:'
+ || !!url.username
+ || !!url.password
+ || !hostname
+ || !hostname.includes('.')
+ || hostname === 'localhost'
+ || hostname.endsWith('.localhost')
+ || hostname.endsWith('.local')
+ || /^(?:\d{1,3}\.){3}\d{1,3}$/.test(hostname)
+ || hostname.includes(':')
+ ) return null;
+ if (options.baseUrl && (url.search || url.hash)) return null;
+ return options.baseUrl
+ ? url.toString().replace(/\/+$/, '')
+ : url.toString();
+}
+
+function normalizeOpenAICompatibleProvider(
+ rawId: string,
+ value: unknown,
+): OpenAICompatibleProviderConfig | null {
+ const id = normalizeKey(rawId).toLowerCase();
+ if (!CONFIGURED_PROVIDER_ID_RE.test(id)) return null;
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
+ const record = value as Record<string, unknown>;
+ const label = typeof record.label === 'string' ? record.label.trim() : '';
+ if (!label || label.length > 80) return null;
+ const baseUrl = normalizePublicHttpsUrl(record.baseUrl, { baseUrl: true });
+ if (!baseUrl) return null;
+ const docsUrl = record.docsUrl === undefined
+ ? undefined
+ : normalizePublicHttpsUrl(record.docsUrl, { baseUrl: false });
+ if (record.docsUrl !== undefined && !docsUrl) return null;
+ return {
+ id,
+ label,
+ baseUrl,
+ ...(docsUrl ? { docsUrl } : {}),
+ };
+}
+
+function mergeOpenAICompatibleProviderSection(
+ target: Record<string, OpenAICompatibleProviderConfig>,
+ value: unknown,
+): void {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return;
+ for (const [rawId, rawProvider] of Object.entries(value as Record<string, unknown>)) {
+ const provider = normalizeOpenAICompatibleProvider(rawId, rawProvider);
+ if (provider) target[provider.id] = provider;
+ }
+}
+
+export function getConfiguredOpenAICompatibleProviders(): OpenAICompatibleProviderConfig[] {
+ return Object.values(loadModelCatalog().openAICompatibleProviders).map((provider) => ({
+ ...provider,
+ }));
+}
+
+export function getConfiguredOpenAICompatibleProvider(
+ providerId: string,
+): OpenAICompatibleProviderConfig | null {
+ const id = normalizeKey(providerId).toLowerCase();
+ if (!id) return null;
+ const provider = loadModelCatalog().openAICompatibleProviders[id];
+ return provider ? { ...provider } : null;
+}
diff --git a/src/main/model/core-agent/external-providers.ts b/src/main/model/core-agent/external-providers.ts
index 1ed161b0..6d08e038 100644
--- a/src/main/model/core-agent/external-providers.ts
+++ b/src/main/model/core-agent/external-providers.ts
@@ -41,6 +41,7 @@ import type { Model } from '@earendil-works/pi-ai';
import { isBearerTokenHeaderSafe } from '../../util/http-authorization';
import {
curatedModelsFor,
+ getConfiguredOpenAICompatibleProvider,
modelInputFromConfiguredCapabilities,
type CustomOpenAICompatibleRuntimeConfig,
} from '../provider_catalog';
@@ -204,7 +205,7 @@ const MOONSHOT_BASE_URL = 'https://api.moonshot.cn/v1';
* if a stale credential references them.
*/
const MOONSHOT_CONTEXT_WINDOW: Record<string, number> = {
- 'kimi-k3': 1048576,
+ 'kimi-k3': 1_000_000,
'kimi-k2.7-code': 262144,
'kimi-k2.7-code-highspeed': 262144,
'kimi-k2.6': 262144,
@@ -311,9 +312,7 @@ export function buildMoonshotModel(
// affect the actual request. Filling 0 means "not accounted for here";
// users check the actual price on their Moonshot bill.
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
- contextWindow: modelId === 'kimi-k3'
- ? moonshotContextWindow(modelId)
- : configuredPositiveInteger(curated?.contextWindow, moonshotContextWindow(modelId)),
+ contextWindow: configuredPositiveInteger(curated?.contextWindow, moonshotContextWindow(modelId)),
maxTokens: configuredPositiveInteger(curated?.maxTokens, moonshotMaxOutputTokens(modelId)),
...(nativeModel?.headers ? { headers: { ...nativeModel.headers } } : {}),
...(protocol?.compat ? { compat: { ...protocol.compat } } : {}),
@@ -368,10 +367,10 @@ const DEEPSEEK_BASE_URL = 'https://api.deepseek.com/v1';
// Compressed Sparse Attention. Fallback 131072 for unknown ids (safe lower
// bound; older deprecated v3 snapshots top out there).
const DEEPSEEK_CONTEXT_WINDOW: Record<string, number> = {
- 'deepseek-flash': 1_048_576,
- 'deepseek-v4-pro': 1_048_576,
- 'deepseek-v4-flash-vision-exp': 1_048_576,
- 'deepseek-v4-flash': 1_048_576,
+ 'deepseek-flash': 1_000_000,
+ 'deepseek-v4-pro': 1_000_000,
+ 'deepseek-v4-flash-vision-exp': 1_000_000,
+ 'deepseek-v4-flash': 1_000_000,
};
function deepseekContextWindow(modelId: string): number {
@@ -383,10 +382,10 @@ function deepseekContextWindow(modelId: string): number {
// so preserving the provider's real cap avoids silently truncating long
// reasoning + answers. Unknown/legacy ids retain a conservative 8192 fallback.
const DEEPSEEK_MAX_OUTPUT_TOKENS: Record<string, number> = {
- 'deepseek-flash': 384_000,
- 'deepseek-v4-pro': 384_000,
- 'deepseek-v4-flash-vision-exp': 384_000,
- 'deepseek-v4-flash': 384_000,
+ 'deepseek-flash': 128_000,
+ 'deepseek-v4-pro': 128_000,
+ 'deepseek-v4-flash-vision-exp': 128_000,
+ 'deepseek-v4-flash': 128_000,
};
function deepseekMaxOutputTokens(modelId: string): number {
@@ -413,12 +412,9 @@ export function buildDeepSeekModel(modelId: string): Model<'openai-completions'>
? ['text', 'image']
: ['text'],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
- contextWindow: Object.prototype.hasOwnProperty.call(DEEPSEEK_CONTEXT_WINDOW, modelId)
- ? deepseekContextWindow(modelId)
- : configuredPositiveInteger(curated?.contextWindow, deepseekContextWindow(modelId)),
- maxTokens: Object.prototype.hasOwnProperty.call(DEEPSEEK_MAX_OUTPUT_TOKENS, modelId)
- ? deepseekMaxOutputTokens(modelId)
- : configuredPositiveInteger(curated?.maxTokens, deepseekMaxOutputTokens(modelId)),
+ contextWindow: configuredPositiveInteger(curated?.contextWindow, deepseekContextWindow(modelId)),
+ maxTokens: configuredPositiveInteger(curated?.maxTokens, deepseekMaxOutputTokens(modelId)),
+ // DeepSeek manages context caching itself and rejects OpenAI cache keys.
compat: { supportsLongCacheRetention: false },
};
}
@@ -437,8 +433,10 @@ export async function createDeepSeekProvider(config: CreateDeepSeekProviderConfi
provider: 'deepseek',
apiKey: config.apiKey,
customModel: model,
- // Replay compatibility is projected by the core adapter.
- onPayload: repairDeepSeekPayload,
+ // The core adapter fills missing tool-turn reasoning after SDK conversion.
+ // Preserve the caller's thinking/effort; this hook owns output limits and
+ // existing tool-receipt ordering only.
+ onPayload: repairDeepSeekRequest,
});
}
@@ -451,6 +449,7 @@ const DOUBAO_BASE_URL = 'https://ark.cn-beijing.volces.com/api/v3';
// endpoint id (ep-xxxx) or a model id; the context window is keyed by model
// id, with a 131072 safe lower-bound fallback for unknown ids.
const DOUBAO_CONTEXT_WINDOW: Record<string, number> = {
+ 'doubao-seed-2-1-pro-260915': 1_000_000,
'doubao-seed-2-0-pro-260215': 262144,
'doubao-seed-2-0-lite-260215': 262144,
'doubao-seed-2-0-lite-260428': 262144,
@@ -464,6 +463,7 @@ function doubaoContextWindow(modelId: string): number {
// 用户填的可能是 endpoint id(ep-xxxx)也可能是模型 id;endpoint id 形式
// 走 fallback 8192 兜底,不会撞到上游 400。
const DOUBAO_MAX_OUTPUT_TOKENS: Record<string, number> = {
+ 'doubao-seed-2-1-pro-260915': 32768,
'doubao-seed-2-0-pro-260215': 16384,
'doubao-seed-2-0-lite-260215': 16384,
'doubao-seed-2-0-lite-260428': 32768,
@@ -535,17 +535,22 @@ export function buildCustomOpenAICompatibleModel(
provider: 'custom' as any,
baseUrl: config.baseUrl,
reasoning: config.supportsReasoning ?? !!config.reasoningEffort,
- input: openAICompatibleModelSupportsImages(modelId, config.supportsVision, true)
- ? ['text', 'image']
- : ['text'],
+ // Custom gateways own model aliases and image handling. Preserve their
+ // declaration instead of inferring capability from an official model name.
+ input: config.supportsVision === false ? ['text'] : ['text', 'image'],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: config.contextWindow,
maxTokens: config.maxTokens,
+ // The custom contract deliberately targets the broadly supported Chat
+ // Completions subset. Provider-specific roles, storage flags, strict tool
+ // schemas, and reasoning controls require a curated adapter instead.
compat: {
supportsDeveloperRole: false,
supportsStore: false,
supportsReasoningEffort: !!config.reasoningEffort,
supportsStrictMode: false,
+ // The SDK otherwise assumes unknown endpoints support OpenAI's 24h
+ // cache extension, which strict Chat-compatible gateways reject.
supportsLongCacheRetention: false,
},
};
@@ -585,14 +590,16 @@ export async function createCustomOpenAICompatibleProvider(
if (!config.baseUrl) throw new Error('custom: baseUrl required');
const mod = await ca();
const isAnthropic = config.protocol === 'anthropic';
- const compatibility = isAnthropic ? null : createCustomOutputLimitCompatibility(config);
+ const isResponses = config.protocol === 'responses';
+ const compatibility = isAnthropic || isResponses ? null : createCustomOutputLimitCompatibility(config);
return mod.createPiProvider({
provider: 'custom',
apiKey: config.apiKey,
customModel: isAnthropic
? buildCustomAnthropicModel(config.modelId, config)
- : buildCustomOpenAICompatibleModel(config.modelId, config),
- normalizeLiteralLeadingThinkText: !isAnthropic,
+ : isResponses ? buildCustomResponsesModel(config.modelId, config)
+ : buildCustomOpenAICompatibleModel(config.modelId, config),
+ normalizeLiteralLeadingThinkText: !isAnthropic && !isResponses,
...(compatibility ? {
onPayload: (payload: unknown) => compatibility.onPayload(repairOpenAICompatiblePayload(payload)),
wrapFetch: compatibility.wrapFetch,
@@ -600,3 +607,98 @@ export async function createCustomOpenAICompatibleProvider(
...(config.reasoningEffort ? { defaultReasoning: config.reasoningEffort } : {}),
});
}
+
+export function buildCustomResponsesModel(
+ modelId: string,
+ config: CustomOpenAICompatibleRuntimeConfig,
+): Model<'openai-responses'> {
+ return {
+ id: modelId, name: modelId, api: 'openai-responses', provider: 'custom' as any,
+ baseUrl: config.baseUrl,
+ reasoning: config.supportsReasoning ?? !!config.reasoningEffort,
+ input: config.supportsVision === false ? ['text'] : ['text', 'image'],
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+ contextWindow: config.contextWindow, maxTokens: config.maxTokens,
+ // Responses otherwise normalizes omitted strictness. Keep ordinary tools
+ // explicitly non-strict so optional fields retain their executor contract.
+ compat: { supportsStrictMode: true, supportsLongCacheRetention: false },
+ };
+}
+
+const CONFIGURED_OPENAI_CONTEXT_WINDOW = 131_072;
+
+const CONFIGURED_OPENAI_MAX_TOKENS = 32_768;
+
+export function buildConfiguredOpenAICompatibleModel(
+ providerId: string,
+ modelId: string,
+): Model<'openai-completions'> | null {
+ const provider = getConfiguredOpenAICompatibleProvider(providerId);
+ const model = curatedModelsFor(providerId).find((entry) => entry.id === modelId);
+ if (!provider || !model) return null;
+ return {
+ id: modelId,
+ name: model.name || modelId,
+ api: 'openai-completions',
+ provider: providerId as any,
+ baseUrl: provider.baseUrl,
+ reasoning: false,
+ input: openAICompatibleModelSupportsImages(
+ modelId,
+ configuredModelVisionDeclaration(model),
+ true,
+ )
+ ? ['text', 'image']
+ : ['text'],
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+ contextWindow: configuredPositiveInteger(model.contextWindow, CONFIGURED_OPENAI_CONTEXT_WINDOW),
+ maxTokens: configuredPositiveInteger(model.maxTokens, CONFIGURED_OPENAI_MAX_TOKENS),
+ compat: {
+ supportsDeveloperRole: false,
+ supportsStore: false,
+ supportsReasoningEffort: false,
+ supportsStrictMode: false,
+ maxTokensField: 'max_tokens',
+ },
+ };
+}
+
+export interface CreateConfiguredOpenAICompatibleProviderConfig {
+ providerId: string;
+ apiKey: string;
+ modelId: string;
+}
+
+export async function createConfiguredOpenAICompatibleProvider(
+ config: CreateConfiguredOpenAICompatibleProviderConfig,
+): Promise<LLMProvider> {
+ if (!config.providerId) throw new Error('configured provider: providerId required');
+ if (!config.apiKey) throw new Error(`${config.providerId}: apiKey required`);
+ if (!isBearerTokenHeaderSafe(config.apiKey)) {
+ throw Object.assign(
+ new Error('Configured provider has an invalid API key for HTTP Authorization headers.'),
+ { code: 'API_KEY_INVALID' },
+ );
+ }
+ if (!config.modelId) throw new Error(`${config.providerId}: modelId required`);
+ const model = buildConfiguredOpenAICompatibleModel(config.providerId, config.modelId);
+ if (!model) throw new Error(`${config.providerId}: model is not configured`);
+ const mod = await ca();
+ return mod.createPiProvider({
+ provider: config.providerId,
+ apiKey: config.apiKey,
+ customModel: model,
+ onPayload: repairOpenAICompatiblePayload,
+ });
+}
+
+export function repairDeepSeekRequest(
+ params: unknown,
+ model: { maxTokens?: number } | undefined,
+ requestMetadata?: unknown,
+): unknown {
+ const metadata = requestMetadata && typeof requestMetadata === 'object' && !Array.isArray(requestMetadata)
+ ? requestMetadata as Record<string, unknown>
+ : {};
+ return repairDeepSeekPayload(omitReservedOutputLimit(params, model?.maxTokens, metadata.outputLimitSource));
+}
diff --git a/src/main/model/core-agent/runner.ts b/src/main/model/core-agent/runner.ts
index 329f8a36..eb6b17c7 100644
--- a/src/main/model/core-agent/runner.ts
+++ b/src/main/model/core-agent/runner.ts
@@ -29,6 +29,7 @@ import {
hasConfiguredModel,
getConfiguredModelCooldown,
getConfiguredModelOAuthExpiredMessage,
+ getConfiguredModelContextWindowMessage,
type ChatEntryChoice,
} from '../../features/auth';
import {
@@ -111,11 +112,14 @@ import {
buildMoonshotModel,
buildDeepSeekModel,
buildDoubaoModel,
+ buildConfiguredOpenAICompatibleModel,
+ createConfiguredOpenAICompatibleProvider,
createMoonshotProvider,
createDeepSeekProvider,
createDoubaoProvider,
buildCustomOpenAICompatibleModel,
buildCustomAnthropicModel,
+ buildCustomResponsesModel,
createCustomOpenAICompatibleProvider,
omitReservedOutputLimitForProvider,
} from './external-providers';
@@ -123,7 +127,7 @@ import { withTaskBudget } from './task-budget-provider';
import { createRotatingProvider, type RotatingCandidate } from './rotating-provider';
import { clearCooldown } from './profile-cooldown';
import {
- EXTERNAL_API_PROVIDERS,
+ isExternalApiProvider,
resolveConfiguredPiModel,
modelInputImageLimit,
} from '../provider_catalog';
@@ -180,10 +184,12 @@ function buildExternalProviderModel(
return customConfig
? (customConfig.protocol === 'anthropic'
? buildCustomAnthropicModel(modelId, customConfig)
- : buildCustomOpenAICompatibleModel(modelId, customConfig))
+ : customConfig.protocol === 'responses'
+ ? buildCustomResponsesModel(modelId, customConfig)
+ : buildCustomOpenAICompatibleModel(modelId, customConfig))
: null;
default:
- return null;
+ return buildConfiguredOpenAICompatibleModel(providerId, modelId);
}
}
@@ -415,7 +421,7 @@ export interface NativeSearchInjectedInfo {
function inputImageLimitForChoice(mod: CA, choice: ChatEntryChoice | undefined): number {
const providerId = choice?.provider || 'anthropic';
const modelId = choice?.model || 'claude-opus-4-8';
- const model = EXTERNAL_API_PROVIDERS.includes(providerId)
+ const model = isExternalApiProvider(providerId)
? buildExternalProviderModel(providerId, modelId, choice?.customConfig)
: resolveConfiguredPiModel(mod, providerId, modelId)?.model;
return modelInputImageLimit(providerId, modelId, model);
@@ -501,6 +507,8 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
const group = await pickChatEntryGroup();
const primary: ChatEntryChoice | undefined = group[0];
if (!primary && (params.requireImageInput || !process.env.ANTHROPIC_API_KEY)) {
+ const contextWindowMessage = getConfiguredModelContextWindowMessage();
+ if (contextWindowMessage) throw new Error(contextWindowMessage);
const oauthExpiredMessage = getConfiguredModelOAuthExpiredMessage();
if (oauthExpiredMessage) throw new Error(oauthExpiredMessage);
const cooldown = getConfiguredModelCooldown();
@@ -1507,7 +1515,7 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
const modelCatalog: Record<string, { provider: string; model: string; contextWindow?: number; maxOutputTokens?: number }> = {};
for (const choice of group) {
if (modelCatalog[choice.model]) continue;
- const model = EXTERNAL_API_PROVIDERS.includes(choice.provider)
+ const model = isExternalApiProvider(choice.provider)
? buildExternalProviderModel(choice.provider, choice.model, choice.customConfig)
: resolveConfiguredPiModel(mod, choice.provider, choice.model)?.model;
if (modelOutputLimitExceedsWindow(model)) {
@@ -1776,7 +1784,7 @@ async function buildExternalProvider(
...choice.customConfig,
});
default:
- throw new Error(`no external provider factory for "${providerId}"`);
+ return createConfiguredOpenAICompatibleProvider({ providerId, apiKey, modelId });
}
}
@@ -1817,7 +1825,7 @@ async function buildRotatingProvider(
const candidates: RotatingCandidate[] = group.map((choice) => {
const candProviderId = choice.provider;
const candModelId = choice.model;
- const isExternal = EXTERNAL_API_PROVIDERS.includes(candProviderId);
+ const isExternal = isExternalApiProvider(candProviderId);
const resolvedModel = isExternal
? null
: resolveConfiguredPiModel(mod, candProviderId, candModelId);
@@ -1843,9 +1851,15 @@ async function buildRotatingProvider(
&& candidateMaxTokens > 0
? { maxTokens: Math.trunc(candidateMaxTokens) }
: {}),
+ ...(choice.refreshApiKey ? { refreshCredential: async () => {
+ const refreshed = await choice.refreshApiKey!(currentApiKey);
+ if (!refreshed) return false;
+ currentApiKey = refreshed;
+ return true;
+ } } : {}),
build: async () => {
if (isExternal) {
- return withTaskBudget(await buildExternalProvider(choice, usageContext), cid);
+ return withTaskBudget(await buildExternalProvider({ ...choice, apiKey: currentApiKey }, usageContext), cid);
}
if (resolvedModel?.isConfiguredFallback) {
log.info('using configured model fallback', {
diff --git a/src/main/model/provider_catalog.ts b/src/main/model/provider_catalog.ts
index bf87dbaa..2633bcaf 100644
--- a/src/main/model/provider_catalog.ts
+++ b/src/main/model/provider_catalog.ts
@@ -38,6 +38,9 @@ import {
type ProviderModelEntry,
getConfiguredImageGenCapability,
getConfiguredProviderModels,
+ type OpenAICompatibleProviderConfig,
+ getConfiguredOpenAICompatibleProviders as getConfiguredOpenAICompatibleProviderConfigs,
+ getConfiguredOpenAICompatibleProvider as getConfiguredOpenAICompatibleProviderConfig,
} from '../features/client_config';
import type { Api, Model } from '@earendil-works/pi-ai';
import {
@@ -207,9 +210,6 @@ const PI_MODEL_TEMPLATE_ALIAS_LABEL: Readonly<Record<string, Readonly<Record<str
};
const MODEL_UPGRADE_ALIAS: Readonly<Record<string, Readonly<Record<string, string>>>> = {
- zai: {
- 'glm-5.1': 'glm-5.2',
- },
anthropic: {
'claude-opus-4-7': 'claude-opus-5',
'claude-opus-4-8': 'claude-opus-5',
@@ -218,16 +218,19 @@ const MODEL_UPGRADE_ALIAS: Readonly<Record<string, Readonly<Record<string, strin
'openai-codex': {
'gpt-5.6-luna': 'gpt-5.6-terra',
'gpt-5.5': 'gpt-5.6-sol',
+ 'gpt-5.4': 'gpt-5.6-sol',
},
openai: {
'gpt-5.6-luna': 'gpt-5.6-terra',
'gpt-5.5': 'gpt-5.6-sol',
+ 'gpt-5.4': 'gpt-5.6-sol',
},
google: {
- 'gemini-3-flash-preview': 'gemini-3.6-flash',
- 'gemini-3.5-flash': 'gemini-3.6-flash',
- 'gemini-3-pro-preview': 'gemini-3.6-flash',
- 'gemini-3.1-pro-preview': 'gemini-3.6-flash',
+ 'gemini-3-flash-preview': 'gemini-3.8-flash',
+ 'gemini-3.5-flash': 'gemini-3.8-flash',
+ 'gemini-3.6-flash': 'gemini-3.8-flash',
+ 'gemini-3-pro-preview': 'gemini-3.8-flash',
+ 'gemini-3.1-pro-preview': 'gemini-3.8-flash',
'gemini-3.1-flash-lite-preview': 'gemini-3.5-flash-lite',
'gemini-3.1-flash-lite': 'gemini-3.5-flash-lite',
},
@@ -248,28 +251,35 @@ const MODEL_UPGRADE_ALIAS: Readonly<Record<string, Readonly<Record<string, strin
'MiniMax-M2.7-highspeed': 'MiniMax-M3',
},
doubao: {
+ 'doubao-seed-2-1-pro-260628': 'doubao-seed-2-1-pro-260915',
'doubao-seed-2-0-lite-260215': 'doubao-seed-2-0-lite-260428',
},
+ zai: {
+ 'glm-5.1': 'glm-5.2',
+ },
openrouter: {
'anthropic/claude-opus-4.7': 'anthropic/claude-opus-5',
'anthropic/claude-opus-4.8': 'anthropic/claude-opus-5',
'anthropic/claude-sonnet-5': 'anthropic/claude-fable-5',
'openai/gpt-5.5': 'openai/gpt-5.6-sol',
+ 'openai/gpt-5.4': 'openai/gpt-5.6-sol',
'openai/gpt-5.6-luna': 'openai/gpt-5.6-terra',
- 'google/gemini-3-flash-preview': 'google/gemini-3.6-flash',
- 'google/gemini-3.5-flash': 'google/gemini-3.6-flash',
- 'google/gemini-3-pro-preview': 'google/gemini-3.6-flash',
- 'google/gemini-3.1-pro-preview': 'google/gemini-3.6-flash',
+ 'google/gemini-3-flash-preview': 'google/gemini-3.8-flash',
+ 'google/gemini-3.5-flash': 'google/gemini-3.8-flash',
+ 'google/gemini-3.6-flash': 'google/gemini-3.8-flash',
+ 'google/gemini-3-pro-preview': 'google/gemini-3.8-flash',
+ 'google/gemini-3.1-pro-preview': 'google/gemini-3.8-flash',
'google/gemini-3.1-flash-lite-preview': 'google/gemini-3.5-flash-lite',
'google/gemini-3.1-flash-lite': 'google/gemini-3.5-flash-lite',
'deepseek/deepseek-v4-flash': 'deepseek/deepseek-v4-flash-0731',
'moonshotai/kimi-k2.5': 'moonshotai/kimi-k3',
'moonshotai/kimi-k2.6': 'moonshotai/kimi-k3',
'moonshotai/kimi-k2.7-code': 'moonshotai/kimi-k3',
- 'qwen/qwen3-max': 'qwen/qwen3.7-max',
- 'qwen/qwen3-coder': 'qwen/qwen3.7-max',
- 'qwen/qwen3-coder-next': 'qwen/qwen3.7-max',
- 'qwen/qwen3.7-flash': 'qwen/qwen3.7-plus',
+ 'qwen/qwen3-max': 'qwen/qwen3.8-max-0902',
+ 'qwen/qwen3-coder': 'qwen/qwen3.8-max-0902',
+ 'qwen/qwen3-coder-next': 'qwen/qwen3.8-max-0902',
+ 'qwen/qwen3.7-max': 'qwen/qwen3.8-max-0902',
+ 'qwen/qwen3.7-flash': 'qwen/qwen3.8-flash',
'z-ai/glm-5.1': 'z-ai/glm-5.2',
'minimax/minimax-m2.7': 'minimax/minimax-m3',
},
@@ -580,7 +590,7 @@ export function modelCatalogEntryFromModel(
if (typeof model.contextWindow === 'number' && model.contextWindow > 0) {
entry.contextWindow = model.contextWindow;
}
- if (typeof model.maxTokens === 'number' && model.maxTokens > 0) {
+ if (typeof model.maxTokens === 'number' && model.maxTokens > 0 && !modelOutputLimitExceedsWindow(model)) {
entry.maxOutputTokens = model.maxTokens;
}
return Object.keys(entry).length ? entry : null;
@@ -619,7 +629,9 @@ export const VISIBLE_PROVIDERS: readonly string[] = CATALOG.map((p) => p.id);
const CATALOG_ORDER = new Map<string, number>(CATALOG.map((p, i) => [p.id, i]));
export function isVisibleProvider(id: string): boolean {
- return CATALOG_ORDER.has(id);
+ const normalized = String(id || '').trim();
+ return CATALOG_ORDER.has(normalized)
+ || getConfiguredOpenAICompatibleProvider(normalized) !== null;
}
/** Providers understood by the runtime but intentionally absent from the
@@ -692,6 +704,8 @@ export const OAUTH_ALIAS_FOR: Readonly<Record<string, string>> = {
export function providerLabel(id: string): string {
const c = CATALOG.find((p) => p.id === id);
if (c) return c.label;
+ const configured = getConfiguredOpenAICompatibleProvider(id);
+ if (configured) return configured.label;
if (EXTRA_LABELS[id]) return EXTRA_LABELS[id];
const oauth = OAUTH_PROVIDERS.find((p) => p.id === id);
if (oauth) return oauth.label;
@@ -703,7 +717,8 @@ export function providerLabelKey(id: string): string | undefined {
}
export function providerDocsUrl(id: string): string | undefined {
- return CATALOG.find((p) => p.id === id)?.docsUrl;
+ return CATALOG.find((p) => p.id === id)?.docsUrl
+ || getConfiguredOpenAICompatibleProvider(id)?.docsUrl;
}
export function providerSubscriptionNote(id: string): string | undefined {
@@ -725,7 +740,7 @@ export function providerUsesCustomOpenAIConfig(id: string): boolean {
export interface CustomOpenAICompatibleRuntimeConfig {
/** Wire protocol; omitted legacy configs use OpenAI-compatible chat completions. */
- protocol?: 'openai' | 'anthropic';
+ protocol?: 'openai' | 'responses' | 'anthropic';
baseUrl: string;
contextWindow: number;
maxTokens: number;
@@ -801,9 +816,20 @@ export function findImageGenCapability(providerId: string): ImageGenCapability |
* at the bottom of the list.
*/
export function sortProviderIds(ids: string[]): string[] {
+ const configuredOrder = new Map(
+ configuredOpenAICompatibleProviders().map((provider, index) => [provider.id, index]),
+ );
return [...ids].sort((a, b) => {
- const ra = CATALOG_ORDER.has(a) ? (CATALOG_ORDER.get(a) as number) : 1000;
- const rb = CATALOG_ORDER.has(b) ? (CATALOG_ORDER.get(b) as number) : 1000;
+ const ra = CATALOG_ORDER.has(a)
+ ? (CATALOG_ORDER.get(a) as number)
+ : configuredOrder.has(a)
+ ? CATALOG.length + (configuredOrder.get(a) as number)
+ : 1000;
+ const rb = CATALOG_ORDER.has(b)
+ ? (CATALOG_ORDER.get(b) as number)
+ : configuredOrder.has(b)
+ ? CATALOG.length + (configuredOrder.get(b) as number)
+ : 1000;
if (ra !== rb) return ra - rb;
return a.localeCompare(b);
});
@@ -949,3 +975,37 @@ function cleanName(raw: string): string {
.replace(/\s*\(\d{4}-\d{2}-\d{2}\)$/, '')
.trim();
}
+
+function isReservedConfiguredProviderId(id: string): boolean {
+ return CATALOG_ORDER.has(id) || isOfficialModelProvider(id);
+}
+
+export function configuredOpenAICompatibleProviders(): OpenAICompatibleProviderConfig[] {
+ return getConfiguredOpenAICompatibleProviderConfigs().filter((provider) => (
+ !isReservedConfiguredProviderId(provider.id)
+ && curatedModelsFor(provider.id).length > 0
+ ));
+}
+
+export function getConfiguredOpenAICompatibleProvider(
+ providerId: string,
+): OpenAICompatibleProviderConfig | null {
+ const id = String(providerId || '').trim();
+ if (!id || isReservedConfiguredProviderId(id)) return null;
+ if (curatedModelsFor(id).length === 0) return null;
+ return getConfiguredOpenAICompatibleProviderConfig(id);
+}
+
+export function isExternalApiProvider(providerId: string): boolean {
+ const id = String(providerId || '').trim();
+ return EXTERNAL_API_PROVIDERS.includes(id)
+ || getConfiguredOpenAICompatibleProvider(id) !== null;
+}
+
+export function modelOutputLimitExceedsWindow(
+ model: { contextWindow?: number; maxTokens?: number } | null | undefined,
+): boolean {
+ if (!model) return false;
+ return typeof model.contextWindow === 'number' && model.contextWindow > 0
+ && typeof model.maxTokens === 'number' && model.maxTokens >= model.contextWindow;
+}
diff --git a/test/main/features/auth.test.ts b/test/main/features/auth.test.ts
index c5fd0cd5..9621dbba 100644
--- a/test/main/features/auth.test.ts
+++ b/test/main/features/auth.test.ts
@@ -486,6 +486,15 @@ describe('auth › custom model configuration', () => {
});
});
+ it.each(['https://gateway.example.test/proxy/v1', 'https://gateway.example.test/proxy/v1/responses/'])('saves and reloads an explicit Responses profile from %s', async baseUrl => {
+ const auth = await import('../../../src/main/features/auth');
+ await auth.addCustomModelEntry({ protocol: 'responses', baseUrl, model: 'custom-responses-alias', apiKey: 'synthetic-responses-key' });
+ vi.resetModules();
+ const users = await import('../../../src/main/features/users'); users.activateUser(TEST_UID);
+ const restarted = await import('../../../src/main/features/auth');
+ expect((await restarted.pickChatEntryGroup())[0]?.customConfig).toMatchObject({ protocol: 'responses', baseUrl: 'https://gateway.example.test/proxy/v1' });
+ });
+
it.each(['https://gateway.example.test/proxy',
'https://gateway.example.test/proxy/v1/',
'https://gateway.example.test/proxy/v1/messages/'])('saves an Anthropic SDK base from %s and reloads its protocol', async (baseUrl) => {
@@ -975,7 +984,7 @@ describe('auth › entries (priority list)', () => {
expect(await a.pickChatEntry()).toBeNull();
});
- it('pickChatEntry prefers the first entry and rotates within a same-(provider, model) group', async () => {
+ it('pickChatEntry keeps the user-selected first credential within the same model group', async () => {
const a = await import('../../../src/main/features/auth');
const p1 = await a.addApiKey('anthropic', 'k-one-xxxxxxxx', 'one');
const p2 = await a.addApiKey('anthropic', 'k-two-xxxxxxxx', 'two');
@@ -988,9 +997,7 @@ describe('auth › entries (priority list)', () => {
expect(first).not.toBeNull();
expect(second).not.toBeNull();
expect(third).not.toBeNull();
- // Both entry ids must show up — round-robin within the top group.
- const ids = new Set([first!.entryId, second!.entryId]);
- expect(ids).toEqual(new Set([e1.entryId, e2.entryId]));
+ expect([first!.entryId, second!.entryId, third!.entryId]).toEqual([e2.entryId, e2.entryId, e2.entryId]);
});
it('pickChatEntry falls back to the next group when top group has no usable credential', async () => {
@@ -1038,15 +1045,15 @@ describe('auth › pickChatEntryGroup + 冷却联动', () => {
expect(group[0].entryId).toBe(e.entryId);
});
- it('同 (provider, model) 两把 key → 组内按 lastUsed 升序返候选', async () => {
+ it('同 (provider, model) 两把 key → lastUsed 不覆盖用户顺序', async () => {
const a = await import('../../../src/main/features/auth');
const p1 = await a.addApiKey('anthropic', 'k-1-xxxxxxxxxxx', 'one');
const p2 = await a.addApiKey('anthropic', 'k-2-xxxxxxxxxxx', 'two');
const e1 = await a.addEntry({ provider: 'anthropic', model: 'claude-opus-4-8', profileId: p1.profileId });
const e2 = await a.addEntry({ provider: 'anthropic', model: 'claude-opus-4-8', profileId: p2.profileId });
- // Bump e1 first → e2 应该成为 oldest,排在前
- a.bumpEntryLastUsed(e1.entryId);
+ // Even a recently used first credential retains the user's priority.
+ a.bumpEntryLastUsed(e2.entryId);
const group = await a.pickChatEntryGroup();
expect(group.map((c) => c.entryId)).toEqual([e2.entryId, e1.entryId]);
@@ -2270,7 +2277,7 @@ describe('auth › chat picker operation ownership', () => {
// Returning to the originating account admits a fresh explicit lookup.
users.activateUser(TEST_UID);
expect((await auth.pickChatEntryGroup())[0]).toMatchObject({ provider: providerId, apiKey: kind === 'oauth' ? 'synthetic-refreshed-a' : `synthetic-${TEST_UID}-key` });
- if (kind === 'oauth') expect(refresh).toHaveBeenCalledWith(expect.objectContaining({ access: `synthetic-${TEST_UID}-old` }));
+ if (kind === 'oauth') expect(refresh).toHaveBeenCalledWith(expect.objectContaining({ access: `synthetic-${TEST_UID}-old` }), expect.objectContaining({ aborted: false }));
expect(fs.readFileSync(paths.userAuthProfilesFile(other), 'utf8')).toBe(otherBefore);
} finally { release(); await pending; }
});
@@ -2348,3 +2355,534 @@ describe('auth › idle API preload metadata', () => {
expect(await a.getChatPreloadApi()).toBeNull();
});
});
+
+describe("auth public configured provider parity",()=>{
+it('adds a provider, preserves per-model capability metadata, and fails closed after withdrawal', async () => {
+ const { clientConfig } = await import('../../../src/main/features/client_config');
+ const a = await import('../../../src/main/features/auth');
+ const configuredCatalog = {
+ providers: {
+ acme: [
+ { id: 'acme-vision', name: 'Acme Vision', supportsVision: true, maxInputImages: 12 },
+ { id: 'acme-default', name: 'Acme Default' },
+ { id: 'acme-text', name: 'Acme Text', supportsVision: false },
+ ],
+ },
+ openai_compatible_providers: {
+ acme: {
+ label: 'Acme AI',
+ baseUrl: 'https://api.acme.example/v1',
+ docsUrl: 'https://docs.acme.example/keys',
+ },
+ },
+ };
+ clientConfig.applyServerPayload({
+ immediate: { model_catalog: configuredCatalog },
+ restart: {},
+ config_hash: 'sha256:acme-provider-on',
+ }, '"acme-provider-on"');
+
+ const acme = (await a.listProviders()).providers.find((provider) => provider.id === 'acme');
+ expect(acme).toMatchObject({
+ label: 'Acme AI',
+ docsUrl: 'https://docs.acme.example/keys',
+ supportsApiKey: true,
+ supportsOAuth: false,
+ customOpenAICompatible: false,
+ profiles: [],
+ });
+ expect((await a.listModels('acme')).models).toEqual([
+ { id: 'acme-vision', name: 'Acme Vision', supportsVision: true, maxInputImages: 12 },
+ { id: 'acme-default', name: 'Acme Default' },
+ { id: 'acme-text', name: 'Acme Text', supportsVision: false },
+ ]);
+ await expect(a.addApiKeyEntry(
+ 'acme',
+ 'acme-vision',
+ 'invalid-щ-key',
+ )).rejects.toMatchObject({ code: 'API_KEY_INVALID' });
+ expect((await a.listSettingsEntries()).entries).toEqual([]);
+
+ const added = await a.addApiKeyEntry(
+ 'acme',
+ 'acme-vision',
+ 'sk-acme-valid-xxxxxxxx',
+ 'work',
+ );
+ expect(await a.pickChatEntryGroup()).toEqual([
+ expect.objectContaining({
+ entryId: added.entryId,
+ provider: 'acme',
+ model: 'acme-vision',
+ apiKey: 'sk-acme-valid-xxxxxxxx',
+ }),
+ ]);
+
+ clientConfig.applyServerPayload({
+ immediate: {
+ model_catalog: {
+ providers: {},
+ openai_compatible_providers: {},
+ },
+ },
+ restart: {},
+ config_hash: 'sha256:acme-provider-off',
+ }, '"acme-provider-off"');
+
+ expect((await a.listModels('acme')).models).toEqual([]);
+ expect(await a.pickChatEntryGroup()).toEqual([]);
+ expect((await a.listSettingsEntries()).entries).toEqual([
+ expect.objectContaining({
+ entryId: added.entryId,
+ provider: 'acme',
+ model: 'acme-vision',
+ selectable: false,
+ availability: 'catalog_removed',
+ }),
+ ]);
+ expect(
+ (await a.listProviders()).providers.find((provider) => provider.id === 'acme')?.profiles,
+ ).toEqual([expect.objectContaining({ profileId: 'acme:work' })]);
+ });
+});
+
+describe('auth › native 32000-token context minimum', () => {
+ it.each(['openai', 'anthropic'])('rejects undersized %s saves and accepts the exact boundary without partial writes', async protocol => {
+ const auth = await import('../../../src/main/features/auth');
+ const config = { protocol, label: 'capacity-boundary', model: 'capacity-fixture',
+ baseUrl: 'https://capacity-fixture.invalid/v1', apiKey: 'synthetic', maxTokens: 8192 };
+ await expect(auth.addCustomModelEntry({ ...config, contextWindow: 31999 }))
+ .rejects.toMatchObject({ code: 'CUSTOM_TOKEN_LIMIT_INVALID' });
+ expect((await auth.listSettingsEntries()).entries).toHaveLength(0);
+ // The implicit 32768 output allowance cannot fit a 32000 window either.
+ await expect(auth.addCustomModelEntry({ ...config, maxTokens: undefined, contextWindow: 32000 }))
+ .rejects.toMatchObject({ code: 'CUSTOM_TOKEN_LIMIT_INVALID' });
+ expect((await auth.listSettingsEntries()).entries).toHaveLength(0);
+ const saved = await auth.addCustomModelEntry({ ...config, contextWindow: 32000 });
+ expect((await auth.pickChatEntryGroup())[0]).toMatchObject({ entryId: saved.entryId,
+ customConfig: { contextWindow: 32000, maxTokens: 8192 } });
+ await expect(auth.addCustomModelEntry({ ...config, contextWindow: 31999 }))
+ .rejects.toMatchObject({ code: 'CUSTOM_TOKEN_LIMIT_INVALID' });
+ expect((await auth.pickChatEntryGroup())[0]?.customConfig?.contextWindow).toBe(32000);
+ });
+
+ it('retains legacy small profiles for remediation but never selects or rotates them', async () => {
+ const auth = await import('../../../src/main/features/auth');
+ const good = await auth.addCustomModelEntry({ label: 'usable', model: 'shared-fixture',
+ baseUrl: 'https://capacity-fixture.invalid/v1', apiKey: 'synthetic',
+ contextWindow: 32000, maxTokens: 8192 });
+ const paths = await import('../../../src/main/paths');
+ const secrets = await import('../../../src/main/util/local-secret-store');
+ const file = paths.userAuthProfilesFile(TEST_UID);
+ const ctx = { namespace: 'auth.profiles', ownerId: TEST_UID, recordId: 'auth-profiles.json' };
+ const store = JSON.parse(secrets.decryptLocalSecret(ctx, fs.readFileSync(file, 'utf8')));
+ store.profiles['custom:legacy-small'] = { ...store.profiles[good.profileId], label: 'legacy-small', contextWindow: 31999 };
+ store.entries.unshift({ ...store.entries[0], entryId: 'legacy-small', profileId: 'custom:legacy-small' });
+ store.profiles['custom:legacy-default-output'] = { ...store.profiles[good.profileId], label: 'legacy-default-output', contextWindow: 4096 };
+ delete store.profiles['custom:legacy-default-output'].maxTokens;
+ store.entries.unshift({ ...store.entries[0], entryId: 'legacy-default-output', profileId: 'custom:legacy-default-output' });
+ fs.writeFileSync(file, secrets.encryptLocalSecret(ctx, JSON.stringify(store)));
+ const before = fs.readFileSync(file, 'utf8');
+ const rows = (await auth.listSettingsEntries()).entries;
+ expect(rows.find(row => row.entryId === 'legacy-small')).toMatchObject({
+ selectable: false, availability: 'context_too_small', profileAvailable: true,
+ availabilityReason: expect.stringContaining('32000'),
+ });
+ expect(rows.find(row => row.entryId === 'legacy-default-output')).toMatchObject({
+ availability: 'context_too_small', profileAvailable: true, availabilityReason: expect.stringContaining('32000') });
+ expect(auth.getConfiguredModelContextWindowMessage()).toBeNull();
+ expect((await auth.listComposerEntries()).entries.map(row => row.entryId)).toEqual([good.entryId]);
+ expect((await auth.listRotationEntries()).entries.map(row => row.entryId)).toEqual([good.entryId]);
+ expect((await auth.pickChatEntryGroup()).map(row => row.entryId)).toEqual([good.entryId]);
+ await expect(auth.selectEntry('legacy-small')).rejects.toMatchObject({ code: 'MODEL_NOT_AVAILABLE', message: expect.stringContaining('32000') });
+ expect(fs.readFileSync(file, 'utf8')).toBe(before);
+ vi.resetModules();
+ const users = await import('../../../src/main/features/users'); users.activateUser(TEST_UID);
+ const restarted = await import('../../../src/main/features/auth');
+ expect((await restarted.pickChatEntryGroup()).map(row => row.entryId)).toEqual([good.entryId]);
+ expect(fs.readFileSync(file, 'utf8')).toBe(before);
+ await restarted.removeEntry(good.entryId);
+ expect(await restarted.pickChatEntryGroup()).toEqual([]);
+ expect(restarted.getConfiguredModelContextWindowMessage()).toContain('32000');
+ });
+
+ it('uses resolved catalog windows to reject a small version switch without changing priorities', async () => {
+ const auth = await import('../../../src/main/features/auth');
+ const profile = await auth.addApiKey('openai', 'synthetic', 'capacity');
+ const good = await auth.addEntry({ provider: 'openai', model: 'gpt-5.6-sol', profileId: profile.profileId });
+ const small = await auth.addEntry({ provider: 'openai', model: 'gpt-5.6-terra', profileId: profile.profileId });
+ const { clientConfig } = await import('../../../src/main/features/client_config');
+ clientConfig.applyServerPayload({ immediate: { model_catalog: { providers: { openai: [
+ { id: 'gpt-5.6-sol', name: 'Fixture large', contextWindow: 32000, maxTokens: 8192 },
+ { id: 'gpt-5.6-terra', name: 'Fixture small', contextWindow: 31999, maxTokens: 8192 },
+ ] } } }, restart: {}, config_hash: 'sha256:context-floor' }, '"context-floor"');
+ expect((await auth.listModels('openai')).models.map(row => row.id)).toEqual(['gpt-5.6-sol']);
+ expect((await auth.listComposerEntries()).entries.map(row => row.entryId)).toEqual([good.entryId]);
+ expect((await auth.listRotationEntries()).entries.map(row => row.entryId)).toEqual([good.entryId]);
+ expect((await auth.pickChatEntryGroup()).map(row => row.entryId)).toEqual([good.entryId]);
+ expect((await auth.listSettingsEntries()).entries.find(row => row.entryId === small.entryId))
+ .toMatchObject({ availability: 'context_too_small', availabilityReason: expect.stringContaining('32000') });
+ await expect(auth.selectEntry(small.entryId)).rejects.toMatchObject({ code: 'MODEL_NOT_AVAILABLE' });
+ await expect(auth.selectEntry(good.entryId, 'gpt-5.6-terra')).rejects.toMatchObject({ code: 'MODEL_NOT_AVAILABLE' });
+ expect((await auth.listSettingsEntries()).entries.map(row => [row.entryId, row.model]))
+ .toEqual([[small.entryId, 'gpt-5.6-terra'], [good.entryId, 'gpt-5.6-sol']]);
+ });
+
+ it('hides undersized external catalog choices before credentials can be saved', async () => {
+ await setDeepSeekEnabled(true);
+ const { clientConfig } = await import('../../../src/main/features/client_config');
+ clientConfig.applyServerPayload({ immediate: { model_catalog: { providers: { deepseek: [
+ { id: 'capacity-small', name: 'Small', contextWindow: 31999, maxTokens: 8192 },
+ { id: 'capacity-exact', name: 'Exact', contextWindow: 32000, maxTokens: 8192 },
+ ] } } }, restart: {}, config_hash: 'sha256:external-floor' }, '"external-floor"');
+ const auth = await import('../../../src/main/features/auth');
+ expect((await auth.listModels('deepseek')).models.map(row => row.id)).toEqual(['capacity-exact']);
+ await expect(auth.addApiKeyEntry('deepseek', 'capacity-small', 'synthetic', 'capacity'))
+ .rejects.toMatchObject({ code: 'MODEL_NOT_AVAILABLE' });
+ expect((await auth.listProviders()).providers.find(provider => provider.id === 'deepseek')?.profiles)
+ .toHaveLength(0);
+ });
+
+ it('defines localized capacity remediation in every registered desktop locale', async () => {
+ const root = path.resolve(__dirname, '../../../src/main/locales');
+ const { SUPPORTED_LANGS } = await import('../../../src/main/i18n');
+ for (const lang of SUPPORTED_LANGS) {
+ const message = JSON.parse(fs.readFileSync(path.join(root, `${lang}.json`), 'utf8'))['errors.model_context_too_small'];
+ expect(message, lang).toEqual(expect.stringContaining('{minimum}'));
+ }
+ });
+
+});
+
+
+
+function mockOAuthRefreshSuccess(providerId: string, providerName: string): ReturnType<typeof vi.fn> {
+ const refreshToken = vi.fn(async () => {
+ // Keep the promise pending for one microtask so concurrent callers have
+ // to share the same in-flight refresh rather than passing sequentially.
+ await Promise.resolve();
+ return {
+ access: 'renewed-access-token',
+ refresh: 'rotated-refresh-token',
+ expires: Date.now() + 60 * 60 * 1000,
+ };
+ });
+ vi.doMock('@earendil-works/pi-ai/oauth', () => {
+ const registry = new Map<string, any>();
+ registry.set(providerId, {
+ id: providerId,
+ name: providerName,
+ usesCallbackServer: true,
+ login: vi.fn(),
+ refreshToken,
+ getApiKey: (credentials: any) => credentials.access,
+ });
+ return {
+ getOAuthProvider: (id: string) => registry.get(id),
+ getOAuthProviders: () => Array.from(registry.values()),
+ registerOAuthProvider: (provider: any) => {
+ registry.set(provider.id, provider);
+ },
+ };
+ });
+ return refreshToken;
+}
+
+describe('auth public priority and forced OAuth recovery',()=>{
+it('exposes a forced OAuth refresh hook and coalesces concurrent refreshes', async () => {
+ const refreshToken = mockOAuthRefreshSuccess('openai-codex', 'OpenAI Codex');
+ await writeExpiredOAuthEntry({
+ providerId: 'openai-codex',
+ model: 'gpt-5.5',
+ // The local clock says this credential is still valid. The hook models
+ // the server-authoritative 401 recovery path.
+ expires: Date.now() + 60 * 60 * 1000,
+ });
+
+ const a = await import('../../../src/main/features/auth');
+ const [choice] = await a.pickChatEntryGroup();
+ expect(choice.apiKey).toBe('expired-access-token');
+ expect(choice.refreshApiKey).toEqual(expect.any(Function));
+
+ const [first, second] = await Promise.all([
+ choice.refreshApiKey!('expired-access-token'),
+ choice.refreshApiKey!('expired-access-token'),
+ ]);
+
+ expect(first).toBe('renewed-access-token');
+ expect(second).toBe('renewed-access-token');
+ expect(refreshToken).toHaveBeenCalledTimes(1);
+
+ // A staggered request that captured the same old access token reuses the
+ // replacement already on disk instead of rotating the refresh token again.
+ await expect(choice.refreshApiKey!('expired-access-token'))
+ .resolves.toBe('renewed-access-token');
+ expect(refreshToken).toHaveBeenCalledTimes(1);
+
+ const [renewedChoice] = await a.pickChatEntryGroup();
+ expect(renewedChoice.apiKey).toBe('renewed-access-token');
+ });
+it('keeps simultaneous OAuth refreshes bound to their account across an account switch', async () => {
+ const refreshToken = mockOAuthRefreshSuccess('openai-codex', 'OpenAI Codex');
+ let release!: () => void;
+ const held = new Promise<void>((resolve) => { release = resolve; });
+ refreshToken.mockImplementation(async (credentials) => {
+ await held;
+ return {
+ access: `${credentials.access}-renewed`, refresh: `${credentials.refresh}-rotated`,
+ expires: Date.now() + 3_600_000,
+ };
+ });
+ const secondUid = '88888888';
+ for (const uid of [TEST_UID, secondUid]) {
+ await writeExpiredOAuthEntry({
+ providerId: 'openai-codex', model: 'gpt-5.5', uid, expires: Date.now() + 3_600_000,
+ access: `${uid}-access`, refresh: `${uid}-refresh`,
+ });
+ }
+ const auth = await import('../../../src/main/features/auth');
+ const users = await import('../../../src/main/features/users');
+ const [firstChoice] = await auth.pickChatEntryGroup();
+ const first = firstChoice.refreshApiKey!(firstChoice.apiKey);
+ let second: Promise<string | undefined> | undefined;
+ try {
+ await vi.waitFor(() => expect(refreshToken).toHaveBeenCalledTimes(1));
+ users.activateUser(secondUid);
+ const [secondChoice] = await auth.pickChatEntryGroup();
+ second = secondChoice.refreshApiKey!(secondChoice.apiKey);
+ await new Promise((resolve) => setImmediate(resolve));
+ release();
+ expect(await Promise.all([first, second])).toEqual([
+ `${TEST_UID}-access-renewed`, `${secondUid}-access-renewed`,
+ ]);
+ expect(refreshToken).toHaveBeenCalledTimes(2);
+ const paths = await import('../../../src/main/paths');
+ const secrets = await import('../../../src/main/util/local-secret-store');
+ for (const uid of [TEST_UID, secondUid]) {
+ const saved = JSON.parse(secrets.decryptLocalSecret({
+ namespace: 'auth.profiles', ownerId: uid, recordId: 'auth-profiles.json',
+ }, fs.readFileSync(paths.userAuthProfilesFile(uid), 'utf8')));
+ expect(saved.profiles['openai-codex:default']).toMatchObject({
+ access: `${uid}-access-renewed`, refresh: `${uid}-refresh-rotated`,
+ });
+ }
+ } finally {
+ release();
+ await Promise.allSettled([first, ...(second ? [second] : [])]);
+ }
+ });
+it('does not let an old account refresh hook read the newly active account credential', async () => {
+ const refreshToken = mockOAuthRefreshSuccess('openai-codex', 'OpenAI Codex');
+ await writeExpiredOAuthEntry({
+ providerId: 'openai-codex', model: 'gpt-5.5', expires: Date.now() + 3_600_000,
+ });
+ const auth = await import('../../../src/main/features/auth');
+ const [choice] = await auth.pickChatEntryGroup();
+ await writeExpiredOAuthEntry({
+ providerId: 'openai-codex', model: 'gpt-5.5', uid: '88888888',
+ expires: Date.now() + 3_600_000, access: 'second-account-access',
+ });
+ const users = await import('../../../src/main/features/users');
+ users.activateUser('88888888');
+ await expect(choice.refreshApiKey!(choice.apiKey)).resolves.toBeUndefined();
+ expect(refreshToken).not.toHaveBeenCalled();
+ });
+it.each(['replaced', 'removed'])('discards a pending OAuth refresh when its credential was %s', async (change) => {
+ const refreshToken = mockOAuthRefreshSuccess('openai-codex', 'OpenAI Codex');
+ let release!: () => void;
+ const held = new Promise<void>((resolve) => { release = resolve; });
+ refreshToken.mockImplementation(async () => {
+ await held;
+ return { access: 'obsolete-access', refresh: 'obsolete-refresh', expires: Date.now() + 3_600_000 };
+ });
+ await writeExpiredOAuthEntry({
+ providerId: 'openai-codex', model: 'gpt-5.5', expires: Date.now() + 3_600_000,
+ });
+ const auth = await import('../../../src/main/features/auth');
+ const [choice] = await auth.pickChatEntryGroup();
+ const pending = choice.refreshApiKey!(choice.apiKey);
+ try {
+ await vi.waitFor(() => expect(refreshToken).toHaveBeenCalledTimes(1));
+ if (change === 'removed') {
+ await auth.removeCredential(choice.profileId);
+ } else {
+ await writeExpiredOAuthEntry({
+ providerId: 'openai-codex', model: 'gpt-5.5', expires: Date.now() + 3_600_000,
+ access: 'reauthorized-access', refresh: 'reauthorized-refresh',
+ });
+ }
+ release();
+ await expect(pending).resolves.toBeUndefined();
+ const paths = await import('../../../src/main/paths');
+ const secrets = await import('../../../src/main/util/local-secret-store');
+ const saved = JSON.parse(secrets.decryptLocalSecret({
+ namespace: 'auth.profiles', ownerId: TEST_UID, recordId: 'auth-profiles.json',
+ }, fs.readFileSync(paths.userAuthProfilesFile(TEST_UID), 'utf8')));
+ if (change === 'removed') expect(saved.profiles[choice.profileId]).toBeUndefined();
+ else expect(saved.profiles[choice.profileId]).toMatchObject({
+ access: 'reauthorized-access', refresh: 'reauthorized-refresh',
+ });
+ } finally {
+ release();
+ await Promise.allSettled([pending]);
+ }
+ });
+it('does not coalesce a reauthorized credential with its obsolete pending refresh', async () => {
+ const refreshToken = mockOAuthRefreshSuccess('openai-codex', 'OpenAI Codex');
+ let release!: () => void;
+ const held = new Promise<void>((resolve) => { release = resolve; });
+ refreshToken.mockImplementation(async (credentials) => {
+ await held;
+ return {
+ access: `${credentials.access}-renewed`, refresh: `${credentials.refresh}-rotated`,
+ expires: Date.now() + 3_600_000,
+ };
+ });
+ await writeExpiredOAuthEntry({
+ providerId: 'openai-codex', model: 'gpt-5.5', expires: Date.now() + 3_600_000,
+ });
+ const auth = await import('../../../src/main/features/auth');
+ const [oldChoice] = await auth.pickChatEntryGroup();
+ const old = oldChoice.refreshApiKey!(oldChoice.apiKey);
+ let current: Promise<string | undefined> | undefined;
+ try {
+ await vi.waitFor(() => expect(refreshToken).toHaveBeenCalledTimes(1));
+ await writeExpiredOAuthEntry({
+ providerId: 'openai-codex', model: 'gpt-5.5', expires: Date.now() + 3_600_000,
+ access: 'reauthorized-access', refresh: 'reauthorized-refresh',
+ });
+ const [newChoice] = await auth.pickChatEntryGroup();
+ current = newChoice.refreshApiKey!(newChoice.apiKey);
+ await new Promise((resolve) => setImmediate(resolve));
+ release();
+ expect(await Promise.all([old, current])).toEqual([undefined, 'reauthorized-access-renewed']);
+ expect(refreshToken).toHaveBeenCalledTimes(2);
+ const [saved] = await auth.pickChatEntryGroup();
+ expect(saved.apiKey).toBe('reauthorized-access-renewed');
+ } finally {
+ release();
+ await Promise.allSettled([old, ...(current ? [current] : [])]);
+ }
+ });
+it('bounds one coalesced server-rejection refresh and releases later attempts', async () => {
+ vi.useFakeTimers();
+ try {
+ let observedSignal: AbortSignal | undefined;
+ const refreshToken = vi.fn((
+ _credentials: { access: string; refresh: string; expires: number },
+ signal?: AbortSignal,
+ ) => {
+ observedSignal = signal;
+ return new Promise((_resolve, reject) => {
+ signal?.addEventListener('abort', () => reject(signal.reason), { once: true });
+ });
+ });
+ vi.doMock('@earendil-works/pi-ai/oauth', () => {
+ const provider = {
+ id: 'openai-codex',
+ name: 'OpenAI Codex',
+ usesCallbackServer: true,
+ login: vi.fn(),
+ refreshToken,
+ getApiKey: (credentials: any) => credentials.access,
+ };
+ return {
+ getOAuthProvider: (id: string) => id === provider.id ? provider : undefined,
+ getOAuthProviders: () => [provider],
+ registerOAuthProvider: vi.fn(),
+ };
+ });
+ await writeExpiredOAuthEntry({
+ providerId: 'openai-codex',
+ model: 'gpt-5.5',
+ expires: Date.now() + 60 * 60 * 1000,
+ });
+
+ const a = await import('../../../src/main/features/auth');
+ const [choice] = await a.pickChatEntryGroup();
+ const first = choice.refreshApiKey!('expired-access-token');
+ const second = choice.refreshApiKey!('expired-access-token');
+ const firstRejected = expect(first).rejects.toMatchObject({ code: 'OAUTH_REFRESH_TIMEOUT' });
+ const secondRejected = expect(second).rejects.toMatchObject({ code: 'OAUTH_REFRESH_TIMEOUT' });
+
+ await vi.advanceTimersByTimeAsync(59_999);
+ expect(observedSignal?.aborted).toBe(false);
+ expect(refreshToken).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1);
+
+ await Promise.all([firstRejected, secondRejected]);
+ expect(observedSignal?.aborted).toBe(true);
+
+ // The timed-out shared promise must leave the profile-level in-flight
+ // map so a later user turn can make one fresh recovery attempt.
+ const later = choice.refreshApiKey!('expired-access-token');
+ await vi.advanceTimersByTimeAsync(0);
+ expect(refreshToken).toHaveBeenCalledTimes(2);
+ const laterRejected = expect(later).rejects.toMatchObject({ code: 'OAUTH_REFRESH_TIMEOUT' });
+ await vi.advanceTimersByTimeAsync(60_000);
+ await laterRejected;
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+it('refreshes an expired OAuth profile once when it backs multiple model entries', async () => {
+ const refreshToken = mockOAuthRefreshSuccess('openai-codex', 'OpenAI Codex');
+ await writeExpiredOAuthEntry({ providerId: 'openai-codex', model: 'gpt-5.5' });
+
+ const a = await import('../../../src/main/features/auth');
+ await a.addEntry({
+ provider: 'openai-codex',
+ model: 'gpt-5.6-terra',
+ profileId: 'openai-codex:default',
+ });
+
+ const choices = await a.pickChatEntryGroup();
+
+ expect(choices).toHaveLength(2);
+ expect(choices.map((choice) => choice.apiKey)).toEqual([
+ 'renewed-access-token',
+ 'renewed-access-token',
+ ]);
+ expect(refreshToken).toHaveBeenCalledTimes(1);
+ });
+it('keeps same-model keys in the user order and only moves on when the first is unavailable', async () => {
+ const a = await import('../../../src/main/features/auth');
+ const fs = await import('node:fs');
+ const paths = await import('../../../src/main/paths');
+ const cd = await import('../../../src/main/model/core-agent/profile-cooldown');
+ cd._clearAll();
+ const p1 = await a.addApiKey('anthropic', 'k-1-xxxxxxxxxxx', 'one');
+ const p2 = await a.addApiKey('anthropic', 'k-2-xxxxxxxxxxx', 'two');
+ await a.addEntry({ provider: 'anthropic', model: 'claude-opus-4-8', profileId: p1.profileId });
+ await a.addEntry({ provider: 'anthropic', model: 'claude-opus-4-8', profileId: p2.profileId });
+ const userOrder = (await a.listEntries()).entries.map((entry) => entry.entryId);
+ const file = paths.userAuthProfilesFile(TEST_UID);
+ const before = fs.readFileSync(file);
+
+ // Repeated successful picks do not rotate keys or rewrite credentials.
+ const first = await a.pickChatEntry();
+ const second = await a.pickChatEntry();
+ expect(first?.entryId).toBe(userOrder[0]);
+ expect(second?.entryId).toBe(userOrder[0]);
+ expect((await a.pickChatEntryGroup()).map((choice) => choice.entryId)).toEqual(userOrder);
+ expect(fs.readFileSync(file).equals(before)).toBe(true);
+
+ // Only an unavailable first key moves selection to the next one.
+ cd.markCooldown(first!.profileId, 'auth', 'mocked 401');
+ expect((await a.pickChatEntry())?.entryId).toBe(userOrder[1]);
+ cd._clearAll();
+ });
+});
+
+describe('public availability remediation', () => {
+ it('keeps a saved disabled provider visible for deletion without advertising it as selectable', async () => {
+ const auth = await import('../../../src/main/features/auth');
+ const saved = await auth.addApiKeyEntry('deepseek', 'deepseek-flash', 'synthetic-policy-key');
+ await setDeepSeekEnabled(false);
+ expect((await auth.listEntries({ includeUnavailable: true })).entries.find(row => row.entryId === saved.entryId))
+ .toMatchObject({ selectable: false, availability: 'service_disabled', profileAvailable: true });
+ expect((await auth.listComposerEntries()).entries).toEqual([]);
+ await auth.removeEntry(saved.entryId);
+ expect((await auth.listSettingsEntries()).entries).toEqual([]);
+ });
+});
diff --git a/test/main/features/client_config.test.ts b/test/main/features/client_config.test.ts
index 3982aac0..a1825c25 100644
--- a/test/main/features/client_config.test.ts
+++ b/test/main/features/client_config.test.ts
@@ -78,7 +78,7 @@ describe('client_config', () => {
google: { model: 'fixture-image', api: 'gemini', supports_edit: true },
} } }, restart: {}, config_hash: 'fixture-image-edit' }, 'fixture-image-edit');
expect(getConfiguredImageGenCapability('google')).toMatchObject({ model: 'fixture-image', supportsEdit: true });
- expect(DEFAULT_IMAGE_GEN_BY_PROVIDER.doubao.model).toBe('doubao-seedream-5-0-lite-260128');
+ expect(DEFAULT_IMAGE_GEN_BY_PROVIDER.doubao.model).toBe('doubao-seedream-5-0-flash-260915');
// The normalized camelCase form is read again through the same catalog path.
expect(getConfiguredImageGenCapability('google')).toMatchObject({ supportsEdit: true });
});
diff --git a/test/main/model/core-agent/custom-model-protocol.test.ts b/test/main/model/core-agent/custom-model-protocol.test.ts
index 8035c5dc..42c5e162 100644
--- a/test/main/model/core-agent/custom-model-protocol.test.ts
+++ b/test/main/model/core-agent/custom-model-protocol.test.ts
@@ -17,6 +17,67 @@ function anthropicSuccess() {
}
afterEach(() => vi.restoreAllMocks());
describe('custom model protocol wire contract', () => {
+ it('round-trips custom Responses tools and images through the real SDK', async () => {
+ const wires: any[] = [];
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => {
+ wires.push(JSON.parse(String(init?.body)));
+ const first = wires.length === 1;
+ const item = first ? { type: 'function_call', id: 'fc_lookup', call_id: 'call_lookup', name: 'lookup', arguments: '{"key":"42"}', status: 'completed' }
+ : { type: 'message', id: 'msg_done', role: 'assistant', status: 'completed', content: [{ type: 'output_text', text: 'Ready: 5827', annotations: [] }] };
+ const response = { id: 'resp_fixture', status: 'completed', model: config.modelId, output: [item], usage: { input_tokens: 3, output_tokens: 2 } };
+ const events = [{ type: 'response.created', response: { ...response, output: [] } },
+ { type: 'response.output_item.added', output_index: 0, item: first ? { ...item, arguments: '' } : { ...item, content: [] } },
+ ...(first ? [{ type: 'response.function_call_arguments.delta', output_index: 0, delta: '{"key":"42"}' }]
+ : [{ type: 'response.content_part.added', output_index: 0, content_index: 0, part: { type: 'output_text', text: '', annotations: [] } },
+ { type: 'response.output_text.delta', output_index: 0, content_index: 0, delta: 'Ready: 5827' }]),
+ { type: 'response.output_item.done', output_index: 0, item }, { type: 'response.completed', response }];
+ return new Response(events.map(e => `data: ${JSON.stringify(e)}\n\n`).join(''), { headers: { 'content-type': 'text/event-stream' } });
+ });
+ const provider = await createCustomOpenAICompatibleProvider({ ...config, protocol: 'responses', supportsVision: true });
+ const schema = { type: 'object', properties: { key: { type: 'string' }, limit: { type: 'integer' } }, required: ['key'] };
+ const input: any = { model: config.modelId, maxTokens: 512,
+ tools: [{ name: 'lookup', description: 'Read status', inputSchema: schema }],
+ messages: [{ role: 'user', content: [{ type: 'text', text: 'Read status' }, { type: 'image', mediaType: 'image/png', data: 'aGVsbG8=' }] }] };
+ const first = await provider.complete(input);
+ const call: any = first.content.find(b => b.type === 'tool_use');
+ expect(call).toMatchObject({ name: 'lookup', input: { key: '42' } });
+ input.messages.push({ role: 'assistant', content: first.content }, { role: 'user', content: [{ type: 'tool_result', toolUseId: call.id, content: 'Ready: 5827' }] });
+ expect((await provider.complete(input)).content).toContainEqual(expect.objectContaining({ type: 'text', text: 'Ready: 5827' }));
+ expect(wires).toHaveLength(2);
+ expect(wires[0].tools[0]).toMatchObject({ type: 'function', name: 'lookup', strict: false, parameters: schema });
+ expect(wires[0].input[0].content).toContainEqual(expect.objectContaining({ type: 'input_image', image_url: 'data:image/png;base64,aGVsbG8=' }));
+ const output = wires[1].input.find((x: any) => x.type === 'function_call_output');
+ expect(output).toMatchObject({ call_id: 'call_lookup', output: expect.stringContaining('5827') });
+ });
+ it.each(['complete', 'stream', 'validateAuth'] as const)('uses Responses for a custom %s without Chat compatibility rewriting', async mode => {
+ const calls: any[] = [];
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (url, init) => {
+ calls.push({ url: String(url), body: JSON.parse(String(init?.body)), headers: new Headers(init?.headers) });
+ const response = { id: 'resp_fixture', object: 'response', status: 'completed', model: config.modelId,
+ output: [{ type: 'message', id: 'msg_fixture', role: 'assistant', status: 'completed', content: [{ type: 'output_text', text: 'hello', annotations: [] }] }],
+ usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 } };
+ const events = [{ type: 'response.created', response: { ...response, status: 'in_progress', output: [] } },
+ { type: 'response.output_item.added', output_index: 0, item: { ...response.output[0], content: [] } },
+ { type: 'response.content_part.added', output_index: 0, content_index: 0, part: { type: 'output_text', text: '', annotations: [] } },
+ { type: 'response.output_text.delta', output_index: 0, content_index: 0, delta: 'hello' },
+ { type: 'response.output_item.done', output_index: 0, item: response.output[0] },
+ { type: 'response.completed', response }];
+ return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(''), { headers: { 'content-type': 'text/event-stream' } });
+ });
+ const provider = await createCustomOpenAICompatibleProvider({ ...config, protocol: 'responses', supportsReasoning: true, reasoningEffort: 'medium' });
+ if (mode === 'complete') expect((await provider.complete(params)).content).toContainEqual(expect.objectContaining({ type: 'text', text: 'hello' }));
+ else if (mode === 'validateAuth') expect(await provider.validateAuth()).toBe(true);
+ else { const events = []; for await (const e of provider.stream(params)) events.push(e); expect(events).toContainEqual({ type: 'text_delta', text: 'hello' }); }
+ expect(calls).toHaveLength(1);
+ expect(new URL(calls[0].url).pathname).toBe('/responses');
+ expect(calls[0].headers.get('authorization')).toBe(`Bearer ${config.apiKey}`);
+ expect(calls[0].body.input).toBeInstanceOf(Array);
+ expect(calls[0].body.messages).toBeUndefined();
+ expect(calls[0].body.max_tokens).toBeUndefined();
+ expect(calls[0].body.max_completion_tokens).toBeUndefined();
+ expect(calls[0].body.max_output_tokens).toBe(mode === 'validateAuth' ? 16 : 512);
+ expect(calls[0].body.reasoning?.effort).toBe(mode === 'validateAuth' ? 'none' : 'medium');
+ });
it.each(['complete', 'stream', 'validateAuth'] as const)('dispatches a clean Anthropic %s request through the real SDK', async mode => {
const calls: any[] = [];
vi.spyOn(globalThis, 'fetch').mockImplementation(async (url, init) => {
diff --git a/test/main/model/core-agent/external-provider-request-parity.test.ts b/test/main/model/core-agent/external-provider-request-parity.test.ts
index 117a62b8..ab18bd1b 100644
--- a/test/main/model/core-agent/external-provider-request-parity.test.ts
+++ b/test/main/model/core-agent/external-provider-request-parity.test.ts
@@ -26,7 +26,7 @@ describe('external provider request policy', () => {
expect(configs.at(-1).customModel).toMatchObject({ id: modelId, reasoning: true });
if (modelId === 'deepseek-flash') {
expect(configs.at(-1).customModel).toMatchObject({
- name: 'DeepSeek V4.1 Flash', input: ['text', 'image'], contextWindow: 1_048_576, maxTokens: 384_000,
+ name: 'DeepSeek V4.1 Flash', input: ['text', 'image'], contextWindow: 1_000_000, maxTokens: 128_000,
});
}
});
diff --git a/test/main/model/core-agent/external-providers.test.ts b/test/main/model/core-agent/external-providers.test.ts
index ed79dda8..a5d89cf2 100644
--- a/test/main/model/core-agent/external-providers.test.ts
+++ b/test/main/model/core-agent/external-providers.test.ts
@@ -8,6 +8,7 @@ import {
buildOrkasApiModel,
createMoonshotProvider,
repairDeepSeekPayload,
+ repairDeepSeekRequest,
} from '../../../../src/main/model/core-agent/external-providers';
import { isSelectableModel, modelInputImageLimit } from '../../../../src/main/model/provider_catalog';
@@ -31,7 +32,7 @@ describe('external-providers › custom OpenAI-compatible model', () => {
}).input).toEqual(['text']);
});
- it('keeps documented DeepSeek text aliases text-only without hiding vision variants', () => {
+ it('honors custom endpoint vision declarations independently of vendor-like model names', () => {
for (const modelId of [
'deepseek-chat',
'deepseek-reasoner',
@@ -42,7 +43,7 @@ describe('external-providers › custom OpenAI-compatible model', () => {
expect(buildCustomOpenAICompatibleModel(modelId, {
...runtimeConfig,
supportsVision: true,
- }).input).toEqual(['text']);
+ }).input).toEqual(['text', 'image']);
}
expect(buildCustomOpenAICompatibleModel(
'deepseek-v4-flash-vision-exp',
@@ -96,8 +97,8 @@ describe('external-providers › DeepSeek model capabilities', () => {
expect(buildDeepSeekModel(modelId)).toMatchObject({
id: modelId,
input: ['text'],
- contextWindow: 1_048_576,
- maxTokens: 384_000,
+ contextWindow: 1_000_000,
+ maxTokens: 128_000,
});
}
});
@@ -107,8 +108,8 @@ describe('external-providers › DeepSeek model capabilities', () => {
expect(model).toMatchObject({
name: 'DeepSeek V4 Flash Vision',
input: ['text', 'image'],
- contextWindow: 1_048_576,
- maxTokens: 384_000,
+ contextWindow: 1_000_000,
+ maxTokens: 128_000,
});
expect(modelInputImageLimit('deepseek', 'deepseek-v4-flash-vision-exp', model)).toBe(20);
});
@@ -120,7 +121,7 @@ describe('external-providers › DeepSeek model capabilities', () => {
id: 'deepseek-flash', name: 'DeepSeek V4.1 Flash',
api: 'openai-completions', baseUrl: 'https://api.deepseek.com/v1',
reasoning: true, input: ['text', 'image'],
- contextWindow: 1_048_576, maxTokens: 384_000,
+ contextWindow: 1_000_000, maxTokens: 128_000,
});
expect(modelInputImageLimit('deepseek', 'deepseek-flash', model)).toBe(20);
});
@@ -142,7 +143,7 @@ describe('external-providers › buildMoonshotModel', () => {
});
it('uses known context windows and falls back to 131072 for unknown ids', () => {
- expect(buildMoonshotModel('kimi-k3').contextWindow).toBe(1048576);
+ expect(buildMoonshotModel('kimi-k3').contextWindow).toBe(1000000);
expect(buildMoonshotModel('kimi-k3').maxTokens).toBe(131072);
expect(buildMoonshotModel('kimi-k2.7-code').contextWindow).toBe(262144);
expect(buildMoonshotModel('kimi-k2.6').contextWindow).toBe(262144);
@@ -266,3 +267,13 @@ describe('external-providers › DeepSeek request compatibility', () => {
expect(mixed.reasoning_effort).toBe('medium');
expect(mixed.thinking).toEqual({ type: 'enabled' });
});
+
+describe('DeepSeek host reservation wire boundary',()=>{
+ it('drops only a marked model-default reservation, preserving explicit and auxiliary caps',()=>{
+ const request={max_tokens:128000,messages:[{role:'user',content:'Hello'}]};
+ expect(repairDeepSeekRequest(request,{maxTokens:128000},{outputLimitSource:'model_default'})).not.toHaveProperty('max_tokens');
+ expect(repairDeepSeekRequest(request,{maxTokens:128000})).toHaveProperty('max_tokens',128000);
+ expect(repairDeepSeekRequest({...request,max_tokens:512},{maxTokens:128000},{outputLimitSource:'model_default'})).toHaveProperty('max_tokens',512);
+ expect(request.max_tokens).toBe(128000);
+ });
+});
diff --git a/test/main/model/provider_catalog.test.ts b/test/main/model/provider_catalog.test.ts
index 4c148c09..9f581537 100644
--- a/test/main/model/provider_catalog.test.ts
+++ b/test/main/model/provider_catalog.test.ts
@@ -11,11 +11,16 @@ import {
OAUTH_ALIAS_FOR,
EXTRA_LABELS,
isVisibleProvider,
+ isKnownModelProvider,
+ isUserAddableProvider,
providerLabel,
providerDocsUrl,
providerSubscriptionNote,
sortProviderIds,
curatedModelsFor,
+ configuredOpenAICompatibleProviders,
+ getConfiguredOpenAICompatibleProvider,
+ isExternalApiProvider,
modelInputFromConfiguredCapabilities,
modelInputImageLimit,
resolveConfiguredPiModel,
@@ -801,3 +806,159 @@ describe('provider_catalog › pickLatestGenerations (fallback)', () => {
}
}
});
+
+describe('configured provider trust boundary',()=>{it('accepts safe Server-configured providers and rejects unsafe or reserved definitions', async () => {
+ const users = await import('../../../src/main/features/users');
+ const paths = await import('../../../src/main/paths');
+ const storage = await import('../../../src/main/storage');
+ const uid = 'configuredopenaiproviders';
+ users.activateUser(uid);
+ const file = paths.userRemoteConfigFile(uid);
+ storage.writeJsonSync(file, {
+ version: 1,
+ active: {
+ immediate: {
+ model_catalog: {
+ providers: {
+ acme: [
+ { id: 'acme-vision', name: 'Acme Vision', supportsVision: true, maxInputImages: 12 },
+ { id: 'acme-default', name: 'Acme Default' },
+ { id: 'acme-text', name: 'Acme Text', supportsVision: false },
+ ],
+ unsafe: [{ id: 'unsafe-model', name: 'Unsafe Model' }],
+ conflict: [{ id: 'conflict-model', supportsVision: false, maxInputImages: 3 }],
+ },
+ openai_compatible_providers: {
+ acme: {
+ label: 'Acme AI',
+ baseUrl: 'https://api.acme.example/v1/',
+ docsUrl: 'https://docs.acme.example/keys',
+ },
+ unsafe: { label: 'Unsafe', baseUrl: 'http://127.0.0.1:9000/v1' },
+ conflict: { label: 'Conflict', baseUrl: 'https://api.conflict.example/v1' },
+ openai: { label: 'Imposter', baseUrl: 'https://evil.example/v1' },
+ },
+ },
+ },
+ },
+ });
+ try {
+ expect(configuredOpenAICompatibleProviders()).toEqual([{
+ id: 'acme',
+ label: 'Acme AI',
+ baseUrl: 'https://api.acme.example/v1',
+ docsUrl: 'https://docs.acme.example/keys',
+ }]);
+ expect(getConfiguredOpenAICompatibleProvider('acme')).toMatchObject({ label: 'Acme AI' });
+ expect(getConfiguredOpenAICompatibleProvider('unsafe')).toBeNull();
+ expect(getConfiguredOpenAICompatibleProvider('conflict')).toBeNull();
+ expect(getConfiguredOpenAICompatibleProvider('openai')).toBeNull();
+ expect(isVisibleProvider('acme')).toBe(true);
+ expect(isKnownModelProvider('acme')).toBe(true);
+ expect(isUserAddableProvider('acme')).toBe(true);
+ expect(isExternalApiProvider('acme')).toBe(true);
+ expect(providerLabel('acme')).toBe('Acme AI');
+ expect(providerDocsUrl('acme')).toBe('https://docs.acme.example/keys');
+ expect(isSelectableModel('acme', 'acme-vision')).toBe(true);
+ expect(isSelectableModel('acme', 'not-configured')).toBe(false);
+ expect(curatedModelsFor('acme')).toEqual([
+ { id: 'acme-vision', name: 'Acme Vision', supportsVision: true, maxInputImages: 12 },
+ { id: 'acme-default', name: 'Acme Default' },
+ { id: 'acme-text', name: 'Acme Text', supportsVision: false },
+ ]);
+ } finally {
+ fs.rmSync(path.dirname(file), { recursive: true, force: true });
+ }
+ });});
+
+describe('current public model upgrade aliases', () => {
+ it.each([
+ ['openai', 'gpt-5.4', 'gpt-5.6-sol'],
+ ['openai-codex', 'gpt-5.4', 'gpt-5.6-sol'],
+ ['google', 'gemini-3.6-flash', 'gemini-3.8-flash'],
+ ['doubao', 'doubao-seed-2-1-pro-260628', 'doubao-seed-2-1-pro-260915'],
+ ['openrouter', 'qwen/qwen3.7-max', 'qwen/qwen3.8-max-0902'],
+ ])('upgrades %s %s only into an available public catalog row', (provider, oldId, expected) => {
+ expect(resolveModelUpgrade(provider, oldId)).toMatchObject({ modelId: expected, upgraded: true });
+ });
+});
+
+describe('configured provider capability declaration',()=>{
+it('accepts the complete capability-field matrix and rejects conflicts or invalid field types', async () => {
+ const users = await import('../../../src/main/features/users');
+ const paths = await import('../../../src/main/paths');
+ const storage = await import('../../../src/main/storage');
+ const uid = 'configuredcapabilitymatrix';
+ users.activateUser(uid);
+ const file = paths.userRemoteConfigFile(uid);
+ const cases: Array<{
+ id: string;
+ supportsVision?: unknown;
+ maxInputImages?: unknown;
+ accepted: boolean;
+ }> = [
+ { id: 'omitted-omitted', accepted: true },
+ { id: 'omitted-zero', maxInputImages: 0, accepted: true },
+ { id: 'omitted-positive', maxInputImages: 12, accepted: true },
+ { id: 'true-omitted', supportsVision: true, accepted: true },
+ { id: 'true-zero', supportsVision: true, maxInputImages: 0, accepted: false },
+ { id: 'true-positive', supportsVision: true, maxInputImages: 12, accepted: true },
+ { id: 'false-omitted', supportsVision: false, accepted: true },
+ { id: 'false-zero', supportsVision: false, maxInputImages: 0, accepted: true },
+ { id: 'false-positive', supportsVision: false, maxInputImages: 12, accepted: false },
+ { id: 'invalid-omitted', supportsVision: 'yes', accepted: false },
+ { id: 'invalid-zero', supportsVision: 'yes', maxInputImages: 0, accepted: false },
+ { id: 'invalid-positive', supportsVision: 'yes', maxInputImages: 12, accepted: false },
+ { id: 'invalid-invalid', supportsVision: 'yes', maxInputImages: '12', accepted: false },
+ { id: 'omitted-invalid', maxInputImages: '12', accepted: false },
+ { id: 'true-invalid', supportsVision: true, maxInputImages: '12', accepted: false },
+ { id: 'false-invalid', supportsVision: false, maxInputImages: '12', accepted: false },
+ { id: 'negative-limit', maxInputImages: -1, accepted: false },
+ { id: 'fractional-limit', maxInputImages: 1.5, accepted: false },
+ { id: 'boolean-limit', maxInputImages: true, accepted: false },
+ { id: 'null-limit', maxInputImages: null, accepted: false },
+ { id: 'object-limit', maxInputImages: { count: 12 }, accepted: false },
+ ];
+ const models = Object.fromEntries(cases.map((entry) => [entry.id, [{
+ id: `${entry.id}-model`,
+ ...(entry.supportsVision !== undefined ? { supportsVision: entry.supportsVision } : {}),
+ ...('maxInputImages' in entry ? { maxInputImages: entry.maxInputImages } : {}),
+ }]]));
+ const definitions = Object.fromEntries(cases.map((entry) => [entry.id, {
+ label: entry.id,
+ baseUrl: `https://api.${entry.id}.example/v1`,
+ }]));
+ storage.writeJsonSync(file, {
+ version: 1,
+ active: {
+ immediate: {
+ model_catalog: {
+ providers: models,
+ openai_compatible_providers: definitions,
+ },
+ },
+ },
+ });
+ try {
+ expect(configuredOpenAICompatibleProviders().map((provider) => provider.id)).toEqual(
+ cases.filter((entry) => entry.accepted).map((entry) => entry.id),
+ );
+ for (const entry of cases) {
+ const provider = getConfiguredOpenAICompatibleProvider(entry.id);
+ if (entry.accepted) {
+ expect(provider, entry.id).not.toBeNull();
+ } else {
+ expect(provider, entry.id).toBeNull();
+ }
+ }
+ expect(curatedModelsFor('false-zero')).toEqual([{
+ id: 'false-zero-model',
+ name: 'false-zero-model',
+ supportsVision: false,
+ maxInputImages: 0,
+ }]);
+ } finally {
+ fs.rmSync(path.dirname(file), { recursive: true, force: true });
+ }
+ });
+});
diff --git a/test/main/model/runner.test.ts b/test/main/model/runner.test.ts
index 0eb563af..051be588 100644
--- a/test/main/model/runner.test.ts
+++ b/test/main/model/runner.test.ts
@@ -3517,3 +3517,65 @@ describe('runner › bounded Skill creation correction', () => {
expect(complete).toHaveBeenCalledTimes(1);
});
});
+
+describe('runner public configured model and credential recovery', () => {
+ it('builds a declared API-key provider with its configured endpoint and model budget', async () => {
+ const createPiProvider = vi.fn(({ provider, customModel }: any) => ({ id: provider, name: 'Declared provider',
+ async *stream() { yield { type: 'text_delta' as const, text: 'ok' }; yield { type: 'message_end' as const, model: customModel.id, stopReason: 'end_turn' as const }; },
+ complete: vi.fn(), validateAuth: vi.fn() }));
+ vi.doMock('#core-agent', async () => ({ ...await vi.importActual<any>('#core-agent'), createPiProvider }));
+ const { clientConfig } = await import('../../../src/main/features/client_config');
+ clientConfig.applyServerPayload({ immediate: { model_catalog: {
+ providers: { acme: [{ id: 'acme-vision', contextWindow: 96000, maxTokens: 8192, supportsVision: true }] },
+ openai_compatible_providers: { acme: { label: 'Acme', baseUrl: 'https://api.acme.example/v1' } },
+ } }, restart: {}, config_hash: 'declared-runner' }, 'declared-runner');
+ const auth = await import('../../../src/main/features/auth');
+ await auth.addApiKeyEntry('acme', 'acme-vision', 'synthetic-declared-key');
+ expect(await auth.getChatPreloadApi()).toBe('openai-completions');
+ const { buildRunner } = await loadRunner();
+ const built = await buildRunner({ sessionId: 'gconv-declared-runner', userId: RUNNER_TEST_UID });
+ for await (const _ of (built.runner as any).providers.get('acme').stream({ messages: [{ role: 'user', content: [{ type: 'text', text: 'hello' }] }] })) { }
+ expect(createPiProvider).toHaveBeenCalledOnce();
+ expect(createPiProvider).toHaveBeenCalledWith(expect.objectContaining({ provider: 'acme', apiKey: 'synthetic-declared-key',
+ customModel: expect.objectContaining({ api: 'openai-completions', baseUrl: 'https://api.acme.example/v1', contextWindow: 96000, maxTokens: 8192, input: ['text', 'image'] }) }));
+ });
+
+ it('rebuilds the same OAuth candidate with the replacement key after one upstream 401', async () => {
+ const used: string[] = [];
+ const createPiProvider = vi.fn(({ provider, apiKey }: any) => ({ id: provider, name: 'OAuth recovery',
+ complete: async () => { used.push(apiKey); if (apiKey === 'synthetic-old') throw Object.assign(new Error('Unauthorized'), { status: 401 });
+ return { role: 'assistant', model: 'gpt-5.6-sol', content: [{ type: 'text', text: 'recovered' }], stopReason: 'end_turn' }; },
+ stream: vi.fn(), validateAuth: vi.fn() }));
+ vi.doMock('#core-agent', async () => ({ ...await vi.importActual<any>('#core-agent'), createPiProvider }));
+ const auth = await import('../../../src/main/features/auth');
+ const refreshApiKey = vi.fn(async (rejected: string) => rejected === 'synthetic-old' ? 'synthetic-new' : undefined);
+ vi.spyOn(auth, 'pickChatEntryGroup').mockResolvedValue([{ entryId: 'refresh-entry', profileId: 'oauth-recovery-owner', provider: 'openai', model: 'gpt-5.6-sol', apiKey: 'synthetic-old', refreshApiKey }]);
+ const { buildRunner } = await loadRunner();
+ const built = await buildRunner({ sessionId: 'gconv-public-oauth-recovery', userId: RUNNER_TEST_UID });
+ const result = await (built.runner as any).providers.get('openai').complete({ model: 'gpt-5.6-sol', messages: [{ role: 'user', content: [{ type: 'text', text: 'hello' }] }] });
+ expect(result.content).toContainEqual({ type: 'text', text: 'recovered' });
+ expect(used).toEqual(['synthetic-old', 'synthetic-new']);
+ expect(refreshApiKey).toHaveBeenCalledExactlyOnceWith('synthetic-old');
+ expect(createPiProvider).toHaveBeenCalledTimes(2);
+ expect((await import('../../../src/main/model/core-agent/profile-cooldown')).getCooldown('oauth-recovery-owner')).toBeUndefined();
+ });
+});
+
+describe('runner legacy capacity remediation', () => {
+ it('explains an all-small saved configuration before constructing a model provider', async () => {
+ const paths = await import('../../../src/main/paths');
+ const secrets = await import('../../../src/main/util/local-secret-store');
+ const file = paths.userAuthProfilesFile(RUNNER_TEST_UID);
+ const context = { namespace: 'auth.profiles', ownerId: RUNNER_TEST_UID, recordId: 'auth-profiles.json' };
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, secrets.encryptLocalSecret(context, JSON.stringify({ version: 6, profiles: {
+ 'custom:small': { type: 'api_key', provider: 'custom', label: 'small', key: 'synthetic-small', baseUrl: 'https://capacity.example/v1', contextWindow: 31999, maxTokens: 8192, createdAt: 1, lastUsed: 0 },
+ }, entries: [{ entryId: 'small-entry', provider: 'custom', profileId: 'custom:small', model: 'small-fixture', createdAt: 1, lastUsed: 0 }] })));
+ const before = fs.readFileSync(file, 'utf8');
+ const { t } = await import('../../../src/main/i18n');
+ const { buildRunner } = await loadRunner();
+ await expect(buildRunner({ sessionId: 'gconv-small-remediation', userId: RUNNER_TEST_UID }))
+ .rejects.toThrow(t('errors.model_context_too_small', { minimum: 32000 }));
+ expect(fs.readFileSync(file, 'utf8')).toBe(before);
+ });
+});