klui-code 0.1.3 → 0.1.5

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 CHANGED
@@ -1,17 +1,47 @@
1
1
  // Token usage across every Klui run on this machine, for /usage. Each finished model reply appends
2
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.
3
+ // `klui` processes, whose chats aren't among the saved sessions) all go through Klui's providers,
4
+ // so all of them count.
5
+ // Each line names the seller that answered (the gateway id, "<peerId>@<service>"), who asked (the
6
+ // main agent or a subagent), the chat it belongs to (a subagent's names its parent's), the timings
7
+ // (request start, first token and the end), and for a failed request what the providers said,
8
+ // which the chat itself never shows (see fallback.ts).
4
9
  // The first time the log is created it starts from the tokens in the saved sessions.
5
10
  import { appendFileSync, existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
6
11
  import { join } from "node:path";
7
12
  import { AGENT_DIR, KLUI_HOME } from "./paths.js";
8
13
  const DAY_MS = 24 * 60 * 60 * 1000;
14
+ /** What the model streams as it answers: the first of these is its first token. */
15
+ const DELTAS = new Set(["text_delta", "thinking_delta", "toolcall_delta", "toolcall_start"]);
9
16
  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) {
17
+ /** Set in a subagent's environment: the session id of the chat that started it. */
18
+ export const PARENT_SESSION_ENV = "KLUI_PARENT_SESSION";
19
+ /** Logs each model request, including follow-up turns and failures with no reported tokens. */
20
+ export function recordUsage(streamSimple, agent = "main", paths = PATHS) {
12
21
  return ((...args) => {
22
+ const start = Date.now();
23
+ const options = args[2];
24
+ const session = process.env[PARENT_SESSION_ENV] || options?.sessionId;
13
25
  const stream = streamSimple(...args);
14
- stream.result().then((message) => logUsage(message.usage, Date.now(), paths), () => { });
26
+ // Watch the events going into the stream for the first token; whoever reads it sees them unchanged.
27
+ let firstAt;
28
+ const push = stream.push?.bind(stream);
29
+ if (push) {
30
+ stream.push = (event) => {
31
+ if (firstAt === undefined && DELTAS.has(event.type))
32
+ firstAt = Date.now();
33
+ push(event);
34
+ };
35
+ }
36
+ // Both from the moment Klui asked, on the wall clock: the reply's own durationMs covers only the
37
+ // peer that answered, not the wait for a key, the peer list or peers that refused before it.
38
+ const log = (reply) => {
39
+ const end = Date.now();
40
+ const error = reply?.providerError || reply?.errorMessage;
41
+ const timing = { start, ttft: firstAt === undefined ? undefined : firstAt - start, ms: end - start };
42
+ appendEntry({ t: end, ...tokens(reply?.usage), model: reply?.responseModel ?? reply?.model, agent, ...timing, session, error: error?.slice(0, 1000) }, paths);
43
+ };
44
+ stream.result().then(log, () => log(undefined));
15
45
  return stream;
16
46
  });
17
47
  }
@@ -39,21 +69,16 @@ export function readUsage(now = Date.now(), paths = PATHS) {
39
69
  }
40
70
  return { day, lifetime };
41
71
  }
42
- function logUsage(usage, t, paths) {
43
- const line = toLine(usage, t);
44
- if (!line)
45
- return;
72
+ function appendEntry(entry, paths) {
46
73
  try {
47
74
  ensureLog(paths);
48
- appendFileSync(paths.file, line);
75
+ appendFileSync(paths.file, `${JSON.stringify(entry)}\n`);
49
76
  }
50
77
  catch { }
51
78
  }
52
- function toLine(usage, t) {
79
+ function tokens(usage) {
53
80
  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`;
81
+ return { input, output, cacheRead, cacheWrite };
57
82
  }
58
83
  /** Creates the log from the saved sessions' replies, once. Another process may beat us to it. */
59
84
  function ensureLog(paths) {
@@ -76,7 +101,8 @@ function ensureLog(paths) {
76
101
  const message = entry.message;
77
102
  if (entry.type !== "message" || message?.role !== "assistant")
78
103
  continue;
79
- lines += toLine(message.usage, message.timestamp ?? Date.parse(entry.timestamp)) ?? "";
104
+ const start = message.timestamp ?? Date.parse(entry.timestamp);
105
+ lines += `${JSON.stringify({ t: start + (message.durationMs ?? 0), ...tokens(message.usage), model: message.responseModel ?? message.model, agent: "main" })}\n`;
80
106
  }
81
107
  catch { }
82
108
  }
@@ -95,17 +121,26 @@ function sessionFiles(dir) {
95
121
  }
96
122
  }
97
123
  function empty() {
98
- return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, requests: 0 };
124
+ return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, requests: 0, subagents: 0, timed: 0, firstTokenMs: 0, streamedOutput: 0, streamMs: 0 };
99
125
  }
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;
126
+ function add(totals, entry) {
127
+ const { input, output, cacheRead, cacheWrite } = tokens(entry);
128
+ const total = input + output + cacheRead + cacheWrite;
105
129
  totals.input += input;
106
130
  totals.output += output;
107
131
  totals.cacheRead += cacheRead;
108
132
  totals.cacheWrite += cacheWrite;
109
- totals.total += input + output + cacheRead + cacheWrite;
133
+ totals.total += total;
110
134
  totals.requests++;
135
+ if (entry.agent === "subagent")
136
+ totals.subagents += total;
137
+ // Speed counts only replies that streamed: output over the time from first token to the end.
138
+ if (typeof entry.ttft === "number" && typeof entry.ms === "number" && entry.ms >= entry.ttft) {
139
+ totals.timed++;
140
+ totals.firstTokenMs += entry.ttft;
141
+ if (output > 0 && entry.ms > entry.ttft) {
142
+ totals.streamedOutput += output;
143
+ totals.streamMs += entry.ms - entry.ttft;
144
+ }
145
+ }
111
146
  }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "klui-code",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "klui-code",
9
- "version": "0.1.3",
9
+ "version": "0.1.5",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@earendil-works/chord": "1.1.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "klui-code",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "description": "Klui Code: a pixel-cute coding agent for your terminal, built on Pi and running on AntSeed.",
5
5
  "keywords": [
6
6
  "klui",