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.
@@ -9,7 +9,7 @@ import { ensureKey, fetchCredits, PassError, readDevice } from "../pass.js";
9
9
  import { PROVIDER } from "../paths.js";
10
10
  import { availableUpdate } from "../update.js";
11
11
  import { recordUsage } from "../usage.js";
12
- import { registerAgents, SUBAGENT_ENV } from "./agents.js";
12
+ import { agentProgress, registerAgents, SUBAGENT_ENV, subagentTokensSoFar } from "./agents.js";
13
13
  import { registerChecks } from "./checks.js";
14
14
  import { registerCommands } from "./commands.js";
15
15
  import { createFooter } from "./footer.js";
@@ -18,7 +18,7 @@ import { initialMode, registerPermissions } from "./permissions.js";
18
18
  import { initState, modelLabel, state, update } from "./state.js";
19
19
  import { registerTodos } from "./todos.js";
20
20
  import { registerCompactTools } from "./tools.js";
21
- import { describeTool } from "./voice.js";
21
+ import { describeTool, preparingLabel } from "./voice.js";
22
22
  import { registerWeb } from "./web.js";
23
23
  import { createDoneWidget, createWorkingWidget } from "./working.js";
24
24
  const WIDGET = "klui-working";
@@ -82,7 +82,7 @@ export const createKluiExtension = ({ config, live, fresh }) => async (pi) => {
82
82
  // instead of Pi asking the attendee to /login somewhere.
83
83
  apiKey: usableKey() ?? "klui-no-key",
84
84
  models: toProviderModels(state.config),
85
- streamSimple: recordUsage(fallback.streamSimple),
85
+ streamSimple: recordUsage(fallback.streamSimple, process.env[SUBAGENT_ENV] === "1" ? "subagent" : "main"),
86
86
  });
87
87
  };
88
88
  // Without a key, Klui keeps asking Klui Pass in the background, soon at first and then about
