klui-code 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,179 @@
1
+ // A screenshot tool, so the model can look at the page it built instead of setting up a browser
2
+ // itself. It finds the Chrome, Edge, Brave or Chromium already installed, runs it headless with a
3
+ // throwaway profile, and drives it over the DevTools protocol: the viewport is exactly the size asked
4
+ // for (a 390px phone really lays out at 390px, which the --window-size flag doesn't promise), and the
5
+ // page's console errors come back with the picture. An optional script runs in the page first, to
6
+ // click, type or scroll, and whatever it returns comes back too.
7
+ import { spawn } from "node:child_process";
8
+ import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
9
+ import { tmpdir } from "node:os";
10
+ import { delimiter, join, resolve } from "node:path";
11
+ import { pathToFileURL } from "node:url";
12
+ import { Type } from "typebox";
13
+ const TIMEOUT_MS = 30_000;
14
+ /** Set to a Chromium-based browser's executable to use that one. */
15
+ const BROWSER_ENV = "KLUI_BROWSER";
16
+ const MAC_APPS = ["Google Chrome", "Chromium", "Microsoft Edge", "Brave Browser"];
17
+ const LINUX_NAMES = ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "microsoft-edge", "brave-browser"];
18
+ const WINDOWS_PATHS = ["Google\\Chrome\\Application\\chrome.exe", "Microsoft\\Edge\\Application\\msedge.exe", "BraveSoftware\\Brave-Browser\\Application\\brave.exe"];
19
+ export function registerBrowser(pi) {
20
+ pi.registerTool({
21
+ name: "screenshot",
22
+ label: "Screenshot",
23
+ description: [
24
+ "Open a page in a headless browser at an exact viewport size and see it as an image, with the page's console errors.",
25
+ "Use it to check web pages you build: a local file path or an http(s) URL (start the dev server first).",
26
+ "For a phone, use width 390 and height 844. script runs in the page before the picture (click, fill a form, scroll) and its return value comes back,",
27
+ "so check behavior by returning what changed, not by finding text that may already be in the page.",
28
+ ].join(" "),
29
+ promptSnippet: "screenshot: see a web page at an exact viewport size, run a script in it, get its console errors",
30
+ parameters: Type.Object({
31
+ url: Type.String({ description: "An http(s) URL, or a path to a local HTML file" }),
32
+ width: Type.Optional(Type.Number({ description: "Viewport width in CSS pixels (default 1280)" })),
33
+ height: Type.Optional(Type.Number({ description: "Viewport height in CSS pixels (default 800)" })),
34
+ script: Type.Optional(Type.String({ description: "JavaScript run in the page after it loads, before the picture; may be async. Its return value comes back as JSON" })),
35
+ }),
36
+ executionMode: "parallel",
37
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
38
+ const url = pageUrl(params.url, ctx.cwd);
39
+ const width = Math.round(params.width ?? 1280);
40
+ const height = Math.round(params.height ?? 800);
41
+ const shot = await screenshot(url, width, height, params.script, signal);
42
+ const lines = [`${width}×${height} screenshot of ${params.url}`];
43
+ if (params.script)
44
+ lines.push(`Script returned: ${shot.returned}`);
45
+ lines.push(shot.errors.length ? `Console errors:\n${shot.errors.join("\n")}` : "No console errors.");
46
+ return {
47
+ content: [
48
+ { type: "text", text: lines.join("\n") },
49
+ { type: "image", data: shot.png, mimeType: "image/png" },
50
+ ],
51
+ details: { width, height, errors: shot.errors.length },
52
+ };
53
+ },
54
+ });
55
+ }
56
+ /** The page to open: a web or file URL as given, anything else a local path (C:\site\index.html included). */
57
+ export function pageUrl(input, cwd) {
58
+ return /^(https?|file):/i.test(input) ? input : pathToFileURL(resolve(cwd, input)).href;
59
+ }
60
+ /** The installed Chromium-based browser to drive, if there is one. */
61
+ export function findBrowser(env = process.env, platform = process.platform) {
62
+ const candidates = [env[BROWSER_ENV]];
63
+ if (platform === "darwin")
64
+ candidates.push(...MAC_APPS.map((app) => `/Applications/${app}.app/Contents/MacOS/${app}`));
65
+ else if (platform === "win32") {
66
+ for (const root of [env.PROGRAMFILES, env["PROGRAMFILES(X86)"], env.LOCALAPPDATA])
67
+ if (root)
68
+ candidates.push(...WINDOWS_PATHS.map((p) => join(root, p)));
69
+ }
70
+ else
71
+ for (const dir of (env.PATH ?? "").split(delimiter))
72
+ if (dir)
73
+ candidates.push(...LINUX_NAMES.map((name) => join(dir, name)));
74
+ return candidates.find((path) => path && existsSync(path));
75
+ }
76
+ async function screenshot(url, width, height, script, signal) {
77
+ const executable = findBrowser();
78
+ if (!executable)
79
+ throw new Error(`No Chrome, Edge, Brave or Chromium found. Install one, or set ${BROWSER_ENV} to a Chromium-based browser's path.`);
80
+ const profile = mkdtempSync(join(tmpdir(), "klui-browser-"));
81
+ const args = ["--headless=new", "--no-first-run", "--no-default-browser-check", "--hide-scrollbars", "--mute-audio", `--user-data-dir=${profile}`, "--remote-debugging-port=0", "about:blank"];
82
+ // Chromium refuses to run as root (say, in a container) with its sandbox on.
83
+ if (process.getuid?.() === 0)
84
+ args.unshift("--no-sandbox");
85
+ const browser = spawn(executable, args, { stdio: "ignore" });
86
+ const over = new AbortController();
87
+ const done = AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS), over.signal, ...(signal ? [signal] : [])]);
88
+ let socket;
89
+ try {
90
+ return await Promise.race([drive(), failed(browser, done)]);
91
+ }
92
+ finally {
93
+ over.abort();
94
+ socket?.close();
95
+ browser.kill();
96
+ // The browser may hold its profile a moment after exiting (always, on Windows).
97
+ setTimeout(() => rmSync(profile, { recursive: true, force: true, maxRetries: 5 }), 1000).unref();
98
+ }
99
+ async function drive() {
100
+ socket = new WebSocket(await pageSocket(profile, done));
101
+ const cdp = devtools(socket);
102
+ await cdp.opened;
103
+ const errors = [];
104
+ cdp.on("Runtime.consoleAPICalled", (p) => {
105
+ if (p.type === "error")
106
+ errors.push((p.args ?? []).map((a) => a.description ?? String(a.value)).join(" "));
107
+ });
108
+ cdp.on("Runtime.exceptionThrown", (p) => errors.push(p.exceptionDetails?.exception?.description ?? p.exceptionDetails?.text ?? "Uncaught exception"));
109
+ await cdp.send("Page.enable");
110
+ await cdp.send("Runtime.enable");
111
+ await cdp.send("Emulation.setDeviceMetricsOverride", { width, height, deviceScaleFactor: 1, mobile: false });
112
+ const loaded = cdp.next("Page.loadEventFired");
113
+ const nav = await cdp.send("Page.navigate", { url });
114
+ if (nav.errorText)
115
+ throw new Error(`Couldn't open ${url}: ${nav.errorText}`);
116
+ await loaded;
117
+ let returned;
118
+ if (script) {
119
+ const result = await cdp.send("Runtime.evaluate", { expression: `(async () => { ${script}\n})()`, awaitPromise: true, returnByValue: true });
120
+ returned = result.exceptionDetails
121
+ ? `error: ${result.exceptionDetails.exception?.description ?? result.exceptionDetails.text}`
122
+ : (JSON.stringify(result.result?.value) ?? "undefined");
123
+ }
124
+ // A moment for fonts, transitions and whatever the script set off.
125
+ await new Promise((r) => setTimeout(r, 300));
126
+ const { data } = await cdp.send("Page.captureScreenshot", { format: "png" });
127
+ return { png: data, returned, errors: errors.slice(0, 20) };
128
+ }
129
+ }
130
+ /** Rejects when the browser exits first, or time runs out. */
131
+ function failed(browser, done) {
132
+ return new Promise((_, reject) => {
133
+ browser.once("error", (e) => reject(new Error(`Couldn't start the browser: ${e.message}`)));
134
+ browser.once("exit", () => reject(new Error("The browser closed before the page loaded.")));
135
+ done.addEventListener("abort", () => reject(new Error(done.reason?.name === "TimeoutError" ? `The page took over ${TIMEOUT_MS / 1000}s.` : "Stopped.")), { once: true });
136
+ });
137
+ }
138
+ /** The page's DevTools socket, once the browser writes its port to the profile. */
139
+ async function pageSocket(profile, done) {
140
+ while (!done.aborted) {
141
+ try {
142
+ const port = readFileSync(join(profile, "DevToolsActivePort"), "utf8").split("\n")[0];
143
+ const targets = (await (await fetch(`http://127.0.0.1:${port}/json/list`, { signal: done })).json());
144
+ const page = targets.find((t) => t.type === "page");
145
+ if (page)
146
+ return page.webSocketDebuggerUrl;
147
+ }
148
+ catch { }
149
+ await new Promise((r) => setTimeout(r, 100));
150
+ }
151
+ throw new Error("aborted");
152
+ }
153
+ /** Just enough of a DevTools protocol client: commands, and events by name. */
154
+ function devtools(socket) {
155
+ let id = 0;
156
+ const pending = new Map();
157
+ const listeners = new Map();
158
+ socket.onmessage = (message) => {
159
+ const data = JSON.parse(String(message.data));
160
+ if (data.id === undefined)
161
+ return listeners.get(data.method)?.forEach((listener) => listener(data.params));
162
+ const call = pending.get(data.id);
163
+ pending.delete(data.id);
164
+ if (data.error)
165
+ call?.reject(new Error(data.error.message));
166
+ else
167
+ call?.resolve(data.result);
168
+ };
169
+ const on = (method, listener) => listeners.set(method, [...(listeners.get(method) ?? []), listener]);
170
+ return {
171
+ opened: new Promise((r) => (socket.onopen = r)),
172
+ on,
173
+ next: (method) => new Promise((r) => on(method, r)),
174
+ send: (method, params = {}) => new Promise((resolve, reject) => {
175
+ pending.set(++id, { resolve, reject });
176
+ socket.send(JSON.stringify({ id, method, params }));
177
+ }),
178
+ };
179
+ }
@@ -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,8 @@ 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
+ import { registerBrowser } from "./browser.js";
13
14
  import { registerChecks } from "./checks.js";
