diff options
| author | Agando <roduccomm@gmail.com> | 2026-10-29 12:42:30 +0100 |
|---|---|---|
| committer | Agando <roduccomm@gmail.com> | 2026-10-29 12:42:30 +0100 |
| commit | af36a408670e6caa61527b5bc5e6f9915b69369c (patch) | |
| tree | 15bb6373bf33c205419b725e97bfd4bfc4fa53d2 | |
| parent | db65ce7628b0073c41ff1c13334723a043b24479 (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
| -rw-r--r-- | help.html | 1 | ||||
| -rw-r--r-- | main.html | 6 | ||||
| -rw-r--r-- | modules-index.json | 15 | ||||
| -rw-r--r-- | modules/core/core-bundle.js | 220 | ||||
| -rw-r--r-- | modules/core/module-billing.js | 184 | ||||
| -rw-r--r-- | modules/core/module-loader.js | 2 | ||||
| -rw-r--r-- | modules/core/terminal.js | 34 | ||||
| -rw-r--r-- | modules/ext/critical-ext-bundle.js | 7 | ||||
| -rw-r--r-- | modules/ext/shell.js | 7 | ||||
| -rw-r--r-- | modules/test/test-parse-args.js | 4 | ||||
| -rw-r--r-- | modules/test/test-pipe-guard.js | 36 | ||||
| -rwxr-xr-x | scripts/newos4-feedback-collect.py | 38 | ||||
| -rw-r--r-- | scripts/newos4-maintain.py | 2 | ||||
| -rw-r--r-- | scripts/rebuild-bundles.py | 1 |
14 files changed, 509 insertions, 48 deletions
@@ -1258,6 +1258,7 @@ sh greet.sh</pre> <tr><td><code>unalias <name></code></td><td>Remove a custom alias</td></tr> <tr><td><code>h</code> · <code>s</code> · <code>ll</code></td><td>Short aliases: <code>h</code> = help, <code>s</code> = web search, <code>ll</code> = detailed listing</td></tr> <tr><td><code>dashboard [--watch|--stop]</code></td><td>Collect live telemetry and open the dashboard page; --watch re-collects every 5 s</td></tr> + <tr><td><code>cost [on|off]</code></td><td>Retail prices per model, today's anonymous free-message allowance and this session's token spend; <code>on</code>/<code>off</code> toggles a per-reply cost line (<code>usage</code> is an alias)</td></tr> <tr><td><code>usage [--json] [--reset]</code></td><td>LLM token usage report for this browser (per model, cost estimate)</td></tr> <tr><td><code>df</code></td><td>Virtual filesystem usage</td></tr> <tr><td><code>free</code></td><td>JS heap / memory snapshot</td></tr> @@ -1349,13 +1349,13 @@ </script> <!-- v4.5.63: A2A scratchpad fixes + agent-register arg fix --> -<script src="modules/core/core-bundle.js?v=v4.6.130"></script> +<script src="modules/core/core-bundle.js?v=v4.6.131"></script> <!-- Async dependency-ordered module loader now only initializes terminal and loads optional ext modules --> -<script src="modules/core/module-loader.js?v=v4.6.130"></script> +<script src="modules/core/module-loader.js?v=v4.6.131"></script> <!-- Critical ext bundle loads AFTER webx11 exists so registerModule calls work --> -<script src="modules/ext/critical-ext-bundle.js?v=v4.6.130"></script> +<script src="modules/ext/critical-ext-bundle.js?v=v4.6.131"></script> <script> // ═══ ONE TRUE VERSION SOURCE ═══ diff --git a/modules-index.json b/modules-index.json index 2f95365..fbc2f8c 100644 --- a/modules-index.json +++ b/modules-index.json @@ -1,5 +1,5 @@ { - "version": "2026-10-27-atlas", + "version": "2026-10-29-atlas", "generated": "2026-06-30T00:00:00.000Z", "modules": { "module-agent-registry": { @@ -1107,6 +1107,19 @@ "course" ], "tier": "ext-auto" + }, + "module-billing": { + "name": "module-billing", + "file": "modules/core/module-billing.js", + "type": "core", + "class": "", + "auto_load": true, + "description": "", + "commands": [ + "cost", + "usage" + ], + "tier": "core-bundle" } }, "total": 45 diff --git a/modules/core/core-bundle.js b/modules/core/core-bundle.js index 9682596..b070e65 100644 --- a/modules/core/core-bundle.js +++ b/modules/core/core-bundle.js @@ -3953,6 +3953,7 @@ Only output XML function calls for tool tasks. If no tool is needed, answer norm this._safeRegister('FileSystemModule', 'filesystem'); this._safeRegister('ModuleManagerModule', 'module manager'); this._safeRegister('OllamaModule', 'ollama'); + this._safeRegister('BillingModule', 'billing'); this._safeRegister('SearXNGModule', 'searxng search'); this._safeRegister('ConfigManagerModule', 'config'); this._safeRegister('WebX11AIAssistantModule', 'AI assistant'); @@ -4021,10 +4022,11 @@ Only output XML function calls for tool tasks. If no tool is needed, answer norm BusyBoxModule: typeof BusyBoxModule !== 'undefined' ? BusyBoxModule : undefined, SmartContextModule: typeof SmartContextModule !== 'undefined' ? SmartContextModule : undefined, DebugSupervisorModule: typeof DebugSupervisorModule !== 'undefined' ? DebugSupervisorModule : undefined, + BillingModule: typeof BillingModule !== 'undefined' ? BillingModule : undefined, }; const cls = registry[className]; if (typeof cls === 'undefined') { - console.log(`[SafeRegister] Skipped ${label}: class not loaded (skipped in boot selection)`); + console.warn(`[SafeRegister] Skipped ${label}: ${className} is not in the registry map — add it there, not only to loadBuiltInModules()`); return; } try { this.moduleManager.registerModule(new cls()); } @@ -4162,22 +4164,28 @@ Only output XML function calls for tool tasks. If no tool is needed, answer norm return parts; } async executePipeChain(pipeParts) { - // Parse every stage once, then drop the ones with no argv. `help |` splits to + // Parse every stage once, then skip the ones with no argv. `help |` splits to // ['help',''], `help | ""` to ['help',''] and `| wc -l` to ['','wc -l'] — all three // produced an empty argv whose parts[0] was undefined and threw TypeError from - // parts[0].toLowerCase() (989 occurrences, first filed 2026-10-20). Filtering on + // parts[0].toLowerCase() (989 occurrences, first filed 2026-10-20). Skipping on // argv (not just the string) also keeps the LAST real stage final, so its output is - // never swallowed by a trailing empty segment. - const stages = pipeParts - .map(t => this.security._parseArgs(String(t || '').trim())) - .filter(argv => argv.length > 0); - if (!stages.length) { + // never swallowed by a trailing empty segment, and keeps the loop index aligned + // with pipeParts so each stage gets its own raw text. + const stages = pipeParts.map(t => this.security._parseArgs(String(t || '').trim())); + // Index of the LAST stage that has a real argv — its output is printed, never + // piped. -1 means every segment was empty, so there is nothing to run. + let lastStage = -1; + for (let i = 0; i < stages.length; i++) if (stages[i].length > 0) lastStage = i; + if (lastStage < 0) { this.print('⚠️ Empty pipeline — nothing to run', 'warning'); return; } let pipeInput = null; for (let i = 0; i < stages.length; i++) { const argv = stages[i]; + // Skip empty segments, but keep `i` pointing at pipeParts[i] so the raw stage + // text handed to the dispatcher always belongs to this argv. + if (argv.length === 0) continue; const cmd = argv[0].toLowerCase(); const args = argv.slice(1); // Rebuilt from argv so the security classifier sees the same tokenisation the @@ -4198,19 +4206,19 @@ Only output XML function calls for tool tasks. If no tool is needed, answer norm return; } this._pipeInput = pipeInput; - if (i < stages.length - 1) { - pipeInput = await this.capturePipeOutput(cmd, args); + if (i < lastStage) { + pipeInput = await this.capturePipeOutput(cmd, args, pipeParts[i]); } else { - await this.dispatchCommand(cmd, args); + await this.dispatchCommand(cmd, args, pipeParts[i]); } } this._pipeInput = null; } - async capturePipeOutput(cmd, args) { + async capturePipeOutput(cmd, args, rawText) { let output = ''; this._pushPrintCapture(buf => { output += buf; }); try { - await this.dispatchCommand(cmd, args); + await this.dispatchCommand(cmd, args, rawText); } finally { this._popPrintCapture(); } @@ -7661,6 +7669,192 @@ class OllamaModule { } } +/* === module-billing.js === */ +// 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; +} + /* === module-modmgr.js === */ // Extracted from newOS4 index.html — ModuleManagerModule // v4.5.43: Enhanced with module-info, module-list, module-stats, module-disable/enable, 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; +} diff --git a/modules/core/module-loader.js b/modules/core/module-loader.js index ad6d0b7..3e50c3e 100644 --- a/modules/core/module-loader.js +++ b/modules/core/module-loader.js @@ -4,7 +4,7 @@ // Core module bundle loaded synchronously in main.html. // This loader only handles version cache-busting, splash, terminal init, and optional ext modules. - const LATEST_VER = 'v4.6.130'; + const LATEST_VER = 'v4.6.131'; const CACHE = '?v=' + LATEST_VER; // Exposed so ext modules can register their own URL with the same cache-busting version // instead of an unversioned path the browser may already have cached (shell.js did). diff --git a/modules/core/terminal.js b/modules/core/terminal.js index 16e2c7e..4122b3c 100644 --- a/modules/core/terminal.js +++ b/modules/core/terminal.js @@ -1361,6 +1361,7 @@ this._safeRegister('FileSystemModule', 'filesystem'); this._safeRegister('ModuleManagerModule', 'module manager'); this._safeRegister('OllamaModule', 'ollama'); + this._safeRegister('BillingModule', 'billing'); this._safeRegister('SearXNGModule', 'searxng search'); this._safeRegister('ConfigManagerModule', 'config'); this._safeRegister('WebX11AIAssistantModule', 'AI assistant'); @@ -1429,10 +1430,11 @@ BusyBoxModule: typeof BusyBoxModule !== 'undefined' ? BusyBoxModule : undefined, SmartContextModule: typeof SmartContextModule !== 'undefined' ? SmartContextModule : undefined, DebugSupervisorModule: typeof DebugSupervisorModule !== 'undefined' ? DebugSupervisorModule : undefined, + BillingModule: typeof BillingModule !== 'undefined' ? BillingModule : undefined, }; const cls = registry[className]; if (typeof cls === 'undefined') { - console.log(`[SafeRegister] Skipped ${label}: class not loaded (skipped in boot selection)`); + console.warn(`[SafeRegister] Skipped ${label}: ${className} is not in the registry map — add it there, not only to loadBuiltInModules()`); return; } try { this.moduleManager.registerModule(new cls()); } @@ -1570,22 +1572,28 @@ return parts; } async executePipeChain(pipeParts) { - // Parse every stage once, then drop the ones with no argv. `help |` splits to + // Parse every stage once, then skip the ones with no argv. `help |` splits to // ['help',''], `help | ""` to ['help',''] and `| wc -l` to ['','wc -l'] — all three // produced an empty argv whose parts[0] was undefined and threw TypeError from - // parts[0].toLowerCase() (989 occurrences, first filed 2026-10-20). Filtering on + // parts[0].toLowerCase() (989 occurrences, first filed 2026-10-20). Skipping on // argv (not just the string) also keeps the LAST real stage final, so its output is - // never swallowed by a trailing empty segment. - const stages = pipeParts - .map(t => this.security._parseArgs(String(t || '').trim())) - .filter(argv => argv.length > 0); - if (!stages.length) { + // never swallowed by a trailing empty segment, and keeps the loop index aligned + // with pipeParts so each stage gets its own raw text. + const stages = pipeParts.map(t => this.security._parseArgs(String(t || '').trim())); + // Index of the LAST stage that has a real argv — its output is printed, never + // piped. -1 means every segment was empty, so there is nothing to run. + let lastStage = -1; + for (let i = 0; i < stages.length; i++) if (stages[i].length > 0) lastStage = i; + if (lastStage < 0) { this.print('⚠️ Empty pipeline — nothing to run', 'warning'); return; } let pipeInput = null; for (let i = 0; i < stages.length; i++) { const argv = stages[i]; + // Skip empty segments, but keep `i` pointing at pipeParts[i] so the raw stage + // text handed to the dispatcher always belongs to this argv. + if (argv.length === 0) continue; const cmd = argv[0].toLowerCase(); const args = argv.slice(1); // Rebuilt from argv so the security classifier sees the same tokenisation the @@ -1606,19 +1614,19 @@ return; } this._pipeInput = pipeInput; - if (i < stages.length - 1) { - pipeInput = await this.capturePipeOutput(cmd, args); + if (i < lastStage) { + pipeInput = await this.capturePipeOutput(cmd, args, pipeParts[i]); } else { - await this.dispatchCommand(cmd, args); + await this.dispatchCommand(cmd, args, pipeParts[i]); } } this._pipeInput = null; } - async capturePipeOutput(cmd, args) { + async capturePipeOutput(cmd, args, rawText) { let output = ''; this._pushPrintCapture(buf => { output += buf; }); try { - await this.dispatchCommand(cmd, args); + await this.dispatchCommand(cmd, args, rawText); } finally { this._popPrintCapture(); } diff --git a/modules/ext/critical-ext-bundle.js b/modules/ext/critical-ext-bundle.js index d241f33..00d7345 100644 --- a/modules/ext/critical-ext-bundle.js +++ b/modules/ext/critical-ext-bundle.js @@ -319,9 +319,12 @@ class ShellModule { try { if (i < pipeParts.length - 1) { - pipeInput = await this.capturePipeOutput(cmd, args); + // v4.6.131: hand the stage's own text to the command (this override is the + // one that actually runs — it replaces terminal.executePipeChain), so + // `js "a b".length | wc -c` keeps its quotes like a bare command does. + pipeInput = await this.capturePipeOutput(cmd, args, cmdText); } else { - await this.dispatchCommand(cmd, args); + await this.dispatchCommand(cmd, args, cmdText); } } finally { // Clean up temp file diff --git a/modules/ext/shell.js b/modules/ext/shell.js index 5784ef3..8640630 100644 --- a/modules/ext/shell.js +++ b/modules/ext/shell.js @@ -183,9 +183,12 @@ class ShellModule { try { if (i < pipeParts.length - 1) { - pipeInput = await this.capturePipeOutput(cmd, args); + // v4.6.131: hand the stage's own text to the command (this override is the + // one that actually runs — it replaces terminal.executePipeChain), so + // `js "a b".length | wc -c` keeps its quotes like a bare command does. + pipeInput = await this.capturePipeOutput(cmd, args, cmdText); } else { - await this.dispatchCommand(cmd, args); + await this.dispatchCommand(cmd, args, cmdText); } } finally { // Clean up temp file diff --git a/modules/test/test-parse-args.js b/modules/test/test-parse-args.js index 75fd7ab..f9836ae 100644 --- a/modules/test/test-parse-args.js +++ b/modules/test/test-parse-args.js @@ -51,6 +51,10 @@ ok('dispatchCommand takes rawText', /async dispatchCommand\(cmd, args, rawText\) ok('module receives rawText', /mod\.commands\[cmd\]\(args, rawText\)/.test(termSrc)); ok('checkAndRun records raw input', /this\._currentRaw\s*=\s*rawInput/.test(termSrc)); ok('_dispatch forwards raw input', /dispatchCommand\(cmd, args, this\._currentRaw/.test(termSrc)); +// Pipes must forward each stage's own text too, otherwise splitPipe()'s raw stage is thrown +// away by a second _parseArgs() pass and `js "a b".length | wc -c` sees `a b.length`. +const chainSrc = termSrc.match(/async executePipeChain\(pipeParts\)\s*\{[\s\S]*?\n\s{12}\}/); +ok('executePipeChain keeps the raw stage', !!chainSrc && /dispatchCommand\(cmd, args, pipeParts\[i\]/.test(chainSrc[0]), chainSrc ? 'no pipeParts[i] passthrough' : 'executePipeChain not found'); // ---- 3. console command uses the raw expression --------------------------------------- const consoleSrc = fs.readFileSync(path.join(extDir, 'console.js'), 'utf8'); diff --git a/modules/test/test-pipe-guard.js b/modules/test/test-pipe-guard.js index 0bd7cc9..7851613 100644 --- a/modules/test/test-pipe-guard.js +++ b/modules/test/test-pipe-guard.js @@ -1,8 +1,13 @@ // modules/test/test-pipe-guard.js — run: node modules/test/test-pipe-guard.js -// Fails fast if either guard is removed or if a guard is placed AFTER the parts[0] read. -// Behavioural proof is the browser matrix (plan Task 8); this test is the cheap tripwire. +// Cheap tripwire for the three things that silently broke pipe handling before: +// 1. _parseArgs('') returning a non-empty argv (parts[0] === undefined -> TypeError, 989 hits) +// 2. the empty-stage guard being placed AFTER the parts[0] read +// 3. v4.6.131: the raw stage text being discarded, in BOTH pipe implementations — the core one +// and the ShellModule override that actually replaces it at boot (measured 2026-10-29: +// terminal.executePipeChain.toString() contained `cmdText.split`, not `lastStage`). const fs = require('fs'), path = require('path'); const src = fs.readFileSync(path.join(__dirname, '../core/terminal.js'), 'utf8'); +const shellSrc = fs.readFileSync(path.join(__dirname, '../ext/shell.js'), 'utf8'); // 1. _parseArgs('') must return [] — that precondition is what made parts[0] undefined. // The source is a CLASS METHOD, so wrap it in an object literal (a bare `new Function('m(){…}')` @@ -19,16 +24,29 @@ const cGuard = src.indexOf('if (!parts.length)', ci); const cRead = src.indexOf('parts[0].toLowerCase()', ci); const classifyGuarded = ci >= 0 && cGuard > ci && cGuard < cRead; +// 3. core executePipeChain: skip empty stages without shifting the index (v4.6.131 replaced the +// `.filter(argv => argv.length > 0)` with a lastStage scan so stages[i] stays aligned with +// pipeParts[i]), and forward each stage's raw text to the dispatcher. const pi = src.indexOf('async executePipeChain('); -const pGuard = src.indexOf('if (!stages.length)', pi); -const pFilter = src.indexOf('.filter(argv => argv.length > 0)', pi); -const pRead = src.indexOf('argv[0].toLowerCase()', pi); -const pipeGuarded = pi >= 0 && pFilter > pi && pGuard > pFilter && pRead > pGuard - && src.indexOf('i < stages.length - 1', pi) > 0; +const body = pi >= 0 ? src.slice(pi, src.indexOf('async capturePipeOutput(', pi)) : ''; +const pEmpty = body.indexOf('if (lastStage < 0)'); +const pSkip = body.indexOf('if (argv.length === 0) continue'); +const pRead = body.indexOf('argv[0].toLowerCase()'); +const pRaw = body.indexOf('dispatchCommand(cmd, args, pipeParts[i])'); +const pipeGuarded = pi >= 0 && pEmpty > 0 && pSkip > pEmpty && pRead > pSkip && pRaw > pRead + && body.indexOf('this.capturePipeOutput(cmd, args, pipeParts[i])') > 0; -const report = { empty, blank, classifyGuarded, pipeGuarded }; +// 4. the override that actually runs: ShellModule.init() replaces terminal.executePipeChain, so a +// fix in the core alone is dead code. Measured live: the wrapper is the shell's. +const si = shellSrc.indexOf('this.terminal.executePipeChain = async function(pipeParts)'); +const shellBody = si >= 0 ? shellSrc.slice(si, shellSrc.indexOf('_splitSequence(', si)) : ''; +const shellForwardsRaw = si >= 0 + && shellBody.indexOf('this.dispatchCommand(cmd, args, cmdText)') > 0 + && shellBody.indexOf('this.capturePipeOutput(cmd, args, cmdText)') > 0; + +const report = { empty, blank, classifyGuarded, pipeGuarded, shellForwardsRaw }; console.log(JSON.stringify(report)); const ok = Array.isArray(empty) && empty.length === 0 && Array.isArray(blank) && blank.length === 0 - && classifyGuarded && pipeGuarded; + && classifyGuarded && pipeGuarded && shellForwardsRaw; process.exit(ok ? 0 : 1); diff --git a/scripts/newos4-feedback-collect.py b/scripts/newos4-feedback-collect.py index c0711d9..5e173a1 100755 --- a/scripts/newos4-feedback-collect.py +++ b/scripts/newos4-feedback-collect.py @@ -19,6 +19,28 @@ APPLIED = os.path.join(ROOT, 'spaces/newos4/data/feedback/applied.json') # led NETFAIL = os.path.join(ROOT, 'spaces/newos4/data/debug/network_failures.json') # ingest-filter counter AUTOREVIEW = os.path.join(ROOT, 'spaces/newos4/data/feedback/autoreview-latest.json') +# A finished plan keeps its '<!-- autonomy: review -->' marker (the applier only flips +# review<->safe), so the marker alone overstates the queue. The body is the evidence: a Status / +# Implementation heading followed by 'shipped'/'executed' plus a version, a commit ref or a dated +# stamp. Order-free on purpose — "executed 2026-10-26" and "shipped v4.6.128 (75c5113)" both count. +STAMP_WORD = re.compile(r'(?i)\b(?:shipped|executed)\b') +STAMP_REF = re.compile(r'\b(?:[vV]\d+\.\d+(?:\.\d+)?|[0-9a-f]{7,40}|20\d\d-\d\d-\d\d)\b') + + +def execution_stamp(lines): + """True when a Status/Implementation heading carries an execution stamp. + + Looks at the heading plus the ~8 lines under it. Truncated or empty files simply fail the + test; this never raises. + """ + for i, line in enumerate(lines): + if not (line.startswith('## Status') or line.startswith('## Implementation')): + continue + block = '\n'.join(lines[i:i + 9]) + if STAMP_WORD.search(block) and STAMP_REF.search(block): + return True + return False + def load(path, default): try: @@ -74,12 +96,17 @@ def plans_needing_decision(dec): excerpt = '\n'.join(lines[:60])[:2400] tasks = [l.lstrip('#').strip() for l in lines if re.match(r'^#{2,3}\s+Task\b', l)][:20] status = [l.strip() for l in lines if l.startswith('## Status') or l.startswith('## Implementation')][:2] + done = execution_stamp(lines) d = dec.get('plan:' + name, {}) items.append({ 'id': 'plan:' + name, 'kind': 'plan', 'title': title, 'path': p, 'size': os.path.getsize(p), 'mtime': datetime.fromtimestamp( os.path.getmtime(p), timezone.utc).isoformat(timespec='seconds'), - 'excerpt': excerpt, 'tasks': tasks, 'status': status, + 'excerpt': excerpt, 'tasks': tasks, + # 'done' when the body records the execution; otherwise the raw heading lines, as before. + # Done plans stay in this list so the page can show them as shipped, but they no longer + # count as a pending review — see the plans_review count in main(). + 'status': 'done' if done else status, 'status_lines': status, 'decision': d.get('decision'), 'decided_at': d.get('decided_at') or d.get('ts'), 'note': d.get('note', ''), 'actor': d.get('actor', ''), }) @@ -133,7 +160,9 @@ def main(): triage = load(TRIAGE, {}) or {} plans = plans_needing_decision(dec) reports = reports_needing_decision(dec) - awaiting = [x for x in plans + reports if not x.get('decision')] + # A plan whose body records its execution is shipped, not pending: it stays in `plans` (so the + # page can show it) but must not sit in the operator's "awaiting a decision" queue. + awaiting = [x for x in plans + reports if not x.get('decision') and x.get('status') != 'done'] net = load(NETFAIL, {}) or {} net_top = sorted(((net.get('by_source') or {}) if isinstance(net.get('by_source'), dict) else {}).items(), key=lambda kv: -int(kv[1]))[:3] @@ -142,7 +171,10 @@ def main(): 'top': [[str(k), int(v)] for k, v in net_top]}, 'generated_at': datetime.now(timezone.utc).isoformat(timespec='seconds'), 'counts': { - 'plans_review': len(plans), 'reports_total': len(reports), + # Only plans still awaiting a decision: a review marker whose body already records the + # execution is a shipped plan, not an open question. It stays in 'plans' below. + 'plans_review': sum(1 for p in plans if p.get('status') != 'done'), + 'reports_total': len(reports), 'awaiting_decision': len(awaiting), 'steering_pending': len(steer) if steer_ok else -1, # -1 = steering.json unreadable/wrong shape 'triage_reports_new': (triage.get('counts') or {}).get('reports_new', 0), diff --git a/scripts/newos4-maintain.py b/scripts/newos4-maintain.py index 2b4a961..acb81c3 100644 --- a/scripts/newos4-maintain.py +++ b/scripts/newos4-maintain.py @@ -297,7 +297,7 @@ def check_links(): def main(): os.chdir(ROOT) bad = syntax_failures() # computed once, gates the bundle rebuild - check_versions(); check_syntax(bad); check_regression_tests(); check_bundles(bad); check_perms(); check_index(); check_data(); check_live(); check_atlas(); check_course(); check_help_coverage(); check_links(); check_changelog(); check_build_tags() + check_versions(); check_syntax(bad); check_regression_tests(); check_bundles(bad); check_perms(); check_atlas(); check_index(); check_data(); check_live(); check_course(); check_help_coverage(); check_links(); check_changelog(); check_build_tags() fails = [m for l, m in issues if l == 'FAIL'] print('newOS4 maintenance — ' + datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%MZ') + (' [fix]' if FIX else '') + (' [deep]' if DEEP else '')) for l, m in issues: print(f'{l}: {m}') diff --git a/scripts/rebuild-bundles.py b/scripts/rebuild-bundles.py index f141292..a231e32 100644 --- a/scripts/rebuild-bundles.py +++ b/scripts/rebuild-bundles.py @@ -15,6 +15,7 @@ CORE_FILES = [ 'module-system.js', 'module-fs.js', 'module-ollama.js', + 'module-billing.js', 'module-modmgr.js', 'module-searxng.js', 'module-servermon.js', |