@@ -207,7 +207,7 @@ export const createKluiExtension = ({ config, live, fresh }) => async (pi) => {
207
207
  ctx.ui.setFooter((tui, theme, footerData) => createFooter(pi, ctx, tui, theme, footerData));
208
208
  // Klui's typing widget replaces Pi's one-line "Working..." loader.
209
209
  ctx.ui.setWorkingVisible(false);
210
- ctx.ui.setHiddenThinkingLabel(`✦ reasoning · ${keyText("app.thinking.toggle")} to show`);
210
+ ctx.ui.setHiddenThinkingLabel(`reasoning · ${keyText("app.thinking.toggle")} to show`);
211
211
  title();
212
212
  void refreshCredits(true);
213
213
  if (state.connection.kind === "closed")
@@ -246,14 +246,46 @@ export const createKluiExtension = ({ config, live, fresh }) => async (pi) => {
246
246
  // Tokens from finished replies, plus characters streamed in the current one (about 4 a token).
247
247
  let counted = 0;
248
248
  let streamed = 0;
249
+ // Subagents running in the foreground, by tool call; and every subagent's tokens when this run began,
250
+ // so the counter takes in what they've streamed since, background ones included.
251
+ const agents = new Map();
252
+ let agentTokensAtStart = subagentTokensSoFar();
253
+ // Output speed: tokens over the time from each reply's first token to its end.
254
+ let firstDeltaAt;
255
+ let streamMs = 0;
256
+ let streamedOutput = 0;
249
257
  let titleTimer;
250
258
  let moodTimer;
251
259
  let doneTimer;
252
260
  let lastError;
261
+ /** Pi starts the loop again for retries and check-driven continuations; the totals last until it settles. */
262
+ let settled = true;
263
+ const tokensNow = () => counted + Math.round(streamed / 4) + subagentTokensSoFar() - agentTokensAtStart;
264
+ /** One subagent: what it's doing (a retry counting down included). Several: how many and their tool calls so far. */
265
+ const agentsDetail = () => {
266
+ const list = [...agents.values()];
267
+ if (list.length === 1)
268
+ return `agent · ${agentProgress(list[0])}`;
269
+ return `${list.length} agents · ${list.reduce((sum, d) => sum + (d.tools ?? 0), 0)} tools`;
270
+ };
271
+ /** Read on every frame: subagents, background ones too, keep the counter and their line moving between main events. */
272
+ const liveStatus = () => ({ ...status, tokens: tokensNow(), detail: agents.size > 0 ? agentsDetail() : status.detail });
253
273
  pi.on("agent_start", async (_event, ctx) => {
254
- status = { activity: "thinking", startedAt: Date.now(), tokens: 0 };
255
- counted = 0;
256
- streamed = 0;
274
+ if (settled) {
275
+ settled = false;
276
+ status = { activity: "thinking", startedAt: Date.now(), tokens: 0 };
277
+ counted = 0;
278
+ streamed = 0;
279
+ agentTokensAtStart = subagentTokensSoFar();
280
+ streamMs = 0;
281
+ streamedOutput = 0;
282
+ }
283
+ else {
284
+ status = { ...status, activity: "thinking", detail: undefined };
285
+ streamed = 0;
286
+ }
287
+ agents.clear();
288
+ firstDeltaAt = undefined;
257
289
  lastError = undefined;
258
290
  clearTimeout(moodTimer);
259
291
  clearTimeout(doneTimer);
@@ -261,7 +293,7 @@ export const createKluiExtension = ({ config, live, fresh }) => async (pi) => {
261
293
  if (ctx.mode !== "tui")
262
294
  return;
263
295
  ctx.ui.setWorkingVisible(false);
264
- ctx.ui.setWidget(WIDGET, (tui, theme) => createWorkingWidget(tui, theme, () => status, reducedMotion));
296
+ ctx.ui.setWidget(WIDGET, (tui, theme) => createWorkingWidget(tui, theme, liveStatus, reducedMotion));
265
297
  clearInterval(titleTimer);
266
298
  if (reducedMotion) {
267
299
  title("…");
@@ -274,24 +306,72 @@ export const createKluiExtension = ({ config, live, fresh }) => async (pi) => {
274
306
  });
275
307
  pi.on("tool_execution_start", async (event) => {
276
308
  const { activity, detail } = describeTool(event.toolName, event.args);
309
+ if (event.toolName === "subagent" && !event.args?.background) {
310
+ agents.set(event.toolCallId, { tokens: 0, tools: 0, progress: "starting up" });
311
+ status = { ...status, activity, detail: agentsDetail() };
312
+ return;
313
+ }
277
314
  status = { ...status, activity, detail };
278
315
  });
316
+ // A subagent's row updates as it works; the line above the editor follows it, counter included.
317
+ pi.on("tool_execution_update", async (event) => {
318
+ if (event.toolName !== "subagent" || !agents.has(event.toolCallId))
319
+ return;
320
+ const details = event.partialResult?.details;
321
+ if (details)
322
+ agents.set(event.toolCallId, details);
323
+ status = { ...status, activity: "delegating", detail: agentsDetail(), tokens: tokensNow() };
324
+ });
325
+ // Tool calls the model is writing out, by content index (they can interleave), with their arguments so far.
326
+ const preparing = new Map();
327
+ pi.on("message_start", async (event) => {
328
+ if (event.message.role === "assistant")
329
+ firstDeltaAt = undefined;
330
+ });
279
331
  pi.on("message_update", async (event) => {
280
332
  const update = event.assistantMessageEvent;
333
+ if (update.type === "toolcall_start") {
334
+ const content = update.partial.content[update.contentIndex];
335
+ const call = { name: content?.type === "toolCall" ? content.name : "tool", args: "" };
336
+ preparing.set(update.contentIndex, call);
337
+ status = { ...status, activity: call.name === "subagent" ? "delegating" : "writing", detail: preparingLabel(call.name, "") };
338
+ return;
339
+ }
281
340
  if (update.type !== "text_delta" && update.type !== "thinking_delta" && update.type !== "toolcall_delta")
282
341
  return;
342
+ firstDeltaAt ??= Date.now();
283
343
  streamed += update.delta.length;
284
- status = { ...status, tokens: counted + Math.round(streamed / 4) };
344
+ let detail = status.detail;
345
+ const call = update.type === "toolcall_delta" ? preparing.get(update.contentIndex) : undefined;
346
+ if (call) {
347
+ call.args += update.delta;
348
+ detail = preparingLabel(call.name, call.args);
349
+ }
350
+ else if (update.type !== "toolcall_delta" && preparing.size > 0) {
351
+ preparing.clear();
352
+ detail = undefined;
353
+ }
354
+ status = { ...status, detail, tokens: tokensNow() };
285
355
  });
286
356
  pi.on("message_end", async (event) => {
287
357
  if (event.message.role !== "assistant")
288
358
  return;
289
- counted += event.message.usage?.output || Math.round(streamed / 4);
359
+ const tokens = event.message.usage?.output || Math.round(streamed / 4);
360
+ if (firstDeltaAt !== undefined && tokens > 0 && Date.now() > firstDeltaAt) {
361
+ streamMs += Date.now() - firstDeltaAt;
362
+ streamedOutput += tokens;
363
+ }
364
+ counted += tokens;
290
365
  streamed = 0;
291
- status = { ...status, tokens: counted };
366
+ preparing.clear();
367
+ status = { ...status, tokens: tokensNow() };
292
368
  });
293
- pi.on("tool_execution_end", async () => {
294
- status = { ...status, activity: "thinking", detail: undefined };
369
+ pi.on("tool_execution_end", async (event) => {
370
+ agents.delete(event.toolCallId);
371
+ // Other subagents may still be going; until they're done the line keeps following them.
372
+ status = agents.size > 0
373
+ ? { ...status, activity: "delegating", detail: agentsDetail(), tokens: tokensNow() }
374
+ : { ...status, activity: "thinking", detail: undefined, tokens: tokensNow() };
295
375
  });
296
376
  // After the permission prompt's tool_call handler, so a declined edit never waits on a check.
297
377
  registerChecks(pi, (active) => {
@@ -303,6 +383,7 @@ export const createKluiExtension = ({ config, live, fresh }) => async (pi) => {
303
383
  lastError = friendlyError(last.errorMessage);
304
384
  });
305
385
  pi.on("agent_settled", async (event, ctx) => {
386
+ settled = true;
306
387
  clearInterval(titleTimer);
307
388
  title();
308
389
  const happy = !event.aborted && !lastError;
@@ -312,7 +393,8 @@ export const createKluiExtension = ({ config, live, fresh }) => async (pi) => {
312
393
  void refreshCredits(true);
313
394
  if (ctx.mode !== "tui")
314
395
  return;
315
- const outcome = { aborted: event.aborted, error: lastError, startedAt: status.startedAt, tokens: status.tokens };
396
+ const tokensPerSecond = streamMs >= 1000 ? Math.round(streamedOutput / (streamMs / 1000)) : undefined;
397
+ const outcome = { aborted: event.aborted, error: lastError, startedAt: status.startedAt, tokens: tokensNow(), tokensPerSecond };
316
398
  ctx.ui.setWidget(WIDGET, (_tui, theme) => createDoneWidget(theme, outcome));
317
399
  clearTimeout(doneTimer);
318
400
  doneTimer = setTimeout(() => {
@@ -366,7 +448,7 @@ export const createKluiExtension = ({ config, live, fresh }) => async (pi) => {
366
448
  reconnect: async (ctx) => {
367
449
  await connect(true);
368
450
  if (state.connection.kind === "ready") {
369
- ctx.ui.notify("Connected to Klui ✦", "info");
451
+ ctx.ui.notify("Connected to Klui", "info");
370
452
  void refreshCredits(true);
371
453
  }
372
454
  else {
@@ -113,8 +113,8 @@ export function todoPanel(todos, theme, width) {
113
113
  if (t.status === "completed")
114
114
  return [` ${theme.fg("success", "✓")} ${theme.fg("dim", theme.strikethrough(t.content))}`];
115
115
  if (t.status === "in_progress")
116
- return [` ${theme.fg("accent", "◼")} ${theme.bold(t.activeForm || t.content)}`];
117
- return [` ${theme.fg("dim", "◻")} ${t.content}`];
116
+ return [` ${theme.fg("accent", "■")} ${theme.bold(t.activeForm || t.content)}`];
117
+ return [` ${theme.fg("dim", "□")} ${t.content}`];
118
118
  });
119
119
  const hidden = todos.length - keep.size;
120
120
  if (hidden)
@@ -1,9 +1,10 @@
1
- // Tool calls drawn the way Claude Code draws them: "⏺ Update(src/app.ts)" with the outcome under
1
+ // Tool calls drawn the way Claude Code draws them: "● Update(src/app.ts)" with the outcome under
2
2
  // it, "⎿ Updated src/app.ts with 4 additions and 1 removal", and edits shown as a short diff. Click
3
3
  // a row, or press the expand key, to see the call and its output drawn the way Pi normally draws them.
4
4
  import { keyText, renderDiff } from "@earendil-works/pi-coding-agent";
5
5
  import { Box, Container, Text, truncateToWidth } from "@earendil-works/pi-tui";
6
6
  import { isAbsolute, relative } from "node:path";
7
+ import { agentLines, formatTokens } from "./agents.js";
7
8
  import { DECLINED } from "./permissions.js";
8
9
  /** How many diff or output lines a row shows before "… +N lines". */
9
10
  const PREVIEW_DIFF = 12;
@@ -40,7 +41,7 @@ function compactCall(toolName, args, theme, context) {
40
41
  state.kluiHead ??= new Lines();
41
42
  // The dot stays dim until the result colors it.
42
43
  if (!state.kluiBody)
43
- state.kluiHead.set([`${theme.fg("dim", "⏺")} ${title(toolName, args, theme, context.cwd)}`], context.outputPad);
44
+ state.kluiHead.set([`${theme.fg("dim", "●")} ${title(toolName, args, theme, context.cwd)}`], context.outputPad);
44
45
  return state.kluiHead;
45
46
  }
46
47
  function compactResult(toolName, result, theme, context) {
@@ -50,11 +51,12 @@ function compactResult(toolName, result, theme, context) {
50
51
  if (context.isPartial) {
51
52
  // Long-running tools (subagents) say what they're up to under the call.
52
53
  const d = result.details;
53
- state.kluiHead?.set([`${theme.fg("dim", "⏺")} ${head}`], context.outputPad);
54
- state.kluiBody.set(d?.progress ? under(theme, [theme.fg("dim", `${d.progress}${d.tools ? ` · ${plural(d.tools, "tool")}` : ""}`)]) : [], context.outputPad);
54
+ state.kluiHead?.set([`${theme.fg("dim", "●")} ${head}`], context.outputPad);
55
+ const live = toolName === "subagent" && d?.startedAt !== undefined ? agentLines(d, theme) : d?.progress ? [theme.fg("dim", d.progress)] : [];
56
+ state.kluiBody.set(under(theme, live), context.outputPad);
55
57
  return state.kluiBody;
56
58
  }
57
- const dot = context.isError ? theme.fg("error", "⏺") : theme.fg("success", "⏺");
59
+ const dot = context.isError ? theme.fg("error", "●") : theme.fg("success", "●");
58
60
  state.kluiHead?.set([`${dot} ${head}`], context.outputPad);
59
61
  const lines = context.isError ? errorLines(result, theme) : outcome(toolName, context.args, result, theme, context.cwd);
60
62
  const time = context.durationMs !== undefined && context.durationMs >= 1000 ? theme.fg("dim", ` · ${(context.durationMs / 1000).toFixed(1)}s`) : "";
@@ -165,7 +167,9 @@ function outcome(toolName, args, result, theme, cwd) {
165
167
  return [];
166
168
  if (d.background)
167
169
  return [theme.fg("dim", `Working in the background as #${d.background}`)];
168
- return [`Done ${theme.fg("dim", `· ${[plural(d.tools ?? 0, "tool"), d.model].filter(Boolean).join(" · ")}`)}`];
170
+ const tokens = d.tokens ? `↓ ${formatTokens(d.tokens)} tokens` : undefined;
171
+ const speed = d.tokensPerSecond ? `${d.tokensPerSecond} tok/s` : undefined;
172
+ return [`Done ${theme.fg("dim", `· ${[plural(d.tools ?? 0, "tool"), tokens, speed, d.model].filter(Boolean).join(" · ")}`)}`];
169
173
  }
170
174
  default:
171
175
  return lineCount ? [theme.fg("dim", plural(lineCount, "line"))] : [];
@@ -1,10 +1,30 @@
1
1
  // Klui's voice, shared with the web app's thinking bar and home greeting (public/js/klui.js).
2
2
  export const PHRASES = {
3
- thinking: ["locking in", "connecting the dots", "big brain time", "cooking something up", "thinking it through"],
4
- reading: ["taking notes", "highlighting the good bits", "skimming the code", "reading the room"],
5
- searching: ["hunting it down", "digging around", "following the trail", "sifting results"],
6
- running: ["running it", "pressing buttons", "watching the logs", "crossing fingers"],
7
- writing: ["making edits", "writing the code", "finding the words", "polishing pixels"],
3
+ thinking: [
4
+ "locking in",
5
+ "connecting the dots",
6
+ "big brain time",
7
+ "cooking something up",
8
+ "thinking it through",
9
+ "flabbergasting",
10
+ "percolating",
11
+ "noodling on it",
12
+ "galaxy-braining",
13
+ "scheming",
14
+ "simmering",
15
+ "marinating",
16
+ "vibing it out",
17
+ "conjuring",
18
+ "cogitating",
19
+ "brewing ideas",
20
+ "pondering the orb",
21
+ "doing the math",
22
+ ],
23
+ reading: ["taking notes", "highlighting the good bits", "skimming the code", "reading the room", "speed reading", "absorbing the lore", "peeking inside", "nose in the docs"],
24
+ searching: ["hunting it down", "digging around", "following the trail", "sifting results", "rummaging", "spelunking", "on the case", "sniffing it out", "treasure hunting"],
25
+ running: ["running it", "pressing buttons", "watching the logs", "crossing fingers", "taking it for a spin", "kicking the tires", "hold onto your hat", "letting it rip"],
26
+ writing: ["making edits", "writing the code", "finding the words", "polishing pixels", "finagling", "tinkering", "sprinkling magic", "bamboozling the bugs", "shipping bits"],
27
+ delegating: ["rallying the crew", "teamwork mode", "the helpers are on it", "divide and conquer", "assembling the squad", "minions deployed", "calling in backup"],
8
28
  };
9
29
  export const GREETINGS = [
10
30
  "what are we building?",
@@ -16,7 +36,7 @@ export const GREETINGS = [
16
36
  "got an idea? let's ship it",
17
37
  "hackathon mode: on",
18
38
  ];
19
- export const DONE_LINES = ["done!", "shipped it", "all yours", "ta-da", "nailed it", "that's a wrap"];
39
+ export const DONE_LINES = ["done!", "shipped it", "all yours", "ta-da", "nailed it", "that's a wrap", "voilà", "chef's kiss", "easy peasy", "and scene", "bam!", "mission accomplished"];
20
40
  export function pick(items, avoid) {
21
41
  if (items.length < 2)
22
42
  return items[0];
@@ -47,12 +67,37 @@ export function describeTool(toolName, args) {
47
67
  case "todo":
48
68
  return { activity: "thinking", detail: "updating the plan" };
49
69
  case "subagent":
50
- return { activity: "searching", detail: `a subagent is ${args?.kind === "general" ? "on it" : "exploring"}` };
70
+ return { activity: "delegating", detail: `a subagent is ${args?.kind === "general" ? "on it" : "exploring"}` };
51
71
  default:
52
72
  return { activity: "thinking", detail: `using ${toolName}` };
53
73
  }
54
74
  }
55
- function shortPath(path) {
75
+ /**
76
+ * What Klui says while the model is still writing out a tool call, before it runs: a big write can
77
+ * stream for minutes. `args` is the JSON so far; the path or command shows up as soon as it's in.
78
+ */
79
+ export function preparingLabel(toolName, args) {
80
+ const field = (name) => {
81
+ const raw = new RegExp(`"${name}"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)`).exec(args)?.[1];
82
+ return raw?.replace(/\\n/g, "\n").replace(/\\(.)/g, "$1");
83
+ };
84
+ const path = field("path") ?? field("file_path");
85
+ switch (toolName) {
86
+ case "write":
87
+ return path ? `drafting ${shortPath(path)}` : "drafting a file";
88
+ case "edit":
89
+ return path ? `drafting an edit to ${shortPath(path)}` : "drafting an edit";
90
+ case "bash": {
91
+ const command = field("command")?.split("\n")[0]?.trim();
92
+ return command ? `drafting $ ${clip(command, 36)}` : "drafting a command";
93
+ }
94
+ case "subagent":
95
+ return "briefing a subagent";
96
+ default:
97
+ return `getting ${toolName} ready`;
98
+ }
99
+ }
100
+ export function shortPath(path) {
56
101
  const parts = path.split("/").filter(Boolean);
57
102
  return parts.length > 2 ? `…/${parts.slice(-2).join("/")}` : path;
58
103
  }
@@ -3,7 +3,7 @@
3
3
  // Exa's public MCP endpoint and falls back to DuckDuckGo's HTML page.
4
4
  import { Type } from "typebox";
5
5
  const TIMEOUT_MS = 20_000;
6
- const MAX_PAGE_CHARS = 30_000;
6
+ const MAX_PAGE_BYTES = 10 * 1024 * 1024;
7
7
  /** When these tools can't get through, the model can still reach the web from the shell. */
8
8
  const USE_CURL = "Fall back to curl in bash (for search: https://html.duckduckgo.com/html/?q=...).";
9
9
  export function registerWeb(pi) {
@@ -28,7 +28,7 @@ export function registerWeb(pi) {
28
28
  pi.registerTool({
29
29
  name: "web_fetch",
30
30
  label: "Web fetch",
31
- description: `Fetch a URL and return its text (pages are reduced to plain text, cut at ${MAX_PAGE_CHARS} characters).`,
31
+ description: "Fetch a URL and return its full text (HTML is reduced to plain text; downloads over 10 MiB are rejected).",
32
32
  promptSnippet: "web_fetch: read a web page or other URL as text",
33
33
  parameters: Type.Object({
34
34
  url: Type.String({ description: "The http(s) URL to fetch" }),
@@ -42,11 +42,18 @@ export function registerWeb(pi) {
42
42
  });
43
43
  if (!response.ok)
44
44
  throw new Error(`${params.url} answered ${response.status}. ${USE_CURL}`);
45
- const body = await response.text();
45
+ const chunks = [];
46
+ let size = 0;
47
+ for await (const chunk of response.body ?? []) {
48
+ size += chunk.byteLength;
49
+ if (size > MAX_PAGE_BYTES)
50
+ throw new Error(`${params.url} exceeds the 10 MiB download limit. Fetch a smaller page or section.`);
51
+ chunks.push(chunk);
52
+ }
53
+ const body = new TextDecoder().decode(Buffer.concat(chunks));
46
54
  const html = /html/i.test(response.headers.get("content-type") ?? "");
47
55
  const text = (html ? htmlToText(body) : body).trim();
48
- const cut = text.length > MAX_PAGE_CHARS ? `${text.slice(0, MAX_PAGE_CHARS)}\n\n[cut at ${MAX_PAGE_CHARS} characters]` : text;
49
- return { content: [{ type: "text", text: cut || "(empty page)" }], details: { chars: text.length } };
56
+ return { content: [{ type: "text", text: text || "(empty page)" }], details: { chars: text.length } };
50
57
  },
51
58
  });
52
59
  }
@@ -1,8 +1,10 @@
1
- // While the agent works, one small box sits above the editor, like Claude Code's: a shimmering
2
- // phrase, then the time and tokens so far. When the run ends it says so for a moment.
1
+ // While the agent works, a tiny one-row Klui sits above the editor and acts out what it's doing
2
+ // (looking around while it reads, typing while it writes, hopping while a command runs, waving
3
+ // while subagents work), next to a shimmering phrase and the time and tokens so far. When the run
4
+ // ends it cheers for a moment, with how fast the replies streamed.
3
5
  import { keyText } from "@earendil-works/pi-coding-agent";
4
- import { backgroundAnsi, foregroundAnsi, parseColor, truncateToWidth } from "@earendil-works/pi-tui";
5
- import { KLUI } from "../mascot.js";
6
+ import { foregroundAnsi, parseColor, truncateToWidth } from "@earendil-works/pi-tui";
7
+ import { KLUI, tinyKlui } from "../mascot.js";
6
8
  import { mixHex } from "../pixels.js";
7
9
  import { DONE_LINES, PHRASES, pick } from "./voice.js";
8
10
  const FRAME_MS = 50;
@@ -10,6 +12,7 @@ const PHRASE_MS = 3600;
10
12
  /** The animated working line. `status()` is read on every frame. */
11
13
  export function createWorkingWidget(tui, theme, status, reducedMotion) {
12
14
  let frame = 0;
15
+ const bornAt = Date.now();
13
16
  let activity = status().activity;
14
17
  let phrase = pick(PHRASES[activity]);
15
18
  let phraseAt = Date.now();
@@ -28,14 +31,16 @@ export function createWorkingWidget(tui, theme, status, reducedMotion) {
28
31
  return {
29
32
  render(width) {
30
33
  const current = status();
34
+ const now = Date.now();
35
+ const t = reducedMotion ? 0 : now - bornAt;
31
36
  const title = reducedMotion ? theme.fg("accent", `${phrase}…`) : shimmer(`${phrase}…`, frame, theme);
32
37
  const meta = [
33
38
  current.detail,
34
- formatElapsed(Date.now() - current.startedAt),
39
+ formatElapsed(now - current.startedAt),
35
40
  current.tokens > 0 ? `↓ ${formatTokens(current.tokens)} tokens` : undefined,
36
41
  `${keyText("app.interrupt")} to stop`,
37
42
  ].filter(Boolean);
38
- return line(title, meta.join(" · "), theme, width);
43
+ return rows(workingPose(current.activity, t), title, meta.join(" · "), theme, width);
39
44
  },
40
45
  invalidate() { },
41
46
  dispose() {
@@ -48,25 +53,52 @@ export function createDoneWidget(theme, outcome) {
48
53
  const happy = !outcome.aborted && !outcome.error;
49
54
  const said = happy ? pick(DONE_LINES) : outcome.aborted ? "stopped" : "hit a snag";
50
55
  const title = happy ? theme.bold(theme.fg("accent", said)) : theme.fg(outcome.aborted ? "muted" : "error", said);
56
+ const pose = happy
57
+ ? { eyes: "happy", arms: "up", step: false }
58
+ : { eyes: "left", arms: "down", step: false }; // a sheepish glance away
51
59
  const meta = [
52
60
  formatElapsed(Date.now() - outcome.startedAt),
53
61
  outcome.tokens > 0 ? `↓ ${formatTokens(outcome.tokens)} tokens` : undefined,
62
+ outcome.tokensPerSecond ? `${outcome.tokensPerSecond} tok/s` : undefined,
54
63
  outcome.error,
55
64
  ].filter(Boolean);
56
65
  return {
57
- render: (width) => line(title, meta.join(" · "), theme, width),
66
+ render: (width) => rows(pose, title, meta.join(" · "), theme, width),
58
67
  invalidate() { },
59
68
  };
60
69
  }
61
- function line(title, meta, theme, width) {
62
- return [truncateToWidth(` ${box(title, meta, theme)}`, width)];
70
+ /** One row: Klui, the phrase, then the numbers dimmed. */
71
+ function rows(pose, title, meta, theme, width) {
72
+ const dim = foregroundAnsi(parseColor(theme.appearance === "light" ? "#56637f" : "#7f93b2"), theme.getColorMode());
73
+ return [truncateToWidth(` ${tinyKlui(pose, theme.getColorMode())} ${title} ${dim}${meta}\x1b[39m`, width)];
63
74
  }
64
- /** The phrase and the numbers on a soft blue background. Every color inside resets only the foreground. */
65
- function box(title, meta, theme) {
66
- const light = theme.appearance === "light";
67
- const bg = backgroundAnsi(parseColor(light ? "#d6e9fb" : "#1b2b45"), theme.getColorMode());
68
- const dim = foregroundAnsi(parseColor(light ? "#56637f" : "#7f93b2"), theme.getColorMode());
69
- return `${bg} ${title} ${dim}${meta} \x1b[39m\x1b[49m`;
75
+ /** What Klui does while it works: it blinks now and then, and acts out the activity. */
76
+ export function workingPose(activity, t) {
77
+ const blink = t % 3400 > 3240;
78
+ const pose = { eyes: blink ? "shut" : "open", arms: "down", step: false };
79
+ const beat = (ms) => Math.floor(t / ms) % 2 === 1;
80
+ switch (activity) {
81
+ case "reading":
82
+ case "searching":
83
+ if (!blink)
84
+ pose.eyes = beat(900) ? "left" : "right";
85
+ break;
86
+ case "writing":
87
+ pose.arms = beat(180) ? "left" : "right";
88
+ break;
89
+ case "running":
90
+ pose.step = beat(220);
91
+ break;
92
+ case "delegating":
93
+ pose.arms = beat(350) ? "right" : "down";
94
+ break;
95
+ case "thinking":
96
+ // Every so often it glances aside, mulling it over.
97
+ if (!blink && t % 5200 > 4200)
98
+ pose.eyes = "left";
99
+ break;
100
+ }
101
+ return pose;
70
102
  }
71
103
  /** A bright band sweeping across the text, sky blue to white. Plain accent on 256-color terminals. */
72
104
  function shimmer(text, frame, theme) {
package/dist/fallback.js CHANGED
@@ -11,6 +11,20 @@ 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
30
  /** Paid peers tried per request: each failure can cost a timeout, and paid peers rarely all fail. */
@@ -29,6 +43,28 @@ export function serviceOf(id) {
29
43
  const at = id.indexOf("@");
30
44
  return at === -1 ? id : id.slice(at + 1);
31
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
+ }
32
68
  /** What a typical turn costs on this offer, in USD per million tokens. */
33
69
  export function turnPrice(offer) {
34
70
  const { inputUsdPerMillion: input, outputUsdPerMillion: output } = offer;
@@ -42,7 +78,8 @@ export function turnPrice(offer) {
42
78
  * Peers serving the model under any of `names` over chat completions, as pinned gateway ids, best
43
79
  * first. A peer's score is 75% price (cheapest 1, dearest 0, on a log scale since prices span
44
80
  * 1000x) and 25% reputation. Free peers always come first. `freeOnly` keeps just those peers;
45
- * 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.
46
83
  */
47
84
  export function rankOffers(models, names, freeOnly = false, needsImages = false) {
48
85
  const wanted = new Set(names.map((n) => n.toLowerCase()));
@@ -52,23 +89,27 @@ export function rankOffers(models, names, freeOnly = false, needsImages = false)
52
89
  for (const offer of model.peers ?? []) {
53
90
  if (!listed && !wanted.has(offer.serviceId.toLowerCase()))
54
91
  continue;
55
- if (needsImages && !offer.capabilities?.inputs?.includes("image"))
92
+ const tested = needsImages && !!VISION_TESTED[offer.peerId]?.some((n) => wanted.has(n));
93
+ if (needsImages && !tested && !offer.capabilities?.inputs?.includes("image"))
56
94
  continue;
57
95
  const price = turnPrice(offer);
58
96
  const chat = !offer.protocols || offer.protocols.includes("openai-chat-completions");
59
97
  if (price === undefined || !chat || (freeOnly && price !== 0))
60
98
  continue;
61
99
  const reputation = offer.effectiveReputationScore ?? offer.reputationScore ?? 0;
62
- if (price !== 0 && reputation < MIN_REPUTATION)
100
+ if (price !== 0 && reputation < MIN_REPUTATION && !tested)
63
101
  continue;
64
102
  const existing = offers.get(offer.peerId);
65
103
  if (existing && existing.price <= price)
66
104
  continue;
67
- 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 });
68
106
  }
69
107
  }
70
108
  const all = [...offers.values()];
71
- // Price/reputation orders each group; a free offer always wins over a paid one.
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) {
72
113
  const logs = all.map((o) => Math.log(o.price + 1e-4));
73
114
  const lo = Math.min(...logs);
74
115
  const hi = Math.max(...logs);
@@ -155,7 +196,7 @@ export function createFallback(getConfig, getApiKey, connect = async () => undef
155
196
  if (needsImages && !next)
156
197
  throw new Error(`No vision provider is available for ${model.name} right now. Try again or pick another vision model with /model.`);
157
198
  let firstError;
158
- let outOfCredits = false;
199
+ const broke = [];
159
200
  const answerTimeout = answerTimeoutMs(context);
160
201
  while (next) {
161
202
  tried.add(next);
@@ -164,7 +205,7 @@ export function createFallback(getConfig, getApiKey, connect = async () => undef
164
205
  const silent = new AbortController();
165
206
  const timer = setTimeout(() => silent.abort(), answerTimeout);
166
207
  const signal = options?.signal ? AbortSignal.any([options.signal, silent.signal]) : silent.signal;
167
- const events = base().streamSimple({ ...model, id: attempt }, context, { ...options, signal });
208
+ const events = base().streamSimple({ ...model, id: attempt }, asSeller(context, attempt), { ...options, signal });
168
209
  let started = false;
169
210
  try {
170
211
  for await (const event of events) {
@@ -175,9 +216,12 @@ export function createFallback(getConfig, getApiKey, connect = async () => undef
175
216
  cooling.set(attempt, Date.now() + COOLDOWN_MS);
176
217
  if (working.get(model.id) === attempt)
177
218
  working.delete(model.id);
178
- // A paid 402 means the wallet itself is empty, so every peer would say the same.
179
- outOfCredits = paid && /^\s*402\b/.test(event.error.errorMessage ?? "");
180
- if (!outOfCredits && !(paid && tried.size >= MAX_PAID_TRIES))
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))
181
225
  next = await nextPeer();
182
226
  break;
183
227
  }
@@ -187,7 +231,7 @@ export function createFallback(getConfig, getApiKey, connect = async () => undef
187
231
  if (!paid && attempt !== model.id)
188
232
  working.set(model.id, attempt);
189
233
  }
190
- out.push(event);
234
+ out.push(sellerAside(event, model.id));
191
235
  }
192
236
  }
193
237
  finally {
@@ -199,12 +243,13 @@ export function createFallback(getConfig, getApiKey, connect = async () => undef
199
243
  // Every peer refused. The gateway's own message (a 402 asking to deposit funds, or a
200
244
  // peer hash) means nothing to an attendee, so say what happened instead.
201
245
  if (firstError?.type === "error") {
246
+ const outOfCredits = broke.length > 0 && broke.every(Boolean);
202
247
  const errorMessage = outOfCredits
203
248
  ? `Klui is out of credits for ${model.name}. Pick a free model with /model.`
204
249
  : paid
205
250
  ? `No provider is answering for ${model.name} right now. Try again, or pick another model with /model.`
206
251
  : `No free provider is serving ${model.name} right now. Pick another model with /model.`;
207
- out.push({ ...firstError, error: { ...firstError.error, errorMessage } });
252
+ out.push(sellerAside({ ...firstError, error: { ...firstError.error, errorMessage } }, model.id));
208
253
  }
209
254
  out.end();
210
255
  })().catch((error) => {