Cost ledger across all chats: after every answer it records the chat cost (as /cost), tokens per model and model calls made by other mods. /ledger shows today…

A cost ledger across all your chats. After every answer, cost-ledger records what the chat has cost so far (the same value as /cost), plus the model calls made by other mods (sidekick, quick-replies …). /ledger shows today, 7 days, 30 days and all time, the history of the last 14 days, your projects and your most expensive chats in an overview styled like Claude Code (theme colors). The history shows 14 days or 14 weeks, each bar split by model; model calls by other mods appear as their own parts (e.g. “Sonnet 5.5 · mods”). On a subscription, /ledger limits shows how much API value went into the current 5-hour and weekly window and into your subscription month, and estimates how much of the window you used outside the ledger (claude.ai, the mobile app, chats without cost-ledger). With /ledger sync <folder> on each of your computers, /ledger shows all of them together through a folder they share, such as one in a cloud drive. It is a pure observer: no budget, no intervention, no model calls of its own.
Texts are English by default; set
languagetodefor German.
Tested with Claude Code v2.1.295 · Plugin version 0.7.0 · Requires Claude Code v2.1.271 or later (setting options)
| Input | Effect | ||
|---|---|---|---|
/ledger | Overview: today, 7 days, 30 days, all time; history of the last 14 days, each bar split by model (with legend, chat and mod calls separate); projects, most expensive chats, mods | ||
/ledger weeks | The same overview with the last 14 calendar weeks instead of days | ||
| `/ledger chats [7\ | 30\ | all]` | The 20 most expensive chats in the period (default 30 days; any number of days from 1 to 3650 works) |
| `/ledger projects [7\ | 30\ | all]` | All projects in the period |
| `/ledger models [7\ | 30\ | all]` | Models: share of the estimated API value, answers, input, output and cache tokens (including subagents and mod calls) |
/ledger limits | Subscription limits: the current 5-hour and weekly window (% used, API value, reset time with countdown, projection “100 % ≈ $X”), your subscription month (API value against the plan price, factor, next renewal) and the last 10 five-hour windows with their average. Each window also shows the estimated share used outside the ledger (see below) | ||
| `/ledger plan <plan> <day\ | today> [price]` | Set your plan and billing day: pro, max5 (5x), max20 (20x), team or enterprise; day 1–31, or today if your plan renewed today; monthly price in $ (comma or dot). Without a price, the list price is used: Pro $20, Max 5x $100, Max 20x $200; Team and Enterprise have none. Example: /ledger plan max20 14 | |
/ledger plan | Show the plan setting and the syntax; /ledger plan off deletes it | ||
/ledger sync <folder> | Turn on sync between your computers through a shared folder (absolute path, spaces allowed), e.g. /ledger sync <your cloud folder>/cost-ledger. Run it on every computer with the same folder | ||
/ledger sync | Sync state: folder, this device's name and ID, the other devices with the time of their last update | ||
/ledger sync name <name> | Name this device (up to 30 characters); the other devices show its chats under this name. Default: “Device 1a2b” from a random ID | ||
/ledger sync off | Turn sync off. This device's file stays in the folder; cost-ledger never deletes files | ||
/ledger reset | Delete everything on this device, after a confirmation (Cancel is recommended and listed first). The plan and sync settings stay; other devices keep their entries | ||
/ledger help | Help as a table: all commands, the current state (plan, sync, storage used, recording since) and your settings with their values, plus how to change them and how to turn the mod off. Also /ledger ? |
Older German arguments still work as aliases: hilfe for help, alle for all, heute for today, aus for off. An unknown command word (the first word after /ledger) answers with a pointer to /ledger help. /ledger days is gone; it only showed the overview.
Help: /ledger help draws a table in the terminal and the desktop app (accent green), with the state as of the moment you ran it. Run it again to see a change. Elsewhere (claude -p, VS Code) you get a short Markdown version, which is also what Claude reads.
On a subscription, /ledger also shows a compact line at the top: 5 h 62 % · $18.40 · reset 18:00 │ week 98 % · $212.10 │ plan $812.40 = 4.1× · /ledger limits. It is left out when there is neither a limit window nor a plan.
Why /ledger plan? Claude Code does not tell mods which plan you have or when it renews, and cost-ledger never reads your login data. So you set it once. Until then the subscription month shows “Plan not set”.
What gets counted:
usage().cost.usd, booked to today. Subagents are included (verified). Remaining costs are booked at session end and before /ledger.$.model.complete / fork / classify call by another mod, with count and amount, priced with cost-ledger's own price table (Haiku 5.5 and Sonnet 5.5 as of 2026-10-07, the other models as of 2026-09-25). classify only counts the number of calls. These costs are not part of /cost and are added on top (verified)..claude/worktrees/ count toward the main folder. Runs with claude -p are listed as Script runs.-p script runs). These 50 characters are kept in the local plugin store. Chats without a message are called Chat from Oct 6 14:05 (date and time of the first booking).usage().rateLimits: % used and reset time). A window is identified by its reset time. If the window has already reset and no new answer has reported the next one, the amount waits and goes into the next window. % used is the highest value seen in the window./ledger plan), only from chats that saw subscription limits (runs with an API key are left out). Factor = API value ÷ plan price.host/owner/repo)./cost value. Not included in the model view: compaction and Claude Code's internal calls, so the sum over models is slightly below /cost.All amounts are API values. On a subscription they count toward your usage limits, not toward a bill.
The plugin store lives on one computer. To see your PC and your laptop together, give both the same folder that your cloud drive (OneDrive, Dropbox, Syncthing …) keeps in sync:
/ledger sync <your cloud folder>/cost-ledger
cost-ledger-<id>.json into that folder and reads the others. It writes when you run /ledger … and after answers at most every 15 minutes; it reads the other files only when you run /ledger …./ledger shows your local ledger with a note and uses the last good copy of the other device. cost-ledger never deletes a file and only writes its own.\\server\…) is rejected; use a folder your sync client keeps on disk. On Windows the folder needs a drive letter (D:\…), and a drive root is not accepted./ledger reset clears only this device and rewrites its (now empty) file. The plan setting from /ledger plan also stays per device.% used covers your whole account, while the dollar amounts only come from chats with cost-ledger. /ledger limits estimates the gap: cost-ledger takes the completed, fully recorded window with at least 20 % where the most API value per percent went through the ledger, as “how much one percent costs”. For every window it then shows “outside the ledger ≈ 12 % of 40 %” (a percentage-point estimate) and marks past windows with “outside 12 %”. Until there is such a window, it says when the estimate starts.
Runs in: terminal and the desktop Code tab (its own rendering at the command line, colors from the theme). Terminal verified with 0.3.x; desktop verified with 0.3.1 on 2026-10-06 (0.3.0 fell back to the Markdown summary there, fixed in 0.3.1). The 0.5.0 views (/ledger limits, the limit line) are covered by rendering tests for both surfaces; a visual check is pending. The help table (0.6.0) was checked in the terminal. Sync (0.7.0) was verified with claude -p in a real session; its views are covered by rendering tests for both surfaces. In claude -p and other surfaces you get the Markdown summary. Claude only reads that summary (at most 10 lines for the views, about 15 for the help), not the rendering.
/plugin → cost-ledger → settings (userConfig):
| Key | Title in /config | Meaning | Default |
|---|---|---|---|
language | Language / Sprache | Language of the overview, summary, help and confirmation: en or de | en |
keepDays | Retention (days) | Chats with no new bookings for this long are deleted by cost-ledger on the next /ledger | 365 |
dayYellow | Daily amount yellow from ($) | Daily amount (chat + mods) from which the day's value in the history turns yellow | 3 |
dayRed | Daily amount red from ($) | Daily amount from which it turns red | 8 |
language switches all texts the mod shows: the /ledger overview and its views, the Markdown summary Claude reads, the help, the reset confirmation, and the formats (en: $14.44, Oct 6, W41; de: 14,44 $, 06.10., KW 41). The default is en; set it to de for German. A change applies to the next /ledger. Stored data does not depend on the language.
claude plugin validate shows:
hooks: session.start, classic.SessionStart, classic.UserPromptSubmit, turn.complete, model.complete, model.fork, model.classify, session.end, command.run{command=ledger}, ui.render{component=CommandOutput, props has {command=ledger}}
calls: $.clock.now, $.command.register, $.fs.list, $.fs.read, $.fs.write, $.session.repo, $.session.root, $.session.surfaces, $.session.usage, $.store.delete, $.store.get, $.store.keys, $.store.set, $.ui.ask, $.ui.log
In plain language, the hooks:
session.start: sets the starting point of the chat's cost counter, reads the project, registers /ledger.classic.SessionStart: the chat's ID and title; /clear, /resume and branching switch the chat without a new start.classic.UserPromptSubmit: names a chat after the start of your first own message when Claude Code reports no title (at most 50 characters, not for commands or -p runs), and finds the chat's ID again after the mod reloads. The prompt itself is neither changed nor stored beyond those 50 characters.turn.complete: books the chat's cost after every answer.model.complete, model.fork, model.classify: see the calls other mods make, to count them (below).session.end: books the rest when the chat ends.command.run{command=ledger}: the /ledger command.ui.render{component=CommandOutput, props has {command=ledger}}: draws the overview, the other views and the help in place of the command's text line.And the calls:
$.command.register: registers /ledger.$.session.usage: reads the chat's cost, without breakdown, so no extra request; from the same call the context fill and the rate-limit windows (% used, reset time) for /ledger limits. Mod calls use the last reading and do not call it again.$.session.surfaces: tells desktop, terminal and script runs apart.$.session.repo, $.session.root: the chat's project name; also the Git remote, stored only as host/owner/repo, never with credentials.$.store.get/set/keys/delete: the ledger in the mod's own plugin store, one entry per chat; cleanup and reset; the plan setting from /ledger plan (plan, billing day, price). /ledger help only reads it (storage used, plan, recording since).$.ui.ask: confirmation before /ledger reset.$.ui.log: errors go to the debug log ({to:'debug'}), never into the transcript.$.clock.now: current date and timestamps.$.fs.list, $.fs.read, $.fs.write: sync between devices (since 0.7.0). Only inside the folder you set with /ledger sync <folder>, and only files named cost-ledger-<id>.json: it lists that folder, reads the other devices' files and writes its own. Nothing happens with these rights until you turn sync on. Claude Code cannot restrict these rights to a folder, so cost-ledger enforces it itself, and tests check every path.The model.* hooks only read the result of a call (usage, origin) and pass it on unchanged. No model calls, no processes or network targets; files only for sync, as above.
Add the marketplace once, then install the mod:
claude plugin marketplace add FynnXland/fynn-mods
claude plugin install cost-ledger@fynn-mods
Inside a session the same works with /plugin marketplace add FynnXland/fynn-mods and /plugin install cost-ledger@fynn-mods. The mod loads in the next session, or after /reload-plugins.
Check: /plugin shows … mod active · cost-ledger.
Update: claude plugin update cost-ledger@fynn-mods, or turn on auto-update for fynn-mods under Marketplaces in /plugin.
Remove: disable it under Installed in /plugin, or run claude plugin uninstall cost-ledger@fynn-mods.
Try it for one session without installing (from a clone of the repo):
claude --plugin-dir <path-to-clone>/mods/cost-ledger
Install in user scope (the default), so the mod records in every project. It only books chats in which it is loaded, and only chats started after installation.
The plugin store is tied to the plugin ID. What gets recorded while the mod is loaded via --plugin-dir (cost-ledger_inline-…) is not visible to the marketplace install (cost-ledger_fynn-mods-…), and vice versa.
session.end), the remainder since the last answer is missing. If the chat is resumed later, cost-ledger books that remainder then./resume in the middle of a session is only covered by a test, not verified in a real session (it cannot be triggered in -p). Assumption: usage().cost afterwards reflects the resumed chat (as when starting with --resume, which is verified). If the counter instead kept running per process, the previous chat's cost would be booked twice onto the resumed one.deny) do not count. Haiku 5.5 is priced by prompt length: above 100,000 prompt tokens (input + cache reads + cache writes) the whole call costs five times as much. cost-ledger applies this only to single mod calls (model.complete). A chat turn and a fork report their responses summed, so their per-model estimate always uses the lower Haiku 5.5 rate and can be too low when a single request in them was over 100,000 tokens.haiku: a mod that calls $.model.complete({ model: 'haiku' }) gets Claude Haiku 5.5 on Claude Code v2.1.293 and later (verified with v2.1.295), Haiku 4.5 before. The call's result does not say which model answered, so cost-ledger prices haiku as Haiku 5.5. On an older Claude Code such calls are booked about ten times too low, and if you point haiku elsewhere with ANTHROPIC_DEFAULT_HAIKU_MODEL, they are still priced as Haiku 5.5./cost value. Claude Code v2.1.291 still priced Haiku 5.5 like Haiku 4.5 (about ten times too much); v2.1.295 prices it correctly.cleanupPeriodDays. A 365-day retention assumes chats with the mod loaded keep running.$.store has 4 MiB in total. With the data collected (including the limit windows since 0.5.0), a chat needs about 0.7–1.1 KB per day on which it runs. That is enough for roughly 4,000–6,000 chat-days; with very many -p runs, lower keepDays. /ledger warns from 75 % and reports a write error./ledger lines only show the Markdown summary after the session restarts (the rendering's data lives only in the process memory).--plugin-dir) and from the marketplace, each copy keeps its own ledger, because the plugin store is tied to the plugin ID. Chats recorded by one copy do not appear in the other.turn.complete reports it).% used covers your whole account, including claude.ai, the mobile app and chats where cost-ledger is not loaded. The dollar amounts only come from chats with cost-ledger. The projection “100 % ≈ $X” (API value ÷ % used × 100) and the average over past windows are therefore estimates: they come out too low when you also use Claude elsewhere.% used./ledger limits shows “reset passed” until the next answer. Countdowns are as of the moment you ran the command; the view does not refresh by itself.% used push it up. Chats from a computer that is not synced count as “outside”./ledger) plus your sync client's delay. /ledger sync shows the time of each device's last update.claude -p) with 0.7.0, a check in the desktop app is pending. Cloud sessions were not tested./ledger reset they show up again. Delete such a file by hand (/ledger sync lists each device with its last update); cost-ledger never deletes files.hooks/register.ts 827 lines1// cost-ledger: Kostenbuch über alle Chats. Reiner Beobachter: bucht nach jedem Turn die Differenz von `usage().cost.usd`,
2// dazu die Modellaufrufe anderer Mods, und zeigt per /ledger eine Übersicht (Sprache aus userConfig `language`).
3// Fail-open: Jeder Erfassungs-Hook gibt das Ergebnis von `next` unverändert zurück, Fehler gehen nur ins Debug-Log; kein `.catch`.
4// Ein $.store-Schlüssel pro Session (`s:<sessionId>`), den nur diese Session schreibt: $.store ist nicht atomar (CHEATSHEET).
5import type { EngineInterface, FsEntry, On } from 'claude-code'
6import { helpMarkdown, helpTree } from './help.ts'
7import type { HelpData } from './help.ts'
8import { T, dateTime, shortDate, usd } from './i18n.ts'
9import {
10 HELP_WORDS,
11 NAME_WORD,
12 NO_FOLDER,
13 OFF_WORDS,
14 PLANS,
15 SYNC_WORD,
16 VIEW_WORDS,
17 ledgerHelp,
18 aggregate,
19 baselineFor,
20 bookChat,
21 bookLim,
22 bookLimAt,
23 bookMod,
24 bookModel,
25 bookRate,
26 bookTurn,
27 cleanPlan,
28 cleanRemote,
29 callCost,
30 cleanRec,
31 cleanSettings,
32 dayKey,
33 DAY,
34 deltaOf,
35 limitsOf,
36 newRec,
37 parsePlan,
38 parseRange,
39 planLabel,
40 planMonth,
41 pluginName,
42 projectOf,
43 summaryText,
44 titleFromPrompt,
45 tokensOf,
46} from './logic.ts'
47import type { Carry, HelpInfo, Kind, Limit, Plan, Rec, Settings, SyncInfo, TurnInfo, Usage } from './logic.ts'
48import { FILE_LIMIT, buildFile, cleanDevice, cleanDeviceName, cleanSync, fileName, idFromName, inDir, mergeRecs, newDeviceId, parseFile, utf8Bytes, validDir } from './sync.ts'
49import type { Device, SyncFile } from './sync.ts'
50import { ledgerTree } from './view.ts'
51import type { View } from './view.ts'
52
53const SELF = 'cost-ledger'
54
55let settings: Settings = cleanSettings(undefined)
56let sessionId = '' // aus classic.SessionStart (kommt vor session.start), nach einem Modul-Reload aus UserPromptSubmit
57let rec: Rec | null = null // eigener Datensatz, im Speicher führend; geschrieben wird er immer ganz
58let seen = 0 // Baseline: letzter gebuchter Stand des Zählers in diesem Prozess
59let rebase = false // Sessionwechsel mitten im Prozess (Resume, Branch): Baseline beim nächsten Messen neu setzen
60let started = false
61let hasCost = true
62let lastModel = '' // Modell der Hauptschleife, für model.fork
63let title = ''
64let titleDirty = false
65let titleFromSession = false // Titel kam als session_title (gewinnt immer) statt aus der ersten Nachricht
66const meta: { project: string; root: string; kind: Kind; remote: string } = { project: NO_FOLDER, root: '', kind: 'terminal', remote: '' }
67// Kennung im Text → Daten der Zeichnung, höchstens 10: eine Ansicht von /ledger oder die Hilfe, dazu die Argumente des
68// Aufrufs. Der Render-Hook zeichnet nur, wenn die Zeile dieselben Argumente hat: `/ledger #<kennung>` gibt „Unbekannt: …“
69// mit der Kennung in der ersten Zeile zurück und darf trotzdem nicht als Tabelle erscheinen (Review worklist 0.7.0, K2).
70type Drawn = ({ kind: 'ledger'; view: View } | { kind: 'help'; data: HelpData }) & { args: string }
71const reports = new Map<string, Drawn>()
72let reportNo = 0
73// Akzent der Hilfe als Theme-Key: passt sich hell und dunkel an (docs/HELP-SPEC.md §4, Fynn 2026-10-09)
74const ACCENT = 'success'
75
76/** Argumente vergleichbar machen: ohne Rand, klein, einfache Leerzeichen. */
77const normArgs = (s: string | undefined) => String(s ?? '').trim().toLowerCase().replace(/\s+/g, ' ')
78
79/** Neue, eindeutige Kennung `#…` für die erste Textzeile; ui.render findet darüber die Daten der Zeichnung. */
80function remember(now: number, d: Drawn): string {
81 const tag = `#${(++reportNo).toString(36)}${now.toString(36).slice(-5)}`
82 reports.set(tag, d)
83 while (reports.size > 10) reports.delete(reports.keys().next().value as string)
84 return tag
85}
86let chain: Promise<unknown> = Promise.resolve() // Messen und Schreiben dieser Session nacheinander
87let writeError = '' // letzter Schreibfehler (z. B. Speicher voll), /ledger zeigt ihn
88// Limit-Fenster der letzten Messung: Mod-Aufrufe buchen hierhin, ohne eigenes usage() (SPEC Nachtrag 0.5.0, Verhalten 2)
89let limits: Limit[] = []
90let carry: Carry = {} // Beträge, die auf das nächste gültige Fenster warten
91let carryAt = 0 // seit wann `carry` Beträge hält; ein späterer Reset (auch aus einem anderen Chat) verwirft sie
92let limSinceChecked = false // `meta:limSince` in diesem Prozess schon geprüft
93let pendingGap = 0 // Nachbuchung beim Start (Resume): gehört ins Fenster der letzten Buchung, nicht ins laufende
94let gapAt: number | undefined // Zeitpunkt der letzten Buchung beim Start; spätere Mod-Aufrufe verschieben ihn nicht
95// Geräte-Sync (SPEC Nachtrag 0.7.0): letzter guter Stand je fremdem Gerät, falls dessen Datei gerade halb geschrieben ist
96const peerCache = new Map<string, SyncFile>()
97const SYNC_EVERY = 15 * 60 * 1000 // nach Turns höchstens so oft schreiben (Verhalten 1)
98const CONFLICT_SLACK = 60 * 1000 // doppelte Geräte-ID erst ab einer Minute Vorsprung der Datei (Review S1)
99let nextSyncCheck = 0 // vorher fragt syncAfterTurn den Store nicht
100type SyncCfg = { dir: string; device: Device }
101
102/** `carryAt` nach einer Fenster-Buchung nachführen. */
103function noteCarry(now: number) {
104 if (!Object.keys(carry).length) carryAt = 0
105 else if (!carryAt) carryAt = now
106}
107
108/** `fn` nach allem, was schon in der Kette steht; ein Fehler bricht die Kette nicht. */
109function serial<T>(fn: () => Promise<T>): Promise<T> {
110 const p = chain.then(fn, fn)
111 chain = p.catch(() => undefined)
112 return p
113}
114
115const msg = (err: unknown) => String((err as Error)?.message ?? err).slice(0, 200)
116
117function log($: EngineInterface, text: string) {
118 try {
119 $.ui.log(`cost-ledger: ${text}`, { to: 'debug' })
120 } catch {
121 // Debug-Log ist Beiwerk
122 }
123}
124
125/** Desktop, Terminal oder Skript-Lauf (`-p`: keine Surface, API-DETAILS.md:303-304). */
126function kindOf(surfaces: readonly string[]): Kind {
127 if (surfaces.includes('desktop')) return 'desktop'
128 return surfaces.length ? 'terminal' : 'script'
129}
130
131async function load($: EngineInterface, id: string): Promise<Rec | null> {
132 return cleanRec(await $.store.get(`s:${id}`))
133}
134
135async function save($: EngineInterface) {
136 if (!rec || !sessionId) return
137 try {
138 await $.store.set(`s:${sessionId}`, rec)
139 writeError = ''
140 } catch (err) {
141 writeError = msg(err)
142 throw err
143 }
144}
145
146/**
147 * Hat eine andere Session `/ledger reset` ausgeführt, seit dieser Datensatz zuletzt gebucht wurde, beginnt er leer;
148 * sonst schriebe dieser Chat die gelöschten Beträge zurück ($.store ist geteilt, interface.md:821-826).
149 */
150async function honorReset($: EngineInterface) {
151 const held = Object.keys(carry).length > 0
152 if (!rec && !held) return
153 const at = await $.store.get('meta:resetAt')
154 if (typeof at !== 'number') return
155 // Wartende Fenster-Beträge von vor dem Reset, auch ohne Datensatz (z. B. nach /clear in eine neue Session)
156 if (held && carryAt < at) {
157 carry = {}
158 carryAt = 0
159 }
160 if (rec && rec.lastAt < at) {
161 rec.days = {}
162 rec.mods = {}
163 rec.models = {}
164 rec.modModels = {}
165 rec.act = {}
166 rec.hours = {}
167 rec.rl = {}
168 rec.lim = {}
169 }
170}
171
172/**
173 * An eine Session binden. Mitten im Prozess (`started`): bei /clear beginnt der Zähler bei 0 (types:11148-11151), sonst
174 * (Resume, Branch, Reload) wird die Baseline beim nächsten Messen aus dem Datensatz gesetzt.
175 */
176async function bind($: EngineInterface, id: string, source: string | undefined, newTitle: string | undefined) {
177 sessionId = id
178 rec = await load($, id)
179 pendingGap = 0 // gehört zur bisherigen Session
180 gapAt = undefined
181 title = newTitle || rec?.title || ''
182 titleDirty = !!newTitle && newTitle !== rec?.title
183 titleFromSession = !!newTitle
184 if (!started) return
185 if (source === 'clear') seen = (await $.session.usage()).cost?.usd ?? 0
186 else rebase = true
187}
188
189/**
190 * Messpunkt (SPEC Verhalten 4): Zähler lesen, Differenz auf heute buchen, dazu Tokens, Aktivität und Limits des Turns.
191 * `final`: am Session-Ende nur das Nötigste (Budget 1,5 s, CHEATSHEET Limits).
192 */
193async function measure($: EngineInterface, final = false, usage?: Usage & { model?: string }, turn?: TurnInfo): Promise<void> {
194 // Ein Aufruf ohne `breakdown` (kostenlos): Kosten, dazu vorsorglich Kontext-Füllung und Limit-Stände
195 const u = await $.session.usage()
196 const cost = u.cost?.usd
197 const counted = typeof cost === 'number' && Number.isFinite(cost)
198 hasCost = counted // Host ohne Kostenbuch: keine Chat-Buchung, /ledger nennt den Grund; Tokens je Modell trotzdem
199 // Fenster der letzten API-Antwort (types:11386-11390); leer ohne Abo oder vor der ersten Antwort des Prozesses
200 limits = limitsOf(u.rateLimits)
201 if (!sessionId) return
202 let delta = 0
203 if (counted) {
204 if (rebase) {
205 rebase = false
206 seen = baselineFor(rec, cost)
207 }
208 const d = deltaOf(seen, cost)
209 seen = d.seen
210 delta = d.delta
211 }
212 const hasUsage = tokensOf(usage) > 0
213 if (!(delta > 0) && !(titleDirty && rec) && !hasUsage && !turn) return
214 const now = await $.clock.now()
215 if (!final && meta.kind === 'script') meta.kind = kindOf(await $.session.surfaces()) // Desktop meldet sich evtl. erst später
216 await honorReset($)
217 const r = rec ?? newRec({ ...meta, title }, now, 0)
218 if (r.kind === 'script' && meta.kind !== 'script') r.kind = meta.kind
219 if (titleDirty) r.title = title
220 if (counted) bookChat(r, dayKey(now), delta, now, cost)
221 if (hasUsage) bookModel(r, usage?.model ?? '', dayKey(now), usage, now)
222 if (turn) bookTurn(r, dayKey(now), turn, delta, u.context?.percent)
223 let windowed = false
224 if (turn || delta > 0) {
225 bookRate(r, dayKey(now), u.rateLimits)
226 // Der Rest, der beim Start schon auf dem Zähler stand, fiel vor diesem Prozess an: ins Fenster der letzten Buchung
227 const gap = Math.min(pendingGap, delta)
228 pendingGap = 0
229 windowed = bookLim(r, limits, now, 'chat', delta - gap, carry)
230 if (gap > 0 && gapAt !== undefined) bookLimAt(r, gapAt, gap)
231 gapAt = undefined
232 noteCarry(now)
233 }
234 rec = r
235 titleDirty = false
236 await save($)
237 // Beginn der Fenster-Daten für „unvollständig“; einmal je Prozess, nicht im knappen Budget von session.end
238 if (windowed && !final && !limSinceChecked) {
239 limSinceChecked = true
240 if ((await $.store.get('meta:limSince')) === undefined) await $.store.set('meta:limSince', now)
241 }
242}
243
244/**
245 * Modellaufruf eines anderen Mods buchen (SPEC Verhalten 5). `usage` steht auf jedem Zweig des Ergebnisses (types ModelCompleteResult).
246 * `single`: `usage` ist genau eine Anfrage (nur `model.complete`), dann gilt eine Preisstufe nach Prompt-Länge (Haiku 5.5).
247 */
248async function bookCall($: EngineInterface, origin: string | undefined, model: string, usage: unknown, countOnly: boolean, single = false) {
249 const name = pluginName(origin ?? '')
250 if (!name || name === 'engine' || name === SELF || !sessionId) return
251 const now = await $.clock.now()
252 const amount = countOnly ? 0 : callCost(usage as Parameters<typeof callCost>[0], model, single)
253 await honorReset($)
254 rec ??= newRec({ ...meta, title }, now, seen)
255 bookMod(rec, name, dayKey(now), amount, now, countOnly ? undefined : (usage as Usage | undefined))
256 if (!countOnly) {
257 bookModel(rec, model, dayKey(now), usage as Usage | undefined, now, 'modModels', single)
258 // Fenster aus der letzten Messung, kein eigenes usage(): Mod-Aufrufe sollen nicht warten (Verhalten 5)
259 bookLim(rec, limits, now, 'mod', amount, carry)
260 noteCarry(now)
261 }
262 await save($)
263}
264
265/**
266 * Alle Datensätze lesen; dabei alte löschen (älter als `keepDays` seit der letzten Buchung). Das Aufräumen liegt hier und
267 * nicht im awaiteten session.start, weil `/ledger` ohnehin jeden Datensatz liest. `bytes` schätzt die Größe des Speichers
268 * (4 MiB JSON insgesamt, docs/raw/en/reference.md:294).
269 */
270async function collect($: EngineInterface, now: number) {
271 const recs: { id: string; rec: Rec }[] = []
272 let unreadable = 0
273 let bytes = 0
274 let plan: Plan | null = null
275 let limSince: number | null = null
276 const cutoff = now - settings.keepDays * DAY
277 await honorReset($) // Reset aus einem anderen Chat auch ohne neue Buchung beachten
278 for (const key of await $.store.keys()) {
279 const value = await $.store.get(key)
280 bytes += key.length + (JSON.stringify(value ?? null)?.length ?? 0)
281 if (key === 'meta:plan') plan = cleanPlan(value)
282 if (key === 'meta:limSince' && typeof value === 'number') limSince = value
283 if (!key.startsWith('s:')) continue
284 const id = key.slice(2)
285 // Eigener Datensatz aus dem Speicher: der ist mindestens so frisch wie der gespeicherte
286 const r = id === sessionId && rec ? rec : cleanRec(value)
287 if (!r) unreadable++
288 else if (id !== sessionId && r.lastAt < cutoff) await $.store.delete(key)
289 else recs.push({ id, rec: r })
290 }
291 const hasData = (r: Rec) => [r.days, r.mods, r.models, r.modModels, r.act, r.lim].some((x) => Object.keys(x).length > 0)
292 if (rec && sessionId && hasData(rec) && !recs.some((x) => x.id === sessionId)) recs.push({ id: sessionId, rec })
293 const since = await $.store.get('meta:since')
294 return { recs, unreadable, bytes, since: typeof since === 'number' ? since : null, plan, limSince }
295}
296
297/**
298 * `/ledger help` (docs/HELP-SPEC.md §3): Schnappschuss mit Plan, Speicherbelegung und Beginn der Erfassung, nur lesend
299 * (kein Aufräumen, kein Buchen). Scheitert das Lesen, zeigt die Hilfe trotzdem Befehle und Einstellungen.
300 */
301async function helpCommand($: EngineInterface, args: string): Promise<string> {
302 const now = await $.clock.now()
303 const info: HelpInfo = { plan: null, storeBytes: 0, since: null, syncDevice: null }
304 try {
305 let on = false
306 let device: Device | null = null
307 for (const key of await $.store.keys()) {
308 const value = await $.store.get(key)
309 info.storeBytes += key.length + (JSON.stringify(value ?? null)?.length ?? 0)
310 if (key === 'meta:plan') info.plan = cleanPlan(value)
311 if (key === 'meta:since' && typeof value === 'number') info.since = value
312 if (key === 'meta:sync') on = cleanSync(value) !== null
313 if (key === 'meta:device') device = cleanDevice(value, deviceDefault)
314 }
315 info.syncDevice = on && device ? device.name : null
316 } catch (err) {
317 log($, `/ledger help: ${msg(err)}`)
318 }
319 const data = ledgerHelp(settings, info)
320 return helpMarkdown(data, remember(now, { kind: 'help', data, args: normArgs(args) }))
321}
322
323/**
324 * `/ledger plan …`: Abo und Abrechnungstag in `meta:plan` (SPEC Nachtrag 0.5.0, Bedienung). Den Plan kann ein Mod nicht
325 * abfragen (kein Feld in der Mods-API, Login-Daten sind tabu: CLAUDE.md Grundregel 3), deshalb stellt der Nutzer ihn ein.
326 */
327async function planCommand($: EngineInterface, args: string[]): Promise<string> {
328 const t = T[settings.lang]
329 const lang = settings.lang
330 const now = await $.clock.now()
331 const price = (p: Plan) => {
332 const v = p.price ?? PLANS[p.plan]?.price
333 return v === undefined ? t.noPrice : `${t.perMonth(usd(v, lang))}${p.price === undefined ? ` (${t.listPrice})` : ''}`
334 }
335 const first = (args[0] ?? '').toLowerCase()
336 if (!first) {
337 const p = cleanPlan(await $.store.get('meta:plan'))
338 return `${p ? t.planCurrent(planLabel(p.plan), p.day, price(p), dateTime(p.at, lang)) : t.planNone}\n${t.planHelp}`
339 }
340 if (OFF_WORDS.includes(first)) {
341 await $.store.delete('meta:plan')
342 return t.planDeleted
343 }
344 const p = parsePlan(args, now)
345 if (!p) return `${t.planInvalid(args.join(' '))}\n${t.planHelp}`
346 await $.store.set('meta:plan', p)
347 const m = planMonth(p.day, now)
348 return t.planSaved(planLabel(p.plan), p.day, price(p), shortDate(m.start, lang), shortDate(m.next, lang))
349}
350
351// ---------- Geräte-Sync (SPEC Nachtrag 0.7.0) ----------
352// `$.fs` nur im per `/ledger sync` gesetzten, absoluten Ordner: gelesen werden nur `cost-ledger-<id>.json`, geschrieben nur
353// die eigene Datei. Die Rechte-Zeile kennt keine Pfade (en/reference.md:181), deshalb setzt das der Code durch.
354
355const deviceDefault = (id: string) => T[settings.lang].deviceDefault(id)
356
357/** Sync-Einstellung dieses Geräts aus `$.store`; `null` = Sync aus. */
358async function syncConfig($: EngineInterface): Promise<SyncCfg | null> {
359 const s = cleanSync(await $.store.get('meta:sync'))
360 if (!s) return null
361 const device = cleanDevice(await $.store.get('meta:device'), deviceDefault)
362 return device ? { dir: s.dir, device } : null
363}
364
365/** Alle Datensätze dieses Geräts, nur lesend (das Aufräumen bleibt bei `/ledger`). */
366async function ownRecs($: EngineInterface): Promise<{ recs: { id: string; rec: Rec }[]; since: number | null }> {
367 const recs: { id: string; rec: Rec }[] = []
368 for (const key of await $.store.keys()) {
369 if (!key.startsWith('s:')) continue
370 const id = key.slice(2)
371 const r = id === sessionId && rec ? rec : cleanRec(await $.store.get(key))
372 if (r) recs.push({ id, rec: r })
373 }
374 const since = await $.store.get('meta:since')
375 return { recs, since: typeof since === 'number' ? since : null }
376}
377
378/**
379 * Eigene Gerätedatei schreiben. Die Uhr erst unmittelbar davor lesen, dann `meta:syncAt` (für alle Chats des Geräts), dann
380 * die Datei mit demselben Zeitpunkt: So ist `at` in der Datei nicht jünger als `meta:syncAt`, solange nur dieses Gerät
381 * schreibt; bis auf die Millisekunden zwischen zwei gleichzeitigen Chats (dafür der Spielraum in `ownConflict`, Review S1).
382 */
383async function writeOwn($: EngineInterface, cfg: SyncCfg, recs: { id: string; rec: Rec }[], since: number | null) {
384 const at = await $.clock.now()
385 const text = buildFile(cfg.device, since, recs, at)
386 if (utf8Bytes(text) > FILE_LIMIT) throw new Error(T[settings.lang].syncTooBig)
387 await $.store.set('meta:syncAt', at)
388 await $.fs.write(inDir(cfg.dir, fileName(cfg.device.id)), text)
389}
390
391/**
392 * Schreibt ein anderes Gerät mit derselben ID (Speicher kopiert)? Dann ist die eigene Datei deutlich jünger als die letzte
393 * eigene Schreibmarke `meta:syncAt`. Erst die Datei lesen, dann die Marke: Ein anderer Chat dieses Geräts setzt die Marke
394 * vor der Datei. Spielraum eine Minute: Zwei Chats dieses Geräts, die gleichzeitig schreiben, liegen weit darunter.
395 */
396async function ownConflict($: EngineInterface, cfg: SyncCfg, entries: readonly FsEntry[]): Promise<boolean> {
397 const name = fileName(cfg.device.id)
398 if (!entries.some((x) => x.kind === 'file' && x.name === name)) return false
399 const f = parseFile(await $.fs.read(inDir(cfg.dir, name)), cfg.device.id)
400 const at = await $.store.get('meta:syncAt')
401 return !!f && f.at > (typeof at === 'number' ? at : 0) + CONFLICT_SLACK
402}
403
404/** Fremde Gerätedateien lesen; halb geschriebene oder kaputte → letzter gute Stand aus diesem Prozess, sonst „nicht lesbar“. */
405async function readPeers($: EngineInterface, cfg: SyncCfg, entries: readonly FsEntry[]): Promise<{ peers: SyncFile[]; unreadable: number }> {
406 const peers: SyncFile[] = []
407 let unreadable = 0
408 for (const x of entries) {
409 const id = x.kind === 'file' ? idFromName(x.name) : null
410 if (!id || id === cfg.device.id) continue
411 let f: SyncFile | null = null
412 if (x.size <= FILE_LIMIT)
413 try {
414 f = parseFile(await $.fs.read(inDir(cfg.dir, x.name)), id)
415 } catch (err) {
416 log($, `Sync lesen ${x.name}: ${msg(err)}`)
417 }
418 if (f) peerCache.set(id, f)
419 else f = peerCache.get(id) ?? null
420 if (f) peers.push(f)
421 else unreadable++
422 }
423 return { peers, unreadable }
424}
425
426/**
427 * Eine Sync-Runde für `/ledger`: Ordner lesen, eigene Datei schreiben, fremde lesen, zusammenführen. Fehlt der Ordner, wird
428 * weder gelesen noch geschrieben (nicht neu anlegen); das lokale Ergebnis bleibt, der Fehler steht als Hinweis da.
429 */
430async function syncRound($: EngineInterface, cfg: SyncCfg, own: { id: string; rec: Rec }[], since: number | null, now: number) {
431 const info: SyncInfo = { on: true, devices: 1, unreadable: 0, error: '', dupId: false }
432 let entries: FsEntry[]
433 try {
434 entries = await $.fs.list(cfg.dir)
435 } catch (err) {
436 info.error = msg(err)
437 return { recs: own, since, info }
438 }
439 // Doppelte Geräte-ID: Dieses Gerät nimmt eine neue und schreibt ab jetzt dorthin; die alte Datei gehört dem anderen
440 try {
441 if (await ownConflict($, cfg, entries)) {
442 cfg = { dir: cfg.dir, device: { id: newDeviceId(), name: cfg.device.name } }
443 await $.store.set('meta:device', cfg.device)
444 info.dupId = true
445 }
446 } catch (err) {
447 log($, `Sync eigene Datei: ${msg(err)}`)
448 }
449 try {
450 await writeOwn($, cfg, own, since)
451 } catch (err) {
452 info.error = msg(err)
453 }
454 const p = await readPeers($, cfg, entries)
455 info.unreadable = p.unreadable
456 info.devices = 1 + p.peers.length
457 const starts = [since, ...p.peers.map((f) => f.since)].filter((x): x is number => typeof x === 'number')
458 return { recs: mergeRecs(own, p.peers, now - settings.keepDays * DAY), since: starts.length ? Math.min(...starts) : null, info }
459}
460
461/**
462 * Nach einem Turn: eigene Datei höchstens alle 15 Minuten (Marke `meta:syncAt` gilt für alle Chats des Geräts). Den Store
463 * fragt der Prozess erst wieder, wenn ein Schreiben fällig sein kann (Review K2); ein Sync, den ein anderer Chat einschaltet,
464 * greift hier so spätestens nach 15 Minuten.
465 */
466async function syncAfterTurn($: EngineInterface) {
467 const now = await $.clock.now()
468 if (now < nextSyncCheck && nextSyncCheck - now <= SYNC_EVERY) return // rückwärts springende Uhr: neu prüfen
469 nextSyncCheck = now + SYNC_EVERY
470 const cfg = await syncConfig($)
471 if (!cfg) return
472 const at = await $.store.get('meta:syncAt')
473 if (typeof at === 'number' && now >= at && now - at < SYNC_EVERY) {
474 nextSyncCheck = at + SYNC_EVERY
475 return
476 }
477 // Ordner weg (Laufwerk getrennt): nicht neu anlegen, nur beim nächsten /ledger melden
478 await $.fs.list(cfg.dir)
479 const own = await ownRecs($)
480 await writeOwn($, cfg, own.recs, own.since)
481}
482
483/** `/ledger sync …` (SPEC Nachtrag 0.7.0, Bedienung). `rest`: der Rest der Zeile in Originalschreibung (Pfad, Name). */
484async function syncCommand($: EngineInterface, rest: string): Promise<string> {
485 const t = T[settings.lang]
486 const lang = settings.lang
487 const words = rest.split(/\s+/).filter(Boolean)
488 const first = (words[0] ?? '').toLowerCase()
489 if (!first) {
490 const cfg = await syncConfig($)
491 if (!cfg) return t.syncOffState
492 const lines = [t.syncState(cfg.dir, cfg.device.name, cfg.device.id)]
493 try {
494 const p = await readPeers($, cfg, await $.fs.list(cfg.dir))
495 for (const f of p.peers) lines.push(t.syncPeer(f.device.name, dateTime(f.at, lang), Object.keys(f.recs).length))
496 if (p.unreadable) lines.push(t.syncUnreadable(p.unreadable))
497 if (!p.peers.length && !p.unreadable) lines.push(t.syncNoPeers)
498 } catch (err) {
499 lines.push(t.syncFailed(msg(err)))
500 }
501 lines.push(t.syncPrivacy)
502 return lines.join('\n\n')
503 }
504 if (OFF_WORDS.includes(first) && words.length === 1) {
505 await $.store.delete('meta:sync')
506 return t.syncOffDone
507 }
508 const now = await $.clock.now()
509 if (first === NAME_WORD) {
510 const raw = rest.slice(rest.indexOf(words[0]!) + words[0]!.length).trim()
511 if (!raw) return t.syncNameMissing
512 const old = cleanDevice(await $.store.get('meta:device'), deviceDefault)
513 const id = old?.id ?? newDeviceId()
514 const device = { id, name: cleanDeviceName(raw, id, deviceDefault) }
515 await $.store.set('meta:device', device)
516 const cfg = await syncConfig($)
517 if (cfg)
518 try {
519 await $.fs.list(cfg.dir)
520 const own = await ownRecs($)
521 await writeOwn($, cfg, own.recs, own.since)
522 } catch (err) {
523 return `${t.syncNamed(device.name)}\n\n${t.syncFailed(msg(err))}`
524 }
525 return t.syncNamed(device.name)
526 }
527 const dir = validDir(rest, /^[A-Za-z]:/.test(await $.session.root()))
528 if (!dir) return t.syncInvalid(rest.trim())
529 let device = cleanDevice(await $.store.get('meta:device'), deviceDefault) ?? { id: newDeviceId(), name: '' }
530 if (!device.name) device = { id: device.id, name: deviceDefault(device.id) }
531 let entries: FsEntry[] = []
532 try {
533 entries = await $.fs.list(dir)
534 } catch {
535 // Ordner gibt es noch nicht: `$.fs.write` legt ihn an (types:3243-3248)
536 }
537 let renewed = false
538 try {
539 if (await ownConflict($, { dir, device }, entries)) {
540 device = { id: newDeviceId(), name: device.name }
541 renewed = true
542 }
543 } catch (err) {
544 log($, `Sync eigene Datei: ${msg(err)}`)
545 }
546 // Erst schreiben, dann speichern: Lässt sich der Ordner nicht beschreiben, bleibt der Sync aus
547 const own = await ownRecs($)
548 try {
549 await writeOwn($, { dir, device }, own.recs, own.since)
550 } catch (err) {
551 return t.syncUnreachable(msg(err))
552 }
553 await $.store.set('meta:device', device)
554 await $.store.set('meta:sync', { v: 1, dir, at: now })
555 let n = 0
556 try {
557 n = (await readPeers($, { dir, device }, await $.fs.list(dir))).peers.length
558 } catch (err) {
559 log($, `Sync lesen: ${msg(err)}`)
560 }
561 return `${t.syncOn(dir, device.name, n, renewed)}\n\n${t.syncPrivacy}`
562}
563
564async function reset($: EngineInterface): Promise<string> {
565 const t = T[settings.lang]
566 const cfg = await syncConfig($)
567 let answer: string
568 try {
569 // Empfohlene Antwort auf Platz 1 (Fynns Regel für Rückfragen); in -p wird ask abgelehnt (API-DETAILS.md:149-154)
570 answer = await $.ui.ask(cfg ? t.askQuestionSync : t.askQuestion, [t.askCancel, t.askDelete])
571 } catch {
572 return t.notDeletedNoAsk
573 }
574 // Beide Sprachen gelten, falls die Einstellung zwischen Frage und Antwort wechselt
575 if (answer !== T.en.askDelete && answer !== T.de.askDelete) return t.notDeleted
576 const now = await $.clock.now()
577 // Zuerst die Marke: Wer ab jetzt bucht oder /ledger zeigt, verwirft seinen alten Stand (honorReset)
578 await $.store.set('meta:resetAt', now)
579 await serial(async () => {
580 rec = null // Die bisherigen Kosten dieser Session werden nicht neu gebucht: `seen` bleibt
581 carry = {}
582 carryAt = 0
583 pendingGap = 0
584 gapAt = undefined
585 limSinceChecked = false
586 reports.clear()
587 })
588 // Löschen außerhalb der Kette: Mod-Aufrufe warten nur auf das eigene Schreiben (SPEC Verhalten 5).
589 // `meta:plan` bleibt: eine Einstellung, keine Buchung (SPEC Nachtrag 0.5.0, Verhalten 5); ebenso Sync und Gerät (0.7.0)
590 const keep = ['meta:resetAt', 'meta:plan', 'meta:sync', 'meta:device', 'meta:syncAt']
591 let n = 0
592 let hadLimits = false
593 for (const key of await $.store.keys()) {
594 if (keep.includes(key) || (!key.startsWith('s:') && !key.startsWith('meta:'))) continue
595 if (key === 'meta:limSince') hadLimits = true
596 await $.store.delete(key)
597 if (key.startsWith('s:')) n++
598 }
599 await $.store.set('meta:since', now)
600 // Die Fenster-Daten beginnen mit dem Reset neu. Gleich setzen statt löschen: Sonst setzte der nächste Prozess, der ein
601 // Fenster bucht, einen späteren Beginn, und Fenster anderer Chats seit dem Reset gälten als unvollständig (Review 0.5.0)
602 if (hadLimits) await $.store.set('meta:limSince', now)
603 // Nur dieses Gerät: seine Datei leer neu schreiben, andere Geräte behalten ihre (SPEC Nachtrag 0.7.0, Verhalten 6)
604 if (cfg)
605 try {
606 await $.fs.list(cfg.dir)
607 await writeOwn($, cfg, [], now)
608 } catch (err) {
609 return `${t.cleared(n)}\n\n${t.syncFailed(msg(err))}`
610 }
611 return t.cleared(n)
612}
613
614export function register(on: On, options: Readonly<Record<string, string | number | boolean | readonly string[]>>) {
615 settings = cleanSettings(options)
616
617 on('session.start', async ($, e, next) => {
618 try {
619 await serial(async () => {
620 const root = await $.session.root()
621 const repo = await $.session.repo()
622 meta.root = root
623 meta.project = projectOf(repo?.name, root)
624 meta.remote = cleanRemote(repo?.remote) // nur host/owner/repo, nie Zugangsdaten
625 meta.kind = kindOf(await $.session.surfaces())
626 if (sessionId && !rec) rec = await load($, sessionId)
627 const cost = (await $.session.usage()).cost?.usd
628 hasCost = typeof cost === 'number'
629 // Resume zählt `cost` weiter: Baseline = gespeicherter Stand, sonst der aktuelle → keine Doppelbuchung
630 seen = typeof cost === 'number' ? baselineFor(rec, cost) : 0
631 // Was zwischen letzter Buchung und Prozessende anfiel (hartes Ende), bucht der nächste Messpunkt nach
632 pendingGap = typeof cost === 'number' ? Math.max(0, cost - seen) : 0
633 gapAt = pendingGap > 0 ? rec?.lastAt : undefined
634 rebase = false
635 started = true
636 if ((await $.store.get('meta:since')) === undefined) await $.store.set('meta:since', await $.clock.now())
637 })
638 } catch (err) {
639 log($, `Start: ${msg(err)}`)
640 }
641 try {
642 await $.command.register({
643 name: 'ledger',
644 description: T[settings.lang].commandDescription,
645 argumentHint: '[weeks|chats|projects|models|limits|plan|sync|reset|help]',
646 })
647 } catch (err) {
648 log($, `/ledger nicht registriert: ${msg(err)}`)
649 }
650 return next(e)
651 })
652
653 // Session-ID und Titel; /clear, /resume und /branch wechseln die Session ohne neues session.start (interface.md:786)
654 on('classic.SessionStart', async ($, e, next) => {
655 try {
656 await serial(async () => {
657 if (e.session_id && e.session_id !== sessionId) await bind($, e.session_id, e.source, e.session_title)
658 else if (e.session_title && e.session_title !== title) {
659 title = e.session_title
660 titleDirty = true
661 titleFromSession = true
662 }
663 })
664 } catch (err) {
665 log($, `SessionStart: ${msg(err)}`)
666 }
667 return next(e)
668 })
669
670 // Titel nur merken; geschrieben wird beim nächsten Buchen. Nach einem Modul-Reload feuert nur session.start, nicht
671 // classic.SessionStart (types:4173-4178, interface.md:789): dann bindet die Session-ID von hier (BaseHookInput)
672 on('classic.UserPromptSubmit', async ($, e, next) => {
673 try {
674 await serial(async () => {
675 if (e.session_id && e.session_id !== sessionId) await bind($, e.session_id, undefined, e.session_title)
676 else if (e.session_title && e.session_title !== title) {
677 title = e.session_title
678 titleDirty = true
679 titleFromSession = true
680 }
681 // Ohne Titel vom Host: die erste eigene Nachricht benennt den Chat (keine System- oder Weck-Prompts). Nicht bei
682 // Skript-Läufen (-p): Skripte schicken oft fremden Text, der sonst in /ledger bei Claude landet
683 const own = e.source === undefined || e.source === 'user' || e.source === 'sdk'
684 if (!title && !titleFromSession && own && meta.kind !== 'script') {
685 const t = titleFromPrompt(e.prompt)
686 if (t) {
687 title = t
688 titleDirty = true
689 }
690 }
691 })
692 } catch (err) {
693 log($, `UserPromptSubmit: ${msg(err)}`)
694 }
695 return next(e)
696 })
697
698 on('turn.complete', async ($, e, next) => {
699 const r = await next(e)
700 try {
701 if (!e.agentId && e.usage?.model) lastModel = e.usage.model
702 // Tokens je Modell aus der Usage des Turns (TurnUsage: Summe seiner Anfragen, Modell der letzten), auch Subagents
703 await serial(() => measure($, false, e.usage, { agentId: e.agentId, durationMs: e.durationMs, reason: e.reason, isAborted: e.isAborted }))
704 } catch (err) {
705 log($, `Buchen: ${msg(err)}`)
706 }
707 try {
708 await syncAfterTurn($) // außerhalb der Kette: Mod-Aufrufe und session.end warten nicht auf den Ordner (Review K1)
709 } catch (err) {
710 log($, `Sync schreiben: ${msg(err)}`)
711 }
712 return r
713 })
714
715 // Modellaufrufe anderer Mods: `next(e)` liefert `{ value }` oder `{ deny }` (types OpEventResult). Nie ändern, nie verzögern
716 // außer um das eigene Schreiben; den eigenen Hook überspringt die Engine ohnehin (types OpEventOf).
717 on('model.complete', async ($, e, next) => {
718 const r = await next(e)
719 try {
720 if ('value' in r) await serial(() => bookCall($, next.origin?.plugin, e.model, r.value.usage, false, true))
721 } catch (err) {
722 log($, `Mod-Aufruf: ${msg(err)}`)
723 }
724 return r
725 })
726
727 on('model.fork', async ($, e, next) => {
728 const r = await next(e)
729 try {
730 // Der Fork läuft auf dem Modell der Hauptschleife; „nothing-to-fork“ hat keine Usage und kostet nichts
731 if ('value' in r && 'usage' in r.value) await serial(() => bookCall($, next.origin?.plugin, lastModel, r.value.usage, false))
732 } catch (err) {
733 log($, `Mod-Aufruf: ${msg(err)}`)
734 }
735 return r
736 })
737
738 // classify liefert nur einen String ohne Usage: nur die Anzahl zählt (types:6539-6546, :6871)
739 on('model.classify', async ($, e, next) => {
740 const r = await next(e)
741 try {
742 if ('value' in r) await serial(() => bookCall($, next.origin?.plugin, '', undefined, true))
743 } catch (err) {
744 log($, `Mod-Aufruf: ${msg(err)}`)
745 }
746 return r
747 })
748
749 // Letzte Buchung; ein Schreibvorgang, kein Warten auf anderes (Budget 1,5 s)
750 on('session.end', async ($, e, next) => {
751 try {
752 await serial(() => measure($, true))
753 } catch (err) {
754 log($, `Ende: ${msg(err)}`)
755 }
756 return next(e)
757 })
758
759 on('command.run', { command: 'ledger' }, async ($, e) => {
760 const t = T[settings.lang]
761 const [sub = '', ...rest] = e.args.trim().split(/\s+/)
762 const arg = rest[0]
763 const what = sub.toLowerCase()
764 // Hilfe: nur das erste Wort, ohne weitere Wörter (docs/HELP-SPEC.md §2)
765 if (HELP_WORDS.includes(what)) return { text: rest.length ? t.unknownArg(e.args.trim()) : await helpCommand($, e.args) }
766 // Speicher voll o. Ä.: ein lesbarer Hinweis statt einer Fehlerzeile (Review 0.5.0 K1)
767 if (what === 'reset' || what === 'plan' || what === SYNC_WORD) {
768 try {
769 if (what === SYNC_WORD) return { text: await syncCommand($, e.args.trim().slice(sub.length).trim()) }
770 return { text: what === 'reset' ? await reset($) : await planCommand($, rest) }
771 } catch (err) {
772 log($, `/ledger ${what}: ${msg(err)}`)
773 return { text: t.writeFailed(msg(err)) }
774 }
775 }
776 if (what && !VIEW_WORDS.includes(what)) return { text: t.unknownArg(sub) }
777 try {
778 await serial(() => measure($)) // den laufenden Chat mitzählen
779 } catch (err) {
780 log($, `Buchen vor /ledger: ${msg(err)}`)
781 }
782 const views: Record<string, View['view']> = { chats: 'chats', projects: 'projects', models: 'models', weeks: 'weeks', limits: 'limits' }
783 const view = views[what] ?? 'overview'
784 const range = view === 'overview' || view === 'weeks' || view === 'limits' ? 30 : parseRange(arg)
785 const now = await $.clock.now()
786 const data = await collect($, now)
787 // Andere Geräte dazu; ohne Sync oder bei Fehlern bleibt es beim lokalen Kostenbuch
788 let recs = data.recs
789 let since = data.since
790 let sync: SyncInfo | undefined
791 try {
792 const cfg = await syncConfig($)
793 if (cfg) ({ recs, since, info: sync } = await syncRound($, cfg, data.recs, data.since, now))
794 } catch (err) {
795 log($, `Sync: ${msg(err)}`)
796 }
797 const report = aggregate(recs, now, {
798 range,
799 unreadable: data.unreadable,
800 hasCost,
801 since,
802 sync,
803 storeBytes: data.bytes,
804 writeError,
805 plan: data.plan,
806 limSince: data.limSince,
807 live: limits,
808 })
809 // Eindeutige Kennung im Text: ui.render findet darüber die Daten der Zeichnung (SPEC Verhalten 7)
810 const tag = remember(now, { kind: 'ledger', view: { report, view, range }, args: normArgs(e.args) })
811 return { text: summaryText(report, view, range, tag, settings.lang) }
812 })
813
814 // Die Übersicht und die Hilfe: ein eigener Baum statt der Markdown-Zeile; „a hook's own tree draws in the row's place“
815 // (types CommandOutput). `command` gehört zu den Props, daher `props: { command }` im Matcher (oben auf `e` feuert er nie).
816 on('ui.render', { component: 'CommandOutput', props: { command: 'ledger' } }, async ($, e, next) => {
817 if (e.props.isErrored || (e.surface !== 'terminal' && e.surface !== 'desktop')) return next(e)
818 // Kennung irgendwo in der ersten Zeile: in -p steht davor „cost-ledger: “ (HELP-SPEC §8 Punkt 1)
819 const tag = /#[0-9a-z]{5,}/.exec(e.props.text.split('\n')[0] ?? '')?.[0]
820 const d = tag ? reports.get(tag) : undefined
821 // Unbekannt (nach Neustart, alte Zeile, reset, plan): die Engine zeichnet den Markdown-Text
822 if (!d || d.args !== normArgs(e.props.args)) return next(e)
823 const columns = e.viewport?.columns ?? 100
824 return d.kind === 'help' ? helpTree(d.data, columns, e.surface, ACCENT) : ledgerTree(d.view, settings, columns, e.surface)
825 })
826}
827hooks/help.ts 205 lines1// help.ts: die gezeichnete Hilfe-Tabelle für `/<befehl> help` (docs/HELP-SPEC.md §3-§4). Allgemein gehalten: Eine Mod
2// liefert nur `HelpData` und ihre Akzentfarbe; Aufbau, Spalten, Farben der Schalter und die Markdown-Fassung stehen hier.
3// Vorlage für alle Mods: templates/help/ (README dort). Ohne `$`, nur Daten → Baum bzw. Text, deshalb ohne Engine testbar.
4//
5// Baum aus reinen Daten {type, props, children} (types RenderElement), nur Box und Text mit erlaubten Props. Desktop:
6// Spaltenbreiten nur als ganzzahlige Prozent, sonst verwirft er den ganzen Baum (cost-ledger 0.3.1). Unter 60 Spalten
7// stehen die Spalten untereinander.
8import type { RenderElement, RenderNode } from 'claude-code'
9
10export type HelpLang = 'en' | 'de'
11export type HelpSurface = 'terminal' | 'desktop'
12
13/** Eine Zeile unter BEFEHLE bzw. BEDIENUNG: Befehl oder Bedienelement (Akzentfarbe) und seine Wirkung. */
14export type HelpCommand = { cmd: string; does: string }
15/**
16 * Zustand einer Funktion: Schalter (`on` → „● an“ in `success`, `off` → „○ aus“ in `inactive`) oder ein Wert als Text, mit
17 * „(Standard)“, wenn `isDefault`. `text` ersetzt „an“/„aus“; bei `on` steht er dann in der normalen Schriftfarbe (lange
18 * Texte bleiben lesbar), nur der Punkt ist grün.
19 */
20export type HelpState = { kind: 'on' | 'off'; text?: string } | { kind: 'value'; text: string; isDefault?: boolean }
21/** Eine Zeile unter FUNKTIONEN; `toggle` ist der Befehl, der den Zustand ändert, sonst z. B. „Einstellung“ oder „nur Info“. */
22export type HelpFeature = { name: string; state: HelpState; toggle: string }
23/** Eine Zeile unter EINSTELLUNGEN: Titel des userConfig-Felds (übersetzt) und sein aktueller Wert. */
24export type HelpSetting = { title: string; value: string; isDefault?: boolean }
25/** Schnappschuss beim Aufruf von `help`; die Zeichnung schreibt sich danach nicht um (HELP-SPEC §3 Punkt 3). */
26export type HelpData = {
27 /** Name der Mod im Titel */
28 mod: string
29 lang: HelpLang
30 /** Ein Satz, was die Mod macht */
31 intro: string
32 commands: HelpCommand[]
33 /** Gedimmte Zeilen unter den Befehlen (z. B. Aliase) */
34 notes?: string[]
35 /** BEDIENUNG: nur, wenn es Klicks oder Tasten gibt */
36 controls?: HelpCommand[]
37 features: HelpFeature[]
38 settings: HelpSetting[]
39 /** Weg zum Ändern der Einstellungen und zum Abschalten der Mod; Terminal und Desktop brauchen verschiedene Wege */
40 footer: { terminal: string; desktop: string }
41}
42
43const LABELS = {
44 en: {
45 help: 'Help',
46 commands: 'COMMANDS',
47 controls: 'CONTROLS',
48 features: 'FEATURES',
49 status: 'STATUS',
50 toggle: 'TOGGLE',
51 settings: 'SETTINGS (/plugin)',
52 value: 'VALUE',
53 on: 'on',
54 off: 'off',
55 isDefault: '(default)',
56 },
57 de: {
58 help: 'Hilfe',
59 commands: 'BEFEHLE',
60 controls: 'BEDIENUNG',
61 features: 'FUNKTIONEN',
62 status: 'STATUS',
63 toggle: 'UMSCHALTEN',
64 settings: 'EINSTELLUNGEN (/plugin)',
65 value: 'WERT',
66 on: 'an',
67 off: 'aus',
68 isDefault: '(Standard)',
69 },
70} as const
71
72export function helpLabels(lang: HelpLang) {
73 return LABELS[lang]
74}
75
76type Props = Record<string, string | number | boolean>
77const el = (type: 'Box' | 'Text', props: Props, children: RenderNode[]): RenderElement => ({ type, props, children })
78const text = (s: string, props: Props = {}) => el('Text', props, [s])
79const dim = (s: string) => text(s, { dimColor: true })
80const row = (props: Props, kids: RenderNode[]) => el('Box', { flexDirection: 'row', ...props }, kids)
81const col = (props: Props, kids: RenderNode[]) => el('Box', { flexDirection: 'column', ...props }, kids)
82const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v))
83
84/** Zustand als Text (für die Markdown-Fassung und zum Messen der Spaltenbreite). */
85export function stateText(s: HelpState, lang: HelpLang): string {
86 const L = LABELS[lang]
87 if (s.kind === 'value') return s.isDefault ? `${s.text} ${L.isDefault}` : s.text
88 return `${s.kind === 'on' ? '●' : '○'} ${s.text ?? (s.kind === 'on' ? L.on : L.off)}`
89}
90
91/**
92 * Zustand gezeichnet: „● an“ in `success`, „○ aus“ in `inactive`; mit eigenem Text bei `on` nur der Punkt grün. Werte in
93 * der normalen Schriftfarbe, „(Standard)“ gedimmt.
94 */
95function stateNode(s: HelpState, lang: HelpLang): RenderElement {
96 const L = LABELS[lang]
97 if (s.kind === 'value') return el('Text', {}, [text(s.text), ...(s.isDefault ? [dim(` ${L.isDefault}`)] : [])])
98 const on = s.kind === 'on'
99 const label = s.text ?? (on ? L.on : L.off)
100 const labelProps: Props = on ? (s.text === undefined ? { color: 'success' } : {}) : { color: 'inactive' }
101 return el('Text', {}, [text(on ? '● ' : '○ ', { color: on ? 'success' : 'inactive' }), text(label, labelProps)])
102}
103
104/**
105 * Spalten einer Zeile. Terminal: feste Zellen, die letzte füllt den Rest. Desktop: ganzzahlige Prozent mit Summe 100
106 * (`share` = gewünschte Breite in Zeichen, daraus die Anteile).
107 */
108function columns(sf: HelpSurface, inner: number, widths: number[], kids: RenderNode[], props: Props = {}): RenderElement {
109 if (sf === 'desktop') {
110 const pct = widths.slice(0, -1).map((w) => clamp(Math.round((w / inner) * 100), 10, 60))
111 const rest = Math.max(10, 100 - pct.reduce((a, b) => a + b, 0))
112 const all = [...pct, rest]
113 // Summe genau 100: Überhang vom größten Anteil abziehen
114 const over = all.reduce((a, b) => a + b, 0) - 100
115 if (over > 0) all[all.indexOf(Math.max(...all))]! -= over
116 return row(props, kids.map((k, i) => el('Box', { width: `${all[i]}%`, paddingRight: 1 }, [k])))
117 }
118 return row(
119 props,
120 kids.map((k, i) => (i < kids.length - 1 ? el('Box', { width: widths[i]!, flexShrink: 0 }, [k]) : el('Box', { flexGrow: 1, flexShrink: 1 }, [k]))),
121 )
122}
123
124const heading = (s: string, accent: string) => text(s, { color: accent, bold: true })
125
126/**
127 * Der ganze Baum für eine `CommandOutput`-Zeile. `columns` ist `e.viewport?.columns` (begrenzt auf 30-140), `accent` die
128 * Akzentfarbe der Mod (Hex oder Theme-Key), nur für Titel, Überschriften und Befehle.
129 */
130export function helpTree(d: HelpData, columnsHint: number, surface: HelpSurface, accent: string): RenderElement {
131 const L = LABELS[d.lang]
132 const cols = clamp(columnsHint || 100, 30, 140)
133 const inner = cols - 4 // Rahmen und paddingX
134 const narrow = cols < 60
135 const kids: RenderNode[] = [heading(`${d.mod} · ${L.help}`, accent), text(d.intro)]
136
137 const commandRows = (title: string, list: HelpCommand[]) => {
138 if (!list.length) return
139 kids.push(el('Box', { marginTop: 1 }, [heading(title, accent)]))
140 const cmdW = clamp(Math.max(...list.map((c) => c.cmd.length)) + 2, 12, Math.floor(inner * 0.5))
141 for (const c of list)
142 kids.push(
143 narrow
144 ? col({}, [text(c.cmd, { color: accent }), el('Box', { paddingLeft: 2 }, [text(c.does)])])
145 : columns(surface, inner, [cmdW, inner - cmdW], [text(c.cmd, { color: accent }), text(c.does)]),
146 )
147 }
148 commandRows(L.commands, d.commands)
149 for (const n of d.notes ?? []) kids.push(dim(n))
150 commandRows(L.controls, d.controls ?? [])
151
152 if (d.features.length) {
153 const nameW = clamp(Math.max(L.features.length, ...d.features.map((f) => f.name.length)) + 2, 12, Math.floor(inner * 0.34))
154 const stateW = clamp(Math.max(L.status.length, ...d.features.map((f) => stateText(f.state, d.lang).length)) + 2, 10, Math.floor(inner * 0.4))
155 if (narrow) {
156 kids.push(el('Box', { marginTop: 1 }, [heading(L.features, accent)]))
157 // Zustand und Umschalten in einem Text, damit sie als ein Absatz umbrechen statt als zwei schmale Spalten
158 for (const f of d.features)
159 kids.push(col({}, [text(f.name), el('Box', { paddingLeft: 2 }, [el('Text', {}, [stateNode(f.state, d.lang), dim(` · ${f.toggle}`)])])]))
160 } else {
161 const widths = [nameW, stateW, inner - nameW - stateW]
162 kids.push(columns(surface, inner, widths, [heading(L.features, accent), heading(L.status, accent), heading(L.toggle, accent)], { marginTop: 1 }))
163 for (const f of d.features) kids.push(columns(surface, inner, widths, [text(f.name), stateNode(f.state, d.lang), dim(f.toggle)]))
164 }
165 }
166
167 if (d.settings.length) {
168 const titleW = clamp(Math.max(L.settings.length, ...d.settings.map((s) => s.title.length)) + 2, 12, Math.floor(inner * 0.5))
169 const value = (s: HelpSetting) => stateNode({ kind: 'value', text: s.value, isDefault: s.isDefault }, d.lang)
170 if (narrow) {
171 kids.push(el('Box', { marginTop: 1 }, [heading(L.settings, accent)]))
172 for (const s of d.settings) kids.push(col({}, [text(s.title), el('Box', { paddingLeft: 2 }, [value(s)])]))
173 } else {
174 const widths = [titleW, inner - titleW]
175 kids.push(columns(surface, inner, widths, [heading(L.settings, accent), heading(L.value, accent)], { marginTop: 1 }))
176 for (const s of d.settings) kids.push(columns(surface, inner, widths, [text(s.title), value(s)]))
177 }
178 }
179
180 kids.push(el('Box', { marginTop: 1 }, [dim(surface === 'desktop' ? d.footer.desktop : d.footer.terminal)]))
181 return col({ borderStyle: 'round', borderDimColor: true, paddingX: 1, width: '100%', key: `${d.mod}-help` }, kids)
182}
183
184/**
185 * Kompakte Markdown-Fassung: was Claude mitliest und was `-p`, das SDK und VS Code zeigen. `tag` (Kennung `#…`) steht in
186 * der ersten Zeile, darüber findet der Render-Hook den Schnappschuss. Fußzeile mit dem Terminal-Weg. Leerzeilen zwischen
187 * den Blöcken: Sonst hängt Markdown (CommonMark) alles nach einer Liste an deren letzten Punkt.
188 */
189export function helpMarkdown(d: HelpData, tag: string): string {
190 const L = LABELS[d.lang]
191 const lines = [`**${d.mod} · ${L.help}**${tag ? ` · ${tag}` : ''}`, '', d.intro]
192 const list = (title: string, items: HelpCommand[]) => {
193 if (!items.length) return
194 lines.push('', `**${title}**`, ...items.map((c) => `- \`${c.cmd}\`: ${c.does}`))
195 }
196 list(L.commands, d.commands)
197 if (d.notes?.length) lines.push('', ...d.notes)
198 list(L.controls, d.controls ?? [])
199 if (d.features.length) lines.push('', `**${L.features}:** ${d.features.map((f) => `${f.name} ${stateText(f.state, d.lang)} (${f.toggle})`).join(' · ')}`)
200 if (d.settings.length)
201 lines.push('', `**${L.settings}:** ${d.settings.map((s) => `${s.title} ${s.value}${s.isDefault ? ` ${L.isDefault}` : ''}`).join(' · ')}`)
202 lines.push('', d.footer.terminal)
203 return lines.join('\n')
204}
205hooks/i18n.ts 444 lines1// cost-ledger: Texte und Formatierer für Englisch und Deutsch (release/I18N.md). Ohne `$`, ohne `Intl`: selbst formatiert.
2// Sprache aus userConfig `language`; Standard Englisch.
3
4export type Lang = 'en' | 'de'
5
6export function langOf(v: unknown): Lang {
7 return v === 'de' ? 'de' : 'en'
8}
9
10const pad = (n: number) => String(n).padStart(2, '0')
11const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
12
13/** en `$1,234.50`, `< $0.01`, `$0.00`; de `1.234,50 $`, `< 0,01 $`, `0,00 $`. */
14export function usd(v: number, lang: Lang): string {
15 if (lang === 'de') {
16 if (!(v > 0)) return '0,00 $'
17 if (v < 0.005) return '< 0,01 $'
18 return `${v.toFixed(2).replace('.', ',').replace(/\B(?=(\d{3})+(?!\d),)/g, '.')} $`
19 }
20 if (!(v > 0)) return '$0.00'
21 if (v < 0.005) return '< $0.01'
22 return `$${v.toFixed(2).replace(/\B(?=(\d{3})+(?!\d)\.)/g, ',')}`
23}
24
25/** Tag `YYYY-MM-DD` kurz: en `Oct 6`, de `06.10.` */
26export function shortDate(key: string, lang: Lang): string {
27 const [, m = '1', d = '1'] = key.split('-')
28 return lang === 'de' ? `${d}.${m}.` : `${MONTHS[Number(m) - 1]} ${Number(d)}`
29}
30
31/** Zeitpunkt mit Uhrzeit: en `Oct 6 14:05`, de `06.10. 14:05` */
32export function dateTime(ms: number, lang: Lang): string {
33 const d = new Date(ms)
34 const day = lang === 'de' ? `${pad(d.getDate())}.${pad(d.getMonth() + 1)}.` : `${MONTHS[d.getMonth()]} ${d.getDate()}`
35 return `${day} ${pad(d.getHours())}:${pad(d.getMinutes())}`
36}
37
38/** Datum mit Jahr: en `Oct 6, 2026`, de `06.10.2026` */
39export function fullDate(ms: number, lang: Lang): string {
40 const d = new Date(ms)
41 return lang === 'de' ? `${pad(d.getDate())}.${pad(d.getMonth() + 1)}.${d.getFullYear()}` : `${MONTHS[d.getMonth()]} ${d.getDate()}, ${d.getFullYear()}`
42}
43
44/** Kalenderwoche: en `W41`, de `KW 41` */
45export function weekLabel(week: number, lang: Lang): string {
46 return lang === 'de' ? `KW ${week}` : `W${week}`
47}
48
49/** Tokens kurz: `412k`, en `1.2M`, de `1,2M` */
50export function tokens(n: number, lang: Lang): string {
51 const v = Math.max(0, Math.round(n || 0))
52 const dec = (x: number) => (lang === 'de' ? x.toFixed(1).replace('.', ',') : x.toFixed(1))
53 if (v >= 1e6) return `${dec(v / 1e6)}M`
54 if (v >= 1e4) return `${Math.round(v / 1e3)}k`
55 if (v >= 1e3) return `${dec(v / 1e3)}k`
56 return String(v)
57}
58
59const WEEKDAYS: Record<Lang, string[]> = { en: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], de: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'] }
60
61/** Uhrzeit `HH:MM` (lokal) */
62export function clock(ms: number): string {
63 const d = new Date(ms)
64 return `${pad(d.getHours())}:${pad(d.getMinutes())}`
65}
66
67/** Reset-Zeitpunkt: am selben Tag nur die Uhrzeit, sonst en `Mon Oct 12 04:00`, de `Mo 12.10. 04:00` */
68export function resetTime(ms: number, now: number, lang: Lang): string {
69 const d = new Date(ms)
70 const n = new Date(now)
71 if (d.getFullYear() === n.getFullYear() && d.getMonth() === n.getMonth() && d.getDate() === n.getDate()) return clock(ms)
72 return `${WEEKDAYS[lang][d.getDay()]} ${dateTime(ms, lang)}`
73}
74
75/** Dauer, abgerundet: `3 h 50 min`, `12 min`, en `3 d 10 h`, de `3 T 10 h`; unter einer Minute `< 1 min` */
76export function duration(ms: number, lang: Lang): string {
77 const m = Math.floor(Math.max(0, ms) / 60000)
78 if (m < 1) return '< 1 min'
79 const d = Math.floor(m / 1440)
80 const h = Math.floor((m % 1440) / 60)
81 if (d > 0) return `${d} ${lang === 'de' ? 'T' : 'd'} ${h} h`
82 return h > 0 ? `${h} h ${m % 60} min` : `${m} min`
83}
84
85/** Auslastung ganzzahlig: `62 %` */
86export function pct(v: number): string {
87 return `${Math.round(v || 0)} %`
88}
89
90/** Faktor mit einer Stelle: en `4.1`, de `4,1` */
91export function factor(v: number, lang: Lang): string {
92 const s = (Number.isFinite(v) ? v : 0).toFixed(1)
93 return lang === 'de' ? s.replace('.', ',') : s
94}
95
96/**
97 * Fenster von–bis mit dem Datum des Beginns: de `08.10. 13–18`, en `Oct 8 16:10–21:10`; volle Stunden ohne Minuten,
98 * ein Ende um Mitternacht als `24`.
99 */
100export function span(start: number, end: number, lang: Lang): string {
101 const s = new Date(start)
102 const e = new Date(end)
103 const hours = s.getMinutes() === 0 && e.getMinutes() === 0
104 const endH = e.getHours() === 0 && e.getMinutes() === 0 && e.getDate() !== s.getDate() ? 24 : e.getHours()
105 const fmt = (h: number, m: number) => (hours ? pad(h) : `${pad(h)}:${pad(m)}`)
106 const day = lang === 'de' ? `${pad(s.getDate())}.${pad(s.getMonth() + 1)}.` : `${MONTHS[s.getMonth()]} ${s.getDate()}`
107 return `${day} ${fmt(s.getHours(), s.getMinutes())}–${fmt(endH, e.getMinutes())}`
108}
109
110/** Zeitraum in Tagen, 0 = alles: en `7 days`/`all time`, de `7 Tage`/`gesamt` */
111export function rangeLabel(range: number, lang: Lang): string {
112 if (range <= 0) return lang === 'de' ? 'gesamt' : 'all time'
113 return lang === 'de' ? `${range} Tage` : `${range} days`
114}
115
116const en = {
117 asOf: (t: string) => `as of ${t}`,
118 since: (d: string) => `since ${d}`,
119 reload: (cmd: string) => `reload: ${cmd}`,
120 empty: 'No entries yet. Counting starts now, after every answer.',
121 today: 'Today',
122 days7: '7 days',
123 days30: '30 days',
124 allTime: 'All time',
125 chats: (n: number) => `${n} ${n === 1 ? 'chat' : 'chats'}`,
126 last14Days: 'Last 14 days',
127 last14Weeks: 'Last 14 weeks',
128 highest: '← highest',
129 noData: 'no data',
130 modsPart: (model: string) => `${model} · mods`,
131 modsNoData: 'mods, no data',
132 unknownModel: 'Unknown',
133 projectsIn: (range: string) => `Projects · ${range}`,
134 chatsIn: (range: string) => `Most expensive chats · ${range}`,
135 modelsIn: (range: string) => `Models · ${range}`,
136 modsIn: (range: string) => `Mods · ${range}`,
137 noCosts: 'no costs in this period',
138 more: (n: number) => `+${n} more`,
139 noModCalls: 'no model calls by other mods in this period',
140 modsExtra: 'adds to the chat costs, not included in /cost',
141 tokenLine: (i: string, o: string, cr: string, cw: string) => `Input ${i} · Output ${o} · Cache ${cr} read, ${cw} written`,
142 noTokens: 'No answers with token data in this period yet.',
143 modelsNote: 'Amount estimated from tokens × price table; includes model calls by other mods.',
144 foot: 'API value; on a subscription it counts against your usage limits · /ledger weeks · chats · projects · models · help',
145 noCost: 'This host reports no chat costs; only model calls by mods are recorded.',
146 unreadable: (n: number) => `${n} ${n === 1 ? 'entry' : 'entries'} unreadable.`,
147 storeFull: (pct: number) => `Storage ${pct} % full (4 MiB): lower the retention (keepDays).`,
148 writeFailed: (err: string) => `Saving failed last time: ${err}`,
149 scriptRuns: 'Script runs',
150 noFolder: '(no folder)',
151 chatFrom: (t: string) => `Chat from ${t}`,
152 sumTitle: (t: string, tag: string) => `**Cost ledger** · as of ${t} · ${tag}`,
153 sumChats: (today: string, n: number, d7: string, d30: string, all: string) => `Chats: today ${today} (${n}) · 7 days ${d7} · 30 days ${d30} · all time ${all}`,
154 sumMods: (today: string, d30: string, all: string) => `Mods: today ${today} · 30 days ${d30} · all time ${all}`,
155 sumProjects: (list: string) => `Projects (30 days): ${list}`,
156 sumTopChats: (list: string) => `Most expensive chats (30 days): ${list}`,
157 sumModsList: (list: string) => `Mods (30 days): ${list}`,
158 sumWeeks: (list: string) => `Weeks (chat + mods): ${list}`,
159 sumChatsHead: (range: string, shown: number, total: number) => `Most expensive chats (${range}), ${shown} of ${total}:`,
160 sumModelsHead: (range: string) => `Models (${range}), estimated API value from tokens, incl. mod calls:`,
161 sumModelLine: (name: string, amt: string, pct: number, n: number, line: string) => `${name}: ${amt} (${pct} %) · ${n}× · ${line}`,
162 sumMoreModels: (n: number) => `+${n} more models`,
163 sumProjectsHead: (range: string) => `Projects (${range}):`,
164 sumProjectRow: (name: string, amt: string, n: number) => `${name} ${amt} (${n} ${n === 1 ? 'chat' : 'chats'})`,
165 sumFoot: 'Model calls by mods add to the chat costs (not included in /cost). API value; on a subscription it counts against your usage limits.',
166 unknownArg: (s: string) => `Unknown: “${s}”. All commands: /ledger help`,
167 // /ledger help (0.6.0, docs/HELP-SPEC.md)
168 helpIntro: 'Records what your chats and other mods cost (API value) after every answer and shows it by day, project, chat, model and limit window.',
169 helpOverview: 'Overview: today, 7 and 30 days, all time, last 14 days, projects, most expensive chats, mods',
170 helpWeeks: 'The overview with the last 14 calendar weeks',
171 helpLists: 'Most expensive chats · all projects · models with tokens; default 30 days, any number of days from 1 to 3650',
172 helpLimits: '5-hour and weekly window, subscription month, last 5-hour windows',
173 helpPlanShow: 'Show the plan setting and its syntax',
174 helpPlanSet: 'Set plan (pro, max5 or 5x/max5x, max20 or 20x/max20x, team, enterprise), billing day 1–31 and monthly price in $',
175 helpPlanOff: 'Delete the plan setting',
176 helpReset: 'Delete all entries (asks first; the plan stays)',
177 helpHelp: 'This help (also: ?)',
178 helpAliases: 'German words work too: hilfe, alle, heute, aus.',
179 helpPlanName: 'Subscription plan',
180 helpDay: (d: number) => `day ${d}`,
181 helpNoPlan: 'not set',
182 helpStorageName: 'Storage used',
183 helpStorage: (pct: number) => `${pct} % of 4 MiB`,
184 helpSinceName: 'Recording since',
185 helpInfo: 'info only',
186 setLanguage: 'Language',
187 setKeepDays: 'Retention (days)',
188 setDayYellow: 'Daily amount yellow from ($)',
189 setDayRed: 'Daily amount red from ($)',
190 helpFooterTerminal: 'Change settings: /plugin configure cost-ledger · Turn the mod off: /plugin disable cost-ledger',
191 // Desktop: Plugins nur an/aus über + → Plugins → Manage plugins (rel/desktop.md:478); Einstellungen gibt es dort nicht,
192 // Terminal-Dialogbefehle laufen im Desktop nicht (rel/desktop.md:1039-1041) → Einstellungen im Terminal
193 helpFooterDesktop: 'Turn the mod off: + → Plugins → Manage plugins · Change settings: /plugin configure cost-ledger in a terminal',
194 askQuestion: 'Delete all entries in the cost ledger?',
195 askCancel: 'Cancel (recommended)',
196 askDelete: 'Delete',
197 notDeletedNoAsk: 'Not deleted: the question cannot be asked here (e.g. in `-p`).',
198 notDeleted: 'Not deleted.',
199 cleared: (n: number) => `Cost ledger cleared (${n} ${n === 1 ? 'entry' : 'entries'}).`,
200 commandDescription: 'Cost ledger: what chats, mods and models have cost',
201 // Limits und Abo (0.5.0)
202 limitsHead: 'cost-ledger · limits',
203 fiveHours: '5 hours',
204 week: 'Week',
205 fiveShort: '5 h',
206 weekShort: 'week',
207 planShort: 'plan',
208 resetAt: (when: string) => `reset ${when}`,
209 inTime: (d: string) => `in ${d}`,
210 projection: (amt: string) => `100 % ≈ ${amt} (estimate)`,
211 projectionLater: 'projection from 5 %',
212 projectionPartial: 'projection from the next window',
213 projectionNone: 'no projection without a recorded amount',
214 partialFrom: (t: string) => `from ${t}`,
215 running: 'running',
216 resetPassed: 'reset passed, no new answer yet',
217 resetPassedShort: 'reset passed',
218 noWindowYet: 'no reading yet',
219 noLimitData: 'No limit data: no subscription detected, or no answer since the update yet.',
220 subMonth: 'Subscription month',
221 planNotSet: 'Plan not set: /ledger plan max20 14',
222 planValue: (amt: string, price: string, f: string) => `${amt} API value for a ${price} plan = ${f}×`,
223 planValueNoPrice: (amt: string) => `${amt} API value (no price set)`,
224 listPrice: 'list price',
225 renews: (d: string, n: number) => `renews ${d} (in ${n} ${n === 1 ? 'day' : 'days'})`,
226 lastWindows: 'Last 5-hour windows',
227 noWindows: 'No 5-hour window recorded yet.',
228 avg: (amt: string, n: number) => `Ø 100 % ≈ ${amt} from ${n} ${n === 1 ? 'window' : 'windows'} (≥ 20 %, estimate)`,
229 avgNone: 'Ø 100 %: no fully recorded, completed window with ≥ 20 % yet',
230 limitsFoot: '% applies to the whole account (incl. claude.ai) · $ only from chats with cost-ledger · projections are estimates · /ledger plan',
231 sumLimitsTitle: (t: string, tag: string) => `**Cost ledger · limits** · as of ${t} · ${tag}`,
232 sumLimitsLine: (list: string) => `Limits: ${list} · /ledger limits`,
233 sumLimitsFoot: '% applies to the whole account (incl. claude.ai); $ only counts chats with cost-ledger; projections are estimates.',
234 perMonth: (price: string) => `${price}/month`,
235 noPrice: 'no price',
236 planSaved: (label: string, day: number, price: string, start: string, next: string) =>
237 `Plan saved: ${label}, billing day ${day}, ${price}. Subscription month since ${start}, renews ${next} · details: /ledger limits`,
238 planCurrent: (label: string, day: number, price: string, at: string) => `Plan: ${label}, billing day ${day}, ${price} (set ${at}).`,
239 planNone: 'No plan set.',
240 planDeleted: 'Plan setting deleted.',
241 planInvalid: (s: string) => `Not saved: “${s}” is not valid.`,
242 planHelp: [
243 '**/ledger plan <plan> <day|today> [price]**: `pro`, `max5` (`5x`), `max20` (`20x`), `team` or `enterprise`; billing day 1–31 or `today`; monthly price in $, default list price (Pro $20, Max 5x $100, Max 20x $200).',
244 'Examples: `/ledger plan max20 14` · `/ledger plan max20 today 180` · `/ledger plan off` deletes the setting. Claude Code does not tell mods your plan, so it is set here.',
245 ].join('\n'),
246 // Geräte-Sync und Anteil außerhalb des Ledgers (0.7.0)
247 otherDevice: (name: string) => `${name} (other device)`,
248 devices: (n: number) => `${n} devices`,
249 deviceDefault: (id: string) => `Device ${id.slice(0, 4)}`,
250 syncFailed: (err: string) => `Sync failed: ${err} (the local ledger is unchanged).`,
251 syncUnreadable: (n: number) => `${n} ${n === 1 ? 'device' : 'devices'} not readable right now.`,
252 syncDupId: 'Another device wrote with this device ID (storage copied?): this device now writes under a new ID.',
253 syncTooBig: 'the device file would exceed 4 MiB; lower the retention (keepDays)',
254 outside: (o: string, p: string) => `outside the ledger ≈ ${o} of ${p} (estimate: claude.ai, phone, chats without cost-ledger)`,
255 outsideLater: 'outside the ledger: estimate from the first complete window ≥ 20 %',
256 outsideShort: (o: string) => `outside ${o}`,
257 syncOn: (dir: string, name: string, n: number, fresh: boolean) =>
258 `Sync on: ${dir} · this device: ${name}${fresh ? ' (new device ID)' : ''} · ${n} other ${n === 1 ? 'device' : 'devices'} found. /ledger shows all devices from now on.`,
259 syncOffState: 'Sync is off. Turn it on with /ledger sync <folder>: an absolute folder your devices share (e.g. in a cloud drive), the same on every device.',
260 syncState: (dir: string, name: string, id: string) => `Sync on: ${dir} · this device: ${name} (ID ${id})`,
261 syncPeer: (name: string, at: string, n: number) => `• ${name}: as of ${at}, ${n} ${n === 1 ? 'chat' : 'chats'}`,
262 syncNoPeers: 'No other device yet: run /ledger sync <folder> with the same folder on the other device.',
263 syncInvalid: (s: string) => `Not saved: “${s}” is not an absolute local folder (on Windows with a drive letter; no network path, no “..”, not a drive root).`,
264 syncUnreachable: (err: string) => `Not saved: the folder cannot be written (${err}).`,
265 syncOffDone: 'Sync off. This device’s file stays in the folder; nothing was deleted.',
266 syncNamed: (name: string) => `Device name: ${name}.`,
267 syncNameMissing: 'Usage: /ledger sync name <name> (up to 30 characters).',
268 syncPrivacy: 'The file holds amounts per day, limit windows, models and tokens, plus what merging needs (session IDs, times of the first and last booking) and the device name: no paths, project or mod names, repositories, chat titles or messages.',
269 askQuestionSync: 'Delete all entries in the cost ledger on this device? Other devices keep theirs.',
270 helpSyncShow: 'Sync state: folder, this device, other devices',
271 helpSyncSetCmd: '/ledger sync <folder>',
272 helpSyncSet: 'Merge devices through a shared folder (absolute, e.g. in a cloud drive); set it on every device',
273 helpSyncNameCmd: '/ledger sync name <name>',
274 helpSyncName: 'Name this device (shown on the other devices)',
275 helpSyncOff: 'Turn sync off (the file stays, nothing is deleted)',
276 helpSyncFeature: 'Sync between devices',
277 helpSyncThis: (name: string) => `this device: ${name}`,
278 helpSyncOffState: 'off',
279}
280
281export type Texts = typeof en
282
283const de: Texts = {
284 asOf: (t) => `Stand ${t}`,
285 since: (d) => `seit ${d}`,
286 reload: (cmd) => `neu laden: ${cmd}`,
287 empty: 'Noch keine Einträge. Gezählt wird ab jetzt, nach jeder Antwort.',
288 today: 'Heute',
289 days7: '7 Tage',
290 days30: '30 Tage',
291 allTime: 'Gesamt',
292 chats: (n) => `${n} ${n === 1 ? 'Chat' : 'Chats'}`,
293 last14Days: 'Letzte 14 Tage',
294 last14Weeks: 'Letzte 14 Wochen',
295 highest: '← höchster',
296 noData: 'ohne Angabe',
297 modsPart: (model) => `${model} · Mods`,
298 modsNoData: 'Mods ohne Angabe',
299 unknownModel: 'Unbekannt',
300 projectsIn: (range) => `Projekte · ${range}`,
301 chatsIn: (range) => `Teuerste Chats · ${range}`,
302 modelsIn: (range) => `Modelle · ${range}`,
303 modsIn: (range) => `Mods · ${range}`,
304 noCosts: 'keine Kosten im Zeitraum',
305 more: (n) => `+${n} weitere`,
306 noModCalls: 'keine Modellaufrufe anderer Mods im Zeitraum',
307 modsExtra: 'kommt zu den Chat-Kosten hinzu, steckt nicht in /cost',
308 tokenLine: (i, o, cr, cw) => `Input ${i} · Output ${o} · Cache ${cr} gelesen, ${cw} geschrieben`,
309 noTokens: 'Noch keine Antworten mit Token-Angaben im Zeitraum.',
310 modelsNote: 'Betrag geschätzt aus Tokens × Preistabelle; enthält die Modellaufrufe anderer Mods.',
311 foot: 'API-Wert, im Abo zählt es aufs Kontingent · /ledger weeks · chats · projects · models · help',
312 noCost: 'Dieser Host liefert keine Chat-Kosten; gebucht werden nur Mod-Aufrufe.',
313 unreadable: (n) => `${n} ${n === 1 ? 'Eintrag' : 'Einträge'} unlesbar.`,
314 storeFull: (pct) => `Speicher zu ${pct} % voll (4 MiB): Aufbewahrung (keepDays) senken.`,
315 writeFailed: (err) => `Speichern scheiterte zuletzt: ${err}`,
316 scriptRuns: 'Skript-Läufe',
317 noFolder: '(ohne Ordner)',
318 chatFrom: (t) => `Chat vom ${t}`,
319 sumTitle: (t, tag) => `**Kostenbuch** · Stand ${t} · ${tag}`,
320 sumChats: (today, n, d7, d30, all) => `Chats: heute ${today} (${n}) · 7 Tage ${d7} · 30 Tage ${d30} · gesamt ${all}`,
321 sumMods: (today, d30, all) => `Mods: heute ${today} · 30 Tage ${d30} · gesamt ${all}`,
322 sumProjects: (list) => `Projekte (30 Tage): ${list}`,
323 sumTopChats: (list) => `Teuerste Chats (30 Tage): ${list}`,
324 sumModsList: (list) => `Mods (30 Tage): ${list}`,
325 sumWeeks: (list) => `Wochen (Chat + Mods): ${list}`,
326 sumChatsHead: (range, shown, total) => `Teuerste Chats (${range}), ${shown} von ${total}:`,
327 sumModelsHead: (range) => `Modelle (${range}), geschätzter API-Wert nach Tokens, inkl. Mod-Aufrufe:`,
328 sumModelLine: (name, amt, pct, n, line) => `${name}: ${amt} (${pct} %) · ${n}× · ${line}`,
329 sumMoreModels: (n) => `+${n} weitere Modelle`,
330 sumProjectsHead: (range) => `Projekte (${range}):`,
331 sumProjectRow: (name, amt, n) => `${name} ${amt} (${n} ${n === 1 ? 'Chat' : 'Chats'})`,
332 sumFoot: 'Mod-Aufrufe kommen zu den Chat-Kosten hinzu (sie stecken nicht in /cost). API-Wert; im Abo zählt es aufs Kontingent.',
333 unknownArg: (s) => `Unbekannt: „${s}“. Alle Befehle: /ledger help`,
334 helpIntro: 'Bucht nach jeder Antwort, was Chats und andere Mods kosten (API-Wert), und zeigt es nach Tag, Projekt, Chat, Modell und Limit-Fenster.',
335 helpOverview: 'Übersicht: heute, 7 und 30 Tage, gesamt, letzte 14 Tage, Projekte, teuerste Chats, Mods',
336 helpWeeks: 'Die Übersicht mit den letzten 14 Kalenderwochen',
337 helpLists: 'Teuerste Chats · alle Projekte · Modelle mit Tokens; Standard 30 Tage, beliebige Tage von 1 bis 3650',
338 helpLimits: '5-Stunden- und Wochenfenster, Abo-Monat, letzte 5-Stunden-Fenster',
339 helpPlanShow: 'Abo-Einstellung und Syntax anzeigen',
340 helpPlanSet: 'Abo einstellen (pro, max5 oder 5x/max5x, max20 oder 20x/max20x, team, enterprise), Abrechnungstag 1–31 und Monatspreis in $',
341 helpPlanOff: 'Abo-Einstellung löschen',
342 helpReset: 'Alle Einträge löschen (mit Rückfrage; das Abo bleibt)',
343 helpHelp: 'Diese Hilfe (auch: ?)',
344 helpAliases: 'Deutsche Wörter gehen auch: hilfe, alle, heute, aus.',
345 helpPlanName: 'Abo',
346 helpDay: (d) => `Tag ${d}`,
347 helpNoPlan: 'kein Abo',
348 helpStorageName: 'Speicher belegt',
349 helpStorage: (pct) => `${pct} % von 4 MiB`,
350 helpSinceName: 'Erfasst seit',
351 helpInfo: 'nur Info',
352 setLanguage: 'Sprache',
353 setKeepDays: 'Aufbewahrung (Tage)',
354 setDayYellow: 'Tagesbetrag gelb ab ($)',
355 setDayRed: 'Tagesbetrag rot ab ($)',
356 helpFooterTerminal: 'Einstellungen ändern: /plugin configure cost-ledger · Mod abschalten: /plugin disable cost-ledger',
357 helpFooterDesktop: 'Mod abschalten: + → Plugins → Manage plugins · Einstellungen ändern: im Terminal /plugin configure cost-ledger',
358 askQuestion: 'Alle Einträge im Kostenbuch löschen?',
359 askCancel: 'Abbrechen (empfohlen)',
360 askDelete: 'Löschen',
361 notDeletedNoAsk: 'Nicht gelöscht: Die Rückfrage ist hier nicht möglich (z. B. in `-p`).',
362 notDeleted: 'Nicht gelöscht.',
363 cleared: (n) => `Kostenbuch geleert (${n} ${n === 1 ? 'Eintrag' : 'Einträge'}).`,
364 commandDescription: 'Kostenbuch: was Chats, Mods und Modelle gekostet haben',
365 limitsHead: 'cost-ledger · Limits',
366 fiveHours: '5 Stunden',
367 week: 'Woche',
368 fiveShort: '5 Std.',
369 weekShort: 'Woche',
370 planShort: 'Abo',
371 resetAt: (when) => `Reset ${when}`,
372 inTime: (d) => `in ${d}`,
373 projection: (amt) => `100 % ≈ ${amt} (Schätzung)`,
374 projectionLater: 'Hochrechnung ab 5 %',
375 projectionPartial: 'Hochrechnung ab dem nächsten Fenster',
376 projectionNone: 'keine Hochrechnung ohne gebuchten Betrag',
377 partialFrom: (t) => `ab ${t}`,
378 running: 'läuft',
379 resetPassed: 'Reset vorbei, noch keine neue Antwort',
380 resetPassedShort: 'Reset vorbei',
381 noWindowYet: 'noch kein Messwert',
382 noLimitData: 'Keine Limit-Daten: kein Abo erkannt oder seit dem Update noch keine Antwort.',
383 subMonth: 'Abo-Monat',
384 planNotSet: 'Abo nicht eingestellt: /ledger plan max20 14',
385 planValue: (amt, price, f) => `${amt} API-Wert für ${price} Abo = ${f}×`,
386 planValueNoPrice: (amt) => `${amt} API-Wert (kein Preis eingestellt)`,
387 listPrice: 'Listenpreis',
388 renews: (d, n) => `erneuert ${d} (in ${n} ${n === 1 ? 'Tag' : 'Tagen'})`,
389 lastWindows: 'Letzte 5-Stunden-Fenster',
390 noWindows: 'Noch kein 5-Stunden-Fenster erfasst.',
391 avg: (amt, n) => `Ø 100 % ≈ ${amt} aus ${n} ${n === 1 ? 'Fenster' : 'Fenstern'} (≥ 20 %, Schätzung)`,
392 avgNone: 'Ø 100 %: noch kein vollständig erfasstes, abgeschlossenes Fenster mit ≥ 20 %',
393 limitsFoot: '% gilt fürs ganze Konto (auch claude.ai) · $ nur aus Chats mit cost-ledger · Hochrechnungen sind Schätzungen · /ledger plan',
394 sumLimitsTitle: (t, tag) => `**Kostenbuch · Limits** · Stand ${t} · ${tag}`,
395 sumLimitsLine: (list) => `Limits: ${list} · /ledger limits`,
396 sumLimitsFoot: '% gilt fürs ganze Konto (auch claude.ai); $ zählt nur Chats mit cost-ledger; Hochrechnungen sind Schätzungen.',
397 perMonth: (price) => `${price} im Monat`,
398 noPrice: 'ohne Preis',
399 planSaved: (label, day, price, start, next) =>
400 `Abo gespeichert: ${label}, Abrechnungstag ${day}, ${price}. Abo-Monat seit ${start}, erneuert ${next} · Details: /ledger limits`,
401 planCurrent: (label, day, price, at) => `Abo: ${label}, Abrechnungstag ${day}, ${price} (eingestellt ${at}).`,
402 planNone: 'Kein Abo eingestellt.',
403 planDeleted: 'Abo-Einstellung gelöscht.',
404 planInvalid: (s) => `Nicht gespeichert: „${s}“ ist ungültig.`,
405 planHelp: [
406 '**/ledger plan <plan> <tag|heute> [preis]**: `pro`, `max5` (`5x`), `max20` (`20x`), `team` oder `enterprise`; Abrechnungstag 1–31 oder `heute`; Monatspreis in $, Standard ist der Listenpreis (Pro 20 $, Max 5x 100 $, Max 20x 200 $).',
407 'Beispiele: `/ledger plan max20 14` · `/ledger plan max20 heute 180` · `/ledger plan off` löscht die Einstellung. Claude Code verrät Mods den Plan nicht, deshalb wird er hier eingestellt.',
408 ].join('\n'),
409 otherDevice: (name) => `${name} (anderes Gerät)`,
410 devices: (n) => `${n} Geräte`,
411 deviceDefault: (id) => `Gerät ${id.slice(0, 4)}`,
412 syncFailed: (err) => `Sync gescheitert: ${err} (das lokale Kostenbuch ist unverändert).`,
413 syncUnreadable: (n) => `${n} ${n === 1 ? 'Gerät' : 'Geräte'} gerade nicht lesbar.`,
414 syncDupId: 'Ein anderes Gerät schrieb mit dieser Geräte-ID (Speicher kopiert?): Dieses Gerät schreibt ab jetzt unter einer neuen ID.',
415 syncTooBig: 'die Gerätedatei wäre größer als 4 MiB; Aufbewahrung (keepDays) senken',
416 outside: (o, p) => `außerhalb des Ledgers ≈ ${o} von ${p} (Schätzung: claude.ai, Handy, Chats ohne cost-ledger)`,
417 outsideLater: 'außerhalb des Ledgers: Schätzung ab dem ersten vollständigen Fenster ≥ 20 %',
418 outsideShort: (o) => `außen ${o}`,
419 syncOn: (dir, name, n, fresh) =>
420 `Sync an: ${dir} · dieses Gerät: ${name}${fresh ? ' (neue Geräte-ID)' : ''} · ${n} ${n === 1 ? 'anderes Gerät' : 'andere Geräte'} gefunden. /ledger zeigt ab jetzt alle Geräte.`,
421 syncOffState: 'Sync ist aus. Einschalten mit /ledger sync <ordner>: ein absoluter Ordner, den deine Geräte teilen (z. B. in einem Cloud-Laufwerk), auf jedem Gerät derselbe.',
422 syncState: (dir, name, id) => `Sync an: ${dir} · dieses Gerät: ${name} (ID ${id})`,
423 syncPeer: (name, at, n) => `• ${name}: Stand ${at}, ${n} ${n === 1 ? 'Chat' : 'Chats'}`,
424 syncNoPeers: 'Noch kein anderes Gerät: auf dem anderen Gerät /ledger sync <ordner> mit demselben Ordner ausführen.',
425 syncInvalid: (s) => `Nicht gespeichert: „${s}“ ist kein absoluter lokaler Ordner (unter Windows mit Laufwerk; kein Netzwerkpfad, kein „..“, nicht die Wurzel).`,
426 syncUnreachable: (err) => `Nicht gespeichert: In den Ordner lässt sich nicht schreiben (${err}).`,
427 syncOffDone: 'Sync aus. Die Datei dieses Geräts bleibt im Ordner; gelöscht wurde nichts.',
428 syncNamed: (name) => `Gerätename: ${name}.`,
429 syncNameMissing: 'Aufruf: /ledger sync name <name> (bis 30 Zeichen).',
430 syncPrivacy: 'Die Datei enthält Beträge je Tag, Limit-Fenster, Modelle und Tokens, dazu was das Zusammenführen braucht (Session-IDs, Zeit der ersten und letzten Buchung) und den Gerätenamen: keine Pfade, Projekt- oder Mod-Namen, Repositories, Chat-Titel oder Nachrichten.',
431 askQuestionSync: 'Alle Einträge im Kostenbuch auf diesem Gerät löschen? Andere Geräte behalten ihre.',
432 helpSyncShow: 'Sync-Stand: Ordner, dieses Gerät, andere Geräte',
433 helpSyncSetCmd: '/ledger sync <ordner>',
434 helpSyncSet: 'Geräte über einen geteilten Ordner zusammenführen (absolut, z. B. in einem Cloud-Laufwerk); auf jedem Gerät setzen',
435 helpSyncNameCmd: '/ledger sync name <name>',
436 helpSyncName: 'Dieses Gerät benennen (so erscheint es auf den anderen)',
437 helpSyncOff: 'Sync ausschalten (die Datei bleibt, gelöscht wird nichts)',
438 helpSyncFeature: 'Sync zwischen Geräten',
439 helpSyncThis: (name) => `dieses Gerät: ${name}`,
440 helpSyncOffState: 'aus',
441}
442
443export const T: Record<Lang, Texts> = { en, de }
444hooks/logic.ts 1222 lines1// cost-ledger: reine Logik ohne $ (Buchen, Aggregieren, Preise, Kurzfassung). Alles hier ist ohne Engine testbar.
2import { T, clock, dateTime, duration, factor, fullDate, langOf, pct, rangeLabel, resetTime, shortDate, span, tokens, usd, weekLabel } from './i18n.ts'
3import type { Lang } from './i18n.ts'
4import type { HelpData } from './help.ts'
5
6export const DAY = 24 * 60 * 60 * 1000
7
8export type Kind = 'desktop' | 'terminal' | 'script'
9/** Je Mod und Tag; ältere Einträge haben nur usd/calls, keine Tokens. */
10export type ModDay = { usd: number; calls: number; in?: number; out?: number; cr?: number; cw?: number }
11/**
12 * Aktivität je Tag (vorsorglich gesammelt): Antworten der Hauptschleife, Subagent-Turns, Arbeitszeit in ms, Abbrüche,
13 * Fehler/Ablehnungen, teuerste Antwort in $, höchste Kontext-Füllung in %.
14 */
15export type ActDay = { turns: number; sub: number; ms: number; abort: number; err: number; maxTurn: number; ctx: number }
16/** Tokens und geschätzter API-Wert je Modell und Tag; `n` = Antworten bzw. Mod-Aufrufe. */
17export type ModelDay = { in: number; out: number; cr: number; cw: number; usd: number; n: number }
18/** Ein Datensatz pro Session unter `s:<sessionId>`; nur diese Session schreibt ihn (SPEC Zustand). */
19export type Rec = {
20 v: 1
21 project: string
22 root: string
23 title: string
24 kind: Kind
25 firstAt: number
26 lastAt: number
27 /** Letzter gelesener Stand von `usage().cost.usd`; Baseline nach Resume (Resume zählt weiter). */
28 c: number
29 days: Record<string, number>
30 mods: Record<string, { days: Record<string, ModDay> }>
31 /** Je Modell (normalisierte ID, z. B. `opus-5-5`) die Antworten des Chats, auch Subagents. */
32 models: Record<string, { days: Record<string, ModelDay> }>
33 /** Je Modell die Modellaufrufe anderer Mods. */
34 modModels: Record<string, { days: Record<string, ModelDay> }>
35 /** Vorsorglich gesammelt: Aktivität je Tag, Chat-Kosten je Tag und Stunde (`HH`), Limit-Stände je Tag. */
36 act: Record<string, ActDay>
37 hours: Record<string, Record<string, number>>
38 /** Höchster gesehener `percentUsed` je Limit-Fenster (`kind`, z. B. `five_hour`) und Tag. */
39 rl: Record<string, Record<string, number>>
40 /**
41 * Je Limit-Fenster (`five_hour`, `seven_day`) und Reset-Zeitpunkt (ms, auf die Minute gerundet, als String) der API-Wert,
42 * der in dieses Fenster fiel (SPEC Nachtrag 0.5.0).
43 */
44 lim: Record<string, Record<string, LimWin>>
45 /** Git-Remote des Projekts als `host/owner/repo`, ohne Zugangsdaten. */
46 remote: string
47}
48/** Ein Limit-Fenster im Datensatz: API-Wert aus Chat und Mods, höchster `percentUsed`, erste und letzte Buchung. */
49export type LimWin = { chat: number; mod: number; pct: number; first: number; last: number }
50
51export type Settings = { keepDays: number; dayYellow: number; dayRed: number; lang: Lang }
52const DEFAULTS: Settings = { keepDays: 365, dayYellow: 3, dayRed: 8, lang: 'en' }
53
54// Wörter, die `/ledger` annimmt. Parser, Hilfe und ein Test nutzen dieselben Listen: Was der Parser neu lernt, muss in
55// der Hilfe stehen, sonst scheitert der Test (docs/HELP-SPEC.md §6 Punkt 5). Deutsche Wörter sind Aliase (release/I18N.md §3).
56export const HELP_WORDS: readonly string[] = ['help', 'hilfe', '?']
57export const VIEW_WORDS: readonly string[] = ['weeks', 'chats', 'projects', 'models', 'limits']
58export const RANGE_WORDS: readonly string[] = ['all', 'alle']
59export const TODAY_WORDS: readonly string[] = ['today', 'heute']
60export const OFF_WORDS: readonly string[] = ['off', 'aus']
61/** `/ledger sync …` und `/ledger sync name …` (SPEC Nachtrag 0.7.0, Bedienung) */
62export const SYNC_WORD = 'sync'
63export const NAME_WORD = 'name'
64
65function num(v: unknown, def: number, min: number): number {
66 const n = typeof v === 'number' ? v : typeof v === 'string' && v.trim() ? Number(v) : NaN
67 return Number.isFinite(n) && n >= min ? n : def
68}
69
70/** userConfig aus `register(on, options)`; unbrauchbare Werte fallen auf den Standard zurück. */
71export function cleanSettings(o: Readonly<Record<string, unknown>> | undefined): Settings {
72 const s = {
73 keepDays: Math.round(num(o?.keepDays, DEFAULTS.keepDays, 1)),
74 dayYellow: num(o?.dayYellow, DEFAULTS.dayYellow, 0),
75 dayRed: num(o?.dayRed, DEFAULTS.dayRed, 0),
76 lang: langOf(o?.language),
77 }
78 if (s.dayRed < s.dayYellow) s.dayRed = s.dayYellow
79 return s
80}
81
82const pad = (n: number) => String(n).padStart(2, '0')
83
84/** Lokales Datum `YYYY-MM-DD` zu einem Zeitpunkt aus `$.clock.now()`. */
85export function dayKey(ms: number): string {
86 const d = new Date(ms)
87 return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
88}
89
90/** Tag `n` Tage vor `ms` (lokal, über Mittag gerechnet, damit Zeitumstellungen nicht verrutschen). */
91export function dayBefore(ms: number, n: number): string {
92 const d = new Date(ms)
93 return dayKey(new Date(d.getFullYear(), d.getMonth(), d.getDate() - n, 12).getTime())
94}
95
96// Dollar je Million Tokens. haiku-5-5 und sonnet-5-5: Stand 2026-10-07 (platform.claude.com/docs/en/about-claude/pricing,
97// SPEC Nachtrag 0.4.3); übrige Zeilen aus mods/sidekick/hooks/cache.ts, Stand 2026-09-25.
98// Längere IDs zuerst: 'opus-5' darf 'opus-5-5' nicht schlucken. `long`: ab `above` Prompt-Tokens gilt das `factor`-Fache für
99// den ganzen Aufruf (Haiku 5.5: zweite Preiszeile „for prompts over 100,000 tokens“, alle Spalten ×5).
100type Price = { input: number; output: number; read: number; long?: { above: number; factor: number } }
101const TABLE: readonly [string, Price][] = [
102 ['fable-5-1', { input: 10, output: 50, read: 0.25 }],
103 ['mythos-5-1', { input: 10, output: 50, read: 0.25 }],
104 ['fable-5', { input: 10, output: 50, read: 1 }],
105 ['opus-5-5', { input: 4, output: 20, read: 0.2 }],
106 ['opus-5', { input: 5, output: 25, read: 0.5 }],
107 ['opus-4-8', { input: 5, output: 25, read: 0.5 }],
108 ['opus-4-7', { input: 5, output: 25, read: 0.5 }],
109 ['opus-4-6', { input: 5, output: 25, read: 0.5 }],
110 ['sonnet-5-5', { input: 2, output: 10, read: 0.1 }],
111 ['sonnet-5', { input: 2, output: 10, read: 0.2 }],
112 ['sonnet-4-6', { input: 3, output: 15, read: 0.3 }],
113 ['haiku-5-5', { input: 0.1, output: 0.5, read: 0.01, long: { above: 100_000, factor: 5 } }],
114 ['haiku-4-5', { input: 1, output: 5, read: 0.1 }],
115]
116// Alias → Eintrag. `haiku` ist seit Claude Code 2.1.293 Haiku 5.5 (Probe 2.1.295: `claude -p --model haiku` →
117// `claude-haiku-5-5`, SPEC Nachtrag 0.6.0); bis 2.1.291 war es Haiku 4.5. Das Ergebnis eines Mod-Aufrufs nennt das
118// aufgelöste Modell nicht (types ModelUsage), deshalb gilt die Zuordnung der getesteten Version.
119const FAMILY: readonly [string, string][] = [
120 ['fable', 'fable-5-1'],
121 ['mythos', 'mythos-5-1'],
122 ['opus', 'opus-5-5'],
123 ['sonnet', 'sonnet-5-5'],
124 ['haiku', 'haiku-5-5'],
125]
126
127/** `claude-opus-5-5-20260101` → `opus-5-5` (ohne Präfix, Kontext-Zusatz und Datum). */
128function bareId(model: string): string {
129 return String(model || '')
130 .toLowerCase()
131 .replace(/^claude-/, '')
132 .replace(/\[.*?\]/g, '')
133 .replace(/-\d{8}$/, '')
134 .trim()
135}
136
137/** Preis je Million Tokens für eine Modell-ID oder einen Alias (`haiku`, `claude-opus-5-5`, `opus[1m]` …). */
138export function priceFor(model: string): { id: string } & Price {
139 const id = bareId(model)
140 for (const [key, p] of TABLE) if (id === key || id.startsWith(key)) return { id: key, ...p }
141 for (const [fam, key] of FAMILY) {
142 const hit = TABLE.find(([k]) => k === key)
143 if (id.includes(fam) && hit) return { id: key, ...hit[1] }
144 }
145 return { id: 'opus-5-5', input: 4, output: 20, read: 0.2 }
146}
147
148export type Usage = {
149 input_tokens?: number
150 output_tokens?: number
151 cache_read_input_tokens?: number
152 cache_creation_input_tokens?: number
153}
154
155/**
156 * API-Wert in $; Cache-Schreiben wie 5-min-TTL (1,25 × Input), wie sidekick completeCost.
157 * Preisstufe (`long`) nur bei `single`, also wenn `u` genau eine Anfrage ist (`model.complete`, types:2525-2528). Turn- und
158 * Fork-Usage sind Summen über mehrere Antworten (types:13262, :6079); dort wäre die Summe kein Prompt, also Faktor 1.
159 * Prompt = `input_tokens + cache_read_input_tokens + cache_creation_input_tokens`. Dass Cache-Tokens mitzählen, ist ein Schluss
160 * aus zwei Seiten, wörtlich steht es nirgends: die Preisseite (…/about-claude/pricing) nennt nur „prompt“, die Seite
161 * …/build-with-claude/context-windows sagt „all three count toward the window“.
162 */
163export function callCost(u: Usage | undefined, model: string, single = false): number {
164 if (!u) return 0
165 const p = priceFor(model)
166 const prompt = (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0)
167 const factor = single && p.long && prompt > p.long.above ? p.long.factor : 1
168 return (
169 (factor *
170 ((u.input_tokens || 0) * p.input +
171 (u.cache_read_input_tokens || 0) * p.read +
172 (u.cache_creation_input_tokens || 0) * p.input * 1.25 +
173 (u.output_tokens || 0) * p.output)) /
174 1e6
175 )
176}
177
178export function tokensOf(u: Usage | undefined): number {
179 return u ? (u.input_tokens || 0) + (u.output_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0) : 0
180}
181
182/** Schlüssel für Beträge ohne Modell-Daten (alte Tage). */
183export const UNKNOWN_MODEL = 'unbekannt'
184
185/**
186 * Modell-Schlüssel: `claude-opus-5-5-20260101` → `opus-5-5`. Ein Alias ohne Version (`haiku`, `opus[1m]`, wie ihn Mods
187 * übergeben) wird über die Preistabelle zur aktuellen Version (`haiku-5-5`, `FAMILY`), damit Turns und Mod-Aufrufe in einer Zeile
188 * landen; leer → `UNKNOWN_MODEL`.
189 */
190export function modelKey(model: string): string {
191 const id = bareId(model)
192 if (!id) return UNKNOWN_MODEL
193 return /^[a-z]+$/.test(id) && FAMILY.some(([fam]) => fam === id) ? priceFor(id).id : id
194}
195
196/** `opus-5-5` → `Opus 5.5`, `haiku` → `Haiku`; `UNKNOWN_MODEL` in der eingestellten Sprache. */
197export function modelName(key: string, lang: Lang): string {
198 if (key === UNKNOWN_MODEL) return T[lang].unknownModel
199 const [fam = '', ...ver] = key.split('-')
200 const name = fam ? fam[0]!.toUpperCase() + fam.slice(1) : key
201 return ver.length && ver.every((x) => /^\d+$/.test(x)) ? `${name} ${ver.join('.')}` : [name, ...ver].join(' ')
202}
203
204/** `sidekick@inline` → `sidekick` */
205export function pluginName(p: string): string {
206 return String(p || '').replace(/@.*$/, '')
207}
208
209/**
210 * Git-Remote ohne Zugangsdaten: nur `host/owner/repo`. `https://user:token@github.com/a/b.git` und `git@github.com:a/b.git`
211 * werden zu `github.com/a/b`; Query und Fragment fallen weg. Tokens werden nie gespeichert (CLAUDE.md Grundregel 3).
212 */
213export function cleanRemote(url: string | null | undefined): string {
214 let s = String(url ?? '').trim()
215 if (!s) return ''
216 s = s.replace(/[?#].*$/, '')
217 const scp = /^[^@\s/]+@([^:/\s]+):(.+)$/.exec(s)
218 if (scp) s = `${scp[1]}/${scp[2]}`
219 else s = s.replace(/^[a-z][a-z0-9+.-]*:\/\//i, '').replace(/^[^@/]*@/, '')
220 return s.replace(/\.git$/, '').replace(/\/+$/, '').slice(0, 200)
221}
222
223/** Gespeicherter Projektname, wenn es weder Repo noch Ordner gibt (bleibt aus Kompatibilität deutsch, Anzeige übersetzt). */
224export const NO_FOLDER = '(ohne Ordner)'
225
226/** Projektname: Repo-Name, sonst letzter Ordner; Worktrees unter `.claude/worktrees/` zählen zum Hauptordner. */
227export function projectOf(repoName: string | null | undefined, root: string): string {
228 const parts = String(root || '').split(/[\\/]+/).filter(Boolean)
229 const wt = parts.findIndex((p, i) => p === '.claude' && parts[i + 1] === 'worktrees')
230 const folder = wt > 0 ? parts[wt - 1] : parts[parts.length - 1]
231 return (repoName && repoName.trim()) || folder || NO_FOLDER
232}
233
234/**
235 * Name eines Chats aus der ersten eigenen Nachricht (der Desktop meldet den Seitenleisten-Titel nicht). Keine Befehle
236 * (`/…`), keine eingespielten Blöcke (`<…>`), Leerraum zusammengezogen, höchstens 50 Zeichen.
237 */
238export function titleFromPrompt(prompt: string | undefined): string {
239 const t = String(prompt ?? '').replace(/\s+/g, ' ').trim()
240 if (!t || /^[/<!]/.test(t)) return ''
241 return t.length <= 50 ? t : `${t.slice(0, 49).trimEnd()}…`
242}
243
244export function newRec(meta: { project: string; root: string; title: string; kind: Kind; remote?: string }, now: number, c: number): Rec {
245 return {
246 v: 1,
247 project: meta.project,
248 root: meta.root,
249 title: meta.title,
250 kind: meta.kind,
251 firstAt: now,
252 lastAt: now,
253 c,
254 days: {},
255 mods: {},
256 models: {},
257 modModels: {},
258 act: {},
259 hours: {},
260 rl: {},
261 lim: {},
262 remote: meta.remote ?? '',
263 }
264}
265
266const isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v)
267const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v)
268
269function numMap(src: unknown): Record<string, number> {
270 const out: Record<string, number> = {}
271 if (isObj(src)) for (const [k, x] of Object.entries(src)) if (isNum(x)) out[k] = x
272 return out
273}
274
275function mapOfMaps(src: unknown): Record<string, Record<string, number>> {
276 const out: Record<string, Record<string, number>> = {}
277 if (isObj(src)) for (const [k, x] of Object.entries(src)) if (isObj(x)) out[k] = numMap(x)
278 return out
279}
280
281function cleanModels(src: unknown): Rec['models'] {
282 const out: Rec['models'] = {}
283 if (isObj(src))
284 for (const [name, m] of Object.entries(src)) {
285 if (!isObj(m) || !isObj(m.days)) continue
286 const md: Record<string, ModelDay> = {}
287 for (const [k, x] of Object.entries(m.days))
288 if (isObj(x) && [x.in, x.out, x.cr, x.cw, x.usd, x.n].every(isNum))
289 md[k] = { in: x.in as number, out: x.out as number, cr: x.cr as number, cw: x.cw as number, usd: x.usd as number, n: x.n as number }
290 out[name] = { days: md }
291 }
292 return out
293}
294
295function cleanLim(src: unknown): Rec['lim'] {
296 const out: Rec['lim'] = {}
297 if (isObj(src))
298 for (const [kind, m] of Object.entries(src)) {
299 if (!LIMIT_KINDS.includes(kind) || !isObj(m)) continue
300 const wins: Record<string, LimWin> = {}
301 for (const [k, x] of Object.entries(m))
302 if (/^\d+$/.test(k) && isObj(x) && [x.chat, x.mod, x.pct, x.first, x.last].every(isNum))
303 wins[k] = { chat: Math.max(0, x.chat as number), mod: Math.max(0, x.mod as number), pct: x.pct as number, first: x.first as number, last: x.last as number }
304 out[kind] = wins
305 }
306 return out
307}
308
309/** Gelesenen Datensatz prüfen; `null` bei unbekannter Version oder kaputter Form. Fehlende Felder älterer Fassungen sind leer. */
310export function cleanRec(v: unknown): Rec | null {
311 if (!isObj(v) || v.v !== 1 || !isObj(v.days) || !isNum(v.firstAt) || !isNum(v.lastAt)) return null
312 const days: Record<string, number> = {}
313 for (const [k, x] of Object.entries(v.days)) if (/^\d{4}-\d\d-\d\d$/.test(k) && isNum(x) && x >= 0) days[k] = x
314 const mods: Rec['mods'] = {}
315 if (isObj(v.mods))
316 for (const [name, m] of Object.entries(v.mods)) {
317 if (!isObj(m) || !isObj(m.days)) continue
318 const md: Record<string, ModDay> = {}
319 for (const [k, x] of Object.entries(m.days))
320 if (isObj(x) && isNum(x.usd) && isNum(x.calls)) {
321 const t = numMap(x)
322 md[k] = { usd: Math.max(0, x.usd), calls: Math.max(0, x.calls), ...(isNum(t.in) ? { in: t.in, out: t.out ?? 0, cr: t.cr ?? 0, cw: t.cw ?? 0 } : {}) }
323 }
324 mods[name] = { days: md }
325 }
326 const act: Record<string, ActDay> = {}
327 if (isObj(v.act))
328 for (const [k, x] of Object.entries(v.act)) {
329 const n = numMap(x)
330 act[k] = { turns: n.turns ?? 0, sub: n.sub ?? 0, ms: n.ms ?? 0, abort: n.abort ?? 0, err: n.err ?? 0, maxTurn: n.maxTurn ?? 0, ctx: n.ctx ?? 0 }
331 }
332 return {
333 v: 1,
334 project: typeof v.project === 'string' && v.project ? v.project : NO_FOLDER,
335 root: typeof v.root === 'string' ? v.root : '',
336 title: typeof v.title === 'string' ? v.title : '',
337 kind: v.kind === 'desktop' || v.kind === 'script' ? v.kind : 'terminal',
338 firstAt: v.firstAt,
339 lastAt: v.lastAt,
340 c: isNum(v.c) ? v.c : 0,
341 days,
342 mods,
343 models: cleanModels(v.models),
344 modModels: cleanModels(v.modModels),
345 act,
346 hours: mapOfMaps(v.hours),
347 rl: mapOfMaps(v.rl),
348 lim: cleanLim(v.lim),
349 remote: typeof v.remote === 'string' ? cleanRemote(v.remote) : '',
350 }
351}
352
353// ---------- Buchen ----------
354
355/** Neue Baseline nach Start oder Resume: der gespeicherte Stand, wenn er zum Zähler passt, sonst der Zähler selbst. */
356export function baselineFor(rec: Rec | null, cost: number): number {
357 return rec && rec.c > 0 && rec.c <= cost ? rec.c : cost
358}
359
360/** Differenz zum letzten Stand; fällt der Zähler, beginnt er neu bei 0. */
361export function deltaOf(seen: number, cost: number): { delta: number; seen: number } {
362 const base = cost < seen ? 0 : seen
363 return { delta: Math.max(0, cost - base), seen: cost }
364}
365
366/** Auf 1e-8 $ runden: hält die Datensätze kurz (Gleitkomma-Reste wie 0.13945199999999998), ohne sichtbaren Fehler. */
367const r8 = (v: number) => Math.round(v * 1e8) / 1e8
368
369export function bookChat(rec: Rec, day: string, delta: number, now: number, cost: number): void {
370 if (delta > 0) {
371 rec.days[day] = r8((rec.days[day] ?? 0) + delta)
372 const h = (rec.hours[day] ??= {})
373 const hour = pad(new Date(now).getHours())
374 h[hour] = r8((h[hour] ?? 0) + delta)
375 }
376 rec.c = cost
377 rec.lastAt = now
378}
379
380export function bookMod(rec: Rec, name: string, day: string, amount: number, now: number, u?: Usage): void {
381 const m = (rec.mods[name] ??= { days: {} })
382 const d = (m.days[day] ??= { usd: 0, calls: 0 })
383 d.usd = r8(d.usd + Math.max(0, amount))
384 d.calls += 1
385 if (u) {
386 d.in = (d.in ?? 0) + (u.input_tokens || 0)
387 d.out = (d.out ?? 0) + (u.output_tokens || 0)
388 d.cr = (d.cr ?? 0) + (u.cache_read_input_tokens || 0)
389 d.cw = (d.cw ?? 0) + (u.cache_creation_input_tokens || 0)
390 }
391 rec.lastAt = now
392}
393
394/** Eine Antwort (`models`) oder einen Mod-Aufruf (`modModels`) je Modell buchen; Betrag geschätzt nach Preistabelle. */
395export function bookModel(rec: Rec, model: string, day: string, u: Usage | undefined, now: number, into: 'models' | 'modModels' = 'models', single = false): void {
396 if (!u) return
397 const m = (rec[into][modelKey(model)] ??= { days: {} })
398 const d = (m.days[day] ??= { in: 0, out: 0, cr: 0, cw: 0, usd: 0, n: 0 })
399 d.in += u.input_tokens || 0
400 d.out += u.output_tokens || 0
401 d.cr += u.cache_read_input_tokens || 0
402 d.cw += u.cache_creation_input_tokens || 0
403 d.usd = r8(d.usd + callCost(u, model, single))
404 d.n += 1
405 rec.lastAt = now
406}
407
408export type TurnInfo = { agentId?: string; durationMs?: number; reason?: string; isAborted?: boolean }
409
410/** Aktivität eines Turns: Antwort oder Subagent, Dauer, Abbruch/Fehler, teuerste Antwort, Kontext-Spitze. */
411export function bookTurn(rec: Rec, day: string, t: TurnInfo, delta: number, ctxPct: number | undefined): void {
412 const a = (rec.act[day] ??= { turns: 0, sub: 0, ms: 0, abort: 0, err: 0, maxTurn: 0, ctx: 0 })
413 if (t.agentId) a.sub += 1
414 else {
415 a.turns += 1
416 a.ms += Math.max(0, Math.round(t.durationMs || 0))
417 if (delta > a.maxTurn) a.maxTurn = r8(delta)
418 }
419 if (t.isAborted || t.reason === 'aborted') a.abort += 1
420 if (t.reason === 'error' || t.reason === 'refusal') a.err += 1
421 if (isNum(ctxPct) && ctxPct > a.ctx) a.ctx = Math.round(ctxPct)
422}
423
424/** Höchster Limit-Stand des Tages je Fenster (5 Stunden, Woche …), für spätere Auswertungen. */
425export function bookRate(rec: Rec, day: string, limits: readonly { kind: string; percentUsed: number }[] | undefined): void {
426 for (const l of limits ?? []) {
427 if (!l || typeof l.kind !== 'string' || !isNum(l.percentUsed)) continue
428 const d = (rec.rl[day] ??= {})
429 const v = Math.round(l.percentUsed * 10) / 10
430 if (!(d[l.kind]! >= v)) d[l.kind] = v
431 }
432}
433
434// ---------- Limit-Fenster und Abo (SPEC Nachtrag 0.5.0) ----------
435
436/** Fenster, die gebucht werden; `spend_limit` (Gateway) und Unbekanntes bleiben außen vor (types:10953). */
437export const LIMIT_KINDS: readonly string[] = ['five_hour', 'seven_day']
438const MINUTE = 60 * 1000
439const HOUR = 60 * MINUTE
440/**
441 * Je Fenster: Länge (aus dem Namen abgeleitet, nur für Beschriftung und „unvollständig“), Toleranz beim Zusammenlegen in
442 * der Aggregation (Absicherung, Phase 0: `resetsAt` war über Antworten und parallele Sessions gleich) und wie viele
443 * Einträge ein Datensatz höchstens behält.
444 */
445const LIM: Record<string, { span: number; tol: number; keep: number }> = {
446 five_hour: { span: 5 * HOUR, tol: 10 * MINUTE, keep: 60 },
447 seven_day: { span: 7 * DAY, tol: 60 * MINUTE, keep: 12 },
448}
449
450/** Ein Fenster, wie `usage().rateLimits` es zuletzt meldete; `resetsAt` in ms. */
451export type Limit = { kind: string; pct: number; resetsAt: number }
452/** Beträge, die auf das nächste gültige Fenster warten (Fenster abgelaufen oder noch unbekannt). */
453export type Carry = Record<string, { chat: number; mod: number }>
454
455/** `five_hour` und `seven_day` mit Zahl und parsebarem `resetsAt` (types:10948-10966); sonst nichts. */
456export function limitsOf(rl: readonly { kind: string; percentUsed: number; resetsAt?: string }[] | undefined): Limit[] {
457 const out: Limit[] = []
458 for (const l of rl ?? []) {
459 if (!l || !LIMIT_KINDS.includes(l.kind) || !isNum(l.percentUsed) || out.some((x) => x.kind === l.kind)) continue
460 const at = typeof l.resetsAt === 'string' ? Date.parse(l.resetsAt) : NaN
461 if (Number.isFinite(at)) out.push({ kind: l.kind, pct: l.percentUsed, resetsAt: at })
462 }
463 return out
464}
465
466/** Schlüssel eines Fensters: `resetsAt` auf die volle Minute gerundet, als String (ms). */
467export function limKey(resetsAt: number): string {
468 return String(Math.round(resetsAt / MINUTE) * MINUTE)
469}
470
471/**
472 * Betrag (`chat`: Delta wie in `bookChat`, `mod`: Mod-Aufruf) dem laufenden Fenster je Art gutschreiben und dessen
473 * `percentUsed` als Höchstwert merken. Ist das Fenster abgelaufen (`now ≥ resetsAt`) oder unbekannt, wartet der Betrag in
474 * `carry` und kommt beim nächsten gültigen Fenster dazu. Je Datensatz bleiben die neuesten 60 bzw. 12 Fenster.
475 * Gibt zurück, ob ein Fenster gebucht wurde.
476 */
477export function bookLim(rec: Rec, limits: readonly Limit[], now: number, part: 'chat' | 'mod', amount: number, carry: Carry): boolean {
478 const v = Math.max(0, amount || 0)
479 let booked = false
480 for (const kind of LIMIT_KINDS) {
481 const l = limits.find((x) => x.kind === kind)
482 if (!l || now >= l.resetsAt) {
483 if (v > 0) {
484 const c = (carry[kind] ??= { chat: 0, mod: 0 })
485 c[part] = r8(c[part] + v)
486 }
487 continue
488 }
489 const wins = (rec.lim[kind] ??= {})
490 const e = (wins[limKey(l.resetsAt)] ??= { chat: 0, mod: 0, pct: 0, first: now, last: now })
491 const c = carry[kind]
492 if (c) {
493 e.chat = r8(e.chat + c.chat)
494 e.mod = r8(e.mod + c.mod)
495 delete carry[kind]
496 }
497 e[part] = r8(e[part] + v)
498 if (l.pct > e.pct) e.pct = l.pct
499 e.last = now
500 booked = true
501 const keys = Object.keys(wins).sort((a, b) => Number(a) - Number(b))
502 for (const k of keys.slice(0, Math.max(0, keys.length - LIM[kind]!.keep))) delete wins[k]
503 }
504 return booked
505}
506
507/**
508 * Nachbuchung beim Start (Rest nach der letzten Buchung, z. B. nach hartem Ende und `--resume`): Sie gehört in das Fenster,
509 * in das die letzte Buchung `at` fiel, nicht ins laufende. Gibt es dort keinen Eintrag (Buchung vor 0.5.0, ohne Abo),
510 * bleibt der Betrag nur im Tag.
511 */
512export function bookLimAt(rec: Rec, at: number, amount: number): void {
513 if (!(amount > 0)) return
514 for (const kind of LIMIT_KINDS) {
515 const wins = rec.lim[kind]
516 if (!wins) continue
517 let hit: string | null = null
518 for (const [k, e] of Object.entries(wins)) if (Number(k) > at && e.first <= at && (hit === null || Number(k) < Number(hit))) hit = k
519 if (hit !== null) wins[hit]!.chat = r8(wins[hit]!.chat + amount)
520 }
521}
522
523/** Abo-Pläne mit Listenpreis in $ je Monat: Pro claude.com/pricing (monatlich), Max support.claude.com Artikel 11049741 (2026-10-08). */
524export const PLANS: Record<string, { label: string; price?: number }> = {
525 pro: { label: 'Pro', price: 20 },
526 max5: { label: 'Max 5x', price: 100 },
527 max20: { label: 'Max 20x', price: 200 },
528 team: { label: 'Team' },
529 enterprise: { label: 'Enterprise' },
530}
531const PLAN_ALIASES: Record<string, string> = { pro: 'pro', max5: 'max5', max5x: 'max5', '5x': 'max5', max20: 'max20', max20x: 'max20', '20x': 'max20', team: 'team', enterprise: 'enterprise' }
532/** Nur eigene Schlüssel: `constructor` oder `__proto__` sind kein Plan. */
533const own = (o: object, k: string) => Object.prototype.hasOwnProperty.call(o, k)
534
535/** Alle Schreibweisen eines Plans, die `/ledger plan` annimmt (für Hilfe und Vollständigkeitstest). */
536export function planWords(): string[] {
537 return Object.keys(PLAN_ALIASES)
538}
539
540/** `meta:plan`: Plan, Abrechnungstag, eigener Preis (ohne: Listenpreis), Zeitpunkt der Einstellung. */
541export type Plan = { v: 1; plan: string; day: number; price?: number; at: number }
542
543export function planLabel(plan: string): string {
544 return own(PLANS, plan) ? PLANS[plan]!.label : plan
545}
546
547/** Gespeicherte Einstellung prüfen; `null` bei fehlender oder kaputter. */
548export function cleanPlan(v: unknown): Plan | null {
549 if (!isObj(v) || v.v !== 1 || typeof v.plan !== 'string' || !own(PLANS, v.plan) || !isNum(v.day) || !isNum(v.at)) return null
550 if (!Number.isInteger(v.day) || v.day < 1 || v.day > 31) return null
551 return { v: 1, plan: v.plan, day: v.day, ...(isNum(v.price) && v.price > 0 ? { price: v.price } : {}), at: v.at }
552}
553
554/**
555 * `/ledger plan <plan> <tag|heute> [preis]` → Einstellung, sonst `null` (dann wird nichts gespeichert). Plan in beliebiger
556 * Schreibweise samt Aliasen, Tag 1–31 oder `today`/`heute`, Preis mit Komma oder Punkt, optional mit `$`.
557 */
558export function parsePlan(args: readonly string[], now: number): Plan | null {
559 const [p = '', d = '', price, ...rest] = args.map((a) => a.trim().toLowerCase())
560 const plan = own(PLAN_ALIASES, p) ? PLAN_ALIASES[p] : undefined
561 if (!plan || rest.length) return null
562 const day = TODAY_WORDS.includes(d) ? new Date(now).getDate() : /^\d{1,2}$/.test(d) ? Number(d) : NaN
563 if (!Number.isInteger(day) || day < 1 || day > 31) return null
564 if (price === undefined) return { v: 1, plan, day, at: now }
565 const s = price.replace(/^\$|\$$/g, '').replace(',', '.')
566 const n = /^\d{1,6}(\.\d{1,2})?$/.test(s) ? Number(s) : NaN
567 return n > 0 ? { v: 1, plan, day, price: n, at: now } : null
568}
569
570/** Tag `day` im Monat (Jahr, Monat 0–11), gekürzt auf die Länge des Monats (31. → 30.09.). */
571function billingDay(y: number, m: number, day: number): Date {
572 const len = new Date(y, m + 1, 0, 12).getDate()
573 return new Date(y, m, Math.min(day, len), 12)
574}
575
576/**
577 * Laufender Abo-Monat zum Abrechnungstag: Beginn = letzter Tag ≤ heute mit dem Tag `min(day, Länge des Monats)`,
578 * nächste Erneuerung einen Monat später, Resttage bis dahin (lokal, über Mittag gerechnet).
579 */
580export function planMonth(day: number, now: number): { start: string; next: string; daysLeft: number } {
581 const t = new Date(now)
582 let s = billingDay(t.getFullYear(), t.getMonth(), day)
583 if (t.getDate() < s.getDate()) s = billingDay(t.getFullYear(), t.getMonth() - 1, day)
584 const n = billingDay(s.getFullYear(), s.getMonth() + 1, day)
585 const noon = new Date(t.getFullYear(), t.getMonth(), t.getDate(), 12).getTime()
586 return { start: dayKey(s.getTime()), next: dayKey(n.getTime()), daysLeft: Math.round((n.getTime() - noon) / DAY) }
587}
588
589/** Ein Fenster in der Auswertung, über alle Datensätze summiert und zusammengelegt. */
590export type LimWindow = {
591 kind: string
592 resetsAt: number
593 /** `resetsAt` minus Fensterlänge (aus dem Namen abgeleitet) */
594 start: number
595 usd: number
596 pct: number
597 running: boolean
598 /** Begann vor der ersten Fenster-Buchung (`meta:limSince`): der Betrag ist unvollständig */
599 partial: boolean
600 /** Hochrechnung `usd ÷ pct × 100`, erst ab 5 % und nur für vollständige Fenster */
601 proj: number | null
602 /**
603 * Geschätzter Anteil außerhalb des Ledgers in Prozentpunkten (claude.ai, Handy, Chats ohne cost-ledger): `pct − usd ÷ k`,
604 * nie negativ; `null` ohne Kalibrierung `k` (SPEC Nachtrag 0.7.0, Verhalten 4).
605 */
606 outside: number | null
607}
608export type PlanReport = {
609 plan: string
610 day: number
611 price: number | null
612 /** Kein eigener Preis: Listenpreis des Plans */
613 listPrice: boolean
614 start: string
615 next: string
616 daysLeft: number
617 /** API-Wert seit Beginn des Abo-Monats aus Datensätzen, die Abo-Limits gesehen haben */
618 usd: number
619 factor: number | null
620 /** Beginn liegt vor `meta:since`: gezählt ab diesem Tag */
621 from: string | null
622}
623export type LimitsReport = {
624 five: LimWindow | null
625 week: LimWindow | null
626 seenFive: boolean
627 seenWeek: boolean
628 /** Letzte 10 Fünf-Stunden-Fenster, neueste zuerst */
629 history: LimWindow[]
630 /** Ø „100 % ≈ usd“ über abgeschlossene, vollständige Fünf-Stunden-Fenster ab 20 % */
631 avg: { usd: number; n: number } | null
632 plan: PlanReport | null
633 limSince: number | null
634 /** Kalibrierung `k` ($ je Prozentpunkt) je Fensterart für den Anteil außerhalb; `null` ohne vollständiges Fenster ≥ 20 % */
635 calib: { five: number | null; week: number | null }
636}
637
638/**
639 * Anteil außerhalb des Ledgers schätzen: Kalibrierung `k` = höchstes `usd ÷ pct` über abgeschlossene, vollständige Fenster
640 * ab 20 % mit Betrag (das Fenster, in dem am meisten über den Ledger lief, kommt „nur Ledger“ am nächsten). Je Fenster
641 * außerhalb ≈ `max(0, pct − usd ÷ k)`. Eher zu niedrig, weil auch das beste Fenster etwas Fremdes enthält.
642 */
643function withOutside(list: LimWindow[], keep: number): { list: LimWindow[]; k: number | null } {
644 const base = list.slice(-keep).filter((w) => !w.running && !w.partial && w.pct >= 20 && w.usd > 0)
645 const k = base.length ? Math.max(...base.map((w) => w.usd / w.pct)) : null
646 return { k, list: list.map((w) => ({ ...w, outside: k && w.pct > 0 && !w.partial ? Math.max(0, w.pct - w.usd / k) : null })) }
647}
648
649/** Hat der Datensatz je Abo-Limits gesehen? Läufe mit API-Schlüssel (ohne Limits) zählen nicht zum Abo-Monat. */
650function sawLimits(rec: Rec): boolean {
651 return Object.values(rec.rl).some((d) => LIMIT_KINDS.some((k) => k in d)) || Object.values(rec.lim).some((w) => Object.keys(w).length > 0)
652}
653
654/**
655 * Limits und Abo für `/ledger limits` und die Zeile in der Übersicht. Je Fenster werden `chat + mod` über alle Datensätze
656 * summiert, `pct` ist das Maximum (innerhalb eines Fensters steigt der Wert nur). Schlüssel, die näher als die Toleranz
657 * beieinanderliegen, werden zusammengelegt. `live`: die Fenster der letzten Messung dieses Prozesses (nur für `pct`).
658 */
659export function limitsReport(
660 recs: { rec: Rec }[],
661 now: number,
662 o: { plan?: Plan | null; limSince?: number | null; since?: number | null; live?: readonly Limit[] } = {},
663): LimitsReport {
664 const byKind = new Map<string, Map<number, { usd: number; pct: number }>>(LIMIT_KINDS.map((k) => [k, new Map()]))
665 let first = Infinity
666 for (const { rec } of recs)
667 for (const [kind, wins] of Object.entries(rec.lim)) {
668 const m = byKind.get(kind)
669 if (m)
670 for (const [k, w] of Object.entries(wins)) {
671 const x = m.get(Number(k)) ?? { usd: 0, pct: 0 }
672 x.usd += w.chat + w.mod
673 x.pct = Math.max(x.pct, w.pct)
674 m.set(Number(k), x)
675 first = Math.min(first, w.first)
676 }
677 }
678 for (const l of o.live ?? []) {
679 const m = byKind.get(l.kind)
680 if (!m || l.resetsAt <= now) continue
681 const at = Number(limKey(l.resetsAt))
682 const x = m.get(at) ?? { usd: 0, pct: 0 }
683 x.pct = Math.max(x.pct, l.pct)
684 m.set(at, x)
685 }
686 // Beginn der Fenster-Daten: `meta:limSince`, aber nie später als die früheste vorhandene Fenster-Buchung (setzt ein
687 // Prozess den Wert erst nach Buchungen anderer Chats, z. B. nach einem Reset, würden deren Fenster sonst rückwirkend
688 // unvollständig; Review 0.5.0). Ohne `meta:limSince` gilt die früheste Buchung.
689 const firstAt = Number.isFinite(first) ? first : null
690 const limSince = typeof o.limSince === 'number' && firstAt !== null ? Math.min(o.limSince, firstAt) : (o.limSince ?? firstAt)
691 const windows = (kind: string): LimWindow[] => {
692 const spec = LIM[kind]!
693 const merged: { resetsAt: number; usd: number; pct: number }[] = []
694 for (const [at, x] of [...byKind.get(kind)!.entries()].sort((a, b) => a[0] - b[0])) {
695 const last = merged[merged.length - 1]
696 if (last && at - last.resetsAt < spec.tol) {
697 last.resetsAt = at
698 last.usd += x.usd
699 last.pct = Math.max(last.pct, x.pct)
700 } else merged.push({ resetsAt: at, usd: x.usd, pct: x.pct })
701 }
702 // Hochrechnung nur für vollständige Fenster: Bei einem unvollständigen fehlt der API-Wert vor `limSince`, die Prozent
703 // zählen aber das ganze Fenster; die Zahl wäre systematisch zu niedrig (Smoke-Test 2026-10-08: Woche „100 % ≈ 2,37 $“).
704 // Ohne gebuchten Betrag (Host ohne Kostenbuch) gibt es ebenfalls keine.
705 return merged.map((w) => {
706 const start = w.resetsAt - spec.span
707 const partial = limSince === null || start < limSince
708 return { kind, ...w, start, running: w.resetsAt > now, partial, proj: w.pct >= 5 && w.usd > 0 && !partial ? (w.usd / w.pct) * 100 : null, outside: null }
709 })
710 }
711 const fiveOut = withOutside(windows('five_hour'), LIM.five_hour!.keep)
712 const weekOut = withOutside(windows('seven_day'), LIM.seven_day!.keep)
713 const five = fiveOut.list
714 const week = weekOut.list
715 // Ø nur über die neuesten 60 Fenster: Ein Datensatz behält höchstens 60 (`bookLim`); in älteren Fenstern fehlte sonst
716 // der gekürzte Betrag eines langen Chats, während andere Chats das volle `pct` liefern (Review 0.5.0)
717 // Fenster ohne gebuchten Betrag (Host ohne Kostenbuch) zählen nicht
718 const done = five.slice(-LIM.five_hour!.keep).filter((w) => !w.running && !w.partial && w.pct >= 20 && w.usd > 0)
719 const pctSum = done.reduce((a, w) => a + w.pct, 0)
720
721 let plan: PlanReport | null = null
722 if (o.plan) {
723 const pm = planMonth(o.plan.day, now)
724 const today = dayKey(now)
725 const inMonth = (d: string) => d >= pm.start && d <= today
726 let usd = 0
727 for (const { rec } of recs) {
728 if (!sawLimits(rec)) continue
729 for (const [d, v] of Object.entries(rec.days)) if (inMonth(d)) usd += v
730 for (const m of Object.values(rec.mods)) for (const [d, v] of Object.entries(m.days)) if (inMonth(d)) usd += v.usd
731 }
732 const price = o.plan.price ?? PLANS[o.plan.plan]?.price ?? null
733 const sinceDay = typeof o.since === 'number' ? dayKey(o.since) : null
734 plan = {
735 plan: o.plan.plan,
736 day: o.plan.day,
737 price,
738 listPrice: o.plan.price === undefined && price !== null,
739 ...pm,
740 usd,
741 factor: price ? usd / price : null,
742 from: sinceDay && pm.start < sinceDay ? sinceDay : null,
743 }
744 }
745 return {
746 five: five.find((w) => w.running) ?? null,
747 week: week.find((w) => w.running) ?? null,
748 seenFive: five.length > 0,
749 seenWeek: week.length > 0,
750 history: five.slice(-10).reverse(),
751 avg: pctSum > 0 ? { usd: (done.reduce((a, w) => a + w.usd, 0) / pctSum) * 100, n: done.length } : null,
752 plan,
753 limSince,
754 calib: { five: fiveOut.k, week: weekOut.k },
755 }
756}
757
758// ---------- Aggregation für /ledger ----------
759
760/** Gruppen-Schlüssel der Skript-Läufe in Projekten (Anzeige übersetzt). */
761export const SCRIPT_PROJECT = ':script'
762/**
763 * Gruppen-Schlüssel der Chats eines anderen Geräts: `:device:<Gerätename>`. Die Sync-Datei enthält keine Projektnamen
764 * (Bedingung Fynn 2026-10-19), deshalb stehen fremde Chats in Projekten unter ihrem Gerät.
765 */
766export const DEVICE_PROJECT = ':device:'
767
768/** Stand des Geräte-Syncs für die Anzeige: Anzahl Geräte (mit diesem), nicht lesbare Geräte, letzter Fehler, doppelte ID. */
769export type SyncInfo = { on: boolean; devices: number; unreadable: number; error: string; dupId: boolean }
770const NO_SYNC: SyncInfo = { on: false, devices: 1, unreadable: 0, error: '', dupId: false }
771
772export type Window = { usd: number; chats: number; mods: number }
773/** `title` leer = kein Name bekannt; die Anzeige nimmt dann „Chat vom …“ mit `firstAt`. */
774export type ChatRow = { id: string; title: string; firstAt: number; project: string; usd: number; lastDay: string; kind: Kind }
775export type ProjectRow = { name: string; usd: number; chats: number }
776export type ModRow = { name: string; usd: number; calls: number }
777export type ModelRow = { key: string; in: number; out: number; cr: number; cw: number; usd: number; n: number }
778/** Ein Balken im Verlauf: Tag oder Woche (Montag), Chat- und Mod-Kosten und ihre Aufteilung nach Modell (`MOD_PART`). */
779export type Bucket = { key: string; usd: number; parts: { key: string; usd: number }[] }
780export type Report = {
781 now: number
782 since: number | null
783 windows: { today: Window; d7: Window; d30: Window; all: Window }
784 projects: ProjectRow[]
785 chats: ChatRow[]
786 mods: ModRow[]
787 models: ModelRow[]
788 /** Verlauf: 14 Tage bzw. 14 Wochen, jeweils neueste zuerst */
789 series: { days: Bucket[]; weeks: Bucket[] }
790 unreadable: number
791 hasCost: boolean
792 total: number
793 /** Geschätzte Größe des Plugin-Speichers in Byte (Grenze 4 MiB, docs/raw/en/reference.md:294) */
794 storeBytes: number
795 writeError: string
796 limits: LimitsReport
797 sync: SyncInfo
798}
799
800export const STORE_LIMIT = 4 * 1024 * 1024
801
802/** `range`: Anzahl Tage einschließlich heute, oder `0` = alles. */
803export function aggregate(
804 recs: { id: string; rec: Rec }[],
805 now: number,
806 opts: {
807 range?: number
808 unreadable?: number
809 hasCost?: boolean
810 since?: number | null
811 storeBytes?: number
812 writeError?: string
813 plan?: Plan | null
814 limSince?: number | null
815 live?: readonly Limit[]
816 sync?: SyncInfo
817 },
818): Report {
819 const today = dayKey(now)
820 const inRange = (d: string, n: number) => (n <= 0 ? true : d >= dayBefore(now, n - 1) && d <= today)
821 const range = opts.range ?? 30
822 const win = (n: number): Window => {
823 let sum = 0
824 let chats = 0
825 let mods = 0
826 for (const { rec } of recs) {
827 let mine = 0
828 for (const [d, v] of Object.entries(rec.days)) if (inRange(d, n)) mine += v
829 for (const m of Object.values(rec.mods)) for (const [d, v] of Object.entries(m.days)) if (inRange(d, n)) mods += v.usd
830 sum += mine
831 if (mine > 0) chats++
832 }
833 return { usd: sum, chats, mods }
834 }
835
836 const proj = new Map<string, ProjectRow>()
837 const chats: ChatRow[] = []
838 const mods = new Map<string, ModRow>()
839 const models = new Map<string, ModelRow>()
840 for (const { id, rec } of recs) {
841 for (const [key, m] of [...Object.entries(rec.models), ...Object.entries(rec.modModels)])
842 for (const [d, v] of Object.entries(m.days))
843 if (inRange(d, range)) {
844 const row = models.get(key) ?? { key, in: 0, out: 0, cr: 0, cw: 0, usd: 0, n: 0 }
845 row.in += v.in
846 row.out += v.out
847 row.cr += v.cr
848 row.cw += v.cw
849 row.usd += v.usd
850 row.n += v.n
851 models.set(key, row)
852 }
853 let mine = 0
854 let lastDay = ''
855 for (const [d, v] of Object.entries(rec.days))
856 if (inRange(d, range) && v > 0) {
857 mine += v
858 if (d > lastDay) lastDay = d
859 }
860 if (mine > 0) {
861 // Fremde Geräte bleiben unter ihrem Gerät, auch ihre Skript-Läufe
862 const name = rec.project.startsWith(DEVICE_PROJECT) ? rec.project : rec.kind === 'script' ? SCRIPT_PROJECT : rec.project
863 const p = proj.get(name) ?? { name, usd: 0, chats: 0 }
864 p.usd += mine
865 p.chats++
866 proj.set(name, p)
867 chats.push({ id, title: rec.title.trim(), firstAt: rec.firstAt, project: name, usd: mine, lastDay, kind: rec.kind })
868 }
869 for (const [name, m] of Object.entries(rec.mods))
870 for (const [d, v] of Object.entries(m.days))
871 if (inRange(d, range)) {
872 const row = mods.get(name) ?? { name, usd: 0, calls: 0 }
873 row.usd += v.usd
874 row.calls += v.calls
875 mods.set(name, row)
876 }
877 }
878 return {
879 now,
880 since: opts.since ?? null,
881 windows: { today: win(1), d7: win(7), d30: win(30), all: win(0) },
882 projects: [...proj.values()].sort((a, b) => b.usd - a.usd || a.name.localeCompare(b.name)),
883 chats: chats.sort((a, b) => b.usd - a.usd || b.lastDay.localeCompare(a.lastDay)),
884 mods: [...mods.values()].sort((a, b) => b.usd - a.usd || b.calls - a.calls),
885 models: [...models.values()].sort((a, b) => b.usd - a.usd || b.n - a.n),
886 series: seriesOf(recs, now),
887 unreadable: opts.unreadable ?? 0,
888 hasCost: opts.hasCost ?? true,
889 total: recs.length,
890 storeBytes: opts.storeBytes ?? 0,
891 writeError: opts.writeError ?? '',
892 limits: limitsReport(recs, now, { plan: opts.plan, limSince: opts.limSince, since: opts.since, live: opts.live }),
893 sync: opts.sync ?? NO_SYNC,
894 }
895}
896
897/** Montag der Woche zu `YYYY-MM-DD` (lokal). */
898export function weekStart(day: string): string {
899 const [y, m, d] = day.split('-').map(Number) as [number, number, number]
900 const dt = new Date(y, m - 1, d, 12)
901 dt.setDate(dt.getDate() - ((dt.getDay() + 6) % 7))
902 return dayKey(dt.getTime())
903}
904
905/** ISO-Kalenderwoche zu einem Montag `YYYY-MM-DD`. */
906export function isoWeek(monday: string): number {
907 const [y, m, d] = monday.split('-').map(Number) as [number, number, number]
908 const thu = new Date(y, m - 1, d + 3, 12) // Donnerstag derselben Woche bestimmt das Jahr
909 const week1 = new Date(thu.getFullYear(), 0, 4, 12) // 4. Januar liegt immer in KW 1
910 return 1 + Math.round(((thu.getTime() - week1.getTime()) / DAY - 3 + ((week1.getDay() + 6) % 7)) / 7)
911}
912
913/** Teil eines Verlaufsbalkens, der aus Mod-Aufrufen stammt: `mod:sonnet-5-5`, ohne Modell-Daten `mod:unbekannt`. */
914export const MOD_PART = 'mod:'
915
916/** Legendentext eines Verlaufsteils: `opus-5-5` → `Opus 5.5`, `mod:sonnet-5-5` → `Sonnet 5.5 · Mods`. */
917export function partLabel(key: string, lang: Lang): string {
918 const t = T[lang]
919 if (!key.startsWith(MOD_PART)) return key === UNKNOWN_MODEL ? t.noData : modelName(key, lang)
920 const model = key.slice(MOD_PART.length)
921 return model === UNKNOWN_MODEL ? t.modsNoData : t.modsPart(modelName(model, lang))
922}
923
924/**
925 * Verlauf je Tag und je Woche. Die echten Chat-Kosten eines Tages werden je Chat nach den geschätzten Modell-Anteilen
926 * dieses Tages aufgeteilt; ohne Modell-Daten fällt der Betrag unter `UNKNOWN_MODEL`. Dazu kommen die Mod-Aufrufe je
927 * Modell als eigene Teile (`MOD_PART`); was in `mods` steht, aber nicht in `modModels` (Daten vor 0.3.0), wird
928 * `mod:unbekannt`. Der Balken zeigt damit Chat + Mods, wie die Kacheln zusammen.
929 */
930function seriesOf(recs: { rec: Rec }[], now: number): { days: Bucket[]; weeks: Bucket[] } {
931 const days = new Map(Array.from({ length: 14 }, (_, i) => [dayBefore(now, i), new Map<string, number>()] as const))
932 // Gleicher Wochentag i Wochen zurück → Montag jener Woche
933 const weeks = new Map(Array.from({ length: 14 }, (_, i) => [weekStart(dayBefore(now, i * 7)), new Map<string, number>()] as const))
934 const add = (bucket: Map<string, number> | undefined, key: string, v: number) => {
935 if (bucket && v > 0) bucket.set(key, (bucket.get(key) ?? 0) + v)
936 }
937 for (const { rec } of recs)
938 for (const [d, chat] of Object.entries(rec.days)) {
939 if (!(chat > 0)) continue
940 const shares: [string, number][] = []
941 for (const [k, m] of Object.entries(rec.models)) {
942 const v = m.days[d]?.usd ?? 0
943 if (v > 0) shares.push([k, v])
944 }
945 const sum = shares.reduce((a, [, v]) => a + v, 0)
946 const parts: [string, number][] = sum > 0 ? shares.map(([k, v]) => [k, (chat * v) / sum]) : [[UNKNOWN_MODEL, chat]]
947 for (const [k, v] of parts) {
948 add(days.get(d), k, v)
949 add(weeks.get(weekStart(d)), k, v)
950 }
951 }
952 for (const { rec } of recs) {
953 const modDays = new Map<string, number>()
954 for (const m of Object.values(rec.mods)) for (const [d, v] of Object.entries(m.days)) modDays.set(d, (modDays.get(d) ?? 0) + v.usd)
955 for (const [k, m] of Object.entries(rec.modModels))
956 for (const [d, v] of Object.entries(m.days)) {
957 add(days.get(d), MOD_PART + k, v.usd)
958 add(weeks.get(weekStart(d)), MOD_PART + k, v.usd)
959 modDays.set(d, (modDays.get(d) ?? 0) - v.usd)
960 }
961 // Rest ohne Modell; Rundungsreste aus r8 nicht als eigenen Teil zeigen
962 for (const [d, rest] of modDays)
963 if (rest > 1e-6) {
964 add(days.get(d), MOD_PART + UNKNOWN_MODEL, rest)
965 add(weeks.get(weekStart(d)), MOD_PART + UNKNOWN_MODEL, rest)
966 }
967 }
968 const toBuckets = (m: Map<string, Map<string, number>>): Bucket[] =>
969 [...m.entries()].map(([key, parts]) => {
970 const list = [...parts.entries()].map(([k, v]) => ({ key: k, usd: v })).sort((a, b) => b.usd - a.usd)
971 return { key, usd: list.reduce((a, p) => a + p.usd, 0), parts: list }
972 })
973 return { days: toBuckets(days), weeks: toBuckets(weeks) }
974}
975
976/** Argument `7|30|all` → Tage (0 = alles); sonst Standard 30. `alle` bleibt als Alias gültig. */
977export function parseRange(a: string | undefined): number {
978 const s = (a ?? '').trim().toLowerCase()
979 if (RANGE_WORDS.includes(s)) return 0
980 const n = Number(s)
981 return Number.isInteger(n) && n > 0 && n <= 3650 ? n : 30
982}
983
984// ---------- Anzeige-Bausteine, die Text und Zeichnung teilen ----------
985
986/** Projektname zur Anzeige: Skript-Läufe und „ohne Ordner“ in der eingestellten Sprache. */
987export function projectLabel(name: string, lang: Lang): string {
988 if (name === SCRIPT_PROJECT) return T[lang].scriptRuns
989 if (name === NO_FOLDER) return T[lang].noFolder
990 if (name.startsWith(DEVICE_PROJECT)) return T[lang].otherDevice(name.slice(DEVICE_PROJECT.length))
991 return name
992}
993
994/** Name eines Chats zur Anzeige; ohne Titel „Chat vom …“ bzw. „Chat from …“. */
995export function chatLabel(c: { title: string; firstAt: number }, lang: Lang): string {
996 return c.title || T[lang].chatFrom(dateTime(c.firstAt, lang))
997}
998
999/** Hinweise für Text und Zeichnung: Host ohne Kosten, unlesbare Einträge, Speicher fast voll, Schreibfehler. */
1000export function notesOf(r: Report, lang: Lang): string[] {
1001 const t = T[lang]
1002 const out: string[] = []
1003 if (!r.hasCost) out.push(t.noCost)
1004 if (r.unreadable) out.push(t.unreadable(r.unreadable))
1005 if (r.storeBytes >= STORE_LIMIT * 0.75) out.push(t.storeFull(Math.round((r.storeBytes / STORE_LIMIT) * 100)))
1006 if (r.writeError) out.push(t.writeFailed(r.writeError))
1007 if (r.sync.error) out.push(t.syncFailed(r.sync.error))
1008 if (r.sync.unreadable) out.push(t.syncUnreadable(r.sync.unreadable))
1009 if (r.sync.dupId) out.push(t.syncDupId)
1010 return out
1011}
1012
1013/** „2 Geräte“ für Kopfzeile und Titel, erst ab zwei Geräten. */
1014export function devicesLabel(r: Report, lang: Lang): string {
1015 return r.sync.devices > 1 ? T[lang].devices(r.sync.devices) : ''
1016}
1017
1018/** Anteil außerhalb des Ledgers als Text; ohne Kalibrierung, wann es eine gibt; `''` bei unvollständigem Fenster. */
1019export function outsideText(w: LimWindow, k: number | null, lang: Lang): string {
1020 const t = T[lang]
1021 if (w.outside !== null) return t.outside(pct(w.outside), pct(w.pct))
1022 return k === null && !w.partial ? t.outsideLater : ''
1023}
1024
1025export type ViewName = 'overview' | 'chats' | 'projects' | 'models' | 'weeks' | 'limits'
1026
1027/** Seit wann ein unvollständiges Fenster zählt: 5 Stunden mit Uhrzeit, Woche mit Datum. */
1028export function partialLabel(w: LimWindow, limSince: number | null, lang: Lang): string {
1029 if (!w.partial || limSince === null) return ''
1030 return T[lang].partialFrom(w.kind === 'five_hour' ? clock(limSince) : shortDate(dayKey(limSince), lang))
1031}
1032
1033/** Hochrechnung „100 % ≈ …“ (als Schätzung beschriftet), sonst warum es noch keine gibt. */
1034export function projectionText(w: LimWindow, lang: Lang): string {
1035 const t = T[lang]
1036 if (w.proj !== null) return t.projection(usd(w.proj, lang))
1037 if (w.partial) return t.projectionPartial
1038 return w.pct >= 5 ? t.projectionNone : t.projectionLater
1039}
1040
1041/** Teile der kompakten Limit-Zeile (Übersicht); leer, wenn es weder ein Fenster noch einen Plan gibt. */
1042export function limitsLineParts(l: LimitsReport, now: number, lang: Lang): string[] {
1043 const t = T[lang]
1044 const out: string[] = []
1045 if (l.five) out.push(`${t.fiveShort} ${pct(l.five.pct)} · ${usd(l.five.usd, lang)} · ${t.resetAt(resetTime(l.five.resetsAt, now, lang))}`)
1046 else if (l.seenFive) out.push(`${t.fiveShort}: ${t.resetPassedShort}`)
1047 if (l.week) out.push(`${t.weekShort} ${pct(l.week.pct)} · ${usd(l.week.usd, lang)}`)
1048 if (l.plan) out.push(`${t.planShort} ${usd(l.plan.usd, lang)}${l.plan.factor !== null ? ` = ${factor(l.plan.factor, lang)}×` : ''}`)
1049 return out
1050}
1051
1052/** Abo-Monat in einer Zeile: Plan, Beginn, Erneuerung, API-Wert gegen Preis (ohne Preis kein Faktor). */
1053export function planLine(p: PlanReport, lang: Lang): { head: string; value: string; note: string } {
1054 const t = T[lang]
1055 const money = (v: number) => usd(v, lang)
1056 const value = p.price !== null && p.factor !== null ? t.planValue(money(p.usd), money(p.price), factor(p.factor, lang)) : t.planValueNoPrice(money(p.usd))
1057 const note = [p.listPrice ? t.listPrice : '', p.from ? t.partialFrom(shortDate(p.from, lang)) : ''].filter(Boolean).join(' · ')
1058 return { head: `${planLabel(p.plan)} · ${t.since(shortDate(p.start, lang))} · ${t.renews(shortDate(p.next, lang), p.daysLeft)}`, value, note }
1059}
1060
1061/** `/ledger limits` als Text: 5 Stunden, Woche, Abo-Monat, Verlauf, Ø (ohne Kopf- und Fußzeile). */
1062function limitsLines(l: LimitsReport, now: number, lang: Lang): string[] {
1063 const t = T[lang]
1064 const money = (v: number) => usd(v, lang)
1065 const out: string[] = []
1066 const hasLim = l.seenFive || l.seenWeek
1067 if (!hasLim) out.push(t.noLimitData)
1068 else
1069 for (const [w, seen, label, k] of [[l.five, l.seenFive, t.fiveHours, l.calib.five], [l.week, l.seenWeek, t.week, l.calib.week]] as const) {
1070 if (!w) {
1071 out.push(`${label}: ${seen ? t.resetPassed : t.noWindowYet}`)
1072 continue
1073 }
1074 const bits = [`${label}: ${pct(w.pct)}`, money(w.usd), `${t.resetAt(resetTime(w.resetsAt, now, lang))} (${t.inTime(duration(w.resetsAt - now, lang))})`]
1075 bits.push(projectionText(w, lang))
1076 const from = partialLabel(w, l.limSince, lang)
1077 if (from) bits.push(from)
1078 const outside = outsideText(w, k, lang)
1079 if (outside) bits.push(outside)
1080 out.push(bits.join(' · '))
1081 }
1082 if (l.plan) {
1083 const p = planLine(l.plan, lang)
1084 out.push(`${t.subMonth}: ${p.head} · ${p.value}${p.note ? ` (${p.note})` : ''}`)
1085 } else out.push(t.planNotSet)
1086 if (hasLim) {
1087 const rows = l.history.slice(0, 4).map((w) => {
1088 const from = partialLabel(w, l.limSince, lang)
1089 const out = w.outside !== null ? ` (${t.outsideShort(pct(w.outside))})` : ''
1090 return `${span(w.start, w.resetsAt, lang)} ${money(w.usd)} ${pct(w.pct)}${out}${w.running ? ` ${t.running}` : ''}${from ? ` ${from}` : ''}`
1091 })
1092 if (rows.length) out.push(`${t.lastWindows}: ${rows.join(' · ')}${l.history.length > 4 ? ` · ${t.more(l.history.length - 4)}` : ''}`)
1093 out.push(l.avg ? t.avg(money(l.avg.usd), l.avg.n) : t.avgNone)
1094 }
1095 return out
1096}
1097
1098/**
1099 * Kurze Markdown-Fassung für Claude und für `-p` (höchstens 10 Zeilen, SPEC Verhalten 7). `tag` macht den Text eindeutig,
1100 * damit `ui.render` die passende Zeichnung findet.
1101 */
1102export function summaryText(r: Report, view: ViewName, range: number, tag: string, lang: Lang): string {
1103 const t = T[lang]
1104 const money = (v: number) => usd(v, lang)
1105 const join = <X>(rows: X[], fmt: (x: X) => string, max: number) => {
1106 const shown = rows.slice(0, max).map(fmt).join(' · ')
1107 return rows.length > max ? `${shown} · ${t.more(rows.length - max)}` : shown
1108 }
1109 const notes = notesOf(r, lang)
1110 // Hinweise und Fußzeile immer am Ende, auch wenn Listen gekürzt werden müssen (höchstens 10 Zeilen)
1111 const capped = (lines: string[], foot: string) => {
1112 const tail = [...notes, foot]
1113 return [...lines.slice(0, 10 - tail.length), ...tail].slice(0, 10).join('\n')
1114 }
1115 // Limits gibt es auch ohne Buchung (Plan eingestellt, Messung dieses Prozesses)
1116 const dev = devicesLabel(r, lang)
1117 const titled = (s: string) => (dev ? `${s} · ${dev}` : s)
1118 if (view === 'limits') return capped([titled(t.sumLimitsTitle(dateTime(r.now, lang), tag)), ...limitsLines(r.limits, r.now, lang)], t.sumLimitsFoot)
1119 const lines = [titled(t.sumTitle(dateTime(r.now, lang), tag))]
1120 // Die Limit-Zeile auch im Leerzustand (z. B. direkt nach /ledger reset: Plan und Messung sind noch da)
1121 const lim = view === 'overview' || view === 'weeks' ? limitsLineParts(r.limits, r.now, lang) : []
1122 if (lim.length) lines.push(t.sumLimitsLine(lim.join(' | ')))
1123 if (r.total === 0) return [...lines, ...notes, t.empty].join('\n')
1124 const w = r.windows
1125 if (view === 'overview' || view === 'weeks') {
1126 lines.push(t.sumChats(money(w.today.usd), w.today.chats, money(w.d7.usd), money(w.d30.usd), money(w.all.usd)))
1127 lines.push(t.sumMods(money(w.today.mods), money(w.d30.mods), money(w.all.mods)))
1128 if (r.projects.length) lines.push(t.sumProjects(join(r.projects, (p) => `${projectLabel(p.name, lang)} ${money(p.usd)}`, 5)))
1129 if (r.chats.length) lines.push(t.sumTopChats(join(r.chats, (c) => `${chatLabel(c, lang)} ${money(c.usd)}`, 3)))
1130 if (r.mods.length) lines.push(t.sumModsList(join(r.mods, (m) => `${projectLabel(m.name, lang)} ${money(m.usd)} (${m.calls}×)`, 4)))
1131 if (view === 'weeks') lines.push(t.sumWeeks(r.series.weeks.slice(0, 6).map((b) => `${weekLabel(isoWeek(b.key), lang)} ${money(b.usd)}`).join(' · ')))
1132 } else if (view === 'chats') {
1133 const rows = r.chats.slice(0, 20)
1134 lines.push(t.sumChatsHead(rangeLabel(range, lang), rows.length, r.chats.length))
1135 for (let i = 0; i < rows.length; i += 5)
1136 lines.push(rows.slice(i, i + 5).map((c, j) => `${i + j + 1}. ${chatLabel(c, lang)} (${projectLabel(c.project, lang)}) ${money(c.usd)}`).join(' · '))
1137 } else if (view === 'models') {
1138 const sum = r.models.reduce((a, m) => a + m.usd, 0)
1139 lines.push(t.sumModelsHead(rangeLabel(range, lang)))
1140 if (!r.models.length) lines.push(t.noTokens)
1141 for (const m of r.models.slice(0, 6)) {
1142 const tok = t.tokenLine(tokens(m.in, lang), tokens(m.out, lang), tokens(m.cr, lang), tokens(m.cw, lang))
1143 lines.push(t.sumModelLine(modelName(m.key, lang), money(m.usd), sum > 0 ? Math.round((m.usd / sum) * 100) : 0, m.n, tok))
1144 }
1145 if (r.models.length > 6) lines.push(t.sumMoreModels(r.models.length - 6))
1146 } else {
1147 lines.push(t.sumProjectsHead(rangeLabel(range, lang)))
1148 // Höchstens 4 Zeilen à 6; der Rest als „+N weitere“
1149 const shown = r.projects.slice(0, 24)
1150 for (let i = 0; i < shown.length; i += 6)
1151 lines.push(shown.slice(i, i + 6).map((p) => t.sumProjectRow(projectLabel(p.name, lang), money(p.usd), p.chats)).join(' · '))
1152 if (r.projects.length > shown.length) lines[lines.length - 1] += ` · ${t.more(r.projects.length - shown.length)}`
1153 }
1154 return capped(lines, t.sumFoot)
1155}
1156
1157// ---------- /ledger help (docs/HELP-SPEC.md §5 „cost-ledger 0.6.0“) ----------
1158
1159/** Was die Hilfe außer den Einstellungen braucht: Plan, Belegung des Speichers, Beginn der Erfassung. */
1160export type HelpInfo = {
1161 plan: Plan | null
1162 storeBytes: number
1163 since: number | null
1164 /** Gerätename bei eingeschaltetem Sync, sonst `null` (der Ordner steht nicht in der Hilfe) */
1165 syncDevice?: string | null
1166}
1167
1168/** Zahl einer Einstellung in der Sprache: en `2.5`, de `2,5`. */
1169const settingNum = (v: number, lang: Lang) => (lang === 'de' ? String(v).replace('.', ',') : String(v))
1170
1171/**
1172 * Schnappschuss für `/ledger help`: Befehle genau so, wie der Parser sie annimmt (Wörter aus `HELP_WORDS` & Co.),
1173 * Funktionen mit Zustand beim Aufruf, Einstellungen mit ihrem wirksamen Wert (nach `cleanSettings`).
1174 */
1175export function ledgerHelp(s: Settings, info: HelpInfo): HelpData {
1176 const lang = s.lang
1177 const t = T[lang]
1178 const money = (v: number) => usd(v, lang)
1179 const p = info.plan
1180 const price = p ? (p.price ?? (own(PLANS, p.plan) ? PLANS[p.plan]!.price : undefined)) : undefined
1181 const priceText = p ? (price === undefined ? t.noPrice : `${t.perMonth(money(price))}${p.price === undefined ? ` (${t.listPrice})` : ''}`) : ''
1182 const pctUsed = Math.round((Math.max(0, info.storeBytes) / STORE_LIMIT) * 100)
1183 return {
1184 mod: 'cost-ledger',
1185 lang,
1186 intro: t.helpIntro,
1187 commands: [
1188 { cmd: '/ledger', does: t.helpOverview },
1189 { cmd: '/ledger weeks', does: t.helpWeeks },
1190 { cmd: '/ledger chats|projects|models [7|30|all]', does: t.helpLists },
1191 { cmd: '/ledger limits', does: t.helpLimits },
1192 { cmd: '/ledger plan', does: t.helpPlanShow },
1193 { cmd: '/ledger plan <plan> <day|today> [price]', does: t.helpPlanSet },
1194 { cmd: '/ledger plan off', does: t.helpPlanOff },
1195 { cmd: '/ledger sync', does: t.helpSyncShow },
1196 { cmd: t.helpSyncSetCmd, does: t.helpSyncSet },
1197 { cmd: t.helpSyncNameCmd, does: t.helpSyncName },
1198 { cmd: '/ledger sync off', does: t.helpSyncOff },
1199 { cmd: '/ledger reset', does: t.helpReset },
1200 { cmd: '/ledger help', does: t.helpHelp },hooks/sync.ts 214 lines1// cost-ledger: Geräte zusammenführen über einen synchronisierten Ordner (SPEC Nachtrag 0.7.0). Reine Logik ohne `$`.
2// Jedes Gerät schreibt nur seine eigene Datei `cost-ledger-<id>.json` und liest die der anderen. Die Datei liegt in einem
3// Cloud-Ordner und enthält deshalb nur Beträge, Tage, Fenster und Modelle, dazu was das Zusammenführen braucht (Session-ID,
4// letzte Buchung): keine Pfade, keinen Projektnamen, keinen Git-Remote, keine Chat-Titel, keine Mod-Namen (Bedingung Fynn
5// 2026-10-19, SPEC Nachtrag 0.7.0, Verhalten 1a).
6import { DEVICE_PROJECT, LIMIT_KINDS, cleanRec } from './logic.ts'
7import type { ModDay, ModelDay, Rec } from './logic.ts'
8
9export type Device = { id: string; name: string }
10export type SyncFile = { v: 1; kind: 'cost-ledger-device'; device: Device; at: number; since: number | null; recs: Record<string, Rec> }
11
12/** Höchstens so groß darf eine Datei sein, die gelesen oder geschrieben wird (`$.fs.read`/`write`, en/reference.md:313). */
13export const FILE_LIMIT = 4 * 1024 * 1024
14const NAME = /^cost-ledger-([0-9a-f]{8})\.json$/
15/** Modell-Schlüssel, die in die Datei dürfen (`opus-5-5`, `unbekannt`); alles andere (ARN, Deployment-Name) wird `other`. */
16const SAFE_MODEL = /^[a-z0-9][a-z0-9.-]{0,39}$/
17export const OTHER_MODEL = 'other'
18/** Alle Mod-Aufrufe eines Datensatzes unter einem Schlüssel, ohne die Namen der Mods. */
19export const POOLED_MODS = 'mods'
20/** Session-IDs (UUIDs); andere Schlüssel kommen nicht in die Datei und werden beim Lesen verworfen. */
21const SESSION_ID = /^[A-Za-z0-9_-]{1,80}$/
22const HOUR = 60 * 60 * 1000
23
24/** Zufällige Geräte-ID, 8 Hex-Zeichen. */
25export function newDeviceId(random: () => number = Math.random): string {
26 return Array.from({ length: 8 }, () => Math.floor(random() * 16).toString(16)).join('')
27}
28
29/** Gerätename: ohne Steuerzeichen, Leerraum zusammengezogen, höchstens 30 Zeichen; leer → Standard aus der ID. */
30export function cleanDeviceName(name: string | undefined, id: string, fallback: (id: string) => string): string {
31 const s = String(name ?? '')
32 .replace(/[\u0000-\u001f\u007f]/g, '')
33 .replace(/\s+/g, ' ')
34 .trim()
35 .slice(0, 30)
36 return s || fallback(id)
37}
38
39/**
40 * Sync-Ordner prüfen: absolut, kein Netzwerkort (`\\server`, `//server`, `\\?\…`; `$.fs` lehnt ihn ohnehin ab, types:3221),
41 * kein `..`, nicht die Wurzel eines Laufwerks oder Dateisystems. `windows`: Die Session läuft unter Windows, dann nur
42 * `X:\…` (ein `/…` hinge dort vom aktuellen Laufwerk ab, types:3216-3219). Gibt den Pfad ohne abschließenden Trenner
43 * zurück, sonst `null`.
44 */
45export function validDir(input: string, windows = false): string | null {
46 const p = String(input ?? '').trim().replace(/^"(.*)"$/, '$1')
47 if (!p || /^[\\/]{2}/.test(p)) return null
48 const drive = /^[A-Za-z]:[\\/]/.test(p)
49 if (!drive && (windows || !p.startsWith('/'))) return null
50 if (p.split(/[\\/]+/).some((s) => s === '..')) return null
51 const out = p.replace(/[\\/]+$/, '')
52 return !out || /^[A-Za-z]:$/.test(out) ? null : out
53}
54
55/** Dateiname der Gerätedatei. */
56export function fileName(id: string): string {
57 return `cost-ledger-${id}.json`
58}
59
60/** Geräte-ID aus einem Dateinamen; andere Dateien im Ordner (auch Konfliktkopien der Sync-Clients) → `null`. */
61export function idFromName(name: string): string | null {
62 return NAME.exec(name)?.[1] ?? null
63}
64
65/** Pfad im Ordner, mit dem Trenner, den der Ordner schon nutzt. */
66export function inDir(dir: string, name: string): string {
67 const sep = dir.includes('\\') ? '\\' : '/'
68 return /[\\/]$/.test(dir) ? `${dir}${name}` : `${dir}${sep}${name}`
69}
70
71/** Länge in UTF-8-Bytes (die Grenze von `$.fs` gilt für Bytes, nicht für Zeichen). */
72export function utf8Bytes(s: string): number {
73 if (s.length * 3 <= FILE_LIMIT) return s.length // reicht sicher; spart die Schleife
74 let n = 0
75 for (const ch of s) {
76 const c = ch.codePointAt(0)!
77 n += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4
78 }
79 return n
80}
81
82/** Modelle mit sicheren Schlüsseln; unbekannte Formen gehen in `other` (Tage werden addiert). */
83function safeModels(src: Rec['models']): Rec['models'] {
84 const out: Rec['models'] = {}
85 for (const [k, m] of Object.entries(src)) {
86 const days = (out[SAFE_MODEL.test(k) ? k : OTHER_MODEL] ??= { days: {} }).days
87 for (const [d, x] of Object.entries(m.days)) {
88 const h: ModelDay | undefined = days[d]
89 days[d] = h ? { in: h.in + x.in, out: h.out + x.out, cr: h.cr + x.cr, cw: h.cw + x.cw, usd: h.usd + x.usd, n: h.n + x.n } : { ...x }
90 }
91 }
92 return out
93}
94
95/** Mod-Aufrufe ohne Namen: alle Mods eines Datensatzes je Tag zusammen unter `mods`. */
96function pooledMods(src: Rec['mods']): Rec['mods'] {
97 const days: Record<string, ModDay> = {}
98 for (const m of Object.values(src))
99 for (const [d, x] of Object.entries(m.days)) {
100 const h = days[d]
101 const tok = h?.in !== undefined || x.in !== undefined
102 days[d] = {
103 usd: (h?.usd ?? 0) + x.usd,
104 calls: (h?.calls ?? 0) + x.calls,
105 ...(tok ? { in: (h?.in ?? 0) + (x.in ?? 0), out: (h?.out ?? 0) + (x.out ?? 0), cr: (h?.cr ?? 0) + (x.cr ?? 0), cw: (h?.cw ?? 0) + (x.cw ?? 0) } : {}),
106 }
107 }
108 return Object.keys(days).length ? { [POOLED_MODS]: { days } } : {}
109}
110
111/**
112 * Was von einem Datensatz in die geteilte Datei darf, als ausdrückliche Liste (ein neues Feld in `Rec` kommt so nie
113 * ungefragt hinein): Beträge je Tag, Mod-Aufrufe ohne Namen, Modelle mit sicheren Schlüsseln, Limit-Fenster, Art des Chats,
114 * erste Buchung auf die Stunde gerundet, letzte Buchung (fürs Zusammenführen). Projekt, Ordner, Titel, Remote und die
115 * Aktivität (`act`, `hours`) bleiben leer.
116 */
117export function shareRec(r: Rec): Rec {
118 const rl: Rec['rl'] = {}
119 for (const [d, k] of Object.entries(r.rl)) {
120 const kinds: Record<string, number> = {}
121 for (const kind of LIMIT_KINDS) if (typeof k[kind] === 'number') kinds[kind] = k[kind]!
122 if (Object.keys(kinds).length) rl[d] = kinds
123 }
124 const lim: Rec['lim'] = {}
125 for (const kind of LIMIT_KINDS) if (r.lim[kind]) lim[kind] = { ...r.lim[kind] }
126 return {
127 v: 1,
128 project: '',
129 root: '',
130 title: '',
131 kind: r.kind,
132 firstAt: Math.floor(r.firstAt / HOUR) * HOUR,
133 lastAt: r.lastAt,
134 c: r.c,
135 days: { ...r.days },
136 mods: pooledMods(r.mods),
137 models: safeModels(r.models),
138 modModels: safeModels(r.modModels),
139 act: {},
140 hours: {},
141 rl,
142 lim,
143 remote: '',
144 }
145}
146
147/** `meta:sync` prüfen: `{ v:1, dir, at }` mit gültigem Ordner, sonst `null` (= Sync aus). */
148export function cleanSync(v: unknown): { dir: string; at: number } | null {
149 const o = v as { v?: unknown; dir?: unknown; at?: unknown } | null
150 if (!o || typeof o !== 'object' || o.v !== 1 || typeof o.dir !== 'string') return null
151 const dir = validDir(o.dir)
152 return dir ? { dir, at: typeof o.at === 'number' ? o.at : 0 } : null
153}
154
155/** `meta:device` prüfen: ID aus 8 Hex-Zeichen, Name bereinigt. */
156export function cleanDevice(v: unknown, fallback: (id: string) => string): Device | null {
157 const o = v as { id?: unknown; name?: unknown } | null
158 if (!o || typeof o !== 'object' || typeof o.id !== 'string' || !/^[0-9a-f]{8}$/.test(o.id)) return null
159 return { id: o.id, name: cleanDeviceName(typeof o.name === 'string' ? o.name : '', o.id, fallback) }
160}
161
162/** Inhalt der eigenen Gerätedatei. */
163export function buildFile(device: Device, since: number | null, recs: { id: string; rec: Rec }[], now: number): string {
164 const out: Record<string, Rec> = {}
165 for (const { id, rec } of recs) if (SESSION_ID.test(id)) out[id] = shareRec(rec)
166 const file: SyncFile = { v: 1, kind: 'cost-ledger-device', device, at: now, since, recs: out }
167 return JSON.stringify(file)
168}
169
170/**
171 * Fremde Gerätedatei prüfen. `null` bei halb geschriebener Datei (Parse-Fehler), unbekannter Version oder Form, oder wenn
172 * die ID im Inhalt nicht zum Dateinamen passt. Einzelne kaputte Datensätze fallen heraus; was durchkommt, läuft noch einmal
173 * durch `shareRec` (keine fremden Schlüssel mit Zeilenumbrüchen o. Ä. in der Anzeige).
174 */
175export function parseFile(text: string, id: string): SyncFile | null {
176 let v: unknown
177 try {
178 v = JSON.parse(text)
179 } catch {
180 return null
181 }
182 const o = v as Partial<SyncFile> | null
183 if (!o || typeof o !== 'object' || o.v !== 1 || o.kind !== 'cost-ledger-device' || !o.device || o.device.id !== id) return null
184 if (typeof o.at !== 'number' || !o.recs || typeof o.recs !== 'object') return null
185 const recs: Record<string, Rec> = {}
186 for (const [sid, r] of Object.entries(o.recs)) {
187 const c = SESSION_ID.test(sid) ? cleanRec(r) : null
188 if (c) recs[sid] = shareRec(c)
189 }
190 const name = cleanDeviceName(typeof o.device.name === 'string' ? o.device.name : '', id, (x) => x)
191 return { v: 1, kind: 'cost-ledger-device', device: { id, name }, at: o.at, since: typeof o.since === 'number' ? o.since : null, recs }
192}
193
194/**
195 * Eigene und fremde Datensätze vereinigen, nach Session-ID ohne doppelte Zählung: Kommt eine ID mehrfach vor (zurückgespielte
196 * Sicherung, kopierter Speicher), zählt nur der Datensatz mit dem jüngsten `lastAt`. Fremde Chats und ihre Mod-Aufrufe stehen
197 * unter dem Gerät. Fremde Datensätze, deren letzte Buchung vor `cutoff` liegt (älter als `keepDays`), zählen nicht; löschen
198 * tut sie nur ihr eigenes Gerät.
199 */
200export function mergeRecs(own: { id: string; rec: Rec }[], peers: SyncFile[], cutoff = 0): { id: string; rec: Rec }[] {
201 const all = new Map<string, Rec>()
202 for (const { id, rec } of own) all.set(id, rec)
203 for (const p of peers)
204 for (const [id, r] of Object.entries(p.recs)) {
205 if (r.lastAt < cutoff) continue
206 const group = `${DEVICE_PROJECT}${p.device.name}`
207 const mods = r.mods[POOLED_MODS] ? { [group]: r.mods[POOLED_MODS]! } : {}
208 const rec = { ...r, project: group, mods }
209 const have = all.get(id)
210 if (!have || rec.lastAt > have.lastAt) all.set(id, rec)
211 }
212 return [...all.entries()].map(([id, rec]) => ({ id, rec }))
213}
214hooks/view.ts 380 lines1// cost-ledger: die Übersicht als reiner Datenbaum {type, props, children} (types RenderElement), ohne $.ui.resolve.
2// Nur Box und Text mit Props aus der Allowlist (API-DETAILS.md:1043-1080), sonst zeichnet die Engine ihr Original.
3//
4// Stil wie limit-bars: Claude-Orange nur für Überschriften, Beträge in normaler Schrift, Nebensachen gedimmt; Farbe tragen
5// nur die Balken. Kein festes Außenmaß: Der Desktop meldet mehr Spalten, als er zeigt, und zeichnet Blockzeichen breiter
6// als eine Zelle. Spalten sind deshalb Boxen mit fester Breite; im Desktop sind Balken Boxen mit Hintergrundfarbe und
7// ganzzahliger Prozentbreite (Kommaprozente verwirft er), im Terminal dünne `▄`. Der leere Teil zeigt den Hintergrund.
8import type { RenderElement, RenderNode } from 'claude-code'
9import { T, dateTime, duration, factor, fullDate, pct, rangeLabel, resetTime, shortDate, span, tokens, usd, weekLabel } from './i18n.ts'
10import type { Lang } from './i18n.ts'
11import {
12 MOD_PART,
13 UNKNOWN_MODEL,
14 chatLabel,
15 devicesLabel,
16 isoWeek,
17 modelName,
18 notesOf,
19 outsideText,
20 partLabel,
21 partialLabel,
22 planLabel,
23 planLine,
24 projectLabel,
25 projectionText,
26} from './logic.ts'
27import type { Bucket, LimWindow, LimitsReport, Report, Settings, ViewName } from './logic.ts'
28
29export type View = { report: Report; view: ViewName; range: number }
30type Surface = 'terminal' | 'desktop'
31
32// Theme-Keys statt fester Hex-Werte: Sie folgen dem Theme des Nutzers, hell wie dunkel (types Color/ThemeKey).
33const ORANGE = 'claude'
34const YELLOW = 'warning'
35const RED = 'error'
36// Farben je Modell, nach Anteil vergeben; ohne Modell-Daten gedimmt
37const MODEL_COLORS = ['claude', 'suggestion', 'success', 'permission', 'warning', 'planMode', 'ide', 'remember']
38const UNKNOWN_COLOR = 'inactive'
39
40type Props = Record<string, string | number | boolean>
41
42function el(type: 'Box' | 'Text', props: Props, children: RenderNode[]): RenderElement {
43 return { type, props, children }
44}
45const text = (s: string, props: Props = {}) => el('Text', props, [s])
46const dim = (s: string) => text(s, { dimColor: true })
47const row = (props: Props, kids: RenderNode[]) => el('Box', { flexDirection: 'row', ...props }, kids)
48const col = (props: Props, kids: RenderNode[]) => el('Box', { flexDirection: 'column', ...props }, kids)
49/** Feste Spalte; `right` richtet den Inhalt rechts aus (Beträge). */
50const cell = (width: number, kid: RenderNode, right = false) =>
51 el('Box', { width, flexShrink: 0, ...(right ? { justifyContent: 'flex-end' } : {}) }, [kid])
52const heading = (s: string) => el('Box', { marginTop: 1 }, [text(s, { color: ORANGE, bold: true })])
53
54/** `total` ganze Einheiten nach Anteilen verteilen: erst abrunden, den Rest an die größten Nachkommareste (Summe = total). */
55function largestRemainder(shares: number[], total: number): number[] {
56 const sum = shares.reduce((a, b) => a + b, 0)
57 if (!(sum > 0) || total <= 0) return shares.map(() => 0)
58 const raw = shares.map((x) => (x / sum) * total)
59 const got = raw.map((x) => Math.floor(x))
60 let left = total - got.reduce((a, b) => a + b, 0)
61 const order = raw.map((x, i) => [x - Math.floor(x), i] as const).sort((a, b) => b[0] - a[0])
62 for (const [, i] of order) {
63 if (left <= 0) break
64 got[i]! += 1
65 left -= 1
66 }
67 return got
68}
69
70/**
71 * Balken der Länge `ratio` (0–1), aufgeteilt in `parts` (Anteile) mit je einer Farbe; ein einfarbiger Balken hat einen Teil.
72 * Desktop: Boxen in ganzzahliger Prozentbreite (der Desktop verwirft Kommaprozente), Summe genau 100. Terminal: ganze
73 * Zellen `▄`, verteilt nach größtem Rest; ein Teil unter einer halben Zelle kann dort fehlen.
74 */
75export function stackedBar(surface: Surface, ratio: number, cells: number, parts: { color: string; share: number }[]): RenderElement {
76 const r = Math.max(0, Math.min(1, ratio || 0))
77 const list = parts.filter((p) => p.share > 0)
78 if (surface === 'desktop') {
79 const pct = r > 0 ? Math.max(1, Math.round(r * 100)) : 0
80 const widths = largestRemainder(list.map((p) => p.share), 100)
81 const segs = list.flatMap((p, i) => (widths[i]! > 0 ? [el('Box', { width: `${widths[i]}%`, backgroundColor: p.color }, [' '])] : []))
82 const fill = pct > 0 && segs.length ? [el('Box', { width: `${pct}%`, flexDirection: 'row' }, segs)] : [' ']
83 return el('Box', { flexGrow: 1, minWidth: 6, marginRight: 1 }, fill)
84 }
85 const n = Math.max(1, cells)
86 const on = r > 0 ? Math.max(1, Math.round(r * n)) : 0
87 const got = largestRemainder(list.map((p) => p.share), on)
88 const kids: RenderNode[] = list.flatMap((p, i) => (got[i]! > 0 ? [text('▄'.repeat(got[i]!), { color: p.color })] : []))
89 return el('Box', { width: n + 1, flexShrink: 0 }, [kids.length ? el('Text', {}, kids) : ' '])
90}
91
92const bar = (sf: Surface, ratio: number, cells: number, color: string) => stackedBar(sf, ratio, cells, [{ color, share: 1 }])
93
94/**
95 * Farbe je Verlaufsteil: erst die Chat-Modelle nach Gesamtbetrag, danach die Mod-Teile (`mod:…`), damit sie in der
96 * Legende hinter dem Chat stehen. Beträge ohne Modell-Daten (Chat wie Mods) immer gedimmt.
97 */
98export function modelColors(buckets: Bucket[]): Map<string, string> {
99 const tot = new Map<string, number>()
100 for (const b of buckets) for (const p of b.parts) tot.set(p.key, (tot.get(p.key) ?? 0) + p.usd)
101 const unknown = (k: string) => k === UNKNOWN_MODEL || k === MOD_PART + UNKNOWN_MODEL
102 const isMod = (k: string) => (k.startsWith(MOD_PART) ? 1 : 0)
103 const keys = [...tot.entries()]
104 .filter(([k]) => !unknown(k))
105 .sort((a, b) => isMod(a[0]) - isMod(b[0]) || b[1] - a[1])
106 .map(([k]) => k)
107 const out = new Map(keys.map((k, i) => [k, MODEL_COLORS[i % MODEL_COLORS.length]!]))
108 for (const k of [UNKNOWN_MODEL, MOD_PART + UNKNOWN_MODEL]) if (tot.has(k)) out.set(k, UNKNOWN_COLOR)
109 return out
110}
111
112/** Ampel für Tagesbeträge (`dayYellow`/`dayRed`); darunter die normale Schriftfarbe des Themes (`text`). */
113function ampel(v: number, s: Settings): Props {
114 return { color: v >= s.dayRed ? RED : v >= s.dayYellow ? YELLOW : 'text' }
115}
116
117function cut(s: string, n: number): string {
118 return s.length <= n ? s : `${s.slice(0, Math.max(1, n - 1))}…`
119}
120
121/** Eine Kennzahl: Überschrift gedimmt, Betrag fett, darunter Chats und Mods. */
122function figure(label: string, w: { usd: number; chats: number; mods: number }, width: string, lang: Lang): RenderElement {
123 return col({ width, paddingRight: 2 }, [dim(label), text(usd(w.usd, lang), { bold: true }), dim(`${T[lang].chats(w.chats)} · Mods ${usd(w.mods, lang)}`)])
124}
125
126/**
127 * Verlauf der letzten 14 Tage oder Wochen: je Zeile ein Balken, geteilt nach Modell, darunter die Legende. Der Betrag ist
128 * der echte Chat-Betrag plus die Mod-Aufrufe; die Aufteilung folgt den geschätzten Modell-Anteilen, Mod-Teile stehen in
129 * der Legende als „Modell · Mods“. Die Ampel färbt bei Tagen den Betrag.
130 */
131function historyBlock(r: Report, s: Settings, sf: Surface, inner: number, weeks: boolean): RenderElement[] {
132 const lang = s.lang
133 const t = T[lang]
134 const buckets = weeks ? r.series.weeks : r.series.days
135 const colors = modelColors(buckets)
136 const max = Math.max(0, ...buckets.map((b) => b.usd))
137 const top = buckets.find((b) => b.usd === max && max > 0)?.key
138 const labelW = 7
139 // Terminal: Beschriftung, Betrag 10, Marke 12 → der Rest ist Balken
140 const cells = Math.max(6, Math.min(32, inner - labelW - 10 - 12 - 1))
141 const rows = buckets.map((b) =>
142 row({}, [
143 cell(labelW, dim(weeks ? weekLabel(isoWeek(b.key), lang) : shortDate(b.key, lang))),
144 stackedBar(sf, max > 0 ? b.usd / max : 0, cells, b.parts.map((p) => ({ color: colors.get(p.key) ?? UNKNOWN_COLOR, share: b.usd > 0 ? p.usd / b.usd : 0 }))),
145 cell(10, b.usd > 0 ? text(usd(b.usd, lang), weeks ? {} : ampel(b.usd, s)) : dim('–'), true),
146 cell(12, b.key === top ? dim(` ${t.highest}`) : ''),
147 ]),
148 )
149 const legend: RenderNode[] = [...colors.entries()].map(([k, c]) =>
150 el('Box', { marginRight: 2 }, [el('Text', {}, [text('▄ ', { color: c }), dim(partLabel(k, lang))])]),
151 )
152 return [heading(weeks ? t.last14Weeks : t.last14Days), ...rows, ...(legend.length ? [row({ flexWrap: 'wrap', marginTop: 1 }, legend)] : [])]
153}
154
155function projectsBlock(r: Report, title: string, sf: Surface, width: number, limit: number, basis: string, lang: Lang): RenderElement {
156 const list = r.projects.slice(0, limit).map((p) => ({ ...p, label: projectLabel(p.name, lang) }))
157 const max = Math.max(0, ...list.map((p) => p.usd))
158 const nameW = Math.min(18, Math.max(8, ...list.map((p) => p.label.length + 1)))
159 const cells = Math.max(4, Math.min(24, width - nameW - 10 - 1 - 2)) // 2 = paddingRight
160 const kids: RenderNode[] = list.length
161 ? list.map((p) => row({}, [cell(nameW, text(cut(p.label, nameW - 1))), bar(sf, max > 0 ? p.usd / max : 0, cells, ORANGE), cell(10, text(usd(p.usd, lang)), true)]))
162 : [dim(T[lang].noCosts)]
163 if (r.projects.length > limit) kids.push(dim(T[lang].more(r.projects.length - limit)))
164 return col({ width: basis, paddingRight: 2 }, [heading(title), ...kids])
165}
166
167function chatsBlock(r: Report, title: string, width: number, limit: number, basis: string, lang: Lang): RenderElement {
168 const list = r.chats.slice(0, limit)
169 const nameW = Math.max(12, Math.min(48, width - 3 - 10))
170 const kids: RenderNode[] = list.length
171 ? list.flatMap((c, i) => [
172 row({}, [
173 cell(3, dim(`${i + 1}`)),
174 el('Box', { flexGrow: 1, minWidth: 8 }, [text(cut(chatLabel(c, lang), nameW), { wrap: 'truncate-end' })]),
175 cell(10, text(usd(c.usd, lang)), true),
176 ]),
177 row({}, [cell(3, ''), dim(`${projectLabel(c.project, lang)} · ${shortDate(c.lastDay, lang)}`)]),
178 ])
179 : [dim(T[lang].noCosts)]
180 return col({ width: basis }, [heading(title), ...kids])
181}
182
183/** `/ledger models`: je Modell Anteil am geschätzten API-Wert als Balken, Betrag, Anzahl und darunter die Tokens. */
184function modelsBlock(r: Report, title: string, sf: Surface, inner: number, lang: Lang): RenderElement {
185 const t = T[lang]
186 const sum = r.models.reduce((a, m) => a + m.usd, 0)
187 const names = r.models.map((m) => modelName(m.key, lang))
188 const nameW = Math.min(16, Math.max(10, ...names.map((n) => n.length + 1)))
189 const cells = Math.max(6, Math.min(32, inner - nameW - 6 - 10 - 8 - 1))
190 const kids: RenderNode[] = r.models.length
191 ? r.models.flatMap((m, i) => [
192 row({ marginTop: 1 }, [
193 cell(nameW, text(names[i]!, { bold: true })),
194 bar(sf, sum > 0 ? m.usd / sum : 0, cells, ORANGE),
195 cell(6, dim(`${sum > 0 ? Math.round((m.usd / sum) * 100) : 0} %`), true),
196 cell(10, text(usd(m.usd, lang)), true),
197 cell(8, dim(`${m.n}×`), true),
198 ]),
199 dim(t.tokenLine(tokens(m.in, lang), tokens(m.out, lang), tokens(m.cr, lang), tokens(m.cw, lang))),
200 ])
201 : [dim(t.noTokens)]
202 kids.push(el('Box', { marginTop: 1 }, [dim(t.modelsNote)]))
203 return col({}, [heading(title), ...kids])
204}
205
206function modsBlock(r: Report, title: string, lang: Lang): RenderElement {
207 const t = T[lang]
208 // Mod-Aufrufe anderer Geräte stehen ohne Mod-Namen unter dem Gerät (Sync, Nachtrag 0.7.0)
209 const line = r.mods.length ? r.mods.map((m) => `${projectLabel(m.name, lang)} ${usd(m.usd, lang)} (${m.calls}×)`).join(' · ') : t.noModCalls
210 return col({}, [heading(title), text(line, r.mods.length ? {} : { dimColor: true }), dim(t.modsExtra)])
211}
212
213/**
214 * Ampel für die Auslastung eines Limit-Fensters: grün unter 70 %, gelb unter 90 %, rot ab 90 % (SPEC Nachtrag 0.5.0).
215 * Nach der angezeigten, gerundeten Zahl, damit „70 %“ nie grün ist (`percentUsed` hat eine Nachkommastelle).
216 */
217function limColor(p: number): string {
218 const v = Math.round(p || 0)
219 return v >= 90 ? RED : v >= 70 ? YELLOW : 'success'
220}
221
222/**
223 * Ein Limit-Fenster (5 Stunden oder Woche): Überschrift mit Reset und Countdown (Stand beim Aufruf), rechts „ab …“, falls
224 * das Fenster vor der ersten Fenster-Buchung begann; darunter Balken = % genutzt, %, API-Wert und die Hochrechnung.
225 */
226function windowBlock(
227 w: LimWindow | null,
228 seen: boolean,
229 title: string,
230 k: number | null,
231 l: LimitsReport,
232 now: number,
233 sf: Surface,
234 inner: number,
235 lang: Lang,
236): RenderNode[] {
237 const t = T[lang]
238 if (!w) return [heading(title), dim(seen ? t.resetPassed : t.noWindowYet)]
239 const from = partialLabel(w, l.limSince, lang)
240 const head = row({ justifyContent: 'space-between', flexWrap: 'wrap', marginTop: 1 }, [
241 text(`${title} · ${t.resetAt(resetTime(w.resetsAt, now, lang))} (${t.inTime(duration(w.resetsAt - now, lang))})`, { color: ORANGE, bold: true }),
242 ...(from ? [dim(from)] : []),
243 ])
244 // Terminal: Balken, % 7, Betrag 12; die Hochrechnung bricht bei schmaler Breite in die nächste Zeile um
245 const cells = Math.max(6, Math.min(32, inner - 7 - 12 - 1))
246 const line = row({ flexWrap: 'wrap' }, [
247 bar(sf, w.pct / 100, cells, limColor(w.pct)),
248 cell(7, text(pct(w.pct), { color: limColor(w.pct) }), true),
249 cell(12, text(usd(w.usd, lang), { bold: true }), true),
250 el('Box', { paddingLeft: 3 }, [dim(projectionText(w, lang))]),
251 ])
252 // Geschätzter Anteil außerhalb des Ledgers (SPEC Nachtrag 0.7.0, Verhalten 4)
253 const outside = outsideText(w, k, lang)
254 return [head, line, ...(outside ? [dim(outside)] : [])]
255}
256
257function planBlock(l: LimitsReport, lang: Lang): RenderNode[] {
258 const t = T[lang]
259 if (!l.plan) return [heading(t.subMonth), dim(t.planNotSet)]
260 const p = planLine(l.plan, lang)
261 return [heading(`${t.subMonth} · ${p.head}`), el('Text', {}, [text(p.value), ...(p.note ? [dim(` · ${p.note}`)] : [])])]
262}
263
264/** Die letzten 10 Fünf-Stunden-Fenster: Balken = API-Wert relativ zum teuersten, Farbe nach % wie oben; darunter das Ø. */
265function windowsHistory(l: LimitsReport, sf: Surface, inner: number, lang: Lang): RenderNode[] {
266 const t = T[lang]
267 const max = Math.max(0, ...l.history.map((w) => w.usd))
268 const labelW = 19
269 // Beschriftung 19, Betrag 10, % 7, Marke 15 („ outside 100 %“) → der Rest ist Balken. Reicht die Breite nicht, brechen
270 // die Zellen um: Der kleinste Balken braucht im Terminal 5 Zellen, im Desktop minWidth 6 + marginRight 1 (stackedBar)
271 const markW = 15
272 const cells = Math.max(4, Math.min(24, inner - labelW - 10 - 7 - markW - 1))
273 const narrow = inner < labelW + (sf === 'desktop' ? 7 : cells + 1) + 10 + 7 + markW
274 // Marke: läuft, unvollständig ab …, sonst der geschätzte Anteil außerhalb des Ledgers
275 const mark = (w: LimWindow) =>
276 w.running ? ` ${t.running}` : w.partial ? ` ${partialLabel(w, l.limSince, lang)}` : w.outside !== null ? ` ${t.outsideShort(pct(w.outside))}` : ''
277 const rows = l.history.map((w) =>
278 row(narrow ? { flexWrap: 'wrap' } : {}, [
279 cell(labelW, dim(span(w.start, w.resetsAt, lang))),
280 bar(sf, max > 0 ? w.usd / max : 0, cells, limColor(w.pct)),
281 cell(10, text(usd(w.usd, lang)), true),
282 cell(7, dim(pct(w.pct)), true),
283 cell(markW, dim(mark(w))),
284 ]),
285 )
286 return [
287 heading(t.lastWindows),
288 ...(rows.length ? rows : [dim(t.noWindows)]),
289 el('Box', { marginTop: 1 }, [l.avg ? text(t.avg(usd(l.avg.usd, lang), l.avg.n)) : dim(t.avgNone)]),
290 ]
291}
292
293/** `/ledger limits`: 5 Stunden, Woche, Abo-Monat, Verlauf; ohne Limit-Daten ein Hinweis statt der Fenster. */
294function limitsBlocks(r: Report, sf: Surface, inner: number, lang: Lang): RenderNode[] {
295 const t = T[lang]
296 const l = r.limits
297 if (!l.seenFive && !l.seenWeek)
298 return [el('Box', { marginTop: 1 }, [text(t.noLimitData)]), ...(l.plan ? planBlock(l, lang) : [dim(t.planNotSet)])]
299 return [
300 ...windowBlock(l.five, l.seenFive, t.fiveHours, l.calib.five, l, r.now, sf, inner, lang),
301 ...windowBlock(l.week, l.seenWeek, t.week, l.calib.week, l, r.now, sf, inner, lang),
302 ...planBlock(l, lang),
303 ...windowsHistory(l, sf, inner, lang),
304 ]
305}
306
307/** Kompakte Limit-Zeile oben in der Übersicht; bricht bei schmaler Breite um. Entfällt ohne Fenster und ohne Plan. */
308function limitsLine(r: Report, lang: Lang): RenderElement | null {
309 const t = T[lang]
310 const l = r.limits
311 const money = (v: number) => usd(v, lang)
312 const parts: RenderNode[][] = []
313 if (l.five)
314 parts.push([text(`${t.fiveShort} `), text(pct(l.five.pct), { color: limColor(l.five.pct) }), dim(' · '), text(money(l.five.usd)), dim(` · ${t.resetAt(resetTime(l.five.resetsAt, r.now, lang))}`)])
315 else if (l.seenFive) parts.push([dim(`${t.fiveShort}: ${t.resetPassedShort}`)])
316 if (l.week) parts.push([text(`${t.weekShort} `), text(pct(l.week.pct), { color: limColor(l.week.pct) }), dim(' · '), text(money(l.week.usd))])
317 if (l.plan) parts.push([text(`${t.planShort} ${money(l.plan.usd)}`), ...(l.plan.factor !== null ? [dim(' = '), text(`${factor(l.plan.factor, lang)}×`)] : [])])
318 if (!parts.length) return null
319 const kids: RenderNode[] = parts.map((p, i) => el('Box', { marginRight: 1 }, [el('Text', {}, [...(i ? [dim('│ ')] : []), ...p])]))
320 kids.push(dim('· /ledger limits'))
321 return row({ flexWrap: 'wrap', marginTop: 1 }, kids)
322}
323
324/** Der Befehl, der dieselbe Ansicht mit frischen Zahlen zeichnet (samt Zeitraum). */
325function reloadCommand(v: View): string {
326 if (v.view === 'overview') return '/ledger'
327 if (v.view === 'weeks' || v.view === 'limits') return `/ledger ${v.view}`
328 return `/ledger ${v.view}${v.range === 30 ? '' : v.range <= 0 ? ' all' : ` ${v.range}`}`
329}
330
331/** Der ganze Baum für eine `CommandOutput`-Zeile von `/ledger`; `columns` dient nur als Richtwert (Terminal-Balken, Umbruch). */
332export function ledgerTree(v: View, s: Settings, columns: number, surface: Surface = 'terminal'): RenderElement {
333 const lang = s.lang
334 const t = T[lang]
335 const r = v.report
336 const cols = Math.max(30, Math.min(columns || 100, 140))
337 const inner = cols - 4 // Rahmen und paddingX
338 const limits = v.view === 'limits'
339 // Ohne Knopf (er bräuchte neue Rechte): oben rechts Stand und wie man neu lädt; bei den Limits statt „seit“ der Plan
340 const first = limits ? (r.limits.plan ? `${planLabel(r.limits.plan.plan)} · ` : '') : r.since ? `${t.since(fullDate(r.since, lang))} · ` : ''
341 const dev = devicesLabel(r, lang)
342 const stand = `${first}${dev ? `${dev} · ` : ''}${t.asOf(dateTime(r.now, lang))} · ${t.reload(reloadCommand(v))}`
343 const head = row({ justifyContent: 'space-between', flexWrap: 'wrap' }, [text(limits ? t.limitsHead : 'cost-ledger', { color: ORANGE, bold: true }), dim(stand)])
344 const notes: RenderNode[] = notesOf(r, lang).map((n) => text(n, { color: YELLOW }))
345 const foot = el('Box', { marginTop: 1 }, [dim(limits ? t.limitsFoot : t.foot)])
346 const frame = (kids: RenderNode[]) => col({ borderStyle: 'round', borderDimColor: true, paddingX: 1, width: '100%' }, [head, ...notes, ...kids, foot])
347
348 // Limits gibt es auch ohne Buchung (Plan eingestellt, Messung dieses Prozesses)
349 if (limits) return frame(limitsBlocks(r, surface, inner, lang))
350 // Die Limit-Zeile entfällt nur ohne Fenster und ohne Plan, auch im Leerzustand (z. B. direkt nach /ledger reset)
351 const lim = v.view === 'overview' || v.view === 'weeks' ? limitsLine(r, lang) : null
352 if (r.total === 0) return frame([...(lim ? [lim] : []), el('Box', { marginTop: 1 }, [text(t.empty)])])
353 const range = rangeLabel(v.range, lang)
354 if (v.view === 'chats') return frame([chatsBlock(r, t.chatsIn(range), inner, 20, '100%', lang)])
355 if (v.view === 'projects') return frame([projectsBlock(r, t.projectsIn(range), surface, inner, 40, '100%', lang)])
356 if (v.view === 'models') return frame([modelsBlock(r, t.modelsIn(range), surface, inner, lang)])
357
358 const w = r.windows
359 const d30 = rangeLabel(30, lang)
360 // Spalten als Prozent der Zeile (nie breiter als die Zeile): zwei Blöcke ab etwa 90 Zeichen, vier Kennzahlen ab 80
361 const side = inner >= 90
362 const half = side ? Math.floor(inner / 2) - 2 : inner
363 const fw = inner >= 80 ? '25%' : inner >= 40 ? '50%' : '100%'
364 return frame([
365 ...(lim ? [lim] : []),
366 row({ flexWrap: 'wrap', marginTop: 1 }, [
367 figure(t.today, w.today, fw, lang),
368 figure(t.days7, w.d7, fw, lang),
369 figure(t.days30, w.d30, fw, lang),
370 figure(t.allTime, w.all, fw, lang),
371 ]),
372 ...historyBlock(r, s, surface, inner, v.view === 'weeks'),
373 row({ flexWrap: 'wrap' }, [
374 projectsBlock(r, t.projectsIn(d30), surface, half, 8, side ? '50%' : '100%', lang),
375 chatsBlock(r, t.chatsIn(d30), half, 5, side ? '50%' : '100%', lang),
376 ]),
377 modsBlock(r, t.modsIn(d30), lang),
378 ])
379}
380