π 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
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat(ruflo-cost-tracker, ruflo-console): multi-provider cost ledger, price book, advisor and Cost page (ADR-437)
ruv283e680ff2ea
diff --git a/plugins/ruflo-console/.claude-plugin/plugin.json b/plugins/ruflo-console/.claude-plugin/plugin.jsonindex 51c1849d29..806448b7ea 100644--- a/plugins/ruflo-console/.claude-plugin/plugin.json+++ b/plugins/ruflo-console/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "ruflo-console","description": "ruflo's cockpit inside Claude Code and the one /ruflo command for every ruflo mod (function hooks, early access). Views: overview with health alerts, swarm topology graph, claims flow with TTL rings, federation map, plugin health matrix, learning curve and pipeline, MetaHarness radar and audit trend, memory, cost gauge, agent timeline, approvals queue, event stream, a main menu, an x.ruv.io federation board, an AI terminal (codex, claude or both in remembered sessions, streamed), Skills (npx skills), a Hive-Mind view, a MetaHarness lab, agent drill-down; a command palette for confirm-gated actions through the ruflo CLI; a band above the prompt. Reads ruflo's files and the CLI's local JSON; anything not measured reads n/a. The one network call it makes by itself is a daily read of the published plugin.json at github.com/ruvnet/ruflo to offer an update (Settings β Updates: ask, auto, or off); it installs only through Claude Code's own claude plugin update, and never a new major version without asking.",- "version": "0.26.1",+ "version": "0.27.0","author": {"name": "ruvnet","url": "https://github.com/ruvnet"diff --git a/plugins/ruflo-console/hooks/controller.ts b/plugins/ruflo-console/hooks/controller.tsindex 9b9b3c3cc8..72a7d528f4 100644--- a/plugins/ruflo-console/hooks/controller.ts+++ b/plugins/ruflo-console/hooks/controller.ts@@ -5,7 +5,8 @@*/import { actionsOf } from './bindings'import type { Catalog } from './data/catalog'-import { PROBES, probeArgv, type ProbeResult } from './data/cli'+import { PROBES, probeArgv, probeReady, type ProbeResult } from './data/cli'+import { COST_PROBES } from './data/cost-ledger'import { X_PROBES } from './data/xruv'import { diffEvents, record } from './data/events'import { plain } from './data/parse'@@ -31,7 +32,7 @@ const ACTIVITY_BUCKET_MS = 5_000const PANE_WATCH_MS = 1_000const MAX_PARALLEL_PROBES = 2/** The CLI probes and the x.ruv.io board's two network reads, one cadence and one option gate for all. */-const ALL_PROBES = [...PROBES, ...X_PROBES]+const ALL_PROBES = [...PROBES, ...X_PROBES, ...COST_PROBES]const BAR_FRESH_MS = 10_000const IDLE_REFRESH_MS = 30_000const TOOLS_RECOUNT_MS = 30_000@@ -207,7 +208,7 @@ export function createController(state: State, host: Host): Controller {lastAttempt.set(probe.id, Date.now())try {- const result = await host.run(probeArgv(probe, state.options.cli), probe.timeoutMs)+ const result = await host.run(probeArgv(probe, state.options.cli, state), probe.timeoutMs)const value = result.exitCode === 0 ? (probe.parse(result.stdout) as unknown) : nullstate.probes.set(@@ -235,7 +236,7 @@ export function createController(state: State, host: Host): Controller {entry =>(isVisible() || force) &&entry.views.includes(state.view) &&- (!entry.isNetwork || state.options.federationNetwork) &&+ (!entry.isNetwork || state.options.federationNetwork) && probeReady(entry, state) &&(force || (state.probes.get(entry.id)?.isRunning !== true && now - (lastAttempt.get(entry.id) ?? 0) >= entry.everyMs)),)diff --git a/plugins/ruflo-console/hooks/data/cli.ts b/plugins/ruflo-console/hooks/data/cli.tsindex a32724bb89..3c54ca59c1 100644--- a/plugins/ruflo-console/hooks/data/cli.ts+++ b/plugins/ruflo-console/hooks/data/cli.ts@@ -6,7 +6,7 @@*/import { idOf, msOf, numberOf, plain, recordOf, stringOf, valuesOf } from './parse'-import { CLI_PREFIXES, type CliChoice, type ViewId } from '../state'+import { CLI_PREFIXES, type CliChoice, type State, type ViewId } from '../state'export type { ViewId }@@ -15,6 +15,8 @@ export type Probe<T> = {args: readonly string[]/** A local executable for a capability check, or an offline-only ruflo read. */argv?: readonly string[]+ /** An argv that depends on what is installed; null while it cannot be built, and the probe then does not run. */+ argvOf?: (state: State) => readonly string[] | nullisOffline?: 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[]@@ -49,7 +51,10 @@ 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]+export const probeArgv = (probe: Pick<Probe<unknown>, 'args' | 'argv' | 'argvOf' | 'isOffline'>, cli: CliChoice, state?: State): readonly string[] => (state === undefined ? undefined : probe.argvOf?.(state)) ?? probe.argv ?? [...CLI_PREFIXES[probe.isOffline && cli === 'npx' ? 'npx-offline' : cli], ...probe.args]++/** A probe with an install-dependent argv runs only while that argv can be built; every other probe is always ready. */+export const probeReady = (probe: Pick<Probe<unknown>, 'argvOf'>, state: State): boolean => probe.argvOf === undefined || probe.argvOf(state) !== null/** Help only: older Claude builds must not get a guessed configuration command. */export const budgetConfigProbe: Probe<boolean> = {diff --git a/plugins/ruflo-console/hooks/data/cost-ledger.ts b/plugins/ruflo-console/hooks/data/cost-ledger.tsnew file mode 100644index 0000000000..8101b688ab--- /dev/null+++ b/plugins/ruflo-console/hooks/data/cost-ledger.ts@@ -0,0 +1,114 @@+/**+ * The Cost page's multi-provider ledger. The mod cannot read the agents' logs itself, so it asks the ruflo-cost-tracker+ * plugin's `ledger.mjs` (installed under Claude Code's plugin cache) for one local JSON summary: Claude Code and Codex+ * spend, cache hit ratio and optimisation findings. Local only: nothing here reaches the network, and the script path+ * comes from `installed_plugins.json`, validated, never from typed text. USD and Codex credits are never added together.+ */+import { jsonAfter, type Probe } from './cli'+import { numberOf, plain, recordOf, stringOf } from './parse'++import type { State } from '../state'++export const COST_PLUGIN = 'ruflo-cost-tracker@ruflo'++export type Money = { usd?: number; credits?: number }+export type LedgerModel = { provider: string; model: string; cost: Money; messages: number; output: number }+export type Finding = { id: string; title: string; evidence: string; action: string; saving: number | null; unit: 'usd' | 'credits' | null }+export type Ledger = {+ since: string+ priceDate: string+ totals: Money+ providers: { name: string; cost: Money; hitRatio: number | null }[]+ models: LedgerModel[]+ days: { day: string; usd: number }[]+ unpriced: string[]+ approx: string[]+ findings: Finding[]+}++const moneyOf = (value: unknown): Money => {+ const record = recordOf(value)+ const usd = numberOf(record?.usd)+ const credits = numberOf(record?.credits)++ return { ...(usd !== undefined && { usd }), ...(credits !== undefined && { credits }) }+}++/** An absolute POSIX path of a plugin's install directory: no `..`, no control characters, no shell-looking text. */+export const safeInstallPath = (value: unknown): string | undefined => {+ const path = typeof value === 'string' ? value : ''++ return /^\/[A-Za-z0-9._@+/ -]{1,300}$/.test(path) && !path.split('/').includes('..') ? path : undefined+}++/** The ledger JSON `ledger.mjs --format json --advise` prints. */+export function parseLedger(stdout: string): Ledger | null {+ const value = recordOf(jsonAfter(stdout))+ const totals = recordOf(value?.totals)+ const byProvider = recordOf(value?.byProvider)++ if (value === null || totals === null || byProvider === null) return null++ const cache = recordOf(value.cache) ?? {}+ const byModel = recordOf(value.byModel) ?? {}+ const tokens = recordOf(value.tokens) ?? {}+ const byDay = recordOf(value.byDay) ?? {}+ const unpriced = recordOf(value.unpriced) ?? {}+ const findings = Array.isArray(value.findings) ? value.findings : []++ return {+ since: stringOf(value.since, 12) ?? '7d',+ priceDate: stringOf(value.priceDate, 12) ?? 'unknown',+ totals: moneyOf(totals),+ providers: Object.entries(byProvider).slice(0, 8).map(([name, cost]) => ({ name: plain(name, 20), cost: moneyOf(cost), hitRatio: numberOf(recordOf(cache[name])?.hitRatio) ?? null })),+ models: Object.entries(byModel).slice(0, 40).map(([key, cost]) => {+ const [provider = '', model = ''] = key.split('|')+ const t = recordOf(tokens[key])++ return { provider: plain(provider, 20), model: plain(model, 50), cost: moneyOf(cost), messages: numberOf(t?.messages) ?? 0, output: numberOf(t?.output) ?? 0 }+ }),+ days: Object.entries(byDay).sort(([a], [b]) => a.localeCompare(b)).slice(-14).map(([day, cost]) => ({ day: plain(day, 10), usd: moneyOf(cost).usd ?? 0 })),+ unpriced: Object.keys(unpriced).slice(0, 10).map(name => plain(name, 50)),+ approx: (Array.isArray(value.approx) ? value.approx : []).slice(0, 10).map(name => plain(name, 50)),+ findings: findings.slice(0, 12).flatMap(item => {+ const finding = recordOf(item)+ const title = stringOf(finding?.title, 140)++ return finding === null || title === undefined ? [] : [{ id: stringOf(finding.id, 40) ?? 'finding', title, evidence: stringOf(finding.evidence, 300) ?? '', action: stringOf(finding.action, 300) ?? '', saving: numberOf(finding.saving) ?? null, unit: finding.unit === 'usd' || finding.unit === 'credits' ? finding.unit : null }]+ }),+ }+}++/** The first release with the ledger script: an older install has no `ledger.mjs` to run. */+export const LEDGER_FROM = [0, 27, 0] as const++const atLeast = (version: string, from: readonly number[]): boolean => {+ const parts = /^(\d+)\.(\d+)\.(\d+)/.exec(version)?.slice(1).map(Number) ?? []++ for (let i = 0; i < 3; i++) if ((parts[i] ?? 0) !== from[i]) return (parts[i] ?? 0) > (from[i] ?? 0)++ return parts.length === 3+}++/** Whether the tracker is absent, too old to have the ledger, or ready (with the script's directory). */+export function trackerOf(state: Pick<State, 'snapshot'>): { kind: 'absent' } | { kind: 'old'; version: string } | { kind: 'ready'; root: string } {+ const entry = state.snapshot?.plugins.installed?.find(plugin => plugin.id === COST_PLUGIN)+ const root = safeInstallPath(entry?.installPath)++ if (entry === undefined || root === undefined) return { kind: 'absent' }++ return atLeast(entry.version, LEDGER_FROM) ? { kind: 'ready', root } : { kind: 'old', version: entry.version }+}++/** Where the plugin's ledger script is, or null when it is absent or too old (the probe then does not run). */+export function ledgerArgv(state: Pick<State, 'snapshot'>): readonly string[] | null {+ const tracker = trackerOf(state)++ return tracker.kind === 'ready' ? ['node', `${tracker.root}/scripts/ledger.mjs`, '--since', '7d', '--format', 'json', '--advise'] : null+}++export const costLedgerProbe: Probe<Ledger> = {+ id: 'cost-ledger', args: [], argvOf: ledgerArgv, views: ['cost'], everyMs: 300_000, timeoutMs: 60_000, parse: parseLedger,+}++export const COST_PROBES = [costLedgerProbe] as constdiff --git a/plugins/ruflo-console/hooks/data/facts.ts b/plugins/ruflo-console/hooks/data/facts.tsindex dae9e8e470..d6bd0a48cb 100644--- a/plugins/ruflo-console/hooks/data/facts.ts+++ b/plugins/ruflo-console/hooks/data/facts.ts@@ -156,7 +156,7 @@ export function parseHelpers(text: string | null): { version: string; files: strreturn { version: stringOf(manifest.version, 20) ?? 'unknown', files, isSigned: typeof value.signature === 'string' && value.signature.length > 20, ...(algorithm !== undefined && { algorithm }) }}-export type Installed = { id: string; name: string; marketplace: string; version: string; scope: string; updatedMs?: number }+export type Installed = { id: string; name: string; marketplace: string; version: string; scope: string; updatedMs?: number; installPath?: string }/** `~/.claude/plugins/installed_plugins.json` (version 2): every installed plugin, `name@marketplace`. */export function parseInstalled(text: string | null): Installed[] | null {@@ -178,8 +178,9 @@ export function parseInstalled(text: string | null): Installed[] | null {}const updatedMs = msOf(entry.lastUpdated)+ const installPath = typeof entry.installPath === 'string' && entry.installPath.length <= 300 ? entry.installPath : undefined- return [{ id: `${name}@${marketplace}`, name, marketplace, version: stringOf(entry.version, 30) ?? '?', scope: stringOf(entry.scope, 12) ?? '?', ...(updatedMs !== undefined && { updatedMs }) }]+ return [{ id: `${name}@${marketplace}`, name, marketplace, version: stringOf(entry.version, 30) ?? '?', scope: stringOf(entry.scope, 12) ?? '?', ...(updatedMs !== undefined && { updatedMs }), ...(installPath !== undefined && { installPath }) }]})}diff --git a/plugins/ruflo-console/hooks/state.ts b/plugins/ruflo-console/hooks/state.tsindex 21e3f543f5..a4471319ef 100644--- a/plugins/ruflo-console/hooks/state.ts+++ b/plugins/ruflo-console/hooks/state.ts@@ -46,7 +46,7 @@ export const VIEWS: readonly { id: ViewId; key: string; label: string; short: st{ id: 'learning', key: '7', label: 'Learning', short: 'Lrn', icon: 'π§ ', blurb: 'router picks and outcomes, and the RETRIEVE β JUDGE β DISTILL β CONSOLIDATE pipeline', rows: 30 },{ id: 'metaharness', key: '8', 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: '9', label: 'Memory', short: 'Mem', icon: 'πΎ', blurb: 'the Memory Lab: browse, search, store and delete entries; AgentDB, embeddings and upkeep, each a button', rows: 60 },- { id: 'cost', key: 'c', label: 'Cost', short: 'Cst', icon: 'π°', blurb: 'set a budget, see where spend is reported, and project its burn', rows: 40 },+ { id: 'cost', key: 'c', label: 'Cost', short: 'Cst', icon: 'π°', blurb: 'set a budget, see spend across Claude Code and Codex, and how to cut it', 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 },diff --git a/plugins/ruflo-console/hooks/version.ts b/plugins/ruflo-console/hooks/version.tsindex cc4e205d8c..df6553e7ca 100644--- a/plugins/ruflo-console/hooks/version.ts+++ b/plugins/ruflo-console/hooks/version.ts@@ -2,4 +2,4 @@* The console's version, shown on the header so a person can tell which build is running. Kept equal to the plugin's manifest* (`.claude-plugin/plugin.json`); tests/version.spec.ts fails if the two drift.*/-export const CONSOLE_VERSION = '0.26.1'+export const CONSOLE_VERSION = '0.27.0'diff --git a/plugins/ruflo-console/hooks/views/cost-providers.ts b/plugins/ruflo-console/hooks/views/cost-providers.tsnew file mode 100644index 0000000000..a4a9f623d1--- /dev/null+++ b/plugins/ruflo-console/hooks/views/cost-providers.ts@@ -0,0 +1,67 @@+import type { RenderElement } from 'claude-code'++import { COST_PLUGIN, LEDGER_FROM, trackerOf, type Finding, type Ledger, type Money } from '../data/cost-ledger'+import { ago, button, kv, live, pct, row, rule, sourceLine, text, THEME, type Ctx } from './common'++const SPARK = 'βββββ βββ'+/** A model id as a short label: no `claude-` prefix and no date suffix, so sonnet-5 and sonnet-5-5 stay distinct. */+export const shortModel = (model: string): string => model.replace(/^claude-/, '').replace(/-\d{8}$/, '')+const grouped = (value: number): string => Math.round(value).toLocaleString('en-US')++/** USD and Codex credits side by side, never summed: they are different currencies. */+export const moneyText = (cost: Money): string => [cost.usd === undefined ? '' : `$${cost.usd >= 100 ? grouped(cost.usd) : cost.usd.toFixed(2)}`, cost.credits === undefined ? '' : `${grouped(cost.credits)} credits`].filter(Boolean).join(' Β· ') || 'n/a'++/** One block per day, scaled to the busiest: the shape of the week, not an exact figure. */+export function spark(values: readonly number[]): string {+ const top = Math.max(...values, 0)++ return values.map(value => (top <= 0 ? SPARK[0] : SPARK[Math.min(7, Math.floor((value / top) * 7.999))])).join('')+}++const saving = (finding: Finding): string => (finding.saving === null || finding.unit === null ? 'saving n/a' : `up to ${moneyText({ [finding.unit]: finding.saving })}`)++/** What each provider cost in the last week, and what to change: from the local logs, via the cost-tracker plugin. */+export function providerRows(ctx: Ctx): RenderElement[] {+ const { state } = ctx+ const result = state.probes.get('cost-ledger')+ const ledger = live<Ledger>(result)+ const rows = [rule(ctx, 'Across providers', ledger === null ? 'Claude Code + Codex Β· local logs' : `last ${ledger.since} Β· local logs Β· list-price estimates`)]++ const tracker = trackerOf(state)++ if (tracker.kind !== 'ready') {+ const name = COST_PLUGIN.split('@')[0]++ rows.push(kv(ctx, 'ledger', tracker.kind === 'old' ? `n/a β ${name} ${tracker.version} is installed; needs ${LEDGER_FROM.join('.')} or newer` : `n/a β ${name} is not installed`))+ rows.push(text(ctx, ' It shows Claude Code and Codex spend, cache hit ratio and savings here. Nothing is sent anywhere.', { dimColor: true }))+ rows.push(row(ctx, [button(ctx, 'cost-install-tracker', tracker.kind === 'old' ? 'Plugins: update it' : 'Plugin Catalog: ruflo-cost-tracker', () => ctx.act.view(tracker.kind === 'old' ? 'plugins' : 'market'))]))++ return rows+ }++ const source = sourceLine(result, ctx.nowMs, 'ledger')++ rows.push(text(ctx, ` ${ledger === null ? source.text : `ledger: cost-tracker plugin, ${ago(result?.okAtMs, ctx.nowMs)}`}`, { dimColor: true, ...(source.color !== undefined && { color: source.color }) }))+ if (ledger === null) return rows++ for (const provider of ledger.providers) rows.push(kv(ctx, provider.name, `${moneyText(provider.cost)} Β· cache hit ${provider.hitRatio === null ? 'n/a' : pct(provider.hitRatio)}`))+ if (ledger.days.length > 1) rows.push(kv(ctx, 'USD / day', `${spark(ledger.days.map(day => day.usd))} ${ledger.days[0]?.day.slice(5)} β ${ledger.days.at(-1)?.day.slice(5)}`))+ const ranked = [...ledger.models].sort((a, b) => (b.cost.usd ?? b.cost.credits ?? 0) - (a.cost.usd ?? a.cost.credits ?? 0)).slice(0, 5)++ for (const model of ranked) rows.push(kv(ctx, shortModel(model.model).slice(0, 16), `${moneyText(model.cost)} Β· ${grouped(model.messages)} msgs`))+ if (ledger.unpriced.length > 0) rows.push(text(ctx, ` Unpriced, NOT counted as $0: ${ledger.unpriced.join(', ')}`, { color: THEME.warn }))+ if (ledger.unpriced.length > 0) rows.push(text(ctx, ' Add them to data/prices.json in the plugin.', { dimColor: true }))+ rows.push(text(ctx, ` List-price estimates (${ledger.priceDate}), not bills.`, { dimColor: true }))+ rows.push(text(ctx, ' USD and credits are never added together.', { dimColor: true }))++ if (ledger.findings.length > 0) {+ rows.push(rule(ctx, 'Savings you can act on', 'evidence from your logs Β· nothing is changed for you'))+ ledger.findings.slice(0, 4).forEach((finding, i) => {+ rows.push(text(ctx, ` ${i + 1}. ${finding.title}`, { bold: true }))+ rows.push(text(ctx, ` ${saving(finding)} Β· ${finding.action}`, finding.saving === null ? { dimColor: true } : { color: THEME.ok }))+ })+ rows.push(text(ctx, ' Same tokens at another rate; quality is not predicted. /cost-advise shows the evidence.', { dimColor: true }))+ }++ return rows+}diff --git a/plugins/ruflo-console/hooks/views/cost.ts b/plugins/ruflo-console/hooks/views/cost.tsindex 1a99b4def8..5e5e6057a1 100644--- a/plugins/ruflo-console/hooks/views/cost.ts+++ b/plugins/ruflo-console/hooks/views/cost.ts@@ -3,6 +3,7 @@ import type { RenderElement } from 'claude-code'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'+import { providerRows } from './cost-providers'const LADDER = [0.5, 0.75, 0.9, 1] as constconst dollars = (value: number | undefined | null): string => value === undefined || value === null || !Number.isFinite(value) || value < 0 ? 'n/a' : `$${value.toFixed(3)}`@@ -71,6 +72,7 @@ export function costView(ctx: Ctx): RenderElement {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(...providerRows(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 }))diff --git a/plugins/ruflo-console/scripts/smoke.sh b/plugins/ruflo-console/scripts/smoke.shindex 881a054d44..272012bb56 100755--- a/plugins/ruflo-console/scripts/smoke.sh+++ b/plugins/ruflo-console/scripts/smoke.sh@@ -11,9 +11,9 @@ step() { printf "β %s ... " "$1"; }ok() { printf "PASS\n"; PASS=$((PASS+1)); }bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }-step "1. plugin.json declares ruflo-console 0.26.1"+step "1. plugin.json declares ruflo-console 0.27.0"grep -q '"name": "ruflo-console"' "$ROOT/.claude-plugin/plugin.json" \- && grep -q '"version": "0.26.1"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"+ && grep -q '"version": "0.27.0"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"step "2. hooks.json names exactly one module and no classic hook commands"grep -q '"modules": \["./register.ts"\]' "$HOOKS/hooks.json" && ! grep -q '"command"' "$HOOKS/hooks.json" \diff --git a/plugins/ruflo-console/tests/cost-ledger.spec.ts b/plugins/ruflo-console/tests/cost-ledger.spec.tsnew file mode 100644index 0000000000..674a20da3f--- /dev/null+++ b/plugins/ruflo-console/tests/cost-ledger.spec.ts@@ -0,0 +1,146 @@+import { describe, expect, it } from 'vitest'++import { COST_PROBES, ledgerArgv, parseLedger, safeInstallPath, trackerOf } from '../hooks/data/cost-ledger'+import { probeArgv, probeReady, PROBES } from '../hooks/data/cli'+import { parseInstalled } from '../hooks/data/facts'+import { newState, type State } from '../hooks/state'+import type { Actions } from '../hooks/views/common'+import { moneyText, shortModel, spark } from '../hooks/views/cost-providers'+import { viewText } from '../hooks/views/pane'++const LEDGER = JSON.stringify({+ since: '7d', priceDate: '2026-10-03', rows: 5,+ totals: { usd: 2945.1, credits: 41104.4 },+ byProvider: { claude: { usd: 2945.1 }, codex: { credits: 41104.4 } },+ byModel: { 'claude|claude-opus-5-5': { usd: 2191.8 }, 'codex|gpt-6-astra': { credits: 41104.4 } },+ tokens: { 'claude|claude-opus-5-5': { messages: 16885, output: 6101817 }, 'codex|gpt-6-astra': { messages: 1348, output: 566209 } },+ byDay: { '2026-10-02': { usd: 400 }, '2026-10-01': { usd: 100 }, '2026-10-03': { usd: 200 } },+ cache: { claude: { hitRatio: 0.981 }, codex: { hitRatio: 0.977 } },+ unpriced: { 'gpt-5.6-sol': { messages: 35 } },+ approx: [],+ findings: [+ { id: 'subagents-claude-opus-5-5', unit: 'usd', saving: 191.13, title: 'Sub-agents ran on claude-opus-5-5', evidence: '9782 sub-agent messages', action: 'Give simple sub-agents model: claude-sonnet-5-5.' },+ { id: 'context-bloat', unit: null, saving: null, title: '3 long sessions re-read a large context', evidence: 'x', action: '/compact at a natural break.' },+ ],+})++const installed = (path: string, version = '0.27.0'): State => {+ const state = newState({})++ state.snapshot = { plugins: { installed: [{ id: 'ruflo-cost-tracker@ruflo', name: 'ruflo-cost-tracker', marketplace: 'ruflo', version, scope: 'user', installPath: path }] } } as unknown as State['snapshot']++ return state+}+const shown = (state: State) => viewText({ state, nowMs: 5, columns: 110, act: {} as Actions }, 'cost')++describe('the multi-provider ledger probe', () => {+ it('parses the ledger JSON, keeping USD and credits as separate currencies', () => {+ const ledger = parseLedger(LEDGER)++ expect(ledger?.totals).toEqual({ usd: 2945.1, credits: 41104.4 })+ expect(ledger?.providers).toEqual([{ name: 'claude', cost: { usd: 2945.1 }, hitRatio: 0.981 }, { name: 'codex', cost: { credits: 41104.4 }, hitRatio: 0.977 }])+ expect(ledger?.models[0]).toMatchObject({ provider: 'claude', model: 'claude-opus-5-5', messages: 16885 })+ expect(ledger?.days.map(day => day.day)).toEqual(['2026-10-01', '2026-10-02', '2026-10-03'])+ expect(ledger?.unpriced).toEqual(['gpt-5.6-sol'])+ expect(ledger?.findings[1]).toMatchObject({ saving: null, unit: null })+ })++ it('is null for anything that is not the ledger, and strips control text', () => {+ for (const bad of ['', 'not json', '{"a":1}', '[]']) expect(parseLedger(bad)).toBeNull()+ expect(parseLedger(JSON.stringify({ totals: {}, byProvider: { 'cl\u001b[31maude': { usd: 1 } } }))?.providers[0]?.name).not.toContain('\u001b')+ })++ it('takes the script path only from a validated install path', () => {+ expect(safeInstallPath('/home/u/.claude/plugins/cache/ruflo/ruflo-cost-tracker/0.27.0')).toBeDefined()+ for (const bad of ['relative/path', '/a/../etc', '/x; rm', '/x$(id)', '/x`id`', '', undefined, 42, `/${'a'.repeat(400)}`]) expect(safeInstallPath(bad)).toBeUndefined()+ })++ it('builds a fixed argv from the installed plugin, and none when it is absent or hostile', () => {+ expect(ledgerArgv(installed('/p/ruflo-cost-tracker/0.27.0'))).toEqual(['node', '/p/ruflo-cost-tracker/0.27.0/scripts/ledger.mjs', '--since', '7d', '--format', 'json', '--advise'])+ expect(ledgerArgv(newState({}))).toBeNull()+ expect(ledgerArgv(installed('/p/$(id)'))).toBeNull()+ expect(probeArgv(COST_PROBES[0], 'npx', installed('/p/ruflo-cost-tracker/0.27.0'))[1]).toBe('/p/ruflo-cost-tracker/0.27.0/scripts/ledger.mjs')+ expect(COST_PROBES[0].views).toEqual(['cost'])+ expect(COST_PROBES[0].isNetwork).toBeUndefined()+ })++ it('runs only while the tracker is installed and new enough: absent or old means the probe is not ready, every other probe always is', () => {+ expect(probeReady(COST_PROBES[0], newState({}))).toBe(false)+ expect(probeReady(COST_PROBES[0], installed('/p/ruflo-cost-tracker/0.26.3', '0.26.3'))).toBe(false)+ expect(probeReady(COST_PROBES[0], installed('/p/ruflo-cost-tracker/0.27.0'))).toBe(true)+ expect(probeReady(COST_PROBES[0], installed('/p/ruflo-cost-tracker/1.0.0', '1.0.0'))).toBe(true)+ expect(trackerOf(installed('/p/x', '0.26.3'))).toEqual({ kind: 'old', version: '0.26.3' })+ expect(trackerOf(installed('/p/x', 'unknown'))).toEqual({ kind: 'old', version: 'unknown' })+ for (const probe of PROBES) expect(probeReady(probe, newState({}))).toBe(true)+ })++ it('reads installPath from installed_plugins.json only when it is a short string', () => {+ const file = (installPath: unknown) => JSON.stringify({ version: 2, plugins: { 'ruflo-cost-tracker@ruflo': [{ scope: 'user', version: '0.27.0', installPath }] } })++ expect(parseInstalled(file('/p/x'))?.[0]?.installPath).toBe('/p/x')+ expect(parseInstalled(file(7))?.[0]?.installPath).toBeUndefined()+ expect(parseInstalled(file('/'.padEnd(400, 'a')))?.[0]?.installPath).toBeUndefined()+ })+})++describe('the Cost page across providers', () => {+ it('says the plugin is missing, with a way to install it, and shows nothing invented', () => {+ const text = shown(newState({}))++ expect(text).toContain('Across providers')+ expect(text).toContain('ruflo-cost-tracker is not installed')+ expect(text).toContain('Plugin Catalog: ruflo-cost-tracker')+ })++ it('says an installed but older tracker needs updating, and does not show a ledger', () => {+ const text = shown(installed('/p/ruflo-cost-tracker/0.26.3', '0.26.3'))++ expect(text).toContain('ruflo-cost-tracker 0.26.3 is installed; needs 0.27.0 or newer')+ expect(text).toContain('Plugins: update it')+ })++ it('shows each provider in its own currency, the cache hit, unpriced models and the savings with evidence', () => {+ const state = installed('/p/ruflo-cost-tracker/0.27.0')++ state.probes.set('cost-ledger', { value: parseLedger(LEDGER), okAtMs: 1, error: null, errorAtMs: null, isRunning: false })+ const text = shown(state)++ expect(text).toContain('$2,945 Β· cache hit')+ expect(text).toContain('41,104 credits')+ expect(text).toContain('Unpriced, NOT counted as $0: gpt-5.6-sol')+ expect(text).toContain('never added together')+ expect(text).toContain('ledger: cost-tracker plugin')+ expect(text).toContain('Sub-agents ran on claude-opus-5-5')+ expect(text).toContain('up to $191 Β·')+ expect(text).toContain('saving n/a')+ expect(text).not.toMatch(/\$2,945\.1.*credits|credits.*\$2,945/)+ })++ it('does not show a stale ledger as live', () => {+ const state = installed('/p/ruflo-cost-tracker/0.27.0')++ state.probes.set('cost-ledger', { value: parseLedger(LEDGER), okAtMs: 1, error: 'exit 1: boom', errorAtMs: 2, isRunning: false })+ expect(shown(state)).not.toContain('$2,945')+ expect(shown(state)).toContain('boom')+ })+})++describe('ledger formatting', () => {+ it('keeps sonnet-5 and sonnet-5-5 apart and drops dates', () => {+ expect(shortModel('claude-sonnet-5-5')).toBe('sonnet-5-5')+ expect(shortModel('claude-sonnet-5')).toBe('sonnet-5')+ expect(shortModel('claude-haiku-4-5-20251001')).toBe('haiku-4-5')+ expect(shortModel('gpt-6-astra')).toBe('gpt-6-astra')+ })++ it('scales the daily bars to the busiest day', () => {+ expect(spark([0, 50, 100])).toBe('βββ')+ expect(spark([0, 0])).toBe('ββ')+ })++ it('writes dollars and credits apart', () => {+ expect(moneyText({ usd: 12.5 })).toBe('$12.50')+ expect(moneyText({ credits: 1234.4 })).toBe('1,234 credits')+ expect(moneyText({})).toBe('n/a')+ })+})diff --git a/plugins/ruflo-cost-tracker/.claude-plugin/plugin.json b/plugins/ruflo-cost-tracker/.claude-plugin/plugin.jsonindex 68b4b471c5..0adbd8778f 100644--- a/plugins/ruflo-cost-tracker/.claude-plugin/plugin.json+++ b/plugins/ruflo-cost-tracker/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "ruflo-cost-tracker","description": "Token usage tracking, model cost attribution per agent, budget alerts, and optimization recommendations β uses memory_* (namespace-routed) for cost-tracking and cost-patterns; pairs with federation budget circuit breaker (ADR-097)",- "version": "0.26.3",+ "version": "0.27.0","author": {"name": "ruvnet","url": "https://github.com/ruvnet"@@ -44,6 +44,12 @@"traceability","drill-down","per-message",+ "multi-provider",+ "codex",+ "openrouter",+ "local-llm",+ "prompt-caching",+ "cost-optimization","ci","prometheus","observability",diff --git a/plugins/ruflo-cost-tracker/README.md b/plugins/ruflo-cost-tracker/README.mdindex e42c009b36..2ced953c62 100644--- a/plugins/ruflo-cost-tracker/README.md+++ b/plugins/ruflo-cost-tracker/README.md@@ -37,6 +37,10 @@ claude --plugin-dir plugins/ruflo-cost-tracker| `cost-diff` | `/cost-diff --baseline <path> --current <path> [--alert-on-pct N] [--alert-on-usd N]` | **PR regression detection** β diffs two cost-summary JSON snapshots. Per-tier + per-model breakdowns sorted by `\|delta\|`. Optional pct/USD alert thresholds for CI gating. || `cost-session` | `/cost-session [--session-id <id>] [--top 20] [--since <iso-ts>]` | **Drill-down** β per-message cost breakdown within ONE session. Surfaces top-N expensive messages with cache_write column so $16 messages stop looking like 569-token outputs. Pair with cost-anomaly. || `cost-health` | `/cost-health [--alert-acceleration 100] [--alert-outliers 1] [--skip burn,anomaly]` | **Composite CI gate** β runs budget+burn+anomaly+projection in parallel, returns `max(exit)`. One shell-out covers all four alert ladders. |+| `cost-ledger` | `/cost-ledger [--since 7d] [--provider claude\|codex\|all]` | **Multi-provider** spend, tokens and cache hit ratio from the local Claude Code and Codex logs; unpriced models flagged, USD and credits never mixed. |+| `cost-advise` | `/cost-advise [--since 7d]` | **Optimisation findings** from your own logs (cache discipline, 1h cache TTL, sub-agent tier, Codex reasoning share, context bloat) with what-if savings. |+| `cost-openrouter` | `/cost-openrouter key\|generation <id>\|credits` | OpenRouter's own billed cost, key limits and credits. Network + key: asks first (`--yes`), key only from the environment. |+| `cost-local` | `/cost-local --tok-per-s <n> [--busy 0.25] [--compare <model>]` | Cost per 1M tokens on your own hardware (fixed + marginal) and the utilisation at which it beats a hosted model. || `cost-conversation` | `/cost-conversation` | Per-conversation cost view (different lens from cost-report's per-agent / per-model) || `cost-export` | `/cost-export [--prometheus <path>] [--webhook <url>]` | Emit cost data as Prometheus textfile or POST to a webhook || `cost-federation` | `/cost-federation` | ADR-097 Phase 3 consumer β per-peer 1h/24h/7d federation_spend rolling windows |@@ -88,11 +92,13 @@ See [ADR-0002](./docs/adrs/0002-agentic-flow-and-agent-booster-integration.md) f## Model Pricing (per 1M tokens)-| Model | Input | Output | Cache Write | Cache Read |+| Model | Input | Output | Cache Write (5m) | Cache Read ||-------|-------|--------|-------------|------------|-| Haiku | $0.25 | $1.25 | $0.30 | $0.03 |-| Sonnet | $3.00 | $15.00 | $3.75 | $0.30 |-| Opus | $15.00 | $75.00 | $18.75 | $1.50 |+| Haiku 4.5 | $1.00 | $5.00 | $1.25 | $0.10 |+| Sonnet 5.5 | $2.00 | $10.00 | $2.50 | $0.20 |+| Opus 5.5 | $4.00 | $20.00 | $5.00 | $0.20 |++Rates live in `data/prices.json` (dated, sourced; `COST_PRICES` points at your own copy). 1-hour cache writes, per-model cache-read rates, OpenAI/Codex models and unpriced-model flagging are handled by the multi-provider ledger (`cost-ledger`).## Budget Alert Thresholds@@ -168,6 +174,8 @@ On every PR touching this plugin, GitHub Actions runs smoke + booster-only bench- [`ADR-0002` β agentic-flow + Agent Booster integration, model-outcome feedback loop, optimize-worker consumption, tier-aware reporting](./docs/adrs/0002-agentic-flow-and-agent-booster-integration.md)- [`ADR-0003` β Implementation arc v0.5 β v0.15 (auto-capture, budget enforcement, model-outcome feedback, observability, federation consumer)](./docs/adrs/0003-implementation-arc-v0.5-to-v0.15.md)+- [`ADR-437` β Cost across providers: one ledger over Claude Code and Codex logs, a dated price book, OpenRouter and local-model costs, the advisor, and the console Cost page](../../v3/docs/adr/ADR-437-console-cost-across-providers.md)+## Related Plugins- `ruflo-agentdb` β namespace convention owner; defines the routing rules ADR-0001 fixes a violation ofdiff --git a/plugins/ruflo-cost-tracker/REFERENCE.md b/plugins/ruflo-cost-tracker/REFERENCE.mdindex 140dd927fa..c49d9032f4 100644--- a/plugins/ruflo-cost-tracker/REFERENCE.md+++ b/plugins/ruflo-cost-tracker/REFERENCE.md@@ -4,11 +4,11 @@ Companion reference for `cost-analyst`. The agent prompt deliberately stays lean## Model pricing (USD per 1M tokens)-| Model | Input | Output | Cache write | Cache read |-|---|---|---|---|---|-| Haiku | $0.25 | $1.25 | $0.30 | $0.03 |-| Sonnet | $3.00 | $15.00 | $3.75 | $0.30 |-| Opus | $15.00 | $75.00 | $18.75 | $1.50 |+| Model | Input | Output | Cache write (5m) | Cache read |+|-------|-------|--------|-------------|------------|+| Haiku 4.5 | $1.00 | $5.00 | $1.25 | $0.10 |+| Sonnet 5.5 | $2.00 | $10.00 | $2.50 | $0.20 |+| Opus 5.5 | $4.00 | $20.00 | $5.00 | $0.20 |Prices are public-list and may need a refresh β verify against the Anthropic pricing page when running quarterly cost reports.diff --git a/plugins/ruflo-cost-tracker/agents/cost-analyst.md b/plugins/ruflo-cost-tracker/agents/cost-analyst.mdindex 67b46cd597..cd7b7bb62a 100644--- a/plugins/ruflo-cost-tracker/agents/cost-analyst.md+++ b/plugins/ruflo-cost-tracker/agents/cost-analyst.md@@ -33,6 +33,10 @@ Model pricing per 1M tokens (Haiku/Sonnet/Opus Γ Input/Output/Cache-Write/Cache| `cost-health` | Composite CI gate β runs budget+burn+anomaly+projection in parallel, returns max exit code | Single CI step that covers all four alert ladders; faster than wiring each separately because subchecks run in parallel || `cost-diff` | PR-level snapshot delta β compares two cost-summary JSON outputs | "Did this PR add cost vs main?"; pair with cost-summary on each branch then diff || `cost-session` | Per-message drill-down within one session β surfaces top-N expensive messages with cache_write column | Natural follow-up to cost-anomaly: "session X was an outlier β which messages?". Distinguishes cache-write costs from output-token costs (the silent killer) |+| `cost-ledger` | Multi-provider ledger over local Claude Code + Codex logs; cache hit ratio; unpriced models flagged | "What did I spend across Claude and Codex?" Never add USD to Codex credits |+| `cost-advise` | Findings with evidence and what-if savings (cache, TTL, sub-agent tier, reasoning effort, context size) | "How do I cut spend?" Present, never apply; savings say nothing about quality |+| `cost-openrouter` | OpenRouter key limit / usage / generation cost / credits | Network + key: ask first, run with `--yes`, never print a key |+| `cost-local` | $/1M tokens on owned hardware and break-even utilisation vs a hosted model | Local-vs-API questions; estimates from the user's own inputs || `cost-export` | Prometheus textfile + webhook POST | External observability dashboards || `cost-federation` | ADR-097 Phase 3 consumer β per-peer 1h/24h/7d windows | After Phase 3 emits federation_spend events || `cost-benchmark` | Run the corpus harness β booster + optional Gemini/Sonnet/Opus | Verifying speedup claims, regression check |diff --git a/plugins/ruflo-cost-tracker/commands/ruflo-cost.md b/plugins/ruflo-cost-tracker/commands/ruflo-cost.mdindex b0d1e523ca..448f140630 100644--- a/plugins/ruflo-cost-tracker/commands/ruflo-cost.md+++ b/plugins/ruflo-cost-tracker/commands/ruflo-cost.md@@ -160,3 +160,15 @@ Cost tracking commands:2. Show daily/weekly totals with trend direction3. Highlight days with unusual spending (>2x average)4. Display: date, total cost, top agent, top model, budget status++**`cost ledger [--since 7d] [--provider claude|codex|all]`** -- Multi-provider spend from local logs (no network).+1. Run `node ${CLAUDE_PLUGIN_ROOT}/scripts/ledger.mjs --since 7d`+2. Report totals per provider/model, cache hit ratio, and any UNPRICED models (never counted as $0). USD and Codex credits are reported separately.++**`cost advise [--since 7d]`** -- Optimisation findings with evidence and what-if savings.+1. Run `node ${CLAUDE_PLUGIN_ROOT}/scripts/advise.mjs --since 7d`+2. Present each finding and its action; do not change settings. Savings are same-token repricings, not quality predictions.++**`cost openrouter key|generation <id>|credits`** -- OpenRouter's own billed figures. Ask the user first; run `node ${CLAUDE_PLUGIN_ROOT}/scripts/openrouter.mjs <cmd> --yes`. The key comes from the environment only.++**`cost local --tok-per-s <n> [--compare <model>]`** -- Local-hardware cost per 1M tokens and break-even utilisation: `node ${CLAUDE_PLUGIN_ROOT}/scripts/local-cost.mjs ...`diff --git a/plugins/ruflo-cost-tracker/data/prices.json b/plugins/ruflo-cost-tracker/data/prices.jsonnew file mode 100644index 0000000000..ff744d0375--- /dev/null+++ b/plugins/ruflo-cost-tracker/data/prices.json@@ -0,0 +1,28 @@+{+ "asOf": "2026-10-03",+ "note": "List prices per 1M tokens. Estimates, not bills: subscriptions, batch, priority tiers and BYOK are not modelled. Edit this file (or point COST_PRICES at your own copy) when a provider changes prices; nothing else hard-codes a rate.",+ "models": [+ { "id": "claude-fable-5-1", "provider": "claude", "match": "fable", "unit": "usd", "input": 10, "output": 50, "cache_write_5m": 12.5, "cache_write_1h": 20, "cache_read": 0.25, "source": "https://platform.claude.com/docs/en/about-claude/pricing" },+ { "id": "claude-opus-5-5", "provider": "claude", "match": "opus-5", "unit": "usd", "input": 4, "output": 20, "cache_write_5m": 5, "cache_write_1h": 8, "cache_read": 0.2, "source": "https://platform.claude.com/docs/en/about-claude/pricing" },+ { "id": "claude-sonnet-5-5", "provider": "claude", "match": "sonnet-5", "unit": "usd", "input": 2, "output": 10, "cache_write_5m": 2.5, "cache_write_1h": 4, "cache_read": 0.2, "source": "https://platform.claude.com/docs/en/about-claude/pricing" },+ { "id": "claude-haiku-4-5", "provider": "claude", "match": "haiku-4", "unit": "usd", "input": 1, "output": 5, "cache_write_5m": 1.25, "cache_write_1h": 2, "cache_read": 0.1, "source": "https://platform.claude.com/docs/en/about-claude/pricing" },+ { "id": "claude-opus-legacy", "provider": "claude", "match": "opus", "unit": "usd", "input": 15, "output": 75, "cache_write_5m": 18.75, "cache_write_1h": 30, "cache_read": 1.5, "approx": true, "source": "family fallback: pre-5 Opus list price" },+ { "id": "claude-sonnet-legacy", "provider": "claude", "match": "sonnet", "unit": "usd", "input": 3, "output": 15, "cache_write_5m": 3.75, "cache_write_1h": 6, "cache_read": 0.3, "approx": true, "source": "family fallback: pre-5 Sonnet list price" },+ { "id": "claude-haiku-legacy", "provider": "claude", "match": "haiku", "unit": "usd", "input": 0.25, "output": 1.25, "cache_write_5m": 0.3, "cache_write_1h": 0.5, "cache_read": 0.03, "approx": true, "source": "family fallback: pre-4.5 Haiku list price" },++ { "id": "gpt-5-nano", "provider": "codex", "match": "gpt-5-nano", "unit": "usd", "input": 0.05, "output": 0.4, "cache_read": 0.005, "source": "https://developers.openai.com/api/docs/pricing" },+ { "id": "gpt-5-mini", "provider": "codex", "match": "gpt-5-mini", "unit": "usd", "input": 0.25, "output": 2, "cache_read": 0.025, "source": "https://developers.openai.com/api/docs/pricing" },+ { "id": "gpt-5.3-codex", "provider": "codex", "match": "gpt-5.3", "unit": "usd", "input": 1.75, "output": 14, "cache_read": 0.175, "source": "https://developers.openai.com/api/docs/pricing" },+ { "id": "gpt-5.2", "provider": "codex", "match": "gpt-5.2", "unit": "usd", "input": 1.75, "output": 14, "cache_read": 0.175, "source": "https://developers.openai.com/api/docs/pricing" },+ { "id": "gpt-5", "provider": "codex", "match": "gpt-5", "re": "^gpt-5(\\.1)?(-codex)?$", "unit": "usd", "input": 1.25, "output": 10, "cache_read": 0.125, "source": "https://developers.openai.com/api/docs/pricing" },++ { "id": "gpt-6-luna", "provider": "codex", "match": "gpt-6-luna", "unit": "credits", "input": 2.5, "output": 12.5, "cache_read": null, "source": "https://learn.chatgpt.com/docs/pricing (Codex credits per 1M tokens; cached rate not published, so cached input is billed at the input rate: an upper bound)" },+ { "id": "gpt-6-sol", "provider": "codex", "match": "gpt-6-sol", "unit": "credits", "input": 50, "output": 250, "cache_read": null, "source": "https://learn.chatgpt.com/docs/pricing (Codex credits per 1M tokens; cached rate not published)" },+ { "id": "gpt-6-astra", "provider": "codex", "match": "gpt-6-astra", "unit": "credits", "input": 250, "output": 1250, "cache_read": null, "source": "https://learn.chatgpt.com/docs/pricing (Codex credits per 1M tokens; cached rate not published)" }+ ],+ "tiers": {+ "note": "Cheaper model that could take over a low-effort turn, per provider; used only for what-if savings in the advisor.",+ "claude": { "downshift": { "claude-fable-5-1": "claude-opus-5-5", "claude-opus-5-5": "claude-sonnet-5-5", "claude-sonnet-5-5": "claude-haiku-4-5" } },+ "codex": { "downshift": { "gpt-6-astra": "gpt-6-sol", "gpt-6-sol": "gpt-6-luna" } }+ }+}diff --git a/plugins/ruflo-cost-tracker/scripts/_ledger.mjs b/plugins/ruflo-cost-tracker/scripts/_ledger.mjsnew file mode 100644index 0000000000..cb569e4f4a--- /dev/null+++ b/plugins/ruflo-cost-tracker/scripts/_ledger.mjs@@ -0,0 +1,142 @@+// _ledger.mjs β provider-agnostic usage rows from the logs agents already write.+//+// Every reader yields rows of ONE shape, so pricing, summaries and the advisor+// never care which tool produced them:+// { provider, model, ts, session, project, input, cache_read, cache_write_5m,+// cache_write_1h, output, reasoning, effort, sidechain }+// `input` is UNCACHED input only; cache reads/writes are their own buckets.+//+// Counting rules, each one a way trackers double-count (all verified against+// real local files, see docs/adrs/0004):+// claude one assistant message is logged once per content block / tool call,+// so rows are de-duplicated by message.id + requestId.+// codex `total_token_usage` is a RUNNING total and `last_token_usage` the+// latest turn; we take the delta between consecutive totals (never both),+// skip events whose total did not move, and treat a total that goes+// DOWN (compaction/reset) as a fresh base. Cached input is a SUBSET of+// input_tokens, so uncached = input - cached. A forked rollout replays+// its parent's events, so events are de-duplicated by timestamp+totals.+// The model comes from the latest `turn_context`, not the token event.+// Nothing is read that is not already on this machine; nothing is sent anywhere.++import { readdirSync, readFileSync, statSync, existsSync } from 'node:fs';+import { join } from 'node:path';+import { homedir } from 'node:os';++const home = () => process.env.HOME || homedir();+export const claudeDir = () => join(process.env.CLAUDE_CONFIG_DIR || join(home(), '.claude'), 'projects');+export const codexDirs = () => (process.env.CODEX_HOME || join(home(), '.codex')).split(',').map(dir => dir.trim()).filter(Boolean);++/** .jsonl files under `root`, at most `depth` directories down, newer than `sinceMs` (by mtime). */+function walk(root, depth, sinceMs, filePrefix = '') {+ const out = [];+ if (!existsSync(root)) return out;+ const visit = (dir, left) => {+ let names;+ try { names = readdirSync(dir, { withFileTypes: true }); } catch { return; }+ for (const entry of names) {+ const path = join(dir, entry.name);+ if (entry.isDirectory()) { if (left > 0) visit(path, left - 1); continue; }+ if (!entry.name.endsWith('.jsonl') || !entry.name.startsWith(filePrefix)) continue;+ try { if (statSync(path).mtimeMs >= sinceMs) out.push(path); } catch { /* vanished */ }+ }+ };+ visit(root, depth);++ return out;+}++const lines = path => { try { return readFileSync(path, 'utf-8').split('\n'); } catch { return []; } };+const parse = text => { if (!text) return null; try { return JSON.parse(text); } catch { return null; } };+const n = value => (Number.isFinite(value) ? value : 0);++/** Claude Code transcripts β rows, de-duplicated. */+export function* claudeRows({ sinceMs = 0 } = {}) {+ const seen = new Set();+ for (const file of walk(claudeDir(), 4, sinceMs)) {+ for (const text of lines(file)) {+ if (!text.includes('"usage"')) continue;+ const line = parse(text);+ const message = line?.message;+ const usage = message?.usage;+ if (usage === undefined || message?.role !== 'assistant' || !message.model || message.model === '<synthetic>') continue;+ const ts = Date.parse(line.timestamp);+ if (!Number.isFinite(ts) || ts < sinceMs) continue;+ const key = `${message.id ?? line.uuid}|${line.requestId ?? ''}`;+ if (seen.has(key)) continue;+ seen.add(key);+ const split = usage.cache_creation;+ const written = n(usage.cache_creation_input_tokens);+ // Without the TTL split every write is priced as the cheaper 5-minute write and the row says so via `unsplit`.+ const w1 = split ? n(split.ephemeral_1h_input_tokens) : 0;+ const w5 = split ? n(split.ephemeral_5m_input_tokens) : written;++ yield {+ provider: 'claude', model: message.model, ts, session: line.sessionId ?? file, project: line.cwd ?? '',+ input: n(usage.input_tokens), cache_read: n(usage.cache_read_input_tokens), cache_write_5m: w5, cache_write_1h: w1,+ output: n(usage.output_tokens), reasoning: n(usage.output_tokens_details?.thinking_tokens),+ effort: line.effort ?? '', sidechain: line.isSidechain === true, unsplit: !split && written > 0,+ };+ }+ }+}++const FIELDS = ['input_tokens', 'cached_input_tokens', 'cache_write_input_tokens', 'output_tokens', 'reasoning_output_tokens'];++/** Codex rollouts (sessions/ and archived_sessions/) β one row per token_count delta. */+export function* codexRows({ sinceMs = 0 } = {}) {+ const seenFiles = new Set();+ const seenEvents = new Set();+ for (const home of codexDirs()) {+ // sessions/ first: when a rollout exists in both places the active copy wins.+ for (const sub of ['sessions', 'archived_sessions']) {+ for (const file of walk(join(home, sub), 4, sinceMs, 'rollout-')) {+ const id = file.replace(/^.*rollout-/, '');+ if (seenFiles.has(id)) continue;+ seenFiles.add(id);+ let model = '';+ let effort = '';+ let session = id;+ let project = '';+ let prev = null;+ for (const text of lines(file)) {+ if (!text.includes('"turn_context"') && !text.includes('"token_count"') && !text.includes('"session_meta"')) continue;+ const line = parse(text);+ const payload = line?.payload;+ if (line?.type === 'session_meta') { session = payload?.id ?? session; project = payload?.cwd ?? project; continue; }+ if (line?.type === 'turn_context') { model = payload?.model ?? model; effort = payload?.effort ?? effort; project = payload?.cwd ?? project; continue; }+ if (payload?.type !== 'token_count' || !payload.info?.total_token_usage) continue;+ const total = payload.info.total_token_usage;+ const ts = Date.parse(line.timestamp);+ if (!Number.isFinite(ts)) continue;+ const delta = {};+ const reset = prev !== null && FIELDS.some(field => n(total[field]) < n(prev[field]));+ for (const field of FIELDS) delta[field] = n(total[field]) - (prev === null || reset ? 0 : n(prev[field]));+ prev = total;+ if (FIELDS.every(field => delta[field] === 0) || ts < sinceMs) continue;+ const key = `${line.timestamp}|${total.input_tokens}|${total.output_tokens}`;+ if (seenEvents.has(key)) continue;+ seenEvents.add(key);+ const cached = delta.cached_input_tokens;+ const written = delta.cache_write_input_tokens;++ yield {+ provider: 'codex', model: model || 'unknown', ts, session, project,+ input: Math.max(0, delta.input_tokens - cached - written), cache_read: cached, cache_write_5m: written, cache_write_1h: 0,+ output: delta.output_tokens, reasoning: delta.reasoning_output_tokens, effort, sidechain: false,+ };+ }+ }+ }+ }+}++export const READERS = { claude: claudeRows, codex: codexRows };++/** Rows for the chosen providers (default all), oldest first. */+export function collect({ providers = Object.keys(READERS), sinceMs = 0 } = {}) {+ const rows = [];+ for (const name of providers) if (READERS[name]) rows.push(...READERS[name]({ sinceMs }));++ return rows.sort((a, b) => a.ts - b.ts);+}diff --git a/plugins/ruflo-cost-tracker/scripts/_pricebook.mjs b/plugins/ruflo-cost-tracker/scripts/_pricebook.mjsnew file mode 100644index 0000000000..d81f53da96--- /dev/null+++ b/plugins/ruflo-cost-tracker/scripts/_pricebook.mjs@@ -0,0 +1,72 @@+// _pricebook.mjs β data-driven pricing for every provider the ledger reads.+//+// Rates live in data/prices.json (dated, sourced, editable; COST_PRICES points+// at another copy). Nothing here hard-codes a rate. Two rules the old+// _prices.mjs broke:+// * a model with no entry is reported UNPRICED, never silently $0;+// * a family fallback (e.g. "sonnet") is marked `approx` so it is never+// presented as an exact figure.+// Prices are list-price estimates, not bills.++import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';++const HERE = dirname(fileURLToPath(import.meta.url));+let book = null;++export function loadBook(path = process.env.COST_PRICES || join(HERE, '..', 'data', 'prices.json')) {+ if (book && !process.env.COST_PRICES) return book;+ book = JSON.parse(readFileSync(path, 'utf-8'));+ return book;+}++/** The most specific entry whose `match` substring is in the model id, or null. */+export function lookup(model, provider) {+ if (!model) return null;+ const id = String(model).toLowerCase();+ let best = null;+ for (const entry of loadBook().models) {+ if (provider && entry.provider !== provider) continue;+ if (entry.re ? !new RegExp(entry.re).test(id) : !id.includes(entry.match) && id !== entry.id) continue;+ if (best === null || entry.match.length > best.match.length) best = entry;+ }+ return best;+}++const per = (tokens, rate) => ((tokens || 0) / 1e6) * (rate || 0);++/**+ * Price one usage record.+ * usage: { input, cache_read, cache_write_5m, cache_write_1h, output }+ * `input` is UNCACHED input only; cache reads/writes are separate buckets+ * (the readers normalise both providers to this shape).+ * Returns { cost, unit, priced, approx, notes[], entry }.+ */+export function priceUsage(model, usage, provider) {+ const entry = lookup(model, provider);+ if (entry === null) return { cost: 0, unit: 'usd', priced: false, approx: false, notes: [`no price for "${model}"`], entry: null };+ const notes = [];+ // A rate the provider does not publish falls back to the input rate (an upper bound) and says so.+ const read = entry.cache_read ?? (notes.push('cache-read rate unpublished: billed at input rate (upper bound)'), entry.input);+ const w5 = entry.cache_write_5m ?? entry.input;+ const w1 = entry.cache_write_1h ?? w5;+ const cost = per(usage.input, entry.input) + per(usage.output, entry.output) + per(usage.cache_read, read)+ + per(usage.cache_write_5m, w5) + per(usage.cache_write_1h, w1);+ if (entry.approx) notes.push(`family fallback (${entry.id}): approximate`);++ return { cost, unit: entry.unit, priced: true, approx: entry.approx === true, notes, entry };+}++/** What the same tokens would cost on another model id (for what-if savings). */+export const reprice = (model, usage, provider) => priceUsage(model, usage, provider);++/** The next cheaper model for this provider, or null. */+export function downshift(model, provider) {+ const entry = lookup(model, provider)+ const map = loadBook().tiers?.[provider]?.downshift ?? {};++ return entry === null ? null : map[entry.id] ?? null;+}++export const bookDate = () => loadBook().asOf;diff --git a/plugins/ruflo-cost-tracker/scripts/_prices.mjs b/plugins/ruflo-cost-tracker/scripts/_prices.mjsindex a35d14696a..068f9abfa1 100644--- a/plugins/ruflo-cost-tracker/scripts/_prices.mjs+++ b/plugins/ruflo-cost-tracker/scripts/_prices.mjs@@ -10,13 +10,22 @@// uses `scripts/*.mjs` for the CLI surface check, but reaches this file// only through the `parses cleanly` step (still valid).-// USD per 1M tokens. Kept in sync with REFERENCE.md "Model pricing" table.+// USD per 1M tokens, per tier. DERIVED from data/prices.json (see _pricebook.mjs),+// the one dated, sourced price table; nothing here hard-codes a rate any more.+// Each tier is the current model of that family; cache_write is the 5-minute rate.// Source of truth for: track.mjs (session cost computation),-// counterfactual.mjs (multi-baseline analysis), bench.mjs (anthropic baseline).+// counterfactual.mjs (multi-baseline analysis). The multi-provider ledger+// (ledger.mjs) prices per model id with the 5m/1h split instead of per tier.+import { loadBook } from './_pricebook.mjs';++const tierOf = (id) => {+ const m = loadBook().models.find((entry) => entry.id === id);+ return { input: m.input, output: m.output, cache_write: m.cache_write_5m, cache_read: m.cache_read };+};export const PRICING = {- haiku: { input: 0.25, output: 1.25, cache_write: 0.30, cache_read: 0.03 },- sonnet: { input: 3.00, output: 15.00, cache_write: 3.75, cache_read: 0.30 },- opus: { input: 15.00, output: 75.00, cache_write: 18.75, cache_read: 1.50 },+ haiku: tierOf('claude-haiku-4-5'),+ sonnet: tierOf('claude-sonnet-5-5'),+ opus: tierOf('claude-opus-5-5'),};/** Map a model id to one of `haiku | sonnet | opus | unknown`. */diff --git a/plugins/ruflo-cost-tracker/scripts/advise.mjs b/plugins/ruflo-cost-tracker/scripts/advise.mjsnew file mode 100644index 0000000000..d7aad0202c--- /dev/null+++ b/plugins/ruflo-cost-tracker/scripts/advise.mjs@@ -0,0 +1,82 @@+#!/usr/bin/env node+// cost-advise β optimisation findings from YOUR logs, each with evidence.+//+// node advise.mjs [--since 7d] [--provider claude|codex|all] [--format json|markdown]+//+// Savings are what-if repricings of tokens you actually used (same tokens, other+// rate); a finding with no defensible figure says "n/a" rather than inventing one.+// Nothing is changed and nothing is sent anywhere.++import { collect } from './_ledger.mjs';+import { priceUsage, downshift, lookup } from './_pricebook.mjs';+import { parseDurationMs } from './_sessions.mjs';++const arg = (name, fallback) => { const i = process.argv.indexOf(`--${name}`); return i > 0 ? process.argv[i + 1] : fallback; };+const sum = (rows, pick) => rows.reduce((total, row) => total + pick(row), 0);+const cost = row => priceUsage(row.model, row, row.provider);++/** Findings, largest saving first. Pure: rows in, findings out. */+export function advise(rows) {+ const out = [];+ const priced = rows.map(row => ({ row, p: cost(row) }));++ // 1. Unpriced models: spend the numbers cannot see.+ const dark = [...new Set(priced.filter(x => !x.p.priced).map(x => x.row.model))];+ if (dark.length > 0) out.push({ id: 'unpriced', unit: null, saving: null, title: `${dark.length} model(s) have no price, so their spend is not counted`, evidence: dark.join(', '), action: 'Add them to data/prices.json (or set COST_PRICES) so totals and advice include them.' });++ // 2. Low cache hit ratio per provider: the largest controllable lever.+ for (const provider of new Set(rows.map(row => row.provider))) {+ const mine = rows.filter(row => row.provider === provider);+ const read = sum(mine, row => row.cache_read);+ const fresh = sum(mine, row => row.input + row.cache_write_5m + row.cache_write_1h);+ if (read + fresh < 5e6 || read / (read + fresh) >= 0.8) continue;+ out.push({ id: `cache-${provider}`, unit: null, saving: null, title: `${provider}: only ${(100 * read / (read + fresh)).toFixed(0)}% of input tokens were cache reads`, evidence: `${read} cached vs ${fresh} fresh input tokens`, action: 'Keep the system prompt, tool list, model and effort stable within a session; avoid mid-session MCP/tool changes; /clear between unrelated tasks.' });+ }++ // 3. 1-hour cache writes that were barely re-read: they cost 2x the 5-minute write.+ const claude = priced.filter(x => x.row.provider === 'claude' && x.p.priced && x.row.cache_write_1h > 0);+ if (claude.length > 0) {+ const w1 = sum(claude, x => x.row.cache_write_1h);+ const reads = sum(claude, x => x.row.cache_read);+ const extra = sum(claude, x => (x.row.cache_write_1h / 1e6) * (x.p.entry.cache_write_1h - x.p.entry.cache_write_5m));+ if (reads / Math.max(1, w1) < 2 && extra > 0.5) out.push({ id: 'ttl-1h', unit: 'usd', saving: extra, title: '1-hour cache writes were not re-read enough to pay back', evidence: `${w1} 1h-written tokens, ${reads} read back (a 1h write needs about two reads to beat a 5m write)`, action: 'Use the 5-minute TTL (CLAUDE_CODE_PROMPT_CACHE_TTL) for bursty or short sessions.' });+ }++ // 4. Sub-agents on a top-tier model: what-if one tier down. (Per-turn output size is NOT used: transcript output counts are placeholders.)+ const side = new Map();+ for (const { row, p } of priced) {+ if (!row.sidechain || !p.priced) continue;+ const down = downshift(row.model, row.provider);+ if (down === null) continue;+ const there = priceUsage(down, row, row.provider);+ const s = side.get(row.model) ?? { from: row.model, to: down, now: 0, then: 0, n: 0, unit: p.unit };+ s.now += p.cost; s.then += there.cost; s.n += 1;+ side.set(row.model, s);+ }+ for (const s of side.values()) if (s.now - s.then > 1) out.push({ id: `subagents-${s.from}`, unit: s.unit, saving: s.now - s.then, title: `Sub-agents ran on ${s.from}`, evidence: `${s.n} sub-agent messages; same tokens on ${s.to} would cost ${s.then.toFixed(2)} vs ${s.now.toFixed(2)}`, action: `Give simple sub-agents model: ${lookup(s.to)?.id ?? s.to}; keep the top tier for the lead. Quality is not measured here: spot-check before switching.` });++ // 5. Codex reasoning share: reasoning tokens bill as output.+ const codex = rows.filter(row => row.provider === 'codex' && row.output > 0);+ const out_ = sum(codex, row => row.output);+ if (codex.length > 20 && sum(codex, row => row.reasoning) / out_ > 0.7) out.push({ id: 'codex-effort', unit: null, saving: null, title: `Codex: ${(100 * sum(codex, row => row.reasoning) / out_).toFixed(0)}% of output tokens are reasoning`, evidence: `${sum(codex, row => row.reasoning)} of ${out_} output tokens`, action: 'Try model_reasoning_effort = "low" or "medium" for routine edits; keep high for hard problems. Savings are not estimated: no measured delta exists.' });++ // 6. Context bloat: sessions whose average turn re-reads a very large cached prefix.+ const bySession = new Map();+ for (const row of rows) { const s = bySession.get(row.session) ?? { cache: 0, n: 0, provider: row.provider }; s.cache += row.cache_read; s.n += 1; bySession.set(row.session, s); }+ const heavy = [...bySession.entries()].filter(([, s]) => s.n >= 30 && s.cache / s.n > 400_000).sort((a, b) => b[1].cache - a[1].cache).slice(0, 3);+ if (heavy.length > 0) out.push({ id: 'context-bloat', unit: null, saving: null, title: `${heavy.length} long session(s) re-read a very large context every turn`, evidence: heavy.map(([id, s]) => `${String(id).slice(0, 8)} ${s.provider}: ${Math.round(s.cache / s.n / 1000)}k cached tokens/turn over ${s.n} turns`).join('; '), action: '/compact at a natural break while the cache is warm, or /clear between tasks; move workflow text from CLAUDE.md into skills.' });++ return out.sort((a, b) => (b.saving ?? -1) - (a.saving ?? -1));+}++const fmt = f => (f.saving === null ? 'saving n/a' : `up to ${f.unit === 'usd' ? '$' : ''}${f.saving.toFixed(2)}${f.unit === 'usd' ? '' : ' credits'} over the window`);++if (import.meta.url === `file://${process.argv[1]}`) {+ const spec = arg('since', '7d');+ const sinceMs = spec === 'all' ? 0 : Date.now() - (parseDurationMs(spec) ?? 7 * 86_400_000);+ const providers = arg('provider', 'all') === 'all' ? undefined : [arg('provider')];+ const findings = advise(collect({ providers, sinceMs }));++ if (arg('format', 'markdown') === 'json') console.log(JSON.stringify({ since: spec, findings }, null, 2));+ else console.log([`# Cost advice (${spec})`, '', ...(findings.length === 0 ? ['No findings: nothing in this window crosses a threshold.'] : findings.flatMap((f, i) => [`${i + 1}. **${f.title}** β ${fmt(f)}`, ` - evidence: ${f.evidence}`, ` - do: ${f.action}`])), '', 'What-if figures reprice the same tokens at another rate; they do not predict quality or future usage.'].join('\n'));+}diff --git a/plugins/ruflo-cost-tracker/scripts/ledger.mjs b/plugins/ruflo-cost-tracker/scripts/ledger.mjsnew file mode 100644index 0000000000..c5a3884a2c--- /dev/null+++ b/plugins/ruflo-cost-tracker/scripts/ledger.mjs@@ -0,0 +1,80 @@+#!/usr/bin/env node+// cost-ledger β one cost view across Claude Code and Codex logs on this machine.+//+// node ledger.mjs [--since 7d|24h|all] [--provider claude|codex|all] [--format json|markdown] [--advise]+// --advise adds the optimisation findings (advise.mjs) from the same single pass over the logs.+//+// Reads local logs only; sends nothing anywhere. Prices come from data/prices.json+// (dated). USD and Codex credits are NEVER added together, and an unpriced model+// is listed, not counted as $0.++import { collect } from './_ledger.mjs';+import { priceUsage, bookDate } from './_pricebook.mjs';+import { parseDurationMs } from './_sessions.mjs';+import { advise } from './advise.mjs';++const arg = (name, fallback) => { const i = process.argv.indexOf(`--${name}`); return i > 0 ? process.argv[i + 1] : fallback; };++/** Aggregate priced rows. Exported so advise.mjs and tests share one definition. */+export function summarise(rows) {+ const out = { totals: {}, byProvider: {}, byModel: {}, byDay: {}, unpriced: {}, approx: [], cache: {}, rows: rows.length };+ const add = (bucket, key, unit, cost) => { bucket[key] ??= {}; bucket[key][unit] = (bucket[key][unit] ?? 0) + cost; };+ const tok = (bucket, key, row) => {+ const t = (bucket[key] ??= { input: 0, cache_read: 0, cache_write: 0, output: 0, messages: 0 });+ t.input += row.input; t.cache_read += row.cache_read; t.cache_write += row.cache_write_5m + row.cache_write_1h; t.output += row.output; t.messages += 1;+ };+ const tokens = {};+ const approx = new Set();+ for (const row of rows) {+ const p = priceUsage(row.model, row, row.provider);+ const day = new Date(row.ts).toISOString().slice(0, 10);+ tok(tokens, `${row.provider}|${row.model}`, row);+ if (!p.priced) { const u = (out.unpriced[row.model] ??= { provider: row.provider, messages: 0, tokens: 0 }); u.messages += 1; u.tokens += row.input + row.cache_read + row.output; continue; }+ if (p.approx) approx.add(row.model);+ add(out.byProvider, row.provider, p.unit, p.cost);+ add(out.byModel, `${row.provider}|${row.model}`, p.unit, p.cost);+ add(out.byDay, day, p.unit, p.cost);+ out.totals[p.unit] = (out.totals[p.unit] ?? 0) + p.cost;+ }+ out.approx = [...approx];+ out.tokens = tokens;+ for (const provider of new Set(rows.map(row => row.provider))) {+ const mine = rows.filter(row => row.provider === provider);+ const read = mine.reduce((sum, row) => sum + row.cache_read, 0);+ const fresh = mine.reduce((sum, row) => sum + row.input + row.cache_write_5m + row.cache_write_1h, 0);+ out.cache[provider] = { hitRatio: read + fresh > 0 ? read / (read + fresh) : null, read, fresh };+ }++ return out;+}++const money = (value, unit) => (unit === 'usd' ? `$${value.toFixed(2)}` : `${value.toFixed(0)} credits`);++function markdown(summary, meta) {+ const lines = [`# Cost ledger (${meta.since}, prices as of ${meta.priceDate})`, ''];+ lines.push(`Totals: ${Object.entries(summary.totals).map(([unit, value]) => money(value, unit)).join(' + ') || 'n/a'} Β· ${summary.rows} messages Β· estimates at list price, not bills`, '');+ lines.push('| Provider Β· model | Cost | Msgs | Input | Cache read | Cache write | Output |', '|---|---|---|---|---|---|---|');+ for (const [key, cost] of Object.entries(summary.byModel).sort((a, b) => Object.values(b[1])[0] - Object.values(a[1])[0])) {+ const t = summary.tokens[key];+ lines.push(`| ${key.replace('|', ' Β· ')} | ${Object.entries(cost).map(([unit, value]) => money(value, unit)).join(', ')} | ${t.messages} | ${t.input} | ${t.cache_read} | ${t.cache_write} | ${t.output} |`);+ }+ for (const [provider, cache] of Object.entries(summary.cache)) lines.push('', `Cache hit ratio Β· ${provider}: ${cache.hitRatio === null ? 'n/a' : `${(cache.hitRatio * 100).toFixed(1)}%`}`);+ const dark = Object.entries(summary.unpriced);+ if (dark.length > 0) lines.push('', `Unpriced (NOT counted as $0): ${dark.map(([model, u]) => `${model} (${u.messages} msgs)`).join(', ')} β add them to data/prices.json`);+ if (summary.approx.length > 0) lines.push('', `Approximate (family fallback price): ${summary.approx.join(', ')}`);+ lines.push('', 'Claude output tokens come from the transcript, which can under-count streamed output; /usage is authoritative for the live session.');++ return lines.join('\n');+}++if (import.meta.url === `file://${process.argv[1]}`) {+ const sinceSpec = arg('since', '7d');+ const sinceMs = sinceSpec === 'all' ? 0 : Date.now() - (parseDurationMs(sinceSpec) ?? 7 * 86_400_000);+ const providers = arg('provider', 'all') === 'all' ? undefined : [arg('provider')];+ const rows = collect({ providers, sinceMs });+ const summary = summarise(rows);+ const meta = { since: sinceSpec, priceDate: bookDate() };+ const findings = process.argv.includes('--advise') ? advise(rows) : undefined;++ console.log(arg('format', 'markdown') === 'json' ? JSON.stringify({ ...meta, ...summary, ...(findings && { findings }) }, null, 2) : markdown(summary, meta));+}diff --git a/plugins/ruflo-cost-tracker/scripts/local-cost.mjs b/plugins/ruflo-cost-tracker/scripts/local-cost.mjsnew file mode 100644index 0000000000..a9ed835357--- /dev/null+++ b/plugins/ruflo-cost-tracker/scripts/local-cost.mjs@@ -0,0 +1,54 @@+#!/usr/bin/env node+// cost-local β what a token costs on hardware you own, and when it beats an API.+//+// node local-cost.mjs --tok-per-s 80 [--busy 0.25] [--watts-idle 80] [--watts-active 350]+// [--kwh 0.15] [--hw-price 3000] [--life-years 3] [--resale 0.2]+// [--compare claude-haiku-4-5] [--out-share 0.25] [--format json|markdown]+//+// Every input is yours and every output an ESTIMATE: throughput and watts are not+// measured here. Cost splits into FIXED (amortisation + idle power, paid busy or+// not) and MARGINAL (extra watts while generating). The number that decides the+// answer is utilisation, so it is always shown at several busy fractions.++import { lookup } from './_pricebook.mjs';++const arg = (name, fallback) => { const i = process.argv.indexOf(`--${name}`); return i > 0 ? Number(process.argv[i + 1]) : fallback; };+const text = name => { const i = process.argv.indexOf(`--${name}`); return i > 0 ? process.argv[i + 1] : undefined; };++/** USD per 1M generated tokens at a busy fraction (0β1). Pure. */+export function localCost({ wattsIdle, wattsActive, kwh, hwPrice, lifeYears, resale, tokPerS }, busy) {+ const amortPerHour = (hwPrice * (1 - resale)) / (lifeYears * 8760);+ const fixedPerHour = amortPerHour + (wattsIdle / 1000) * kwh;+ const marginalPerHour = (Math.max(0, wattsActive - wattsIdle) / 1000) * kwh;+ const tokensPerHour = busy * tokPerS * 3600;++ return { fixedPerHour, marginalPerHour, perMtok: tokensPerHour > 0 ? ((fixedPerHour + busy * marginalPerHour) / tokensPerHour) * 1e6 : null };+}++/** The busy fraction above which local beats `apiPerMtok`, or null if it never does at this throughput. */+export function breakEvenBusy(config, apiPerMtok) {+ const { fixedPerHour, marginalPerHour } = localCost(config, 1);+ const denominator = (apiPerMtok * config.tokPerS * 3600) / 1e6 - marginalPerHour;++ return denominator > 0 && fixedPerHour / denominator <= 1 ? fixedPerHour / denominator : null;+}++if (import.meta.url === `file://${process.argv[1]}`) {+ const config = { wattsIdle: arg('watts-idle', 80), wattsActive: arg('watts-active', 350), kwh: arg('kwh', 0.15), hwPrice: arg('hw-price', 3000), lifeYears: arg('life-years', 3), resale: arg('resale', 0.2), tokPerS: arg('tok-per-s', NaN) };+ if (!Number.isFinite(config.tokPerS) || config.tokPerS <= 0) { console.error('usage: local-cost.mjs --tok-per-s <measured generation speed> [options]'); process.exit(2); }+ const busy = arg('busy', 0.25);+ const entry = lookup(text('compare') ?? '');+ const share = arg('out-share', 0.25);+ // Blended API price per 1M tokens for a mix of `share` output and the rest input.+ const api = entry === null || entry.unit !== 'usd' ? null : entry.input * (1 - share) + entry.output * share;+ const steps = [0.05, 0.25, 0.5, 1].map(b => ({ busy: b, ...localCost(config, b) }));+ const result = { config, busy, atBusy: localCost(config, busy), sensitivity: steps, compare: api === null ? null : { model: entry.id, blendedPerMtok: api, outShare: share, breakEvenBusy: breakEvenBusy(config, api) }, note: 'Estimates from the inputs given; throughput and power are not measured. A local model and a frontier API are different products: compare against a same-capability hosted model.' };++ if (text('format') === 'json') console.log(JSON.stringify(result, null, 2));+ else {+ const out = [`# Local cost estimate`, '', `Fixed: $${result.atBusy.fixedPerHour.toFixed(3)}/h (amortisation + idle power) Β· marginal: $${result.atBusy.marginalPerHour.toFixed(3)}/h while generating`, '', '| Busy | $ per 1M tokens |', '|---|---|', ...steps.map(s => `| ${s.busy * 100}% | ${s.perMtok === null ? 'n/a' : `$${s.perMtok.toFixed(2)}`} |`)];+ if (result.compare) out.push('', `Against ${result.compare.model} (blended $${api.toFixed(2)}/1M at ${share * 100}% output): ${result.compare.breakEvenBusy === null ? 'local never wins on cost at this throughput' : `local wins above ${(result.compare.breakEvenBusy * 100).toFixed(0)}% busy`}.`);+ out.push('', result.note);+ console.log(out.join('\n'));+ }+}diff --git a/plugins/ruflo-cost-tracker/scripts/openrouter.mjs b/plugins/ruflo-cost-tracker/scripts/openrouter.mjsnew file mode 100644index 0000000000..874719ae7c--- /dev/null+++ b/plugins/ruflo-cost-tracker/scripts/openrouter.mjs@@ -0,0 +1,51 @@+#!/usr/bin/env node+// cost-openrouter β what OpenRouter says you spent. Network, so it asks first.+//+// OPENROUTER_API_KEY=β¦ node openrouter.mjs key --yes per-key limit, remaining, usage today/week/month+// OPENROUTER_API_KEY=β¦ node openrouter.mjs generation <id> --yes one request's real billed cost + tokens+// OPENROUTER_MANAGEMENT_KEY=β¦ node openrouter.mjs credits --yes account credits (management key only)+//+// Rules: without --yes nothing is sent (the command prints what it WOULD call);+// the only host is openrouter.ai; the key is read from the environment and is+// never printed, logged or written. `usage.cost` / `total_cost` from OpenRouter is+// the authoritative figure: do not recompute it from a price list.++const HOST = 'https://openrouter.ai/api/v1';+const [command, ...rest] = process.argv.slice(2);+const yes = process.argv.includes('--yes');+const id = rest.find(item => !item.startsWith('--'));++const PLAN = {+ key: { path: '/key', env: 'OPENROUTER_API_KEY', pick: ['label', 'limit', 'limit_remaining', 'limit_reset', 'usage', 'usage_daily', 'usage_weekly', 'usage_monthly', 'byok_usage', 'is_free_tier', 'free_model_daily_requests'] },+ generation: { path: `/generation?id=${encodeURIComponent(id ?? '')}`, env: 'OPENROUTER_API_KEY', pick: ['id', 'model', 'provider_name', 'router', 'total_cost', 'usage', 'upstream_inference_cost', 'cache_discount', 'is_byok', 'tokens_prompt', 'tokens_completion', 'native_tokens_prompt', 'native_tokens_completion', 'native_tokens_reasoning', 'native_tokens_cached', 'service_tier', 'cancelled', 'finish_reason', 'session_id', 'created_at'] },+ credits: { path: '/credits', env: 'OPENROUTER_MANAGEMENT_KEY', pick: ['total_credits', 'total_usage'] },+};++const plan = PLAN[command];+if (plan === undefined || (command === 'generation' && id === undefined)) {+ console.error('usage: openrouter.mjs key|credits|generation <id> --yes');+ process.exit(2);+}+if (!yes) {+ console.log(`Would GET ${HOST}${plan.path} using $${plan.env}. Nothing was sent. Re-run with --yes to allow this one request.`);+ process.exit(0);+}+const key = process.env[plan.env];+if (!key) { console.error(`${plan.env} is not set; export it in your shell (never paste a key into a prompt or a file).`); process.exit(2); }++try {+ const response = await fetch(`${HOST}${plan.path}`, { headers: { authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(15_000) });+ if (!response.ok) {+ const hint = response.status === 403 && command === 'credits' ? ' (credits needs a management key, not a normal one)' : response.status === 404 && command === 'generation' ? ' (a just-finished request can take a moment to appear; retry shortly)' : '';+ console.error(`OpenRouter answered ${response.status}${hint}`);+ process.exit(1);+ }+ const body = (await response.json()).data ?? {};+ const out = {};+ for (const field of plan.pick) if (body[field] !== undefined) out[field] = body[field];+ console.log(JSON.stringify(out, null, 2));+} catch (error) {+ // Never echo the request: only the error class and message, which carry no headers.+ console.error(`request failed: ${error?.name ?? 'error'}`);+ process.exit(1);+}diff --git a/plugins/ruflo-cost-tracker/scripts/smoke.sh b/plugins/ruflo-cost-tracker/scripts/smoke.shindex 9dd6724c6d..ec2cd4e5b2 100755--- a/plugins/ruflo-cost-tracker/scripts/smoke.sh+++ b/plugins/ruflo-cost-tracker/scripts/smoke.sh@@ -1,5 +1,5 @@#!/usr/bin/env bash-# Structural smoke test for ruflo-cost-tracker v0.26.3.+# Structural smoke test for ruflo-cost-tracker v0.27.0.set -uROOT="$(cd "$(dirname "$0")/.." && pwd)"PASS=0@@ -8,10 +8,10 @@ step() { printf "β %s ... " "$1"; }ok() { printf "PASS\n"; PASS=$((PASS+1)); }bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }-step "1. plugin.json declares 0.26.3 with new keywords"+step "1. plugin.json declares 0.27.0 with new keywords"v=$(grep -E '"version"' "$ROOT/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)-if [[ "$v" != "0.26.3" ]]; then- bad "expected 0.26.3, got '$v'"+if [[ "$v" != "0.27.0" ]]; then+ bad "expected 0.27.0, got '$v'"elsemiss=""for k in namespace-routing mcp agentic-flow agent-booster tier1-routing model-routing benchmarking verified telemetry budget projection forecast counterfactual drift-detection trend-alert anomaly-detection outlier-detection health-check composite-gate auto-track stop-hook snapshot-diff pr-regression git-context traceability drill-down per-message; do@@ -654,5 +654,17 @@ step "44. plugin.json parses + version sentinel matches step 1"node -e "JSON.parse(require('fs').readFileSync('$ROOT/.claude-plugin/plugin.json'))" 2>/dev/null \&& ok || bad "plugin.json invalid JSON"+step "45. multi-provider ledger: runtime counting-rule tests + price book + new skills"+miss=""+node "$ROOT/scripts/test-ledger.mjs" >/dev/null 2>&1 || miss="$miss test-ledger-failed"+node -e "const b=JSON.parse(require('fs').readFileSync('$ROOT/data/prices.json'));if(!b.asOf||!b.models.length||b.models.some(m=>!m.source||!m.unit))process.exit(1)" 2>/dev/null || miss="$miss price-book-invalid"+for s in cost-ledger cost-advise cost-openrouter cost-local; do+ f="$ROOT/skills/$s/SKILL.md"+ [[ -f "$f" ]] || { miss="$miss missing-$s"; continue; }+ for k in 'name:' 'description:' 'allowed-tools: Bash'; do grep -q "^$k" "$f" || miss="$miss $s-no-$k"; done+done+grep -q -- '--yes' "$ROOT/scripts/openrouter.mjs" || miss="$miss openrouter-no-consent-gate"+[[ -z "$miss" ]] && ok || bad "$miss"+printf "\n%s passed, %s failed\n" "$PASS" "$FAIL"[[ $FAIL -eq 0 ]] || exit 1diff --git a/plugins/ruflo-cost-tracker/scripts/test-ledger.mjs b/plugins/ruflo-cost-tracker/scripts/test-ledger.mjsnew file mode 100644index 0000000000..91c5d4ba0b--- /dev/null+++ b/plugins/ruflo-cost-tracker/scripts/test-ledger.mjs@@ -0,0 +1,99 @@+#!/usr/bin/env node+// Runtime test for the multi-provider ledger: builds throwaway Claude and Codex+// logs and asserts every counting rule that trackers commonly get wrong.+// node plugins/ruflo-cost-tracker/scripts/test-ledger.mjs++import assert from 'node:assert/strict';+import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs';+import { spawnSync } from 'node:child_process';+import { tmpdir } from 'node:os';+import { join, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';++const HERE = dirname(fileURLToPath(import.meta.url));+const tmp = mkdtempSync(join(tmpdir(), 'ledger-'));+process.env.CLAUDE_CONFIG_DIR = join(tmp, 'claude');+process.env.CODEX_HOME = join(tmp, 'codex');+mkdirSync(join(process.env.CLAUDE_CONFIG_DIR, 'projects', 'p'), { recursive: true });+mkdirSync(join(process.env.CODEX_HOME, 'sessions', '2026', '10', '03'), { recursive: true });+mkdirSync(join(process.env.CODEX_HOME, 'archived_sessions'), { recursive: true });++const { collect } = await import('./_ledger.mjs');+const { priceUsage, lookup } = await import('./_pricebook.mjs');+const { summarise } = await import('./ledger.mjs');+const { advise } = await import('./advise.mjs');+const { localCost, breakEvenBusy } = await import('./local-cost.mjs');++const jsonl = (path, items) => writeFileSync(path, items.map(item => JSON.stringify(item)).join('\n') + '\n');+const T = i => `2026-10-03T00:00:${String(i).padStart(2, '0')}.000Z`;+let failed = 0;+const test = (name, fn) => { try { fn(); console.log(`ok ${name}`); } catch (error) { failed += 1; console.log(`FAIL ${name}\n ${error.message}`); } };++// ββ Claude: one message logged three times (content blocks) counts once; TTL split is priced.+const message = (id, extra = {}) => ({ type: 'assistant', sessionId: 's1', cwd: '/x', requestId: `r-${id}`, timestamp: T(1), message: { id, role: 'assistant', model: 'claude-opus-5-5', usage: { input_tokens: 1000, output_tokens: 500, cache_read_input_tokens: 10000, cache_creation_input_tokens: 2000, cache_creation: { ephemeral_5m_input_tokens: 500, ephemeral_1h_input_tokens: 1500 } } }, ...extra });+jsonl(join(process.env.CLAUDE_CONFIG_DIR, 'projects', 'p', 's1.jsonl'), [message('m1'), message('m1'), message('m1'), message('m2', { isSidechain: true }), { type: 'user', message: { role: 'user' } }, { type: 'assistant', timestamp: T(2), message: { id: 'syn', role: 'assistant', model: '<synthetic>', usage: { input_tokens: 9 } } }]);++// ββ Codex: running totals β deltas, cached β input, a reset, a replayed (forked) event, model from turn_context.+const total = (input, cached, output) => ({ input_tokens: input, cached_input_tokens: cached, cache_write_input_tokens: 0, output_tokens: output, reasoning_output_tokens: 0, total_tokens: input + output });+const event = (i, usage) => ({ timestamp: T(i), type: 'event_msg', payload: { type: 'token_count', info: { total_token_usage: usage } } });+const rollout = [+ { type: 'session_meta', payload: { id: 'cx1', cwd: '/y' } },+ { type: 'turn_context', payload: { model: 'gpt-5.3-codex', effort: 'high' } },+ event(10, total(1000, 800, 100)),+ event(10, total(1000, 800, 100)), // identical running total: no new usage+ event(11, total(3000, 2600, 300)),+ event(12, total(500, 400, 50)), // total went DOWN: compaction/reset, a fresh base+];+jsonl(join(process.env.CODEX_HOME, 'sessions', '2026', '10', '03', 'rollout-a.jsonl'), rollout);+jsonl(join(process.env.CODEX_HOME, 'archived_sessions', 'rollout-a.jsonl'), rollout); // same rollout archived: active copy wins+jsonl(join(process.env.CODEX_HOME, 'sessions', '2026', '10', '03', 'rollout-fork.jsonl'), [{ type: 'turn_context', payload: { model: 'gpt-5.3-codex' } }, event(10, total(1000, 800, 100)), event(11, total(3000, 2600, 300))]); // replayed parent history++const rows = collect();+const claude = rows.filter(row => row.provider === 'claude');+const codex = rows.filter(row => row.provider === 'codex');++test('claude: duplicate message ids count once; <synthetic> and non-assistant lines are skipped', () => assert.equal(claude.length, 2));+test('claude: 5m and 1h cache writes are priced separately', () => {+ const r = claude[0];+ assert.equal(r.cache_write_5m, 500); assert.equal(r.cache_write_1h, 1500);+ const p = priceUsage(r.model, r, 'claude');+ const expected = (1000 * 4 + 500 * 20 + 10000 * 0.2 + 500 * 5 + 1500 * 8) / 1e6;+ assert.ok(Math.abs(p.cost - expected) < 1e-9, `${p.cost} vs ${expected}`);+});+test('claude: sidechain flag is kept', () => assert.equal(claude.filter(row => row.sidechain).length, 1));+test('codex: deltas of the running total, replay and archived copies de-duplicated', () => {+ assert.equal(codex.length, 3);+ assert.deepEqual(codex.map(row => row.input + row.cache_read), [1000, 2000, 500]);+});+test('codex: cached input is a subset (uncached = input - cached)', () => assert.deepEqual([codex[0].input, codex[0].cache_read], [200, 800]));+test('codex: model comes from turn_context', () => assert.equal(codex[0].model, 'gpt-5.3-codex'));+test('price: an unknown model is UNPRICED, not $0', () => assert.equal(priceUsage('mystery-9', { input: 1e6 }, 'codex').priced, false));+test('price: gpt-5.6-sol is not mistaken for gpt-5', () => assert.equal(lookup('gpt-5.6-sol', 'codex'), null));+test('price: family fallback is flagged approximate', () => assert.equal(priceUsage('claude-sonnet-3-5', { input: 1e6 }, 'claude').approx, true));+test('price: credits and usd never merge', () => {+ const s = summarise([{ ...claude[0] }, { provider: 'codex', model: 'gpt-6-sol', ts: 1, session: 'z', input: 1e6, cache_read: 0, cache_write_5m: 0, cache_write_1h: 0, output: 0, reasoning: 0 }]);+ assert.ok(s.totals.usd > 0 && s.totals.credits === 50);+});+test('advise: sub-agent on a top tier reports a what-if saving; unpriced model is surfaced', () => {+ const big = { ...claude[1], input: 5e6, output: 5e6 };+ const f = advise([big, { ...big, model: 'mystery-9' }]);+ assert.ok(f.some(x => x.id.startsWith('subagents-') && x.saving > 1));+ assert.ok(f.some(x => x.id === 'unpriced'));+});+test('local: break-even busy fraction matches the cost curve', () => {+ const config = { wattsIdle: 80, wattsActive: 350, kwh: 0.15, hwPrice: 3000, lifeYears: 3, resale: 0.2, tokPerS: 80 };+ const b = breakEvenBusy(config, 2);+ assert.ok(Math.abs(localCost(config, b).perMtok - 2) < 1e-6);+ assert.equal(breakEvenBusy({ ...config, tokPerS: 0.1 }, 2), null);+});+test('openrouter: without --yes nothing is sent and no key is needed', () => {+ const r = spawnSync(process.execPath, [join(HERE, 'openrouter.mjs'), 'key'], { encoding: 'utf-8', env: { PATH: process.env.PATH } });+ assert.equal(r.status, 0); assert.match(r.stdout, /Nothing was sent/);+});+test('openrouter: a key in the environment is never echoed', () => {+ const r = spawnSync(process.execPath, [join(HERE, 'openrouter.mjs'), 'key'], { encoding: 'utf-8', env: { PATH: process.env.PATH, OPENROUTER_API_KEY: 'sk-or-SECRET123' } });+ assert.ok(!(r.stdout + r.stderr).includes('SECRET123'));+});++if (failed > 0) { console.log(`\n${failed} failed`); process.exit(1); }+console.log('\nall passed');diff --git a/plugins/ruflo-cost-tracker/skills/cost-advise/SKILL.md b/plugins/ruflo-cost-tracker/skills/cost-advise/SKILL.mdnew file mode 100644index 0000000000..da850947d3--- /dev/null+++ b/plugins/ruflo-cost-tracker/skills/cost-advise/SKILL.md@@ -0,0 +1,20 @@+---+name: cost-advise+description: Optimisation findings from your own Claude Code and Codex logs β low cache hit ratio, 1-hour cache writes that did not pay back, sub-agents on a top-tier model, Codex reasoning share, bloated sessions β each with evidence and a what-if saving. Use when asked how to cut spend or why it is high.+argument-hint: "[--since 7d] [--provider claude|codex|all] [--format json|markdown]"+allowed-tools: Bash+---++# Cost Advise++```bash+node ${CLAUDE_PLUGIN_ROOT}/scripts/advise.mjs --since 7d+```++## Rules for presenting findings++- Savings are **what-if repricings of the same tokens** at another rate. They say nothing about quality; tell the user to spot-check before switching a model.+- A finding with `saving n/a` has no defensible number (no measured delta exists). Do not invent one.+- Do not change settings, models or CLAUDE.md on the user's behalf; present the action and let them choose.+- Prefer the largest controllable lever first: cache discipline, then model tier for sub-agents, then reasoning effort, then context size.+- Pair with `cost-ledger` for the totals and `cost-session` to drill into one expensive session.diff --git a/plugins/ruflo-cost-tracker/skills/cost-ledger/SKILL.md b/plugins/ruflo-cost-tracker/skills/cost-ledger/SKILL.mdnew file mode 100644index 0000000000..20ed594b47--- /dev/null+++ b/plugins/ruflo-cost-tracker/skills/cost-ledger/SKILL.md@@ -0,0 +1,27 @@+---+name: cost-ledger+description: One cost view across Claude Code and Codex on this machine β spend, tokens, cache hit ratio per provider and model, with unpriced models flagged. Use when asked "what did I spend", "how much did Codex cost", or to compare providers. Local logs only, nothing is sent.+argument-hint: "[--since 7d|24h|all] [--provider claude|codex|all] [--format json|markdown]"+allowed-tools: Bash+---++# Cost Ledger++Reads the logs the agents already wrote (`~/.claude/projects`, `$CODEX_HOME` or `~/.codex`) and prices them from `data/prices.json` (dated, editable).++## Run++```bash+node ${CLAUDE_PLUGIN_ROOT}/scripts/ledger.mjs --since 7d+node ${CLAUDE_PLUGIN_ROOT}/scripts/ledger.mjs --provider codex --format json+```++## Read the result correctly++- **USD and Codex credits are never added.** GPT-6 Codex models are priced in credits; their cached-input rate is unpublished, so the figure is an upper bound.+- **Estimates at list price, not bills.** Subscriptions bill by window, not by token. `/usage` is authoritative for the live Claude session; the Console or provider dashboard is authoritative for invoices.+- **Unpriced models are listed, never counted as $0.** Say so, and offer to add them to `data/prices.json`.+- **Counting rules** (why numbers differ from naive sums): Claude messages are de-duplicated by `message.id + requestId`; Codex uses deltas of the running `total_token_usage` (never also `last_token_usage`), cached input is a subset of input, and forked rollouts are de-duplicated.+- Claude transcript output tokens can under-count streamed output.++If the log directory is missing, say so; do not invent numbers.diff --git a/plugins/ruflo-cost-tracker/skills/cost-local/SKILL.md b/plugins/ruflo-cost-tracker/skills/cost-local/SKILL.mdnew file mode 100644index 0000000000..65f29da6ec--- /dev/null+++ b/plugins/ruflo-cost-tracker/skills/cost-local/SKILL.md@@ -0,0 +1,21 @@+---+name: cost-local+description: Cost per million tokens on hardware you own (Ollama, llama.cpp, vLLM, LM Studio) from watts, electricity price, hardware price and measured tokens/second, and the utilisation at which local beats a hosted model. Use for local-vs-API break-even questions.+argument-hint: "--tok-per-s <n> [--busy 0.25] [--compare <model>] [--format json|markdown]"+allowed-tools: Bash+---++# Cost Local++```bash+node ${CLAUDE_PLUGIN_ROOT}/scripts/local-cost.mjs --tok-per-s 80 --busy 0.25 --compare claude-haiku-4-5+```++Inputs (all the user's): `--watts-idle`, `--watts-active`, `--kwh`, `--hw-price`, `--life-years`, `--resale`. `--tok-per-s` is required and must be a **measured** generation speed.++## Rules++- Cost = **fixed** (amortisation + idle power, paid busy or not) + **marginal** (extra watts while generating). Utilisation decides the answer: always show the table at 5/25/50/100% busy.+- It is an estimate from the inputs; say so. Nothing is measured.+- Compare against a same-capability hosted model, not a frontier one; price alone is a poor reason to buy a GPU for sporadic use.+- Read real counts from the server (Ollama `eval_count`/`prompt_eval_count` on the native API, llama.cpp `timings`, vLLM `/metrics`), not the lossy OpenAI-compatible `usage`, and count model reloads (`load_duration`) as overhead.diff --git a/plugins/ruflo-cost-tracker/skills/cost-openrouter/SKILL.md b/plugins/ruflo-cost-tracker/skills/cost-openrouter/SKILL.mdnew file mode 100644index 0000000000..6ed2f0488a--- /dev/null+++ b/plugins/ruflo-cost-tracker/skills/cost-openrouter/SKILL.md@@ -0,0 +1,25 @@+---+name: cost-openrouter+description: OpenRouter real spend β key limit and usage today/week/month, one request's billed cost by generation id, account credits. Use when asked what OpenRouter charged or whether a key is near its limit. Network and API key: asks first.+argument-hint: "key | generation <id> | credits"+allowed-tools: Bash+---++# Cost OpenRouter++Network skill. **Ask the user before running it**, and run it only with their yes.++```bash+node ${CLAUDE_PLUGIN_ROOT}/scripts/openrouter.mjs key --yes+node ${CLAUDE_PLUGIN_ROOT}/scripts/openrouter.mjs generation gen-abc123 --yes+node ${CLAUDE_PLUGIN_ROOT}/scripts/openrouter.mjs credits --yes+```++## Rules++- Without `--yes` the script prints the call it would make and sends nothing.+- The key comes from `OPENROUTER_API_KEY` (credits: `OPENROUTER_MANAGEMENT_KEY`). Never ask the user to paste a key, never print, log or write one.+- OpenRouter's `usage.cost` / `total_cost` is **authoritative**; do not recompute it from list prices.+- `credits` needs a management key (a normal key returns 403). A fresh generation can 404 briefly: retry.+- BYOK rows carry the 5% OpenRouter fee in `usage`, the provider's charge in `upstream_inference_cost`: show both, labelled.+- Fallback and `openrouter/auto` can change the billed model: report `model` and `provider_name` as returned.diff --git a/v3/docs/adr/ADR-437-console-cost-across-providers.md b/v3/docs/adr/ADR-437-console-cost-across-providers.mdnew file mode 100644index 0000000000..12a383c04d--- /dev/null+++ b/v3/docs/adr/ADR-437-console-cost-across-providers.md@@ -0,0 +1,40 @@+# ADR 437: The Cost page across providers: Claude Code, Codex, OpenRouter and local models++Status: Accepted (ships in ruflo-console 0.27.0 with ruflo-cost-tracker 0.27.0)++Date: 2026 10 03++Scope: `plugins/ruflo-cost-tracker` (`data/prices.json`, `scripts/_pricebook.mjs`, `_ledger.mjs`, `ledger.mjs`, `advise.mjs`, `local-cost.mjs`, `openrouter.mjs`, four skills), `plugins/ruflo-console` (`hooks/data/cost-ledger.ts`, `hooks/views/cost-providers.ts`, the Cost page)++Source: five research briefs (2026-10-03): the `npx skills` ecosystem, Claude Code, Codex CLI, OpenRouter, locally hosted models. Figures marked UNVERIFIED in the briefs are not relied on here.++## 1. The problem++The cost system priced Claude Code only, with three stale tiers (Sonnet at $3/$15 when the current rate is $2/$10), no de-duplication, no 5-minute/1-hour cache split, and a model it did not know cost $0 without a word. The Cost page knew only this session's spend from `usage()`. Nothing covered Codex, OpenRouter or local models, and nothing said what to change.++The `npx skills` search found no skill that tracks cost across providers, prices cache writes by TTL, covers local models or reads OpenRouter's billed cost. The only real Claude Code cost skill (ECC `cost-tracking`) is a reader of a hook's own log. What was worth taking: "latest cumulative row per session, never sum every row", "log missing means say so, never fabricate", prices in data not prose, a ranked report with the cheapest fix per driver, and an explicit yes before any metered action.++## 2. Decision++- **One provider-agnostic row**, read from logs already on the machine, nothing sent: `{provider, model, ts, session, input (uncached), cache_read, cache_write_5m, cache_write_1h, output, reasoning, effort, sidechain}`.+- **One dated, sourced price book** (`data/prices.json`, `COST_PRICES` to override). No rate is hard-coded anywhere; the old per-tier `PRICING` is now derived from it. An unknown model is **unpriced and listed, never $0**; a family fallback is marked approximate. A regex entry stops `gpt-5.6-sol` being priced as `gpt-5` (found by running the ledger on real logs).+- **USD and Codex credits are never added.** GPT-6 Codex models are billed in credits (the model name was read from a real rollout); their cached-input rate is unpublished, so cached input is billed at the input rate and the note says it is an upper bound.+- **Counting rules**, each a way trackers double-count, each held by a test that was shown to fail when the rule is broken: Claude de-duplicated by `message.id + requestId`; Codex by deltas of the running `total_token_usage` (never also `last_token_usage`), skipping unchanged totals, treating a falling total as a new base, cached input as a subset of input, replayed fork events and archived copies de-duplicated, the model from `turn_context`.+- **OpenRouter** (`openrouter.mjs`): network, so it prints the call and sends nothing without `--yes`; one host; the key only from the environment and never printed; OpenRouter's own `usage.cost` / `total_cost` is authoritative and is not recomputed from list prices; BYOK shows the 5% fee and the upstream cost apart.+- **Local models** (`local-cost.mjs`): cost = fixed (amortisation + idle power) + marginal (extra watts while generating), shown at 5/25/50/100% busy because utilisation decides the answer, with the busy fraction above which local beats a named hosted model. An estimate from the user's own inputs; throughput is not measured.+- **The advisor** (`advise.mjs`) reprices the user's own tokens: cache hit ratio, 1-hour cache writes that were not re-read enough to pay back, sub-agents on a top tier, Codex reasoning share, context bloat, unpriced models. A finding with no defensible number says `saving n/a`. It changes nothing.+- **The console Cost page** gains "Across providers" and "Savings you can act on". A mod cannot read logs, so one probe runs the plugin's `ledger.mjs --format json --advise` (one pass for both) from its install path, read from `installed_plugins.json` and validated; the probe does not run when the plugin is absent, and the page then says so and links the Plugin Catalog. It runs only while the Cost page is in front, at most every five minutes, locally.++## 3. Not done, and why++- **No live OpenRouter or local-server probe in the page.** OpenRouter needs a key and the network; the page does not ask for either. Use `/cost-openrouter`.+- **No electricity or hardware figures are invented.** They are inputs.+- **Claude transcript output tokens can under-count streamed output** (the per-step value is a placeholder until the result message): the ledger says so. `/usage` is authoritative for the live session.+- **Subscriptions bill by window, not by token.** Every dollar figure is a list-price estimate, labelled so.+- **Windows install paths are not accepted** by the probe's path check yet.+- **Not verified live in a real pane:** the page's look at narrow widths, and a run of the probe from a real install under Claude Code's `$.process.run` (the specs use the fixture world).++## 4. Kept honest++- Runtime tests build throwaway Claude and Codex logs and assert each counting rule, unpriced handling, USD/credits separation, the local break-even against its own cost curve, the OpenRouter consent gate and that a key in the environment is never echoed. The plugin smoke runs them (step 45).+- Console specs hold the parser, the path validation (rejecting `..`, shell characters, relative paths), that the argv is fixed, that a stale ledger is not shown as live, and the page copy.