From 6991285ae5da1ac37727574cc98455f3c07c794e Mon Sep 17 00:00:00 2001 From: ahokik Date: Tue, 20 Oct 2026 20:08:08 +0100 Subject: [PATCH 01/15] Free plan in models, agents create and chat: plan marks, the free model first, refusals with their ways forward, session notices (D3.16) - types: PickModel.plan (free, within_ceiling, pro_and_max) and the wallet's new fields (granted and paid credit, free_model, network, credit_request, included_hours_withheld). - orca models: a plan column ("free model", "Pro and Max") where the server marks a model; plain rows gain the mark as a fourth column. - agents create with no model: on Free the picker lists the free model the server marks first and preselects it; picker rows carry the mark. - Refusals (model_not_in_plan, free_plan, free_model_daily, free_model_capacity, included_hours, free_model_unavailable): the server's message as it is, then the dashboard's ways forward as words with the command for each, exit 1 (a 403 there is the plan's answer, not the key's role). Where the free model is one, the chat switch in a terminal lists it first; included_hours offers no switch of model. - chat: orca.compute.warning, orca.free_model.turn_limit, orca.turn.time_limit and orca.network.off print on stderr (network as "network off. "), in the REPL transcript, and pass through --json as raw events. Co-Authored-By: Claude Opus 5.5 --- src/commands/agents.tsx | 11 ++- src/commands/chat.tsx | 44 +++++++--- src/commands/models.tsx | 9 ++- src/lib/api.ts | 9 +++ src/lib/models.ts | 47 ++++++++--- src/lib/plan.ts | 55 +++++++++++++ src/lib/sessions.ts | 27 ++++++- src/lib/types.ts | 42 ++++++++++ src/ui/Chat.tsx | 17 +++- src/ui/SwitchPrompt.tsx | 14 +++- test/api.test.ts | 33 ++++++++ test/commands/agents.test.ts | 63 ++++++++++++++- test/commands/chat.test.ts | 150 ++++++++++++++++++++++++++++++++++- test/commands/models.test.ts | 44 +++++++++- test/lib/models.test.ts | 79 +++++++++++++++++- test/lib/plan.test.ts | 51 ++++++++++++ test/lib/sessions.test.ts | 26 +++++- test/ui/Chat.test.tsx | 106 +++++++++++++++++++++++++ 18 files changed, 781 insertions(+), 46 deletions(-) create mode 100644 src/lib/plan.ts create mode 100644 test/lib/plan.test.ts diff --git a/src/commands/agents.tsx b/src/commands/agents.tsx index 70271a8..03f1837 100644 --- a/src/commands/agents.tsx +++ b/src/commands/agents.tsx @@ -5,7 +5,7 @@ import { toPage } from '../lib/api.js' import { findAgent, hasModel, loadAgentFile, missingModel, resolveAgentId } from '../lib/agents.js' import { CliError, ExitCode } from '../lib/errors.js' import { formatTime } from '../lib/format.js' -import { pickerItems } from '../lib/models.js' +import { freeFirst, freeModels, pickerItems } from '../lib/models.js' import { interactive, outputMode, printJson, printPlainRows, renderStatic } from '../lib/output.js' import { accentVerb, hintText } from '../ui/theme.js' import { confirm } from './prompts.js' @@ -55,17 +55,20 @@ async function resolveAgent(ref: string | undefined, verb: string, api: ApiConte // pickModel opens the model picker over every model the organization can // pick, by who pays (orca-design model-billing D3.13): Orca credit with -// OpenRouter's prices and fee, then each provider with a saved key. +// OpenRouter's prices and fee, then each provider with a saved key. On Free +// the free model the server marks comes first and is preselected +// (free-plan D3.16, F16). async function pickModel(api: ApiContext): Promise { const list = await withApi(api, (c) => c.models()) - const items = pickerItems(list) + const free = freeModels(list) + const items = freeFirst(pickerItems(list), free) if (items.length === 0) { throw new CliError('no models to pick from: the model lists could not be read', ExitCode.Failure, [ 'Name the model in the file instead, such as model: orca/openrouter/openai/gpt-5.6-luna', ]) } const { pickItem } = await import('../ui/AgentPicker.js') - return pickItem('Select a model (type to filter)', items) + return pickItem('Select a model (type to filter)', items, free[0]) } async function renderAgentDetail(a: Agent): Promise { diff --git a/src/commands/chat.tsx b/src/commands/chat.tsx index 64dfd71..83c94b2 100644 --- a/src/commands/chat.tsx +++ b/src/commands/chat.tsx @@ -5,8 +5,9 @@ import type { AgentSessionEvent } from 'openai/resources/beta/agents/agents' import { resolveAgentId } from '../lib/agents.js' import { mapApiError, toPage } from '../lib/api.js' -import { creditOut, otherSide, pickerItems, preselect, refusedAtAdmission } from '../lib/models.js' +import { creditOut, freeModels, offersFreeModel, otherSide, pickerItems, preselect, refusedAtAdmission } from '../lib/models.js' import { CliError, ExitCode } from '../lib/errors.js' +import { planWords } from '../lib/plan.js' import { stripControlSequences } from '../lib/markdown.js' import { interactive } from '../lib/output.js' import { readStdin } from '../lib/stdin.js' @@ -78,18 +79,24 @@ function noteStaged(files: readonly StagedFile[]): void { const CONTINUE_MESSAGE = 'Continue' // switcher loads the other side of who pays for a session and switches it. -// The REPL and the single-shot prompt share it. -function switcher(api: ApiContext): Switcher { +// The REPL and the single-shot prompt share it. With freeModel (a Free plan +// refusal that offers it, free-plan D3.16 F16), the free model the server +// marks comes first and is preselected. Exported for tests. +export function switcher(api: ApiContext): Switcher { return { - load: async (sessionId) => + load: async (sessionId, freeModel = false) => withApi(api, async (c) => { const current = await c.sessionModel(sessionId) const list = await c.models() const side = otherSide(list, current.payer) + const free = freeModel ? freeModels(list) : [] + const freeItems = pickerItems(list, (group) => group.payer === 'orca_credit').filter((item) => free.includes(item.value)) + const sideItems = pickerItems(list, (group) => side.includes(group)).filter((item) => !free.includes(item.value)) return { - items: pickerItems(list, (group) => side.includes(group)), - initial: preselect(side, current.model), + items: [...freeItems, ...sideItems], + initial: free[0] ?? preselect(side, current.model), provider: current.model.split('/')[0] ?? null, + ...(free.length ? { freeModel: true } : {}), } }), apply: async (sessionId, model) => { @@ -101,15 +108,17 @@ function switcher(api: ApiContext): Switcher { // offerSwitch says which credit ran out and asks, in one prompt, whether to // top up or switch this session, with the design's warning; on switch, the // model is picked from the other side (preselected only for the same -// OpenRouter model) and posted. True means the next turn can go on. +// OpenRouter model, or the free model when the refusal offers it) and +// posted. True means the next turn can go on. async function offerSwitch( api: ApiContext, sessionId: string, out: 'orca_credit' | 'provider_quota', reason: string, + freeModel = false, ): Promise { const sessions = switcher(api) - const offer = await sessions.load(sessionId) + const offer = await sessions.load(sessionId, freeModel) process.stderr.write(`${stripControlSequences(reason)}\n`) const { render } = await import('ink') const { SwitchPrompt } = await import('../ui/SwitchPrompt.js') @@ -165,10 +174,11 @@ async function runSingleShot( // anything else is rethrown as it came. const switchedAfterRefusal = async (err: unknown): Promise => { const code = err instanceof APIError ? (err.code ?? undefined) : undefined - if (refusedAtAdmission(code) && !json && interactive()) { + const param = err instanceof APIError ? (err.param ?? undefined) : undefined + if (refusedAtAdmission(code) && creditOut(code, param) && !json && interactive()) { nameSession() const reason = err instanceof Error ? err.message : String(err) - if (await offerSwitch(api, sessionId, 'orca_credit', reason)) return null + if (await offerSwitch(api, sessionId, 'orca_credit', reason, offersFreeModel(code, param))) return null } throw err } @@ -184,6 +194,10 @@ async function runSingleShot( // even to a pipe (downstream terminals re-render them). process.stdout.write(stripControlSequences(event.text)) wroteText = true + } else if (event.type === 'notice') { + // The server's notice (free-plan D3.16), on stderr so stdout + // stays the reply; noticeText already made it one clean line. + process.stderr.write(`${hintText(event.text)}\n`) } else { noteTool(event) } @@ -213,7 +227,9 @@ async function runSingleShot( await runSingleShot(api, undefined, CONTINUE_MESSAGE, { ...opts, session: sessionId }, json) return } - throw new CliError(result.message || result.errorCode || 'the turn failed', ExitCode.Failure) + // A Free plan stop (free-plan D3.16) adds its ways forward as words. + const ways = planWords(result.errorCode, result.errorParam) + throw new CliError(result.message || result.errorCode || 'the turn failed', ExitCode.Failure, ways.length ? ways : undefined) } if (result.terminated === 'dropped') { throw new CliError('the event stream closed before the turn ended', ExitCode.Failure, [ @@ -250,9 +266,11 @@ async function runRepl( return { ...result, sessionId: id } } catch (err) { const mapped = mapApiError(err, { contextName: api.resolved.name, apiUrl: api.client.apiUrl }) - // The code stays, so a refusal for Orca credit offers the switch. + // The code and param stay, so a refusal for Orca credit offers the + // switch and a Free plan refusal its ways forward. const errorCode = err instanceof APIError ? (err.code ?? undefined) : undefined - return { terminated: 'error' as const, message: mapped.message, errorCode, sessionId: id } + const errorParam = err instanceof APIError ? (err.param ?? undefined) : undefined + return { terminated: 'error' as const, message: mapped.message, errorCode, errorParam, sessionId: id } } } diff --git a/src/commands/models.tsx b/src/commands/models.tsx index e910149..a324868 100644 --- a/src/commands/models.tsx +++ b/src/commands/models.tsx @@ -2,6 +2,7 @@ import type { Command } from 'commander' import { groupHeading, payerWord, priceLine, withPayer } from '../lib/models.js' import { outputMode, printJson, printPlainRows, renderStatic } from '../lib/output.js' +import { planColumn, planWord } from '../lib/plan.js' import type { PickModel } from '../lib/types.js' import { hintText } from '../ui/theme.js' import { apiContext, globalFlags, withApi } from './shared.js' @@ -13,7 +14,8 @@ const MODEL_COLUMN = 80 // `orca models` lists every model a member can pick, grouped by who pays, // from GET /api/models: the picker's list, outside a terminal too // (orca-design publish-cli, D5.7, amended 2026-10-12). Every name and price -// is the server's. +// is the server's, and so is each Orca credit model's plan mark (free-plan +// D3.16, F16): "free model", or "Pro and Max" for one Free cannot run. export function registerModels(program: Command): void { program .command('models') @@ -33,7 +35,9 @@ export function registerModels(program: Command): void { } if (mode === 'plain') { printPlainRows( - list.groups.flatMap((group) => group.models.map((m) => [m.id, payerWord(group), priceLine(m) ?? '-'])), + list.groups.flatMap((group) => + group.models.map((m) => [m.id, payerWord(group), priceLine(m) ?? '-', planWord(m.plan) ?? '-']), + ), ) return } @@ -59,6 +63,7 @@ export function registerModels(program: Command): void { ...(group.payer === 'orca_credit' ? [{ header: 'openrouter price', get: (m: PickModel) => priceLine(m) ?? '-', max: MODEL_COLUMN }] : []), + ...planColumn(group.models), ]} rows={group.models} /> diff --git a/src/lib/api.ts b/src/lib/api.ts index 96a7931..8ce7c56 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -15,6 +15,7 @@ import type { Credential } from 'openai/resources/beta/agents/vaults/credentials import { APIConnectionTimeoutError, APIError as OpenAIAPIError, APIConnectionError } from 'openai/error' import { CliError, ExitCode } from './errors.js' +import { planWords } from './plan.js' import type { APIKey, APIKeyIssued, @@ -142,15 +143,23 @@ export function mapApiError(err: unknown, opts: { contextName: string; apiUrl: s let status: number | undefined let reason = '' let param: string | null = null + let code: string | null = null if (err instanceof ApiError) { status = err.status reason = extractErrorBody(err.body) param = errorParam(err.body) + code = err.code } else if (err instanceof OpenAIAPIError && err.status !== undefined) { status = err.status reason = extractErrorBody({ error: err.error }) param = errorParam({ error: err.error }) + code = errorCode({ error: err.error }) } + // A Free plan refusal (free-plan D3.16) is the server's message as it is, + // then its ways forward, whatever the status: a 403 there is the plan's + // answer, not the key's role. + const ways = planWords(code, param) + if (reason && ways.length) return new CliError(reason, ExitCode.Failure, ways) if (reason && param) reason = `${reason} (${param})` if (status !== undefined) { if (status === 401) { diff --git a/src/lib/models.ts b/src/lib/models.ts index df7951c..6038f91 100644 --- a/src/lib/models.ts +++ b/src/lib/models.ts @@ -6,6 +6,7 @@ import { glyphs } from '../ui/theme.js' import { CliError, ExitCode } from './errors.js' import { tokenPrice, usdMicro } from './money.js' +import { planActions, planWord } from './plan.js' import type { ModelGroup, ModelGroups, Payer, PickModel } from './types.js' const ORCA_PREFIX = 'orca/openrouter/' @@ -71,13 +72,15 @@ export function withPayer(list: ModelGroups, payer?: string): ModelGroups { return { ...list, groups } } -// ModelRow is one model as a flat row: its name, who pays in one word, and -// OpenRouter's price where the server gives one. +// ModelRow is one model as a flat row: its name, who pays in one word, +// OpenRouter's price where the server gives one, and what the plan allows +// of an Orca credit model (free-plan D3.16). export type ModelRow = { id: string payer: string input_micro_usd_per_million?: number | null output_micro_usd_per_million?: number | null + plan?: PickModel['plan'] } // modelRows flattens the groups into rows, in the server's order, keeping @@ -92,6 +95,7 @@ export function modelRows(list: ModelGroups, query?: string): ModelRow[] { payer: payerWord(group), ...(m.input_micro_usd_per_million !== undefined ? { input_micro_usd_per_million: m.input_micro_usd_per_million } : {}), ...(m.output_micro_usd_per_million !== undefined ? { output_micro_usd_per_million: m.output_micro_usd_per_million } : {}), + ...(m.plan !== undefined ? { plan: m.plan } : {}), })), ) } @@ -99,18 +103,33 @@ export function modelRows(list: ModelGroups, query?: string): ModelRow[] { export type ModelItem = { label: string; value: string; detail: string } // pickerItems lists the groups' models for the terminal picker, in the -// server's order. The group (who pays) and the price go in each row's -// detail, since the picker has no headings. +// server's order. The group (who pays), the price and the plan's mark go in +// each row's detail, since the picker has no headings. export function pickerItems(list: ModelGroups, include: (group: ModelGroup) => boolean = () => true): ModelItem[] { return list.groups.filter(include).flatMap((group) => { const heading = groupHeading(group, list.openrouter_fee_bps) return group.models.map((model) => { - const price = priceLine(model) - return { label: model.id, value: model.id, detail: price ? `${heading} ${glyphs.separator} ${price}` : heading } + const detail = [heading, priceLine(model), planWord(model.plan)].filter(Boolean).join(` ${glyphs.separator} `) + return { label: model.id, value: model.id, detail } }) }) } +// freeModels is the Orca credit models the server marks as the free model, +// which it does only on Free (free-plan D3.16, F16): the list itself is the +// server's, from its plan facts, never typed here. +export function freeModels(list: ModelGroups): string[] { + return list.groups + .filter((group) => group.payer === 'orca_credit') + .flatMap((group) => group.models.filter((model) => model.plan === 'free').map((model) => model.id)) +} + +// freeFirst puts the free models' rows first, in the server's order +// otherwise, so a picker on Free offers the free model first. +export function freeFirst(items: readonly ModelItem[], free: readonly string[]): ModelItem[] { + return [...items.filter((item) => free.includes(item.value)), ...items.filter((item) => !free.includes(item.value))] +} + // otherSide is the groups a switch from `payer` can pick from. export function otherSide(list: ModelGroups, payer: Payer | null): ModelGroup[] { return list.groups.filter((group) => group.payer !== payer) @@ -126,9 +145,12 @@ export function preselect(groups: readonly ModelGroup[], model: string): string // creditOut names the credit that ran out, from the server's code and // param, never its message: a turn it ended (`usage_limit_exceeded` with // `orca_credit` or `provider_quota`), or a message it refused at admission -// for Orca credit (`insufficient_quota`). +// for Orca credit (`insufficient_quota`, or on Free `model_not_in_plan`). +// Free's included hour used up (`included_hours`) is machine time, which no +// switch of model pays for. export function creditOut(code: string | undefined, param: string | undefined): 'orca_credit' | 'provider_quota' | null { - if (code === 'insufficient_quota') return 'orca_credit' + if (code === 'model_not_in_plan') return 'orca_credit' + if (code === 'insufficient_quota') return param === 'included_hours' ? null : 'orca_credit' if (code !== 'usage_limit_exceeded') return null if (param === 'orca_credit' || param === 'provider_quota') return param return null @@ -137,5 +159,12 @@ export function creditOut(code: string | undefined, param: string | undefined): // refusedAtAdmission is a message the server refused before any turn began: // after a switch it is sent again, where a turn the server ended continues. export function refusedAtAdmission(code: string | undefined): boolean { - return code === 'insufficient_quota' + return code === 'insufficient_quota' || code === 'model_not_in_plan' +} + +// offersFreeModel is a refusal whose ways forward include switching this +// session to the free model (free-plan D3.16, F16): the switch then lists +// the free model first. +export function offersFreeModel(code: string | undefined, param: string | undefined): boolean { + return planActions(code, param).includes('free_model') } diff --git a/src/lib/plan.ts b/src/lib/plan.ts new file mode 100644 index 0000000..4da6c92 --- /dev/null +++ b/src/lib/plan.ts @@ -0,0 +1,55 @@ +// The Free plan's refusals and marks (orca-design free-plan D3.16). The +// server writes every message; the CLI adds only the ways forward the +// dashboard offers as buttons, here as words with the command for each. + +import type { ModelPlan, PickModel } from './types.js' + +// planWord is an Orca credit model's mark, as `orca models` and the pickers +// show it: the free model, a model that needs Pro or Max, or nothing. +export function planWord(plan: ModelPlan | undefined): string | undefined { + if (plan === 'free') return 'free model' + if (plan === 'pro_and_max') return 'Pro and Max' + return undefined +} + +// planColumn is a model table's plan column: present only where the server +// marks a model, so Pro and Max, where every model runs, show none. +export function planColumn(models: readonly PickModel[]): { header: string; get: (m: PickModel) => string }[] { + return models.some((m) => planWord(m.plan)) ? [{ header: 'plan', get: (m) => planWord(m.plan) ?? '' }] : [] +} + +// A way forward from a refusal, as the dashboard names it. +export type PlanAction = 'free_model' | 'provider_key' | 'add_credit' | 'upgrade' + +const ACTION_WORDS: Record = { + free_model: 'Switch this session to the free model (orca chat offers it at a terminal)', + provider_key: 'Add a provider key: in the dashboard, Settings, Providers', + add_credit: 'Add credit: orca billing buy pack: (orca billing wallet lists the packs)', + upgrade: 'Upgrade: orca billing buy pro, or orca billing buy max', +} + +// planActions reads a refusal's ways forward from the server's code and +// param, never its message: at turn admission (`model_not_in_plan`, +// `free_model_unavailable`, `insufficient_quota`) or a turn the server ended +// (`usage_limit_exceeded`). Empty for anything else. +export function planActions(code: string | null | undefined, param: string | null | undefined): PlanAction[] { + if (code === 'model_not_in_plan') return ['upgrade', 'free_model'] + if (code === 'free_model_unavailable') return ['provider_key', 'add_credit'] + if (code !== 'insufficient_quota' && code !== 'usage_limit_exceeded') return [] + switch (param) { + case 'free_plan': + return ['free_model', 'provider_key', 'add_credit', 'upgrade'] + case 'free_model_capacity': + case 'free_model_daily': + return ['provider_key', 'upgrade'] + case 'included_hours': + return ['add_credit'] + default: + return [] + } +} + +// planWords is the ways forward as lines, printed under the server's message. +export function planWords(code: string | null | undefined, param: string | null | undefined): string[] { + return planActions(code, param).map((action) => ACTION_WORDS[action]) +} diff --git a/src/lib/sessions.ts b/src/lib/sessions.ts index c961dc5..084fdd8 100644 --- a/src/lib/sessions.ts +++ b/src/lib/sessions.ts @@ -42,10 +42,12 @@ export type ChatToolStatus = 'running' | 'ok' | 'error' | 'stopped' // A tool event carries a web search's query and, when it failed, the // server's reason (model-billing, Web search, The item), both one line of -// remote text with control bytes stripped. Other tools carry neither. +// remote text with control bytes stripped. Other tools carry neither. A +// notice is one of the server's session notices, as the line to show. export type ChatEvent = | { type: 'delta'; text: string } | { type: 'tool'; id: string; name?: string; status: ChatToolStatus; query?: string; reason?: string } + | { type: 'notice'; text: string } // How a turn ended: // done - the turn completed (message is the reply text) @@ -58,7 +60,8 @@ export type ChatTurnResult = { message: string errorCode?: string // The error's param: with usage_limit_exceeded, `orca_credit` or - // `provider_quota` says whose credit ran out. + // `provider_quota` says whose credit ran out, and Free's stops name + // theirs (`included_hours`, `free_model_capacity`, free-plan D3.16). errorParam?: string } @@ -98,6 +101,20 @@ function oneLine(text: string, max: number): string { return line.length > max ? `${line.slice(0, max - 3).trimEnd()}...` : line } +// The server's session notices (orca-design free-plan D3.16), each +// {type, message, at}: machine time nearly used, a turn ended at the free +// model's calls or at Free's 30 minutes, a sandbox started without network. +// None ends the turn. +const NOTICES = new Set(['orca.compute.warning', 'orca.free_model.turn_limit', 'orca.turn.time_limit', 'orca.network.off']) + +// noticeText is the line a notice shows: its message as one line, the +// network's after `network off.` as every surface says it. +export function noticeText(event: { type: string; message?: unknown }): string | null { + if (!NOTICES.has(event.type) || typeof event.message !== 'string' || !event.message.trim()) return null + const message = oneLine(event.message, 500) + return event.type === 'orca.network.off' ? `network off. ${message}` : message +} + // webSearchQuery is what a web search searched for. The server sets the // item's action from the start, so an in-progress or failed search has its // query too; an older server sends action null, and then there is none. @@ -176,6 +193,12 @@ export async function streamTurn( try { for await (const event of stream) { opts.onRaw?.(event) + // The SDK's union does not list Orca's notices; they arrive as sent. + const notice = noticeText(event as { type: string; message?: unknown }) + if (notice !== null) { + opts.onEvent?.({ type: 'notice', text: notice }) + continue + } switch (event.type) { case 'agent.session.turn.created': if (followed === null && event.turn.subagent_id === null) followed = event.turn_id diff --git a/src/lib/types.ts b/src/lib/types.ts index 1999cf6..5cf6ae0 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -151,21 +151,63 @@ export type Wallet = { // OpenRouter's credit fee on tokens and searches on Orca credit, in basis // points. The CLI shows it and does no arithmetic with it. openrouter_fee_bps: number + // The Free plan (orca-design free-plan D3.16). Each is absent from a server + // older than it. + // Granted credit left now, and the rest of the balance, which never + // expires: granted credit is spent first. + granted_credit_micro_usd?: number + paid_credit_micro_usd?: number + // Live grants with something left, soonest expiry first. + granted_credit?: GrantedCredit[] + // Granted credit that expired unspent. + expired_micro_usd?: number + // The organization's free-model calls today; null on Pro and Max. + free_model?: WalletFreeModel | null + // The email domain's age withheld the included hours and the free model. + included_hours_withheld?: boolean + // Free sandboxes have no network until the organization has credit; the + // message is the server's, said the same way everywhere. + network?: { off: boolean; message?: string } + // On Free, where to ask for credit, in the server's words. + credit_request?: { message: string; url: string } | null } +// One grant with credit left: an operator grant (`grant`, with its reason +// code) or honoured signup credit (`signup`). expires_at is the first moment +// it no longer counts, 00:00 UTC the day after its last day. +export type GrantedCredit = { + kind: 'grant' | 'signup' + grant_reason: string | null + granted_micro_usd: number + left_micro_usd: number + granted_at: number + expires_at: number +} + +// The free model's calls today against the organization's share a day; +// available is false when it cannot run now. +export type WalletFreeModel = { calls_today: number; calls_per_day: number; available: boolean } + // -- Models ------------------------------------------------------------------- // Who pays for a model's calls (orca-design model-billing D3.13). export type Payer = 'orca_credit' | 'own_key' +// What the organization's plan allows of an Orca credit model (orca-design +// free-plan D3.16, F16): `free` is the free model (on Free only), +// `within_ceiling` runs on credit, `pro_and_max` needs Pro or Max. +export type ModelPlan = 'free' | 'within_ceiling' | 'pro_and_max' + // One model a member can pick. Prices are OpenRouter's, Orca credit only, in // micro-USD per million tokens; null where OpenRouter has no fixed price. +// plan is on Orca credit models only, absent from an older server. export type PickModel = { id: string name?: string context_length?: number input_micro_usd_per_million?: number | null output_micro_usd_per_million?: number | null + plan?: ModelPlan } export type ModelGroup = { diff --git a/src/ui/Chat.tsx b/src/ui/Chat.tsx index f78be0b..96f9e78 100644 --- a/src/ui/Chat.tsx +++ b/src/ui/Chat.tsx @@ -4,7 +4,8 @@ import { useEffect, useRef, useState } from 'react' import type { ChatEvent, ChatToolStatus, ChatTurnResult } from '../lib/sessions.js' import { renderMarkdown, stripControlSequences } from '../lib/markdown.js' -import { creditOut, refusedAtAdmission } from '../lib/models.js' +import { creditOut, offersFreeModel, refusedAtAdmission } from '../lib/models.js' +import { planWords } from '../lib/plan.js' import { SwitchPrompt, type SwitchChoice, type SwitchOffer } from './SwitchPrompt.js' import { colorEnabled, glyphs, theme } from './theme.js' @@ -21,9 +22,10 @@ export type SendTurn = ( // Switcher is the switch of who pays for the session (orca-design // model-billing D3.13), injected like send: `load` reads the other side's -// models (with the one to preselect, if any), `apply` posts the choice. +// models (with the one to preselect, if any), and with freeModel the free +// model first (free-plan D3.16); `apply` posts the choice. export type Switcher = { - load: (sessionId: string) => Promise + load: (sessionId: string, freeModel?: boolean) => Promise apply: (sessionId: string, model: string) => Promise } @@ -288,6 +290,10 @@ export function Chat({ agentLabel, initialSessionId, send, switcher, onExit }: C // (not the delta) also catches sequences split across deltas. accum += event.text setLiveText(stripControlSequences(accum)) + } else if (event.type === 'notice') { + // The server's notice (free-plan D3.16) goes in the transcript + // as it arrives; the turn goes on. + pushItem({ kind: 'note', text: event.text }) } else if (event.type === 'tool') { const previous = tools.get(event.id) tools.set(event.id, { @@ -336,6 +342,9 @@ export function Chat({ agentLabel, initialSessionId, send, switcher, onExit }: C } else { // terminated === 'error' pushItem({ kind: 'error', message: result.message || result.errorCode || 'upstream error' }) + // A Free plan refusal or stop: its ways forward, as words. + const ways = planWords(result.errorCode, result.errorParam) + if (ways.length) pushItem({ kind: 'note', text: ways.join('\n') }) // A credit ran out: ask whether to top up or switch who pays. Nothing // switches on its own. const out = creditOut(result.errorCode, result.errorParam) @@ -343,7 +352,7 @@ export function Chat({ agentLabel, initialSessionId, send, switcher, onExit }: C const sessionId = sessionRef.current if (out && switcher && sessionId) { switcher - .load(sessionId) + .load(sessionId, offersFreeModel(result.errorCode, result.errorParam)) .then((offer) => setPause({ out, offer, resend })) .catch((err: unknown) => pushItem({ kind: 'error', message: err instanceof Error ? err.message : String(err) })) } diff --git a/src/ui/SwitchPrompt.tsx b/src/ui/SwitchPrompt.tsx index b34067f..c2a27b6 100644 --- a/src/ui/SwitchPrompt.tsx +++ b/src/ui/SwitchPrompt.tsx @@ -7,8 +7,9 @@ import { theme } from './theme.js' // What the other side of who pays offers a session: its models, the one to // preselect (the same OpenRouter model, if listed), and the provider whose -// account ran out, for the wording. -export type SwitchOffer = { items: PickerItem[]; initial?: string; provider: string | null } +// account ran out, for the wording. freeModel is set when the free model +// leads the list (free-plan D3.16). +export type SwitchOffer = { items: PickerItem[]; initial?: string; provider: string | null; freeModel?: boolean } // How the prompt ended: a model to switch to, a top-up instead, or no model // on the other side to switch to. @@ -20,6 +21,13 @@ type SwitchPromptProps = { onDone: (choice: SwitchChoice) => void } +// switchLabel names what the switch offers: the free model first when it +// leads the list, else the other side of who pays. +function switchLabel(out: SwitchPromptProps['out'], offer: SwitchOffer): string { + if (out !== 'orca_credit') return 'Switch this session to Orca credit' + return offer.freeModel ? 'Switch this session to the free model or your own key' : 'Switch this session to your own key' +} + // The switch of who pays after a credit ran out (orca-design model-billing // D3.13): the design's warning, then "top up, or switch this session?", then // the other side's models. One component for both steps, so the REPL and a @@ -47,7 +55,7 @@ export function SwitchPrompt({ out, offer, onDone }: SwitchPromptProps) { Top up, or switch this session? { expect(mapApiError(quota, CTX).message).toBe('429: Your plan runs 1 sessions at once') }) + it('prints a Free plan refusal as the server wrote it, with its ways forward, never as the key\'s role', () => { + // free-plan D3.16: a 403 model_not_in_plan is the plan's answer. + const message = + 'This model needs Pro or Max. On Free, use the free model (cohere/north-mini-code:free), your own key, or a model up to $3/M input and $15/M output on credit you add. Upgrade: https://app.orcapods.ai/settings/plans' + const notInPlan = OpenAIAPIError.generate( + 403, + { error: { message, type: 'invalid_request_error', param: 'agent.model', code: 'model_not_in_plan' } }, + undefined, + new Headers(), + ) + expect(mapApiError(notInPlan, CTX)).toMatchObject({ + exitCode: ExitCode.Failure, + message, + detail: [ + 'Upgrade: orca billing buy pro, or orca billing buy max', + 'Switch this session to the free model (orca chat offers it at a terminal)', + ], + }) + // The same on the /api client, by code and param. + const daily = new ApiError('429', 429, { + error: { message: 'Your organization has used today\'s 100 free-model calls.', param: 'free_model_daily', code: 'insufficient_quota' }, + }) + expect(mapApiError(daily, CTX)).toMatchObject({ + exitCode: ExitCode.Failure, + message: 'Your organization has used today\'s 100 free-model calls.', + detail: ['Add a provider key: in the dashboard, Settings, Providers', 'Upgrade: orca billing buy pro, or orca billing buy max'], + }) + // A 503 for the free model withdrawn is not a retry-later. + const gone = new ApiError('503', 503, { error: { message: 'Orca\'s free model is not available right now.', code: 'free_model_unavailable' } }) + expect(mapApiError(gone, CTX).message).toBe('Orca\'s free model is not available right now.') + expect(mapApiError(gone, CTX).detail).toHaveLength(2) + }) + it('maps an unreachable host to a connectivity error', () => { expect(mapApiError(new TypeError('fetch failed'), CTX).message).toContain('cannot reach http://test:8080') expect(mapApiError(new APIConnectionError({ message: 'Connection error.' }), CTX).message).toContain('cannot reach') diff --git a/test/commands/agents.test.ts b/test/commands/agents.test.ts index 95447c1..bceb8a1 100644 --- a/test/commands/agents.test.ts +++ b/test/commands/agents.test.ts @@ -2,13 +2,18 @@ import { writeFile } from 'node:fs/promises' import os from 'node:os' import path from 'node:path' -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { registerAgents } from '../../src/commands/agents.js' import { ExitCode } from '../../src/lib/errors.js' import { commandHarness, list } from '../helpers/cli.js' import { jsonResponse, stubFetch } from '../helpers/fetch-mock.js' +// The model picker, so a test can see what it offers and answer for the +// person at the terminal. +const pickItem = vi.hoisted(() => vi.fn()) +vi.mock('../../src/ui/AgentPicker.js', () => ({ pickItem, pickOne: vi.fn() })) + const ID = 'agent_' + '1'.repeat(32) const OTHER = 'agent_' + '2'.repeat(32) @@ -146,6 +151,62 @@ describe('agents create and update', () => { }) }) +describe('agents create with no model, at a terminal', () => { + const FREE = 'orca/openrouter/cohere/north-mini-code:free' + const LUNA = 'orca/openrouter/openai/gpt-5.6-luna' + const models = (free: boolean) => ({ + object: 'list', + openrouter_fee_bps: 550, + groups: [ + { + payer: 'orca_credit', + provider: 'openrouter', + label: 'Orca credit', + available: true, + models: [ + { id: LUNA, input_micro_usd_per_million: 400_000, output_micro_usd_per_million: 1_800_000, plan: 'within_ceiling' }, + ...(free ? [{ id: FREE, input_micro_usd_per_million: 0, output_micro_usd_per_million: 0, plan: 'free' }] : []), + ], + }, + { payer: 'own_key', provider: 'anthropic', label: 'Anthropic', available: true, models: [{ id: 'anthropic/claude-sonnet-4-5' }] }, + ], + }) + + async function asTerminal(fn: () => Promise): Promise { + const [stdin, stdoutTty] = [process.stdin.isTTY, process.stdout.isTTY] + process.stdin.isTTY = true + process.stdout.isTTY = true + try { + await fn() + } finally { + process.stdin.isTTY = stdin + process.stdout.isTTY = stdoutTty + } + } + + it('offers the free model first, preselected, on Free (free-plan D3.16)', async () => { + const file = await agentFile('name: support\n') + pickItem.mockResolvedValueOnce(FREE) + const calls = stubFetch({ 'GET /api/models': jsonResponse(models(true)), 'POST /v1/agents': jsonResponse(agent(ID, 'support')) }) + await asTerminal(() => run(['agents', 'create', '-f', file])) + const [, items, initial] = pickItem.mock.calls.at(-1) as [string, { value: string; detail: string }[], string | undefined] + expect(items.map((item) => item.value)).toEqual([FREE, LUNA, 'anthropic/claude-sonnet-4-5']) + expect(items[0].detail).toMatch(/free model$/) + expect(initial).toBe(FREE) + expect(JSON.parse(calls.find((c) => c.method === 'POST')?.body ?? '{}')).toEqual({ name: 'support', model: FREE }) + }) + + it('keeps the server\'s order and preselects nothing on Pro and Max', async () => { + const file = await agentFile('name: support\n') + pickItem.mockResolvedValueOnce(LUNA) + stubFetch({ 'GET /api/models': jsonResponse(models(false)), 'POST /v1/agents': jsonResponse(agent(ID, 'support')) }) + await asTerminal(() => run(['agents', 'create', '-f', file])) + const [, items, initial] = pickItem.mock.calls.at(-1) as [string, { value: string }[], string | undefined] + expect(items.map((item) => item.value)).toEqual([LUNA, 'anthropic/claude-sonnet-4-5']) + expect(initial).toBeUndefined() + }) +}) + describe('agents delete', () => { it('refuses without --yes when not interactive', async () => { stubFetch({ [`GET /v1/agents/${ID}`]: jsonResponse(agent(ID, 'support')) }) diff --git a/test/commands/chat.test.ts b/test/commands/chat.test.ts index 6fe30dc..08d2795 100644 --- a/test/commands/chat.test.ts +++ b/test/commands/chat.test.ts @@ -5,9 +5,10 @@ import { Readable } from 'node:stream' import { describe, expect, it, vi } from 'vitest' -import { registerChat } from '../../src/commands/chat.js' +import { registerChat, switcher } from '../../src/commands/chat.js' +import { ApiClient } from '../../src/lib/api.js' import { ExitCode } from '../../src/lib/errors.js' -import { commandHarness, list } from '../helpers/cli.js' +import { API, commandHarness, KEY, list } from '../helpers/cli.js' import { jsonResponse, stubFetch } from '../helpers/fetch-mock.js' import { AGENT_ID, @@ -17,6 +18,7 @@ import { VAULT_ID, hostedSession, session, + sessionModelRoute, template, templateByName, templateRoute, @@ -249,3 +251,147 @@ describe('orca chat --file', () => { expect(calls).toHaveLength(0) }) }) + +// One turn on SESSION_ID with the server's Free plan notices in it +// (free-plan D3.16): they are session events, not the turn's. +function turnWithNotices(): Record[] { + const events = turnEvents() + const notices = [ + { event_id: 'evt_n1', session_id: SESSION_ID, type: 'orca.network.off', message: NETWORK, at: 1_783_245_600 }, + { event_id: 'evt_n2', session_id: SESSION_ID, type: 'orca.compute.warning', message: WARNING, at: 1_783_245_601 }, + { event_id: 'evt_n3', session_id: SESSION_ID, type: 'orca.free_model.turn_limit', message: TURN_LIMIT, at: 1_783_245_602 }, + { event_id: 'evt_n4', session_id: SESSION_ID, type: 'orca.turn.time_limit', message: TIME_LIMIT, at: 1_783_245_603 }, + ] + return [events[0], notices[0], notices[1], ...events.slice(1, -2), notices[2], notices[3], ...events.slice(-2)] +} + +const NETWORK = 'Network is off on Free sandboxes until your organization has credit. Add credit, or write to us on Discord (https://discord.gg/btTYzdzvqq).' +const WARNING = '5 minutes of included machine time left this month. Add credit to keep the sandbox running after that.' +const TURN_LIMIT = "This turn reached the free model's 25 calls. Send a message to continue." +const TIME_LIMIT = "This turn reached Free's 30 minutes. Send a message to continue." + +describe('orca chat on the Free plan (free-plan D3.16)', () => { + it('prints each session notice on stderr, the network line as every surface says it, and keeps stdout the reply', async () => { + stubFetch({ ...agentRoute(), 'POST /v1/agents/sessions': jsonResponse(session()), ...turnRoutes(turnWithNotices()) }) + await run(['chat', AGENT_ID, 'hi']) + expect(stdout()).toBe('Let me look.\n\nHello there\n') + expect(stderr()).toContain(`network off. ${NETWORK}\n`) + expect(stderr()).toContain(`${WARNING}\n`) + expect(stderr()).toContain(`${TURN_LIMIT}\n`) + expect(stderr()).toContain(`${TIME_LIMIT}\n`) + }) + + it('passes the notices through as raw events with --json', async () => { + stubFetch({ ...agentRoute(), 'POST /v1/agents/sessions': jsonResponse(session()), ...turnRoutes(turnWithNotices()) }) + await run(['--json', 'chat', AGENT_ID, 'hi']) + const types = stdout().trim().split('\n').map((l) => (JSON.parse(l) as { type: string }).type) + expect(types).toEqual(expect.arrayContaining(['orca.network.off', 'orca.compute.warning', 'orca.free_model.turn_limit', 'orca.turn.time_limit'])) + expect(stderr()).not.toContain(NETWORK) + }) + + it('prints a model refused on Free as the server wrote it, with the ways forward, exit 1', async () => { + const message = 'This model needs Pro or Max. On Free, use the free model (cohere/north-mini-code:free), your own key, or a model up to $3/M input and $15/M output on credit you add. Upgrade: https://app.orcapods.ai/settings/plans' + stubFetch({ + ...agentRoute(), + 'POST /v1/agents/sessions': jsonResponse(session()), + ...turnRoutes(turnEvents()), + [`POST /v1/agents/sessions/${SESSION_ID}/events`]: jsonResponse( + { error: { message, type: 'invalid_request_error', param: 'agent.model', code: 'model_not_in_plan' } }, + { status: 403 }, + ), + }) + await expect(run(['chat', AGENT_ID, 'hi'])).rejects.toMatchObject({ + exitCode: ExitCode.Failure, + message, + detail: [ + 'Upgrade: orca billing buy pro, or orca billing buy max', + 'Switch this session to the free model (orca chat offers it at a terminal)', + ], + }) + expect(stderr()).toContain(`session ${SESSION_ID}`) + }) + + it('prints a paid model refused at $0 on Free with its four ways forward', async () => { + const message = 'On Free, this agent\'s model runs on credit. Switch this session to the free model (cohere/north-mini-code:free), add your own provider key in Settings, Providers, or add credit or upgrade: https://app.orcapods.ai/wallet' + stubFetch({ + ...agentRoute(), + 'POST /v1/agents/sessions': jsonResponse(session()), + ...turnRoutes(turnEvents()), + [`POST /v1/agents/sessions/${SESSION_ID}/events`]: jsonResponse( + { error: { message, type: 'insufficient_quota', param: 'free_plan', code: 'insufficient_quota' } }, + { status: 429 }, + ), + }) + const err = await run(['chat', AGENT_ID, 'hi']).catch((e: unknown) => e) + expect(err).toMatchObject({ exitCode: ExitCode.Failure, message }) + expect((err as { detail: string[] }).detail).toHaveLength(4) + }) + + it('ends a turn stopped at the included hour with the server\'s message and the way forward', async () => { + const events = turnEvents('failed').map((e) => + e.type === 'agent.session.turn.failed' + ? { + ...e, + turn: { + ...(e.turn as Record), + error: { code: 'usage_limit_exceeded', param: 'included_hours', message: "Free's 1 included hour this month is used up and this organization has no credit. The workspace is saved. Add credit to continue now, or it resumes on 1 November." }, + }, + } + : e, + ) + stubFetch({ ...agentRoute(), 'POST /v1/agents/sessions': jsonResponse(session()), ...turnRoutes(events) }) + await expect(run(['chat', AGENT_ID, 'hi'])).rejects.toMatchObject({ + exitCode: ExitCode.Failure, + message: expect.stringContaining('The workspace is saved.'), + detail: ['Add credit: orca billing buy pack: (orca billing wallet lists the packs)'], + }) + }) + + it('keeps an out-of-credit turn as it was, with no Free plan words', async () => { + stubFetch({ ...agentRoute(), 'POST /v1/agents/sessions': jsonResponse(session()), ...turnRoutes(turnEvents('failed')) }) + const err = await run(['chat', AGENT_ID, 'hi']).catch((e: unknown) => e) + expect(err).toMatchObject({ message: 'Out of credit' }) + expect((err as { detail?: string[] }).detail).toBeUndefined() + }) +}) + +describe('the switch on Free', () => { + const FREE = 'orca/openrouter/cohere/north-mini-code:free' + const models = { + object: 'list', + openrouter_fee_bps: 550, + groups: [ + { + payer: 'orca_credit', + provider: 'openrouter', + label: 'Orca credit', + available: true, + models: [ + { id: 'orca/openrouter/anthropic/claude-fable-5', input_micro_usd_per_million: 10_000_000, output_micro_usd_per_million: 50_000_000, plan: 'pro_and_max' }, + { id: FREE, input_micro_usd_per_million: 0, output_micro_usd_per_million: 0, plan: 'free' }, + ], + }, + { payer: 'own_key', provider: 'anthropic', label: 'Anthropic', available: true, models: [{ id: 'anthropic/claude-sonnet-4-5' }] }, + ], + } + const api = () => ({ + client: new ApiClient({ apiUrl: API, apiKey: KEY, contextName: 'default' }), + resolved: { name: 'default', apiUrl: API, apiKey: KEY, defaulted: new Set(), configPath: '' }, + }) + + it('offers the free model first and preselected when the refusal offers it', async () => { + stubFetch({ ...sessionModelRoute('orca/openrouter/anthropic/claude-fable-5', 'orca/openrouter/anthropic/claude-fable-5'), 'GET /api/models': jsonResponse(models) }) + const offer = await switcher(api()).load(SESSION_ID, true) + expect(offer.items.map((item) => item.value)).toEqual([FREE, 'anthropic/claude-sonnet-4-5']) + expect(offer.initial).toBe(FREE) + expect(offer.freeModel).toBe(true) + }) + + it('offers only the other side otherwise, as before', async () => { + stubFetch({ ...sessionModelRoute('orca/openrouter/anthropic/claude-fable-5', 'orca/openrouter/anthropic/claude-fable-5'), 'GET /api/models': jsonResponse(models) }) + const offer = await switcher(api()).load(SESSION_ID) + expect(offer.items.map((item) => item.value)).toEqual(['anthropic/claude-sonnet-4-5']) + expect(offer.initial).toBeUndefined() + expect(offer.freeModel).toBeUndefined() + }) +}) diff --git a/test/commands/models.test.ts b/test/commands/models.test.ts index e7e4076..ea7626a 100644 --- a/test/commands/models.test.ts +++ b/test/commands/models.test.ts @@ -29,15 +29,34 @@ const MODELS: ModelGroups = { const [luna, auto] = MODELS.groups[0].models const ORCA_ROWS = [ - `${luna.id}\torca\t${priceLine(luna)}\n`, - `${auto.id}\torca\t${priceLine(auto)}\n`, + `${luna.id}\torca\t${priceLine(luna)}\t-\n`, + `${auto.id}\torca\t${priceLine(auto)}\t-\n`, ] -const ANTHROPIC_ROWS = ['anthropic/claude-sonnet-4-5\tanthropic\t-\n'] +const ANTHROPIC_ROWS = ['anthropic/claude-sonnet-4-5\tanthropic\t-\t-\n'] + +// The same answer for a Free organization (free-plan D3.16): the server +// marks each Orca credit model with what Free allows of it. +const FREE = 'orca/openrouter/cohere/north-mini-code:free' +const FABLE = 'orca/openrouter/anthropic/claude-fable-5' +const FREE_MODELS: ModelGroups = { + ...MODELS, + groups: [ + { + ...MODELS.groups[0], + models: [ + { ...luna, plan: 'within_ceiling' }, + { id: FREE, input_micro_usd_per_million: 0, output_micro_usd_per_million: 0, plan: 'free' }, + { id: FABLE, input_micro_usd_per_million: 10_000_000, output_micro_usd_per_million: 50_000_000, plan: 'pro_and_max' }, + ], + }, + MODELS.groups[1], + ], +} const { run, stdout, stderr } = commandHarness(registerModels) describe('orca models', () => { - it('prints one plain row per model: id, who pays, and the price', async () => { + it('prints one plain row per model: id, who pays, the price and the plan mark', async () => { stubFetch({ 'GET /api/models': jsonResponse(MODELS) }) await run(['models']) expect(stdout()).toBe([...ORCA_ROWS, ...ANTHROPIC_ROWS].join('')) @@ -87,4 +106,21 @@ describe('orca models', () => { expect(stderr()).toContain('OpenAI: the server could not read this list.') expect(stdout()).toBe([...ORCA_ROWS, ...ANTHROPIC_ROWS].join('')) }) + + it('marks the free model and the models that need Pro or Max, as the server says, and nothing else', async () => { + stubFetch({ 'GET /api/models': jsonResponse(FREE_MODELS) }) + await run(['models', '--payer', 'orca']) + const [lunaRow, freeRow, fableRow] = stdout().trimEnd().split('\n').map((line) => line.split('\t')) + expect(lunaRow[0]).toBe(luna.id) + expect(lunaRow[3]).toBe('-') + expect(freeRow).toEqual([FREE, 'orca', '$0.00 in, $0.00 out per million tokens', 'free model']) + expect(fableRow[0]).toBe(FABLE) + expect(fableRow[3]).toBe('Pro and Max') + }) + + it('passes the plan field through with --json', async () => { + stubFetch({ 'GET /api/models': jsonResponse(FREE_MODELS) }) + await run(['--json', 'models']) + expect(JSON.parse(stdout())).toEqual(FREE_MODELS) + }) }) diff --git a/test/lib/models.test.ts b/test/lib/models.test.ts index 1287211..a6bd4e9 100644 --- a/test/lib/models.test.ts +++ b/test/lib/models.test.ts @@ -1,6 +1,18 @@ import { describe, expect, it } from 'vitest' -import { counterpart, creditOut, otherSide, payerOf, pickerItems, preselect, refusedAtAdmission } from '../../src/lib/models.js' +import { + counterpart, + creditOut, + freeFirst, + freeModels, + modelRows, + offersFreeModel, + otherSide, + payerOf, + pickerItems, + preselect, + refusedAtAdmission, +} from '../../src/lib/models.js' import { percentBps, tokenPrice } from '../../src/lib/money.js' import type { ModelGroups } from '../../src/lib/types.js' import { glyphs } from '../../src/ui/theme.js' @@ -88,4 +100,69 @@ describe('the switch', () => { expect(refusedAtAdmission('insufficient_quota')).toBe(true) expect(refusedAtAdmission('usage_limit_exceeded')).toBe(false) }) + it('on Free, offers the switch for a model refused at admission, never for machine time', () => { + // free-plan D3.16: a model above the ceiling, or a paid model at $0. + expect(creditOut('model_not_in_plan', 'agent.model')).toBe('orca_credit') + expect(refusedAtAdmission('model_not_in_plan')).toBe(true) + expect(creditOut('insufficient_quota', 'free_plan')).toBe('orca_credit') + // No switch of model pays for Free's included hour. + expect(creditOut('insufficient_quota', 'included_hours')).toBeNull() + expect(creditOut('usage_limit_exceeded', 'included_hours')).toBeNull() + // The free model leads the switch only where the refusal offers it. + expect(offersFreeModel('model_not_in_plan', 'agent.model')).toBe(true) + expect(offersFreeModel('insufficient_quota', 'free_plan')).toBe(true) + expect(offersFreeModel('insufficient_quota', 'free_model_daily')).toBe(false) + expect(offersFreeModel('insufficient_quota', undefined)).toBe(false) + }) +}) + +// The same list for a Free organization: the server marks the free model +// and the models above Free's ceiling (free-plan D3.16, F16). +const FREE = 'orca/openrouter/cohere/north-mini-code:free' +const FREE_LIST: ModelGroups = { + ...LIST, + groups: [ + { + ...LIST.groups[0], + models: [ + { ...LIST.groups[0].models[0], plan: 'within_ceiling' }, + { id: 'orca/openrouter/anthropic/claude-fable-5', input_micro_usd_per_million: 10_000_000, output_micro_usd_per_million: 50_000_000, plan: 'pro_and_max' }, + { id: FREE, input_micro_usd_per_million: 0, output_micro_usd_per_million: 0, plan: 'free' }, + ], + }, + ...LIST.groups.slice(1), + ], +} + +describe('the free model', () => { + it('is the one the server marks, only on Free', () => { + expect(freeModels(FREE_LIST)).toEqual([FREE]) + expect(freeModels(LIST)).toEqual([]) + }) + it('comes first in a picker, the rest in the server\'s order', () => { + const items = freeFirst(pickerItems(FREE_LIST), freeModels(FREE_LIST)) + expect(items.map((item) => item.value)).toEqual([ + FREE, + 'orca/openrouter/openai/gpt-5.6-luna', + 'orca/openrouter/anthropic/claude-fable-5', + 'openrouter/openai/gpt-5.6-luna', + 'anthropic/claude-sonnet-4-5', + ]) + // No free model, no change. + expect(freeFirst(pickerItems(LIST), [])).toEqual(pickerItems(LIST)) + }) + it('and Pro and Max are marked in the picker\'s detail', () => { + const sep = glyphs.separator + const items = pickerItems(FREE_LIST) + expect(items.find((item) => item.value === FREE)?.detail).toBe( + `Orca credit, OpenRouter's price plus their 5.5% fee ${sep} $0.00 in, $0.00 out per million tokens ${sep} free model`, + ) + expect(items.find((item) => item.value.includes('fable'))?.detail).toMatch(/Pro and Max$/) + expect(items.find((item) => item.value.endsWith('luna'))?.detail).not.toMatch(/Pro and Max|free model/) + }) + it('keeps its plan in the flat rows the MCP server lists', () => { + const rows = modelRows(FREE_LIST, 'north') + expect(rows).toEqual([{ id: FREE, payer: 'orca', input_micro_usd_per_million: 0, output_micro_usd_per_million: 0, plan: 'free' }]) + expect(modelRows(LIST, 'claude')[0]).not.toHaveProperty('plan') + }) }) diff --git a/test/lib/plan.test.ts b/test/lib/plan.test.ts new file mode 100644 index 0000000..9e8cc95 --- /dev/null +++ b/test/lib/plan.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from 'vitest' + +import { planActions, planColumn, planWord, planWords } from '../../src/lib/plan.js' +import type { PickModel } from '../../src/lib/types.js' + +describe('the plan marks (free-plan D3.16)', () => { + it('name the free model and the models that need Pro or Max, and nothing else', () => { + expect(planWord('free')).toBe('free model') + expect(planWord('pro_and_max')).toBe('Pro and Max') + expect(planWord('within_ceiling')).toBeUndefined() + expect(planWord(undefined)).toBeUndefined() + }) + + it('make a column only where the server marks a model', () => { + const marked: PickModel[] = [{ id: 'a', plan: 'free' }, { id: 'b', plan: 'within_ceiling' }, { id: 'c', plan: 'pro_and_max' }] + const [column] = planColumn(marked) + expect(column.header).toBe('plan') + expect(marked.map(column.get)).toEqual(['free model', '', 'Pro and Max']) + // Pro and Max, or an older server: every model runs, no column. + expect(planColumn([{ id: 'a', plan: 'within_ceiling' }, { id: 'b' }])).toEqual([]) + }) +}) + +describe('a refusal\'s ways forward', () => { + it('are the dashboard\'s, read from code and param', () => { + expect(planActions('insufficient_quota', 'free_plan')).toEqual(['free_model', 'provider_key', 'add_credit', 'upgrade']) + expect(planActions('model_not_in_plan', 'agent.model')).toEqual(['upgrade', 'free_model']) + expect(planActions('insufficient_quota', 'free_model_capacity')).toEqual(['provider_key', 'upgrade']) + expect(planActions('insufficient_quota', 'free_model_daily')).toEqual(['provider_key', 'upgrade']) + expect(planActions('usage_limit_exceeded', 'free_model_capacity')).toEqual(['provider_key', 'upgrade']) + expect(planActions('insufficient_quota', 'included_hours')).toEqual(['add_credit']) + expect(planActions('usage_limit_exceeded', 'included_hours')).toEqual(['add_credit']) + expect(planActions('free_model_unavailable', undefined)).toEqual(['provider_key', 'add_credit']) + }) + + it('are none for every other refusal', () => { + expect(planActions('insufficient_quota', undefined)).toEqual([]) + expect(planActions('usage_limit_exceeded', 'orca_credit')).toEqual([]) + expect(planActions('rate_limit_exceeded', 'free_plan')).toEqual([]) + expect(planActions(null, null)).toEqual([]) + }) + + it('are words with the command for each', () => { + expect(planWords('insufficient_quota', 'free_plan')).toEqual([ + 'Switch this session to the free model (orca chat offers it at a terminal)', + 'Add a provider key: in the dashboard, Settings, Providers', + 'Add credit: orca billing buy pack: (orca billing wallet lists the packs)', + 'Upgrade: orca billing buy pro, or orca billing buy max', + ]) + }) +}) diff --git a/test/lib/sessions.test.ts b/test/lib/sessions.test.ts index 20fd44e..9669b57 100644 --- a/test/lib/sessions.test.ts +++ b/test/lib/sessions.test.ts @@ -2,7 +2,7 @@ import OpenAI from 'openai' import type { AgentSessionItem } from 'openai/resources/beta/agents/agents' import { afterEach, describe, expect, it, vi } from 'vitest' -import { itemText, sandboxStateWords, streamTurn, type ChatEvent } from '../../src/lib/sessions.js' +import { itemText, noticeText, sandboxStateWords, streamTurn, type ChatEvent } from '../../src/lib/sessions.js' import { stubFetch } from '../helpers/fetch-mock.js' import { SESSION_ID, session, turnRoutes } from '../helpers/session-events.js' @@ -124,3 +124,27 @@ describe('sandboxStateWords', () => { ]) }) }) + +describe('the server\'s session notices (free-plan D3.16)', () => { + it('are the four Orca notices, each its message as one clean line', () => { + expect(noticeText({ type: 'orca.compute.warning', message: '5 minutes of included\nmachine time left this month.' })).toBe( + '5 minutes of included machine time left this month.', + ) + expect(noticeText({ type: 'orca.free_model.turn_limit', message: 'This turn reached the free model\'s 25 calls.' })).toBe( + 'This turn reached the free model\'s 25 calls.', + ) + expect(noticeText({ type: 'orca.turn.time_limit', message: 'This turn reached Free\'s 30 minutes.\u001b[2J' })).toBe( + 'This turn reached Free\'s 30 minutes.', + ) + expect(noticeText({ type: 'orca.network.off', message: 'Network is off on Free sandboxes.' })).toBe( + 'network off. Network is off on Free sandboxes.', + ) + }) + + it('leave every other event, and a notice with no message, to the stream', () => { + expect(noticeText({ type: 'agent.session.idle' })).toBeNull() + expect(noticeText({ type: 'orca.something.new', message: 'x' })).toBeNull() + expect(noticeText({ type: 'orca.network.off' })).toBeNull() + expect(noticeText({ type: 'orca.network.off', message: ' ' })).toBeNull() + }) +}) diff --git a/test/ui/Chat.test.tsx b/test/ui/Chat.test.tsx index 0516c68..51a2fb7 100644 --- a/test/ui/Chat.test.tsx +++ b/test/ui/Chat.test.tsx @@ -261,6 +261,112 @@ describe('Chat REPL', () => { }, 20000) }) +describe('Chat on the Free plan (free-plan D3.16)', () => { + const NETWORK = 'network off. Network is off on Free sandboxes until your organization has credit.' + + it('shows the server\'s notices in the transcript as they arrive', async () => { + const send: SendTurn = async (_message, handlers) => { + handlers.onEvent({ type: 'notice', text: NETWORK }) + handlers.onEvent({ type: 'notice', text: "This turn reached the free model's 25 calls. Send a message to continue." }) + return { terminated: 'done', message: 'Wrote the script.', sessionId: 'sess_1' } + } + const { stdin, frames } = render( {}} />) + await waitFor(() => frames.join('').includes('Chat')) + await ready(stdin as unknown as EventEmitter) + stdin.write('go') + await waitFor(() => frames.join('\n').includes('go')) + stdin.write('\r') + await waitFor(() => frames.join('\n').includes('Wrote the script.')) + const all = frames.join('\n').replace(/\s+/g, ' ') + expect(all).toContain(NETWORK.replace(/\s+/g, ' ')) + expect(all).toContain("This turn reached the free model's 25 calls. Send a message to continue.") + }, 20000) + + it('after a stop for machine time, prints its ways forward and offers no switch of model', async () => { + let loaded = false + const send: SendTurn = async () => ({ + terminated: 'error', + message: "Free's 1 included hour this month is used up and this organization has no credit.", + errorCode: 'usage_limit_exceeded', + errorParam: 'included_hours', + sessionId: 'sess_1', + }) + const switcher: Switcher = { + load: async () => { + loaded = true + return { items: [], provider: 'orca' } + }, + apply: async () => {}, + } + const { stdin, frames, lastFrame } = render( {}} />) + await waitFor(() => frames.join('').includes('Chat')) + await ready(stdin as unknown as EventEmitter) + stdin.write('go') + await waitFor(() => frames.join('\n').includes('go')) + stdin.write('\r') + await waitFor(() => frames.join('\n').includes('Add credit: orca billing buy')) + expect(frames.join('\n')).toContain('included hour this month is used up') + expect(loaded).toBe(false) + expect(lastFrame() ?? '').not.toContain('Top up, or switch') + }, 20000) + + it('after a model refused on Free, prints the ways forward and offers the free model first', async () => { + const sent: string[] = [] + const send: SendTurn = async (message) => { + sent.push(message) + if (sent.length === 1) { + return { + terminated: 'error', + message: 'This model needs Pro or Max.', + errorCode: 'model_not_in_plan', + errorParam: 'agent.model', + sessionId: 'sess_1', + } + } + return { terminated: 'done', message: 'Answered on the free model', sessionId: 'sess_1' } + } + const loads: Array = [] + const applied: string[] = [] + const switcher: Switcher = { + load: async (_sessionId, freeModel) => { + loads.push(freeModel) + return { + items: [ + { label: 'orca/openrouter/cohere/north-mini-code:free', value: 'orca/openrouter/cohere/north-mini-code:free' }, + { label: 'anthropic/claude-sonnet-4-5', value: 'anthropic/claude-sonnet-4-5' }, + ], + initial: 'orca/openrouter/cohere/north-mini-code:free', + provider: 'orca', + freeModel: true, + } + }, + apply: async (_sessionId, model) => { + applied.push(model) + }, + } + const { stdin, frames, lastFrame } = render( {}} />) + await waitFor(() => frames.join('').includes('Chat')) + await ready(stdin as unknown as EventEmitter) + stdin.write('go') + await waitFor(() => frames.join('\n').includes('go')) + stdin.write('\r') + await waitFor(() => (lastFrame() ?? '').includes('Top up, or switch this session?')) + expect(frames.join('\n')).toContain('Upgrade: orca billing buy pro, or orca billing buy max') + expect(frames.join('\n')).toContain('Switch this session to the free model (orca chat offers it at a terminal)') + expect(lastFrame() ?? '').toContain('Switch this session to the free model or your own key') + expect(loads).toEqual([true]) + await ready(stdin as unknown as EventEmitter) + stdin.write('\r') + await waitFor(() => (lastFrame() ?? '').includes('Select a model')) + await ready(stdin as unknown as EventEmitter) + stdin.write('\r') + await waitFor(() => frames.join('\n').includes('Answered on the free model')) + expect(applied).toEqual(['orca/openrouter/cohere/north-mini-code:free']) + // Refused at admission, so the same message goes again. + expect(sent).toEqual(['go', 'go']) + }, 20000) +}) + describe('Chat web search lines', () => { const QUERY = 'rust async runtimes 2026' const NO_SEARCH = 'openai/gpt-x answered without searching the web. Use a model with built-in web search: docs.orcapods.ai/providers#web-search' From 08debb2ca88cb8f7ac6d9629bb2f67c7111c9fac Mon Sep 17 00:00:00 2001 From: ahokik Date: Tue, 20 Oct 2026 20:08:42 +0100 Subject: [PATCH 02/15] billing wallet: granted and paid credit, machine time, the free model, the network and more credit lines; MCP descriptions (D3.16) - orca billing wallet at a terminal prints the design's lines: one "granted credit $12.40 left of $20.00, expires 4 Dec 2026" per grant (its last day, the day before expires_at), "paid credit $18.20 (never expires)", "machine time 1 h included: 0.4 h used, resets 1 November" (or "used"), "free model 40 of 100 calls today", "network off. ..." and on Free "more credit ..." in the server's words. - Plain mode adds granted_credit, paid_credit, one grant row each (left, granted, last day), expired, free_model_calls_today and _per_day and network_off; the network and more credit messages go to stderr. --json passes every field through. - MCP list_models names plan, get_wallet names the new fields. Co-Authored-By: Claude Opus 5.5 --- src/commands/billing.tsx | 28 +++++++++++++-- src/lib/format.ts | 27 ++++++++++++++ src/lib/wallet.ts | 50 ++++++++++++++++++++++++++ src/mcp/server.ts | 4 +-- src/ui/WalletView.tsx | 34 ++++++++++++++---- test/commands/billing.test.ts | 53 ++++++++++++++++++++++++++++ test/format.test.ts | 19 +++++++++- test/mcp/server.test.ts | 31 ++++++++++++++++ test/ui/WalletView.test.tsx | 66 ++++++++++++++++++++++++++++++++++- 9 files changed, 299 insertions(+), 13 deletions(-) create mode 100644 src/lib/wallet.ts diff --git a/src/commands/billing.tsx b/src/commands/billing.tsx index f5971f1..8bd6e60 100644 --- a/src/commands/billing.tsx +++ b/src/commands/billing.tsx @@ -6,6 +6,7 @@ import { formatDate } from '../lib/format.js' import { belowZeroNote, usdMicro } from '../lib/money.js' import { interactive, outputMode, printJson, printPlainRows, renderStatic } from '../lib/output.js' import type { BillingURL } from '../lib/types.js' +import { creditRequest, grantLastDay, networkOff } from '../lib/wallet.js' import { hintText } from '../ui/theme.js' import { apiContext, globalFlags, withApi } from './shared.js' @@ -47,7 +48,7 @@ export function registerBilling(program: Command): void { billing .command('wallet') - .description('show the balance, plan, period, and the credit packs on sale') + .description('show the balance, granted and paid credit, plan, period, machine time, and the credit packs on sale') .action(async (_opts: Record, cmd: Command) => { const flags = globalFlags(cmd) const api = await apiContext(cmd) @@ -71,11 +72,34 @@ export function registerBilling(program: Command): void { ['included_compute_seconds', wallet.included_compute_seconds], ['packs', wallet.packs.map((p) => `pack:${p.cents}`).join(',') || '-'], ['openrouter_fee_bps', wallet.openrouter_fee_bps], + // Granted and paid credit, and the Free plan (free-plan D3.16), + // where the server sends them: one row per grant, with what is + // left, what was granted and its last day. + ...(wallet.granted_credit_micro_usd !== undefined ? [['granted_credit', usdMicro(wallet.granted_credit_micro_usd)]] : []), + ...(wallet.paid_credit_micro_usd !== undefined ? [['paid_credit', usdMicro(wallet.paid_credit_micro_usd)]] : []), + ...(wallet.granted_credit ?? []).map((g) => [ + 'grant', + usdMicro(g.left_micro_usd), + usdMicro(g.granted_micro_usd), + formatDate(grantLastDay(g)), + ]), + ...(wallet.expired_micro_usd !== undefined ? [['expired', usdMicro(wallet.expired_micro_usd)]] : []), + ...(wallet.free_model + ? [ + ['free_model_calls_today', wallet.free_model.calls_today], + ['free_model_calls_per_day', wallet.free_model.calls_per_day], + ] + : []), + ...(wallet.network ? [['network_off', String(wallet.network.off)]] : []), ]) - // The rows stay key and value for cut and grep; the note goes to + // The rows stay key and value for cut and grep; the notes go to // stderr, as the CLI's other hints do. const note = belowZeroNote(wallet.balance_micro_usd, wallet.min_balance_micro_usd) if (note) console.error(hintText(note)) + const network = networkOff(wallet) + if (network) console.error(hintText(`network ${network}`)) + const moreCredit = creditRequest(wallet) + if (moreCredit) console.error(hintText(`more credit ${moreCredit}`)) return } const { WalletView } = await import('../ui/WalletView.js') diff --git a/src/lib/format.ts b/src/lib/format.ts index ba6608f..8328e80 100644 --- a/src/lib/format.ts +++ b/src/lib/format.ts @@ -22,3 +22,30 @@ export function formatCount(n: number): string { if (Math.abs(n) >= 1_000) return `${(n / 1_000).toFixed(1)}k` return String(n) } + +const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] + +// formatDayMonth renders unix seconds as the UTC day and month, "1 November": +// the day a plan's period resets. +export function formatDayMonth(seconds: number): string { + const d = new Date(seconds * 1000) + if (Number.isNaN(d.getTime())) return '-' + return `${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]}` +} + +// formatDayShort renders unix seconds as the UTC day, short month and year, +// "4 Dec 2026". +export function formatDayShort(seconds: number): string { + const d = new Date(seconds * 1000) + if (Number.isNaN(d.getTime())) return '-' + return `${d.getUTCDate()} ${MONTHS[d.getUTCMonth()].slice(0, 3)} ${d.getUTCFullYear()}` +} + +// formatHours renders seconds as hours to a tenth, rounded down so time not +// all used never reads as all used: 3600 is "1 h", 1440 "0.4 h", 3,600,000 +// "1,000 h". +export function formatHours(seconds: number): string { + const tenths = Math.floor(Math.max(0, seconds) / 360) + const whole = String(Math.floor(tenths / 10)).replace(/\B(?=(\d{3})+(?!\d))/g, ',') + return tenths % 10 ? `${whole}.${tenths % 10} h` : `${whole} h` +} diff --git a/src/lib/wallet.ts b/src/lib/wallet.ts new file mode 100644 index 0000000..65c3add --- /dev/null +++ b/src/lib/wallet.ts @@ -0,0 +1,50 @@ +// The wallet's Free plan and granted credit lines (orca-design free-plan +// D3.16, "What a person sees", CLI), shared by the panel at a terminal and +// the plain rows. Every figure and message is the server's; the CLI only +// formats them. + +import { formatDayMonth, formatDayShort, formatHours } from './format.js' +import { stripControlSequences } from './markdown.js' +import { usdMicro } from './money.js' +import type { GrantedCredit, Wallet } from './types.js' + +// machineTime is the period's included machine time and how much is used: +// "1 h included: 0.4 h used, resets 1 November", or "used" once it all is. +export function machineTime(w: Wallet): string { + const used = w.used_compute_seconds >= w.included_compute_seconds ? 'used' : `${formatHours(w.used_compute_seconds)} used` + return `${formatHours(w.included_compute_seconds)} included: ${used}, resets ${formatDayMonth(w.period_end)}` +} + +// freeModelCalls is the free model's calls today against the share, on Free: +// "40 of 100 calls today". Null on Pro and Max. +export function freeModelCalls(w: Wallet): string | null { + return w.free_model ? `${w.free_model.calls_today} of ${w.free_model.calls_per_day} calls today` : null +} + +// networkOff is the network line while Free sandboxes have none: "off." +// and the server's message. Null when the network is on. +export function networkOff(w: Wallet): string | null { + return w.network?.off ? `off. ${stripControlSequences(w.network.message ?? '')}`.trimEnd() : null +} + +// creditRequest is where a Free organization asks for credit, in the +// server's words. Null on Pro and Max. +export function creditRequest(w: Wallet): string | null { + return w.credit_request ? stripControlSequences(w.credit_request.message) : null +} + +// grantLastDay is the last UTC day a grant can be spent: expires_at is +// 00:00 UTC the day after it. +export function grantLastDay(grant: GrantedCredit): number { + return grant.expires_at - 1 +} + +// grantedLine is one grant: "$12.40 left of $20.00, expires 4 Dec 2026". +export function grantedLine(grant: GrantedCredit): string { + return `${usdMicro(grant.left_micro_usd)} left of ${usdMicro(grant.granted_micro_usd)}, expires ${formatDayShort(grantLastDay(grant))}` +} + +// paidCredit is the credit that never expires: "$18.20 (never expires)". +export function paidCredit(w: Wallet): string | null { + return w.paid_credit_micro_usd === undefined ? null : `${usdMicro(w.paid_credit_micro_usd)} (never expires)` +} diff --git a/src/mcp/server.ts b/src/mcp/server.ts index 2649cb5..8454dea 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -253,7 +253,7 @@ export function buildMcpServer(getClient: ClientSource): McpServer { tool( 'list_models', - 'List the model names an agent can use, one row each: id, payer (orca for Orca credit, else the provider whose saved key pays) and, for Orca credit, OpenRouter\'s price per million tokens in micro-USD; Orca credit pays that plus OpenRouter\'s fee (openrouter_fee_bps). The list is long: narrow it with query (part of the name, such as luna or claude) or payer, and page with limit and after. Use an id as an agent\'s model.', + 'List the model names an agent can use, one row each: id, payer (orca for Orca credit, else the provider whose saved key pays) and, for Orca credit, OpenRouter\'s price per million tokens in micro-USD and plan, what this organization\'s plan allows: free (Orca\'s free model, no charge, on the Free plan only), within_ceiling (runs on credit), or pro_and_max (needs Pro or Max; on Free it is refused). Orca credit pays the price plus OpenRouter\'s fee (openrouter_fee_bps). The list is long: narrow it with query (part of the name, such as luna or claude) or payer, and page with limit and after. Use an id as an agent\'s model.', { payer: z.string().optional().describe('orca, or a provider such as anthropic'), query: z.string().optional().describe('only names containing this, in any case'), @@ -605,7 +605,7 @@ export function buildMcpServer(getClient: ClientSource): McpServer { tool( 'get_wallet', - 'The credit wallet: balance, credited and charged (micro-USD), plan tier, period, compute allowance, and the credit packs on sale.', + 'The credit wallet: balance, credited and charged (micro-USD), plan tier, period, compute allowance (included_compute_seconds, used_compute_seconds), and the credit packs on sale. granted_credit_micro_usd is credit Orca granted, spent first, and paid_credit_micro_usd the rest, which never expires; granted_credit lists each grant with left_micro_usd and expires_at (00:00 UTC the day after its last day); expired_micro_usd is granted credit that expired unspent. On the Free plan: free_model (calls_today of calls_per_day, the free model\'s share today; null on Pro and Max), network (off is true while Free sandboxes have no network, with the message to show), credit_request (where to ask for credit, with its message), and included_hours_withheld.', {}, async (client) => client.wallet(), ) diff --git a/src/ui/WalletView.tsx b/src/ui/WalletView.tsx index bb14dac..c78ef17 100644 --- a/src/ui/WalletView.tsx +++ b/src/ui/WalletView.tsx @@ -3,36 +3,56 @@ import { Box, Text } from 'ink' import { formatDate } from '../lib/format.js' import { belowZeroNote, tokenPrice, usdCents, usdMicro } from '../lib/money.js' import type { Wallet } from '../lib/types.js' +import { creditRequest, freeModelCalls, grantedLine, machineTime, networkOff, paidCredit } from '../lib/wallet.js' import { Field, Panel } from './Panel.js' import { theme } from './theme.js' +// The label column, wide enough for "granted credit" and a gap. +const LABEL_WIDTH = 16 + // WalletView is `orca billing wallet` at a terminal: the balance as it is -// (negative after a late charge), the server's paused verdict, and, below -// zero, the one line that says when paid work resumes. +// (negative after a late charge), the server's paused verdict, granted and +// paid credit, the Free plan's lines (free-plan D3.16) where the server +// sends them, and, below zero, the one line that says when paid work +// resumes. export function WalletView({ wallet: w }: { wallet: Wallet }) { const note = belowZeroNote(w.balance_micro_usd, w.min_balance_micro_usd) + const paid = paidCredit(w) + const freeModel = freeModelCalls(w) + const network = networkOff(w) + const moreCredit = creditRequest(w) return ( - - - - - + {(w.granted_credit ?? []).map((grant, i) => ( + + ))} + {paid ? : null} + + + + + {freeModel ? : null} + {network ? : null} + {w.packs.length > 0 ? ( `pack:${p.cents} (${usdCents(p.cents)}, credits ${usdMicro(p.credited_micro_usd)})`).join(', ')} /> ) : null} + {moreCredit ? : null} {note ? ( {note} diff --git a/test/commands/billing.test.ts b/test/commands/billing.test.ts index ee4d311..ff6589b 100644 --- a/test/commands/billing.test.ts +++ b/test/commands/billing.test.ts @@ -24,6 +24,27 @@ const WALLET = { openrouter_fee_bps: 550, } +// A Free organization's wallet (free-plan D3.16): granted and paid credit, +// the free model today, the network off and where to ask for credit. +const NETWORK = 'Network is off on Free sandboxes until your organization has credit. Add credit, or write to us on Discord (https://discord.gg/btTYzdzvqq).' +const MORE_CREDIT = 'Need more to try Orca? Write to us on Discord (https://discord.gg/btTYzdzvqq).' +const FREE_WALLET = { + ...WALLET, + tier: 'free', + included_compute_seconds: 3_600, + used_compute_seconds: 1_440, + granted_credit_micro_usd: 12_400_000, + paid_credit_micro_usd: 6_100_000, + granted_credit: [ + { kind: 'grant', grant_reason: 'on_request', granted_micro_usd: 20_000_000, left_micro_usd: 12_400_000, granted_at: 1_793_750_400, expires_at: 1_796_428_800 }, + ], + expired_micro_usd: 0, + free_model: { calls_today: 40, calls_per_day: 100, available: true }, + included_hours_withheld: false, + network: { off: true, message: NETWORK }, + credit_request: { message: MORE_CREDIT, url: 'https://discord.gg/btTYzdzvqq' }, +} + const { run, stdout, stderr } = commandHarness(registerBilling) afterEach(() => { @@ -88,6 +109,38 @@ describe('billing wallet', () => { }) }) +describe('billing wallet on Free (free-plan D3.16)', () => { + it('adds granted and paid credit, each grant with its last day, and the free model today', async () => { + stubFetch({ 'GET /api/billing/wallet': jsonResponse(FREE_WALLET) }) + await run(['billing', 'wallet']) + expect(stdout()).toContain('granted_credit\t$12.40\n') + expect(stdout()).toContain('paid_credit\t$6.10\n') + // What is left, what was granted, and the last day it can be spent. + expect(stdout()).toContain('grant\t$12.40\t$20.00\t2026-12-04\n') + expect(stdout()).toContain('expired\t$0.00\n') + expect(stdout()).toContain('free_model_calls_today\t40\nfree_model_calls_per_day\t100\n') + expect(stdout()).toContain('network_off\ttrue\n') + // The server's messages go to stderr, the rows stay key and value. + expect(stdout()).not.toContain('Discord') + expect(stderr()).toBe(`network off. ${NETWORK}\nmore credit ${MORE_CREDIT}\n`) + }) + + it('passes every new field through with --json', async () => { + stubFetch({ 'GET /api/billing/wallet': jsonResponse(FREE_WALLET) }) + await run(['--json', 'billing', 'wallet']) + expect(JSON.parse(stdout())).toEqual(FREE_WALLET) + expect(stderr()).toBe('') + }) + + it('adds nothing on Pro, where the server sends no Free plan fields', async () => { + stubFetch({ 'GET /api/billing/wallet': jsonResponse({ ...WALLET, free_model: null, network: { off: false }, credit_request: null }) }) + await run(['billing', 'wallet']) + expect(stdout()).not.toContain('free_model') + expect(stdout()).toContain('network_off\tfalse\n') + expect(stderr()).toBe('') + }) +}) + describe('billing buy', () => { it('opens a checkout for a plan and prints the link when piped', async () => { const opened: string[] = [] diff --git a/test/format.test.ts b/test/format.test.ts index b15fa90..6de2e98 100644 --- a/test/format.test.ts +++ b/test/format.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' -import { formatCount, formatDate, formatTime } from '../src/lib/format.js' +import { formatCount, formatDate, formatDayMonth, formatDayShort, formatHours, formatTime } from '../src/lib/format.js' import { belowZeroNote, usdCents, usdMicro } from '../src/lib/money.js' describe('formatTime', () => { @@ -20,6 +20,23 @@ describe('formatDate', () => { }) }) +describe('the wallet\'s dates and hours (free-plan D3.16)', () => { + it('render a reset day as day and month, and a grant\'s day with the year, in UTC', () => { + // 2026-11-01 00:00 UTC, when Free's October period resets. + expect(formatDayMonth(1_793_491_200)).toBe('1 November') + // 2026-12-04 23:59:59 UTC. + expect(formatDayShort(1_796_428_799)).toBe('4 Dec 2026') + }) + it('render hours to a tenth, rounded down, with thousands', () => { + expect(formatHours(3_600)).toBe('1 h') + expect(formatHours(1_440)).toBe('0.4 h') + expect(formatHours(3_599)).toBe('0.9 h') + expect(formatHours(0)).toBe('0 h') + expect(formatHours(216_000)).toBe('60 h') + expect(formatHours(3_600_000)).toBe('1,000 h') + }) +}) + describe('formatCount', () => { it('compacts thousands and millions', () => { expect(formatCount(950)).toBe('950') diff --git a/test/mcp/server.test.ts b/test/mcp/server.test.ts index 183d55c..faf9eb3 100644 --- a/test/mcp/server.test.ts +++ b/test/mcp/server.test.ts @@ -487,6 +487,37 @@ describe('orca mcp serve: models, artifacts and staged files', () => { expect(firstText(unknown)).toContain('Payers: orca, anthropic') }) + it('list_models carries each Orca credit model\'s plan mark, and its description names it (free-plan D3.16)', async () => { + const free = { id: 'orca/openrouter/cohere/north-mini-code:free', input_micro_usd_per_million: 0, output_micro_usd_per_million: 0, plan: 'free' } + const marked = { ...MODELS, groups: [{ ...MODELS.groups[0], models: [free] }, MODELS.groups[1]] } + stubFetch({ 'GET /api/models': jsonResponse(marked) }) + const client = await connect() + const rows = JSON.parse(firstText(await client.callTool({ name: 'list_models', arguments: { payer: 'orca' } }))) + expect(rows.items).toEqual([{ ...free, payer: 'orca' }]) + const tool = (await client.listTools()).tools.find((t) => t.name === 'list_models') + for (const word of ['plan', 'free', 'within_ceiling', 'pro_and_max']) expect(tool?.description).toContain(word) + }) + + it('get_wallet\'s description names granted and paid credit and the Free plan fields (free-plan D3.16)', async () => { + const client = await connect() + const tool = (await client.listTools()).tools.find((t) => t.name === 'get_wallet') + for (const field of [ + 'granted_credit_micro_usd', + 'paid_credit_micro_usd', + 'granted_credit', + 'left_micro_usd', + 'expires_at', + 'expired_micro_usd', + 'free_model', + 'calls_today', + 'network', + 'credit_request', + 'included_hours_withheld', + ]) { + expect(tool?.description).toContain(field) + } + }) + it('list_artifacts returns a page of the session\'s artifacts', async () => { stubFetch({ [`GET ${ARTIFACTS}?limit=20`]: jsonResponse(list([artifact('art_2', '/workspace/outputs/primes.txt', 'turn_2')])), diff --git a/test/ui/WalletView.test.tsx b/test/ui/WalletView.test.tsx index f759337..ebe3bf7 100644 --- a/test/ui/WalletView.test.tsx +++ b/test/ui/WalletView.test.tsx @@ -23,11 +23,37 @@ const WALLET: Wallet = { const NOTE = 'Your balance is below zero. Paid work resumes when credit brings it to $0.50.' +// A Free organization in October 2026 (free-plan D3.16): the free model +// today, the network off, the request line, honoured signup credit and an +// operator grant, soonest expiry first. +const NETWORK = 'Network is off on Free sandboxes until your organization has credit. Add credit, or write to us on Discord (https://discord.gg/btTYzdzvqq).' +const MORE_CREDIT = 'Need more to try Orca? Write to us on Discord (https://discord.gg/btTYzdzvqq).' +const FREE_WALLET: Wallet = { + ...WALLET, + balance_micro_usd: 35_600_000, + tier: 'free', + period_start: 1_790_812_800, + period_end: 1_793_491_200, + included_compute_seconds: 3_600, + used_compute_seconds: 1_440, + granted_credit_micro_usd: 17_400_000, + paid_credit_micro_usd: 18_200_000, + granted_credit: [ + { kind: 'signup', grant_reason: null, granted_micro_usd: 20_000_000, left_micro_usd: 5_000_000, granted_at: 1_791_072_000, expires_at: 1_793_836_800 }, + { kind: 'grant', grant_reason: 'on_request', granted_micro_usd: 20_000_000, left_micro_usd: 12_400_000, granted_at: 1_793_750_400, expires_at: 1_796_428_800 }, + ], + expired_micro_usd: 0, + free_model: { calls_today: 40, calls_per_day: 100, available: true }, + included_hours_withheld: false, + network: { off: true, message: NETWORK }, + credit_request: { message: MORE_CREDIT, url: 'https://discord.gg/btTYzdzvqq' }, +} + describe('WalletView', () => { it('shows a balance below zero as it is, and one line naming the minimum', () => { const { lastFrame } = render() const frame = lastFrame() ?? '' - expect(frame).toContain('balance -$0.60') + expect(frame).toContain('balance -$0.60') expect(frame).toContain('paused under the $0.50 minimum, until a top-up') expect(frame.split(NOTE)).toHaveLength(2) }) @@ -36,4 +62,42 @@ describe('WalletView', () => { expect(render().lastFrame()).not.toContain('below zero') expect(render().lastFrame()).not.toContain('below zero') }) + + it('says the plan\'s machine time in hours and when it resets', () => { + // Pro: 10 hours included, 120 s used, the period ends 4 August. + expect(render().lastFrame()).toContain('machine time 10 h included: 0 h used, resets 4 August') + }) + + it('adds no Free plan or granted credit line where the server sends none', () => { + const frame = render().lastFrame() ?? '' + for (const label of ['granted credit', 'paid credit', 'free model', 'network', 'more credit']) expect(frame).not.toContain(label) + }) + + it('prints the Free plan\'s lines as the design writes them', () => { + const frame = (render().lastFrame() ?? '').replace(/\s+/g, ' ') + expect(frame).toContain('WALLET · free plan') + expect(frame).toContain('machine time 1 h included: 0.4 h used, resets 1 November') + expect(frame).toContain('free model 40 of 100 calls today') + expect(frame).toContain(`network off. ${NETWORK}`) + expect(frame).toContain(`more credit ${MORE_CREDIT}`) + }) + + it('prints one line per grant, its last day, then the paid credit that never expires', () => { + const lines = (render().lastFrame() ?? '').split('\n').map((line) => line.trim()) + expect(lines).toContain('granted credit $5.00 left of $20.00, expires 4 Nov 2026') + expect(lines).toContain('granted credit $12.40 left of $20.00, expires 4 Dec 2026') + expect(lines).toContain('paid credit $18.20 (never expires)') + // Soonest expiry first, as the server lists them. + expect(lines.findIndex((l) => l.includes('4 Nov 2026'))).toBeLessThan(lines.findIndex((l) => l.includes('4 Dec 2026'))) + }) + + it('says the included hour is used once it all is', () => { + const frame = render().lastFrame() ?? '' + expect(frame).toContain('machine time 1 h included: used, resets 1 November') + }) + + it('prints no network line once the network is on', () => { + const frame = render().lastFrame() ?? '' + expect(frame).not.toContain('network') + }) }) From dac006ed816a8768ee3c82782826d9c89323c5a1 Mon Sep 17 00:00:00 2001 From: ahokik Date: Tue, 20 Oct 2026 20:08:42 +0100 Subject: [PATCH 03/15] README and use-orca: plan marks, Free refusals and notices, granted and paid credit (D3.16) Co-Authored-By: Claude Opus 5.5 --- README.md | 26 ++++++++++++++++--- plugins/orca/skills/use-orca/SKILL.md | 5 ++-- .../use-orca/references/cli-cheatsheet.md | 4 +-- 3 files changed, 27 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index f02b9a9..abd24e6 100644 --- a/README.md +++ b/README.md @@ -188,7 +188,7 @@ orca agents create -f agent.yaml # YAML or JSON; - for stdin orca agents update -f fields.yaml # only the fields in the file change orca agents delete [agent] [--yes] -orca models [--payer orca|] # every model you can use, grouped by who pays +orca models [--payer orca|] # every model you can use, grouped by who pays, with Free's plan marks orca sessions list [--agent agent] orca sessions get @@ -272,7 +272,10 @@ you can use, grouped by who pays: Orca credit, at OpenRouter's price per million tokens plus their fee, then each provider you saved a key for. With `--json` or outside a terminal the file must name the model; `orca models` lists the same names anywhere (`--payer orca` or `--payer anthropic` for one group, `--json` -for the server's list). +for the server's list). On the Free plan the server marks each Orca credit +model: `orca models` shows "free model" for Orca's free model and "Pro and Max" +for a model Free cannot run on credit, and the picker offers the free model +first. `orca chat [prompt]` runs a turn on a `/v1` session with your API key. Without `--session` it creates a session of the agent first (no environment by @@ -332,6 +335,16 @@ exists there), applies from the next turn for this session only, and continues with `Continue`. Outside a terminal or with `--json` it prints the reason and the session id and exits 1. +On the Free plan, a refusal (a model that needs Pro or Max, a paid model with +no credit, the free model's calls used up for today, the included hour of +machine time used up) prints the server's message and its ways forward as +words: switch this session to the free model, add a provider key, add credit, +or upgrade, each with its command. Where the free model is one of them, the +switch in a terminal lists it first. The server's notices during a turn (5 +minutes of machine time left, a turn ended at the free model's calls or at +Free's 30 minutes, a sandbox with no network) are printed on stderr, and with +`--json` arrive as their own events. + ## Usage and billing Every money figure is the server's: usage rows are priced when they are written, @@ -347,14 +360,19 @@ paused, as the server treats it. A call whose cost was not reported when it ended is charged later, on a `late_charges` row that `orca usage events` shows as "Charged later" for the row it charges, so a balance can go below zero; `orca billing wallet` then prints it as it is (`-$0.60`) and says paid work -resumes when credit brings it to the minimum. +resumes when credit brings it to the minimum. Credit Orca grants is spent +first and expires; credit you buy never does: the wallet prints one `granted +credit` line per grant with what is left and its last day, then `paid credit`. +On Free it adds the included machine time and when it resets, the free model's +calls today, the network line while Free sandboxes have none, and where to ask +for more credit. ```sh orca usage # last 30 days: cost, meters, daily chart orca usage --days 7 --group-by agent # also each agent's tokens and cost orca usage --session sess_123 # one session orca usage events --charged # the rows with a cost: what the wallet's charges sum -orca billing wallet # balance, plan, period, packs on sale +orca billing wallet # balance, granted and paid credit, plan, period, packs on sale orca billing buy pro # checkout for the Pro plan orca billing buy pack:2000 # checkout for the $20 credit pack orca billing manage # change or cancel the plan diff --git a/plugins/orca/skills/use-orca/SKILL.md b/plugins/orca/skills/use-orca/SKILL.md index e2c3863..949104d 100644 --- a/plugins/orca/skills/use-orca/SKILL.md +++ b/plugins/orca/skills/use-orca/SKILL.md @@ -60,7 +60,7 @@ orca agents list --json # only when the user does not know `` is an agent id or the name of exactly one agent (the server says which; a shared name is refused with the ids). Add `--sandbox` (or `--template