14
15
  import { registerCommands } from "./commands.js";
15
16
  import { createFooter } from "./footer.js";
@@ -18,7 +19,7 @@ import { initialMode, registerPermissions } from "./permissions.js";
18
19
  import { initState, modelLabel, state, update } from "./state.js";
19
20
  import { registerTodos } from "./todos.js";
20
21
  import { registerCompactTools } from "./tools.js";
21
- import { describeTool } from "./voice.js";
22
+ import { describeTool, preparingLabel } from "./voice.js";
22
23
  import { registerWeb } from "./web.js";
23
24
  import { createDoneWidget, createWorkingWidget } from "./working.js";
24
25
  const WIDGET = "klui-working";
@@ -82,7 +83,7 @@ export const createKluiExtension = ({ config, live, fresh }) => async (pi) => {
82
83
  // instead of Pi asking the attendee to /login somewhere.
83
84
  apiKey: usableKey() ?? "klui-no-key",
84
85
  models: toProviderModels(state.config),
85
- streamSimple: recordUsage(fallback.streamSimple),
86
+ streamSimple: recordUsage(fallback.streamSimple, process.env[SUBAGENT_ENV] === "1" ? "subagent" : "main"),
86
87
  });
87
88
  };
88
89
  // Without a key, Klui keeps asking Klui Pass in the background, soon at first and then about
