aboutsummaryrefslogtreecommitdiff
path: root/modules/core/module-billing.js
diff options
context:
space:
mode:
authorAgando <roduccomm@gmail.com>2026-10-29 12:42:30 +0100
committerAgando <roduccomm@gmail.com>2026-10-29 12:42:30 +0100
commit320877d2c8a3bb6be3d32780ecfc6e7d14528f66 (patch)
tree26e9ad9323f6abf960065e2f27c7949518df19ff /modules/core/module-billing.js
parent12968861b81c6aef3ca15488476db0b33fbf8104 (diff)
fix(newos4): pipe stage quoting, maintain ordering, help cost row, plan status (v4.6.131)
Four items closed in one batch; three ran as parallel subagents on disjoint files, the bundle was rebuilt once by the parent (rebuild-bundles.py serialises the working tree, which carries other sessions' work — see 161372f). 1. PIPE STAGES KEEP THEIR QUOTES. `js "a b".length | wc -c` reached eval as `a b.length` and printed a ReferenceError. terminal.js executePipeChain() now keeps `stages[i]` aligned 1:1 with `pipeParts[i]` (the `.filter(argv => argv.length > 0)` shifted the index; replaced by a lastStage scan + `if (argv.length === 0) continue`) and forwards the stage's own text to the dispatcher. The core path alone was dead code: ShellModule.init() replaces terminal.executePipeChain (shell.js:144), and that override is what runs in the browser (`executePipeChain.toString()` contained `cmdText.split`, not `lastStage`). Both now pass `cmdText`/`pipeParts[i]`. test-pipe-guard.js was rewritten for the new shape and now also asserts the shell override forwards raw text — the assertion that would have caught the shadowing. RED on HEAD: both flags false; GREEN now. 2. MAINTENANCE --fix CAN CLEAR ITS OWN WARN. check_index() ran before check_atlas(), which is what regenerates course/atlas.json, so --fix rebuilt modules-index.json from the stale atlas and the same WARN reappeared every run. check_atlas() now runs immediately before check_index(). modules-index.json regenerated: cost/usage present, 349 commands, version 2026-10-29-atlas. 3. `cost` DOCUMENTED. modules/core/module-billing.js registers `cost [on|off]` (an alias of `usage`); help.html had no row. Added above the `usage` row. help coverage 362/363 -> 363/363. 4. SHIPPED PLANS STOP ASKING FOR A DECISION. The applier only flips review<->safe, so every executed review-gated plan kept counting as an open decision (5 of 5). newos4-feedback-collect.py now reads the body: a `## Status` / `## Implementation` heading followed by shipped|executed plus a version, commit or date is `status: done`; those stay in `plans` (visible as shipped) but leave plans_review and awaiting_decision. Counts: plans_review 5 -> 0, awaiting_decision 4 -> 1 (the remaining one is a real open report, RPT-20261027-160751). admin/feedback.html read `it.status[0]`, which would render `d` for a string status; it now prefers `status_lines[0]`. Also carried, authored by earlier uncommitted sessions and already live in the bundle (attributed, not silently absorbed): modules/core/module-billing.js (new, BillingModule: cost/usage), its CORE_FILES entry in scripts/rebuild-bundles.py, and the BillingModule registry entry in terminal.js. The bundle was rebuilt from HEAD + this batch with ollama-manager.js taken from HEAD, so another session's in-flight `_httpError` refactor is deliberately NOT in the shipped bundle (grep -c _httpError core-bundle.js = 0). Verification node modules/test/test-pipe-guard.js -> {"empty":[],"blank":[],"classifyGuarded":true,"pipeGuarded":true,"shellForwardsRaw":true} node modules/test/test-parse-args.js -> 28/28 pass maintained job -> node tests 21/21 pass scripts/newos4-maintain.py -> maintenance result: OK (modules-index 349, help 363/363, changelog current v4.6.131) live v4.6.131 (real DOM, no print monkey-patch): js "a b".length | wc -c -> 1 (js printed 3, one byte) js "a b".length -> 3 js "abc".toUpperCase() -> ABC echo "two words" -> two words node -e "import('fs')" -> red error + Node-builtin hint js 6*7 -> 42 unhandledrejection -> 0 livePipeImpl: shell-override, livePipeForwardsRaw: true, costRegistered: true
Diffstat (limited to 'modules/core/module-billing.js')
-rw-r--r--modules/core/module-billing.js184
1 files changed, 184 insertions, 0 deletions
diff --git a/modules/core/module-billing.js b/modules/core/module-billing.js
new file mode 100644
index 0000000..b353e79
--- /dev/null
+++ b/modules/core/module-billing.js
@@ -0,0 +1,184 @@
+// Billing / pricing surface for newOS4 (2026-10-28)
+//
+// Why: the terminal could show a model's name but never what it costs. Prices and the anonymous
+// message allowance are public data, so they need no login — the account BALANCE does, and newOS4
+// has no session layer, so that is reported honestly as "not signed in" rather than guessed.
+//
+// Commands: cost [on|off], usage
+class BillingModule {
+ constructor() {
+ this.commands = {};
+ this.terminal = null;
+ this._prices = null;
+ this._pricesAt = 0;
+ this._installed = false;
+ }
+
+ getHelpInfo() {
+ return {
+ 'cost': 'cost [on|off] — AI prices, today\'s free-message allowance and this session\'s spend',
+ 'usage': 'usage — same as cost',
+ };
+ }
+
+ registerCommands() {
+ this.commands['cost'] = (args) => this.run(args);
+ this.commands['usage'] = (args) => this.run(args);
+ }
+
+ init(terminal) {
+ this.terminal = terminal;
+ this._hookUsage();
+ }
+
+ // --- data -----------------------------------------------------------------
+ async _loadPrices() {
+ if (this._prices && Date.now() - this._pricesAt < 300000) return this._prices;
+ try {
+ const r = await fetch('/api/billing/prices');
+ if (!r.ok) return null;
+ this._prices = await r.json();
+ this._pricesAt = Date.now();
+ return this._prices;
+ } catch (e) {
+ return null;
+ }
+ }
+
+ async _loadDemo() {
+ try {
+ const r = await fetch('/api/billing/demo-usage');
+ if (!r.ok) return null;
+ return await r.json();
+ } catch (e) {
+ return null;
+ }
+ }
+
+ async _loadBalance() {
+ // Only answers when a session exists; newOS4 currently has none, so this is expected to 401.
+ try {
+ const r = await fetch('/api/billing/subscription', { credentials: 'include' });
+ if (!r.ok) return null;
+ const d = await r.json();
+ return d && d.balance_usd != null ? d : null;
+ } catch (e) {
+ return null;
+ }
+ }
+
+ // --- session spend, measured where the tokens actually are ----------------
+ _hookUsage() {
+ const om = this.terminal && this.terminal.ollamaManager;
+ if (!om || om.__billingHooked) return;
+ const orig = om._logUsage ? om._logUsage.bind(om) : null;
+ if (!orig) return;
+ om._billingSession = { msgs: 0, prompt: 0, completion: 0, cost: 0, byModel: {} };
+ om._logUsage = (provider, model, latency, promptTokens, completionTokens) => {
+ try { this._accumulate(model, promptTokens, completionTokens); } catch (e) { /* never break a reply */ }
+ return orig(provider, model, latency, promptTokens, completionTokens);
+ };
+ om.__billingHooked = true;
+ }
+
+ _rate(model) {
+ const cat = (this._prices && this._prices.models) || [];
+ const bare = String(model || '').replace(/:cloud$|-cloud$/, '');
+ return cat.find(m => m.model === model) || cat.find(m => m.model === bare) || null;
+ }
+
+ _accumulate(rawModel, promptTokens, completionTokens) {
+ const om = this.terminal.ollamaManager;
+ const s = om._billingSession;
+ if (!s) return;
+ const model = rawModel || 'unknown';
+ const pt = Number(promptTokens) || 0;
+ const ct = Number(completionTokens) || 0;
+ if (!pt && !ct) return; // metadata calls carry no tokens
+ const row = this._rate(model);
+ const r = row ? row.retail_per_million : null;
+ const cost = r ? (pt * r.input + ct * r.output) / 1e6 : 0;
+ s.msgs += 1; s.prompt += pt; s.completion += ct; s.cost += cost;
+ const m = s.byModel[model] || (s.byModel[model] = { msgs: 0, tokens: 0, cost: 0 });
+ m.msgs += 1; m.tokens += pt + ct; m.cost += cost;
+
+ if (this._costLineOn() && ct > 0 && cost > 0) {
+ this.terminal.print(
+ `💵 $${cost.toFixed(4)} · ${model} · ${(pt / 1000).toFixed(1)}k in / ${(ct / 1000).toFixed(1)}k out (retail est.)`,
+ 'info');
+ }
+ }
+
+ _costLineOn() {
+ try { return localStorage.getItem('webx11_cost_line') === '1'; } catch (e) { return false; }
+ }
+
+ // --- the command ----------------------------------------------------------
+ async run(args) {
+ const p = this.terminal.print.bind(this.terminal);
+ if (args && args[0] === 'on') {
+ try { localStorage.setItem('webx11_cost_line', '1'); } catch (e) {}
+ p('💵 cost line on — each reply will show its retail estimate. `cost off` to stop.', 'success');
+ return;
+ }
+ if (args && args[0] === 'off') {
+ try { localStorage.setItem('webx11_cost_line', '0'); } catch (e) {}
+ p('💵 cost line off.', 'info');
+ return;
+ }
+
+ const [prices, demo, bal] = await Promise.all([this._loadPrices(), this._loadDemo(), this._loadBalance()]);
+ const s = (this.terminal.ollamaManager && this.terminal.ollamaManager._billingSession) || null;
+
+ if (demo) {
+ const cap = demo.exempt ? 'unlimited (operator exemption)'
+ : `${demo.used} / ${demo.limit} messages today — ${demo.remaining} left, resets ${String(demo.resets_at).slice(0, 10)}`;
+ p(`📊 Anonymous allowance: ${cap}`, 'info'); // distinct from the monthly money allowance below
+ } else {
+ p('📊 Free allowance: unavailable (billing API did not answer)', 'warning');
+ }
+
+ p(`💰 Balance: ${bal && bal.balance_usd != null ? '$' + Number(bal.balance_usd).toFixed(2) : 'not signed in — newOS4 sends no session token, so a balance cannot be shown here yet'}`, 'info');
+
+ if (bal && bal.plan_allowance) {
+ const pa = bal.plan_allowance;
+ p(`🎁 Included usage (${pa.plan}): $${Number(pa.used_usd).toFixed(2)} of $${Number(pa.limit_usd).toFixed(2)} this month — $${Number(pa.remaining_usd).toFixed(2)} left, then your balance pays`, 'info');
+ }
+
+ if (s && s.msgs) {
+ p(`🧮 This session: ${s.msgs} call(s), ${(s.prompt / 1000).toFixed(1)}k in / ${(s.completion / 1000).toFixed(1)}k out ≈ $${s.cost.toFixed(4)} retail`, 'info');
+ Object.entries(s.byModel)
+ .sort((a, b) => b[1].cost - a[1].cost)
+ .slice(0, 5)
+ .forEach(([m, v]) => p(` · ${m}: ${v.msgs} call(s), ${(v.tokens / 1000).toFixed(1)}k tok, $${v.cost.toFixed(4)}`, ''));
+ } else {
+ p('🧮 This session: nothing yet', '');
+ }
+
+ if (prices) {
+ const rows = prices.models
+ .filter(m => m.retail_per_million.input > 0)
+ .sort((a, b) => a.retail_per_million.output - b.retail_per_million.output);
+ const body = rows.map(m => {
+ const r = m.retail_per_million;
+ return `<tr><td style="padding:2px 8px">${m.model}</td>
+ <td style="padding:2px 8px;text-align:right">$${r.input.toFixed(2)}</td>
+ <td style="padding:2px 8px;text-align:right">$${r.cached_input.toFixed(3)}</td>
+ <td style="padding:2px 8px;text-align:right">$${r.output.toFixed(2)}</td></tr>`;
+ }).join('');
+ this.terminal.printHTML(`<div style="margin:8px 0"><b>Retail prices per 1M tokens</b> (cost × ${prices.markup})<br>
+ <table style="border-collapse:collapse;margin-top:4px;font-size:12px">
+ <tr><th style="text-align:left;padding:2px 8px">model</th><th style="padding:2px 8px">input</th>
+ <th style="padding:2px 8px">cached</th><th style="padding:2px 8px">output</th></tr>
+ ${body}</table>
+ <div style="opacity:.7;margin-top:4px">Catalog ${String(prices.fetched_at || '').slice(0, 16)} · input billed as fresh
+ (cached counts are not exposed upstream), so figures here are a ceiling.</div></div>`);
+ } else {
+ p('💲 Prices unavailable (billing API did not answer)', 'warning');
+ }
+ }
+}
+
+if (typeof window !== 'undefined') {
+ window.BillingModule = BillingModule;
+}