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.
@@ -86,7 +86,7 @@ export function registerChecks(pi, onChecking = () => { }) {
86
86
  const shown = options.expanded ? d.lines : d.lines.slice(0, PREVIEW);
87
87
  const hidden = total - shown.length;
88
88
  const rows = [
89
- `${pad}${theme.fg("warning", "⏺")} ${theme.bold("Checks")}`,
89
+ `${pad}${theme.fg("warning", "●")} ${theme.bold("Checks")}`,
90
90
  `${pad} ${theme.fg("dim", "⎿")} ${total} problem${total === 1 ? "" : "s"} to fix`,
91
91
  ...shown.map((l) => `${pad} ${theme.fg("muted", l)}`),
92
92
  ...(hidden ? [`${pad} ${theme.fg("dim", `… +${hidden} more`)}`] : []),
@@ -53,7 +53,7 @@ export function registerCommands(pi, actions) {
53
53
  },
54
54
  });
55
55
  pi.registerCommand("usage", {
56
- description: "Tokens used in the last 24 hours and overall, subagents included",
56
+ description: "Tokens and model requests in the last 24 hours and overall, subagents included",
57
57
  handler: async (_args, ctx) => {
58
58
  ctx.ui.notify(usageReport(readUsage()), "info");
59
59
  },
@@ -164,13 +164,13 @@ function aboutCard(theme, done) {
164
164
  invalidate() { },
165
165
  };
166
166
  }
167
- /** Three rows: the header, total tokens (736.8K) and messages, last 24 hours next to lifetime. */
167
+ /** Three rows: the header, total tokens (736.8K) and requests, last 24 hours next to lifetime. */
168
168
  export function usageReport({ day, lifetime }) {
169
169
  const line = (label, a, b) => `${label.padEnd(14)}${a.padStart(10)} ${b.padStart(10)}`;
170
170
  return [
171
171
  line("Usage", "Last 24h", "Lifetime"),
172
172
  line("Total tokens", compact(day.total), compact(lifetime.total)),
173
- line("Messages", day.requests.toLocaleString("en-US"), lifetime.requests.toLocaleString("en-US")),
173
+ line("Requests", day.requests.toLocaleString("en-US"), lifetime.requests.toLocaleString("en-US")),
174
174
  ].join("\n");
175
175
  }
176
176
  /** 950, 736.8K, 1.2M, 3.4B: one decimal at most. */
@@ -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) {