klui-code 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/usage.js ADDED
@@ -0,0 +1,111 @@
1
+ // Token usage across every Klui run on this machine, for /usage. Each finished model reply appends
2
+ // one line to a log in KLUI_HOME: the main chat, compaction summaries and subagents (separate
3
+ // `klui` processes that keep no session) all go through Klui's providers, so all of them count.
4
+ // The first time the log is created it starts from the tokens in the saved sessions.
5
+ import { appendFileSync, existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { AGENT_DIR, KLUI_HOME } from "./paths.js";
8
+ const DAY_MS = 24 * 60 * 60 * 1000;
9
+ const PATHS = { file: join(KLUI_HOME, "usage.jsonl"), sessions: join(AGENT_DIR, "sessions") };
10
+ /** Wraps a provider's stream so each finished reply's tokens are logged, whatever it ends with. */
11
+ export function recordUsage(streamSimple, paths = PATHS) {
12
+ return ((...args) => {
13
+ const stream = streamSimple(...args);
14
+ stream.result().then((message) => logUsage(message.usage, Date.now(), paths), () => { });
15
+ return stream;
16
+ });
17
+ }
18
+ /** Tokens in the last 24 hours and since the log began. */
19
+ export function readUsage(now = Date.now(), paths = PATHS) {
20
+ ensureLog(paths);
21
+ const day = empty();
22
+ const lifetime = empty();
23
+ let text = "";
24
+ try {
25
+ text = readFileSync(paths.file, "utf8");
26
+ }
27
+ catch { }
28
+ for (const line of text.split("\n")) {
29
+ let entry;
30
+ try {
31
+ entry = JSON.parse(line);
32
+ }
33
+ catch {
34
+ continue;
35
+ }
36
+ add(lifetime, entry);
37
+ if (typeof entry.t === "number" && now - entry.t < DAY_MS)
38
+ add(day, entry);
39
+ }
40
+ return { day, lifetime };
41
+ }
42
+ function logUsage(usage, t, paths) {
43
+ const line = toLine(usage, t);
44
+ if (!line)
45
+ return;
46
+ try {
47
+ ensureLog(paths);
48
+ appendFileSync(paths.file, line);
49
+ }
50
+ catch { }
51
+ }
52
+ function toLine(usage, t) {
53
+ const { input = 0, output = 0, cacheRead = 0, cacheWrite = 0 } = usage ?? {};
54
+ if (input + output + cacheRead + cacheWrite <= 0)
55
+ return undefined;
56
+ return `${JSON.stringify({ t, input, output, cacheRead, cacheWrite })}\n`;
57
+ }
58
+ /** Creates the log from the saved sessions' replies, once. Another process may beat us to it. */
59
+ function ensureLog(paths) {
60
+ if (existsSync(paths.file))
61
+ return;
62
+ let lines = "";
63
+ for (const file of sessionFiles(paths.sessions)) {
64
+ let text;
65
+ try {
66
+ text = readFileSync(file, "utf8");
67
+ }
68
+ catch {
69
+ continue;
70
+ }
71
+ for (const line of text.split("\n")) {
72
+ if (!line.includes('"usage"'))
73
+ continue;
74
+ try {
75
+ const entry = JSON.parse(line);
76
+ const message = entry.message;
77
+ if (entry.type !== "message" || message?.role !== "assistant")
78
+ continue;
79
+ lines += toLine(message.usage, message.timestamp ?? Date.parse(entry.timestamp)) ?? "";
80
+ }
81
+ catch { }
82
+ }
83
+ }
84
+ try {
85
+ writeFileSync(paths.file, lines, { flag: "wx" });
86
+ }
87
+ catch { }
88
+ }
89
+ function sessionFiles(dir) {
90
+ try {
91
+ return readdirSync(dir, { recursive: true, encoding: "utf8" }).filter((f) => f.endsWith(".jsonl")).map((f) => join(dir, f));
92
+ }
93
+ catch {
94
+ return [];
95
+ }
96
+ }
97
+ function empty() {
98
+ return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, requests: 0 };
99
+ }
100
+ function add(totals, usage) {
101
+ const input = usage.input ?? 0;
102
+ const output = usage.output ?? 0;
103
+ const cacheRead = usage.cacheRead ?? 0;
104
+ const cacheWrite = usage.cacheWrite ?? 0;
105
+ totals.input += input;
106
+ totals.output += output;
107
+ totals.cacheRead += cacheRead;
108
+ totals.cacheWrite += cacheWrite;
109
+ totals.total += input + output + cacheRead + cacheWrite;
110
+ totals.requests++;
111
+ }