klui-code 0.1.4 → 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.
package/README.md CHANGED
@@ -15,17 +15,17 @@ device its own event pass and picks the default model.
15
15
 
16
16
  Already on Node 22.19+? `npm install -g klui-code` works too.
17
17
 
18
- On Windows, install [Node.js](https://nodejs.org) (the LTS one) and
19
- [Git for Windows](https://git-scm.com/download/win) first (Klui runs commands through Git Bash),
20
- then open a new terminal and run:
18
+ On Windows, install [Git for Windows](https://git-scm.com/download/win) first (Klui runs commands
19
+ through Git Bash), then run this in PowerShell:
21
20
 
22
21
  ```
23
- npm install -g klui-code
22
+ irm https://klui.ai/code/install.ps1 | iex
24
23
  klui
25
24
  ```
26
25
 
27
- "npm is not recognized" means Node.js isn't installed yet, or the terminal was open before it was:
28
- install it, then open a new terminal.
26
+ It works the same way: your Node.js if it's 22.19 or newer, otherwise its own copy, all in
27
+ `~\.klui`, with no admin rights. If your computer blocks it, install [Node.js](https://nodejs.org)
28
+ (the LTS one) and run `npm install -g klui-code` instead.
29
29
 
30
30
  ## Using it
31
31
 
@@ -132,7 +132,7 @@ a small pool and start Pass (see [server/README.md](server/README.md#local-dry-r
132
132
  ```
133
133
  npm version patch # or minor; commits and tags vX.Y.Z
134
134
  git push --follow-tags # CI publishes the tag to npm (needs the NPM_TOKEN secret)
135
- scp install.sh root@klui.ai:/srv/klui-code/install.sh # only when the installer changed
135
+ scp install.sh install.ps1 root@klui.ai:/srv/klui-code/ # only when an installer changed
136
136
  ```
137
137
 
138
138
  `npm publish` runs the tests first and rebuilds `dist/` from scratch. Installed copies see the new
package/dist/cli.js CHANGED
@@ -55,6 +55,8 @@ function seedSettings(config, piVersion) {
55
55
  settings.defaultProvider = PROVIDER;
56
56
  settings.defaultModel = config.defaultModel;
57
57
  }
58
+ // A provider that fails or stalls gets three more tries, 5 s apart (Pi's default doubles the wait).
59
+ settings.retry = { ...settings.retry, enabled: true, maxRetries: 3, baseDelayMs: 5000, maxAgentDelayMs: 5000 };
58
60
  settings.lastChangelogVersion = piVersion;
59
61
  settings.enableInstallTelemetry = false;
60
62
  mkdirSync(AGENT_DIR, { recursive: true });
@@ -9,14 +9,20 @@
9
9
  // line and OpenCode's "Preparing write…": waiting on the model, thinking, preparing a write to
10
10
  // styles.css, running a command, retrying. Under that sit its last finished steps, a token
11
11
  // counter that moves as output streams in, and the time.
12
+ //
13
+ // A subagent can't show a dialog, so when a call of its needs the user's OK it asks this Klui over
14
+ // an IPC channel, and the dialog shows here. Its chat is saved in KLUI_HOME/subagents (only the
15
+ // newest few, for a week), and the result names the file, so `klui --session <file>` opens it.
12
16
  import { spawn } from "node:child_process";
17
+ import { mkdirSync, readdirSync, rmSync, statSync } from "node:fs";
13
18
  import { join } from "node:path";
14
19
  import { StringEnum } from "@earendil-works/pi-ai";
15
20
  import { getMarkdownTheme, keyText } from "@earendil-works/pi-coding-agent";
16
21
  import { Container, Markdown, Text } from "@earendil-works/pi-tui";
17
22
  import { Type } from "typebox";
18
- import { PACKAGE_DIR, PROVIDER } from "../paths.js";
19
- import { PERMISSIONS_ENV } from "./permissions.js";
23
+ import { KLUI_HOME, PACKAGE_DIR, PROVIDER } from "../paths.js";
24
+ import { PARENT_SESSION_ENV } from "../usage.js";
25
+ import { ASK_PARENT, decide, PERMISSIONS_ENV } from "./permissions.js";
20
26
  import { state } from "./state.js";
21
27
  import { preparingLabel, shortPath } from "./voice.js";
22
28
  /** Set in a subagent's environment: subagents don't start subagents of their own. */
@@ -27,6 +33,10 @@ const WIDGET = "klui-agents";
27
33
  const TICK_MS = 500;
28
34
  /** Finished steps kept for the expanded view: plenty for any real run, and a bound on a runaway one. */
29
35
  const MAX_STEPS = 500;
36
+ /** Subagent chats kept: the newest this many, none older than a week. */
37
+ const TRANSCRIPTS = join(KLUI_HOME, "subagents");
38
+ const MAX_TRANSCRIPTS = 30;
39
+ const TRANSCRIPT_DAYS = 7;
30
40
  const REPORT = "The other agent can't see your work, only that report. If the task needs something your tools can't do, say so at the top of the report instead of guessing.";
31
41
  const KINDS = {
32
42
  explore: {
@@ -34,7 +44,7 @@ const KINDS = {
34
44
  prompt: `You are a Klui subagent researching for another agent. You can read files and search and fetch the web, but never change anything. Search broadly, read what matters, and finish with a compact report: the answer, the exact file paths and line numbers or the URLs you actually read, and short excerpts where they help. ${REPORT}`,
35
45
  },
36
46
  general: {
37
- tools: "read,bash,edit,write,grep,find,ls,web_search,web_fetch",
47
+ tools: "read,bash,edit,write,grep,find,ls,web_search,web_fetch,screenshot",
38
48
  prompt: `You are a Klui subagent doing one task for another agent. Do the task completely, check your work, and finish with a short report: what you changed (file paths), how you verified it, and anything left undone. ${REPORT}`,
39
49
  },
40
50
  };
@@ -101,7 +111,7 @@ export function registerAgents(pi) {
101
111
  running.set(id, { controller, details });
102
112
  showRunning();
103
113
  let shownAt = 0;
104
- void runAgent(ctx.cwd, kind, run, params.task, controller.signal, details, () => {
114
+ void runAgent(ctx, kind, run, params.task, controller.signal, details, () => {
105
115
  if (Date.now() - shownAt < 250)
106
116
  return;
107
117
  shownAt = Date.now();
@@ -134,7 +144,7 @@ export function registerAgents(pi) {
134
144
  const tick = setInterval(emit, TICK_MS);
135
145
  tick.unref?.();
136
146
  emit();
137
- const outcome = await runAgent(ctx.cwd, kind, run, params.task, signal, details, () => {
147
+ const outcome = await runAgent(ctx, kind, run, params.task, signal, details, () => {
138
148
  if (Date.now() - lastUpdate >= 150)
139
149
  emit();
140
150
  }).finally(() => clearInterval(tick));
@@ -410,13 +420,14 @@ export function createTracker(details, now = Date.now) {
410
420
  };
411
421
  }
412
422
  /** Run one subagent to completion, following its progress into `details` as it goes. */
413
- function runAgent(cwd, kind, run, task, signal, details, onProgress) {
423
+ function runAgent(ctx, kind, run, task, signal, details, onProgress) {
414
424
  const args = [
415
425
  join(PACKAGE_DIR, "bin", "klui.js"),
416
426
  "--mode",
417
427
  "json",
418
428
  "-p",
419
- "--no-session",
429
+ "--session",
430
+ (details.transcript = newTranscript(kind)),
420
431
  "--model",
421
432
  run.model,
422
433
  "--thinking",
@@ -428,7 +439,8 @@ function runAgent(cwd, kind, run, task, signal, details, onProgress) {
428
439
  `Task: ${task}`,
429
440
  ];
430
441
  return new Promise((resolve) => {
431
- const child = spawn(process.execPath, args, { cwd, env: { ...process.env, [SUBAGENT_ENV]: "1", [PERMISSIONS_ENV]: state.mode }, stdio: ["ignore", "pipe", "pipe"] });
442
+ const env = { ...process.env, [SUBAGENT_ENV]: "1", [PERMISSIONS_ENV]: state.mode, [PARENT_SESSION_ENV]: ctx.sessionManager.getSessionId() };
443
+ const child = spawn(process.execPath, args, { cwd: ctx.cwd, env, stdio: ["ignore", "pipe", "pipe", "ipc"] });
432
444
  const tracker = createTracker(details);
433
445
  let stderr = "";
434
446
  let buffer = "";
@@ -453,6 +465,23 @@ function runAgent(cwd, kind, run, task, signal, details, onProgress) {
453
465
  newline = buffer.indexOf("\n");
454
466
  }
455
467
  });
468
+ // A call that needs the user's OK: ask here, and answer the subagent.
469
+ child.on("message", async (message) => {
470
+ if (message?.type !== ASK_PARENT)
471
+ return;
472
+ const was = details.progress;
473
+ details.progress = "waiting for your OK";
474
+ onProgress();
475
+ const decision = await decide(ctx, message.toolName, message.input, message.cwd, `${kind} agent`).catch(() => ({
476
+ block: true,
477
+ reason: "Nobody could be asked for the user's OK. Don't work around it: say what you wanted to do in your report.",
478
+ }));
479
+ if (details.progress === "waiting for your OK")
480
+ details.progress = was;
481
+ onProgress();
482
+ if (child.connected)
483
+ child.send({ type: ASK_PARENT, id: message.id, decision });
484
+ });
456
485
  child.stderr.setEncoding("utf8");
457
486
  child.stderr.on("data", (chunk) => {
458
487
  stderr = (stderr + chunk).slice(-2000);
@@ -474,6 +503,23 @@ function runAgent(cwd, kind, run, task, signal, details, onProgress) {
474
503
  });
475
504
  });
476
505
  }
506
+ let transcripts = 0;
507
+ /** A path for a new subagent's chat, after clearing out old ones. */
508
+ function newTranscript(kind) {
509
+ try {
510
+ mkdirSync(TRANSCRIPTS, { recursive: true });
511
+ const files = readdirSync(TRANSCRIPTS)
512
+ .filter((f) => f.endsWith(".jsonl"))
513
+ .map((f) => ({ path: join(TRANSCRIPTS, f), at: statSync(join(TRANSCRIPTS, f)).mtimeMs }))
514
+ .sort((a, b) => b.at - a.at);
515
+ const old = Date.now() - TRANSCRIPT_DAYS * 24 * 60 * 60 * 1000;
516
+ for (const [i, file] of files.entries())
517
+ if (i >= MAX_TRANSCRIPTS - 1 || file.at < old)
518
+ rmSync(file.path, { force: true });
519
+ }
520
+ catch { }
521
+ return join(TRANSCRIPTS, `${new Date().toISOString().replace(/[:.]/g, "-")}-${kind}-${process.pid}-${++transcripts}.jsonl`);
522
+ }
477
523
  /** What a tool call is doing, while it runs: "reading src/app.ts", "$ npm test". */
478
524
  function activity(toolName, args) {
479
525
  const a = args ?? {};
@@ -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
+ }
@@ -10,6 +10,7 @@ import { PROVIDER } from "../paths.js";
10
10
  import { availableUpdate } from "../update.js";
11
11
  import { recordUsage } from "../usage.js";
12
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";
@@ -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);
@@ -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) {
@@ -81,6 +81,7 @@ const NAMES = {
81
81
  codemode: "Script",
82
82
  web_search: "Web Search",
83
83
  web_fetch: "Fetch",
84
+ screenshot: "Screenshot",
84
85
  todo: "Todos",
85
86
  };
86
87
  function title(toolName, args, theme, cwd) {
package/dist/fallback.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // a `paid` model tries free peers first, then the best mix of price and reputation; a `free` one
4
4
  // stays on peers serving it for free. A request a peer can't serve moves to the next one, and only
5
5
  // when none of them answers does the error reach the chat.
6
- import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
6
+ import { createAssistantMessageEventStream, isContextOverflow, } from "@earendil-works/pi-ai";
7
7
  import { getApiProvider } from "@earendil-works/pi-ai/compat";
8
8
  /** A coding turn re-sends the conversation, so most of its input is already cached on the peer. */
9
9
  const TURN_MIX = { cached: 24, input: 6, output: 1 };
@@ -29,9 +29,17 @@ const VISION_TESTED = {
29
29
  const COOLDOWN_MS = 10 * 60_000;
30
30
  /** Paid peers tried per request: each failure can cost a timeout, and paid peers rarely all fail. */
31
31
  const MAX_PAID_TRIES = 4;
32
+ /** Once a reply streams, a peer that sends nothing (no text, reasoning or tool call) this long has stalled. */
33
+ const STALL_MS = 45_000;
32
34
  /**
33
- * A peer that hasn't started answering by now is treated as gone (some hang without a word). Long
34
- * prompts get longer: reading an uncached 900K-token conversation alone takes a peer 20-30 s.
35
+ * All the chat ever says about a failed provider: what went wrong is for troubleshooting, so it goes
36
+ * in the usage log (see usage.ts). Pi retries a reply that failed with it (see pi-patches.ts).
37
+ */
38
+ export const PROVIDER_ISSUE = "Klui had a model provider issue. Please retry.";
39
+ /**
40
+ * A peer that hasn't started answering by now is treated as gone (some hang without a word, others
41
+ * send headers and then nothing). Long prompts get longer: reading an uncached 900K-token
42
+ * conversation alone takes a peer 20-30 s.
35
43
  */
36
44
  export function answerTimeoutMs(context) {
37
45
  // About 4 characters a token; image data is left out, since a picture costs far fewer tokens than its base64.
@@ -65,6 +73,20 @@ function asSeller(context, attempt) {
65
73
  return context;
66
74
  return { ...context, messages: context.messages.map((m) => (m.role === "assistant" && m.responseModel === attempt ? { ...m, model: attempt } : m)) };
67
75
  }
76
+ /** A failure whose own message is for the user (Klui can't connect, say), not a provider's. */
77
+ class ForTheUser extends Error {
78
+ }
79
+ /**
80
+ * A failure as the chat shows it: PROVIDER_ISSUE, with what the peers said kept in `providerError`
81
+ * for the usage log. A context overflow keeps its own message, so Pi compacts the chat and goes on.
82
+ */
83
+ function providerIssue(event, id, failures) {
84
+ if (event.type !== "error")
85
+ return event;
86
+ const failed = { ...event.error, stopReason: "error" };
87
+ const errorMessage = isContextOverflow(failed, 0) ? failed.errorMessage : PROVIDER_ISSUE;
88
+ return sellerAside({ type: "error", reason: "error", error: { ...failed, errorMessage, providerError: failures.join(" | ").slice(0, 1000) } }, id);
89
+ }
68
90
  /** What a typical turn costs on this offer, in USD per million tokens. */
69
91
  export function turnPrice(offer) {
70
92
  const { inputUsdPerMillion: input, outputUsdPerMillion: output } = offer;
@@ -174,15 +196,17 @@ export function createFallback(getConfig, getApiKey, connect = async () => undef
174
196
  if (options?.signal?.aborted)
175
197
  throw new Error("Request was aborted");
176
198
  if (!getApiKey())
177
- throw new Error(problem ?? "Can't reach Klui. Check your wifi and try again.");
199
+ throw new ForTheUser(problem ?? "Can't reach Klui. Check your wifi and try again.");
178
200
  // The gateway may have changed while this message waited for its key.
179
201
  model = { ...model, baseUrl: getConfig().baseUrl };
180
202
  }
181
203
  // The key Pi started this request with may be the placeholder from before Klui connected.
182
204
  options = { ...options, apiKey: getApiKey() };
183
205
  if (!entry?.free && !entry?.paid) {
184
- for await (const event of base().streamSimple(model, context, options))
185
- out.push(event);
206
+ for await (const event of base().streamSimple(model, context, options)) {
207
+ const failed = event.type === "error" && !options?.signal?.aborted;
208
+ out.push(failed ? providerIssue(event, model.id, [`${model.id}: ${event.error.errorMessage}`]) : event);
209
+ }
186
210
  return out.end();
187
211
  }
188
212
  const tried = new Set();
@@ -197,39 +221,64 @@ export function createFallback(getConfig, getApiKey, connect = async () => undef
197
221
  throw new Error(`No vision provider is available for ${model.name} right now. Try again or pick another vision model with /model.`);
198
222
  let firstError;
199
223
  const broke = [];
224
+ /** What each peer that failed said, for the usage log. */
225
+ const failures = [];
200
226
  const answerTimeout = answerTimeoutMs(context);
201
227
  while (next) {
202
228
  tried.add(next);
203
229
  const attempt = next;
204
230
  next = undefined;
205
231
  const silent = new AbortController();
206
- const timer = setTimeout(() => silent.abort(), answerTimeout);
232
+ // Until the model says something, the peer has the whole answer timeout; after that,
233
+ // every text, reasoning or tool-call event restarts a shorter stall timer.
234
+ let timer = setTimeout(() => silent.abort(), answerTimeout);
207
235
  const signal = options?.signal ? AbortSignal.any([options.signal, silent.signal]) : silent.signal;
208
236
  const events = base().streamSimple({ ...model, id: attempt }, asSeller(context, attempt), { ...options, signal });
237
+ /** The start event comes with the response headers, before any token: held until the model says something. */
238
+ const held = [];
209
239
  let started = false;
210
240
  try {
211
241
  for await (const event of events) {
212
- // Nothing has reached the chat yet, so a refusal here can still go to another peer.
213
- const refused = event.type === "error" && (silent.signal.aborted || worthAnotherPeer(event.error.errorMessage));
214
- if (!started && refused && !options?.signal?.aborted) {
215
- firstError ??= event;
216
- cooling.set(attempt, Date.now() + COOLDOWN_MS);
217
- if (working.get(model.id) === attempt)
218
- working.delete(model.id);
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))
225
- next = await nextPeer();
226
- break;
242
+ if (event.type === "error") {
243
+ const stopped = !!options?.signal?.aborted;
244
+ const why = silent.signal.aborted ? `silent for ${(started ? STALL_MS : answerTimeout) / 1000}s` : (event.error.errorMessage ?? "error");
245
+ // Nothing has reached the chat yet, so a refusal here can still go to another peer.
246
+ if (!started && !stopped && (silent.signal.aborted || worthAnotherPeer(event.error.errorMessage))) {
247
+ firstError ??= event;
248
+ failures.push(`${attempt}: ${why}`);
249
+ cooling.set(attempt, Date.now() + COOLDOWN_MS);
250
+ if (working.get(model.id) === attempt)
251
+ working.delete(model.id);
252
+ // A paid 402 from one seller doesn't mean the wallet is empty: a seller Klui hasn't paid
253
+ // yet must first reserve part of it for a payment channel, which a small balance can't
254
+ // cover while sellers that already have one keep answering. So try the next seller, and
255
+ // only call it out of credits when every seller tried said 402.
256
+ broke.push(paid && /^\s*402\b/.test(event.error.errorMessage ?? ""));
257
+ if (!(paid && tried.size >= MAX_PAID_TRIES))
258
+ next = await nextPeer();
259
+ break;
260
+ }
261
+ // Stopped by the user, or failed (a stall included) after tokens reached the chat.
262
+ if (started && !stopped) {
263
+ cooling.set(attempt, Date.now() + COOLDOWN_MS);
264
+ if (working.get(model.id) === attempt)
265
+ working.delete(model.id);
266
+ }
267
+ out.push(stopped ? sellerAside(event, model.id) : providerIssue(event, model.id, [...failures, `${attempt}: ${why}`]));
268
+ return out.end();
227
269
  }
270
+ if (!started && event.type === "start") {
271
+ held.push(event);
272
+ continue;
273
+ }
274
+ clearTimeout(timer);
275
+ timer = setTimeout(() => silent.abort(), STALL_MS);
228
276
  if (!started) {
229
277
  started = true;
230
- clearTimeout(timer);
231
278
  if (!paid && attempt !== model.id)
232
279
  working.set(model.id, attempt);
280
+ for (const h of held)
281
+ out.push(sellerAside(h, model.id));
233
282
  }
234
283
  out.push(sellerAside(event, model.id));
235
284
  }
@@ -244,21 +293,20 @@ export function createFallback(getConfig, getApiKey, connect = async () => undef
244
293
  // peer hash) means nothing to an attendee, so say what happened instead.
245
294
  if (firstError?.type === "error") {
246
295
  const outOfCredits = broke.length > 0 && broke.every(Boolean);
247
- const errorMessage = outOfCredits
248
- ? `Klui is out of credits for ${model.name}. Pick a free model with /model.`
249
- : paid
250
- ? `No provider is answering for ${model.name} right now. Try again, or pick another model with /model.`
251
- : `No free provider is serving ${model.name} right now. Pick another model with /model.`;
252
- out.push(sellerAside({ ...firstError, error: { ...firstError.error, errorMessage } }, model.id));
296
+ out.push(outOfCredits
297
+ ? sellerAside({ ...firstError, error: { ...firstError.error, errorMessage: `Klui is out of credits for ${model.name}. Pick a free model with /model.` } }, model.id)
298
+ : providerIssue(firstError, model.id, failures));
253
299
  }
254
300
  out.end();
255
301
  })().catch((error) => {
256
302
  const reason = options?.signal?.aborted ? "aborted" : "error";
257
- out.push({
303
+ const said = error instanceof Error ? error.message : String(error);
304
+ const event = {
258
305
  type: "error",
259
306
  reason,
260
- error: { role: "assistant", content: [], api: model.api, provider: model.provider, model: model.id, stopReason: reason, errorMessage: error instanceof Error ? error.message : String(error), usage: emptyUsage(), timestamp: Date.now() },
261
- });
307
+ error: { role: "assistant", content: [], api: model.api, provider: model.provider, model: model.id, stopReason: reason, errorMessage: said, usage: emptyUsage(), timestamp: Date.now() },
308
+ };
309
+ out.push(reason === "aborted" || error instanceof ForTheUser ? event : providerIssue(event, model.id, [said]));
262
310
  out.end();
263
311
  });
264
312
  return out;
@@ -2,7 +2,7 @@
2
2
  // Pi's own modules (the same instance Pi runs, resolved from its package) and is skipped quietly
3
3
  // if a Pi update moves things around.
4
4
  import { Spacer, TruncatedText, TuiAltScreen } from "@earendil-works/pi-tui";
5
- import { serviceOf } from "./fallback.js";
5
+ import { PROVIDER_ISSUE, serviceOf } from "./fallback.js";
6
6
  import { chipFor, isClipboardImageFile } from "./images.js";
7
7
  import { PROVIDER } from "./paths.js";
8
8
  import { scrollFrame } from "./scroll.js";
@@ -11,7 +11,7 @@ export async function patchPi(config) {
11
11
  brandOutput();
12
12
  scrollWithTerminal();
13
13
  clearAfterCopy();
14
- for (const patch of [() => sellerModelIds(config), removeLlama, hidePiFooter, hoverJumpToLatest, queuedMessages, trimSlashMenu, slashAliases, simpleThinkingMenu, thinkingAfterModel, () => tidyModelPicker(), () => quietPiHints(config), pasteImageChips])
14
+ for (const patch of [() => sellerModelIds(config), retryProviderIssues, removeLlama, hidePiFooter, hoverJumpToLatest, queuedMessages, trimSlashMenu, slashAliases, simpleThinkingMenu, thinkingAfterModel, () => tidyModelPicker(), () => quietPiHints(config), pasteImageChips])
15
15
  await patch().catch(() => { });
16
16
  }
17
17
  /**
@@ -34,6 +34,21 @@ async function sellerModelIds(config) {
34
34
  return model ? getModel.call(this, provider, model.id) : undefined;
35
35
  };
36
36
  }
37
+ /**
38
+ * Klui shows a failed provider as PROVIDER_ISSUE rather than what it said (see fallback.ts), which
39
+ * Pi's retry wouldn't recognise as worth another try. It is: Pi waits and asks again (every 5s,
40
+ * three times; see seedSettings in cli.ts), a reply that stalled halfway included.
41
+ */
42
+ async function retryProviderIssues() {
43
+ const { AgentSession } = await piModule("./core/agent-session.js");
44
+ const proto = AgentSession.prototype;
45
+ const isRetryable = proto._isRetryableError;
46
+ if (typeof isRetryable !== "function")
47
+ return;
48
+ proto._isRetryableError = function (message) {
49
+ return message.errorMessage === PROVIDER_ISSUE || isRetryable.call(this, message);
50
+ };
51
+ }
37
52
  /** Klui uses event models, so don't load Pi's local llama.cpp manager or its /llama command. */
38
53
  async function removeLlama() {
39
54
  const { builtInExtensions } = await piModule("./extensions/index.js");
package/dist/usage.js CHANGED
@@ -1,8 +1,11 @@
1
1
  // Token usage across every Klui run on this machine, for /usage. Each finished model reply appends
2
2
  // one line to a log in KLUI_HOME: the main chat, compaction summaries and subagents (separate
3
- // `klui` processes that keep no session) all go through Klui's providers, so all of them count.
3
+ // `klui` processes, whose chats aren't among the saved sessions) all go through Klui's providers,
4
+ // so all of them count.
4
5
  // Each line names the seller that answered (the gateway id, "<peerId>@<service>"), who asked (the
5
- // main agent or a subagent) and the timings: request start, first token and the end.
6
+ // main agent or a subagent), the chat it belongs to (a subagent's names its parent's), the timings
7
+ // (request start, first token and the end), and for a failed request what the providers said,
8
+ // which the chat itself never shows (see fallback.ts).
6
9
  // The first time the log is created it starts from the tokens in the saved sessions.
7
10
  import { appendFileSync, existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
8
11
  import { join } from "node:path";
@@ -11,10 +14,14 @@ const DAY_MS = 24 * 60 * 60 * 1000;
11
14
  /** What the model streams as it answers: the first of these is its first token. */
12
15
  const DELTAS = new Set(["text_delta", "thinking_delta", "toolcall_delta", "toolcall_start"]);
13
16
  const PATHS = { file: join(KLUI_HOME, "usage.jsonl"), sessions: join(AGENT_DIR, "sessions") };
17
+ /** Set in a subagent's environment: the session id of the chat that started it. */
18
+ export const PARENT_SESSION_ENV = "KLUI_PARENT_SESSION";
14
19
  /** Logs each model request, including follow-up turns and failures with no reported tokens. */
15
20
  export function recordUsage(streamSimple, agent = "main", paths = PATHS) {
16
21
  return ((...args) => {
17
22
  const start = Date.now();
23
+ const options = args[2];
24
+ const session = process.env[PARENT_SESSION_ENV] || options?.sessionId;
18
25
  const stream = streamSimple(...args);
19
26
  // Watch the events going into the stream for the first token; whoever reads it sees them unchanged.
20
27
  let firstAt;
@@ -30,7 +37,9 @@ export function recordUsage(streamSimple, agent = "main", paths = PATHS) {
30
37
  // peer that answered, not the wait for a key, the peer list or peers that refused before it.
31
38
  const log = (reply) => {
32
39
  const end = Date.now();
33
- appendEntry({ t: end, ...tokens(reply?.usage), model: reply?.responseModel ?? reply?.model, agent, start, ttft: firstAt === undefined ? undefined : firstAt - start, ms: end - start }, paths);
40
+ const error = reply?.providerError || reply?.errorMessage;
41
+ const timing = { start, ttft: firstAt === undefined ? undefined : firstAt - start, ms: end - start };
42
+ appendEntry({ t: end, ...tokens(reply?.usage), model: reply?.responseModel ?? reply?.model, agent, ...timing, session, error: error?.slice(0, 1000) }, paths);
34
43
  };
35
44
  stream.result().then(log, () => log(undefined));
36
45
  return stream;
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "klui-code",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "klui-code",
9
- "version": "0.1.4",
9
+ "version": "0.1.5",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@earendil-works/chord": "1.1.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "klui-code",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "description": "Klui Code: a pixel-cute coding agent for your terminal, built on Pi and running on AntSeed.",
5
5
  "keywords": [
6
6
  "klui",