@@ -207,7 +208,7 @@ export const createKluiExtension = ({ config, live, fresh }) => async (pi) => {
207
208
  ctx.ui.setFooter((tui, theme, footerData) => createFooter(pi, ctx, tui, theme, footerData));
208
209
  // Klui's typing widget replaces Pi's one-line "Working..." loader.
209
210
  ctx.ui.setWorkingVisible(false);
210
- ctx.ui.setHiddenThinkingLabel(`✦ reasoning · ${keyText("app.thinking.toggle")} to show`);
211
+ ctx.ui.setHiddenThinkingLabel(`reasoning · ${keyText("app.thinking.toggle")} to show`);
211
212
  title();
212
213
  void refreshCredits(true);
213
214
  if (state.connection.kind === "closed")
@@ -237,6 +238,7 @@ export const createKluiExtension = ({ config, live, fresh }) => async (pi) => {
237
238
  });
238
239
  registerCompactTools(pi);
239
240
  registerWeb(pi);
241
+ registerBrowser(pi);
240
242
  registerPermissions(pi, process.env[SUBAGENT_ENV] === "1");
241
243
  if (process.env[SUBAGENT_ENV] !== "1")
242
244
  registerAgents(pi);
@@ -246,14 +248,46 @@ export const createKluiExtension = ({ config, live, fresh }) => async (pi) => {
246
248
  // Tokens from finished replies, plus characters streamed in the current one (about 4 a token).
247
249
  let counted = 0;
248
250
  let streamed = 0;
251
+ // Subagents running in the foreground, by tool call; and every subagent's tokens when this run began,
252
+ // so the counter takes in what they've streamed since, background ones included.
253
+ const agents = new Map();
254
+ let agentTokensAtStart = subagentTokensSoFar();
255
+ // Output speed: tokens over the time from each reply's first token to its end.
256
+ let firstDeltaAt;
257
+ let streamMs = 0;
258
+ let streamedOutput = 0;
249
259
  let titleTimer;
250
260
  let moodTimer;
251
261
  let doneTimer;
252
262
  let lastError;
263
+ /** Pi starts the loop again for retries and check-driven continuations; the totals last until it settles. */
264
+ let settled = true;
265
+ const tokensNow = () => counted + Math.round(streamed / 4) + subagentTokensSoFar() - agentTokensAtStart;
266
+ /** One subagent: what it's doing (a retry counting down included). Several: how many and their tool calls so far. */
267
+ const agentsDetail = () => {
268
+ const list = [...agents.values()];
269
+ if (list.length === 1)
270
+ return `agent · ${agentProgress(list[0])}`;
271
+ return `${list.length} agents · ${list.reduce((sum, d) => sum + (d.tools ?? 0), 0)} tools`;
272
+ };
273
+ /** Read on every frame: subagents, background ones too, keep the counter and their line moving between main events. */
274
+ const liveStatus = () => ({ ...status, tokens: tokensNow(), detail: agents.size > 0 ? agentsDetail() : status.detail });
253
275
  pi.on("agent_start", async (_event, ctx) => {
254
- status = { activity: "thinking", startedAt: Date.now(), tokens: 0 };
255
- counted = 0;
256
- streamed = 0;
276
+ if (settled) {
277
+ settled = false;
278
+ status = { activity: "thinking", startedAt: Date.now(), tokens: 0 };
279
+ counted = 0;
280
+ streamed = 0;
281
+ agentTokensAtStart = subagentTokensSoFar();
282
+ streamMs = 0;
283
+ streamedOutput = 0;
284
+ }
285
+ else {
286
+ status = { ...status, activity: "thinking", detail: undefined };
287
+ streamed = 0;
288
+ }
289
+ agents.clear();
290
+ firstDeltaAt = undefined;
257
291
  lastError = undefined;
258
292
  clearTimeout(moodTimer);
259
293
  clearTimeout(doneTimer);
@@ -261,7 +295,7 @@ export const createKluiExtension = ({ config, live, fresh }) => async (pi) => {
261
295
  if (ctx.mode !== "tui")
262
296
  return;
263
297
  ctx.ui.setWorkingVisible(false);
264
- ctx.ui.setWidget(WIDGET, (tui, theme) => createWorkingWidget(tui, theme, () => status, reducedMotion));
298
+ ctx.ui.setWidget(WIDGET, (tui, theme) => createWorkingWidget(tui, theme, liveStatus, reducedMotion));
265
299
  clearInterval(titleTimer);
266
300
  if (reducedMotion) {
267
301
  title("…");
@@ -274,24 +308,72 @@ export const createKluiExtension = ({ config, live, fresh }) => async (pi) => {
274
308
  });
275
309
  pi.on("tool_execution_start", async (event) => {
276
310
  const { activity, detail } = describeTool(event.toolName, event.args);
311
+ if (event.toolName === "subagent" && !event.args?.background) {
312
+ agents.set(event.toolCallId, { tokens: 0, tools: 0, progress: "starting up" });
313
+ status = { ...status, activity, detail: agentsDetail() };
314
+ return;
315
+ }
277
316
  status = { ...status, activity, detail };
278
317
  });
318
+ // A subagent's row updates as it works; the line above the editor follows it, counter included.
319
+ pi.on("tool_execution_update", async (event) => {
320
+ if (event.toolName !== "subagent" || !agents.has(event.toolCallId))
321
+ return;
322
+ const details = event.partialResult?.details;
323
+ if (details)
324
+ agents.set(event.toolCallId, details);
325
+ status = { ...status, activity: "delegating", detail: agentsDetail(), tokens: tokensNow() };
326
+ });
327
+ // Tool calls the model is writing out, by content index (they can interleave), with their arguments so far.
328
+ const preparing = new Map();
329
+ pi.on("message_start", async (event) => {
330
+ if (event.message.role === "assistant")
331
+ firstDeltaAt = undefined;
332
+ });
279
333
  pi.on("message_update", async (event) => {
280
334
  const update = event.assistantMessageEvent;
335
+ if (update.type === "toolcall_start") {
336
+ const content = update.partial.content[update.contentIndex];
337
+ const call = { name: content?.type === "toolCall" ? content.name : "tool", args: "" };
338
+ preparing.set(update.contentIndex, call);
339
+ status = { ...status, activity: call.name === "subagent" ? "delegating" : "writing", detail: preparingLabel(call.name, "") };
340
+ return;
341
+ }
281
342
  if (update.type !== "text_delta" && update.type !== "thinking_delta" && update.type !== "toolcall_delta")
282
343
  return;
344
+ firstDeltaAt ??= Date.now();
283
345
  streamed += update.delta.length;
284
- status = { ...status, tokens: counted + Math.round(streamed / 4) };
346
+ let detail = status.detail;
347
+ const call = update.type === "toolcall_delta" ? preparing.get(update.contentIndex) : undefined;
348
+ if (call) {
349
+ call.args += update.delta;
350
+ detail = preparingLabel(call.name, call.args);
351
+ }
352
+ else if (update.type !== "toolcall_delta" && preparing.size > 0) {
353
+ preparing.clear();
354
+ detail = undefined;
355
+ }
356
+ status = { ...status, detail, tokens: tokensNow() };
285
357
  });
286
358
  pi.on("message_end", async (event) => {
287
359
  if (event.message.role !== "assistant")
288
360
  return;
289
- counted += event.message.usage?.output || Math.round(streamed / 4);
361
+ const tokens = event.message.usage?.output || Math.round(streamed / 4);
362
+ if (firstDeltaAt !== undefined && tokens > 0 && Date.now() > firstDeltaAt) {
363
+ streamMs += Date.now() - firstDeltaAt;
364
+ streamedOutput += tokens;
365
+ }
366
+ counted += tokens;
290
367
  streamed = 0;
291
- status = { ...status, tokens: counted };
368
+ preparing.clear();
369
+ status = { ...status, tokens: tokensNow() };
292
370
  });
293
- pi.on("tool_execution_end", async () => {
294
- status = { ...status, activity: "thinking", detail: undefined };
371
+ pi.on("tool_execution_end", async (event) => {
372
+ agents.delete(event.toolCallId);
373
+ // Other subagents may still be going; until they're done the line keeps following them.
374
+ status = agents.size > 0
375
+ ? { ...status, activity: "delegating", detail: agentsDetail(), tokens: tokensNow() }
376
+ : { ...status, activity: "thinking", detail: undefined, tokens: tokensNow() };
295
377
  });
296
378
  // After the permission prompt's tool_call handler, so a declined edit never waits on a check.
297
379
  registerChecks(pi, (active) => {
@@ -303,6 +385,7 @@ export const createKluiExtension = ({ config, live, fresh }) => async (pi) => {
303
385
  lastError = friendlyError(last.errorMessage);
304
386
  });
305
387
  pi.on("agent_settled", async (event, ctx) => {
388
+ settled = true;
306
389
  clearInterval(titleTimer);
307
390
  title();
308
391
  const happy = !event.aborted && !lastError;
@@ -312,7 +395,8 @@ export const createKluiExtension = ({ config, live, fresh }) => async (pi) => {
312
395
  void refreshCredits(true);
313
396
  if (ctx.mode !== "tui")
314
397
  return;
315
- const outcome = { aborted: event.aborted, error: lastError, startedAt: status.startedAt, tokens: status.tokens };
398
+ const tokensPerSecond = streamMs >= 1000 ? Math.round(streamedOutput / (streamMs / 1000)) : undefined;
399
+ const outcome = { aborted: event.aborted, error: lastError, startedAt: status.startedAt, tokens: tokensNow(), tokensPerSecond };
316
400
  ctx.ui.setWidget(WIDGET, (_tui, theme) => createDoneWidget(theme, outcome));
317
401
  clearTimeout(doneTimer);
318
402
  doneTimer = setTimeout(() => {
@@ -366,7 +450,7 @@ export const createKluiExtension = ({ config, live, fresh }) => async (pi) => {
366
450
  reconnect: async (ctx) => {
367
451
  await connect(true);
368
452
  if (state.connection.kind === "ready") {
369
- ctx.ui.notify("Connected to Klui ✦", "info");
453
+ ctx.ui.notify("Connected to Klui", "info");
370
454
  void refreshCredits(true);
371
455
  }
372
456
  else {
@@ -4,8 +4,8 @@
4
4
  // ask asks before every edit and every command that isn't plainly read-only
5
5
  // auto works freely inside the project; asks before risky commands and changes outside it
6
6
  // yolo never asks
7
- // Reads, searches and web lookups never ask. Subagents can't show a dialog, so there a call that
8
- // would ask is refused, and the subagent reports back instead.
7
+ // Reads, searches and web lookups never ask. Subagents can't show a dialog, so a call there that
8
+ // would ask goes to the main Klui, which asks the user (its own "don't ask again" answers count).
9
9
  import { decodeKittyPrintable, matchesKey, truncateToWidth } from "@earendil-works/pi-tui";
10
10
  import { existsSync, lstatSync, readlinkSync, realpathSync, statSync } from "node:fs";
11
11
  import { homedir } from "node:os";
@@ -672,47 +672,88 @@ export function modeLabel(theme, mode = state.mode, withKey = true) {
672
672
  // ── Wiring ──────────────────────────────────────────────────────────────────────────────────
673
673
  const PREVIEW_LINES = 10;
674
674
  const OPTIONS = ["Yes", "", "No", "No, and tell Klui what to do instead"];
675
+ /** "Don't ask again" answers, for this session. */
676
+ const grants = new Set();
677
+ // One dialog at a time: parallel tool calls queue up, and each re-checks once its turn comes,
678
+ // since a "don't ask again" answer may already cover it.
679
+ let queue = Promise.resolve();
675
680
  export function registerPermissions(pi, subagent) {
676
- const grants = new Set();
677
- // One dialog at a time: parallel tool calls queue up, and each re-checks once its turn comes,
678
- // since a "don't ask again" answer may already cover it.
679
- let queue = Promise.resolve();
680
681
  if (!subagent)
681
682
  pi.registerShortcut(MODE_KEY, { description: "Cycle permission mode (ask, auto, yolo)", handler: nextMode });
682
683
  pi.on("session_shutdown", async () => grants.clear());
683
684
  pi.on("tool_call", async (event, ctx) => {
684
- const ask = () => check(state.mode, event.toolName, event.input, ctx.cwd, grants);
685
- if (!ask())
685
+ // The main Klui may have changed modes since this subagent started, so it decides anything
686
+ // ask mode would ask about, under its mode and "don't ask again" answers of now.
687
+ if (subagent && process.send)
688
+ return check("ask", event.toolName, event.input, ctx.cwd, grants) ? askParent(event.toolName, event.input, ctx.cwd) : undefined;
689
+ if (!check(state.mode, event.toolName, event.input, ctx.cwd, grants))
690
+ return undefined;
691
+ return ctx.hasUI ? decide(ctx, event.toolName, event.input, ctx.cwd) : nobody();
692
+ });
693
+ }
694
+ const nobody = () => ({
695
+ block: true,
696
+ reason: `Klui is in ${state.mode} mode, so this needs the user's OK, and nobody can be asked from here. Don't work around it: say what you wanted to do in your report.`,
697
+ });
698
+ /**
699
+ * Whether a tool call may run, asking the user when it needs their OK. `from` names a subagent
700
+ * asking through this Klui, in the dialog's title.
701
+ */
702
+ export async function decide(ctx, toolName, input, cwd, from) {
703
+ const ask = () => check(state.mode, toolName, input, cwd, grants);
704
+ if (!ask())
705
+ return undefined;
706
+ if (!ctx.hasUI)
707
+ return nobody();
708
+ const turn = queue.then(async () => {
709
+ const request = ask();
710
+ if (!request)
711
+ return undefined;
712
+ if (from)
713
+ request.title = `${from} · ${request.title}`;
714
+ if (toolName === "edit")
715
+ request.preview = editPreview(input);
716
+ if (toolName === "write")
717
+ request.preview = String(input.content ?? "").split("\n").map((l) => `+${l}`);
718
+ const answer = await prompt(ctx, request, () => ask() !== undefined);
719
+ if (answer === 0)
720
+ return undefined;
721
+ if (answer === 1) {
722
+ grants.add(request.grant.key);
686
723
  return undefined;
687
- if (!ctx.hasUI) {
688
- return {
689
- block: true,
690
- reason: `Klui is in ${state.mode} mode, so this needs the user's OK, and nobody can be asked from here. Don't work around it: say what you wanted to do in your report.`,
691
- };
692
724
  }
693
- const turn = queue.then(async () => {
694
- const request = ask();
695
- if (!request)
696
- return undefined;
697
- if (event.toolName === "edit")
698
- request.preview = editPreview(event.input);
699
- if (event.toolName === "write")
700
- request.preview = String(event.input.content ?? "").split("\n").map((l) => `+${l}`);
701
- const answer = await prompt(ctx, request, () => ask() !== undefined);
702
- if (answer === 0)
703
- return undefined;
704
- if (answer === 1) {
705
- grants.add(request.grant.key);
706
- return undefined;
707
- }
708
- const note = answer === 3 ? (await ctx.ui.input("What should Klui do instead?", "tell Klui…"))?.trim() : undefined;
709
- // A plain "no" ends the turn, so the attendee can say what they want instead.
710
- return note
711
- ? { block: true, reason: `${DECLINED} and said: ${note}` }
712
- : { block: true, terminate: true, reason: `${DECLINED}. Don't retry it; wait for their next message.` };
713
- });
714
- queue = turn.catch(() => undefined);
715
- return turn;
725
+ const note = answer === 3 ? (await ctx.ui.input("What should Klui do instead?", "tell Klui…"))?.trim() : undefined;
726
+ // A plain "no" ends the turn, so the attendee can say what they want instead.
727
+ return note
728
+ ? { block: true, reason: `${DECLINED} and said: ${note}` }
729
+ : { block: true, terminate: true, reason: `${DECLINED}. Don't retry it; wait for their next message.` };
730
+ });
731
+ queue = turn.catch(() => undefined);
732
+ return turn;
733
+ }
734
+ // ── Subagents ───────────────────────────────────────────────────────────────────────────────
735
+ // A subagent runs as a child process with an IPC channel to the main Klui (see agents.ts).
736
+ /** The message a subagent sends to ask, and the one that answers it. */
737
+ export const ASK_PARENT = "klui-permission";
738
+ let asks = 0;
739
+ /** Asks the main Klui. A "no" doesn't end the subagent's turn: it reports back, so the main agent hears why. */
740
+ function askParent(toolName, input, cwd) {
741
+ const id = ++asks;
742
+ return new Promise((resolve) => {
743
+ const done = (decision) => {
744
+ process.off("message", onMessage);
745
+ process.off("disconnect", onGone);
746
+ resolve(decision && { block: true, reason: decision.terminate ? `${DECLINED}. Don't retry it; say so in your report.` : decision.reason });
747
+ };
748
+ const onMessage = (message) => {
749
+ if (message?.type === ASK_PARENT && message.id === id)
750
+ done(message.decision);
751
+ };
752
+ const onGone = () => done(nobody());
753
+ // Listening keeps the channel open while the user decides; it's let go again right after.
754
+ process.on("message", onMessage);
755
+ process.once("disconnect", onGone);
756
+ process.send({ type: ASK_PARENT, id, toolName, input, cwd });
716
757
  });
717
758
  }
718
759
  function editPreview(input) {
@@ -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`) : "";
@@ -79,6 +81,7 @@ const NAMES = {
79
81
  codemode: "Script",
80
82
  web_search: "Web Search",
81
83
  web_fetch: "Fetch",
84
+ screenshot: "Screenshot",
82
85
  todo: "Todos",
83
86
  };
84
87
  function title(toolName, args, theme, cwd) {
@@ -165,7 +168,9 @@ function outcome(toolName, args, result, theme, cwd) {
165
168
  return [];
166
169
  if (d.background)
167
170
  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(" · ")}`)}`];
171
+ const tokens = d.tokens ? `↓ ${formatTokens(d.tokens)} tokens` : undefined;
172
+ const speed = d.tokensPerSecond ? `${d.tokensPerSecond} tok/s` : undefined;
173
+ return [`Done ${theme.fg("dim", `· ${[plural(d.tools ?? 0, "tool"), tokens, speed, d.model].filter(Boolean).join(" · ")}`)}`];
169
174
  }
170
175
  default:
171
176
  return lineCount ? [theme.fg("dim", plural(lineCount, "line"))] : [];