Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

feat(ruflo-console): Cost can set a budget, shows where spend goes, and projects the burn (codex)

ruv484cf7b3a840
diff --git a/plugins/ruflo-console/hooks/actions.ts b/plugins/ruflo-console/hooks/actions.ts
index 5fb683024c..62316782b9 100644
--- a/plugins/ruflo-console/hooks/actions.ts
+++ b/plugins/ruflo-console/hooks/actions.ts
@@ -9,6 +9,9 @@ import type { Snapshot } from './data/snapshot'
export type ActionSpec = {
label: string
args: readonly string[]
+ /** A fixed command outside ruflo, or an offline read, with optional JSON on stdin. */
+ argv?: readonly string[]
+ stdin?: string
expect: string
verify?: (snapshot: Snapshot) => boolean
/** Reads only: runs at once, without the confirm step, and shows what the CLI printed. */
diff --git a/plugins/ruflo-console/hooks/bindings.ts b/plugins/ruflo-console/hooks/bindings.ts
index a52ccfc673..15a9aa8d2f 100644
--- a/plugins/ruflo-console/hooks/bindings.ts
+++ b/plugins/ruflo-console/hooks/bindings.ts
@@ -118,6 +118,9 @@ export function actionsOf(state: State, host: Host, runner: Runner, steps: Steps
if (best !== undefined) runner.runEntry(best, best.run.kind === 'text' ? state.palette.query.trim().slice(best.run.keyword.length).trim() : '')
},
run: (id, text = '') => runner.runById(id, text),
+ costBudgetDraft: text => {
+ state.costBudgetDraft = text.slice(0, 40)
+ },
filter: () => {
const order = ['all', ...EVENT_KINDS] as const
const at = order.indexOf(state.eventFilter)
diff --git a/plugins/ruflo-console/hooks/controller.ts b/plugins/ruflo-console/hooks/controller.ts
index 3a53a91496..34d035dea3 100644
--- a/plugins/ruflo-console/hooks/controller.ts
+++ b/plugins/ruflo-console/hooks/controller.ts
@@ -5,7 +5,7 @@
*/
import { actionsOf } from './bindings'
import type { Catalog } from './data/catalog'
-import { PROBES, type ProbeResult } from './data/cli'
+import { PROBES, probeArgv, type ProbeResult } from './data/cli'
import { diffEvents, record } from './data/events'
import { plain } from './data/parse'
import { readSnapshot } from './data/snapshot'
@@ -196,7 +196,7 @@ export function createController(state: State, host: Host): Controller {
lastAttempt.set(probe.id, Date.now())
try {
- const result = await host.run([...CLI_PREFIXES[state.options.cli], ...probe.args], probe.timeoutMs)
+ const result = await host.run(probeArgv(probe, state.options.cli), probe.timeoutMs)
const value = result.exitCode === 0 ? (probe.parse(result.stdout) as unknown) : null
state.probes.set(
diff --git a/plugins/ruflo-console/hooks/cost.ts b/plugins/ruflo-console/hooks/cost.ts
new file mode 100644
index 0000000000..ff762311d7
--- /dev/null
+++ b/plugins/ruflo-console/hooks/cost.ts
@@ -0,0 +1,70 @@
+import type { ActionSpec } from './actions'
+import { modelStatsProbe, probeArgv } from './data/cli'
+import type { Sample, State } from './state'
+import { live } from './views/common'
+
+export const BUDGET_PRESETS = [1, 5, 10, 25] as const
+export const BUDGET_HELP = 'set costBudgetUsd in /config → ruflo-mods; restart/reload may be needed'
+export const BUDGET_ARGV = ['claude', 'plugin', 'configure', 'ruflo-mods@ruflo', '--values-stdin'] as const
+
+/** Decimal dollars only: no flags, exponents, currency marks or non-finite values. */
+export function budgetAmount(text: string): number | null {
+ const value = text.trim()
+ const amount = Number(value)
+
+ return /^(?:\d+(?:\.\d+)?|\.\d+)$/.test(value) && Number.isFinite(amount) && amount >= 0.01 && amount <= 10_000 ? amount : null
+}
+
+/** The ruflo-mods ladder: OK below 50%, then INFO, WARNING, CRITICAL and HARD_STOP. */
+export function ladderDollars(limit: number | undefined): { level: string; percent: number; usd: number | null }[] {
+ return [['INFO', 50], ['WARNING', 75], ['CRITICAL', 90], ['HARD_STOP', 100]].map(([level, percent]) => ({
+ level: String(level), percent: Number(percent), usd: limit !== undefined && Number.isFinite(limit) && limit > 0 ? limit * Number(percent) / 100 : null,
+ }))
+}
+
+export type Projection = { usdPerMinute: number; minutes: number | null }
+
+/** A budget and the last 20 spend observations, spanning a minute without resets or duplicate times. */
+export function projectSpend(samples: readonly Sample[], limit?: number, used?: number): Projection | null {
+ const window = samples.slice(-20)
+ const first = window[0]
+ const last = window.at(-1)
+
+ if (limit === undefined || !Number.isFinite(limit) || limit <= 0 || window.length < 3 || first === undefined || last === undefined || last.atMs - first.atMs < 60_000) return null
+ if (window.some((sample, i) => {
+ const previous = window[i - 1]
+
+ return !Number.isFinite(sample.atMs) || !Number.isFinite(sample.value) || sample.value < 0 || (previous !== undefined && (sample.atMs <= previous.atMs || sample.value < previous.value))
+ })) return null
+
+ const usdPerMinute = (last.value - first.value) / ((last.atMs - first.atMs) / 60_000)
+ const spend = used ?? last.value
+ if (!Number.isFinite(spend) || spend < 0) return null
+
+ return { usdPerMinute, minutes: spend >= limit ? 0 : usdPerMinute > 0 ? (limit - spend) / usdPerMinute : null }
+}
+
+/** A supported CLI is required before a budget button can ask to change anything. */
+export const canSetBudget = (state: State): boolean => live<boolean>(state.probes.get('budget-config')) === true
+
+export const budgetWhy = (state: State, value: string): string => budgetAmount(value) === null ? 'budget must be a number from 0.01 to 10000 USD' : `budget setter unavailable${state.probes.has('budget-config') ? '' : ' — open Cost to check CLI support'}; ${BUDGET_HELP}`
+
+/** Only this option is sent to Claude Code; its configure command preserves all omitted options. */
+export function setBudget(state: State, value: string): ActionSpec | null {
+ const amount = budgetAmount(value)
+
+ if (amount === null || !canSetBudget(state)) return null
+
+ const stdin = JSON.stringify({ costBudgetUsd: String(amount) })
+
+ return {
+ label: `set ruflo-mods@ruflo costBudgetUsd to $${amount}`,
+ args: [], argv: BUDGET_ARGV, stdin,
+ shows: `${BUDGET_ARGV.join(' ')} · stdin ${stdin}`,
+ expect: `costBudgetUsd = ${amount}; restart/reload may be needed before the live budget changes`,
+ note: 'Changes the ruflo-mods user plugin option only; restart/reload may be needed. Does not change the AI terminal’s $1 per-turn cap.',
+ }
+}
+
+/** Reads local router counts at once; the JSON contains no billing totals. */
+export const inspectModels = (state: State): ActionSpec => ({ label: 'model routing counts (dollars and tokens n/a)', args: modelStatsProbe.args, argv: probeArgv(modelStatsProbe, state.options.cli), isReadOnly: true, expect: 'local routing counts' })
diff --git a/plugins/ruflo-console/hooks/data/cli.ts b/plugins/ruflo-console/hooks/data/cli.ts
index cede4dd459..5a7df49edc 100644
--- a/plugins/ruflo-console/hooks/data/cli.ts
+++ b/plugins/ruflo-console/hooks/data/cli.ts
@@ -6,13 +6,16 @@
*/
import { idOf, msOf, numberOf, plain, recordOf, stringOf, valuesOf } from './parse'
-import type { ViewId } from '../state'
+import { CLI_PREFIXES, type CliChoice, type ViewId } from '../state'
export type { ViewId }
export type Probe<T> = {
id: string
args: readonly string[]
+ /** A local executable for a capability check, or an offline-only ruflo read. */
+ argv?: readonly string[]
+ isOffline?: boolean
/** The views that draw it: a probe runs only while one of them is in front (the overview's run with the bar too). */
views: readonly ViewId[]
everyMs: number
@@ -45,6 +48,37 @@ export function jsonAfter(stdout: string): unknown {
const objectOf = (stdout: string) => recordOf(jsonAfter(stdout))
const exec = (tool: string, params: Record<string, unknown>) => ['mcp', 'exec', '-t', tool, '-p', JSON.stringify(params)] as const
+/** Offline probes never let the download-enabled CLI choice reach the registry. */
+export const probeArgv = (probe: Pick<Probe<unknown>, 'args' | 'argv' | 'isOffline'>, cli: CliChoice): readonly string[] => probe.argv ?? [...CLI_PREFIXES[probe.isOffline && cli === 'npx' ? 'npx-offline' : cli], ...probe.args]
+
+/** Help only: older Claude builds must not get a guessed configuration command. */
+export const budgetConfigProbe: Probe<boolean> = {
+ id: 'budget-config', args: [], argv: ['claude', 'plugin', 'configure', '--help'], views: ['cost'], everyMs: 600_000, timeoutMs: 10_000,
+ parse: stdout => /Usage: claude plugin configure/.test(stdout) && /--values-stdin/.test(stdout),
+}
+
+export type ModelStats = { isAvailable: boolean; total?: number; models: { name: string; count: number }[] }
+
+/** Persisted router decisions, not billing: the CLI records neither model dollars nor tokens here. */
+export const modelStatsProbe: Probe<ModelStats> = {
+ id: 'model-stats', args: ['hooks', 'model-stats', '--format', 'json'], views: ['cost'], everyMs: 30_000, timeoutMs: 30_000, isOffline: true,
+ parse: stdout => {
+ const value = objectOf(stdout)
+
+ if (value === null || typeof value.available !== 'boolean') return null
+
+ const countOf = (n: unknown) => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0 ? n : undefined
+ const total = countOf(value.totalDecisions)
+ const models = Object.entries(recordOf(value.modelDistribution) ?? {}).slice(0, 12).flatMap(([name, n]) => {
+ const count = countOf(n)
+
+ return count === undefined ? [] : [{ name: plain(name, 40), count }]
+ })
+
+ return { isAvailable: value.available, ...(total !== undefined && { total }), models }
+ },
+}
+
export const versionProbe: Probe<string> = {
id: 'version',
args: ['--version'],
@@ -59,7 +93,7 @@ export type MemoryStats = { backend: string; total?: number; vectors?: number; s
export const memoryProbe: Probe<MemoryStats> = {
id: 'memory',
args: ['memory', 'stats', '--format', 'json'],
- views: ['overview', 'memory', 'cost'],
+ views: ['overview', 'memory'],
everyMs: 30_000,
timeoutMs: 30_000,
parse: stdout => {
@@ -421,7 +455,7 @@ export const registryProbe: Probe<Registry> = {
},
}
-export const PROBES = [versionProbe, memoryProbe, namespacesProbe, scoreProbe, flywheelProbe, auditProbe, intelligenceProbe, peersProbe, channelsProbe, rosterProbe, registryProbe] as const
+export const PROBES = [versionProbe, memoryProbe, namespacesProbe, scoreProbe, flywheelProbe, auditProbe, intelligenceProbe, peersProbe, channelsProbe, rosterProbe, registryProbe, budgetConfigProbe, modelStatsProbe] as const
export type ProbeId = (typeof PROBES)[number]['id']
diff --git a/plugins/ruflo-console/hooks/dispatch.ts b/plugins/ruflo-console/hooks/dispatch.ts
index 52f917f9b2..ab82a4c5b8 100644
--- a/plugins/ruflo-console/hooks/dispatch.ts
+++ b/plugins/ruflo-console/hooks/dispatch.ts
@@ -105,6 +105,8 @@ export async function dispatch(control: Controller, state: State, args: string,
return open(control, state, 'palette')
case 'run': {
+ // A headless budget ask checks the installed CLI's help before building a setter spec.
+ if (intent.paletteId === 'cost-budget' || intent.paletteId.startsWith('cost-budget-')) await dumpOf(control, state, 'cost')
const askedAtMs = Date.now()
const isRun = control.actions.run(intent.paletteId, intent.text)
@@ -114,7 +116,13 @@ export async function dispatch(control: Controller, state: State, args: string,
// A lab read answers with what it printed, so `/ruflo run mh-genome` works headless.
if (state.pending === null) await control.runner.settled()
- return { text: state.pending !== null ? `Asked: ${state.pending.label}. Confirm with /ruflo yes (or y in the pane), cancel with /ruflo no.` : (labAnswer(state, intent.paletteId, askedAtMs) ?? (state.outcome !== null && !state.outcome.ok ? `${state.outcome.label}: ${state.outcome.detail}` : (state.outcome?.label ?? 'done'))) }
+ if (state.pending !== null) {
+ const pending = state.pending
+
+ return { text: [`Asked: ${pending.label}. Confirm with /ruflo yes (or y in the pane), cancel with /ruflo no.`, ...(pending.shows === undefined ? [] : [`runs: ${pending.shows}`, pending.note ?? ''])].filter(Boolean).join('\n') }
+ }
+
+ return { text: labAnswer(state, intent.paletteId, askedAtMs) ?? (state.outcome !== null && !state.outcome.ok ? `${state.outcome.label}: ${state.outcome.detail}` : (state.outcome?.label ?? 'done')) }
}
case 'confirm':
if (state.pending === null) return { text: 'Nothing is waiting for a confirm.' }
diff --git a/plugins/ruflo-console/hooks/harness.ts b/plugins/ruflo-console/hooks/harness.ts
index fa47a745bc..ae2da2cd6a 100644
--- a/plugins/ruflo-console/hooks/harness.ts
+++ b/plugins/ruflo-console/hooks/harness.ts
@@ -211,7 +211,10 @@ async function runAgent(state: State, host: Host, agent: AgentId, prompt: string
},
done: ({ costUsd, tokens, isError, message }) => {
if (agent === 'codex' || agent === 'claude') term.turns[agent] += 1
- if (costUsd !== undefined) term.costUsd += costUsd
+ if (costUsd !== undefined) {
+ term.costUsd += costUsd
+ term.costReports += 1
+ }
ended = isError === true ? `✗ ${message ?? 'failed'}` : `✓ ${secs()}${costUsd !== undefined ? ` · $${costUsd.toFixed(3)}` : ''}${tokens !== undefined ? ` · ${tokens.toLocaleString('en-US')} tokens` : ''}`
},
}
diff --git a/plugins/ruflo-console/hooks/host.ts b/plugins/ruflo-console/hooks/host.ts
index 493fa6441c..d6e88dc75a 100644
--- a/plugins/ruflo-console/hooks/host.ts
+++ b/plugins/ruflo-console/hooks/host.ts
@@ -26,7 +26,7 @@ export type Host = {
closePane: (id: string) => Promise<void>
panes: () => Promise<readonly { id: string; isShown: boolean; isFocused: boolean }[]>
registerCommand: (spec: CommandSpec) => Promise<unknown>
- run: (argv: readonly string[], timeoutMs: number) => Promise<ProcessRunResult>
+ run: (argv: readonly string[], timeoutMs: number, stdin?: string) => Promise<ProcessRunResult>
/** Starts a command and streams what it writes; `input` goes to its stdin, which is then closed. */
spawn: (argv: readonly string[], input?: string) => HookStream<ProcessSpawnChunk, ProcessSpawnResult>
usage: () => Promise<{ costUsd?: number; contextPercent?: number }>
diff --git a/plugins/ruflo-console/hooks/palette.ts b/plugins/ruflo-console/hooks/palette.ts
index 320a67f328..2fe127c0e4 100644
--- a/plugins/ruflo-console/hooks/palette.ts
+++ b/plugins/ruflo-console/hooks/palette.ts
@@ -4,6 +4,7 @@
* argument from the query after their keyword: `route fix the login bug`.
*/
import { HIVE_ROLES, pickedProposal } from './data/hive'
+import { BUDGET_PRESETS, budgetWhy, inspectModels, setBudget } from './cost'
import { hiveBroadcast, hivePropose, hiveSpawn, hiveVote } from './hive'
import { claimTask, handoffClaim, releaseClaim, stealClaim, type ActionSpec } from './actions'
import { LAB, labSpec, labWhy } from './mh-lab'
@@ -15,7 +16,7 @@ export type PaletteRun =
| { kind: 'spec'; spec: ActionSpec | null; why: string }
| { kind: 'view'; view: ViewId }
| { kind: 'drill'; agentId: string }
- | { kind: 'text'; keyword: string; make: (text: string) => ActionSpec | null }
+ | { kind: 'text'; keyword: string; make: (text: string) => ActionSpec | null; why?: (text: string) => string }
| { kind: 'command'; name: 'refresh' | 'help' | 'close' }
export type PaletteEntry = { id: string; label: string; group: string; run: PaletteRun }
@@ -49,7 +50,7 @@ export function fuzzy(query: string, label: string): number | null {
return whole < 0 ? score : score + 5 + (whole === 0 || text[whole - 1] === ' ' ? 3 : 0)
}
-const TEXT_KEYWORDS = ['route', 'store', 'search', 'propose', 'broadcast'] as const
+const TEXT_KEYWORDS = ['route', 'store', 'search', 'propose', 'broadcast', 'cost-budget'] as const
/** Every entry for the state as it is, before filtering. */
export function paletteEntries(state: State, nowMs: number): PaletteEntry[] {
@@ -57,6 +58,10 @@ export function paletteEntries(state: State, nowMs: number): PaletteEntry[] {
const out: PaletteEntry[] = []
const add = (id: string, group: string, label: string, run: PaletteRun) => out.push({ id, group, label, run })
+ for (const amount of BUDGET_PRESETS) add(`cost-budget-${amount}`, 'cost', `set ruflo-mods budget to $${amount}`, { kind: 'spec', spec: setBudget(state, String(amount)), why: budgetWhy(state, String(amount)) })
+ add('cost-budget', 'cost', 'cost-budget <amount>: set ruflo-mods costBudgetUsd (0.01–10000)', { kind: 'text', keyword: 'cost-budget', make: text => setBudget(state, text), why: text => budgetWhy(state, text) })
+ add('cost-model-stats', 'cost', 'inspect local model routing counts (spend n/a)', { kind: 'spec', spec: inspectModels(state), why: '' })
+
if (agent !== null) {
const name = agent.name ?? agent.type
diff --git a/plugins/ruflo-console/hooks/register.ts b/plugins/ruflo-console/hooks/register.ts
index 2581b49b40..a53b5d5890 100644
--- a/plugins/ruflo-console/hooks/register.ts
+++ b/plugins/ruflo-console/hooks/register.ts
@@ -43,7 +43,7 @@ function hostOf($: EngineInterface, cwd: string): Host {
closePane: async id => $.ui.close({ id }),
panes: async () => $.ui.panes(),
registerCommand: async spec => $.command.register(spec),
- run: async (argv, timeoutMs) => $.process.run(argv, { cwd, timeoutMs }),
+ run: async (argv, timeoutMs, stdin) => $.process.run(argv, { cwd, timeoutMs, ...(stdin !== undefined && { stdin }) }),
spawn: (argv, input) => $.process.spawn({ argv, cwd, ...(input !== undefined && { input }) }),
usage: async () => {
const usage = await $.session.usage()
diff --git a/plugins/ruflo-console/hooks/runner.ts b/plugins/ruflo-console/hooks/runner.ts
index 6a61fe2313..60ed2df8bf 100644
--- a/plugins/ruflo-console/hooks/runner.ts
+++ b/plugins/ruflo-console/hooks/runner.ts
@@ -53,7 +53,7 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
host.invalidate()
try {
- const result = await host.run([...CLI_PREFIXES[state.options.cli], ...spec.args], spec.timeoutMs ?? 90_000)
+ const result = await host.run(spec.argv ?? [...CLI_PREFIXES[state.options.cli], ...spec.args], spec.timeoutMs ?? 90_000, spec.stdin)
const answer = /"success"\s*:\s*(true|false)/.exec(result.stdout)?.[1]
const error = /"error"\s*:\s*"([^"]{0,160})"/.exec(result.stdout)?.[1] ?? /\[ERROR\]\s*(.{0,160})/.exec(result.stdout)?.[1]
const ok = result.exitCode === 0 && answer !== 'false' && error === undefined
@@ -78,7 +78,7 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
label: spec.label,
ok: ok && verified !== 'no',
verified,
- detail: ok ? `ruflo answered ok; expected ${spec.expect}` : plain(error ?? result.stderr, 160) || `exit ${result.exitCode}`,
+ detail: ok ? `${spec.argv === undefined ? 'ruflo' : 'the command'} answered ok; expected ${spec.expect}` : plain(error ?? result.stderr, 160) || `exit ${result.exitCode}`,
atMs: Date.now(),
}
} catch (error) {
@@ -97,6 +97,8 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
state.palette.isOpen = false
if (spec === null) {
+ pendingSpec = null
+ state.pending = null
say('nothing to do', false, why)
return
@@ -145,7 +147,7 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
ask(entry.run.spec, entry.run.why)
break
case 'text':
- ask(entry.run.make(text), `type "${entry.run.keyword} <text>"; text may not start with -`)
+ ask(entry.run.make(text), entry.run.why?.(text) ?? `type "${entry.run.keyword} <text>"; text may not start with -`)
break
case 'view':
deps.setView(entry.run.view)
diff --git a/plugins/ruflo-console/hooks/state.ts b/plugins/ruflo-console/hooks/state.ts
index 4270e97672..5763ac0e09 100644
--- a/plugins/ruflo-console/hooks/state.ts
+++ b/plugins/ruflo-console/hooks/state.ts
@@ -33,7 +33,7 @@ export const VIEWS: readonly { id: ViewId; key: string; label: string; short: st
{ id: 'learning', key: '6', label: 'Learning', short: 'Lrn', icon: '🧠', blurb: 'router picks and outcomes, and the RETRIEVE → JUDGE → DISTILL → CONSOLIDATE pipeline', rows: 30 },
{ id: 'metaharness', key: '7', label: 'MetaHarness', short: 'MH', icon: '🔬', blurb: 'harness readiness, the flywheel, the audit trend, and a lab that runs every MetaHarness verb', rows: 40 },
{ id: 'memory', key: '8', label: 'Memory', short: 'Mem', icon: '💾', blurb: 'AgentDB entries by namespace: what the swarm has stored', rows: 22 },
- { id: 'cost', key: '9', label: 'Cost', short: 'Cst', icon: '💰', blurb: 'this session spend against the budget, and how fast it is burning', rows: 20 },
+ { id: 'cost', key: '9', label: 'Cost', short: 'Cst', icon: '💰', blurb: 'set a budget, see where spend is reported, and project its burn', rows: 40 },
{ id: 'timeline', key: 'g', label: 'Timeline', short: 'Gnt', icon: '🕒', blurb: 'each agent busy or idle over the last minutes, beside Claude Code tool calls', rows: 24 },
{ id: 'approvals', key: 'q', label: 'Approvals', short: 'Apv', icon: '✅', blurb: 'decisions waiting for a person: votes, stealable claims, refused mods, budget', rows: 24 },
{ id: 'events', key: 'e', label: 'Events', short: 'Evt', icon: '📡', blurb: 'every swarm, claim, memory and mod event as it happens (f filters them)', rows: 26 },
@@ -165,6 +165,8 @@ export type State = {
probes: Map<string, ProbeResult>
ruflo: { snapshot: RufloSnapshot | null; route: RufloRoute | null; error: string | null }
usage: { costUsd?: number; contextPercent?: number } | null
+ /** The custom budget field, kept across redraws. */
+ costBudgetDraft: string
rufloTools: { tools: number; servers: string[] } | null
mods: ModSeen[]
denied: Denied[]
@@ -209,6 +211,8 @@ export type State = {
/** Turns and spend this session, as the agents reported them. */
turns: { codex: number; claude: number }
costUsd: number
+ /** How many terminal results actually reported dollars, including measured zero. */
+ costReports: number
/** Screen rows scrolled up from the newest (0 follows the tail), and how many lines arrived while scrolled up. */
scroll: number
unseen: number
@@ -237,6 +241,7 @@ export function newState(raw: PluginOptions | undefined): State {
probes: new Map(),
ruflo: { snapshot: null, route: null, error: null },
usage: null,
+ costBudgetDraft: '',
rufloTools: null,
mods: [],
denied: [],
@@ -259,7 +264,7 @@ export function newState(raw: PluginOptions | undefined): State {
lab: { result: null, running: null },
isRefreshing: false,
barDrawnAtMs: 0,
- terminal: { harness: 'codex', draft: '', lines: [], runs: new Map(), sessions: {}, isLive: { codex: false, claude: false }, turns: { codex: 0, claude: 0 }, costUsd: 0, scroll: 0, unseen: 0, asked: null },
+ terminal: { harness: 'codex', draft: '', lines: [], runs: new Map(), sessions: {}, isLive: { codex: false, claude: false }, turns: { codex: 0, claude: 0 }, costUsd: 0, costReports: 0, scroll: 0, unseen: 0, asked: null },
skills: emptySkills(),
timers: new Map(),
stats: { renders: [], refreshes: [], frames: [] },
diff --git a/plugins/ruflo-console/hooks/views/common.ts b/plugins/ruflo-console/hooks/views/common.ts
index 482d9f5b70..aee9a242f2 100644
--- a/plugins/ruflo-console/hooks/views/common.ts
+++ b/plugins/ruflo-console/hooks/views/common.ts
@@ -36,6 +36,7 @@ export type Actions = {
paletteRun: (id: string) => void
paletteSubmit: () => void
run: (id: string, text?: string) => boolean
+ costBudgetDraft: (text: string) => void
/** Cycles the events view's filter. */
filter: () => void
/** The terminal view: pick a harness, follow the field, ask to run its text, stop the run, clear the scrollback. */
diff --git a/plugins/ruflo-console/hooks/views/cost.ts b/plugins/ruflo-console/hooks/views/cost.ts
index 0424abe55a..1a99b4def8 100644
--- a/plugins/ruflo-console/hooks/views/cost.ts
+++ b/plugins/ruflo-console/hooks/views/cost.ts
@@ -1,10 +1,13 @@
import type { RenderElement } from 'claude-code'
-import { col, kv, pct, picture, rule, text, THEME, type Ctx } from './common'
+import { BUDGET_HELP, BUDGET_PRESETS, canSetBudget, ladderDollars, projectSpend } from '../cost'
+import type { ModelStats } from '../data/cli'
+import { button, col, kv, live, pct, picture, row, rule, sourceLine, text, THEME, type Ctx } from './common'
const LADDER = [0.5, 0.75, 0.9, 1] as const
+const dollars = (value: number | undefined | null): string => value === undefined || value === null || !Number.isFinite(value) || value < 0 ? 'n/a' : `$${value.toFixed(3)}`
-/** The budget ladder as a text bar: marks at 50/75/90/100% of the limit, the spend filled to where it stands. */
+/** The budget ladder as a text bar, with marks at 50/75/90/100% of the limit. */
export function ladder(usd: number, limit: number, width: number): string {
const cells = Math.max(10, width)
const at = Math.min(cells, Math.round((usd / limit) * cells))
@@ -13,30 +16,68 @@ export function ladder(usd: number, limit: number, width: number): string {
return Array.from({ length: cells }, (_, i) => (marks.has(i) ? '│' : i < at ? '█' : '·')).join('')
}
-/** This session's spend from Claude Code, against the ruflo-mods budget ladder where one is set, and its burn since load. */
+/** Presets and custom dollars share the same confirm-gated palette entry. */
+function budgetRows(ctx: Ctx): RenderElement[] {
+ const { state } = ctx
+ const rows = [rule(ctx, 'Set a budget', 'ruflo-mods · asks first')]
+
+ rows.push(row(ctx, BUDGET_PRESETS.map(amount => button(ctx, `cost-budget-${amount}`, `$${amount}`, () => void ctx.act.run(`cost-budget-${amount}`)))))
+ if (ctx.kit.Input !== undefined) rows.push(ctx.kit.Input({ key: 'cost-budget', label: 'custom USD', value: state.costBudgetDraft, placeholder: '0.01–10000', onInput: ctx.act.costBudgetDraft, onSubmit: value => void ctx.act.run('cost-budget', value), submitLabel: 'ask' }))
+ rows.push(button(ctx, 'cost-budget-apply', 'Set custom budget', () => void ctx.act.run('cost-budget', state.costBudgetDraft)))
+ rows.push(text(ctx, canSetBudget(state) ? ' Changes costBudgetUsd only; restart/reload may be needed. AI terminal cap stays $1 per Claude turn.' : ` Budget setter unavailable: ${BUDGET_HELP}`, { dimColor: true }))
+
+ return rows
+}
+
+/** Sources have different scopes and coverage, so they are never added into a grand total. */
+function breakdownRows(ctx: Ctx): RenderElement[] {
+ const { state } = ctx
+ const budget = state.ruflo.snapshot?.budget
+ const used = budget?.usd ?? state.usage?.costUsd
+ const term = state.terminal
+ const stats = live<ModelStats>(state.probes.get('model-stats'))
+ const rows = [rule(ctx, 'Where it goes', 'reported USD · sources are not additive')]
+
+ rows.push(kv(ctx, 'Claude Code', `${dollars(state.usage?.costUsd)} · this session`))
+ rows.push(kv(ctx, 'AI terminal', `${dollars(term.costReports > 0 ? term.costUsd : undefined)} · reported subtotal this session (${term.costReports} cost reports)`))
+ rows.push(kv(ctx, 'terminal turns', `codex ${term.turns.codex} · claude ${term.turns.claude} · per-agent dollars n/a`))
+ rows.push(kv(ctx, 'ruflo models', `n/a USD · tokens n/a · ${stats?.isAvailable === true ? `${stats.total ?? 'n/a'} decisions` : 'router unavailable'}`))
+ for (const model of stats?.isAvailable === true ? stats.models : []) rows.push(kv(ctx, model.name, `${model.count} routes · spend n/a · tokens n/a`))
+ rows.push(text(ctx, ' Router counts are persisted across sessions, not bills. Missing cost reports are not zero.', { dimColor: true }))
+ rows.push(text(ctx, ` ${sourceLine(state.probes.get('model-stats'), ctx.nowMs, 'model-stats').text}`, { dimColor: true }))
+ rows.push(kv(ctx, 'headroom', budget === undefined || used === undefined ? 'n/a' : `${dollars(Math.max(0, budget.limit - used))} · ruflo-mods budget${used > budget.limit ? ` · over by ${dollars(used - budget.limit)}` : ''}`))
+ rows.push(row(ctx, [button(ctx, 'cost-model-stats', 'Inspect model stats', () => void ctx.act.run('cost-model-stats')), button(ctx, 'cost-refresh', 'Refresh cost', ctx.act.refresh)]))
+
+ return rows
+}
+
+/** Session spend, budget controls, source coverage and a projection from actual timed observations. */
export function costView(ctx: Ctx): RenderElement {
const { state } = ctx
const budget = state.ruflo.snapshot?.budget
const spend = state.usage?.costUsd
- const rows: RenderElement[] = [rule(ctx, 'Cost', 'this session')]
+ const used = budget?.usd ?? spend
+ const projection = projectSpend(state.history.spend, budget?.limit, used)
+ const rows: RenderElement[] = [rule(ctx, 'Cost', 'this session'), ...budgetRows(ctx)]
- rows.push(picture(ctx, 'gauge', budget === undefined ? 'no budget set' : `$${(budget.usd ?? spend ?? 0).toFixed(2)} of $${budget.limit.toFixed(2)}`))
- rows.push(kv(ctx, 'session spend', spend === undefined ? 'n/a — Claude Code did not report a cost' : `$${spend.toFixed(3)}`))
+ rows.push(picture(ctx, 'gauge', budget === undefined ? 'no budget set' : `${dollars(used)} of $${budget.limit.toFixed(2)}`))
rows.push(kv(ctx, 'context', state.usage?.contextPercent === undefined ? 'n/a' : `${Math.round(state.usage.contextPercent)}% of the window`))
-
if (budget === undefined) {
- rows.push(kv(ctx, 'budget', state.ruflo.snapshot === null ? 'n/a — ruflo-mods not seated' : 'none set (ruflo-mods costBudgetUsd = 0)'))
+ rows.push(kv(ctx, 'budget', state.ruflo.snapshot === null ? 'n/a — ruflo-mods not seated' : 'none set · choose a preset or custom amount'))
} else {
- const used = budget.usd ?? spend
const color = budget.level === 'OK' || budget.level === 'INFO' ? THEME.ok : budget.level === 'WARNING' ? THEME.warn : THEME.bad
rows.push(kv(ctx, 'budget', `${budget.level} · ${used === undefined ? 'n/a' : `$${used.toFixed(2)}`} of $${budget.limit.toFixed(2)} (${used === undefined ? 'n/a' : pct(used / budget.limit)})`, color))
if (used !== undefined) rows.push(text(ctx, `${' '.repeat(17)}${ladder(used, budget.limit, Math.min(40, ctx.columns - 20))} 50·75·90·100%`, { color }))
}
-
+ rows.push(...breakdownRows(ctx))
+ rows.push(rule(ctx, 'Alert thresholds', 'OK below 50%'))
+ for (const rung of ladderDollars(budget?.limit)) rows.push(kv(ctx, rung.level, `${rung.percent}% · ${rung.usd === null ? 'n/a' : `$${rung.usd.toFixed(2)}`}`))
+ rows.push(text(ctx, ' HARD_STOP blocks new agents only when ruflo-mods costHardStop is enabled.', { dimColor: true }))
rows.push(rule(ctx, 'Burn', `${state.history.spend.length} samples since the console loaded`))
rows.push(picture(ctx, 'burn', `spend since load: ${state.history.spend.map(sample => `$${sample.value.toFixed(2)}`).join(' ') || 'n/a'}`))
- rows.push(text(ctx, 'gauge: needle at spend / limit, arc green to 50%, amber to 90%, red past · burn: each change of spend Claude Code reported', { dimColor: true }))
+ rows.push(kv(ctx, 'burn rate', projection === null ? 'n/a — need a budget and 3 samples spanning at least 60 s' : `$${projection.usdPerMinute.toFixed(4)}/min · last 20 observations at most`))
+ rows.push(text(ctx, projection?.minutes === 0 ? ' Budget already reached.' : projection?.minutes === null || projection === null ? ' Budget reached in: n/a — needs a budget and positive measured burn.' : ` At this rate the budget is reached in ~${Math.ceil(projection.minutes)} min.`, { dimColor: true }))
return col(ctx, rows, 'cost')
}
diff --git a/plugins/ruflo-console/tests/cost.spec.ts b/plugins/ruflo-console/tests/cost.spec.ts
new file mode 100644
index 0000000000..6e06663811
--- /dev/null
+++ b/plugins/ruflo-console/tests/cost.spec.ts
@@ -0,0 +1,110 @@
+import { describe, expect, it } from 'vitest'
+
+import { BUDGET_ARGV, budgetAmount, canSetBudget, ladderDollars, projectSpend, setBudget } from '../hooks/cost'
+import { budgetConfigProbe, modelStatsProbe, probeArgv } from '../hooks/data/cli'
+import { filterPalette, paletteEntries } from '../hooks/palette'
+import { newState } from '../hooks/state'
+import type { Actions } from '../hooks/views/common'
+import { viewText } from '../hooks/views/pane'
+import { CONFIGURE_HELP, MODEL_STATS } from './fixtures/cost'
+
+const samples = [{ atMs: 0, value: 1 }, { atMs: 30_000, value: 1.5 }, { atMs: 60_000, value: 2 }]
+
+describe('cost projection', () => {
+ it('measures dollars per minute and remaining budget from elapsed time', () => {
+ expect(projectSpend(samples, 5)).toEqual({ usdPerMinute: 1, minutes: 3 })
+ expect(projectSpend(samples, 5, 4)).toEqual({ usdPerMinute: 1, minutes: 1 })
+ expect(projectSpend(samples.map(s => ({ ...s, atMs: s.atMs * 2 })), 5)).toEqual({ usdPerMinute: 0.5, minutes: 6 })
+ })
+
+ it('needs three samples spanning a minute and rejects resets or malformed observations', () => {
+ expect(projectSpend(samples.slice(1), 5)).toBeNull()
+ expect(projectSpend(samples.map(s => ({ ...s, atMs: s.atMs / 2 })), 5)).toBeNull()
+ for (const bad of [{ atMs: 30_000, value: 2 }, { atMs: 60_000, value: 0 }, { atMs: NaN, value: 2 }, { atMs: 60_000, value: Infinity }]) {
+ expect(projectSpend([...samples.slice(0, 2), bad], 5)).toBeNull()
+ }
+ })
+
+ it('has no arrival time without a budget or positive burn, and clamps reached budgets to zero', () => {
+ for (const limit of [undefined, 0, -1, NaN, Infinity]) expect(projectSpend(samples, limit)).toBeNull()
+ expect(projectSpend(samples.map(s => ({ ...s, value: 1 })), 5)).toEqual({ usdPerMinute: 0, minutes: null })
+ expect(projectSpend(samples, 2)?.minutes).toBe(0)
+ expect(projectSpend(samples, 1)?.minutes).toBe(0)
+ })
+
+ it('uses only the newest 20 observations', () => {
+ const recent = Array.from({ length: 20 }, (_, i) => ({ atMs: i * 60_000, value: i }))
+
+ expect(projectSpend([{ atMs: -60_000, value: 200 }, ...recent], 25)).toEqual({ usdPerMinute: 1, minutes: 6 })
+ })
+})
+
+describe('budget dollars and actions', () => {
+ it('shows the exact ruflo-mods threshold dollars, with OK below INFO', () => {
+ expect(ladderDollars(10)).toEqual([{ level: 'INFO', percent: 50, usd: 5 }, { level: 'WARNING', percent: 75, usd: 7.5 }, { level: 'CRITICAL', percent: 90, usd: 9 }, { level: 'HARD_STOP', percent: 100, usd: 10 }])
+ for (const limit of [undefined, 0, -1, NaN]) expect(ladderDollars(limit).every(rung => rung.usd === null)).toBe(true)
+ })
+
+ it('validates the inclusive range without accepting flags or shell text', () => {
+ for (const value of ['0.01', '.5', ' 5 ', '10000', '25.125']) expect(budgetAmount(value)).toBe(Number(value))
+ for (const value of ['', '0', '0.009', '10000.01', '-1', 'NaN', 'Infinity', '1e2', '0x10', '$5', '--help', '5; touch /tmp/x', '5\n6']) expect(budgetAmount(value)).toBeNull()
+ })
+
+ it('requires confirmed support, sends only one option on stdin, and shows the exact change', () => {
+ const state = newState({})
+
+ expect(setBudget(state, '5')).toBeNull()
+ state.probes.set('budget-config', { value: true, okAtMs: 1, error: null, errorAtMs: null, isRunning: false })
+ expect(setBudget(state, '5')).toMatchObject({ argv: BUDGET_ARGV, stdin: '{"costBudgetUsd":"5"}' })
+ expect(setBudget(state, '5')?.shows).toContain('stdin {"costBudgetUsd":"5"}')
+ expect(setBudget(state, '5')?.isReadOnly).not.toBe(true)
+ expect(setBudget(state, '--help')).toBeNull()
+ state.probes.set('budget-config', { value: true, okAtMs: 1, error: 'refused', errorAtMs: 2, isRunning: false })
+ expect(canSetBudget(state)).toBe(false)
+ })
+
+ it('uses the exact keyword as the custom palette id', () => {
+ const entries = filterPalette(paletteEntries(newState({}), 0), 'cost-budget 12.5', 'all')
+
+ expect(entries.map(entry => entry.id)).toEqual(['cost-budget'])
+ })
+})
+
+describe('local cost probes', () => {
+ it('distinguishes absent terminal cost from measured zero and suppresses stale model counts', () => {
+ const state = newState({})
+ const shown = () => viewText({ state, nowMs: 3, columns: 100, act: {} as Actions }, 'cost')
+
+ state.terminal.turns.codex = 2
+ expect(shown()).toContain('n/a · reported subtotal this session (0 cost reports)')
+ expect(shown()).toContain('codex 2 · claude 0')
+ state.terminal.costReports = 1
+ expect(shown()).toContain('$0.000 · reported subtotal this session (1 cost reports)')
+ state.terminal.costUsd = 0.42
+ expect(shown()).toContain('$0.420 · reported subtotal')
+ state.probes.set('model-stats', { value: modelStatsProbe.parse(MODEL_STATS), okAtMs: 1, error: 'offline cache missing', errorAtMs: 2, isRunning: false })
+ expect(shown()).not.toContain('8 decisions')
+ expect(shown()).toContain('offline cache missing')
+ })
+
+ it('gates both probes to Cost and forces offline even with the download-enabled choice', () => {
+ expect(modelStatsProbe.views).toEqual(['cost'])
+ expect(budgetConfigProbe.views).toEqual(['cost'])
+ expect(probeArgv(modelStatsProbe, 'npx')).toEqual(['npx', '--offline', '-y', '@claude-flow/cli@latest', 'hooks', 'model-stats', '--format', 'json'])
+ expect(probeArgv(modelStatsProbe, 'ruflo')).toEqual(['ruflo', 'hooks', 'model-stats', '--format', 'json'])
+ expect(probeArgv(budgetConfigProbe, 'npx')).toEqual(['claude', 'plugin', 'configure', '--help'])
+ })
+
+ it('recognizes configure help and does not mistake generic help for support', () => {
+ expect(budgetConfigProbe.parse(CONFIGURE_HELP)).toBe(true)
+ expect(budgetConfigProbe.parse('Usage: claude plugin [options]')).toBe(false)
+ })
+
+ it('keeps measured routing counts, with no invented costs or tokens', () => {
+ expect(modelStatsProbe.parse(MODEL_STATS)).toEqual({ isAvailable: true, total: 8, models: [{ name: 'haiku', count: 5 }, { name: 'sonnet', count: 3 }, { name: 'opus', count: 0 }, { name: 'inherit', count: 0 }] })
+ expect(modelStatsProbe.parse('{"available":false}')).toEqual({ isAvailable: false, models: [] })
+ expect(modelStatsProbe.parse('{"available":true,"modelDistribution":{"bad":-1,"string":"2"}}')?.models).toEqual([])
+ expect(modelStatsProbe.parse('{}')).toBeNull()
+ expect(modelStatsProbe.parse('not JSON')).toBeNull()
+ })
+})
diff --git a/plugins/ruflo-console/tests/fixtures/cost.ts b/plugins/ruflo-console/tests/fixtures/cost.ts
new file mode 100644
index 0000000000..a46321c3e4
--- /dev/null
+++ b/plugins/ruflo-console/tests/fixtures/cost.ts
@@ -0,0 +1,3 @@
+/** Claude's local configure help, and synthetic routing counts shaped by ModelRouter.getStats(). */
+export const CONFIGURE_HELP = 'Usage: claude plugin configure [options] <plugin>\n--values-stdin Read option values from stdin as a JSON object of single-line strings; options left out keep their values'
+export const MODEL_STATS = JSON.stringify({ available: true, totalDecisions: 8, modelDistribution: { haiku: 5, sonnet: 3, opus: 0, inherit: 0 }, routedByCounts: { neural: 0, heuristic: 0 }, timestamp: '2026-10-02T12:00:00.000Z' })
diff --git a/plugins/ruflo-console/tests/fixtures/world.ts b/plugins/ruflo-console/tests/fixtures/world.ts
index 0bf9052dfa..193ce81975 100644
--- a/plugins/ruflo-console/tests/fixtures/world.ts
+++ b/plugins/ruflo-console/tests/fixtures/world.ts
@@ -2,6 +2,7 @@ import type { On, RenderElement, RenderInput, RenderNode, SessionStartInput } fr
import type { Plugin } from 'claude-code/testing'
import { CLI_OUT } from './ruflo-run'
+import { CONFIGURE_HELP, MODEL_STATS } from './cost'
export const PLUGIN = 'ruflo-console'
export const CWD = '/work'
@@ -32,6 +33,7 @@ export type Answer = { exitCode: number; stdout: string; stderr: string } | { de
export type World = {
files: Map<string, string>
runs: string[][]
+ inputs: string[]
blits: string[]
opened: string[]
commands: string[]
@@ -48,6 +50,9 @@ export function cliAnswer(argv: readonly string[]): Answer {
const line = argv.join(' ')
const out = (name: string): Answer => ({ exitCode: 0, stdout: CLI_OUT[name] ?? '', stderr: '' })
+ if (line === 'claude plugin configure --help') return { exitCode: 0, stdout: CONFIGURE_HELP, stderr: '' }
+ if (line.includes('hooks model-stats')) return { exitCode: 0, stdout: MODEL_STATS, stderr: '' }
+
if (line.endsWith('--version')) return out('version')
if (line.includes('memory stats')) return out('memory-stats')
if (line.includes('memory list')) return out('memory-list')
@@ -77,6 +82,7 @@ export function worldOf(on: On, files: Readonly<Record<string, string>>, options
const world: World = {
files: all,
runs: [],
+ inputs: [],
blits: [],
opened: [],
commands: [],
@@ -109,6 +115,7 @@ export function worldOf(on: On, files: Readonly<Record<string, string>>, options
if (refuse) return { deny: 'process.run withheld' }
world.runs.push([...e.argv])
+ if (e.init?.stdin !== undefined) world.inputs.push(e.init.stdin)
const answer = world.respond(e.argv)
diff --git a/plugins/ruflo-console/tests/palette.test.ts b/plugins/ruflo-console/tests/palette.test.ts
index bf0366f178..9f20021ab8 100644
--- a/plugins/ruflo-console/tests/palette.test.ts
+++ b/plugins/ruflo-console/tests/palette.test.ts
@@ -7,6 +7,25 @@ import { command, elementsOf, keyOf, paneAt, PLUGIN, SESSION, textOf, worldOf }
const runsOf = (runs: readonly string[][], word: string) => runs.filter(argv => argv.includes(word))
describe('palette and /ruflo', () => {
+ test('cost headless: direct custom and preset entries check support, ask, and only configure on yes', { options: { boot: false } }, async ($, on) => {
+ const world = worldOf(on, RUFLO_FILES)
+
+ mock.clock(on)
+ await $.session.start({ ...SESSION, isInteractive: false })
+ const ask = (await $.command.run(command('run cost-budget 12.5'))).text ?? ''
+
+ expect(ask).toContain('Asked: set ruflo-mods@ruflo costBudgetUsd to $12.5')
+ expect(ask).toContain('stdin {"costBudgetUsd":"12.5"}')
+ expect(ask).toContain('restart/reload may be needed')
+ expect(world.runs.some(argv => argv.includes('--values-stdin'))).toBe(false)
+ expect((await $.command.run(command('yes'))).text).toContain('restart/reload may be needed')
+ expect(world.runs.filter(argv => argv.includes('--values-stdin'))).toHaveLength(1)
+ expect((await $.command.run(command('run cost-budget-10'))).text).toContain('Asked: set ruflo-mods@ruflo costBudgetUsd to $10')
+ await $.command.run(command('no'))
+ expect(world.runs.filter(argv => argv.includes('--values-stdin'))).toHaveLength(1)
+ expect((await $.command.run(command('run cost-budget 0'))).text).toContain('budget must be a number from 0.01 to 10000 USD')
+ })
+
test('p opens the palette; typing filters; a change asks first and runs one fixed argv on yes', { options: { boot: false } }, async ($, on) => {
const world = worldOf(on, RUFLO_FILES)
mock.clock(on)
diff --git a/plugins/ruflo-console/tests/terminal.spec.ts b/plugins/ruflo-console/tests/terminal.spec.ts
index d89aee59f8..2933dd693a 100644
--- a/plugins/ruflo-console/tests/terminal.spec.ts
+++ b/plugins/ruflo-console/tests/terminal.spec.ts
@@ -122,6 +122,7 @@ describe('terminal sessions', () => {
expect(state.terminal.sessions.codex).toBe('01a0fe1f-b077-7793-9612-f134bd61bc85')
expect(stored.get('ruflo-console/term:/work')).toEqual({ codex: '01a0fe1f-b077-7793-9612-f134bd61bc85' })
expect(state.terminal.turns.codex).toBe(1)
+ expect(state.terminal.costReports).toBe(0)
})
it('claude: the answer types out from deltas (not twice), tool calls show, the cost is counted', async () => {
@@ -136,6 +137,7 @@ describe('terminal sessions', () => {
expect(shown(state)).toEqual(['claude in:hi', 'claude head:claude', 'claude out:Hello there', 'claude out:second', 'claude tool:⚙ Read src/auth.ts', expect.stringMatching(/^claude end:✓ \d+ s · \$0\.012$/)])
expect(state.terminal.sessions.claude).toBe('6b1c2d3e-0000-4000-8000-000000000001')
expect(state.terminal.costUsd).toBeCloseTo(0.0123)
+ expect(state.terminal.costReports).toBe(1)
})
it('a busy agent refuses a second question; s stops it; /new forgets the session', async () => {
diff --git a/plugins/ruflo-console/tests/views.test.ts b/plugins/ruflo-console/tests/views.test.ts
index 39a1187e2b..1428b6279b 100644
--- a/plugins/ruflo-console/tests/views.test.ts
+++ b/plugins/ruflo-console/tests/views.test.ts
@@ -221,6 +221,88 @@ describe('views', () => {
expect(cost.rasters).toEqual(['header', 'title', 'gauge', 'burn'])
expect(cost.text).toContain('$0.421')
expect(cost.text).toContain('WARNING · $3.90 of $5.00 (78%)')
+ expect(cost.text).toContain('WHERE IT GOES')
+ expect(cost.text).toContain('AI terminal')
+ expect(cost.text).toContain('8 decisions')
+ expect(cost.text).toContain('5 routes · spend n/a · tokens n/a')
+ expect(cost.text).toContain('$1.100 · ruflo-mods budget')
+ expect(cost.text).toContain('50% · $2.50')
+ expect(elementsOf(cost.tree, 'Button').map(keyOf)).toEqual(expect.arrayContaining(['cost-budget-1', 'cost-budget-5', 'cost-budget-10', 'cost-budget-25', 'cost-budget-apply', 'cost-model-stats']))
+ expect(elementsOf(cost.tree, 'Input').map(keyOf)).toEqual(['cost-budget'])
+ })
+
+ test('cost: a preset asks first, names the exact change, and sends one fixed argv with JSON stdin on yes', { options: { boot: false } }, async ($, on) => {
+ const world = worldOf(on, RUFLO_FILES)
+ mock.clock(on)
+ await $.session.start(SESSION)
+ await drawn($, 'cost')
+
+ const pane = await $.ui.mount({ ...paneAt(110), surface: 'terminal' as const, plugin: PLUGIN })
+ const setters = () => world.runs.filter(argv => argv.includes('--values-stdin'))
+
+ await pane.press({ key: 'cost-budget-5' })
+ const ask = textOf(await pane.drawn())
+
+ expect(ask).toContain('Confirm: set ruflo-mods@ruflo costBudgetUsd to $5?')
+ expect(ask).toContain('runs: claude plugin configure ruflo-mods@ruflo --values-stdin · stdin {"costBudgetUsd":"5"}')
+ expect(ask).toContain('restart/reload may be needed')
+ expect(setters()).toHaveLength(0)
+ await pane.press({ key: 'confirm' })
+ expect(setters()).toEqual([['claude', 'plugin', 'configure', 'ruflo-mods@ruflo', '--values-stdin']])
+ expect(world.inputs).toEqual(['{"costBudgetUsd":"5"}'])
+ await pane.press({ key: 'cost-budget-25' })
+ await pane.press({ key: 'cancel' })
+ expect(setters()).toHaveLength(1)
+ await pane.input({ key: 'cost-budget', text: '12.5', kind: 'change' })
+ await pane.press({ key: 'cost-budget-apply' })
+ expect(textOf(await pane.drawn())).toContain('costBudgetUsd to $12.5?')
+ await pane.input({ key: 'cost-budget', text: '--help', kind: 'submit' })
+ expect(textOf(await pane.drawn())).toContain('budget must be a number from 0.01 to 10000 USD')
+ expect((await $.command.run(command('yes'))).text).toBe('Nothing is waiting for a confirm.')
+ expect(setters()).toHaveLength(1)
+ await pane.unmount()
+ })
+
+ test('cost: unsupported configuration says where to set it and no preset or custom entry runs a setter', { options: { boot: false } }, async ($, on) => {
+ const world = worldOf(on, RUFLO_FILES)
+
+ world.respond = argv => argv.includes('configure') ? { exitCode: 1, stdout: '', stderr: 'unknown command configure' } : cliAnswer(argv)
+ mock.clock(on)
+ await $.session.start(SESSION)
+ const cost = await drawn($, 'cost')
+
+ expect(cost.text).toContain('set costBudgetUsd in /config → ruflo-mods')
+ const pane = await $.ui.mount({ ...paneAt(110), surface: 'terminal' as const, plugin: PLUGIN })
+
+ await pane.press({ key: 'cost-budget-1' })
+ expect(textOf(await pane.drawn())).not.toContain('Confirm:')
+ await pane.input({ key: 'cost-budget', text: '5', kind: 'submit' })
+ expect((await $.command.run(command('yes'))).text).toBe('Nothing is waiting for a confirm.')
+ expect(world.runs.some(argv => argv.includes('--values-stdin'))).toBe(false)
+ await pane.unmount()
+ })
+
+ test('cost: its probes stay on Cost and model inspection is an immediate offline read', { options: { boot: false, cli: 'npx' } }, async ($, on) => {
+ const world = worldOf(on, RUFLO_FILES)
+
+ mock.clock(on)
+ await $.session.start(SESSION)
+ await drawn($, 'overview')
+ expect(world.runs.some(argv => argv.includes('model-stats') || argv.includes('configure'))).toBe(false)
+ const costStart = world.runs.length
+
+ await drawn($, 'cost')
+ const pane = await $.ui.mount({ ...paneAt(110), surface: 'terminal' as const, plugin: PLUGIN })
+ const before = world.runs.filter(argv => argv.includes('model-stats')).length
+
+ await pane.press({ key: 'cost-model-stats' })
+ expect(textOf(await pane.drawn())).not.toContain('Confirm:')
+ const reads = world.runs.filter(argv => argv.includes('model-stats'))
+
+ expect(reads).toHaveLength(before + 1)
+ expect(reads.every(argv => argv[1] === '--offline')).toBe(true)
+ expect(world.runs.slice(costStart).filter(argv => argv[0] === 'npx').every(argv => argv[1] === '--offline')).toBe(true)
+ await pane.unmount()
})
test('timeline, approvals and events draw from what was seen; the drill-down opens an agent', { options: { boot: false } }, async ($, on) => {