Your team of AI agents, on your Mac, Windows or Linux. Agents that talk in channels, write code, review each other and use your tools, on the Claude Code, Codex, OpenCode or Pi you already have. Anything that touches the real world waits for your yes.
TypeScript agent-teamagentic-aiai-agentsai-assistantclaude-codecodexcursorelectrongrokgrok-bot-alternativelinuxlocal-firstmacosmcpmulti-agentopenclaw-alternativeopencodewindows
Let an agent fall back to a reserve model when its subscription is out (#70)
Eduardo Machado6c391cb97856
diff --git a/src/core/db.ts b/src/core/db.tsindex 5f7a626..9f548d9 100644--- a/src/core/db.ts+++ b/src/core/db.ts@@ -221,6 +221,9 @@ const MIGRATIONS = [`,`ALTER TABLE agents ADD COLUMN apps TEXT NOT NULL DEFAULT '[]';+ `,+ `+ ALTER TABLE agents ADD COLUMN fallback_model TEXT;`]@@ -304,6 +307,7 @@ export class Db {color: str(r['color']) as AgentColor,instructions: str(r['instructions']),modelId: str(r['model']),+ ...(str(r['fallback_model']) ? { fallbackModelId: str(r['fallback_model']) } : {}),effort: str(r['effort']) as Effort,limit: Number(r['limit_tokens']),used: this.usedThisMonth(str(r['id'])),@@ -333,14 +337,14 @@ export class Db {saveAgent(a: Agent): void {this.db.prepare(- `INSERT INTO agents (id, name, handle, role, color, instructions, model, effort, limit_tokens, grants, memory_mode, computer, computer_kind, web, browser, apps, auto_approve, archived, kind, created_at)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ `INSERT INTO agents (id, name, handle, role, color, instructions, model, fallback_model, effort, limit_tokens, grants, memory_mode, computer, computer_kind, web, browser, apps, auto_approve, archived, kind, created_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)ON CONFLICT (id) DO UPDATE SET name = excluded.name, handle = excluded.handle, role = excluded.role,- color = excluded.color, instructions = excluded.instructions, model = excluded.model, effort = excluded.effort,+ color = excluded.color, instructions = excluded.instructions, model = excluded.model, fallback_model = excluded.fallback_model, effort = excluded.effort,limit_tokens = excluded.limit_tokens, grants = excluded.grants, memory_mode = excluded.memory_mode,computer = excluded.computer, computer_kind = excluded.computer_kind, web = excluded.web, browser = excluded.browser, apps = excluded.apps, auto_approve = excluded.auto_approve, archived = excluded.archived, kind = COALESCE(excluded.kind, agents.kind)`)- .run(a.id, a.name, a.handle, a.role, a.color, a.instructions, a.modelId, a.effort, a.limit, JSON.stringify(a.grants), a.memory ?? 'auto', a.computer ? 1 : 0, a.computerKind === 'mac' ? 'mac' : 'linux', a.web === false ? 0 : 1, a.browser ? 1 : 0, JSON.stringify(a.apps ?? []), JSON.stringify(a.autoApprove ?? []), a.archived ? 1 : 0, a.kind ?? null, Date.now())+ .run(a.id, a.name, a.handle, a.role, a.color, a.instructions, a.modelId, a.fallbackModelId || null, a.effort, a.limit, JSON.stringify(a.grants), a.memory ?? 'auto', a.computer ? 1 : 0, a.computerKind === 'mac' ? 'mac' : 'linux', a.web === false ? 0 : 1, a.browser ? 1 : 0, JSON.stringify(a.apps ?? []), JSON.stringify(a.autoApprove ?? []), a.archived ? 1 : 0, a.kind ?? null, Date.now())}// Kept apart from saveAgent: folders change only after the core checks them.diff --git a/src/core/engines/cli.ts b/src/core/engines/cli.tsindex d0f359a..85a5d73 100644--- a/src/core/engines/cli.ts+++ b/src/core/engines/cli.ts@@ -72,6 +72,13 @@ export function parseJson(line: string): Record<string, unknown> | null {}}+// The CLI's own words when the subscription or the provider is out for now: Claude Code's+// "You've hit your limit" and 5-hour or weekly limit, Codex's "usage limit", Gemini's quota+// (RESOURCE_EXHAUSTED), OpenCode's and the providers' 429s. Not Tucano's own monthly limit,+// which never reaches here as an engine error.+const OUT_OF_QUOTA = /usage limit|hit your (usage )?limit|limit reached|limit_reached|quota|resource_exhausted|rate.?limit|too many requests|\b429\b|insufficient_quota|credit balance is too low|out of (extra )?usage/i+export const outOfQuota = (message: string): boolean => OUT_OF_QUOTA.test(message)+export const num = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) ? v : 0)export function lastLines(text: string, n = 3): string {diff --git a/src/core/engines/fake.ts b/src/core/engines/fake.tsindex dd7a76e..ad3cc17 100644--- a/src/core/engines/fake.ts+++ b/src/core/engines/fake.ts@@ -14,6 +14,11 @@ export function fakeEngine(id: Engine['id'], opts: { delayMs?: number; reply?: (id,async *run(turn): AsyncIterable<EngineEvent> {const last = lastMessage(turn.prompt)+ // "acabou o limite": Claude's subscription is out, to see an agent's reserve model take over.+ if (id === 'claude' && /acabou o limite|out of quota/i.test(last) && turn.system !== routerSystem() && turn.system !== memorySystem()) {+ yield { type: 'error', message: "You've hit your limit · resets 5pm" }+ return+ }let reply: stringlet spend = 0 // "gaste N tokens": a reply that costs that much, to see the budget pauseif (turn.system === routerSystem()) {diff --git a/src/core/runs.ts b/src/core/runs.tsindex ac9afe9..cee9102 100644--- a/src/core/runs.ts+++ b/src/core/runs.ts@@ -16,6 +16,7 @@ import { LER_SKILL, PROPOR_SKILL, SKILL_TOOL_NAMES, type Skills } from './skillsimport { availableModels, builderSection, draftFrom, PROPOR_AGENTE } from './tuca'import type { Db } from './db'import type { Engine, TurnImage } from './engines/types'+import { outOfQuota } from './engines/cli'import { textResult, type Gateway, type ToolDef } from './gateway'import { JEV_MODEL, routeJev } from './jev'import { route } from './router'@@ -423,13 +424,23 @@ export class Runner {}}+ // The agent's reserve model, when it has one that can run now: another model, on a harness that's ready.+ private reserveFor(agent: Agent, settings: Settings): ReturnType<typeof modelInfo> {+ const reserve = agent.fallbackModelId && agent.fallbackModelId !== agent.modelId ? modelInfo(agent.fallbackModelId) : undefined+ const status = reserve?.id ? settings.engines[reserve.engine] : undefined+ return reserve && status?.installed && status.loggedIn ? reserve : undefined+ }+private async execute(agent: Agent, conv: Conversation, opts: { depth: number; existing?: Message; task?: string; work?: string; routine?: boolean }): Promise<Message> {const { db, emit, engines } = this.depsconst settings = await this.deps.settings()agent = db.agent(agent.id) ?? agent // limits or instructions may have changed while queuedconst model = modelInfo(agent.modelId)- const engineId: EngineId = model?.engine ?? 'claude'- const engineLabel = `${ENGINES[engineId].label} · ${model?.label ?? agent.modelId}`+ // The model this reply runs on: the agent's, or its reserve once the main one's subscription is out.+ let modelId = agent.modelId+ let modelName = model?.id ?? agent.modelId+ let engineId: EngineId = model?.engine ?? 'claude'+ let engineLabel = `${ENGINES[engineId].label} · ${model?.label ?? agent.modelId}`const msg: Message = opts.existing ?? { id: randomUUID(), conversationId: conv.id, author: { kind: 'agent', id: agent.id }, text: '', at: Date.now() }const started = Date.now()@@ -528,6 +539,7 @@ export class Runner {const seen = new Map<string, { result: string; n: number }>()let failing = 0 // tool calls failing in a rowlet inFlight = 0 // a tool running has its own timeout, so it isn't silence+ let acted = false // called a tool or searched the web: a failed turn then isn't redone on the reserve modellet lastSign = Date.now()let overBudget = falselet refusedOver = 0@@ -1012,6 +1024,7 @@ export class Runner {)}inFlight+++ acted = truesign()try {const r = await runTool(name, args)@@ -1050,64 +1063,83 @@ export class Runner {.slice(-MAX_TURN_IMAGES).flatMap((a) => (blockOf.has(a.messageId) ? [{ block: blockOf.get(a.messageId)!, path: join(this.deps.dataDir!, 'artifacts', a.id, a.name), mime: mimeOf(a.name) }] : []))try {- const events = engines[engineId].run({- model: model?.id ?? agent.modelId,- effort: agent.effort,- system: systemPrompt({- agent,- settings,- conversation: conv,- peers,- memories: promptMemories,- canRemember,- hasComputer: !!computers,- browser: !!browser,- apps: apps ? agent.apps : undefined,- offline: (this.deps.connectors?.list() ?? []).filter((c) => c.status !== 'connected' && (agent.grants[c.id] ?? 'none') !== 'none').map((c) => c.name),- macFolder: computers?.mac && agent.computerKind === 'mac' ? computers.mac.cwd(agent) : undefined,- web: agent.web !== false,- routines: routines?.forAgent(agent.id),- skills: skills && mySkills,- publish: repos,- builder: builds ? builderSection(settings, { models: this.deps.models?.() ?? availableModels(settings), connectors: this.deps.connectors?.list() ?? [], team: db.agents().filter((a) => !a.archived && a.kind !== 'tuca'), own: agent.modelId }) : undefined- }),- prompt: blocks.join('\n\n'),- blocks,- images,- cwd,- signal: control.ctl.signal,- mcpUrl: session?.url,- web: agent.web !== false- })- for await (const ev of events) {- sign()- if (ev.type === 'text') {- msg.text += ev.delta- pending += ev.delta- timer ??= setTimeout(flush, DELTA_FLUSH_MS)- } else if (ev.type === 'progress') {- progress = { tokens: ev.tokens, cacheRead: ev.cacheRead ?? 0 }- const counted = Math.round(ev.tokens - progress.cacheRead * (1 - CACHE_READ_WEIGHT))- if (used + counted > agent.limit) halt('limit')- else if (counted > budget) {- if (!overBudget) addSteps({ id: randomUUID(), label: L('Chegou no teto da resposta', 'Reached the reply cap'), detail: `${tokenCount(budget)} tokens`, status: 'error' })- overBudget = true- if (counted > budget * BUDGET_OVERRUN) halt('budget')+ for (;;) {+ try {+ const events = engines[engineId].run({+ model: modelName,+ effort: agent.effort,+ system: systemPrompt({+ agent,+ settings,+ conversation: conv,+ peers,+ memories: promptMemories,+ canRemember,+ hasComputer: !!computers,+ browser: !!browser,+ apps: apps ? agent.apps : undefined,+ offline: (this.deps.connectors?.list() ?? []).filter((c) => c.status !== 'connected' && (agent.grants[c.id] ?? 'none') !== 'none').map((c) => c.name),+ macFolder: computers?.mac && agent.computerKind === 'mac' ? computers.mac.cwd(agent) : undefined,+ web: agent.web !== false,+ routines: routines?.forAgent(agent.id),+ skills: skills && mySkills,+ publish: repos,+ builder: builds ? builderSection(settings, { models: this.deps.models?.() ?? availableModels(settings), connectors: this.deps.connectors?.list() ?? [], team: db.agents().filter((a) => !a.archived && a.kind !== 'tuca'), own: agent.modelId }) : undefined+ }),+ prompt: blocks.join('\n\n'),+ blocks,+ images,+ cwd,+ signal: control.ctl.signal,+ mcpUrl: session?.url,+ web: agent.web !== false+ })+ for await (const ev of events) {+ sign()+ if (ev.type === 'text') {+ msg.text += ev.delta+ pending += ev.delta+ timer ??= setTimeout(flush, DELTA_FLUSH_MS)+ } else if (ev.type === 'progress') {+ progress = { tokens: ev.tokens, cacheRead: ev.cacheRead ?? 0 }+ const counted = Math.round(ev.tokens - progress.cacheRead * (1 - CACHE_READ_WEIGHT))+ if (used + counted > agent.limit) halt('limit')+ else if (counted > budget) {+ if (!overBudget) addSteps({ id: randomUUID(), label: L('Chegou no teto da resposta', 'Reached the reply cap'), detail: `${tokenCount(budget)} tokens`, status: 'error' })+ overBudget = true+ if (counted > budget * BUDGET_OVERRUN) halt('budget')+ }+ } else if (ev.type === 'quota') {+ this.deps.onQuota?.(ev.quota)+ } else if (ev.type === 'web') {+ // Not through the gateway, so it can't be refused or warned: the same search over and over is a loop.+ acted = true+ addSteps({ id: randomUUID(), label: ev.action === 'search' ? L('Pesquisou na web', 'Searched the web') : L('Leu uma página', 'Read a page'), detail: ev.detail, status: 'done' })+ if (repeated(`web ${ev.action} ${ev.detail}`, '') >= REPEAT_STOP) halt('loop')+ } else if (ev.type === 'done') {+ result = ev+ } else if (ev.type === 'error') {+ error = ev.message+ }}- } else if (ev.type === 'quota') {- this.deps.onQuota?.(ev.quota)- } else if (ev.type === 'web') {- // Not through the gateway, so it can't be refused or warned: the same search over and over is a loop.- addSteps({ id: randomUUID(), label: ev.action === 'search' ? L('Pesquisou na web', 'Searched the web') : L('Leu uma página', 'Read a page'), detail: ev.detail, status: 'done' })- if (repeated(`web ${ev.action} ${ev.detail}`, '') >= REPEAT_STOP) halt('loop')- } else if (ev.type === 'done') {- result = ev- } else if (ev.type === 'error') {- error = ev.message+ } catch (e) {+ error = e instanceof Error ? e.message : String(e)}+ // The main model's subscription is out before it did anything: the same reply goes to the reserve, once.+ // After a tool call it doesn't, since that would run the call again; the next reply starts on the main model.+ const reserve = modelId === agent.modelId && !result && error && !control.reason && !acted && !question && !approval && (!msg.text.trim() || outOfQuota(msg.text)) && outOfQuota(error) ? this.reserveFor(agent, settings) : undefined+ if (!reserve) break+ const from = engineLabel+ flush()+ msg.text = '' // the CLI's own "you've hit your limit", when it wrote it as text+ modelId = agent.fallbackModelId!+ modelName = reserve.id+ engineId = reserve.engine+ engineLabel = `${ENGINES[engineId].label} · ${reserve.label}`+ addSteps({ id: randomUUID(), label: L('Foi pro modelo reserva', 'Moved to the reserve model'), detail: L(`${from} está sem limite agora; segue no ${engineLabel}`, `${from} is out of quota for now; going on with ${engineLabel}`), status: 'done' })+ error = null+ progress = { tokens: 0, cacheRead: 0 }}- } catch (e) {- error = e instanceof Error ? e.message : String(e)} finally {clearInterval(stall)flush()@@ -1117,9 +1149,9 @@ export class Runner {const ms = Date.now() - startedconst receipt: Receipt | undefined = result- ? { model: agent.modelId, ms, ...result.usage }+ ? { model: modelId, ms, ...result.usage }: progress.tokens > 0- ? { model: agent.modelId, ms, inputTokens: progress.tokens, cacheReadTokens: progress.cacheRead, outputTokens: 0 } // partial: what the stream reported before it ended+ ? { model: modelId, ms, inputTokens: progress.tokens, cacheReadTokens: progress.cacheRead, outputTokens: 0 } // partial: what the stream reported before it ended: undefinedif (receipt) db.addReceipt({ ...receipt, messageId: msg.id, agentId: agent.id, engine: engineId, at: Date.now(), work })const usedNow = db.usedThisMonth(agent.id)diff --git a/src/renderer/src/components/Pages.tsx b/src/renderer/src/components/Pages.tsxindex 5377840..59c5f26 100644--- a/src/renderer/src/components/Pages.tsx+++ b/src/renderer/src/components/Pages.tsx@@ -43,6 +43,7 @@ import {saveSkill,skillApplies,modelInfo,+ MODELS,type Agent,type AgentColor,type Connector,@@ -55,7 +56,7 @@ import {isTeam,reachable} from '../store'-import { HarnessList, HarnessMcps, ModelPicker, onGateway, OutsideGateway } from './Harness'+import { HarnessList, HarnessMcps, ModelPicker, onGateway, OutsideGateway, usableEngines } from './Harness'import { AppsCard } from './Apps'import { ApprovalCard } from './Conversation'import { AgentAvatar, Icon, NumberInput, SleepingToucan, time, tokens, UsageBar } from './ui'@@ -523,6 +524,7 @@ export function AgentPage({ id, draft: proposed, fromMessage }: { id?: string; d{pane('perfil') && (<Card title={L('Harness e modelo', 'Harness and model')} lead={L('O agente roda num dos harnesses que você usa, como você o configurou: no seu plano, no gateway da empresa ou no seu provedor.', 'The agent runs on one of the harnesses you use, the way you set it up: on your plan, your company’s gateway or your provider.')}><ModelPicker value={draft.modelId} onChange={(modelId) => patch({ modelId })} />+ <ReserveModel draft={draft} patch={patch} />{!engineStatus.loggedIn && (<p className="hint hint--warn"><Icon name="lock" size={13} />{' '}@@ -1244,6 +1246,40 @@ function Tabs({ page, tabs }: { page: string; tabs: TabList }): ReactNode {}// A model to run with, from what each harness in use offers, or another by name.+// Where the agent's replies go when its model's subscription is out (a 5-hour or weekly limit, a 429).+// Off by default; turned on, it starts on another harness, since the same subscription is out for both.+function ReserveModel({ draft, patch }: { draft: Agent; patch: (p: Partial<Agent>) => void }): ReactNode {+ const usable = useStore((s) => usableEngines(s.settings))+ const main = modelInfo(draft.modelId)?.engine+ const on = !!draft.fallbackModelId+ const first = (): string => {+ const other = usable.find((e) => e !== main) ?? usable[0]+ return MODELS.find((m) => m.engine === other)?.id ?? draft.modelId+ }+ const reserve = draft.fallbackModelId ? modelInfo(draft.fallbackModelId) : undefined+ return (+ <div className="reserve">+ <div className="key-row">+ <Icon name="layers" />+ <div className="grow">+ <strong>{L('Modelo reserva', 'Reserve model')}</strong>+ <p className="muted small">+ {L(+ `Quando a assinatura do modelo principal chega no limite (o de 5 horas ou o semanal), a resposta segue no reserva. Na resposta seguinte, ${draft.name || 'o agente'} tenta o principal de novo.`,+ `When the main model’s subscription hits its limit (the 5-hour or the weekly one), the reply goes on with the reserve. On the next reply, ${draft.name || 'the agent'} tries the main one again.`+ )}+ </p>+ </div>+ <Toggle on={on} onChange={(v) => patch({ fallbackModelId: v ? first() : undefined })} />+ </div>+ {on && <ModelPicker value={draft.fallbackModelId!} onChange={(fallbackModelId) => patch({ fallbackModelId })} />}+ {on && reserve && reserve.engine === main && (+ <p className="hint hint--warn">{L('É o mesmo harness do principal: se o limite for da assinatura, ele também vai estar sem.', 'It’s the same harness as the main one: if the limit is the subscription’s, it’ll be out too.')}</p>+ )}+ </div>+ )+}+export function ModelSelect(p: { value: string; onChange: (v: string) => void; jev?: boolean; engines?: EngineId[] }): ReactNode {return <ModelPicker {...p} />}diff --git a/src/renderer/src/styles.css b/src/renderer/src/styles.cssindex 52b93f5..5552197 100644--- a/src/renderer/src/styles.css+++ b/src/renderer/src/styles.css@@ -3921,6 +3921,13 @@ table.csv th {font-size: 13px;line-height: 1.5;}+/* An agent's reserve model, under the main one. */+.reserve {+ display: grid;+ gap: 10px;+ margin-bottom: 16px;+}+.model-picker {display: flex;flex-wrap: wrap;diff --git a/src/shared/types.ts b/src/shared/types.tsindex d704b6d..4bf6626 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -57,6 +57,9 @@ export interface Agent {color: AgentColorinstructions: stringmodelId: string+ // Where a reply goes when modelId's subscription is out (its 5-hour or weekly limit, a 429): tried+ // only when the main model failed before doing anything, and the next reply tries the main one again.+ fallbackModelId?: stringeffort: Effortlimit: number // tokens per monthused: number // tokens used this month, computed from receiptsdiff --git a/test/reserve.test.ts b/test/reserve.test.tsnew file mode 100644index 0000000..8ac4c73--- /dev/null+++ b/test/reserve.test.ts@@ -0,0 +1,136 @@+import { mkdtempSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { beforeEach, describe, expect, it } from 'vitest'+import type { Agent, EngineId, Message, Settings } from '../src/shared/types'+import { Db } from '../src/core/db'+import { outOfQuota } from '../src/core/engines/cli'+import { fakeEngine } from '../src/core/engines/fake'+import type { Engine, EngineEvent, Turn } from '../src/core/engines/types'+import { Runner } from '../src/core/runs'++const ready = { installed: true, loggedIn: true }+const agent = (extra: Partial<Agent> = {}): Agent => ({ id: 'a1', name: 'lia', handle: 'lia', role: '', color: 'sky', instructions: '', modelId: 'sonnet', effort: 'low', limit: 1_000_000, used: 0, grants: {}, memory: 'auto', computer: false, archived: false, ...extra })++// Claude says its subscription is out (as text, then as the error, like the CLI can), or fails some other way.+const failing = (message: string, text = ''): Engine & { turns: Turn[] } => {+ const turns: Turn[] = []+ return {+ id: 'claude',+ turns,+ run: (t) => {+ turns.push(t)+ return (async function* (): AsyncIterable<EngineEvent> {+ if (text) yield { type: 'text', delta: text }+ yield { type: 'error', message }+ })()+ }+ }+}+const counted = (engine: Engine): Engine & { turns: Turn[] } => {+ const turns: Turn[] = []+ return { id: engine.id, turns, run: (t) => (turns.push(t), engine.run(t)) }+}++let db: Db+let settings: Settings+let codex: ReturnType<typeof counted>++function runner(claude: Engine): Runner {+ codex = counted(fakeEngine('codex', { delayMs: 1 }))+ const engines: Record<EngineId, Engine> = { claude, codex, opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini') }+ return new Runner({ db, engines, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ad-work-')) })+}+const reply = (): Message => db.messages().find((m) => m.author.kind === 'agent')!++beforeEach(() => {+ db = new Db(join(mkdtempSync(join(tmpdir(), 'ad-db-')), 'test.db'))+ settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }+ db.saveAgent(agent({ fallbackModelId: 'gpt-5.6-luna' }))+ db.createConversation({ id: 'd1', kind: 'dm', name: 'a1', members: ['a1'] })+})++describe('the reserve model', () => {+ it('is kept with the agent, and cleared', () => {+ expect(db.agent('a1')!.fallbackModelId).toBe('gpt-5.6-luna')+ db.saveAgent(agent())+ expect(db.agent('a1')!.fallbackModelId).toBeUndefined()+ })++ it('takes the reply when the main model’s subscription is out, and the receipt says so', async () => {+ const claude = failing("You've hit your limit · resets 5pm", "You've hit your limit · resets 5pm")+ const r = runner(claude)+ await r.send('d1', 'oi')+ await r.idle()+ const m = reply()+ expect(m.run?.status).toBe('done')+ expect(m.text).toContain('Resposta de teste (codex')+ expect(m.text).not.toContain('hit your limit')+ expect(m.run?.steps.some((s) => s.label === 'Foi pro modelo reserva' && s.detail?.includes('Codex'))).toBe(true)+ expect(m.run?.receipt?.model).toBe('gpt-5.6-luna')+ expect(claude.turns).toHaveLength(1)+ expect(codex.turns).toHaveLength(1)+ })++ it('starts on the main model again on the next reply', async () => {+ const claude = failing('usage limit reached')+ const r = runner(claude)+ await r.send('d1', 'oi')+ await r.idle()+ await r.send('d1', 'e agora?')+ await r.idle()+ expect(claude.turns).toHaveLength(2)+ expect(codex.turns).toHaveLength(2)+ })++ it('isn’t used for other failures, nor without a reserve, nor when its harness isn’t ready', async () => {+ let claude = failing('Claude Code exited without a reply (code 1).')+ let r = runner(claude)+ await r.send('d1', 'oi')+ await r.idle()+ expect(reply().run?.status).toBe('failed')+ expect(codex.turns).toHaveLength(0)++ for (const setup of [() => db.saveAgent(agent()), () => (settings = { ...settings, engines: { ...settings.engines, codex: { installed: true, loggedIn: false } } })]) {+ db = new Db(join(mkdtempSync(join(tmpdir(), 'ad-db-')), 'test.db'))+ db.saveAgent(agent({ fallbackModelId: 'gpt-5.6-luna' }))+ db.createConversation({ id: 'd1', kind: 'dm', name: 'a1', members: ['a1'] })+ setup()+ claude = failing('usage limit reached')+ r = runner(claude)+ await r.send('d1', 'oi')+ await r.idle()+ expect(reply().run).toMatchObject({ status: 'failed', error: 'usage limit reached' })+ expect(codex.turns).toHaveLength(0)+ }+ })++ it('isn’t used once the reply already said something of its own', async () => {+ const r = runner(failing('rate limit', 'Vou abrir o arquivo e'))+ await r.send('d1', 'oi')+ await r.idle()+ expect(reply().run?.status).toBe('failed')+ expect(codex.turns).toHaveLength(0)+ })+})++describe('out of quota', () => {+ it('knows the CLIs’ words for a subscription that’s out', () => {+ for (const m of [+ "You've hit your limit · resets 5pm (America/Sao_Paulo)",+ 'Claude AI usage limit reached|1792374000',+ '5-hour limit reached ∙ resets 3pm',+ "You've hit your usage limit. Upgrade to Pro (https://chatgpt.com/explore/pro) or try again at 3:21 PM.",+ 'usage_limit_reached',+ '[API Error: 429 RESOURCE_EXHAUSTED] Quota exceeded for quota metric',+ 'Rate limit exceeded. Too many requests.',+ 'Your credit balance is too low to access the Anthropic API.'+ ])+ expect(outOfQuota(m), m).toBe(true)+ })++ it('leaves other failures alone', () => {+ for (const m of ["Claude Code isn't installed. See Settings.", 'Claude Code exited without a reply (code 1).', 'prompt is too long: 210000 tokens > 200000 maximum', 'Codex ended with an error.', 'Not logged in · Please run /login'])+ expect(outOfQuota(m), m).toBe(false)+ })+})