Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/commands/extract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -419,10 +419,10 @@ export async function extract(root: string, opts: { report?: boolean; review?: b

/** API creds → sdk; else a usable claude CLI → cli; else sdk (its
* resolution error names the options). LORE_LLM overrides. */
/** The backend for log lines: the CLI reads as the API once a limit switched this process to the fallback key. */
/** The backend for log lines: the CLI reads as the API once a limit or lost login switched this process to the fallback key. */
const backendLabel = (llm: Backend) => (llm === 'cli' && fallbackApiKey() ? 'api-fallback' : llm)

/** Run on the configured backend; on the CLI, a subscription limit switches to the fallback API key (llm-fallback). */
/** Run on the configured backend; on the CLI, a subscription limit or lost login switches to the fallback API key (llm-fallback). */
function onBackend<T>(cli: () => T, sdk: () => Promise<T>): Promise<T> {
return pickBackend() === 'sdk' ? sdk() : withCliFallback(cli, sdk)
}
Expand Down
66 changes: 49 additions & 17 deletions src/llm-fallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,24 @@ import { createSendMail, emailConfigFromEnv, type MailMessage } from './board/em
import { esc } from './markdown.js'

/**
* Subscription limits on the claude CLI backend. When `claude -p` reports a
* usage limit (weekly, daily, five-hour), the rest of this process calls the
* Claude API with LORE_FALLBACK_ANTHROPIC_API_KEY instead, and
* LORE_LLM_FALLBACK_NOTIFY gets one email per episode. Every new process
* Subscription limits and lost logins on the claude CLI backend. When
* `claude -p` reports a usage limit (weekly, daily, five-hour) or that it can
* no longer authenticate (an expired OAuth session or setup-token, a logout),
* the rest of this process calls the Claude API with
* LORE_FALLBACK_ANTHROPIC_API_KEY instead, and LORE_LLM_FALLBACK_NOTIFY gets
* one email per episode — for a lost login, with the steps to restore it,
* since unlike a limit it never resets by itself. (Nov 2026: the host's CLI
* session expired and every fold failed for six days without a word.) Every new process
* tries the CLI first — one fast rejected call while the limit lasts — so the
* subscription is used again as soon as it resets, and that first successful
* CLI call ends the episode. Without a fallback key, a limit fails as before.
*/

const LIMIT = /hit your (?:[\w-]+ )?limit|usage limit reached|[\w-]+ limit reached/i
const AUTH = /failed to authenticate|oauth (?:session|token)\b[^.]*\b(?:expired|revoked|invalid)|not logged in|please run \/login|invalid (?:api key|bearer token|oauth token)|authentication_error/i

export type FallbackKind = 'limit' | 'auth'
export interface CliFailure { kind: FallbackKind; reason: string }
const MARKER = () => join(loreHome(), 'llm-fallback.json')

let reason: string | undefined
Expand All @@ -38,23 +46,45 @@ export function usageLimitReason(err: unknown): string | undefined {
return LIMIT.test(message) ? message.replace(/^(?:load|extract): (?:claude cli error: )?/, '') : undefined
}

/** The login failure behind a failed CLI call (HTTP 401 or an auth message), or undefined. */
export function authFailureReason(err: unknown): string | undefined {
const stdout = (err as { stdout?: Buffer | string } | undefined)?.stdout?.toString()
if (stdout) {
try {
const envelope = JSON.parse(stdout) as { result?: unknown; api_error_status?: unknown }
const result = typeof envelope.result === 'string' ? envelope.result : ''
if (AUTH.test(result) || envelope.api_error_status === 401) return result || 'authentication failed (HTTP 401)'
} catch { /* not a CLI envelope */ }
}
const message = err instanceof Error ? err.message : String(err)
return AUTH.test(message) ? message.replace(/^(?:load|extract): (?:claude cli error: )?/, '') : undefined
}

/** Why a CLI failure should switch to the API key, or undefined when it should not. */
export function cliFailureReason(err: unknown): CliFailure | undefined {
const limit = usageLimitReason(err)
if (limit) return { kind: 'limit', reason: limit }
const auth = authFailureReason(err)
return auth ? { kind: 'auth', reason: auth } : undefined
}

/**
* Run `cli`; if it hits a subscription limit and a fallback key is set, switch
* Run `cli`; if it hits a subscription limit or has lost its login and a fallback key is set, switch
* this process to the API and run `api` instead. Once switched, `cli` is
* skipped for the rest of the process.
*/
export async function withCliFallback<T>(cli: () => T | Promise<T>, api: () => Promise<T>, notify: (reason: string) => Promise<void> = notifyFallback): Promise<T> {
export async function withCliFallback<T>(cli: () => T | Promise<T>, api: () => Promise<T>, notify: (reason: string, kind: FallbackKind) => Promise<void> = notifyFallback): Promise<T> {
if (reason && fallbackKey()) return api()
let result: T
try {
result = await cli()
} catch (err) {
const limit = usageLimitReason(err)
if (!limit || !fallbackKey()) throw err
const failure = cliFailureReason(err)
if (!failure || !fallbackKey()) throw err
activation ??= (async () => {
reason = limit
console.warn(`⚠ claude CLI: ${limit} — using the Claude API key for the rest of this run`)
try { await notify(limit) } catch (e) { console.warn(`⚠ fallback notice not sent: ${e instanceof Error ? e.message : String(e)}`) }
reason = failure.reason
console.warn(`⚠ claude CLI: ${failure.reason} — using the Claude API key for the rest of this run${failure.kind === 'auth' ? ' (the CLI login needs renewing: claude setup-token)' : ''}`)
try { await notify(failure.reason, failure.kind) } catch (e) { console.warn(`⚠ fallback notice not sent: ${e instanceof Error ? e.message : String(e)}`) }
})()
await activation
return api()
Expand All @@ -64,16 +94,16 @@ export async function withCliFallback<T>(cli: () => T | Promise<T>, api: () => P
}

/** Email LORE_LLM_FALLBACK_NOTIFY once per episode; the marker keeps later runs from repeating it. */
export async function notifyFallback(limit: string, send?: (msg: MailMessage) => Promise<void>): Promise<void> {
export async function notifyFallback(limit: string, kind: FallbackKind = 'limit', send?: (msg: MailMessage) => Promise<void>): Promise<void> {
if (existsSync(MARKER())) return
writeFileSync(MARKER(), JSON.stringify({ since: new Date().toISOString(), reason: limit }) + '\n')
writeFileSync(MARKER(), JSON.stringify({ since: new Date().toISOString(), kind, reason: limit }) + '\n')
const to = process.env.LORE_LLM_FALLBACK_NOTIFY
const cfg = emailConfigFromEnv()
if (!to || (!send && (!cfg.from || !cfg.api))) {
console.warn('⚠ fallback notice not emailed: set LORE_LLM_FALLBACK_NOTIFY and the board email settings')
return
}
await (send ?? createSendMail(cfg, console.log))(fallbackEmail(to, limit))
await (send ?? createSendMail(cfg, console.log))(fallbackEmail(to, limit, kind))
}

function endEpisode(): void {
Expand All @@ -82,11 +112,13 @@ function endEpisode(): void {
console.log('claude CLI is answering again — back on the subscription')
}

export function fallbackEmail(to: string, limit: string): MailMessage {
const text = `Lore has used its Claude subscription limit and is switching to the backup Claude API key.\n\nClaude Code said: ${limit}\n\nFolds keep running on the API key, billed per token, until the subscription answers again; lore switches back on its own.\n`
export function fallbackEmail(to: string, limit: string, kind: FallbackKind = 'limit'): MailMessage {
const text = kind === 'auth'
? `Lore's Claude Code login on the host stopped working, so it is switching to the backup Claude API key.\n\nClaude Code said: ${limit}\n\nFolds keep running on the API key, billed per token, until the login is restored. Unlike a usage limit, this does not fix itself. To restore it: run \`claude setup-token\` (on any machine signed in to the Claude subscription), save the token in 1Password, and install it as CLAUDE_CODE_OAUTH_TOKEN in /etc/lore/env on the host. Lore switches back on the next run after that.\n`
: `Lore has used its Claude subscription limit and is switching to the backup Claude API key.\n\nClaude Code said: ${limit}\n\nFolds keep running on the API key, billed per token, until the subscription answers again; lore switches back on its own.\n`
return {
to,
subject: 'Lore hit its Claude limit and switched to the API key',
subject: kind === 'auth' ? 'Lore lost its Claude login and switched to the API key' : 'Lore hit its Claude limit and switched to the API key',
text,
html: `<div style="font:16px/1.5 system-ui,sans-serif;color:#1f1d1a;max-width:520px">${text.split('\n\n').map(p => `<p>${esc(p)}</p>`).join('')}</div>`,
}
Expand Down
47 changes: 42 additions & 5 deletions test/llm-fallback.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,16 @@ import { existsSync, mkdtempSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { beforeEach, test } from 'node:test'
import { fallbackApiKey, notifyFallback, resetFallback, usageLimitReason, withCliFallback } from '../src/llm-fallback.js'
import { authFailureReason, cliFailureReason, fallbackApiKey, notifyFallback, resetFallback, usageLimitReason, withCliFallback } from '../src/llm-fallback.js'
import type { MailMessage } from '../src/board/email.js'

process.env.LORE_HOME = mkdtempSync(join(tmpdir(), 'lore-fallback-home-'))
const marker = () => join(process.env.LORE_HOME!, 'llm-fallback.json')

/** What execFileSync throws when `claude -p` exits non-zero with its JSON envelope on stdout. */
const cliFailure = (envelope: Record<string, unknown>) => Object.assign(new Error('Command failed: claude -p --output-format json --model sonnet'), { stdout: Buffer.from(JSON.stringify(envelope)) })
/** What the host's CLI said on 2026-11-12 when its OAuth session lapsed. */
const expired = () => cliFailure({ is_error: true, result: 'Failed to authenticate: OAuth session expired and could not be refreshed', terminal_reason: 'api_error' })
const weekly = () => cliFailure({ is_error: true, result: 'You\'ve hit your weekly limit · resets 11am (UTC)', api_error_status: 429 })

beforeEach(() => {
Expand All @@ -28,6 +30,26 @@ test('fallback: recognises subscription limits from the CLI envelope or a wrappe
assert.equal(usageLimitReason(new Error('extract: output truncated — lower BATCH_CHARS')), undefined)
})

test('fallback: recognises a lost CLI login, kept apart from limits', () => {
assert.equal(authFailureReason(expired()), 'Failed to authenticate: OAuth session expired and could not be refreshed')
assert.equal(authFailureReason(cliFailure({ is_error: true, result: 'Invalid API key · Please run /login' })), 'Invalid API key · Please run /login')
assert.equal(authFailureReason(cliFailure({ is_error: true, api_error_status: 401 })), 'authentication failed (HTTP 401)')
assert.equal(authFailureReason(new Error('extract: claude cli error: OAuth token has expired')), 'OAuth token has expired')
assert.equal(authFailureReason(weekly()), undefined)
assert.equal(authFailureReason(new Error('extract: output truncated — lower BATCH_CHARS')), undefined)
assert.deepEqual(cliFailureReason(weekly()), { kind: 'limit', reason: 'You\'ve hit your weekly limit · resets 11am (UTC)' })
assert.deepEqual(cliFailureReason(expired()), { kind: 'auth', reason: 'Failed to authenticate: OAuth session expired and could not be refreshed' })
assert.equal(cliFailureReason(cliFailure({ is_error: true, result: 'Overloaded' })), undefined)
})

test('fallback: a lost login switches to the API key and says it is an auth problem', async () => {
process.env.LORE_FALLBACK_ANTHROPIC_API_KEY = 'sk-ant-test'
const notices: [string, string][] = []
assert.equal(await withCliFallback(() => { throw expired() }, async () => 'api', async (r, k) => { notices.push([r, k]) }), 'api')
assert.deepEqual(notices, [['Failed to authenticate: OAuth session expired and could not be refreshed', 'auth']])
assert.equal(fallbackApiKey(), 'sk-ant-test')
})

test('fallback: without a fallback key a limit fails as before', async () => {
await assert.rejects(withCliFallback(() => { throw weekly() }, async () => 'api', async () => {}), /Command failed/)
assert.equal(fallbackApiKey(), undefined)
Expand All @@ -51,16 +73,17 @@ test('fallback: a limit switches the process to the API key once — concurrent

test('fallback: other CLI failures are not a switch', async () => {
process.env.LORE_FALLBACK_ANTHROPIC_API_KEY = 'sk-ant-test'
await assert.rejects(withCliFallback(() => { throw cliFailure({ is_error: true, result: 'Invalid API key' }) }, async () => 'api', async () => {}), /Command failed/)
await assert.rejects(withCliFallback(() => { throw cliFailure({ is_error: true, result: 'Overloaded' }) }, async () => 'api', async () => {}), /Command failed/)
await assert.rejects(withCliFallback(() => { throw new Error('extract: output truncated — lower BATCH_CHARS') }, async () => 'api', async () => {}), /truncated/)
assert.equal(fallbackApiKey(), undefined)
})

test('fallback: one email per episode; a CLI success ends the episode so the next limit emails again', async () => {
process.env.LORE_LLM_FALLBACK_NOTIFY = 'ops@example.com'
const sent: MailMessage[] = []
const send = async (msg: MailMessage) => { sent.push(msg) }
await notifyFallback('You\'ve hit your weekly limit', send)
await notifyFallback('You\'ve hit your weekly limit', send)
await notifyFallback('You\'ve hit your weekly limit', 'limit', send)
await notifyFallback('You\'ve hit your weekly limit', 'limit', send)
assert.equal(sent.length, 1)
assert.equal(sent[0].to, 'ops@example.com')
assert.match(sent[0].subject, /switched to the API key/)
Expand All @@ -69,7 +92,21 @@ test('fallback: one email per episode; a CLI success ends the episode so the nex
assert.ok(existsSync(marker()))
assert.equal(await withCliFallback(() => 'cli', async () => 'api'), 'cli')
assert.ok(!existsSync(marker()), 'the subscription answering again ends the episode')
await notifyFallback('You\'ve hit your weekly limit', send)
await notifyFallback('You\'ve hit your weekly limit', 'limit', send)
assert.equal(sent.length, 2)
delete process.env.LORE_LLM_FALLBACK_NOTIFY
})

test('fallback: a lost login emails how to restore it, never the key', async () => {
process.env.LORE_LLM_FALLBACK_NOTIFY = 'ops@example.com'
assert.equal(await withCliFallback(() => 'cli', async () => 'api'), 'cli') // clear any episode
const sent: MailMessage[] = []
await notifyFallback('Failed to authenticate: OAuth session expired and could not be refreshed', 'auth', async (msg) => { sent.push(msg) })
assert.equal(sent.length, 1)
assert.match(sent[0].subject, /lost its Claude login/)
assert.match(sent[0].text, /does not fix itself/)
assert.match(sent[0].text, /claude setup-token/)
assert.match(sent[0].text, /CLAUDE_CODE_OAUTH_TOKEN/)
assert.doesNotMatch(sent[0].text, /sk-ant/)
delete process.env.LORE_LLM_FALLBACK_NOTIFY
})
Loading