klui-code 0.1.2 → 0.1.4
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/README.md +21 -7
- package/dist/catalog.js +2 -15
- package/dist/extension/agents.js +362 -57
- package/dist/extension/checks.js +1 -1
- package/dist/extension/commands.js +3 -3
- package/dist/extension/index.js +97 -15
- package/dist/extension/todos.js +2 -2
- package/dist/extension/tools.js +10 -6
- package/dist/extension/voice.js +53 -8
- package/dist/extension/web.js +12 -5
- package/dist/extension/working.js +47 -15
- package/dist/fallback.js +69 -16
- package/dist/mascot.js +15 -0
- package/dist/pi-patches.js +41 -6
- package/dist/usage.js +46 -20
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
package/dist/fallback.js
CHANGED
|
@@ -11,17 +11,60 @@ const TURN_MIX = { cached: 24, input: 6, output: 1 };
|
|
|
11
11
|
const COST_WEIGHT = 0.75;
|
|
12
12
|
/** Klui's minimum reputation for paid peers, shared by every AntSeed model. */
|
|
13
13
|
const MIN_REPUTATION = 51;
|
|
14
|
+
/**
|
|
15
|
+
* Sellers we've checked read images on these models (Oct 2026: each named both colors of a
|
|
16
|
+
* two-color picture, and its token counts matched the model's own tokenizer), by peer id. Many
|
|
17
|
+
* don't say so in the gateway list, so an image goes to these first, by the usual price and
|
|
18
|
+
* reputation pick but past the reputation cutoff, since we know they work. Sellers that only advertise
|
|
19
|
+
* images come after.
|
|
20
|
+
*/
|
|
21
|
+
const VISION_TESTED = {
|
|
22
|
+
"666e688780b9fdee5d2fe8ccafa666bb084c4666": ["deepseek-v4.1-flash"], // bartly.eth64.de
|
|
23
|
+
"0b0b9574d5b038f6fd906325e699020423adf446": ["deepseek-v4.1-flash"], // ZLKPro-Api
|
|
24
|
+
"9e402b4d2b20f723ea8b7ae32bd46fec6d2a8ec3": ["deepseek-v4.1-flash"], // engy
|
|
25
|
+
"0ee134b462785a6407860278ced89d193e1d6c41": ["deepseek-v4.1-flash"], // klinn
|
|
26
|
+
"c3cf17082a164c4cf3504d50962668649d327662": ["deepseek-v4.1-flash"], // Apiport
|
|
27
|
+
};
|
|
14
28
|
/** A peer that failed sits out this long before it's tried again. */
|
|
15
29
|
const COOLDOWN_MS = 10 * 60_000;
|
|
16
|
-
/** A peer that hasn't started answering by now is treated as gone (some hang without a word). */
|
|
17
|
-
const ANSWER_TIMEOUT_MS = 25_000;
|
|
18
30
|
/** Paid peers tried per request: each failure can cost a timeout, and paid peers rarely all fail. */
|
|
19
31
|
const MAX_PAID_TRIES = 4;
|
|
20
|
-
/**
|
|
32
|
+
/**
|
|
33
|
+
* A peer that hasn't started answering by now is treated as gone (some hang without a word). Long
|
|
34
|
+
* prompts get longer: reading an uncached 900K-token conversation alone takes a peer 20-30 s.
|
|
35
|
+
*/
|
|
36
|
+
export function answerTimeoutMs(context) {
|
|
37
|
+
// About 4 characters a token; image data is left out, since a picture costs far fewer tokens than its base64.
|
|
38
|
+
const tokens = JSON.stringify(context, (key, value) => (key === "data" ? undefined : value)).length / 4;
|
|
39
|
+
return 25_000 + Math.round((tokens / 100_000) * 5_000);
|
|
40
|
+
}
|
|
41
|
+
/** The service name in a gateway model id: "<peerId>@deepseek-v4.1-flash" → "deepseek-v4.1-flash". */
|
|
21
42
|
export function serviceOf(id) {
|
|
22
43
|
const at = id.indexOf("@");
|
|
23
44
|
return at === -1 ? id : id.slice(at + 1);
|
|
24
45
|
}
|
|
46
|
+
/**
|
|
47
|
+
* The reply keeps the event model's id, so a resumed chat finds its model again, and names the peer
|
|
48
|
+
* that answered (`<peer>@<service>`) as the response model, for the usage log.
|
|
49
|
+
*/
|
|
50
|
+
function sellerAside(event, id) {
|
|
51
|
+
const reply = event.type === "done" ? event.message : event.type === "error" ? event.error : "partial" in event ? event.partial : undefined;
|
|
52
|
+
if (reply && reply.model !== id) {
|
|
53
|
+
reply.responseModel = reply.model;
|
|
54
|
+
reply.model = id;
|
|
55
|
+
}
|
|
56
|
+
return event;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Pi replays a reply's reasoning only to the model that wrote it, by id. Replies keep the event
|
|
60
|
+
* model's id (see sellerAside), so a copy of the chat names the seller again on the replies that
|
|
61
|
+
* seller wrote, as it did when replies kept the seller's id.
|
|
62
|
+
*/
|
|
63
|
+
function asSeller(context, attempt) {
|
|
64
|
+
if (!context.messages.some((m) => m.role === "assistant" && m.responseModel === attempt))
|
|
65
|
+
return context;
|
|
66
|
+
return { ...context, messages: context.messages.map((m) => (m.role === "assistant" && m.responseModel === attempt ? { ...m, model: attempt } : m)) };
|
|
67
|
+
}
|
|
25
68
|
/** What a typical turn costs on this offer, in USD per million tokens. */
|
|
26
69
|
export function turnPrice(offer) {
|
|
27
70
|
const { inputUsdPerMillion: input, outputUsdPerMillion: output } = offer;
|
|
@@ -35,7 +78,8 @@ export function turnPrice(offer) {
|
|
|
35
78
|
* Peers serving the model under any of `names` over chat completions, as pinned gateway ids, best
|
|
36
79
|
* first. A peer's score is 75% price (cheapest 1, dearest 0, on a log scale since prices span
|
|
37
80
|
* 1000x) and 25% reputation. Free peers always come first. `freeOnly` keeps just those peers;
|
|
38
|
-
* paid peers below Klui's reputation cutoff are left out.
|
|
81
|
+
* paid peers below Klui's reputation cutoff are left out. With `needsImages`, sellers in
|
|
82
|
+
* VISION_TESTED come first (cutoff or not), then those advertising images.
|
|
39
83
|
*/
|
|
40
84
|
export function rankOffers(models, names, freeOnly = false, needsImages = false) {
|
|
41
85
|
const wanted = new Set(names.map((n) => n.toLowerCase()));
|
|
@@ -45,23 +89,27 @@ export function rankOffers(models, names, freeOnly = false, needsImages = false)
|
|
|
45
89
|
for (const offer of model.peers ?? []) {
|
|
46
90
|
if (!listed && !wanted.has(offer.serviceId.toLowerCase()))
|
|
47
91
|
continue;
|
|
48
|
-
|
|
92
|
+
const tested = needsImages && !!VISION_TESTED[offer.peerId]?.some((n) => wanted.has(n));
|
|
93
|
+
if (needsImages && !tested && !offer.capabilities?.inputs?.includes("image"))
|
|
49
94
|
continue;
|
|
50
95
|
const price = turnPrice(offer);
|
|
51
96
|
const chat = !offer.protocols || offer.protocols.includes("openai-chat-completions");
|
|
52
97
|
if (price === undefined || !chat || (freeOnly && price !== 0))
|
|
53
98
|
continue;
|
|
54
99
|
const reputation = offer.effectiveReputationScore ?? offer.reputationScore ?? 0;
|
|
55
|
-
if (price !== 0 && reputation < MIN_REPUTATION)
|
|
100
|
+
if (price !== 0 && reputation < MIN_REPUTATION && !tested)
|
|
56
101
|
continue;
|
|
57
102
|
const existing = offers.get(offer.peerId);
|
|
58
103
|
if (existing && existing.price <= price)
|
|
59
104
|
continue;
|
|
60
|
-
offers.set(offer.peerId, { id: `${offer.peerId}@${offer.serviceId}`, price, reputation: Math.min(Math.max(reputation / 100, 0), 1) });
|
|
105
|
+
offers.set(offer.peerId, { id: `${offer.peerId}@${offer.serviceId}`, price, reputation: Math.min(Math.max(reputation / 100, 0), 1), tested });
|
|
61
106
|
}
|
|
62
107
|
}
|
|
63
108
|
const all = [...offers.values()];
|
|
64
|
-
|
|
109
|
+
return [...rank(all.filter((o) => o.tested)), ...rank(all.filter((o) => !o.tested))];
|
|
110
|
+
}
|
|
111
|
+
/** Price/reputation orders the peers; a free offer always wins over a paid one. */
|
|
112
|
+
function rank(all) {
|
|
65
113
|
const logs = all.map((o) => Math.log(o.price + 1e-4));
|
|
66
114
|
const lo = Math.min(...logs);
|
|
67
115
|
const hi = Math.max(...logs);
|
|
@@ -148,15 +196,16 @@ export function createFallback(getConfig, getApiKey, connect = async () => undef
|
|
|
148
196
|
if (needsImages && !next)
|
|
149
197
|
throw new Error(`No vision provider is available for ${model.name} right now. Try again or pick another vision model with /model.`);
|
|
150
198
|
let firstError;
|
|
151
|
-
|
|
199
|
+
const broke = [];
|
|
200
|
+
const answerTimeout = answerTimeoutMs(context);
|
|
152
201
|
while (next) {
|
|
153
202
|
tried.add(next);
|
|
154
203
|
const attempt = next;
|
|
155
204
|
next = undefined;
|
|
156
205
|
const silent = new AbortController();
|
|
157
|
-
const timer = setTimeout(() => silent.abort(),
|
|
206
|
+
const timer = setTimeout(() => silent.abort(), answerTimeout);
|
|
158
207
|
const signal = options?.signal ? AbortSignal.any([options.signal, silent.signal]) : silent.signal;
|
|
159
|
-
const events = base().streamSimple({ ...model, id: attempt }, context, { ...options, signal });
|
|
208
|
+
const events = base().streamSimple({ ...model, id: attempt }, asSeller(context, attempt), { ...options, signal });
|
|
160
209
|
let started = false;
|
|
161
210
|
try {
|
|
162
211
|
for await (const event of events) {
|
|
@@ -167,9 +216,12 @@ export function createFallback(getConfig, getApiKey, connect = async () => undef
|
|
|
167
216
|
cooling.set(attempt, Date.now() + COOLDOWN_MS);
|
|
168
217
|
if (working.get(model.id) === attempt)
|
|
169
218
|
working.delete(model.id);
|
|
170
|
-
// A paid 402
|
|
171
|
-
|
|
172
|
-
|
|
219
|
+
// A paid 402 from one seller doesn't mean the wallet is empty: a seller Klui hasn't paid
|
|
220
|
+
// yet must first reserve part of it for a payment channel, which a small balance can't
|
|
221
|
+
// cover while sellers that already have one keep answering. So try the next seller, and
|
|
222
|
+
// only call it out of credits when every seller tried said 402.
|
|
223
|
+
broke.push(paid && /^\s*402\b/.test(event.error.errorMessage ?? ""));
|
|
224
|
+
if (!(paid && tried.size >= MAX_PAID_TRIES))
|
|
173
225
|
next = await nextPeer();
|
|
174
226
|
break;
|
|
175
227
|
}
|
|
@@ -179,7 +231,7 @@ export function createFallback(getConfig, getApiKey, connect = async () => undef
|
|
|
179
231
|
if (!paid && attempt !== model.id)
|
|
180
232
|
working.set(model.id, attempt);
|
|
181
233
|
}
|
|
182
|
-
out.push(event);
|
|
234
|
+
out.push(sellerAside(event, model.id));
|
|
183
235
|
}
|
|
184
236
|
}
|
|
185
237
|
finally {
|
|
@@ -191,12 +243,13 @@ export function createFallback(getConfig, getApiKey, connect = async () => undef
|
|
|
191
243
|
// Every peer refused. The gateway's own message (a 402 asking to deposit funds, or a
|
|
192
244
|
// peer hash) means nothing to an attendee, so say what happened instead.
|
|
193
245
|
if (firstError?.type === "error") {
|
|
246
|
+
const outOfCredits = broke.length > 0 && broke.every(Boolean);
|
|
194
247
|
const errorMessage = outOfCredits
|
|
195
248
|
? `Klui is out of credits for ${model.name}. Pick a free model with /model.`
|
|
196
249
|
: paid
|
|
197
250
|
? `No provider is answering for ${model.name} right now. Try again, or pick another model with /model.`
|
|
198
251
|
: `No free provider is serving ${model.name} right now. Pick another model with /model.`;
|
|
199
|
-
out.push({ ...firstError, error: { ...firstError.error, errorMessage } });
|
|
252
|
+
out.push(sellerAside({ ...firstError, error: { ...firstError.error, errorMessage } }, model.id));
|
|
200
253
|
}
|
|
201
254
|
out.end();
|
|
202
255
|
})().catch((error) => {
|
package/dist/mascot.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// The pixel Klui from the web app's composer (public/js/composerKlui.js), drawn with half blocks.
|
|
2
2
|
// Same flat style and colors: a plain body, block arms, two block legs and dark eyes.
|
|
3
|
+
import { backgroundAnsi, foregroundAnsi, parseColor } from "@earendil-works/pi-tui";
|
|
3
4
|
import { canvas, fillRect, fromArt } from "./pixels.js";
|
|
4
5
|
export const KLUI = {
|
|
5
6
|
body: "#8fd3fb",
|
|
@@ -71,3 +72,17 @@ export function smallKlui(eyes = "open") {
|
|
|
71
72
|
const cheeks = eyes === "happy" || eyes === "wink" ? "..BPBBBBBBPB.." : "..BBBBBBBBBB..";
|
|
72
73
|
return fromArt(["..BBBBBBBBBB..", "..BBBBBBBBBB..", face, face, cheeks, cheeks, "....B....B....", "....B....B...."], MINI_PALETTE);
|
|
73
74
|
}
|
|
75
|
+
const TINY_EYES = { open: " ▪ ▪ ", left: "▪ ▪ ", right: " ▪ ▪", shut: " - - ", happy: " ^ ^ " };
|
|
76
|
+
/**
|
|
77
|
+
* The working line's Klui, one row tall: a blue body with dark eyes and an arm nub on each side,
|
|
78
|
+
* 8 columns wide. At this size the eyes are glyphs on the body color rather than pixels, since a
|
|
79
|
+
* whole dark cell reads as a hole on a dark terminal.
|
|
80
|
+
*/
|
|
81
|
+
export function tinyKlui(pose, mode) {
|
|
82
|
+
const body = foregroundAnsi(parseColor(KLUI.body), mode);
|
|
83
|
+
const eye = foregroundAnsi(parseColor(KLUI.eye), mode);
|
|
84
|
+
const fill = backgroundAnsi(parseColor(KLUI.body), mode);
|
|
85
|
+
const up = (side) => (pose.arms === "up" || pose.arms === side ? "▀" : "▄");
|
|
86
|
+
const sprite = `${body}${up("left")}${fill}${eye}${TINY_EYES[pose.eyes]}\x1b[49m${body}${up("right")}\x1b[39m`;
|
|
87
|
+
return pose.step ? ` ${sprite}` : `${sprite} `;
|
|
88
|
+
}
|
package/dist/pi-patches.js
CHANGED
|
@@ -2,16 +2,45 @@
|
|
|
2
2
|
// Pi's own modules (the same instance Pi runs, resolved from its package) and is skipped quietly
|
|
3
3
|
// if a Pi update moves things around.
|
|
4
4
|
import { Spacer, TruncatedText, TuiAltScreen } from "@earendil-works/pi-tui";
|
|
5
|
+
import { serviceOf } from "./fallback.js";
|
|
5
6
|
import { chipFor, isClipboardImageFile } from "./images.js";
|
|
7
|
+
import { PROVIDER } from "./paths.js";
|
|
6
8
|
import { scrollFrame } from "./scroll.js";
|
|
7
9
|
export const piModule = async (path) => (await import(new URL(path, import.meta.resolve("@earendil-works/pi-coding-agent")).href));
|
|
8
10
|
export async function patchPi(config) {
|
|
9
11
|
brandOutput();
|
|
10
12
|
scrollWithTerminal();
|
|
11
13
|
clearAfterCopy();
|
|
12
|
-
for (const patch of [hidePiFooter, hoverJumpToLatest, queuedMessages, trimSlashMenu, slashAliases, simpleThinkingMenu, thinkingAfterModel, () => tidyModelPicker(), () => quietPiHints(config), pasteImageChips])
|
|
14
|
+
for (const patch of [() => sellerModelIds(config), removeLlama, hidePiFooter, hoverJumpToLatest, queuedMessages, trimSlashMenu, slashAliases, simpleThinkingMenu, thinkingAfterModel, () => tidyModelPicker(), () => quietPiHints(config), pasteImageChips])
|
|
13
15
|
await patch().catch(() => { });
|
|
14
16
|
}
|
|
17
|
+
/**
|
|
18
|
+
* Chats saved before 0.1.4 name the peer that answered (`<peer>@deepseek-v4-1-flash`) as the model,
|
|
19
|
+
* so resuming one looked for a model that doesn't exist and warned before falling back. Resolve
|
|
20
|
+
* such an id to the event model it serves.
|
|
21
|
+
*/
|
|
22
|
+
async function sellerModelIds(config) {
|
|
23
|
+
const { ModelRuntime } = await piModule("./core/model-runtime.js");
|
|
24
|
+
const proto = ModelRuntime.prototype;
|
|
25
|
+
const getModel = proto.getModel;
|
|
26
|
+
if (typeof getModel !== "function")
|
|
27
|
+
return;
|
|
28
|
+
proto.getModel = function (provider, id) {
|
|
29
|
+
const found = getModel.call(this, provider, id);
|
|
30
|
+
if (found || provider !== PROVIDER || !id.includes("@"))
|
|
31
|
+
return found;
|
|
32
|
+
const service = serviceOf(id);
|
|
33
|
+
const model = config.models.find((m) => m.id === service || m.aliases?.includes(service));
|
|
34
|
+
return model ? getModel.call(this, provider, model.id) : undefined;
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/** Klui uses event models, so don't load Pi's local llama.cpp manager or its /llama command. */
|
|
38
|
+
async function removeLlama() {
|
|
39
|
+
const { builtInExtensions } = await piModule("./extensions/index.js");
|
|
40
|
+
const index = builtInExtensions.findIndex((extension) => extension.name === "llama.cpp");
|
|
41
|
+
if (index !== -1)
|
|
42
|
+
builtInExtensions.splice(index, 1);
|
|
43
|
+
}
|
|
15
44
|
/** Klui puts its own footer in place once it loads; Pi's would show until then, and again on /new. */
|
|
16
45
|
async function hidePiFooter() {
|
|
17
46
|
const { FooterComponent } = await piModule("./modes/interactive/components/footer.js");
|
|
@@ -136,11 +165,11 @@ function rebrand(text) {
|
|
|
136
165
|
/**
|
|
137
166
|
* Klui's slash menu: /resume and /exit (see slashAliases) open /sessions and quit. Pi's /session,
|
|
138
167
|
* its bug reporter (it files issues with the Pi developers), its changelog and /scoped-models stay
|
|
139
|
-
* out of the list; they still work when typed.
|
|
168
|
+
* out of the list; they still work when typed. Provider login/logout are removed as well.
|
|
140
169
|
*/
|
|
141
170
|
async function trimSlashMenu() {
|
|
142
171
|
const { BUILTIN_SLASH_COMMANDS: commands } = await piModule("./core/slash-commands.js");
|
|
143
|
-
const hidden = new Set(["session", "bug", "changelog", "scoped-models"]);
|
|
172
|
+
const hidden = new Set(["session", "bug", "changelog", "scoped-models", "login", "logout"]);
|
|
144
173
|
for (let i = commands.length - 1; i >= 0; i--)
|
|
145
174
|
if (hidden.has(commands[i].name))
|
|
146
175
|
commands.splice(i, 1);
|
|
@@ -157,7 +186,7 @@ export function showThinkingMenu() {
|
|
|
157
186
|
if (interactive?.session.supportsThinking())
|
|
158
187
|
interactive.showThinkingSelector();
|
|
159
188
|
}
|
|
160
|
-
/**
|
|
189
|
+
/** Session aliases and event-pass guidance in place of provider login/logout. */
|
|
161
190
|
async function slashAliases() {
|
|
162
191
|
const { InteractiveMode } = await piModule("./modes/interactive/interactive-mode.js");
|
|
163
192
|
const proto = InteractiveMode.prototype;
|
|
@@ -171,7 +200,13 @@ async function slashAliases() {
|
|
|
171
200
|
if (!submit)
|
|
172
201
|
return;
|
|
173
202
|
const aliases = { "/resume": "/sessions", "/exit": "/quit" };
|
|
174
|
-
this.defaultEditor.onSubmit = (text) =>
|
|
203
|
+
this.defaultEditor.onSubmit = async (text) => {
|
|
204
|
+
if (/^\/(login|logout)(\s|$)/.test(text.trim())) {
|
|
205
|
+
this.showError("Klui connects with your event pass automatically. Use /klui retry to reconnect.");
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
await submit(aliases[text.trim()] ?? text);
|
|
209
|
+
};
|
|
175
210
|
};
|
|
176
211
|
}
|
|
177
212
|
/**
|
|
@@ -261,7 +296,7 @@ async function tidyModelPicker() {
|
|
|
261
296
|
}
|
|
262
297
|
/**
|
|
263
298
|
* Pi suggests "/bug sends a report to the developers" after an error, and confirms a model switch
|
|
264
|
-
* with its gateway id ("Model: 73b4…@
|
|
299
|
+
* with its gateway id ("Model: 73b4…@deepseek-v4.1-flash"). Klui shows the model's name instead.
|
|
265
300
|
*/
|
|
266
301
|
async function quietPiHints(config) {
|
|
267
302
|
const { InteractiveMode } = await piModule("./modes/interactive/interactive-mode.js");
|
package/dist/usage.js
CHANGED
|
@@ -1,17 +1,38 @@
|
|
|
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
3
|
// `klui` processes that keep no session) all go through Klui's providers, so all of them count.
|
|
4
|
+
// Each line names the seller that answered (the gateway id, "<peerId>@<service>"), who asked (the
|
|
5
|
+
// main agent or a subagent) and the timings: request start, first token and the end.
|
|
4
6
|
// The first time the log is created it starts from the tokens in the saved sessions.
|
|
5
7
|
import { appendFileSync, existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
6
8
|
import { join } from "node:path";
|
|
7
9
|
import { AGENT_DIR, KLUI_HOME } from "./paths.js";
|
|
8
10
|
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
11
|
+
/** What the model streams as it answers: the first of these is its first token. */
|
|
12
|
+
const DELTAS = new Set(["text_delta", "thinking_delta", "toolcall_delta", "toolcall_start"]);
|
|
9
13
|
const PATHS = { file: join(KLUI_HOME, "usage.jsonl"), sessions: join(AGENT_DIR, "sessions") };
|
|
10
|
-
/**
|
|
11
|
-
export function recordUsage(streamSimple, paths = PATHS) {
|
|
14
|
+
/** Logs each model request, including follow-up turns and failures with no reported tokens. */
|
|
15
|
+
export function recordUsage(streamSimple, agent = "main", paths = PATHS) {
|
|
12
16
|
return ((...args) => {
|
|
17
|
+
const start = Date.now();
|
|
13
18
|
const stream = streamSimple(...args);
|
|
14
|
-
stream
|
|
19
|
+
// Watch the events going into the stream for the first token; whoever reads it sees them unchanged.
|
|
20
|
+
let firstAt;
|
|
21
|
+
const push = stream.push?.bind(stream);
|
|
22
|
+
if (push) {
|
|
23
|
+
stream.push = (event) => {
|
|
24
|
+
if (firstAt === undefined && DELTAS.has(event.type))
|
|
25
|
+
firstAt = Date.now();
|
|
26
|
+
push(event);
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
// Both from the moment Klui asked, on the wall clock: the reply's own durationMs covers only the
|
|
30
|
+
// peer that answered, not the wait for a key, the peer list or peers that refused before it.
|
|
31
|
+
const log = (reply) => {
|
|
32
|
+
const end = Date.now();
|
|
33
|
+
appendEntry({ t: end, ...tokens(reply?.usage), model: reply?.responseModel ?? reply?.model, agent, start, ttft: firstAt === undefined ? undefined : firstAt - start, ms: end - start }, paths);
|
|
34
|
+
};
|
|
35
|
+
stream.result().then(log, () => log(undefined));
|
|
15
36
|
return stream;
|
|
16
37
|
});
|
|
17
38
|
}
|
|
@@ -39,21 +60,16 @@ export function readUsage(now = Date.now(), paths = PATHS) {
|
|
|
39
60
|
}
|
|
40
61
|
return { day, lifetime };
|
|
41
62
|
}
|
|
42
|
-
function
|
|
43
|
-
const line = toLine(usage, t);
|
|
44
|
-
if (!line)
|
|
45
|
-
return;
|
|
63
|
+
function appendEntry(entry, paths) {
|
|
46
64
|
try {
|
|
47
65
|
ensureLog(paths);
|
|
48
|
-
appendFileSync(paths.file,
|
|
66
|
+
appendFileSync(paths.file, `${JSON.stringify(entry)}\n`);
|
|
49
67
|
}
|
|
50
68
|
catch { }
|
|
51
69
|
}
|
|
52
|
-
function
|
|
70
|
+
function tokens(usage) {
|
|
53
71
|
const { input = 0, output = 0, cacheRead = 0, cacheWrite = 0 } = usage ?? {};
|
|
54
|
-
|
|
55
|
-
return undefined;
|
|
56
|
-
return `${JSON.stringify({ t, input, output, cacheRead, cacheWrite })}\n`;
|
|
72
|
+
return { input, output, cacheRead, cacheWrite };
|
|
57
73
|
}
|
|
58
74
|
/** Creates the log from the saved sessions' replies, once. Another process may beat us to it. */
|
|
59
75
|
function ensureLog(paths) {
|
|
@@ -76,7 +92,8 @@ function ensureLog(paths) {
|
|
|
76
92
|
const message = entry.message;
|
|
77
93
|
if (entry.type !== "message" || message?.role !== "assistant")
|
|
78
94
|
continue;
|
|
79
|
-
|
|
95
|
+
const start = message.timestamp ?? Date.parse(entry.timestamp);
|
|
96
|
+
lines += `${JSON.stringify({ t: start + (message.durationMs ?? 0), ...tokens(message.usage), model: message.responseModel ?? message.model, agent: "main" })}\n`;
|
|
80
97
|
}
|
|
81
98
|
catch { }
|
|
82
99
|
}
|
|
@@ -95,17 +112,26 @@ function sessionFiles(dir) {
|
|
|
95
112
|
}
|
|
96
113
|
}
|
|
97
114
|
function empty() {
|
|
98
|
-
return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, requests: 0 };
|
|
115
|
+
return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, requests: 0, subagents: 0, timed: 0, firstTokenMs: 0, streamedOutput: 0, streamMs: 0 };
|
|
99
116
|
}
|
|
100
|
-
function add(totals,
|
|
101
|
-
const input
|
|
102
|
-
const
|
|
103
|
-
const cacheRead = usage.cacheRead ?? 0;
|
|
104
|
-
const cacheWrite = usage.cacheWrite ?? 0;
|
|
117
|
+
function add(totals, entry) {
|
|
118
|
+
const { input, output, cacheRead, cacheWrite } = tokens(entry);
|
|
119
|
+
const total = input + output + cacheRead + cacheWrite;
|
|
105
120
|
totals.input += input;
|
|
106
121
|
totals.output += output;
|
|
107
122
|
totals.cacheRead += cacheRead;
|
|
108
123
|
totals.cacheWrite += cacheWrite;
|
|
109
|
-
totals.total +=
|
|
124
|
+
totals.total += total;
|
|
110
125
|
totals.requests++;
|
|
126
|
+
if (entry.agent === "subagent")
|
|
127
|
+
totals.subagents += total;
|
|
128
|
+
// Speed counts only replies that streamed: output over the time from first token to the end.
|
|
129
|
+
if (typeof entry.ttft === "number" && typeof entry.ms === "number" && entry.ms >= entry.ttft) {
|
|
130
|
+
totals.timed++;
|
|
131
|
+
totals.firstTokenMs += entry.ttft;
|
|
132
|
+
if (output > 0 && entry.ms > entry.ttft) {
|
|
133
|
+
totals.streamedOutput += output;
|
|
134
|
+
totals.streamMs += entry.ms - entry.ttft;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
111
137
|
}
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "klui-code",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.4",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "klui-code",
|
|
9
|
-
"version": "0.1.
|
|
9
|
+
"version": "0.1.4",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@earendil-works/chord": "1.1.0",
|