klui-code 0.1.3 → 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/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
+ }
@@ -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
- /** /resume opens Klui's /sessions picker, and /exit quits like /quit. */
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) => submit(aliases[text.trim()] ?? 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
  /**
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
- /** Wraps a provider's stream so each finished reply's tokens are logged, whatever it ends with. */
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.result().then((message) => logUsage(message.usage, Date.now(), paths), () => { });
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 logUsage(usage, t, paths) {
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, line);
66
+ appendFileSync(paths.file, `${JSON.stringify(entry)}\n`);
49
67
  }
50
68
  catch { }
51
69
  }
52
- function toLine(usage, t) {
70
+ function tokens(usage) {
53
71
  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`;
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
- lines += toLine(message.usage, message.timestamp ?? Date.parse(entry.timestamp)) ?? "";
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, 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;
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 += input + output + cacheRead + cacheWrite;
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
  }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "klui-code",
3
- "version": "0.1.3",
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.3",
9
+ "version": "0.1.4",
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.4",
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",