diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a44a454..905d99d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ from the section of its version (`scripts/releases/notes.ts`); a release without one fails. At tag time, rename `[Unreleased]` to the version and date, like `## [0.4.16] - 2026-10-24`. +## [Unreleased] + +### Fixed + +- Claude models a plan can't run (for example Fable or Mythos on a plan without them) no longer show as available on that account. The hub learns it from the plan's refusal or CLIProxyAPI's "not supported" cooldown on that account, lists that account's row under Not available ("Not on the neu plan"), and routes the model to an account that can run it. It asks again after a day, or as soon as the account is signed in again. + ## [0.4.99] - 2026-11-13 ### Changed diff --git a/packages/android/client/src/test/kotlin/dev/conclave/client/PickerTabsTest.kt b/packages/android/client/src/test/kotlin/dev/conclave/client/PickerTabsTest.kt index e29a9440..c94df816 100644 --- a/packages/android/client/src/test/kotlin/dev/conclave/client/PickerTabsTest.kt +++ b/packages/android/client/src/test/kotlin/dev/conclave/client/PickerTabsTest.kt @@ -63,6 +63,25 @@ class PickerTabsTest { assertTrue(PickerTabs.items(entries, "", Tab.ALL).none { it is Item.Fold }) } + @Test + fun oneClaudePlanWithoutAModelHasItsRowInTheFoldTheOtherPlanKeepsIt() { + // as the hub merges it (providers/merge.ts): neu's row is its own and unavailable, personal's a route of the model + val bare = ModelInfo(id = "claude-mythos-5-1", ref = "cliproxy/claude-mythos-5-1", provider = "cliproxy", name = "Claude Mythos 5.1", via = "your Claude plan", choices = listOf("cliproxy/personal/claude-mythos-5-1")) + val personal = ModelInfo(id = "personal/claude-mythos-5-1", ref = "cliproxy/personal/claude-mythos-5-1", provider = "cliproxy", name = "Claude Mythos 5.1", sameAs = "cliproxy/claude-mythos-5-1") + val neu = ModelInfo(id = "neu/claude-mythos-5-1", ref = "cliproxy/neu/claude-mythos-5-1", provider = "cliproxy", name = "Claude Mythos 5.1", unavailable = "Not on the neu plan") + val list = PickerTabs.entries(ModelPicks.groups(listOf(g("cliproxy", bare, personal, neu, m("cliproxy", "claude-opus-5-5", "Claude Opus 5.5"))))) + val open = PickerTabs.items(list, "", Tab.ANTHROPIC, unavailable = true) + val row = open.filterIsInstance().last() + assertEquals("cliproxy/neu/claude-mythos-5-1", row.entry.row.ref) + assertEquals("Not on the neu plan", row.entry.row.model.unavailable) + assertEquals(Item.Fold(PickerTabs.NOT_AVAILABLE, 1, open = true), open[open.size - 2]) + // the model itself is still offered, through personal + val shut = PickerTabs.items(list, "", Tab.ANTHROPIC) + val mythos = shut.filterIsInstance().first { it.entry.row.ref == "cliproxy/claude-mythos-5-1" } + assertEquals(null, mythos.entry.row.model.unavailable) + assertEquals(listOf("cliproxy/claude-mythos-5-1", "cliproxy/personal/claude-mythos-5-1"), mythos.entry.row.routes.map { it.ref }) + } + @Test fun eachModelInItsTabLocalByServerAndCodingAgentsApart() { val tabOf = entries.associate { it.row.ref to it.tab } diff --git a/packages/cli/src/commands/data.ts b/packages/cli/src/commands/data.ts index 793c513c..36e64442 100644 --- a/packages/cli/src/commands/data.ts +++ b/packages/cli/src/commands/data.ts @@ -149,7 +149,7 @@ export async function modelsCommand(args: ParsedArgs): Promise { ' ' + p.fg(modelColor(m.ref))('●') + ' ' + (m.name || m.ref), p.dim(m.ref), p.dim(m.contextWindow ? formatTokens(m.contextWindow) + ' ctx' : ''), - p.dim(m.via ?? (m.inputPrice || m.outputPrice ? `$${m.inputPrice}/$${m.outputPrice} per M` : '')), + m.unavailable ? p.yellow(m.unavailable) : p.dim(m.via ?? (m.inputPrice || m.outputPrice ? `$${m.inputPrice}/$${m.outputPrice} per M` : '')), p.dim([m.vision ? 'vision' : '', m.thinking ? 'thinking' : '', m.tier ?? ''].filter(Boolean).join(' ')), ]); print(table(rows)); diff --git a/packages/core/src/accounts/service.ts b/packages/core/src/accounts/service.ts index 68ee1622..c2eb8251 100644 --- a/packages/core/src/accounts/service.ts +++ b/packages/core/src/accounts/service.ts @@ -58,8 +58,10 @@ export interface CliproxyCredentialFacts { /** Merged from the last response's signals and the usage endpoint. */ windows: LimitWindow[]; cooldowns: Array<{ model?: string; reason: string; until: number }>; - /** Undefined until read. */ + /** Undefined until read. Without the models in notOn. */ models?: Array<{ id: string; name?: string }>; + /** Models CLIProxyAPI still gives this plan that it cannot run (its plan refused them): a bare id must not reach it. */ + notOn?: string[]; /** A ChatGPT plan approved for Daybreak: the programs whose alias its own model list has. */ daybreak?: CyberProgram[]; observedAt?: number; @@ -113,7 +115,7 @@ export class AccountsService { private spent = new Map(); private sticky = new Map(); private hitListeners = new Set<(vendor: string) => void>(); - private refusalListeners = new Set<(provider: string, model: string, reason: string) => void>(); + private refusalListeners = new Set<(provider: string, model: string, reason: string, account?: string) => void>(); private changeListeners = new Set<() => void>(); private lastEvent = ''; private lastLimits = new Map(); @@ -591,7 +593,12 @@ export class AccountsService { // the owner's order puts a key here: the key's turn comes first if (a.cfg.kind !== 'subscription' || a.provider !== gw) return undefined; const label = this.label(a, all); - if (bareReaches(a)) return { wire: model, account: a.cfg.id, label, covers: this.forVendor(vendor, model).filter(bareReaches).map((x) => x.cfg.id) }; + if (bareReaches(a)) { + // a plan that cannot run it still has it in CLIProxyAPI's shared list: name this plan, so the bare id is not sent there + const stray = all.some((x) => x.cfg.id !== a.cfg.id && x.provider === gw && x.facts?.notOn?.includes(bareModel(model))); + if (stray && a.facts?.prefix) return { wire: `${a.facts.prefix}/${bareModel(model)}`, account: a.cfg.id, label, covers: [a.cfg.id] }; + return { wire: model, account: a.cfg.id, label, covers: this.forVendor(vendor, model).filter(bareReaches).map((x) => x.cfg.id) }; + } const own = a.facts?.prefix && a.facts.models ? ownModel(a.facts.models.map((m) => m.id), model) : undefined; if (own) return { wire: `${a.facts!.prefix}/${bareModel(own)}`, account: a.cfg.id, label, covers: [a.cfg.id] }; } @@ -779,14 +786,14 @@ export class AccountsService { } /** A plan refused one model (providers/errors.ts modelRefusal): the cliproxy manager marks it unavailable. Returns the unsubscribe. */ - onModelRefused(fn: (provider: string, model: string, reason: string) => void): () => void { + onModelRefused(fn: (provider: string, model: string, reason: string, account?: string) => void): () => void { this.refusalListeners.add(fn); return () => this.refusalListeners.delete(fn); } - /** Tell the listeners a plan refused this model (the id as called, prefixed for one plan). */ - noteRefusal(provider: string, model: string, reason: string): void { - for (const fn of this.refusalListeners) fn(provider, model, reason); + /** Tell the listeners a plan refused this model (the id as called, prefixed for one plan). `account`: the plan the call went to, when it is known. */ + noteRefusal(provider: string, model: string, reason: string, account?: string): void { + for (const fn of this.refusalListeners) fn(provider, model, reason, account); } /** The list or the order changed (the cliproxy manager writes priorities). */ diff --git a/packages/core/src/providers/merge.ts b/packages/core/src/providers/merge.ts index b52be4f1..f35be7b1 100644 --- a/packages/core/src/providers/merge.ts +++ b/packages/core/src/providers/merge.ts @@ -114,7 +114,7 @@ export function mergeModelGroups(groups: ModelGroup[], routeOf: (model: string) // a ref that names a route of its own: one plan's prefix, or a provider outside the order (a ref on a provider in it // still follows the order, registry routed()). Only usable ones: a choice that cannot answer is no choice const inOrder = new Set((all ?? []).map((s) => s.provider)); - const choices = others.filter((s) => usable.has(s.provider) && (s.m.id.includes('/') || !inOrder.has(s.provider))).map((s) => s.m.ref); + const choices = others.filter((s) => usable.has(s.provider) && !s.m.unavailable && (s.m.id.includes('/') || !inOrder.has(s.provider))).map((s) => s.m.ref); const mark: Partial = { ...(steps.length && vendor ? { via: routeWords(steps, vendor, opts) } : {}), ...(others.length ? { refs: [keep.m.ref, ...others.map((s) => s.m.ref)] } : {}), @@ -122,7 +122,8 @@ export function mergeModelGroups(groups: ModelGroup[], routeOf: (model: string) ...(listedVendor ? { vendor: listedVendor } : {}), }; if (Object.keys(mark).length) marks.set(keep.m.ref, mark); - for (const s of others) marks.set(s.m.ref, { sameAs: keep.m.ref, ...(listedVendor ? { vendor: listedVendor } : {}) }); + // one plan's row it cannot run stays a row of its own, so the pickers list it under Not available with the reason + for (const s of others) marks.set(s.m.ref, { ...(s.m.unavailable && s.m.id.includes('/') ? {} : { sameAs: keep.m.ref }), ...(listedVendor ? { vendor: listedVendor } : {}) }); } if (!marks.size) return groups; return groups.map((g) => (g.models.some((m) => marks.has(m.ref)) ? { ...g, models: g.models.map((m) => (marks.has(m.ref) ? { ...m, ...marks.get(m.ref) } : m)) } : g)); diff --git a/packages/core/src/session/stream.ts b/packages/core/src/session/stream.ts index 74645e54..8b8e2b05 100644 --- a/packages/core/src/session/stream.ts +++ b/packages/core/src/session/stream.ts @@ -533,7 +533,8 @@ async function streamCall( } // a plan that refuses this one model: its picker row greys out with the reason, so the next turn is not sent to it again const refused = paidBy === 'hub' && accounts ? modelRefusal(e) : undefined; - if (refused) accounts!.noteRefusal(resolved.provider, resolved.model, refused); + // the plan it went to, when the call named one (a pin, a prefixed id); a bare id's plan CLIProxyAPI's cooldown names + if (refused) accounts!.noteRefusal(resolved.provider, resolved.model, refused, (target.pin?.provider === resolved.provider ? target.pin.account : undefined) ?? (splitAccount(resolved.model).account ? accounts!.accountFor(resolved.provider, resolved.model) : undefined)); // a plan signed out, or a key refused: the next route in the owner's order takes the call (providers/merge.ts) if (e.kind === 'auth' && paidBy === 'hub' && accounts && !begun && fallback(resolved.provider, `${engine.providerLabel(resolved.provider)} refused the sign in.`)) { fullRef = `${resolved.provider}/${resolved.model}`; diff --git a/packages/server/src/cliproxy/index.ts b/packages/server/src/cliproxy/index.ts index 01d1532f..911068f4 100644 --- a/packages/server/src/cliproxy/index.ts +++ b/packages/server/src/cliproxy/index.ts @@ -91,6 +91,8 @@ export const CLIENT_SECRET = 'cliproxy.clientKey'; export const EXT_KEY_SECRET = 'cliproxy.external.key'; export const EXT_MGMT_SECRET = 'cliproxy.external.managementKey'; const KV_PORT = 'cliproxy.port'; +/** Per credential, the models its plan cannot run and until when (index.ts notEntitled). */ +const KV_NOT_ON = 'cliproxy.notOn'; export const PROVIDER_ID = 'cliproxy'; /** Models that go over the Anthropic Messages wire. */ export const ANTHROPIC_MODELS = ['claude-*', '*/claude-*']; @@ -179,6 +181,8 @@ interface SignIn { mgmt: Management; /** Who started it, for the audit log. */ actor: string; + /** Each credential's last write when it started: one of the same type written since is the one signed in again. */ + stamps: Map; done?: number; } @@ -211,6 +215,15 @@ interface CredState { /** Wait after the last 429 from the usage endpoint; doubles up to an hour. */ backoff: number; usageError?: string; + /** Models this plan cannot run (its plan refused them, or CLIProxyAPI cooled them as not supported here): until when. */ + notOn?: Map; + /** Cooldowns (model and retry time) that were there when it was signed in again: they say nothing about the new sign-in. */ + stale?: Set; +} + +/** The models a plan cannot run now (a day-old entry no longer counts). */ +function notOnNow(s: CredState | undefined, now = Date.now()): Set { + return new Set([...(s?.notOn ?? [])].filter(([, until]) => until > now).map(([m]) => m)); } /** @@ -221,8 +234,10 @@ interface CredState { */ function planModels(s: CredState): Array<{ id: string; name?: string }> | undefined { const own = new Map((s.own ?? []).map((m) => [m.id, m])); + // a model the plan cannot run is not one it offers: routing, the order and "your Claude plans" leave it out + const not = notOnNow(s); return s.models - ?.filter((m) => !own.get(m.id)?.hidden && !RETIRED_ALIASES[m.id]) + ?.filter((m) => !own.get(m.id)?.hidden && !RETIRED_ALIASES[m.id] && !not.has(m.id)) .map((m) => (own.get(m.id)?.name ? { ...m, name: own.get(m.id)!.name } : m)); } @@ -244,6 +259,8 @@ const DAY_MS = 86_400_000; const PREFIX_SETTLE_MS = 5 * 60_000; /** How long a model a plan refused stays greyed out, unless Refresh models asks again. */ const REFUSED_MS = DAY_MS; +/** CLIProxyAPI's reasons for a model cooldown on one credential that mean the plan cannot run the model (sdk/cliproxy/auth/cooldown_view.go): a 404 or its model-support check. */ +const NOT_ON_PLAN = new Set(['model_not_supported', 'not_found']); const STATUS_WORDS: Record = { error: 'Failing', refreshing: 'Refreshing its sign-in', pending: 'Waiting to sign in' }; /** "http://host:8317/v1/" -> "http://host:8317". Undefined for anything that is not a plain http(s) base. */ @@ -357,6 +374,10 @@ export class CliproxyManager { private catalog: { base?: Catalog; baseAt?: number; path?: string; added: Set; failedAt?: number } = { added: new Set() }; /** Models a plan refused (id as called, prefixed for one plan): why, and until when the pickers grey them out. */ private refused = new Map(); + /** What every plan could not run at the last credentials read: a change applies the provider again. */ + private notOnSig = ''; + /** Bare ids a plan refused while several plans list them: which one the next credentials read must say, else every plan greys them out. */ + private pendingBare = new Map(); private catalogRun?: Promise; private offAccounts: Array<() => void> = []; readonly files: CliproxyFiles; @@ -451,8 +472,19 @@ export class CliproxyManager { this.offAccounts.push(this.accountService.onLimitHit(() => this.soon())); // a plan refused one model: grey it out in the pickers with the reason, until Refresh models or a day passes this.offAccounts.push( - this.accountService.onModelRefused((provider, model, reason) => { + this.accountService.onModelRefused((provider, model, reason, account) => { if (provider !== PROVIDER_ID) return; + // one plan refused it (a prefixed id, a pinned call): only that plan stops offering it + const cred = account ? this.accountService.credentialOf(account)?.name : undefined; + if (cred) return void this.notEntitled(cred, splitAccount(model).model); + // a bare id several plans list: CLIProxyAPI's cooldown names the plan that refused it (learnNotOn), read soon + const listers = this.raw.filter((c) => !c.disabled && this.creds.get(c.name)?.models?.some((m) => m.id === model) && !notOnNow(this.creds.get(c.name)).has(model)); + if (!model.includes('/') && listers.length > 1) { + log.warn(`${PROVIDER_ID}/${model}: ${reason}; reading which plan refused it`); + this.pendingBare.set(model, { reason, at: Date.now() }); + this.soon(); + return; + } this.refused.set(model, { reason, until: Date.now() + REFUSED_MS }); log.warn(`${PROVIDER_ID}/${model}: ${reason}; the pickers show it as unavailable`); this.applyProvider(); @@ -916,6 +948,20 @@ export class CliproxyManager { if (r.until > now) out[id] = { unavailable: r.reason }; else this.refused.delete(id); } + // a model one plan cannot run: its row on that plan waits in Not available; the bare id too once no plan that lists it can + const listers = new Map(); + for (const c of this.raw) { + if (c.disabled) continue; + for (const m of this.creds.get(c.name)?.models ?? []) if (!m.id.includes('/')) listers.set(m.id, [...(listers.get(m.id) ?? []), c]); + } + for (const [model, creds] of listers) { + const not = creds.filter((c) => notOnNow(this.creds.get(c.name), now).has(model)); + for (const c of not) { + const prefix = this.prefixOf(c); + if (prefix) out[`${prefix}/${model}`] = { ...out[`${prefix}/${model}`], unavailable: `Not on the ${prefix} plan` }; + } + if (not.length && not.length === creds.length && !out[model]?.unavailable) out[model] = { ...out[model], unavailable: not.length === 1 ? `Not on the ${this.planName(not[0])} plan` : 'Not on any of your plans' }; + } for (const c of this.raw) { if (c.disabled) continue; for (const m of this.creds.get(c.name)?.own ?? []) { @@ -989,9 +1035,79 @@ export class CliproxyManager { this.credAt = Date.now(); this.accounts = list.map((c) => this.toAccount(c)); for (const name of [...this.creds.keys()]) if (!list.some((c) => c.name === name)) this.creds.delete(name); + this.learnNotOn(); this.feedAccounts(); + // a plan that cannot run a model, or can again (a day passed), changes the pickers + const sig = [...this.creds].map(([n, s]) => `${n}:${[...notOnNow(s)].sort().join(',')}`).join('\n'); + const notOnChanged = sig !== this.notOnSig; + this.notOnSig = sig; // an account that left (or was paused) takes the models only its own list had - if (this.allModels().map((m) => m.id).join('\n') !== before) this.applyProvider(); + if (notOnChanged || this.allModels().map((m) => m.id).join('\n') !== before) this.applyProvider(); + } + + /** A model cooldown CLIProxyAPI put on one credential because the plan cannot run the model: that plan stops offering it. */ + private learnNotOn(): void { + const now = Date.now(); + // a day-old entry goes: the plan is asked again + let gone = false; + for (const s of this.creds.values()) for (const [m, until] of s.notOn ?? []) if (until <= now) (s.notOn!.delete(m), (gone = true)); + if (gone) this.saveNotOn(); + for (const c of this.raw) { + for (const cd of c.cooldowns ?? []) { + if (cd.scope !== 'model' || !cd.model || !NOT_ON_PLAN.has(cd.reason) || !cd.retryAt || cd.retryAt <= now) continue; + const model = splitAccount(cd.model).model; + if (this.creds.get(c.name)?.stale?.has(`${model}@${cd.retryAt}`)) continue; + this.notEntitled(c.name, model, false); + this.pendingBare.delete(model); + } + } + // a refused bare id no plan's cooldown named after a read: grey it out everywhere, as before + for (const [model, p] of this.pendingBare) { + // shortcut: a read already under way may predate the refusal, so give it 3 s; a slower read would grey it out early + if (now - p.at < 3_000) continue; + this.pendingBare.delete(model); + this.refused.set(model, { reason: p.reason, until: now + REFUSED_MS }); + log.warn(`${PROVIDER_ID}/${model}: ${p.reason}; no plan was named, the pickers show it as unavailable`); + } + } + + /** + * Record that a plan cannot run a model, for a day (a plan upgrade shows the + * next day, or at once when the account is signed in again). False when the + * credential is unknown or it was already recorded. `apply`: tell the + * accounts and the pickers now. + */ + private notEntitled(cred: string, model: string, apply = true): boolean { + const c = this.raw.find((x) => x.name === cred); + if (!c) return false; + const s = this.cred(cred); + if (notOnNow(s).has(model)) return false; + (s.notOn ??= new Map()).set(model, Date.now() + REFUSED_MS); + this.saveNotOn(); + log.warn(`${PROVIDER_ID}: ${this.planName(c)} cannot run ${model}; it stays off that plan for a day or until it is signed in again`); + if (apply) { + this.feedAccounts(); + this.applyProvider(); + } + return true; + } + + /** Keep what each plan cannot run across a restart (an update), so its next turn does not fail again. */ + private saveNotOn(): void { + try { + // an account not read yet keeps its entry; one that is gone loses it + const out = Object.fromEntries(Object.entries(this.engine.repos.kv.get>>(KV_NOT_ON, {})).filter(([name]) => !this.creds.has(name) && this.raw.some((c) => c.name === name))); + for (const [name, s] of this.creds) if (s.notOn?.size) out[name] = Object.fromEntries(s.notOn); + if (Object.keys(out).length) this.engine.repos.kv.set(KV_NOT_ON, out); + else this.engine.repos.kv.delete(KV_NOT_ON); + } catch (err) { + log.warn(`could not save the models a plan cannot run: ${(err as Error).message}`); + } + } + + /** A plan's name in the pickers' words: its short name, else its label. */ + private planName(c: RawCredential): string { + return this.prefixOf(c) ?? this.toAccount(c).label ?? c.name; } // ------------------------------------------------------------------------- @@ -1001,8 +1117,9 @@ export class CliproxyManager { private cred(name: string): CredState { let s = this.creds.get(name); if (!s) { - // a new account: its usage and models are read on the next pass - s = { windows: [], usageNext: 0, backoff: 0 }; + // a new account: its usage and models are read on the next pass; what it could not run before a restart still holds + const saved = Object.entries(this.engine.repos.kv.get>>(KV_NOT_ON, {})[name] ?? {}).filter(([, until]) => until > Date.now()); + s = { windows: [], usageNext: 0, backoff: 0, ...(saved.length ? { notOn: new Map(saved) } : {}) }; this.creds.set(name, s); } return s; @@ -1048,6 +1165,7 @@ export class CliproxyManager { windows: mergeWindows(this.signalWindows(c), s?.windows ?? []), cooldowns, ...(s?.models ? { models: planModels(s) } : {}), + ...(notOnNow(s, now).size ? { notOn: [...notOnNow(s, now)] } : {}), ...(daybreakOf(s).length ? { daybreak: daybreakOf(s) } : {}), ...(c.signalsAt || s?.windows.length ? { observedAt: Math.max(c.signalsAt ?? 0, ...(s?.windows ?? []).map((w) => w.observedAt ?? 0)) } : {}), }; @@ -1728,7 +1846,7 @@ export class CliproxyManager { this.wrap(err); } const ttl = start.expiresIn ? start.expiresIn * 1000 : 10 * 60_000; - const s: SignIn = { state: start.state, provider: id, flow: start.flow, url: start.url, userCode: start.userCode, expiresAt: Date.now() + ttl, status: 'wait', before: new Set(this.accounts.map((a) => a.name)), caught: false, mgmt, actor }; + const s: SignIn = { state: start.state, provider: id, flow: start.flow, url: start.url, userCode: start.userCode, expiresAt: Date.now() + ttl, status: 'wait', before: new Set(this.accounts.map((a) => a.name)), caught: false, mgmt, actor, stamps: new Map(this.raw.map((c) => [c.name, c.updatedAt])) }; if (start.flow === 'redirect') { const r = redirectOf(start.url); if (r) { @@ -1803,6 +1921,20 @@ export class CliproxyManager { } await this.syncModels().catch(() => undefined); await this.syncAccounts(); + // signed in again (its file written since, same type): what it could not run is asked again (a plan upgrade). + // shortcut: a token refresh of a same-type plan during the sign-in looks the same; it costs one refused turn + let again = false; + const type = SIGN_IN_VIA[s.provider] ?? s.provider; + for (const c of this.raw) { + const st = this.creds.get(c.name); + if (!st?.notOn?.size || c.provider !== type || !s.stamps.has(c.name) || c.updatedAt === s.stamps.get(c.name)) continue; + st.notOn.clear(); + // its old not-supported cooldowns stay in the proxy (a reset would clear its quota ones too): they are not read again + st.stale = new Set((c.cooldowns ?? []).filter((cd) => cd.scope === 'model' && cd.model && NOT_ON_PLAN.has(cd.reason)).map((cd) => `${splitAccount(cd.model!).model}@${cd.retryAt}`)); + again = true; + log.info(`${PROVIDER_ID}: ${this.planName(c)} was signed in again; the models it could not run are offered again`); + } + if (again) (this.saveNotOn(), this.feedAccounts(), this.applyProvider()); const added = this.accounts.filter((a) => !s.before.has(a.name)); s.account = added.find((a) => a.provider === (SIGN_IN_VIA[s.provider] ?? s.provider)) ?? added[0]; // the new account's models, plan usage and place in the order diff --git a/packages/server/test/accounts.test.ts b/packages/server/test/accounts.test.ts index db7ac11f..72a057d2 100644 --- a/packages/server/test/accounts.test.ts +++ b/packages/server/test/accounts.test.ts @@ -15,6 +15,7 @@ import { renderConfig } from '../src/cliproxy/config'; import { ProviderRegistry } from '@conclave/core/providers/registry.ts'; import { ProviderError } from '@conclave/core/providers/types.ts'; import { modelRefusal } from '@conclave/core/providers/errors.ts'; +import { mergeModelGroups } from '@conclave/core/providers/merge.ts'; import { accountsOf } from '@conclave/core/accounts/attached.ts'; import { WindowStarter, sendStarter } from '@conclave/core/accounts/starter.ts'; import type { UsageInput } from '@conclave/core/usage/readers/common.ts'; @@ -887,6 +888,85 @@ describe('builtin: a ChatGPT plan\'s own models reach CLIProxyAPI through its ca await hub.api('/api/models/refresh', { method: 'POST' }); expect(hub.engine.config.get().providers.cliproxy.modelMeta?.['claude-mythos-5-1']).toBeUndefined(); }, 20_000); + + test('a Claude plan without a model (Mythos on neu): only that plan stops offering it, routing skips it; a day or a new sign in asks again', async () => { + const meta = () => hub.engine.config.get().providers.cliproxy.modelMeta ?? {}; + const svc = accountsOf(hub.engine)!; + const later = new Date(Date.now() + 12 * 3600_000).toISOString(); + write('claude-me@example.test.json', { type: 'claude', email: 'claude@example.test', prefix: 'personal' }); + // other cooldowns on neu say nothing about what its plan has: a limit, an overload + write('claude-neu@example.test.json', { type: 'claude', email: 'neu@example.test', prefix: 'neu', cooldowns: [{ scope: 'model', model_key: 'claude-opus-5-5', reason: 'quota', retry_at: later }, { scope: 'model', model_key: 'claude-sonnet-5-5', reason: 'transient_error', retry_at: later }] }); + await hub.api('/api/models/refresh', { method: 'POST' }); + await until(async () => (await accountModels('claude-neu@example.test')).includes('claude-mythos-5-1') && (await accountModels('claude-me@example.test')).includes('claude-mythos-5-1'), 8000, 'both plans with Mythos'); + await until(() => svc.status().accounts.find((a) => a.id === 'claude-neu@example.test')?.prefix === 'neu', 8000, 'the neu prefix'); + expect(Object.entries(meta()).filter(([, v]) => v.unavailable)).toEqual([]); + // the old "Claude Code version" 400, a rate limit and an overload are no refusal + expect(modelRefusal(new ProviderError('bad_request', "cliproxy 400 invalid_request_error: Claude Code 2.1.280 does not support this model; version 2.1.290 or newer is required. Run 'claude update', or update the Claude desktop app, then try again.", { status: 400 }))).toBeUndefined(); + expect(modelRefusal(new ProviderError('rate_limit', 'cliproxy 429 rate_limit_error: Number of requests has exceeded your rate limit', { status: 429 }))).toBeUndefined(); + expect(modelRefusal(new ProviderError('overloaded', 'cliproxy 529 overloaded_error: Overloaded', { status: 529 }))).toBeUndefined(); + + // CLIProxyAPI cooled Mythos on neu alone as not supported there (sdk/cliproxy/auth/cooldown_view.go model_not_supported) + write('claude-neu@example.test.json', { type: 'claude', email: 'neu@example.test', prefix: 'neu', cooldowns: [{ scope: 'model', model_key: 'claude-mythos-5-1', reason: 'model_not_supported', retry_at: later }] }); + await until(() => meta()['neu/claude-mythos-5-1']?.unavailable, 8000, 'neu/claude-mythos-5-1 unavailable'); + expect(meta()['neu/claude-mythos-5-1']).toEqual({ unavailable: 'Not on the neu plan' }); + // the hub-wide model stays: personal runs it + expect(meta()['claude-mythos-5-1']?.unavailable).toBeUndefined(); + expect(meta()['personal/claude-mythos-5-1']?.unavailable).toBeUndefined(); + expect(await accountModels('claude-neu@example.test')).not.toContain('claude-mythos-5-1'); + expect(await accountModels('claude-me@example.test')).toContain('claude-mythos-5-1'); + // the picker data: neu's row waits under Not available as a row of its own, the model reads "your Claude plan" (one) + const fresh = new ProviderRegistry(hub.engine.config); + const rows = mergeModelGroups(await fresh.groups(), (m) => svc.routeOf(m)).find((g) => g.provider === 'cliproxy')!.models; + fresh.dispose(); + expect(rows.find((m) => m.ref === 'cliproxy/claude-mythos-5-1')?.via).toBe('your Claude plan'); + expect(rows.find((m) => m.ref === 'cliproxy/neu/claude-mythos-5-1')).toMatchObject({ unavailable: 'Not on the neu plan' }); + expect(rows.find((m) => m.ref === 'cliproxy/neu/claude-mythos-5-1')?.sameAs).toBeUndefined(); + const head = rows.find((m) => m.ref === 'cliproxy/claude-mythos-5-1')!; + expect(head.unavailable).toBeUndefined(); + expect(head.choices ?? []).not.toContain('cliproxy/neu/claude-mythos-5-1'); + // routing: neu is not ready for it, the next plan is named so CLIProxyAPI cannot send the bare id to neu + expect(svc.readyAccounts('claude-mythos-5-1').map((a) => a.id)).not.toContain('claude-neu@example.test'); + expect(svc.planWire('claude-mythos-5-1')).toMatchObject({ wire: 'personal/claude-mythos-5-1', account: 'claude-me@example.test' }); + // Opus, which neu runs, still goes by its bare id + expect(svc.planWire('claude-opus-5-5')?.wire).toBe('claude-opus-5-5'); + + // kept on disk: the hub forgets neu (as a restart does) and reads it again without the cooldown; Mythos stays off it + const saved = () => hub.engine.repos.kv.get>>('cliproxy.notOn', {}); + expect(Object.keys(saved()['claude-neu@example.test.json'] ?? {})).toEqual(['claude-mythos-5-1']); + const neuFile = join(authDir(), 'claude-neu@example.test.json'); + rmSync(neuFile); + await until(() => !svc.status().accounts.some((a) => a.id === 'claude-neu@example.test'), 8000, 'neu gone'); + write('claude-neu@example.test.json', { type: 'claude', email: 'neu@example.test', prefix: 'neu' }); + await until(async () => (await accountModels('claude-neu@example.test')).includes('claude-opus-5-5'), 8000, 'neu back'); + expect(await accountModels('claude-neu@example.test')).not.toContain('claude-mythos-5-1'); + expect(meta()['neu/claude-mythos-5-1']).toEqual({ unavailable: 'Not on the neu plan' }); + + // a day later (the cooldown gone too): asked again + write('claude-neu@example.test.json', { type: 'claude', email: 'neu@example.test', prefix: 'neu' }); + const real = Date.now; + const clock = spyOn(Date, 'now').mockImplementation(() => real() + 25 * 3600_000); + try { + await hub.api('/api/accounts/refresh', { method: 'POST' }); + // the full suite is slow: read the credentials until the day-old entry goes + await until(async () => (await hub.api('/api/accounts/refresh', { method: 'POST' }), !meta()['neu/claude-mythos-5-1']?.unavailable), 20_000, 'cleared after a day'); + } finally { + clock.mockRestore(); + } + expect(svc.readyAccounts('claude-mythos-5-1').map((a) => a.id)).toContain('claude-neu@example.test'); + + // a refused turn on a pinned or prefixed call names neu: recorded at once, without a cooldown + svc.noteRefusal('cliproxy', 'neu/claude-mythos-5-1', 'Your plan refused it (HTTP 404)', 'claude-neu@example.test'); + expect(meta()['neu/claude-mythos-5-1']).toEqual({ unavailable: 'Not on the neu plan' }); + expect(meta()['claude-mythos-5-1']?.unavailable).toBeUndefined(); + // signed in again (a plan upgrade): offered again at once + const start = await hub.api('/api/subscriptions/signin', { method: 'POST', json: { provider: 'claude' } }); + const s = (await start.json()) as { state: string; callbackHost: string }; + const done = await hub.api(`/api/subscriptions/signin/${s.state}/callback`, { method: 'POST', json: { url: `http://${s.callbackHost}/callback?code=ok:neu@example.test:neu&state=${s.state}` } }); + expect(((await done.json()) as { status: string }).status).toBe('ok'); + await until(() => !meta()['neu/claude-mythos-5-1']?.unavailable, 8000, 'cleared by the sign in'); + expect(saved()['claude-neu@example.test.json']).toBeUndefined(); + expect(svc.readyAccounts('claude-mythos-5-1').map((a) => a.id)).toContain('claude-neu@example.test'); + }, 40_000); }); void appendFileSync; diff --git a/packages/web/src/mock/data.ts b/packages/web/src/mock/data.ts index 5b1a6016..4f0d828f 100644 --- a/packages/web/src/mock/data.ts +++ b/packages/web/src/mock/data.ts @@ -17,7 +17,7 @@ import type { Todo, UsageRecord, } from '@conclave/core/types'; -import type { GatewayKeyDto, McpStatus, ModelGroup } from '@conclave/core/client'; +import type { GatewayKeyDto, McpStatus, ModelEntry, ModelGroup } from '@conclave/core/client'; import type { AgentDef, InstalledPlugin } from '@conclave/core/extensions/types'; import type { ModelInfo } from '@conclave/core/providers/types'; import { EFFORTS, modelEffort, type Effort } from '@conclave/core/providers/effort'; @@ -42,7 +42,7 @@ function rand() { // Models // --------------------------------------------------------------------------- -function model(provider: string, id: string, name: string, ctx: number, inP: number, outP: number, extra: Partial = {}): ModelInfo { +function model(provider: string, id: string, name: string, ctx: number, inP: number, outP: number, extra: Partial = {}): ModelEntry { return { id, ref: `${provider}/${id}`, @@ -72,7 +72,10 @@ export const modelGroups: ModelGroup[] = [ models: [ // the hub's catalog prices (core providers/catalog.ts): 5 minute writes 1.25x input, 1 hour writes 2x model('anthropic', 'claude-mythos-5-2', 'Claude Mythos 5.2', 1_000_000, 8, 40, { tier: 'deep', cacheReadPrice: 0.2, cacheWrite1hPrice: 16, unavailable: 'Your plan refused it (HTTP 404)' }), - model('anthropic', 'claude-fable-5-2', 'Claude Fable 5.2', 1_000_000, 8, 40, { tier: 'deep', cacheReadPrice: 0.2, cacheWrite1hPrice: 16 }), + model('anthropic', 'claude-fable-5-2', 'Claude Fable 5.2', 1_000_000, 8, 40, { tier: 'deep', cacheReadPrice: 0.2, cacheWrite1hPrice: 16, via: 'your Claude plan', choices: ['anthropic/personal/claude-fable-5-2'] }), + // two Claude plans: personal runs Fable 5.2, the neu plan does not (its row waits under Not available) + model('anthropic', 'personal/claude-fable-5-2', 'Claude Fable 5.2', 1_000_000, 8, 40, { tier: 'deep', sameAs: 'anthropic/claude-fable-5-2' }), + model('anthropic', 'neu/claude-fable-5-2', 'Claude Fable 5.2', 1_000_000, 8, 40, { tier: 'deep', unavailable: 'Not on the neu plan' }), model('anthropic', 'claude-mythos-5-1', 'Claude Mythos 5.1', 1_000_000, 15, 75, { tier: 'deep', unavailable: 'Your plan refused it (HTTP 404)' }), model('anthropic', 'claude-fable-5-1', 'Claude Fable 5.1', 1_000_000, 10, 50, { tier: 'deep' }), model('anthropic', 'claude-opus-4-6', 'Claude Opus 4.6', 1_000_000, 5, 25, { tier: 'deep' }), diff --git a/packages/web/test/model-picker.test.tsx b/packages/web/test/model-picker.test.tsx index b855f9d6..9ff981c5 100644 --- a/packages/web/test/model-picker.test.tsx +++ b/packages/web/test/model-picker.test.tsx @@ -234,6 +234,27 @@ describe('a model the plan refused', () => { expect(mythos.model?.unavailable).toBe('Your plan refused it (HTTP 404)'); expect(rows.find((r) => r.ref === 'cliproxy/claude-opus-5-5')!.disabled).toBe(false); }); + + test('one Claude plan without it (Mythos not on neu): that plan\'s row waits in Not available with the reason, the model stays on the other plan', () => { + // as the hub merges it (providers/merge.ts): neu's row is not folded into the model, personal's is a route of it + const models = [ + group('cliproxy', [ + model('cliproxy', 'claude-mythos-5-1', 'Claude Mythos 5.1', { via: 'your Claude plan', refs: ['cliproxy/claude-mythos-5-1', 'cliproxy/personal/claude-mythos-5-1', 'cliproxy/neu/claude-mythos-5-1'], choices: ['cliproxy/personal/claude-mythos-5-1'] }), + model('cliproxy', 'personal/claude-mythos-5-1', 'Claude Mythos 5.1', { sameAs: 'cliproxy/claude-mythos-5-1' }), + model('cliproxy', 'neu/claude-mythos-5-1', 'Claude Mythos 5.1', { unavailable: 'Not on the neu plan' }), + model('cliproxy', 'claude-opus-5-5', 'Claude Opus 5.5'), + ]), + ]; + const p = buildPicker(input({ models, sessions: {} })); + const rows = allRows(p); + expect(rows.find((r) => r.ref === 'cliproxy/neu/claude-mythos-5-1')).toMatchObject({ disabled: true, model: { unavailable: 'Not on the neu plan' } }); + const mythos = rows.find((r) => r.ref === 'cliproxy/claude-mythos-5-1')!; + expect(mythos.disabled).toBe(false); + expect(mythos.routes?.map((r) => r.ref)).toEqual(['cliproxy/claude-mythos-5-1', 'cliproxy/personal/claude-mythos-5-1']); + const items = lines(pickerItems(p, '', 'anthropic', [], null, true)); + expect(items.slice(-2)).toEqual(['+ Not available (1)', 'cliproxy/neu/claude-mythos-5-1']); + expect(items.indexOf('cliproxy/claude-mythos-5-1')).toBeLessThan(items.indexOf('+ Not available (1)')); + }); }); describe('a custom provider', () => {