diff --git a/src/components/LimitSwitchDialog.test.ts b/src/components/LimitSwitchDialog.test.ts
new file mode 100644
index 0000000000..75545cb099
--- /dev/null
+++ b/src/components/LimitSwitchDialog.test.ts
@@ -0,0 +1,78 @@
+import { expect, test } from 'bun:test'
+
+import { describeFailedTurn, limitSwitchDoneMessage, limitSwitchModelOptions } from './LimitSwitchDialog.js'
+
+test('offers Verboo models, last used first, plus keeping the current one', () => {
+ const options = limitSwitchModelOptions(
+ [
+ { id: 'ultra/a', displayName: 'A' },
+ { id: 'ultra/b', displayName: 'B' },
+ { id: 'ultra/c' },
+ ],
+ 'ultra/b',
+ )
+ expect(options.map(option => option.value)).toEqual([
+ 'ultra/b',
+ 'ultra/a',
+ 'ultra/c',
+ '__keep_current_model__',
+ ])
+ expect(options[2]?.label).toBe('ultra/c')
+})
+
+test('caps the list at five models', () => {
+ const models = Array.from({ length: 8 }, (_, i) => ({ id: `m${i}` }))
+ expect(limitSwitchModelOptions(models, undefined)).toHaveLength(6)
+})
+
+const limitError = { type: 'assistant', isApiErrorMessage: true, message: { content: [{ type: 'text', text: 'limit' }] } }
+const reply = { type: 'assistant', message: { content: [{ type: 'text', text: 'ok' }] } }
+
+test('a turn where nothing ran can be sent again', () => {
+ const turn = describeFailedTurn([
+ { type: 'user', uuid: 'old', message: { content: 'first request' } },
+ reply,
+ { type: 'user', uuid: 'new', message: { content: 'refactor the parser' } },
+ { type: 'user', isMeta: true, message: { content: 'system reminder' } },
+ limitError,
+ ] as never)
+ expect(turn).toEqual({ prompt: 'refactor the parser', promptUuid: 'new', toolsRan: false })
+ expect(describeFailedTurn([] as never)).toEqual({ prompt: null, toolsRan: false })
+})
+
+test('a turn that already ran tools is reported, so it is not repeated', () => {
+ const turn = describeFailedTurn([
+ { type: 'user', uuid: 'new', message: { content: 'append to the file' } },
+ { type: 'assistant', message: { content: [{ type: 'tool_use', id: 't', name: 'Bash', input: {} }] } },
+ { type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 't', content: 'out' }] } },
+ limitError,
+ ] as never)
+ expect(turn.toolsRan).toBe(true)
+ expect(limitSwitchDoneMessage('m', turn)).toContain('nada foi reenviado')
+})
+
+test('the compaction summary is not mistaken for what the user typed', () => {
+ const turn = describeFailedTurn([
+ { type: 'user', uuid: 'typed', message: { content: 'next step' } },
+ { type: 'system', subtype: 'compact_boundary' },
+ { type: 'user', isCompactSummary: true, isVisibleInTranscriptOnly: true, message: { content: 'This session is being continued' } },
+ limitError,
+ ] as never)
+ expect(turn.prompt).toBe('next step')
+})
+
+test('a turn not started by typed text never falls back to an older prompt', () => {
+ for (const content of [
+ [{ type: 'image', source: {} }, { type: 'text', text: 'see this' }],
+ 'done',
+ 'agent finished',
+ ]) {
+ const turn = describeFailedTurn([
+ { type: 'user', uuid: 'old', message: { content: 'older prompt' } },
+ reply,
+ { type: 'user', uuid: 'new', message: { content } },
+ limitError,
+ ] as never)
+ expect(turn.prompt).toBeNull()
+ }
+})
diff --git a/src/components/LimitSwitchDialog.tsx b/src/components/LimitSwitchDialog.tsx
new file mode 100644
index 0000000000..729dc02d8a
--- /dev/null
+++ b/src/components/LimitSwitchDialog.tsx
@@ -0,0 +1,128 @@
+import * as React from 'react'
+
+import { getUserMessageText, textForResubmit } from '../utils/messages.js'
+import type { Message, UserMessage } from '../types/message.js'
+import { Select } from './CustomSelect/select.js'
+import { Dialog } from './design-system/Dialog.js'
+import { Box, Text } from '../ink.js'
+
+const KEEP = '__keep_current_model__'
+const MAX_MODELS = 5
+// Text the CLI itself placed in a user message; the user did not type it.
+const NOT_TYPED = /^\s*<(local-command-|bash-|task-notification)/
+
+/** Verboo models to offer, the last Verboo model used first. */
+export function limitSwitchModelOptions(
+ models: ReadonlyArray<{ id: string; displayName?: string }>,
+ lastRouterModel: string | undefined,
+): Array<{ label: string; value: string }> {
+ const ordered = [...models].sort((a, b) =>
+ a.id === lastRouterModel ? -1 : b.id === lastRouterModel ? 1 : 0,
+ )
+ return [
+ ...ordered.slice(0, MAX_MODELS).map(model => ({
+ label: model.displayName ?? model.id,
+ value: model.id,
+ })),
+ { label: 'Manter o modelo atual', value: KEEP },
+ ]
+}
+
+export type FailedTurn = {
+ /** The prompt that started the failed turn, when it can be sent again as is. */
+ prompt: string | null
+ promptUuid?: string
+ /** Tools already ran in this turn: sending the prompt again would repeat them. */
+ toolsRan: boolean
+}
+
+/** Looks back from the limit error to the message that started that turn. */
+export function describeFailedTurn(messages: readonly Message[]): FailedTurn {
+ let toolsRan = false
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const message = messages[i]!
+ if (message.type === 'assistant') {
+ const content = message.message.content
+ if (Array.isArray(content) && content.some(block => block.type === 'tool_use')) {
+ toolsRan = true
+ }
+ continue
+ }
+ if (
+ message.type !== 'user' ||
+ message.isMeta ||
+ message.isCompactSummary ||
+ message.isVisibleInTranscriptOnly
+ ) {
+ continue
+ }
+ const content = message.message.content
+ if (Array.isArray(content) && content.some(block => block.type === 'tool_result')) {
+ continue
+ }
+ // Images and other attachments cannot be sent again from the text alone.
+ const hasOnlyText = !Array.isArray(content) || content.every(block => block.type === 'text')
+ const resubmit = hasOnlyText ? textForResubmit(message as UserMessage) : null
+ const text = resubmit?.mode === 'prompt' ? resubmit.text : ''
+ return {
+ prompt: text.trim() && !NOT_TYPED.test(getUserMessageText(message as UserMessage) ?? '') ? text : null,
+ promptUuid: message.uuid,
+ toolsRan,
+ }
+ }
+ return { prompt: null, toolsRan }
+}
+
+export function limitSwitchDoneMessage(model: string, turn: FailedTurn): string {
+ if (turn.toolsRan) {
+ return `Modelo alterado para ${model}. A resposta anterior parou depois de executar ferramentas, então nada foi reenviado para não repetir ações. Diga como continuar.`
+ }
+ if (turn.prompt === null) {
+ return `Modelo alterado para ${model}. Envie sua mensagem novamente para continuar.`
+ }
+ return `Modelo alterado para ${model}.`
+}
+
+type Props = {
+ reason: string
+ models: ReadonlyArray<{ id: string; displayName?: string }>
+ lastRouterModel: string | undefined
+ turn: FailedTurn
+ onSwitch: (model: string) => void
+ onKeep: () => void
+}
+
+/**
+ * Opened by the REPL when the user's own account (ChatGPT plan, OpenAI or
+ * Anthropic key) runs out; offers to continue on a Verboo model.
+ */
+export function LimitSwitchDialog({
+ reason,
+ models,
+ lastRouterModel,
+ turn,
+ onSwitch,
+ onKeep,
+}: Props): React.ReactNode {
+ const options = limitSwitchModelOptions(models, lastRouterModel)
+ const consequence = turn.toolsRan
+ ? ' Sua última mensagem não será reenviada, porque ela já executou ferramentas.'
+ : turn.prompt !== null
+ ? ' Sua última mensagem será reenviada.'
+ : ''
+ return (
+
+ )
+}
diff --git a/src/screens/REPL.tsx b/src/screens/REPL.tsx
index 460b991d6a..ce1467b6c7 100644
--- a/src/screens/REPL.tsx
+++ b/src/screens/REPL.tsx
@@ -268,6 +268,10 @@ import { useIDEStatusIndicator } from 'src/hooks/notifs/useIDEStatusIndicator.js
import { useModelMigrationNotifications } from 'src/hooks/notifs/useModelMigrationNotifications.js';
import { useCanSwitchToExistingSubscription } from 'src/hooks/notifs/useCanSwitchToExistingSubscription.js';
import { useClaudeLoginRetiredNotification } from 'src/hooks/notifs/useClaudeLoginRetiredNotification.js';
+import { limitSwitchReasonFromMessage } from 'src/services/api/providerLimitErrors.js';
+import { describeFailedTurn, limitSwitchDoneMessage, LimitSwitchDialog } from 'src/components/LimitSwitchDialog.js';
+import { getCachedVerbooModels } from 'src/services/api/verbooModels.js';
+import { saveLastVerbooModel } from 'src/utils/model/model.js';
import { useTeammateLifecycleNotification } from 'src/hooks/notifs/useTeammateShutdownNotification.js';
import { useFastModeNotification } from 'src/hooks/notifs/useFastModeNotification.js';
import type { HookProgress } from '../types/hooks.js';
@@ -576,6 +580,12 @@ export type Props = {
thinkingConfig: ThinkingConfig;
};
export type Screen = 'prompt' | 'transcript';
+/** What ran out, when this message is the provider-limit error of a user's own account. */
+function providerLimitReason(message: MessageType): string | null {
+ if (message.type !== 'assistant' || !message.isApiErrorMessage) return null;
+ const block = message.message.content[0];
+ return limitSwitchReasonFromMessage(block && block.type === 'text' ? block.text : '');
+}
export function REPL({
commands: initialCommands,
debug,
@@ -1815,6 +1825,7 @@ export function REPL({
...prev,
fileHistory: fileHistoryState
})));
+ const handledProviderLimitRef = useRef(messages.at(-1)?.uuid);
const resume = useCallback(async (sessionId: UUID, log: LogOption, entrypoint: ResumeEntrypoint) => {
const resumeStart = performance.now();
try {
@@ -2015,6 +2026,9 @@ export function REPL({
}
const hydratedMessages = contentReplacementStateRef.current ? applyToolResultReplacementsToMessages(messages, contentReplacementStateRef.current.replacements) : messages;
+ // VERBOO-BRAND: a limit error saved in that session is old news.
+ handledProviderLimitRef.current = hydratedMessages.at(-1)?.uuid;
+
// Reset messages to the provided initial messages
// Use a callback to ensure we're not dependent on stale state
setMessages(() => hydratedMessages);
@@ -3790,6 +3804,68 @@ export function REPL({
resetHistory: () => { }
});
}, []);
+ // VERBOO-BRAND: the resend waits for the next render. onSubmit reads the model
+ // from its closure, so calling it right after the switch would send the prompt
+ // back to the account that just ran out.
+ const [limitResendPrompt, setLimitResendPrompt] = useState(null);
+ useEffect(() => {
+ if (limitResendPrompt === null) return;
+ setLimitResendPrompt(null);
+ void onSubmitRef.current(limitResendPrompt, {
+ setCursorOffset: () => { },
+ clearBuffer: () => { },
+ resetHistory: () => { }
+ }, undefined, {
+ fromKeybinding: true
+ });
+ }, [limitResendPrompt]);
+ // VERBOO-BRAND: when the user's own account (ChatGPT plan, OpenAI or
+ // Anthropic key) runs out, open the switch to a Verboo model right away
+ // instead of making them type /model. Errors that came with a resumed session
+ // are ignored (see handledProviderLimitRef). The dialog is rendered here, not
+ // submitted as a command: the prompt draft, history and transcript stay intact.
+ useEffect(() => {
+ const last = messages.at(-1);
+ if (!last || handledProviderLimitRef.current === last.uuid) return;
+ const reason = providerLimitReason(last);
+ if (reason === null) return;
+ handledProviderLimitRef.current = last.uuid;
+ const models = getCachedVerbooModels() ?? [];
+ if (models.length === 0) {
+ setMessages(prev => [...prev, createSystemMessage('Nenhum modelo Verboo disponível na sua conta. Use /model para ver as opções.', 'warning')]);
+ return;
+ }
+ const turn = describeFailedTurn(messages);
+ const close = (text: string) => {
+ setToolJSX({
+ jsx: null,
+ shouldHidePromptInput: false,
+ clearLocalJSX: true
+ });
+ // Not 'info': that level only shows in verbose mode.
+ setMessages(prev => [...prev, createSystemMessage(text, 'suggestion')]);
+ };
+ setToolJSX({
+ jsx: close('Modelo mantido. Use /model quando quiser trocar.')} onSwitch={model => {
+ saveLastVerbooModel(model);
+ setAppState(prev => ({
+ ...prev,
+ mainLoopModel: model,
+ mainLoopModelForSession: null
+ }));
+ close(limitSwitchDoneMessage(model, turn));
+ if (turn.prompt === null || turn.toolsRan) return;
+ // Nothing ran: the failed attempt leaves history, so the model gets the
+ // request once. fromKeybinding keeps the draft and skips adding to history.
+ const prompt = turn.prompt;
+ setMessages(prev => prev.filter(message => message.uuid !== turn.promptUuid && message.uuid !== last.uuid));
+ setLimitResendPrompt(prompt);
+ }} />,
+ shouldHidePromptInput: true,
+ showSpinner: false,
+ isLocalJSXCommand: true
+ });
+ }, [messages]);
const handleExit = useCallback(async () => {
setIsExiting(true);
// In bg sessions, always detach instead of kill — even when a worktree is
@@ -4058,9 +4134,13 @@ export function REPL({
queuedCommands
});
}, [queryGuard, commands, setToolJSX, getToolUseContext, messages, mainLoopModel, ideSelection, setUserInputOnProcessing, canUseTool, setAbortController, onQuery, addNotification, setAppState, onBeforeQuery, awaitPendingHooks]);
+ // VERBOO-BRAND: a queued message waits for the choice on the limit dialog; it
+ // must not hit the account that just ran out while the dialog is opening.
+ const lastMessage = messages.at(-1);
+ const isLimitSwitchPending = limitResendPrompt !== null || (lastMessage !== undefined && handledProviderLimitRef.current !== lastMessage.uuid && providerLimitReason(lastMessage) !== null);
useQueueProcessor({
executeQueuedInput,
- hasActiveLocalJsxUI: isShowingLocalJSXCommand,
+ hasActiveLocalJsxUI: isShowingLocalJSXCommand || isLimitSwitchPending,
queryGuard
});
diff --git a/src/services/api/errors.ts b/src/services/api/errors.ts
index ccb19e2625..3a696dc5ea 100644
--- a/src/services/api/errors.ts
+++ b/src/services/api/errors.ts
@@ -60,6 +60,12 @@ import {
} from '../claudeAiLimits.js'
import { shouldProcessRateLimits } from '../rateLimitMocking.js' // Used for /mock-limits command
import { extractConnectionErrorDetails, formatAPIError } from './errorUtils.js'
+import {
+ classifyProviderLimitError,
+ formatProviderLimitMessage,
+ PROVIDER_LIMIT_MESSAGE_PREFIX,
+} from './providerLimitErrors.js'
+import { getActiveModelIdentity } from '../../utils/model/activeModelIdentity.js'
import {
extractOpenAICategoryHost,
extractOpenAICategoryMarker,
@@ -207,7 +213,9 @@ function mapOpenAICompatibilityFailureToAssistantMessage(options: {
export function startsWithApiErrorPrefix(text: string): boolean {
return (
text.startsWith(API_ERROR_MESSAGE_PREFIX) ||
- text.startsWith(`Please run /login · ${API_ERROR_MESSAGE_PREFIX}`)
+ text.startsWith(`Please run /login · ${API_ERROR_MESSAGE_PREFIX}`) ||
+ // VERBOO-BRAND: also a failed request; /compact must not keep it as a summary.
+ text.startsWith(PROVIDER_LIMIT_MESSAGE_PREFIX)
)
}
export const PROMPT_TOO_LONG_ERROR_MESSAGE = 'Prompt is too long'
@@ -647,6 +655,18 @@ export function getAssistantMessageFromError(
})
}
}
+ // VERBOO-BRAND: the user's own account (ChatGPT plan, OpenAI or Anthropic
+ // key) ran out. Retrying will not help; the REPL offers a Verboo model.
+ const providerLimit = classifyProviderLimitError(
+ error,
+ getActiveModelIdentity(model).provider,
+ )
+ if (providerLimit) {
+ return createAssistantAPIErrorMessage({
+ content: formatProviderLimitMessage(providerLimit),
+ error: 'rate_limit',
+ })
+ }
// Check for SDK timeout errors
if (
error instanceof APIConnectionTimeoutError ||
diff --git a/src/services/api/providerLimitErrors.test.ts b/src/services/api/providerLimitErrors.test.ts
new file mode 100644
index 0000000000..598f7344fe
--- /dev/null
+++ b/src/services/api/providerLimitErrors.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ classifyProviderLimitError,
+ formatProviderLimitMessage,
+ limitSwitchReasonFromMessage,
+ PROVIDER_LIMIT_MESSAGE_PREFIX,
+} from './providerLimitErrors.js'
+
+const NOW = Date.UTC(2026, 10, 3, 12, 0, 0)
+
+describe('classifyProviderLimitError', () => {
+ test('ChatGPT plan usage limit (Codex) with renewal time', () => {
+ const error = Object.assign(
+ new Error('429 {"error":{"type":"usage_limit_reached","message":"The usage limit has been reached","resets_in_seconds":3600}}'),
+ { status: 429 },
+ )
+ const limit = classifyProviderLimitError(error, 'Codex', NOW)
+ expect(limit?.providerLabel).toBe('ChatGPT')
+ expect(limit?.resetsAt?.getTime()).toBe(NOW + 3_600_000)
+ })
+
+ test('OpenAI API key without quota', () => {
+ const error = Object.assign(
+ new Error('429 You exceeded your current quota, please check your plan and billing details.'),
+ { status: 429, error: { code: 'insufficient_quota' } },
+ )
+ expect(classifyProviderLimitError(error, 'OpenAI', NOW)).toEqual({ providerLabel: 'OpenAI' })
+ })
+
+ test('Anthropic API key without credit', () => {
+ const error = Object.assign(
+ new Error('400 Your credit balance is too low to access the Anthropic API.'),
+ { status: 400 },
+ )
+ expect(classifyProviderLimitError(error, 'Claude', NOW)).toEqual({ providerLabel: 'Anthropic' })
+ })
+
+ test('temporary rate limits and Verboo models are not account limits', () => {
+ const rateLimited = Object.assign(new Error('429 Rate limit reached for requests'), { status: 429 })
+ expect(classifyProviderLimitError(rateLimited, 'OpenAI', NOW)).toBeNull()
+ expect(classifyProviderLimitError(rateLimited, 'Codex', NOW)).toBeNull()
+ const quota = Object.assign(new Error('insufficient_quota'), { status: 429 })
+ expect(classifyProviderLimitError(quota, 'Verboo', NOW)).toBeNull()
+ })
+})
+
+test('the message carries the prefix the REPL uses to open the switch', () => {
+ const text = formatProviderLimitMessage(
+ { providerLabel: 'ChatGPT', resetsAt: new Date(NOW + 3_600_000) },
+ NOW,
+ )
+ expect(text.startsWith(PROVIDER_LIMIT_MESSAGE_PREFIX)).toBe(true)
+ expect(text).toContain('plano ChatGPT')
+ expect(text).toContain('renova')
+ expect(limitSwitchReasonFromMessage(text)).toContain('o limite do seu plano ChatGPT acabou')
+ expect(limitSwitchReasonFromMessage('API Error: 500 Internal error')).toBeNull()
+})
+
+test('the API error path, retries and REPL are wired to the account limit flow', async () => {
+ const { resolve } = await import('path')
+ const read = (relative: string) => Bun.file(resolve(import.meta.dir, '../..', relative)).text()
+ const errors = await read('services/api/errors.ts')
+ expect(errors.indexOf('classifyProviderLimitError(')).toBeGreaterThan(-1)
+ expect(errors.indexOf('classifyProviderLimitError(')).toBeLessThan(
+ errors.indexOf('Your credit balance is too low'),
+ )
+ const retry = await read('services/api/withRetry.ts')
+ expect(retry).toContain("msg.includes('usage_limit_reached')")
+ expect(retry).toContain("msg.includes('insufficient_quota')")
+ const repl = await read('screens/REPL.tsx')
+ expect(repl).toContain('limitSwitchReasonFromMessage(')
+ expect(repl).toContain('(messages.at(-1)?.uuid)')
+})
diff --git a/src/services/api/providerLimitErrors.ts b/src/services/api/providerLimitErrors.ts
new file mode 100644
index 0000000000..454fa54695
--- /dev/null
+++ b/src/services/api/providerLimitErrors.ts
@@ -0,0 +1,108 @@
+/**
+ * Recognizes "your plan/balance ran out" errors from the providers the user
+ * connects with their own account (ChatGPT plan via Codex, OpenAI API key,
+ * Anthropic API key). Unlike a temporary rate limit, retrying does not help;
+ * the REPL offers to switch to a Verboo model instead.
+ */
+import type { ActiveModelProvider } from '../../utils/model/activeModelIdentity.js'
+
+export const PROVIDER_LIMIT_MESSAGE_PREFIX = 'Limite da sua conta atingido:'
+
+export type ProviderLimit = {
+ /** User-facing name of the account that ran out (ChatGPT, OpenAI, Anthropic). */
+ providerLabel: string
+ /** When the plan window renews, if the provider said so. */
+ resetsAt?: Date
+}
+
+function errorText(error: unknown): string {
+ if (!error) return ''
+ if (typeof error === 'string') return error
+ const parts: string[] = []
+ const record = error as { message?: unknown; error?: unknown; body?: unknown }
+ if (typeof record.message === 'string') parts.push(record.message)
+ for (const extra of [record.error, record.body]) {
+ if (extra && typeof extra === 'object') {
+ try {
+ parts.push(JSON.stringify(extra))
+ } catch {
+ // Not serializable; the message is enough.
+ }
+ } else if (typeof extra === 'string') {
+ parts.push(extra)
+ }
+ }
+ return parts.join('\n')
+}
+
+function errorStatus(error: unknown): number | undefined {
+ const status = (error as { status?: unknown } | undefined)?.status
+ return typeof status === 'number' ? status : undefined
+}
+
+function parseResetsAt(text: string, now: number): Date | undefined {
+ const at = /"resets_at"\s*:\s*(\d{9,})/.exec(text)
+ if (at) return new Date(Number(at[1]) * 1000)
+ const inSeconds = /"resets_in_seconds"\s*:\s*(\d+)/.exec(text)
+ if (inSeconds) return new Date(now + Number(inSeconds[1]) * 1000)
+ return undefined
+}
+
+export function classifyProviderLimitError(
+ error: unknown,
+ provider: ActiveModelProvider,
+ now = Date.now(),
+): ProviderLimit | null {
+ const text = errorText(error)
+ const lower = text.toLowerCase()
+ const status = errorStatus(error)
+
+ if (provider === 'Codex') {
+ if (
+ lower.includes('usage_limit_reached') ||
+ (status === 429 && lower.includes('usage limit'))
+ ) {
+ return { providerLabel: 'ChatGPT', resetsAt: parseResetsAt(text, now) }
+ }
+ return null
+ }
+ if (provider === 'OpenAI') {
+ if (
+ lower.includes('insufficient_quota') ||
+ lower.includes('exceeded your current quota')
+ ) {
+ return { providerLabel: 'OpenAI' }
+ }
+ return null
+ }
+ if (provider === 'Claude') {
+ if (lower.includes('credit balance is too low')) {
+ return { providerLabel: 'Anthropic' }
+ }
+ return null
+ }
+ // Verboo models have their own plan messages from the router.
+ return null
+}
+
+function formatResetsAt(resetsAt: Date, now: number): string {
+ const sameDay = new Date(now).toDateString() === resetsAt.toDateString()
+ const time = resetsAt.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' })
+ return sameDay
+ ? time
+ : `${resetsAt.toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit' })} às ${time}`
+}
+
+export function formatProviderLimitMessage(limit: ProviderLimit, now = Date.now()): string {
+ const what = limit.providerLabel === 'ChatGPT'
+ ? 'o limite do seu plano ChatGPT acabou'
+ : `o saldo ou a cota da sua chave ${limit.providerLabel} acabou`
+ const renews = limit.resetsAt ? ` (renova ${formatResetsAt(limit.resetsAt, now)})` : ''
+ return `${PROVIDER_LIMIT_MESSAGE_PREFIX} ${what}${renews}. Você pode trocar para um modelo Verboo e continuar.`
+}
+
+/** What ran out, taken from the error text, for the REPL's switch dialog. */
+export function limitSwitchReasonFromMessage(text: string): string | null {
+ if (!text.startsWith(PROVIDER_LIMIT_MESSAGE_PREFIX)) return null
+ return text.slice(PROVIDER_LIMIT_MESSAGE_PREFIX.length).trim()
+}
diff --git a/src/services/api/withRetry.ts b/src/services/api/withRetry.ts
index 0552e7910e..2ba1caf651 100644
--- a/src/services/api/withRetry.ts
+++ b/src/services/api/withRetry.ts
@@ -11,6 +11,7 @@ import { isAwsCredentialsProviderError } from 'src/utils/aws.js'
import { logForDebugging } from 'src/utils/debug.js'
import { logError } from 'src/utils/log.js'
import { getActiveModelIdentity } from 'src/utils/model/activeModelIdentity.js'
+import { classifyProviderLimitError } from './providerLimitErrors.js'
import { createSystemAPIErrorMessage } from 'src/utils/messages.js'
import { getAPIProvider, getAPIProviderForStatsig } from 'src/utils/model/providers.js'
import {
@@ -111,7 +112,11 @@ function isQuotaExhausted(error: any): boolean {
return (
error?.status === 429 &&
- (msg.includes('limit: 0') || msg.includes('exceeded your current quota'))
+ (msg.includes('limit: 0') ||
+ msg.includes('exceeded your current quota') ||
+ // VERBOO-BRAND: own-account limits. They renew or need a top-up later.
+ msg.includes('insufficient_quota') ||
+ msg.includes('usage_limit_reached'))
)
}
@@ -290,6 +295,11 @@ export async function* withRetry(
{ level: 'error' },
)
if (isQuotaExhausted(error)) {
+ // VERBOO-BRAND: keep the provider's error, so the REPL can name the
+ // account that ran out and offer the switch to a Verboo model.
+ if (classifyProviderLimitError(error, getActiveModelIdentity(options.model).provider)) {
+ throw new CannotRetryError(error, retryContext)
+ }
throw new CannotRetryError(
new Error(
'API quota exhausted or not enabled.\n' +
diff --git a/src/utils/config.ts b/src/utils/config.ts
index a60fe3feda..042df56a49 100644
--- a/src/utils/config.ts
+++ b/src/utils/config.ts
@@ -603,6 +603,8 @@ export type GlobalConfig = {
teammateMode?: 'auto' | 'tmux' | 'in-process' // How to spawn teammates (default: 'auto')
// Last Verboo model used across sessions (persisted for default selection)
lastVerbooModel?: string
+ /** Last model used from the Verboo catalog; lastVerbooModel also follows own-account models. */
+ lastRouterModel?: string
// Model for new teammates when the tool call doesn't pass one.
// undefined = hardcoded Opus (backward-compat); null = leader's model; string = model alias/ID.
diff --git a/src/utils/model/model.ts b/src/utils/model/model.ts
index c78daf3c01..3c494d8975 100644
--- a/src/utils/model/model.ts
+++ b/src/utils/model/model.ts
@@ -88,8 +88,17 @@ export function getDefaultVerbooModel(): ModelName {
}
export function saveLastVerbooModel(model: string): void {
- if (getGlobalConfig().lastVerbooModel !== model) {
- saveGlobalConfig(current => ({ ...current, lastVerbooModel: model }))
+ const isRouterModel = getCachedVerbooModels()?.some(candidate => candidate.id === model) === true
+ const config = getGlobalConfig()
+ if (
+ config.lastVerbooModel !== model ||
+ (isRouterModel && config.lastRouterModel !== model)
+ ) {
+ saveGlobalConfig(current => ({
+ ...current,
+ lastVerbooModel: model,
+ ...(isRouterModel ? { lastRouterModel: model } : {}),
+ }))
}
}